From db802d123027524ae5dbb75555a168743e1bd42c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:07:08 -0600 Subject: [PATCH 01/15] fix(heartbeat): deliver a queued comment again unless the reading run cites it as handled (#21243) 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 add a comment to a task while the agent's run on that task is still working > - #21175 made a `get_task_history` read of a queued comment's current revision count as delivery > - A read is not handling. In `agent-chat.multiple-handoffs`, Morgan's running turn read the "Launch sooner" comment, set it aside, and saved "Launch later". No continuation ran, so the instruction was lost. > - This pull request counts a read as delivery only when the run's accepted result cites the comment as handled. Otherwise one continuation still delivers it, and that continuation is told the comment may already be applied. > - The benefit is that a person's comment is never silently lost, and the #21175 protection against repeated completed work stays in place ## Linked Issue or Issue Description Refs #21175 Refs #21203 Refs #21210 **What happened?** Paid run 43321773136 (OpenCode, `openrouter/deepseek/deepseek-v4.1-flash-1017`), case `agent-chat.multiple-handoffs`. Morgan's running turn called `get_task_history` and received the CEO's queued "Launch sooner" comment at its current revision (`task_history.read` at seq 75). The model judged the comment as an unauthenticated agent instruction and saved "Launch later" from the brief. Its accepted result did not mention the comment. `deliveredQueuedCommentIds` counted the read as delivery, the release drain dropped the held comment, and no continuation ran. **Expected behavior** A read counts as delivery only when the run records the comment as handled. A comment that was read but not recorded as handled is delivered once in a new turn. The new turn's prompt says that an earlier turn already read the comment and may have applied it. **Steps to reproduce** 1. Start a native run on a task. 2. Queue a comment behind the run. 3. Let the run read `get_task_history` and finish without applying the comment. 4. Before this change, no continuation runs and the comment is lost. ## What Changed - `server/src/services/queued-comment-delivery.ts`: the history-read delivery rule now also requires the reading run's `run.result.accepted` event to cite `comment:` (top-level `evidence[].ref` or a criterion's `evidenceRefs`, prefix match so an annotated ref counts). The read revision, succeeded-run and finished-after-revision rules are unchanged. All consumers (release drain, stale-continuation save, ownership reconciler, first-turn queued input, remote-Stop resume) use this one rule. - New `readByEarlierTurnCommentIds`, `commentsArrivedDuringRun` and `taskHistoryHandlingGuidance`. - `get_task_history` (both tool authorities) returns `arrivedDuringThisTurn` (the `comment:` refs of comments other authors posted or edited after the run started) and a `handling` instruction to cite each applied comment in `paperclip_finish` / `paperclip_block` evidence. The comment list itself is unchanged. A failure to compute the list returns no guidance, so the comment stays owed. - `buildPaperclipWakePayload` marks a wake comment `readByEarlierTurn` when another finished run of the agent read its current revision. `renderPaperclipWakePrompt` adds one line after that comment: check the current task state first, and do not repeat work that is already done. - `doc/run-log-events.md`: the delivery rule and the new fields. - Evals: `agent-chat.multiple-handoffs` (oracle `runtime-multiple-handoffs.v6`) and `steering.edit-queued-message` (oracle `edit-queued-message.structural.v6`) accept in-turn consumption only with a current-revision read and a citation. A read without a citation must get exactly one continuation whose saved wake marks `readByEarlierTurn`, and the final saved revision must hold the change ("Launch sooner"; blue). `runtime-queue.ts` reads citations from the run's `run.result.accepted` event. No scenario YAML changed. ## Verification - RED on master `b1ef1f3022`, `server/src/__tests__/heartbeat-held-comment-wake.test.ts`: 10 of 41 fail. The key one: "settles a held message as soon as its run closes the task (read mid-turn: true, cited: false)" delivered 0, expected 1. - GREEN: 41/41. The three required shapes: - read, not cited: one continuation, and its wake marks `readByEarlierTurn` (`...read mid-turn: true, cited: false` and the stale-queued-run variant). - read and cited: no continuation (`...cited: true`). - never read: one continuation, as before. - Edited after the read, or a failed reader: still owed. - `server/src/services/queued-comment-history-read.test.ts` (remote-Stop resume): succeeded+cited not owed; succeeded+uncited owed; failed+cited owed. 4/4. - `packages/adapter-utils/src/server-utils.test.ts`: the prompt line renders only for `readByEarlierTurn`. - Neighbouring suites: `muse-control`, `dot-runner`, `paperclip-runner-tool-authority`, `paperclip-control-plane-port`, `muse-native-follow-up`, `runner-prp-coordinator`, `native-session-handoff`, `execution-continuation-history-read`, `heartbeat-comment-wake-batching`, `ownership-reconciliation-report`, `run-preparation`: all pass. Server and adapter-utils `tsc --noEmit`: clean. - Eval graders: `npx vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/chat-catalog tests/runner-e2e/chat-catalog-domains`: 283 files pass. New calibration: the observed lost-instruction case (read, not cited, no continuation) fails; read-not-cited with one warned continuation passes; an unwarned continuation, a missing final change, and a cited read plus a continuation fail. - `pnpm test:e2e:runner:typecheck`: pass. `node --test tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs`: 10/10. `node tests/runner-e2e/source-sdk-public-inputs.mjs --check`: `changed: false`. - Paid run: Runner Full-Stack E2E 43338695850 on throwaway branch `chat-eval/qa-mr-paid` (this change plus the model-retry fix on master 19f8ed1ea2). Result to follow in a comment. ## Risks - A run that applies a queued comment but does not cite it gets one more turn on that task. That turn is told the comment may already be applied. In the restart-chaos t005 shape (#21175) this can reopen a done task when the agent does not cite the comment. This is the chosen tradeoff: a lost comment is worse than one extra checked turn. - Each `get_task_history` call adds one small indexed read of the run's `started_at`. - Upgrade-safe: runs saved by older builds have no citation, so a read-only delivery from before this change stays owed and is delivered once more. No migration. > 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 Opus 5.5 --- doc/run-log-events.md | 35 +++++++----- .../adapter-utils/src/server-utils.test.ts | 33 ++++++++++++ packages/adapter-utils/src/server-utils.ts | 12 +++++ .../heartbeat-held-comment-wake.test.ts | 44 ++++++++++----- .../src/services/heartbeat/run-preparation.ts | 7 +++ .../native-continuation.test.ts | 6 +++ .../native-runtime/native-continuation.ts | 5 +- .../paperclip-runner-tool-authority.ts | 6 ++- .../runner-semantic-authority.ts | 6 ++- .../src/services/queued-comment-delivery.ts | 54 +++++++++++++++++-- .../queued-comment-history-read.test.ts | 15 ++++-- .../runner-e2e/chat-catalog-descriptors.json | 2 +- .../runtime-multiple-handoffs.test.ts | 33 +++++++++--- .../runtime-multiple-handoffs.ts | 20 ++++--- .../runtime-queue-controls.test.ts | 37 +++++++++---- .../runtime-queue-controls.ts | 24 +++++---- .../runtime-queue.test.ts | 11 +++- .../chat-catalog-domains/runtime-queue.ts | 25 ++++++++- 18 files changed, 299 insertions(+), 76 deletions(-) diff --git a/doc/run-log-events.md b/doc/run-log-events.md index be2c7c8d1e5..7f171facf52 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -1010,19 +1010,28 @@ to that run's log. Its payload has one field, `comments`, which maps each returned comment ID to that comment's `updatedAt` timestamp. It contains no comment bodies or author identifiers. The event creates no Telemetry or OpenTelemetry export. -Per-comment delivery (`deliveredQueuedCommentIds`) reads this event. A -person's comment counts as received when a run of the task's assignee succeeded -after reading the comment's current revision. The comment's queued -wake then neither reopens the finished task nor starts another turn. An edit -after the read, or a read by a run that did not succeed, leaves the comment -owed, so it is delivered once. The check reads only the assignee's succeeded -runs of that task that finished at or after the comment's current revision, -through the existing run-binding and `(company_id, run_id)` event indexes. -A saved follow-up resumed after a remote Stop uses the same rule. A read by a -run that did not succeed never counts. `taskHistoryReadsForRun` lists the -comments one run read, with each read's time and the comment revision it saw, -whatever the run's outcome. A failure to write the event leaves the comment -owed in the same way. +Per-comment delivery (`deliveredQueuedCommentIds`) reads this event together +with the run's `run.result.accepted` event. A read alone is not delivery: the +run may have read the comment and set it aside. A comment counts as received +only when a run of the task's assignee succeeded after reading the comment's +current revision, and that run's accepted result cites the comment as a +`comment:` evidence reference (top-level `evidence[].ref` or a criterion's +`evidenceRefs`). The comment's queued wake then neither reopens the finished +task nor starts another turn. An edit after the read, a read by a run that did +not succeed, or a read the result does not cite leaves the comment owed, so it +is delivered once in a new turn. That turn's wake marks the comment +`readByEarlierTurn` when an earlier finished run read its current revision, and +the prompt asks the agent to check the current task state before acting so +already-applied work is not repeated. `get_task_history` returns +`arrivedDuringThisTurn` (the `comment:` refs of comments that other authors +posted or edited after the run started) with instructions to cite each applied +comment. The check reads only the assignee's succeeded runs of that task that +finished at or after the comment's current revision, through the existing +run-binding and `(company_id, run_id)` event indexes. A saved follow-up +resumed after a remote Stop uses the same rule. `taskHistoryReadsForRun` lists +the comments one run read, with each read's time and the comment revision it +saw, whatever the run's outcome. A failure to write the event leaves the +comment owed in the same way. When a run reads a finished child task, the server writes one `child_task.read` event (`stream: "system"`, level `info`) to that run's log. diff --git a/packages/adapter-utils/src/server-utils.test.ts b/packages/adapter-utils/src/server-utils.test.ts index c15bc4923f6..f60271aa0a4 100644 --- a/packages/adapter-utils/src/server-utils.test.ts +++ b/packages/adapter-utils/src/server-utils.test.ts @@ -2891,6 +2891,39 @@ describe("renderPaperclipWakePrompt", () => { ); }); + it("warns that a delivered comment an earlier turn read may already be applied", () => { + const render = (readByEarlierTurn: boolean) => renderPaperclipWakePrompt({ + reason: "issue_commented", + issue: { id: "issue-1", identifier: "PAP-1", title: "Website", status: "in_progress" }, + commentIds: ["comment-1"], + latestCommentId: "comment-1", + commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 }, + comments: [{ id: "comment-1", body: "Change the headline to Launch sooner.", author: { type: "user", id: "board-user-1" }, + createdAt: "2026-06-01T12:05:00.000Z", ...(readByEarlierTurn ? { readByEarlierTurn: true } : {}) }], + fallbackFetchNeeded: false, + }); + const note = "An earlier turn already read this comment and may have applied it."; + expect(render(true)).toContain(note); + expect(render(true).indexOf(note)).toBeGreaterThan(render(true).indexOf("Change the headline to Launch sooner.")); + expect(render(false)).not.toContain(note); + }); + + it("keeps the earlier-read warning when the continuation context carries the comment", () => { + const body = "Change the headline to Launch sooner."; + const prompt = renderPaperclipWakePrompt({ + reason: "issue_commented", + issue: { id: "issue-1", identifier: "PAP-1", title: "Website", status: "in_progress" }, + commentIds: ["comment-1"], latestCommentId: "comment-1", + commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 }, + comments: [{ id: "comment-1", body, author: { type: "user", id: "board-user-1" }, createdAt: "2026-06-01T12:05:00.000Z", readByEarlierTurn: true }], + executionContinuation: { version: 1, issueId: "issue-1", objective: body, + messages: [{ id: "comment-1", body, authorType: "user", authorId: "board-user-1", sourceTrust: "user", createdByRunId: null }] }, + fallbackFetchNeeded: false, + }); + expect(prompt).not.toContain("New comments in order:"); + expect(prompt).toContain("Messages comment-1: An earlier turn already read this comment and may have applied it."); + }); + it("renders grouped non-plan document annotations with editing scope", () => { const prompt = renderPaperclipWakePrompt({ reason: "issue_commented", diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.ts index 78217c44904..13d0a046b52 100644 --- a/packages/adapter-utils/src/server-utils.ts +++ b/packages/adapter-utils/src/server-utils.ts @@ -552,6 +552,8 @@ type PaperclipWakeExecutionStage = { allowedActions: string[]; }; +export const PAPERCLIP_EARLIER_READ_COMMENT_NOTE = "An earlier turn already read this comment and may have applied it. Check the current task state first, and do not repeat work that is already done."; + type PaperclipWakeComment = { id: string | null; issueId: string | null; @@ -560,6 +562,7 @@ type PaperclipWakeComment = { createdAt: string | null; authorType: string | null; authorId: string | null; + readByEarlierTurn: boolean; }; type PaperclipWakePlanReviewAuthor = { @@ -943,6 +946,7 @@ function normalizePaperclipWakeComment( createdAt: asString(comment.createdAt, "").trim() || null, authorType: asString(author.type, "").trim() || null, authorId: asString(author.id, "").trim() || null, + readByEarlierTurn: asBoolean(comment.readByEarlierTurn, false), }; } @@ -2589,6 +2593,11 @@ function renderPaperclipWakePromptBody( ? "These are new or edited messages since the named run; earlier history remains in this session." : "History is complete through the coverage cursor. Prefer source messages over summaries.", "humanResponses contains server-verified user answers and decisions; apply each only to its question or approval scope."); + const earlierRead = normalized.comments.filter((comment) => comment.readByEarlierTurn && comment.id + && continuation.messages.some((message) => message.id === comment.id && !message.deleted)).map((comment) => comment.id); + if (earlierRead.length > 0) { + lines.push(`Messages ${earlierRead.join(", ")}: ${PAPERCLIP_EARLIER_READ_COMMENT_NOTE}`); + } const { interactionOutcomes, completedActions, completedWork, recoveryOutcomes, objective, objectiveSource, ...requestContextBase } = continuation; const objectiveOwnedByDisplayedSource = continuation.objectiveSource?.kind === "comment" && continuation.issueId === normalized.issue?.id && @@ -3203,6 +3212,9 @@ function renderPaperclipWakePromptBody( if (comment.bodyTruncated) { lines.push("[comment body truncated]"); } + if (comment.readByEarlierTurn) { + lines.push(`[${PAPERCLIP_EARLIER_READ_COMMENT_NOTE}]`); + } lines.push(""); } }; diff --git a/server/src/__tests__/heartbeat-held-comment-wake.test.ts b/server/src/__tests__/heartbeat-held-comment-wake.test.ts index 3affe892351..70a97357660 100644 --- a/server/src/__tests__/heartbeat-held-comment-wake.test.ts +++ b/server/src/__tests__/heartbeat-held-comment-wake.test.ts @@ -4,8 +4,8 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { and, eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { activityLog, agents, agentWakeupRequests, authUsers, budgetPolicies, companies, companyMemberships, costEvents, createDb, heartbeatRuns, - issueComments, issues } from "@paperclipai/db"; +import { activityLog, agents, agentWakeupRequests, authUsers, budgetPolicies, companies, companyMemberships, costEvents, createDb, heartbeatRunEvents, + heartbeatRuns, issueComments, issues } from "@paperclipai/db"; import { accountRunCost } from "../services/run-cost-accounting.js"; import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; import { requestTaskRetry } from "../services/task-retry.js"; @@ -750,9 +750,18 @@ describePostgres("saved intents while another run's accounting is pending", () = try { const history = await reader.execute({ tool: "get_task_history", callId: `history-${f.sourceRunId}`, arguments: {} }); expect((history as { comments: Array<{ id: string }> }).comments.map(comment => comment.id)).toContain(f.commentId); + expect((history as { arrivedDuringThisTurn?: string[] }).arrivedDuringThisTurn).toContain(`comment:${f.commentId}`); } finally { reader.close(); } } + const reportResult = (f: { companyId: string; agentId: string; commentId: string }, runId: string, cited: boolean) => + db.insert(heartbeatRunEvents).values({ companyId: f.companyId, runId, agentId: f.agentId, seq: 100_000, eventType: "run.result.accepted", + stream: "system", level: "info", payload: { prpEvent: { payload: { result: { schema: "paperclip.run_result.v1", + reportedWorkDisposition: "done", summary: "Done.", + evidence: [{ ref: "document:plan" }, ...(cited ? [{ ref: `comment:${f.commentId} (applied)` }] : [])], + completionClaim: { contractRevision: "1", objectiveSatisfied: true, remainingWork: [], + criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: ["document:plan"] }] } } } } } }); + async function closeSourceRun(f: Awaited>) { await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(Date.now() + 1_000) }) .where(eq(heartbeatRuns.id, f.sourceRunId)); @@ -772,9 +781,10 @@ describePostgres("saved intents while another run's accounting is pending", () = }); it.each([ - { shape: "read unchanged", edit: false, delivered: 0 }, - { shape: "edited after the read", edit: true, delivered: 1 }, - ])("settles a stale queued run of a message the closing run read mid-turn ($shape)", async ({ edit, delivered }) => { + { shape: "read unchanged and cited as handled", edit: false, cited: true, delivered: 0 }, + { shape: "read unchanged but not cited", edit: false, cited: false, delivered: 1 }, + { shape: "edited after the read", edit: true, cited: true, delivered: 1 }, + ])("settles a stale queued run of a message the closing run read mid-turn ($shape)", async ({ edit, cited, delivered }) => { const f = await seedHeldComment(); await runningNativeSource(f); const [wake] = await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, source: "automation", @@ -788,6 +798,7 @@ describePostgres("saved intents while another run's accounting is pending", () = await readHistoryDuringTurn(f); if (edit) await db.update(issueComments).set({ body: "Edited: also include the FOLLOWUP line twice.", updatedAt: new Date(Date.now() + 500) }).where(eq(issueComments.id, f.commentId)); + await reportResult(f, f.sourceRunId, cited); await closeSourceRun(f); await db.update(issues).set({ executionRunId: null, executionLockedAt: null }).where(eq(issues.id, f.issueId)); await settle(f); await settle(f); @@ -805,14 +816,16 @@ describePostgres("saved intents while another run's accounting is pending", () = }, 180_000); it.each([ - { outcome: "succeeded", edit: "none", consumed: true }, - { outcome: "succeeded", edit: "during the run", consumed: false }, - { outcome: "succeeded", edit: "after the run finished", consumed: false }, - { outcome: "failed", edit: "none", consumed: false }, - ])("counts a mid-turn history read as delivery only for a run that $outcome on the current revision (edited: $edit)", async ({ outcome, edit, consumed }) => { + { outcome: "succeeded", edit: "none", cited: true, consumed: true }, + { outcome: "succeeded", edit: "none", cited: false, consumed: false }, + { outcome: "succeeded", edit: "during the run", cited: true, consumed: false }, + { outcome: "succeeded", edit: "after the run finished", cited: true, consumed: false }, + { outcome: "failed", edit: "none", cited: true, consumed: false }, + ])("counts a mid-turn history read as delivery only for a run that $outcome on the current revision and cited it (edited: $edit, cited: $cited)", async ({ outcome, edit, cited, consumed }) => { const f = await seedHeldComment(); await runningNativeSource(f); await readHistoryDuringTurn(f); + await reportResult(f, f.sourceRunId, cited); const editComment = (at: number) => db.update(issueComments).set({ body: "Edited after the read.", updatedAt: new Date(at) }) .where(eq(issueComments.id, f.commentId)); if (edit === "during the run") await editComment(Date.now() + 500); @@ -836,9 +849,10 @@ describePostgres("saved intents while another run's accounting is pending", () = }, 180_000); it.each([ - { read: true, delivered: 0 }, - { read: false, delivered: 1 }, - ])("settles a held message as soon as its run closes the task (read mid-turn: $read)", async ({ read, delivered }) => { + { read: true, cited: true, delivered: 0 }, + { read: true, cited: false, delivered: 1 }, + { read: false, cited: false, delivered: 1 }, + ])("settles a held message as soon as its run closes the task (read mid-turn: $read, cited: $cited)", async ({ read, cited, delivered }) => { const f = await seedHeldComment(); await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, f.pendingRunId)); await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId)); @@ -846,10 +860,12 @@ describePostgres("saved intents while another run's accounting is pending", () = duringTurn = async runId => { duringTurn = null; closingRunId = runId; + await db.update(issueComments).set({ createdAt: new Date(), updatedAt: new Date() }).where(eq(issueComments.id, f.commentId)); await postComment(f); if (!read) return; await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: f.issueId }).where(eq(heartbeatRuns.id, runId)); await readHistoryDuringTurn({ ...f, sourceRunId: runId }); + await reportResult(f, runId, cited); await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, runId)); await closeByAgent(f); }; @@ -864,6 +880,8 @@ describePostgres("saved intents while another run's accounting is pending", () = await settle(f); await settle(f); expect(deliveries(f.commentId)).toHaveLength(delivered); expect(await issueStatus(f)).toBe("done"); + const delivery = deliveries(f.commentId)[0]?.context.paperclipWake as { comments?: Array<{ id: string; readByEarlierTurn?: boolean }> } | undefined; + if (delivered) expect(delivery?.comments?.find(comment => comment.id === f.commentId)?.readByEarlierTurn ?? false).toBe(read); }, 180_000); it("still refuses work at a reached hard stop, which the board owns", async () => { diff --git a/server/src/services/heartbeat/run-preparation.ts b/server/src/services/heartbeat/run-preparation.ts index dfec84316ce..796237196c7 100644 --- a/server/src/services/heartbeat/run-preparation.ts +++ b/server/src/services/heartbeat/run-preparation.ts @@ -1,6 +1,7 @@ import { skillPackageStore, skillVersionMetadataColumns } from "../skill-package-store.js"; import { skillAccessService } from "../skill-access.js"; import { buildReviewPathRecoveryDisposition } from "../recovery/review-path-recovery.js"; +import { readByEarlierTurnCommentIds } from "../queued-comment-delivery.js"; import type { AuthorizationActor } from "../authorization.js"; import { spekoToolsForSession } from "../voice/speko-agent-tools.js"; import { githubConfiguredInstructionSources } from "../chat-github-review-policy.js"; @@ -2359,6 +2360,11 @@ export async function buildPaperclipWakePayload(input: { const commentsById = new Map( commentRows.map((comment) => [comment.id, comment]), ); + const readByEarlierTurn = issueId && input.agentId + ? await readByEarlierTurnCommentIds(input.db, { companyId: input.companyId, issueId, agentId: input.agentId, + commentIds: commentRows.filter(row => !row.deletedAt).map(row => row.id), currentRunId: input.runId ?? null }) + .catch(() => new Set()) + : new Set(); const issueDescription = conversationMode ? null : issueSummary?.description ?? null; const issueDescriptionTruncated = issueDescription !== null && @@ -2427,6 +2433,7 @@ export async function buildPaperclipWakePayload(input: { deletedByRunId: deletedAt ? (row.deletedByRunId ?? null) : null, sourceTrust: row.sourceTrust ?? null, createdAt: row.createdAt.toISOString(), + ...(readByEarlierTurn.has(row.id) ? { readByEarlierTurn: true } : {}), author: row.authorAgentId ? { type: "agent", id: row.authorAgentId } : row.authorUserId diff --git a/server/src/services/native-runtime/native-continuation.test.ts b/server/src/services/native-runtime/native-continuation.test.ts index d1deadc00a1..bc72a9c520e 100644 --- a/server/src/services/native-runtime/native-continuation.test.ts +++ b/server/src/services/native-runtime/native-continuation.test.ts @@ -25,6 +25,12 @@ describe("native continuation event projection", () => { expect(JSON.parse(text).messages[0]).toMatchObject({ authorType: "user", body: message.body }); expect(text.length).toBeLessThan(600); }); + it("tells a resumed turn which delivered comments an earlier turn already read", () => { + const comment = { id: "new", body: message.body, author: { type: "user", id: "board" } }; + const marked = JSON.parse(build({ ...wake, comments: [{ ...comment, readByEarlierTurn: true }] })!); + expect(marked.readByEarlierTurn).toEqual({ messageIds: ["new"], note: expect.stringContaining("may have applied it") }); + expect(JSON.parse(build({ ...wake, comments: [comment] })!).readByEarlierTurn).toBeUndefined(); + }); it("only uses a delta whose base matches the actual previous run", () => { expect(build({ ...wake, executionContinuation: { ...wake.executionContinuation, resumeDelta: { baseRunId: "different", messages: [message] } } })).toBeNull(); expect(build({ ...wake, executionContinuation: null })).toBeNull(); diff --git a/server/src/services/native-runtime/native-continuation.ts b/server/src/services/native-runtime/native-continuation.ts index 52374260cac..27543cd74eb 100644 --- a/server/src/services/native-runtime/native-continuation.ts +++ b/server/src/services/native-runtime/native-continuation.ts @@ -1,4 +1,4 @@ -import { isPaperclipExternalChatContractTurn, normalizePaperclipWakePayload } from "@paperclipai/adapter-utils/server-utils"; +import { isPaperclipExternalChatContractTurn, normalizePaperclipWakePayload, PAPERCLIP_EARLIER_READ_COMMENT_NOTE } from "@paperclipai/adapter-utils/server-utils"; import type { CaseExecutionContext, projectCaseContinuation } from "../case-context.js"; import { caseInstructionAlreadyRepresented } from "../case-context.js"; @@ -85,6 +85,9 @@ export function buildNativeContinuationPrompt(input: { ...(wake.childIssueSummaryTruncated ? { childResultsTruncated: true } : {}), ...(wake.unresolvedBlockerIssueIds.length ? { unresolvedBlockerIssueIds: wake.unresolvedBlockerIssueIds } : {}), }; + const earlierRead = wake.comments.filter((comment) => comment.readByEarlierTurn && comment.id + && events.messages.some((message) => message.id === comment.id)).map((comment) => comment.id!); + if (earlierRead.length > 0) Object.assign(events, { readByEarlierTurn: { messageIds: earlierRead, note: PAPERCLIP_EARLIER_READ_COMMENT_NOTE } }); if (!events.messages.length && !humanResponses.length && !wake.childIssueSummaries.length && !Object.keys(taskChanges).length && !input.workflowCase) return null; return JSON.stringify(events); } 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 9e6495fdc06..ead8a3c426c 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -138,7 +138,7 @@ import { READ_CHAT_ATTACHMENT_TOOL_NAME, type NativeChatAttachmentReadScope, } from "./chat-attachment-read.js"; -import { recordTaskHistoryRead } from "../queued-comment-delivery.js"; +import { commentsArrivedDuringRun, recordTaskHistoryRead, taskHistoryHandlingGuidance } from "../queued-comment-delivery.js"; import { recordChildTaskRead } from "./native-child-completion-delivery.js"; import { logger } from "../../middleware/logger.js"; @@ -1011,10 +1011,12 @@ export class PaperclipRunnerToolAuthority { await recordTaskHistoryRead(this.db, { companyId: this.binding.companyId, agentId: this.binding.agentId, runId: this.binding.runId, comments }).catch(error => logger.warn({ err: error, runId: this.binding.runId }, "could not record the task history a run read")); + const arrived = await commentsArrivedDuringRun(this.db, { companyId: this.binding.companyId, + runId: this.binding.runId, agentId: this.binding.agentId, comments }).catch(() => [] as string[]); return { comments: comments.reverse().map(({ updatedAt: _updatedAt, ...comment }) => { const visible = isLowTrustQuarantined(readerSourceTrust) ? comment : sanitizeQuarantinedCommentForHigherTrust(comment); return { ...visible, body: fastResponseHistoryBody(visible) }; - }) }; + }), ...taskHistoryHandlingGuidance(arrived) }; } case "search_tasks": { const tasks = await issueService(this.db).list(this.binding.companyId, { readCondition: await issueReadSqlCondition(this.db, this.#privacyActor(context.run)) }); diff --git a/server/src/services/native-runtime/runner-semantic-authority.ts b/server/src/services/native-runtime/runner-semantic-authority.ts index 529c1ef483b..205f9956cfc 100644 --- a/server/src/services/native-runtime/runner-semantic-authority.ts +++ b/server/src/services/native-runtime/runner-semantic-authority.ts @@ -7,7 +7,7 @@ import { sanitizeQuarantinedCommentForHigherTrust, } from "../source-trust.js"; import { and, desc, eq, isNull } from "drizzle-orm"; -import { recordTaskHistoryRead } from "../queued-comment-delivery.js"; +import { commentsArrivedDuringRun, recordTaskHistoryRead, taskHistoryHandlingGuidance } from "../queued-comment-delivery.js"; import { logger } from "../../middleware/logger.js"; import type { Db } from "@paperclipai/db"; @@ -194,8 +194,10 @@ export class PaperclipRunnerSemanticAuthority { : sanitizeQuarantinedCommentForHigherTrust(row); return { ...comment, body: fastResponseHistoryBody(comment) }; }); + const arrived = await commentsArrivedDuringRun(this.#db, { companyId: this.#binding.companyId, + runId: this.#binding.runId, agentId: this.#binding.agentId, comments: rows }).catch(() => [] as string[]); return { - value: jsonValue({ comments }), + value: jsonValue({ comments, ...taskHistoryHandlingGuidance(arrived) }), references: [{ kind: "task", id: context.issue.id }], }; } diff --git a/server/src/services/queued-comment-delivery.ts b/server/src/services/queued-comment-delivery.ts index 98664b6ef78..343671a16ec 100644 --- a/server/src/services/queued-comment-delivery.ts +++ b/server/src/services/queued-comment-delivery.ts @@ -88,8 +88,22 @@ export async function historyReadDeliveredCommentIds(tx: Pick, inp return new Set(rows.map(row => row.id)); } +export const COMMENT_EVIDENCE_REF_PREFIX = "comment:"; + function historyReadDeliveredSql(companyId: string, issueId: string, agentId: string) { - const readBy = (binding: SQL) => sql`exists (select 1 from ${heartbeatRuns} reading_run + const handled = sql`exists (select 1 from ${heartbeatRunEvents} handled + where handled.company_id = ${companyId} and handled.run_id = reading_run.id + and handled.event_type = 'run.result.accepted' + and (jsonb_path_exists(handled.payload, '$.prpEvent.payload.result.evidence[*].ref ? (@ starts with $ref)', + jsonb_build_object('ref', ${COMMENT_EVIDENCE_REF_PREFIX} || ${issueComments.id}::text)) + or jsonb_path_exists(handled.payload, '$.prpEvent.payload.result.completionClaim.criteria[*].evidenceRefs[*] ? (@ starts with $ref)', + jsonb_build_object('ref', ${COMMENT_EVIDENCE_REF_PREFIX} || ${issueComments.id}::text))))`; + return sql`(${historyReadSql(companyId, agentId, sql`reading_run.native_issue_id = ${issueId}`, sql`and reading_run.status = 'succeeded' and ${handled}`)} + or ${historyReadSql(companyId, agentId, sql`reading_run.context_snapshot->>'issueId' = ${issueId}`, sql`and reading_run.status = 'succeeded' and ${handled}`)})`; +} + +function historyReadSql(companyId: string, agentId: string, binding: SQL, condition: SQL) { + return sql`exists (select 1 from ${heartbeatRuns} reading_run cross join lateral (select 1 from ${heartbeatRunEvents} history_read where history_read.company_id = ${companyId} and history_read.run_id = reading_run.id and history_read.event_type = ${TASK_HISTORY_READ_EVENT} @@ -97,10 +111,42 @@ function historyReadDeliveredSql(companyId: string, issueId: string, agentId: st >= date_trunc('milliseconds', ${issueComments.updatedAt}) limit 1) read_revision where reading_run.company_id = ${companyId} and ${binding} - and reading_run.agent_id = ${agentId} and reading_run.status = 'succeeded' + and reading_run.agent_id = ${agentId} ${condition} and reading_run.finished_at >= date_trunc('milliseconds', ${issueComments.updatedAt}) offset 0)`; - return sql`(${readBy(sql`reading_run.native_issue_id = ${issueId}`)} - or ${readBy(sql`reading_run.context_snapshot->>'issueId' = ${issueId}`)})`; +} + +export async function readByEarlierTurnCommentIds(tx: Pick, input: { + companyId: string; issueId: string; agentId: string; commentIds: string[]; currentRunId?: string | null; +}): Promise> { + if (input.commentIds.length === 0) return new Set(); + const { companyId, issueId, agentId } = input; + const notCurrent = input.currentRunId ? sql`and reading_run.id <> ${input.currentRunId}` : sql``; + const rows = await tx.select({ id: issueComments.id }).from(issueComments).where(and( + eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), + inArray(issueComments.id, input.commentIds), + sql`(${historyReadSql(companyId, agentId, sql`reading_run.native_issue_id = ${issueId}`, notCurrent)} + or ${historyReadSql(companyId, agentId, sql`reading_run.context_snapshot->>'issueId' = ${issueId}`, notCurrent)})`)); + return new Set(rows.map(row => row.id)); +} + +export async function commentsArrivedDuringRun(db: Pick, input: { + companyId: string; runId: string; agentId: string; + comments: ReadonlyArray<{ id: string; authorAgentId: string | null; createdAt: Date; updatedAt: Date }>; +}): Promise { + if (input.comments.length === 0) return []; + const [run] = await db.select({ startedAt: heartbeatRuns.startedAt }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId))); + const startedAt = run?.startedAt; + if (!startedAt) return []; + return input.comments.filter(comment => comment.authorAgentId !== input.agentId + && Math.max(comment.createdAt.getTime(), comment.updatedAt.getTime()) > startedAt.getTime()).map(comment => comment.id); +} + +export function taskHistoryHandlingGuidance(commentIds: readonly string[]) { + return commentIds.length === 0 ? {} : { + arrivedDuringThisTurn: commentIds.map(id => `${COMMENT_EVIDENCE_REF_PREFIX}${id}`), + handling: "These comments arrived while this turn was running. For each one this turn applies, include its ref in the evidence of paperclip_finish or paperclip_block. Paperclip delivers any comment that is not cited to you again in a new turn after this one.", + }; } /** diff --git a/server/src/services/queued-comment-history-read.test.ts b/server/src/services/queued-comment-history-read.test.ts index 8f04500a9bc..f1358db944c 100644 --- a/server/src/services/queued-comment-history-read.test.ts +++ b/server/src/services/queued-comment-history-read.test.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRunEvents, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { undeliveredLegacyUserCommentIds } from "./explicit-native-continuation.js"; import { PaperclipRunnerToolAuthority } from "./native-runtime/paperclip-runner-tool-authority.js"; @@ -59,13 +59,20 @@ describe.skipIf(!support.supported)("task history reads", () => { expect(await taskHistoryReadsForRun(db, { companyId: randomUUID(), runId: f.runId })).toEqual([]); }); + const citeAsHandled = (f: Awaited>, commentId: string) => db.insert(heartbeatRunEvents).values({ + companyId: f.companyId, runId: f.runId, agentId: f.agentId, seq: 100_000, eventType: "run.result.accepted", stream: "system", level: "info", + payload: { prpEvent: { payload: { result: { schema: "paperclip.run_result.v1", evidence: [], + completionClaim: { criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [`comment:${commentId}`] }] } } } } } }); + it.each([ - { status: "succeeded" as const, owed: false }, - { status: "failed" as const, owed: true }, - ])("treats a remote-stop follow-up that a $status run read mid-turn as owed: $owed", async ({ status, owed }) => { + { status: "succeeded" as const, cited: true, owed: false }, + { status: "succeeded" as const, cited: false, owed: true }, + { status: "failed" as const, cited: true, owed: true }, + ])("treats a remote-stop follow-up that a $status run read mid-turn (cited: $cited) as owed: $owed", async ({ status, cited, owed }) => { const f = await seed(); const followUp = await comment(f, "Additional requirement: include the FOLLOWUP line."); await readHistory(f); + if (cited) await citeAsHandled(f, followUp.id); await finish(f, status); expect(await undeliveredLegacyUserCommentIds(db, f.companyId, f.issueId, f.agentId, [followUp.id])) .toEqual(owed ? [followUp.id] : []); diff --git a/tests/runner-e2e/chat-catalog-descriptors.json b/tests/runner-e2e/chat-catalog-descriptors.json index b6929ed11ac..6b268176c3e 100644 --- a/tests/runner-e2e/chat-catalog-descriptors.json +++ b/tests/runner-e2e/chat-catalog-descriptors.json @@ -323,7 +323,7 @@ "registered-artifact.ts", "chat-scenarios/agent-chat.yaml" ], - "oracleVersion": "paperclip.chat-catalog.runtime-multiple-handoffs.v5", + "oracleVersion": "paperclip.chat-catalog.runtime-multiple-handoffs.v6", "coverageGaps": [], "expectedRunCount": 5, "minimumRunCount": 4, diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.test.ts b/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.test.ts index e334d976efd..ce22d91fac7 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.test.ts @@ -49,24 +49,45 @@ it("finds a delivered comment in a native continuation that embeds it as JSON", }); function inTurn() { const o = valid(); o.runs.pop(); - Object.assign(o.state, { savedComment: { id: "headline", updatedAt: "2026-11-12T21:50:58.894Z" }, workerHistoryReads: { headline: "2026-11-12T21:50:58.894Z" }, + Object.assign(o.state, { savedComment: { id: "headline", updatedAt: "2026-11-12T21:50:58.894Z" }, workerCommentReceipts: { reads: { headline: "2026-11-12T21:50:58.894Z" }, cited: ["headline"] }, nativeDeliveryBound: false, finalHeadlineRevision: false, originalWebsiteRevisionRetained: false, inTurnHeadlineRevision: true }); return o; } it("accepts the running Website turn reading the current headline feedback and saving it, with no continuation", () => expect(gradeMultipleHandoffs(inTurn()).passed).toBe(true)); it("accepts the same in-turn consumption with a later read of the same revision", () => { - const o = inTurn(); (o.state as Record).workerHistoryReads = { headline: "2026-11-12T21:51:25.000Z" }; expect(gradeMultipleHandoffs(o).passed).toBe(true); + const o = inTurn(); (o.state as Record).workerCommentReceipts = { reads: { headline: "2026-11-12T21:51:25.000Z" }, cited: ["headline"] }; expect(gradeMultipleHandoffs(o).passed).toBe(true); }); it("rejects an in-turn read of an earlier revision with no continuation", () => { - const o = inTurn(); (o.state as Record).workerHistoryReads = { headline: "2026-11-12T21:50:00.000Z" }; expect(gradeMultipleHandoffs(o).passed).toBe(false); + const o = inTurn(); (o.state as Record).workerCommentReceipts = { reads: { headline: "2026-11-12T21:50:00.000Z" }, cited: ["headline"] }; expect(gradeMultipleHandoffs(o).passed).toBe(false); }); it("rejects an in-turn read whose headline was never saved", () => { const o = inTurn(); (o.state as Record).inTurnHeadlineRevision = false; expect(gradeMultipleHandoffs(o).passed).toBe(false); }); -it("rejects a double application: an in-turn read and a continuation", () => { - const o = valid(); Object.assign(o.state, { savedComment: { id: "headline", updatedAt: "2026-11-12T21:50:58.894Z" }, workerHistoryReads: { headline: "2026-11-12T21:50:58.894Z" }, inTurnHeadlineRevision: true }); +it("rejects a double application: an in-turn read cited as handled and a continuation", () => { + const o = valid(); Object.assign(o.state, { savedComment: { id: "headline", updatedAt: "2026-11-12T21:50:58.894Z" }, + workerCommentReceipts: { reads: { headline: "2026-11-12T21:50:58.894Z" }, cited: ["headline"] }, inTurnHeadlineRevision: true, continuationWarnedEarlierRead: true }); expect(gradeMultipleHandoffs(o).passed).toBe(false); }); +it("rejects an instruction the running turn read but neither cited nor received again", () => { + const o = inTurn(); (o.state as Record).workerCommentReceipts = { reads: { headline: "2026-11-12T21:50:58.894Z" }, cited: [] }; + (o.state as Record).inTurnHeadlineRevision = false; expect(gradeMultipleHandoffs(o).passed).toBe(false); +}); +it("rejects a saved in-turn headline that the running turn did not cite, with no continuation", () => { + const o = inTurn(); (o.state as Record).workerCommentReceipts = { reads: { headline: "2026-11-12T21:50:58.894Z" }, cited: [] }; + expect(gradeMultipleHandoffs(o).passed).toBe(false); +}); +function readNotCited() { + const o = valid(); Object.assign(o.state, { savedComment: { id: "headline", updatedAt: "2026-11-12T21:50:58.894Z" }, + workerCommentReceipts: { reads: { headline: "2026-11-12T21:50:58.894Z" }, cited: [] }, continuationWarnedEarlierRead: true }); + return o; +} +it("accepts a read the running turn did not cite, delivered once to a continuation told about the earlier read", () => expect(gradeMultipleHandoffs(readNotCited()).passed).toBe(true)); +it("rejects that continuation when it was not told the running turn already read the instruction", () => { + const o = readNotCited(); (o.state as Record).continuationWarnedEarlierRead = false; expect(gradeMultipleHandoffs(o).passed).toBe(false); +}); +it("rejects that continuation when the final Website revision lacks the headline", () => { + const o = readNotCited(); o.state.finalHeadlineRevision = false; expect(gradeMultipleHandoffs(o).passed).toBe(false); +}); it("rejects two Website continuations", () => { const o = valid(); o.runs.push({ id: "again", agentId: "morgan", status: "succeeded" }); expect(gradeMultipleHandoffs(o).passed).toBe(false); }); it("rejects an in-turn read of a different comment", () => { - const o = inTurn(); (o.state as Record).savedComment = { id: "other", updatedAt: "2026-11-12T21:50:58.894Z" }; (o.state as Record).workerHistoryReads = { other: "2026-11-12T21:50:58.894Z" }; + const o = inTurn(); (o.state as Record).savedComment = { id: "other", updatedAt: "2026-11-12T21:50:58.894Z" }; (o.state as Record).workerCommentReceipts = { reads: { other: "2026-11-12T21:50:58.894Z" }, cited: ["other"] }; expect(gradeMultipleHandoffs(o).passed).toBe(false); }); diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.ts b/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.ts index f4b75bdf310..3ce2beb57f7 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-multiple-handoffs.ts @@ -7,7 +7,7 @@ import { readRegisteredArtifacts } from "../registered-artifact.js"; import { checks, sameTask, type Entity } from "./internal-support.js"; import { openStandingChat } from "./identity-support.js"; import { busyRuntimeWorker, releaseRuntimeWorker } from "./runtime-busy-worker.js"; -import { promptCarriesComment, readCurrentRevision, replyNamesTask, runHistoryReads, runtimeQueueCases, settledQueue } from "./runtime-queue.js"; +import { handledInTurn, promptCarriesComment, readCurrentRevision, replyNamesTask, runCommentReceipts, runtimeQueueCases, settledQueue, wakeMarksEarlierRead } from "./runtime-queue.js"; import { runtimeDefinition, runtimeObservation, observeRuntime, runtimeWorker } from "./runtime-support.js"; export { promptCarriesComment } from "./runtime-queue.js"; type Artifact = Awaited>[number]; @@ -18,14 +18,17 @@ export function gradeMultipleHandoffs(value: unknown) { const before = s.logoArtifactBefore as Artifact, after = s.logoArtifactAfter as Artifact; const worker = s.worker as Entity | undefined, websiteRuns = o.runs.filter(row => row.agentId === worker?.id); const continuations = websiteRuns.filter(row => row.id !== s.workerRunId), saved = s.savedComment as { id: string; updatedAt?: unknown } | undefined; - const readInTurn = !!saved && saved.id === target?.comment.id && readCurrentRevision(s.workerHistoryReads as Record | undefined, saved); - const consumedInTurn = readInTurn && continuations.length === 0 && s.inTurnHeadlineRevision === true; - const consumedByContinuation = !readInTurn && continuations.length === 1 && s.nativeDeliveryBound === true && s.finalHeadlineRevision === true && s.originalWebsiteRevisionRetained === true; + const receipts = s.workerCommentReceipts as { reads?: Record; cited?: string[] } | undefined; + const isTarget = !!saved && saved.id === target?.comment.id; + const readInTurn = isTarget && readCurrentRevision(receipts?.reads, saved), handled = isTarget && handledInTurn(receipts, saved); + const consumedInTurn = handled && continuations.length === 0 && s.inTurnHeadlineRevision === true; + const consumedByContinuation = !handled && continuations.length === 1 && s.nativeDeliveryBound === true && s.finalHeadlineRevision === true + && s.originalWebsiteRevisionRetained === true && (!readInTurn || s.continuationWarnedEarlierRead === true); c.add("existing-website-worker-receives-one-saved-requirement", s.sourceHistoryBound === true && queue?.issueId === (s.task as Entity).id && queue.targetRunId === s.workerRunId && queue.entries.length === 1 && ["queued", "deferred"].includes(queue.state ?? "") && target?.comment.authorAgentId === o.leadId && target.comment.createdByRunId === s.canonicalRunId && target.comment.body.includes("Launch sooner") && s.workerRunningAtReply === true && (consumedInTurn || consumedByContinuation) && s.queueEmptyAfterDelivery === true, - "One CEO-attributed headline instruction is saved against the actual active Website owner and is consumed once: read at its current revision and applied by the running turn with no continuation, or delivered to exactly one ordinary continuation."); + "One CEO-attributed headline instruction is saved against the actual active Website owner and is consumed once: read at its current revision, applied and cited as handled by the running turn with no continuation, or delivered to exactly one ordinary continuation, which is told when the running turn already read it."); c.add("logo-task-and-delivered-logo-unchanged", !!logoBefore && !!logo && sameTask(logoBefore, logo) && logo.status === "done" && logo.assigneeAgentId === (s.logoWorker as Entity).id && before?.contentVerified === true && after?.contentVerified === true && before.attachmentId === after.attachmentId && before.sha256 === after.sha256 && before.content === after.content && after.content.includes(String(s.logoMarker)) && / !row.authorAgentId).length === 1 && comments.some(row => !row.authorAgentId && row.body?.includes(busy.task.identifier ?? busy.task.id) && row.body.includes(logo.identifier ?? logo.id) && row.body.includes(artifact.attachmentId)), setupRunIds: saved.runs.map(row => row.id) }; }, gradeMultipleHandoffs, { - setupHumanMessageCount: 1, expectedHumanMessageCount: 2, expectedRunCount: 5, minimumRunCount: 4, attemptTimeoutMs: 1_020_000, oracleVersion: "paperclip.chat-catalog.runtime-multiple-handoffs.v5", + setupHumanMessageCount: 1, expectedHumanMessageCount: 2, expectedRunCount: 5, minimumRunCount: 4, attemptTimeoutMs: 1_020_000, oracleVersion: "paperclip.chat-catalog.runtime-multiple-handoffs.v6", sourceFiles: ["chat-catalog-domains/runtime-multiple-handoffs.ts", "chat-catalog-domains/runtime-queue.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/identity-support.ts", "registered-artifact.ts", "chat-scenarios/agent-chat.yaml"], setupPolicy: runtimeQueueCases[0]!.setupPolicy, verifySetup: runtimeQueueCases[0]!.verifySetup, async act(ctx, state) { @@ -88,9 +91,10 @@ export const runtimeMultipleHandoffCases = [runtimeDefinition("agent-chat.multip reject: v => v.runs.length > 5 || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "Headline continuation failed or duplicated/wrong-task work" : undefined }); const saved = first.queue.entries[0]!.comment, current = (await ctx.input.api.get(`/api/issues/${task.id}/comments?order=asc`)).find(row => row.id === saved.id); state.savedComment = current ? { id: current.id, updatedAt: current.updatedAt } : null; - state.workerHistoryReads = await runHistoryReads(ctx, String(state.workerRunId)); + state.workerCommentReceipts = await runCommentReceipts(ctx, String(state.workerRunId)); const consumer = final.runs.find(row => row.agentId === (state.worker as Entity).id && row.id !== state.workerRunId); - const detail = consumer && await ctx.input.api.get<{ contextSnapshot?: { wakeCommentIds?: string[] }; runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${consumer.id}`); + const detail = consumer && await ctx.input.api.get<{ contextSnapshot?: { wakeCommentIds?: string[]; paperclipWake?: { comments?: Array<{ id?: string; readByEarlierTurn?: boolean }> } }; runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${consumer.id}`); + state.continuationWarnedEarlierRead = wakeMarksEarlierRead(detail?.contextSnapshot, saved.id); state.nativeDeliveryBound = detail?.contextSnapshot?.wakeCommentIds?.length === 1 && detail.contextSnapshot.wakeCommentIds[0] === saved.id && promptCarriesComment(detail.runnerProfileJson?.nativeExecutionInput?.task?.prompt, saved); state.queueEmptyAfterDelivery = final.queue.entries.length === 0; state.finalWebsiteRunId = consumer?.id ?? null; diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.test.ts b/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.test.ts index 2e0957ee478..3fa1dfbc4ba 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.test.ts @@ -9,7 +9,8 @@ function valid() { runs: [{ id: "prior", agentId: "morgan", status: "succeeded" }, { id: "guide", agentId: "ceo", status: "succeeded" }, { id: "consumer", agentId: "morgan", status: "succeeded" }], state: { task: { id: "website" }, worker: { id: "morgan" }, queueBefore: before, targetId: "color", workerRunId: "prior", humanId: "human", concurrentMarker: "Preserve the human note.", queuedComments: [{ id: "color", updatedAt: "2026-11-12T21:52:30.494Z" }, { id: "font", updatedAt: "2026-11-12T21:50:24.404Z" }], - workerHistoryReads: {} as Record, taskDone: true, inTurnOutcomeApplied: false, + workerCommentReceipts: { reads: {} as Record, cited: [] as string[] }, taskDone: true, inTurnOutcomeApplied: false, + finalOutcomeApplied: true, continuationWarnedEarlierReads: true, queueAfter: { ...before, entries: [{ ...before.entries[1]!, position: 0, comment: { ...before.entries[1]!.comment, body: "Make the website blue. Keep the existing note about accessible labels. Preserve the human note." } }, { ...before.entries[0]!, position: 1 }] }, queryReply: "Your pending red request is in the Website queue. Open its message menu, edit the full request to blue, then move it first.", @@ -51,20 +52,23 @@ it.each([200, 403, 500])("rejects late edit status %s rather than replacing the function inTurn() { const o = valid(); o.runs.pop(); - o.state.workerHistoryReads = { color: "2026-11-12T21:52:30.494Z", font: "2026-11-12T21:50:24.404Z" }; + o.state.workerCommentReceipts = { reads: { color: "2026-11-12T21:52:30.494Z", font: "2026-11-12T21:50:24.404Z" }, cited: ["color", "font"] }; Object.assign(o.state, { consumingRunCount: 0, nativeDeliveryBound: false, inTurnOutcomeApplied: true }); return o; } it("accepts the running turn consuming the current edited revision with no continuation", () => expect(gradeQueueEdit(inTurn()).passed).toBe(true)); -it("accepts an in-turn read made after the last edit", () => { const o = inTurn(); o.state.workerHistoryReads.color = "2026-11-12T21:52:39.000Z"; expect(gradeQueueEdit(o).passed).toBe(true); }); +it("accepts an in-turn read made after the last edit", () => { const o = inTurn(); o.state.workerCommentReceipts.reads.color = "2026-11-12T21:52:39.000Z"; expect(gradeQueueEdit(o).passed).toBe(true); }); it("still accepts one continuation when the running turn read only the earlier revision", () => { - const o = valid(); o.state.workerHistoryReads = { color: "2026-11-12T21:50:32.657Z" }; expect(gradeQueueEdit(o).passed).toBe(true); + const o = valid(); o.state.workerCommentReceipts = { reads: { color: "2026-11-12T21:50:32.657Z" }, cited: ["color"] }; expect(gradeQueueEdit(o).passed).toBe(true); }); -it("rejects an in-turn read of the earlier revision only", () => { const o = inTurn(); o.state.workerHistoryReads.color = "2026-11-12T21:50:32.657Z"; expect(gradeQueueEdit(o).passed).toBe(false); }); -it("rejects an in-turn read of only one queued message", () => { const o = inTurn(); delete (o.state.workerHistoryReads as Record).font; expect(gradeQueueEdit(o).passed).toBe(false); }); +it("rejects an in-turn read of the earlier revision only", () => { const o = inTurn(); o.state.workerCommentReceipts.reads.color = "2026-11-12T21:50:32.657Z"; expect(gradeQueueEdit(o).passed).toBe(false); }); +it("rejects an in-turn read of only one queued message", () => { const o = inTurn(); delete (o.state.workerCommentReceipts.reads as Record).font; expect(gradeQueueEdit(o).passed).toBe(false); }); it("rejects an in-turn read whose change was never saved", () => { const o = inTurn(); o.state.inTurnOutcomeApplied = false; expect(gradeQueueEdit(o).passed).toBe(false); }); -it("rejects a double application: an in-turn read and a continuation", () => { - const o = valid(); o.state.workerHistoryReads = { color: "2026-11-12T21:52:30.494Z", font: "2026-11-12T21:50:24.404Z" }; o.state.inTurnOutcomeApplied = true; +it("rejects in-turn reads of both messages that cite only one, with no continuation", () => { + const o = inTurn(); o.state.workerCommentReceipts.cited = ["color"]; expect(gradeQueueEdit(o).passed).toBe(false); +}); +it("rejects a double application: an in-turn read cited as handled and a continuation", () => { + const o = valid(); o.state.workerCommentReceipts = { reads: { color: "2026-11-12T21:52:30.494Z", font: "2026-11-12T21:50:24.404Z" }, cited: ["color", "font"] }; o.state.inTurnOutcomeApplied = true; expect(gradeQueueEdit(o).passed).toBe(false); }); it("rejects two continuations", () => { @@ -76,7 +80,8 @@ it("rejects consumption that leaves the queue or task unfinished", () => { }); function mixed() { const o = valid() as ReturnType & { state: Record }; - Object.assign(o.state, { workerHistoryReads: { color: "2026-11-12T21:52:30.494Z" }, inTurnOutcomeApplied: false, inTurnOutcomeSaved: true, latestOutcomeKept: true }); + Object.assign(o.state, { workerCommentReceipts: { reads: { color: "2026-11-12T21:52:30.494Z" }, cited: ["color"] }, inTurnOutcomeApplied: false, inTurnOutcomeSaved: true, latestOutcomeKept: true, + finalOutcomeApplied: false }); return o; } it("grades the whole limit-1 partial read: the turn saved blue, the continuation got only the font note and saved the latest revision", () => { @@ -88,3 +93,17 @@ it("rejects the edited message read in the running turn whose change was never s const o = mixed(); o.state.inTurnOutcomeSaved = false; expect(gradeQueueEdit(o).passed).toBe(false); }); it("rejects a continuation that re-delivers the message the running turn already read", () => { const o = mixed(); o.state.nativeDeliveryBound = false; expect(gradeQueueEdit(o).passed).toBe(false); }); +function readNotCited() { + const o = valid(); o.state.workerCommentReceipts = { reads: { color: "2026-11-12T21:52:30.494Z", font: "2026-11-12T21:50:24.404Z" }, cited: [] }; + return o; +} +it("accepts reads the running turn did not cite, delivered once to a continuation told about the earlier reads", () => expect(gradeQueueEdit(readNotCited()).passed).toBe(true)); +it("rejects that continuation when it was not told the running turn already read the messages", () => { + const o = readNotCited(); o.state.continuationWarnedEarlierReads = false; expect(gradeQueueEdit(o).passed).toBe(false); +}); +it("rejects that continuation when it saves no latest revision", () => { + const o = readNotCited(); o.state.finalOutcomeApplied = false; expect(gradeQueueEdit(o).passed).toBe(false); +}); +it("rejects messages the running turn read but did not cite, with no continuation", () => { + const o = inTurn(); o.state.workerCommentReceipts.cited = []; expect(gradeQueueEdit(o).passed).toBe(false); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.ts b/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.ts index 4b73110be47..b4bdc7ca957 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-queue-controls.ts @@ -8,7 +8,7 @@ import { submitTaskReply } from "../user-actions.js"; import { checks, hasLink, type Entity } from "./internal-support.js"; import { probeAgentPermission, cleanupIdentityProbes, waitForTurnReplyLinks } from "./identity-support.js"; import { busyRuntimeWorker, releaseRuntimeWorker } from "./runtime-busy-worker.js"; -import { keyboardMoveQueuedMessageUp, readCurrentRevision, runHistoryReads, runtimeQueueCases, settledQueue } from "./runtime-queue.js"; +import { handledInTurn, keyboardMoveQueuedMessageUp, readCurrentRevision, runCommentReceipts, runtimeQueueCases, settledQueue, wakeMarksEarlierRead } from "./runtime-queue.js"; import { observeRuntime, runtimeDefinition, runtimeObservation } from "./runtime-support.js"; const otherText = "Use a readable font with accessible labels."; @@ -71,15 +71,15 @@ export function gradeQueueEdit(value: unknown) { c.add("dispatched-edit-is-visible-new-direction", s.dispatchedStatus === 409 && s.dispatchedWarningVisible === true && s.originalCommentStillReadable === true, "After actual dispatch, the old edit rejects and the real composer offers a new message rather than rewriting consumed history."); const queued = Array.isArray(s.queuedComments) ? s.queuedComments as Array<{ id: string; updatedAt?: unknown }> : []; - const reads = s.workerHistoryReads as Record | undefined, worker = s.worker as Entity | undefined; + const receipts = s.workerCommentReceipts as { reads?: Record; cited?: string[] } | undefined, worker = s.worker as Entity | undefined; const continuations = o.runs.filter(row => row.agentId === worker?.id && row.id !== s.workerRunId); - const targetRead = readCurrentRevision(reads, queued.find(row => row.id === s.targetId)), unread = queued.filter(row => !readCurrentRevision(reads, row)); - const consumedInTurn = queued.length === 2 && unread.length === 0 && continuations.length === 0 && o.runs.length === 2 && s.inTurnOutcomeApplied === true; - const consumedByContinuation = unread.length > 0 && continuations.length === 1 && s.consumingRunCount === 1 && s.nativeDeliveryBound === true && o.runs.length === 3 - && (!targetRead || s.inTurnOutcomeSaved === true && s.latestOutcomeKept === true); + const targetHandled = handledInTurn(receipts, queued.find(row => row.id === s.targetId)), owed = queued.filter(row => !handledInTurn(receipts, row)); + const consumedInTurn = queued.length === 2 && owed.length === 0 && continuations.length === 0 && o.runs.length === 2 && s.inTurnOutcomeApplied === true; + const consumedByContinuation = owed.length > 0 && continuations.length === 1 && s.consumingRunCount === 1 && s.nativeDeliveryBound === true && o.runs.length === 3 + && s.continuationWarnedEarlierReads === true && (targetHandled ? s.inTurnOutcomeSaved === true && s.latestOutcomeKept === true : s.finalOutcomeApplied === true); c.add("edited-message-consumed-once", queued.length === 2 && queued[0]?.id === s.targetId && (consumedInTurn || consumedByContinuation) && s.queueEmptyAfterDelivery === true && s.taskDone === true && o.runs.every(row => row.status === "succeeded") && s.initialRevisionRetained === true, - "The edited message is consumed exactly once: the running turn read its current revision and saved the change with no continuation, or one ordinary continuation receives it in its final order."); + "The edited message is consumed exactly once: the running turn read its current revision, saved the change and cited it as handled with no continuation, or one ordinary continuation receives every message not handled in turn, in its final order, and that continuation saves the latest revision."); return c.result(); } @@ -159,12 +159,13 @@ export const runtimeQueueControlCases = [runtimeDefinition("steering.edit-queued state.originalCommentStillReadable = comments.some(row => row.id === targetId && row.body === `${blueText} ${state.concurrentMarker}` && row.authorUserId === state.humanId); const otherId = initial.entries.find(row => row.comment.id !== targetId)?.comment.id; state.queuedComments = [targetId, otherId].map(id => comments.find(row => row.id === id)).filter(Boolean).map(row => ({ id: row!.id, updatedAt: row!.updatedAt, body: row!.body })); - state.workerHistoryReads = await runHistoryReads(ctx, String(state.workerRunId)); - const unread = (state.queuedComments as Array<{ id: string; updatedAt?: unknown; body?: string }>).filter(row => !readCurrentRevision(state.workerHistoryReads as Record, row)); + const receipts = await runCommentReceipts(ctx, String(state.workerRunId)); state.workerCommentReceipts = receipts; + const unread = (state.queuedComments as Array<{ id: string; updatedAt?: unknown; body?: string }>).filter(row => !handledInTurn(receipts, row)); const consumers = delivered.runs.filter(row => row.agentId === (state.worker as Entity).id && row.id !== state.workerRunId); - const run = consumers[0] && await ctx.input.api.get<{ contextSnapshot?: { wakeCommentIds?: string[] }; runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${consumers[0].id}`); + const run = consumers[0] && await ctx.input.api.get<{ contextSnapshot?: { wakeCommentIds?: string[]; paperclipWake?: { comments?: Array<{ id?: string; readByEarlierTurn?: boolean }> } }; runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${consumers[0].id}`); + state.continuationWarnedEarlierReads = unread.every(row => !readCurrentRevision(receipts.reads, row) || wakeMarksEarlierRead(run?.contextSnapshot, row.id)); const ids = run?.contextSnapshot?.wakeCommentIds ?? [], prompt = run?.runnerProfileJson?.nativeExecutionInput?.task?.prompt ?? ""; - state.consumingRunCount = consumers.length; state.nativeDeliveryBound = unread.length > 0 && JSON.stringify(ids) === JSON.stringify(unread.map(row => row.id)) + state.consumingRunCount = consumers.length; state.consumerRunId = consumers[0]?.id ?? null; state.nativeDeliveryBound = unread.length > 0 && JSON.stringify(ids) === JSON.stringify(unread.map(row => row.id)) && unread.every(row => prompt.includes(String(row.body))); state.queueEmptyAfterDelivery = delivered.queue.entries.length === 0; state.taskDone = delivered.task.status === "done"; await ctx.input.capture("actual-queued-edit-stale-dispatch", "Consumed human direction remains history and stale editing offers a new message", "runtime-queued-edit.png"); @@ -176,6 +177,7 @@ export const runtimeQueueControlCases = [runtimeDefinition("steering.edit-queued const blue = o.revisions.filter(row => row.createdByRunId === state.workerRunId && row.createdByAgentId === (state.worker as Entity).id && /\bblue\b/i.test(row.body ?? "")); const latest = (row: Entity) => o.documents.some(doc => doc.id === row.documentId && doc.latestRevisionId === row.id); state.inTurnOutcomeApplied = blue.some(latest); state.inTurnOutcomeSaved = blue.length > 0; + state.finalOutcomeApplied = !!state.consumerRunId && o.revisions.some(row => row.createdByRunId === state.consumerRunId && row.createdByAgentId === (state.worker as Entity).id && latest(row)); state.latestOutcomeKept = blue.some(saved => o.revisions.some(row => row.documentId === saved.documentId && latest(row) && /\bblue\b/i.test(row.body ?? ""))); return o; }, diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-queue.test.ts b/tests/runner-e2e/chat-catalog-domains/runtime-queue.test.ts index 59fc6835c3a..11f665b3465 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-queue.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-queue.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from "vitest"; import { deflateRawSync } from "node:zlib"; -import { gradeQueuedFollowup, historyReadRevisions, keyboardMoveQueuedMessageUp, promptCarriesComment, readCurrentRevision, zipEntryTexts } from "./runtime-queue.js"; +import { gradeQueuedFollowup, historyReadRevisions, keyboardMoveQueuedMessageUp, promptCarriesComment, readCurrentRevision, resultCitedCommentIds, zipEntryTexts } from "./runtime-queue.js"; /** A minimal zip with one deflated and one stored entry, laid out as zip tools write it. */ function zip(entries: Array<{ name: string; text: string; deflate: boolean }>) { const locals: Buffer[] = [], centrals: Buffer[] = []; let offset = 0; @@ -118,3 +118,12 @@ describe("task history reads", () => { expect(readCurrentRevision(reads, undefined)).toBe(false); }); }); +it("reads comment citations only from the run's accepted result", () => { + const id = "3047528e-3c1d-41ee-94e9-122ee17f3032", other = "b9e3ab32-934e-4d07-a5cf-e06fc28d574a"; + const accepted = (result: unknown) => ({ eventType: "run.result.accepted", payload: { prpEvent: { payload: { result } } } }); + expect(resultCitedCommentIds([accepted({ evidence: [{ ref: `comment:${id} (applied)` }, { ref: "document:plan" }] })])).toEqual([id]); + expect(resultCitedCommentIds([accepted({ evidence: [], completionClaim: { criteria: [{ evidenceRefs: [`comment:${other}`] }] } })])).toEqual([other]); + expect(resultCitedCommentIds([accepted({ evidence: [{ ref: `comment:${other.toUpperCase()}` }, { ref: `Comment:${other}` }] })])).toEqual([]); + expect(resultCitedCommentIds([{ eventType: "run.result.proposed", payload: { prpEvent: { payload: { result: { evidence: [{ ref: `comment:${id}` }] } } } } }])).toEqual([]); + expect(resultCitedCommentIds([accepted({ evidence: [{ ref: `document:comment:${id}` }, { ref: "comment:not-a-comment" }] })])).toEqual([]); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-queue.ts b/tests/runner-e2e/chat-catalog-domains/runtime-queue.ts index 3ec0a8b7559..783fb937726 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-queue.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-queue.ts @@ -83,9 +83,32 @@ export function readCurrentRevision(reads: Record | undefined, c const read = Date.parse(String(reads?.[comment.id] ?? "")), current = Date.parse(String(comment.updatedAt ?? "")); return Number.isFinite(read) && Number.isFinite(current) && read >= current; } +export function resultCitedCommentIds(events: ReadonlyArray<{ eventType?: unknown; payload?: unknown }>) { + const cited = new Set(); + for (const row of events) { + if (row.eventType !== "run.result.accepted") continue; + const result = (row.payload as { prpEvent?: { payload?: { result?: { evidence?: unknown; completionClaim?: { criteria?: unknown } } } } } | null | undefined)?.prpEvent?.payload?.result; + const refs = [...(Array.isArray(result?.evidence) ? result.evidence.map(entry => (entry as { ref?: unknown } | null)?.ref) : []), + ...(Array.isArray(result?.completionClaim?.criteria) ? result.completionClaim.criteria.flatMap(entry => (entry as { evidenceRefs?: unknown } | null)?.evidenceRefs ?? []) : [])]; + for (const ref of refs) { + const match = typeof ref === "string" ? /^comment:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(ref) : null; + if (match) cited.add(match[1]!); + } + } + return [...cited]; +} export async function runHistoryReads(ctx: ChatCatalogContext, runId: string) { + return (await runCommentReceipts(ctx, runId)).reads; +} +export async function runCommentReceipts(ctx: ChatCatalogContext, runId: string) { const events = await collectRunEvents<{ seq?: number; eventType?: unknown; payload?: unknown }>((afterSeq, limit) => ctx.input.api.get(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=${limit}`)); - return historyReadRevisions(events); + return { reads: historyReadRevisions(events), cited: resultCitedCommentIds(events) }; +} +export function handledInTurn(receipts: { reads?: Record; cited?: string[] } | undefined, comment: { id: string; updatedAt?: unknown } | undefined) { + return !!comment && readCurrentRevision(receipts?.reads, comment) && !!receipts?.cited?.includes(comment.id); +} +export function wakeMarksEarlierRead(context: { paperclipWake?: { comments?: Array<{ id?: string; readByEarlierTurn?: boolean }> } } | undefined, commentId: string) { + return context?.paperclipWake?.comments?.some(row => row.id === commentId && row.readByEarlierTurn === true) === true; } export function settledQueue(accept: (value: T) => boolean, quietMs: number) { let since: number | undefined; From a298ca7fbce4195ecaf119cf613b9a225522cabb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:08:19 -0600 Subject: [PATCH 02/15] fix(runner): prove ownership right before starting a turn in a recovered session (#21260) 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 > - Paperclip Runner runs native agent sessions (Codex, Claude, and others) and keeps them alive across server swaps. A new server generation recovers the session and continues it. > - Only the generation that owns the run may submit a turn into the provider session. The Runner proves ownership with a fenced checkpoint (controller boot, generation and lease, judged by the database clock). > - On a recovered session, the startup turn and the restart continuation took that checkpoint right after recovery, then prepared the turn's input (attachments, queued input, steered messages), then submitted. > - A generation that lost the run during input preparation still submitted a turn into the shared provider session. > - This pull request repeats the fenced checkpoint right before `turn.start` on those two recovered-session paths. > - The benefit is that a server generation that no longer owns a run cannot add a turn to its provider session. New sessions are unchanged, so nothing is added before their first turn. ## Linked Issues or Issue Description **What happened?** On staging, a Codex run crossed three server swaps. After its turn finished without a result, a turn that no generation could account for appeared in the same provider thread. Every path that submits a turn into an existing session is preceded by the fenced checkpoint, but the two startup paths took it before input preparation, not right before the submit. A generation that lost the run in that window still submitted. **Expected behavior** A generation submits a turn into a recovered session only if it still owns the run at the moment of the submit. **Steps to reproduce** 1. Recover a native session on a new server generation. 2. While it prepares the startup turn's input, fence the generation (another generation takes the lease). 3. Before this change, the turn is still submitted. After it, the checkpoint fails and no turn starts. ## What Changed - `packages/paperclip-runner/src/native-session-runtime.ts`: - The restart continuation calls the fenced `checkpoint` right before `session.startTurn`, after attachments and steered messages are prepared. - The startup turn on a recovered session (`recovered === true`) calls `checkpoint` right before `session.startTurn`. A new session's normal path is unchanged. - `packages/paperclip-runner/src/native-session-runtime.test.ts`: new tests "proves it still owns a recovered session right before starting a turn in it" (startup turn) and "proves it still owns a recovered session right before a restart continuation" at startup and when the lost turn's terminal arrives (`resumeInterruptedTurn`). Turn starts into an existing session, and how each proves ownership right before the submit: - Startup turn on a recovered session: new checkpoint, covered by the first test. - Restart continuation (`startRestartContinuation`), at startup and via `resumeInterruptedTurn`: new checkpoint, covered by the second test (both cases). - Continuation disposition (`requestContinuationDisposition`): already persists the fenced checkpoint immediately before `startTurn`, with only a snapshot read between them and no input preparation. No change. - Compaction turn: started right after the fenced recovery checkpoint with an empty message; there is no input preparation between them (the only possible await is the disposition-replay read, which applies only when a disposition turn was submitted, and then no compaction turn starts). No change. - Runner-only change. No change to `protocol/`, `generated/`, Rust shapes or the ACPX patch, so the provider-pack `contractDigest` and interface revisions are unchanged and older image packs stay compatible. The Runner build and image content for this source change are produced by CI (`runner-artifacts`); nothing is deployed by this PR. ## Verification - Red-to-green: "proves it still owns a recovered session right before starting a turn in it" fails without the startup-turn checkpoint (the turn is submitted after the generation is fenced) and passes with it. Both restart-continuation cases fail with the checkpoint removed from `startRestartContinuation` and pass with it. - Local: `cd packages/paperclip-runner && pnpm exec vitest run src/native-session-runtime.test.ts`: 290 passed. - Local: `node scripts/typecheck-test-programs.mjs packages/paperclip-runner/tsconfig.test.json`: passed (the first CI run failed on the test's attachment prompt returning `undefined`; it now returns a string). - **Not run locally:** one test case that needs the Rust `paperclip-runnerd` binary, and `src/live/runnerd-restart-continuation.test.ts` (10 cases). The Rust binary was not built on this machine. CI must cover them. ## Risks - One extra checkpoint round trip before `turn.start` on a recovered session and on a restart continuation. These are recovery paths; a new session's first turn gets no added wait, so boot and time-to-first-token for new runs are unchanged. - If the checkpoint fails (the generation lost the run), the turn is not submitted. That is the intended behaviour; the owning generation continues the run. - No migration. No schema change. No pack contract change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent 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 - [ ] I have updated relevant documentation to reflect my changes (no documented behavior or command 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 --- .../src/native-session-runtime.test.ts | 99 +++++++++++++++++++ .../src/native-session-runtime.ts | 7 ++ 2 files changed, 106 insertions(+) diff --git a/packages/paperclip-runner/src/native-session-runtime.test.ts b/packages/paperclip-runner/src/native-session-runtime.test.ts index 6811cdfd7bc..0ff940f210e 100644 --- a/packages/paperclip-runner/src/native-session-runtime.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.test.ts @@ -8896,6 +8896,105 @@ describe("executeNativeSession recovery", () => { ).toEqual(["run.result.accepted", "run.terminal"]); }); + it("proves it still owns a recovered session right before starting a turn in it", async () => { + // Staging run cd2bf273: a turn nobody can attribute appeared in the same + // provider thread across server swaps. The recovery checkpoint is fenced + // (controller boot, generation, lease), but preparing the turn's input can + // take a while and another generation may take the run over meanwhile. + // The fenced checkpoint is repeated right before the submit, so the + // replaced server submits nothing. + const checkpoint: PersistedNativeSession = { + backendKind: "mock", sessionId: "driver-recovery", identity, providerSessionId: "provider-recovery", cursor: "1", + activeTurnId: null, terminalTurns: [], pendingRuntimeRequests: [], lineage: [], + }; + const startTurn = vi.fn(async () => ({ turnId: "late-turn" })); + const session: NativeSession = { + identity: () => identity, + async capabilities() { return { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }; }, + events: () => (async function* () {})(), + startTurn, + async result() { return null; }, + async snapshot() { return structuredClone(checkpoint); }, + async close() {}, + }; + const backend: NativeSessionBackend = { + async descriptor() { + return { kind: "mock", name: "recovery-backend", version: "1", + capabilities: { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true } }; + }, + async openSession() { throw new Error("must recover the provider session"); }, + async recoverSession() { return { recovered: true, session }; }, + }; + let takenOver = false; + const checkpointSession = vi.fn(async () => { if (takenOver) throw new Error("native_runner_checkpoint_owner_lost"); }); + const port: ControlPlanePort = { + async openRun() {}, + async loadSessionCheckpoint() { return structuredClone(checkpoint); }, + checkpointSession, + async appendEvent() { return { cursor: 1, highestContiguousSourceSeq: 0, disposition: "committed" }; }, + async replayEvents() { return { events: [], highestContiguousSourceSeq: 0 }; }, + completeRun: vi.fn(async () => undefined), + }; + await executeNativeSession({ input, backend, controlPlane: port, runnerInstanceId: "runner-recovery", + controlPlaneInstanceId: "control-recovery", + // Another server generation claims the run while this one prepares the turn. + prepareWakeAttachmentPrompt: async () => { takenOver = true; return ""; } }).catch(() => undefined); + expect(takenOver).toBe(true); + expect(startTurn).not.toHaveBeenCalled(); + }); + + it.each([ + { label: "at startup", interruptedAtStartup: true }, + { label: "when the lost turn's terminal arrives", interruptedAtStartup: false }, + ])("proves it still owns a recovered session right before a restart continuation $label", async ({ interruptedAtStartup }) => { + // Same takeover window as the startup turn, on the restart-continuation + // path: steered messages and attachments are prepared before the submit. + const failure = { code: "provider_turn_lost_on_restore", recoverable: true }; + const checkpoint: PersistedNativeSession = { + backendKind: "runner", driverKind: "acpx_runtime", sessionId: "record-recovery", identity, + providerSessionId: "provider-recovery", cursor: "0", activeTurnId: "turn-recovery", + terminalTurns: [], semanticResult: null, pendingRuntimeRequests: [], lineage: [], + }; + const interrupted: PersistedNativeSession = { + ...checkpoint, activeTurnId: null, + terminalTurns: [{ turnId: "turn-recovery", fingerprint: JSON.stringify({ terminalState: "failed", error: failure, result: null }) }], + }; + const startTurn = vi.fn(async () => ({ turnId: "turn-continuation" })); + const session: NativeSession = { + identity: () => identity, + async capabilities() { return { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }; }, + async *events() { + if (!interruptedAtStartup) yield runnerEvent(1, "turn.failed", { status: "failed", error: failure }); + }, + startTurn, + async result() { return null; }, + async snapshot() { return structuredClone(interrupted); }, + async close() {}, + }; + const backend: NativeSessionBackend = { + async descriptor() { return { kind: "runner", name: "restart", version: "1", capabilities: await session.capabilities() }; }, + async openSession() { throw new Error("must preserve the provider session"); }, + async recoverSession() { return { recovered: true, session }; }, + }; + let takenOver = false; + const port: ControlPlanePort = { + async openRun() {}, + async checkpointSession() { if (takenOver) throw new Error("native_runner_checkpoint_owner_lost"); }, + async appendEvent(event: PrpEvent) { return { cursor: event.sourceSeq, highestContiguousSourceSeq: event.sourceSeq, disposition: "committed" }; }, + async replayEvents() { return { events: [], highestContiguousSourceSeq: 0 }; }, + async completeRun() {}, + }; + const prepareWakeAttachmentPrompt = vi.fn(async () => { takenOver = true; return ""; }); + await executeNativeSession({ + input, backend, controlPlane: port, persistedSession: interruptedAtStartup ? interrupted : checkpoint, + runnerInstanceId: "runner-recovery", controlPlaneInstanceId: "control-recovery", resumeInterruptedTurn: true, + // Another server generation claims the run while this one prepares the continuation. + prepareWakeAttachmentPrompt, + }).catch(() => undefined); + expect(prepareWakeAttachmentPrompt).toHaveBeenCalledOnce(); + expect(startTurn).not.toHaveBeenCalled(); + }); + it("resolves a checkpointed result-less disposition without resubmitting when its terminal event is missing", async () => { const workProposal: PrpEvent = { ...runnerEvent(1, "run.result.proposed", result), diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.ts index f3bded13bf3..3496497b61d 100644 --- a/packages/paperclip-runner/src/native-session-runtime.ts +++ b/packages/paperclip-runner/src/native-session-runtime.ts @@ -2867,6 +2867,9 @@ export async function executeNativeSession( signal?.throwIfAborted(); const attachmentPrompt = await options.prepareWakeAttachmentPrompt?.(); signal?.throwIfAborted(); + // The fenced checkpoint proves this controller still owns the run + // right before the submit; input preparation above may have taken a while. + await checkpoint(signal); const started = await session.startTurn(restartContinuation(steeredMessages, attachmentPrompt)); restartContinuationTurnId = started.turnId; if (started.borrowedDispositionMarker === true) borrowedContinuationTurnId = started.turnId; @@ -3208,6 +3211,10 @@ export async function executeNativeSession( modelEnvelope.events = `${modelEnvelope.events}\n\n${supplemental}`; } } + // A recovered session is shared provider state: prove ownership with + // the fenced checkpoint right before the submit. A new session's + // normal path adds nothing before turn.start. + if (recovered) await checkpoint(); await session.startTurn({ message: { role: "user", text: JSON.stringify(modelEnvelope) }, ...(recovered && modelEnvelope.schema === "paperclip.native-continuation.v1" From 6cb0dd0c6bc911f4cf98d1e39c5a78c0de29bdfd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:10:47 -0600 Subject: [PATCH 03/15] fix(recovery): continue twice-interrupted tasks and waiting follow-ups after a release swap (#21250) 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 run is cut off by a restart or a release swap, the fresh-continuation fallback continues the task in a new run. > - The continuation goes through normal admission, or through a person's saved follow-up when one is waiting. > - In release-swap waves, three gaps left tasks stopped with no run: admission refused an isolated continuation of a task with no project, a person's saved follow-up behind the replaced run was never promoted, and the fallback relied on a saved follow-up that the cut-off run had already read. > - This pull request closes those three gaps. > - The benefit is that a twice-interrupted task, and a task with a waiting follow-up, continue by themselves. ## Linked Issues or Issue Description Refs #21135, #21222 **What happened?** 1. A task with no project was interrupted twice. The second continuation used a fresh isolated workspace, which clears the task's workspace binding. The admission preflight still required that binding for an isolated task with no project, so it refused the continuation as `workspace_worktree_requires_project` about every 15 s. Each refusal re-blocked the task and added a comment (329 to 428 skipped wakes per wave). The runtime itself supports this case: it prepares a new workspace (`create_new`). 2. The fallback continued a task with delivery `saved_input` (a person's deferred follow-up is the next turn). The stranded-queue pass refused to promote that follow-up, because the replaced native run's finalization was `terminal_failure` (restart recovery ended it), not `committed`. The release path would also have re-blocked the task with a reconciliation incident. The follow-up never ran. 3. The fallback chose `saved_input` because a deferred user wake existed, but the cut-off run had already taken that message into its turn. Promotion settled the message as delivered, and no run followed. The task showed "working". **Expected behavior** An interrupted task continues by itself in each case, with no person action and no repeated comments. **Steps to reproduce** 1. Run a release-swap wave with projectless tasks in isolated mode and person follow-ups during runs. 2. Interrupt the same task twice, or interrupt a run that has a deferred follow-up behind it. 3. See the task stay blocked or "working" with no run. ## What Changed - Admission (`server/src/services/execution-workspace-policy.ts`, `server/src/services/heartbeat/queue.ts`, `server/src/services/fresh-continuation-fallback.ts`): `isUnrunnableWorktreeCombo` accepts `freshIsolatedContinuation`. The admission preflight sets it from the new `isFreshIsolatedContinuationWake`, which returns at once (no query) unless the wake context carries `freshContinuationIsolation`. This does not touch the dispatch ranking. - Follow-up promotion (`server/src/modules/wake-queue/adapters/postgres.ts`): the stranded-queue pass and the release path skip the native finalization gate and the reconciliation incident for a run that the fallback superseded (`agentRunSupersededByFreshContinuation`). - Saved-input choice (`server/src/services/fresh-continuation-fallback.ts`): a deferred user wake counts as saved input only when it has no comment ids, or still has a message that the agent has not received (`undeliveredLegacyUserCommentIds`, called, not changed). Otherwise the fallback records its own continuation. - Review round 1: (a) whenever the old writer is not proven stopped (`fresh_isolated_workspace`), the fallback records its own isolated continuation first, also when the task had a binding; saved input follows it on the new workspace. (b) Release skips the manual-admission hold and the pending-cleanup check for a run the fallback replaced with an isolated continuation (`fresh_isolated_workspace` or `remote_epoch`, via `freshContinuationIsolatesRun`); other replacements still wait. - Review round 2 (the isolated continuation must run before the waiting follow-up): while the fallback's `fresh_isolated_workspace` continuation is still pending delivery, release leaves the person's follow-up deferred. Otherwise the follow-up would become the task's next run without the isolation marker, and delivery would count it as the continuation and skip the isolated run. The continuation's own release promotes the follow-up behind it. `freshContinuationIsolatesRun` now also reports `continuationPending`. ## Verification Red-to-green tests (each failed before its fix and passes after it): - `server/src/__tests__/execution-workspace-policy.test.ts`: admission keeps a fresh isolated continuation of a projectless task runnable. - `server/src/modules/wake-queue/adapters/postgres.test.ts` "restart-ended native run": saved input behind a run the fallback replaced is promoted. - `server/src/services/fresh-continuation-fallback.test.ts` "relies on saved input only while it still holds an undelivered message" (taken: true gives `recorded`, taken: false gives `saved_input`). - `postgres.test.ts` "promotes saved input behind an exhausted restart hold ... (released, continuation pending)": the follow-up stays deferred while the isolated continuation is pending, then is promoted when the continuation's run is released. It was red before the fix (`expected 'promoted' to be 'released'`). - Local, round 2: `cd server && npx vitest run src/modules/wake-queue/adapters/postgres.test.ts src/services/fresh-continuation-fallback.test.ts`: 2 files, 177 tests passed. Local command, on this branch based on current master (includes #21222 and #21234): - `cd server && npx vitest run src/services/fresh-continuation-fallback.test.ts src/__tests__/execution-workspace-policy.test.ts src/modules/wake-queue/adapters/postgres.test.ts`: 3 files, 221 tests passed (re-run after rebasing on #21234). Local release-swap cells: - L1 (6 tasks, 3 swaps): 5 fresh isolated continuations delivered, including a second one on the same task; 0 `workspace_worktree_requires_project` rows (before: 329 to 428 skipped wakes per wave). - R2 (6 tasks, 3 swaps): a task interrupted three times had its second and third continuations delivered. The same cell found gap 3 (a follow-up already read by the cut-off run), which the last commit fixes. - Hour-long release-swap wave (w-20261112T233630-s7201) on the branch that holds these fixes and the related recovery fixes: 11/11 tasks finished hands-off (master: 9/11). The lost-continuation and follow-up-promotion fixes were visibly working in it. Review-round tests: "moves the task off the old writer's workspace and runs the isolated continuation before saved input" (changed expectation: `recorded` instead of `saved_input`; red on the previous head); "promotes saved input behind an exhausted restart hold once a %s continuation replaced the run" (isolated: promoted, red before; `writer_ended`: held). 3 files, 224 tests passed. Conflict note: the last commit was resolved onto current master. It no longer imports `taskHistoryReadsForRun`, which belongs to a separate opening-note change. ## Risks - An isolated projectless continuation now passes admission. It runs in a new workspace that the run prepares, so it never shares a workspace with the cut-off run. - A superseded run's follow-up is promoted without its native finalization committed. The superseded run is fenced (its writes are refused), so there is still one writer. - No migration. No schema change. The normal admission path adds no query. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent 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 - [ ] I have updated relevant documentation to reflect my changes (no documented behavior or command 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 --- .../execution-workspace-policy.test.ts | 8 ++ .../wake-queue/adapters/postgres.test.ts | 82 ++++++++++++++++++- .../modules/wake-queue/adapters/postgres.ts | 31 ++++++- .../services/execution-workspace-policy.ts | 4 + .../fresh-continuation-fallback.test.ts | 26 +++++- .../services/fresh-continuation-fallback.ts | 61 ++++++++++++-- server/src/services/heartbeat/queue.ts | 4 +- 7 files changed, 200 insertions(+), 16 deletions(-) diff --git a/server/src/__tests__/execution-workspace-policy.test.ts b/server/src/__tests__/execution-workspace-policy.test.ts index e44ea327f3a..6253cba8841 100644 --- a/server/src/__tests__/execution-workspace-policy.test.ts +++ b/server/src/__tests__/execution-workspace-policy.test.ts @@ -154,6 +154,14 @@ describe("execution workspace policy helpers", () => { ).toEqual({ type: "git_worktree", existingBranch: "PAP-14754-run-redaction" }); }); + it("admits a fresh isolated continuation of a projectless task whose binding the fallback cleared", () => { + const issue = { projectId: null, projectWorkspaceId: null, executionWorkspaceId: null, + executionWorkspacePreference: "reuse_existing" }; + expect(isUnrunnableWorktreeCombo({ issue, resolvedMode: "isolated_workspace", resolvedStrategy: "git_worktree" })).toBe(true); + expect(isUnrunnableWorktreeCombo({ issue, resolvedMode: "isolated_workspace", resolvedStrategy: "git_worktree", + freshIsolatedContinuation: true })).toBe(false); + }); + it("centralizes unrunnable isolated worktree detection", () => { expect( isUnrunnableWorktreeCombo({ diff --git a/server/src/modules/wake-queue/adapters/postgres.test.ts b/server/src/modules/wake-queue/adapters/postgres.test.ts index 01a6c659415..aac74f1f3bc 100644 --- a/server/src/modules/wake-queue/adapters/postgres.test.ts +++ b/server/src/modules/wake-queue/adapters/postgres.test.ts @@ -2,9 +2,10 @@ import { resolveExternalTestDatabaseUrl } from "../../../__tests__/helpers/exter import { DELIVERY_QUEUES } from "../../../services/delivery-work-notifications.js"; import { instanceSettingsService } from "../../../services/instance-settings.js"; import { randomBytes, randomUUID } from "node:crypto"; -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; +import { createSystemRecovery } from "../../../services/system-recovery-state.js"; import { activityLog, agentWakeupRequests, @@ -474,6 +475,85 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { expect((await release({ companyId, runId, now: new Date(), suppressImmediateRecovery: true, resumeStrandedQueue: true })).outcome.kind).toBe("promoted"); }); + it.each([true, false])("promotes saved input behind a restart-ended native run only once the fresh continuation replaced it (replaced: %s)", async replaced => { + const companyId = await seedCompany(), agentId = await seedAgent({ companyId }); + const issueId = await seedIssue({ companyId, status: "in_progress", assigneeAgentId: agentId }); + const runId = await seedRun({ companyId, agentId, status: "failed", contextSnapshot: { issueId } }); + await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId, finishedAt: new Date(), + errorCode: "native_restart_recovery_blocked", + resultJson: replaced ? { freshContinuationSupersededAt: new Date().toISOString() } : {}, + }).where(eq(heartbeatRuns.id, runId)); + // Restart recovery ended the run: its finalization stays terminal_failure, never committed. + await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId, phase: "terminal_failure", + recoveryState: "blocked", failureCode: "native_restart_recovery_blocked" }); + const [comment] = await db.insert(issueComments).values({ companyId, issueId, authorType: "user", authorUserId: "responsible-user", body: "Follow-up during the run" }).returning(); + const wakeId = await seedDeferredWake({ companyId, agentId, issueId, requestedByActorId: "responsible-user", + payload: { _paperclipWakeContext: { issueId, wakeReason: "issue_commented", wakeCommentIds: [comment.id] } }, + }); + const release = createReleaseIssueExecution({ issueLock: createPostgresWakeQueueAdapter(db, stubDeps), + recovery: { escalateStrandedAssignedIssue: async () => undefined, escalateStrandedRecoveryIssueInPlace: async () => undefined }, + }); + const result = await release({ companyId, runId, now: new Date(), suppressImmediateRecovery: true, resumeStrandedQueue: true }); + if (replaced) { + expect(result.outcome.kind).toBe("promoted"); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)))[0].status).not.toBe("deferred_issue_execution"); + // No reconciliation incident re-blocks the task the fallback released. + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).not.toBe("blocked"); + } else { + expect(result.outcome.kind).toBe("released"); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)))[0].status).toBe("deferred_issue_execution"); + } + }); + + it.each([ + ["fresh_isolated_workspace", "promoted", "not_requested"], ["remote_epoch", "promoted", "not_requested"], + ["writer_ended", "released", "not_requested"], + // The isolated continuation is still to be delivered: it runs first and binds the new workspace; + // promoting the follow-up now would make it the task's next run, without the isolation. + ["fresh_isolated_workspace", "released", "pending"], + ] as const)("promotes saved input behind an exhausted restart hold once a %s continuation replaced the run (%s, continuation %s)", async (isolation, expected, continuationDelivery) => { + // Restart recovery exhausted its retries (systemRecovery.state exhausted, no stop receipt), then the + // fallback replaced the run. An isolated continuation reuses none of the old executor's workspace, + // so the manual-admission hold no longer stands between the task and the person's follow-up. + const companyId = await seedCompany(), agentId = await seedAgent({ companyId }); + const issueId = await seedIssue({ companyId, status: "in_progress", assigneeAgentId: agentId }); + const runId = await seedRun({ companyId, agentId, status: "failed", contextSnapshot: { issueId } }); + await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId, finishedAt: new Date(), + errorCode: "native_restart_recovery_blocked", resultJson: { freshContinuationSupersededAt: new Date().toISOString() }, + }).where(eq(heartbeatRuns.id, runId)); + await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId, phase: "terminal_failure", + recoveryState: "blocked", failureCode: "native_restart_recovery_blocked", + failureDetail: { systemRecovery: { ...createSystemRecovery(runId), state: "exhausted" }, replacementDenied: "fresh_continuation" } }); + await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", + status: "resolved", outcome: "restored", ownerType: "system", returnOwnerAgentId: agentId, + cause: "fresh_continuation", fingerprint: `fresh-continuation:${runId}`, nextAction: "Continuing.", resolvedAt: new Date(), + evidence: { runId, freshContinuation: { sourceRunId: runId, isolation, + delivery: continuationDelivery === "pending" ? "recorded" : "saved_input" }, continuationDelivery } }); + const [comment] = await db.insert(issueComments).values({ companyId, issueId, authorType: "user", authorUserId: "responsible-user", body: "Follow-up during the run" }).returning(); + const wakeId = await seedDeferredWake({ companyId, agentId, issueId, requestedByActorId: "responsible-user", + payload: { _paperclipWakeContext: { issueId, wakeReason: "issue_commented", wakeCommentIds: [comment.id] } }, + }); + const release = createReleaseIssueExecution({ issueLock: createPostgresWakeQueueAdapter(db, stubDeps), + recovery: { escalateStrandedAssignedIssue: async () => undefined, escalateStrandedRecoveryIssueInPlace: async () => undefined }, + }); + const result = await release({ companyId, runId, now: new Date(), suppressImmediateRecovery: true, resumeStrandedQueue: true }); + expect(result.outcome.kind).toBe(expected); + const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)); + if (expected === "promoted") expect(wake.status).not.toBe("deferred_issue_execution"); + else expect(wake.status).toBe("deferred_issue_execution"); + if (continuationDelivery !== "pending") return; + // The isolated continuation is delivered and runs; its release promotes the follow-up behind it. + const continuationRunId = await seedRun({ companyId, agentId, status: "succeeded", contextSnapshot: { issueId } }); + await db.update(heartbeatRuns).set({ finishedAt: new Date() }).where(eq(heartbeatRuns.id, continuationRunId)); + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} + || ${JSON.stringify({ continuationDelivery: "delivered", continuationRunId })}::jsonb` }) + .where(eq(issueRecoveryActions.sourceIssueId, issueId)); + expect((await release({ companyId, runId: continuationRunId, now: new Date(), suppressImmediateRecovery: true })).outcome.kind) + .toBe("promoted"); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)))[0].status) + .not.toBe("deferred_issue_execution"); + }); + it.each([ "completed", "multiple_comments", "repeated_reference", "parent_reference", "mixed_issue_references", "mixed_foreign_references", "mixed_unknown_references", "no_comments", "missing_comment", "human_comment", "other_run_comment", "foreign_comment", "other_issue_comment", "deleted_comment", diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 95341f6bf18..ff582a93cc6 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -18,6 +18,8 @@ import { nativeManualAdmissionHoldsExecution } from "../../../services/native-ru 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 { agentRunSupersededByFreshContinuation } from "../../../agent-run-cancellation.js"; +import { freshContinuationIsolatesRun } from "../../../services/fresh-continuation-fallback.js"; import type { Db } from "@paperclipai/db"; import { deliveredQueuedCommentIds, EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, EXTERNAL_CHAT_MESSAGE_WAKE_REASON } from "../../../services/queued-comment-delivery.js"; import { extractIssueReferenceIdentifiers, isUuidLike } from "@paperclipai/shared"; @@ -1284,7 +1286,10 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd `, ); - if (input.resumeStrandedQueue && run.runtimeMode === "native") { + // A run the fresh-continuation fallback replaced is settled for good: its + // finalization may stay terminal_failure (restart recovery ended it), and + // the saved input queued behind it is now the task's next turn. + if (input.resumeStrandedQueue && run.runtimeMode === "native" && !agentRunSupersededByFreshContinuation(run)) { const [finalized] = contextIssueId && run.nativeIssueId === contextIssueId ? await tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations).where(and( eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, run.id), @@ -1293,10 +1298,16 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd : []; if (!finalized) return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; } - if (await nativeManualAdmissionHoldsExecution(tx, { companyId: input.companyId, runId: run.id })) { + // These two holds protect the old executor's workspace and resources. A + // continuation in a new isolated workspace (or an abandoned remote epoch) + // reuses none of them, so they no longer hold the task's next turn; any + // other replacement still waits for them. + const isolatedReplacement = agentRunSupersededByFreshContinuation(run) + ? await freshContinuationIsolatesRun(tx, { companyId: input.companyId, runId: run.id }) : false; + if (!isolatedReplacement && await nativeManualAdmissionHoldsExecution(tx, { companyId: input.companyId, runId: run.id })) { return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; } - if (input.resumeStrandedQueue && await hasPendingRunCleanup(tx, input.companyId, run.id)) { + if (input.resumeStrandedQueue && !isolatedReplacement && await hasPendingRunCleanup(tx, input.companyId, run.id)) { return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; } @@ -1448,13 +1459,25 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd && issueRow.status === "blocked" && issueRow.assigneeAgentId === run.agentId) { return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; } - if (!handoffAssigneeAgentId && await recordNativeTerminalRecoveryIfNeeded(tx, run, issueRow, input.now)) { + // The fallback already decided this run's continuation; a reconciliation + // incident would re-block the task it just released. + if (!handoffAssigneeAgentId && !agentRunSupersededByFreshContinuation(run) + && await recordNativeTerminalRecoveryIfNeeded(tx, run, issueRow, input.now)) { return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; } // A release must leave deferred messages intact while execution is held. // The finishing conversation may still own its lease until finally cleanup. // Allow only bounded retry planning in that case; admission stays gated. + // The fallback's isolated continuation runs before any saved input: it + // alone carries the marker that prepares the new workspace and binds it. + // Promoting the follow-up now would make it the task's next run without + // that isolation (and the delivery worker would then skip the + // continuation). The follow-up stays deferred and is promoted behind + // the continuation when that run is released. + if (isolatedReplacement && isolatedReplacement.continuationPending) { + return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot }; + } const executionBlocker = await getExecutionBlocker(tx, issueRow.companyId, issueRow.id); const recoveryOnly = Boolean(executionBlocker && executionBlocker.cause === "execution_owner_active" && executionBlocker.runId === run.id && diff --git a/server/src/services/execution-workspace-policy.ts b/server/src/services/execution-workspace-policy.ts index 4a7f9c9fa33..1b27f8fcc04 100644 --- a/server/src/services/execution-workspace-policy.ts +++ b/server/src/services/execution-workspace-policy.ts @@ -94,7 +94,11 @@ export function isUnrunnableWorktreeCombo(input: { resolvedStrategy: string | null | undefined; reusableExecutionWorkspaceAvailable?: boolean | null; hasResolvablePriorSessionWorkspace?: boolean | null; + /** The wake continues a cut-off run in a new isolated workspace that the run + * prepares itself (`create_new`); it never needs the task's old binding. */ + freshIsolatedContinuation?: boolean | null; }): boolean { + if (input.freshIsolatedContinuation === true) return false; if (input.resolvedMode !== "isolated_workspace" && input.resolvedMode !== "operator_branch") return false; if (input.resolvedStrategy !== "git_worktree") return false; if (input.issue.projectId || input.issue.projectWorkspaceId) return false; diff --git a/server/src/services/fresh-continuation-fallback.test.ts b/server/src/services/fresh-continuation-fallback.test.ts index 1cc5121b76c..8aeb661c102 100644 --- a/server/src/services/fresh-continuation-fallback.test.ts +++ b/server/src/services/fresh-continuation-fallback.test.ts @@ -3,7 +3,7 @@ import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { activityLog, agentWakeupRequests, agents, approvals, authUsers, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, - issues, nativeRunFinalizations, toolInvocations, + issueComments, issues, nativeRunFinalizations, toolInvocations, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { deliverReconciledExecutions, settleUnrecoverableExecutions } from "./execution-recovery-resolution.js"; @@ -803,6 +803,22 @@ suite("fresh-continuation fallback", () => { expect(decision.outcomeEvidence).not.toMatch(adminText); }, 60_000); + it.each([true, false])("relies on saved input only while it still holds an undelivered message (already taken by the cut-off run: %s)", async taken => { + // R2 cell t003: the cut-off run had taken the follow-up into its turn; the fallback chose saved_input, + // promotion settled the message as delivered, and no run followed. + const f = await unfinishedRun({ runtime: "native", errorCode: "native_restart_recovery_blocked" }); + const [comment] = await db.insert(issueComments).values({ companyId, issueId: f.issueId, authorType: "user", + authorUserId: userId, body: "Additional requirement: include FOLLOWUP-1" } as typeof issueComments.$inferInsert).returning(); + if (taken) await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeCommentIds: [comment!.id] } }) + .where(eq(heartbeatRuns.id, f.runId)); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", triggerDetail: "system", + reason: "issue_execution_deferred", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: userId, + payload: { issueId: f.issueId, _paperclipWakeContext: { issueId: f.issueId, wakeReason: "issue_commented", wakeCommentIds: [comment!.id] } }, + } as typeof agentWakeupRequests.$inferInsert); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", delivery: taken ? "recorded" : "saved_input" }); + }, 60_000); + it.each([ { title: "a pending approval", setup: "approval" as const, errorCode: "native_continuation_requires_reconciliation" }, { title: "a credential the person has not shared", setup: "none" as const, errorCode: "configuration_incomplete" }, @@ -881,18 +897,20 @@ suite("fresh-continuation fallback", () => { }, 60_000); // The isolation decision is a property of the task's next run, whatever path starts it. - it("moves the task off the old writer's workspace for every next run, saved input included", async () => { + it("moves the task off the old writer's workspace and runs the isolated continuation before saved input", async () => { const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost", error: "Legacy controller lease lost" }); const [workspace] = await db.insert(executionWorkspaces).values({ companyId, sourceIssueId: f.issueId, mode: "isolated", strategyType: "git_worktree", name: "Task workspace", cwd: "/tmp/old-writer" }).returning(); await db.update(issues).set({ executionWorkspaceId: workspace!.id, workspaceBindingRevision: 2 }).where(eq(issues.id, f.issueId)); await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000), contextSnapshot: { issueId: f.issueId, executionWorkspaceId: workspace!.id } }).where(eq(heartbeatRuns.id, f.runId)); - // A person's saved message is waiting: it continues the task itself. + // A person's saved message is waiting. It carries no isolation marker, so it cannot prepare the + // new workspace (a projectless task would be refused at admission once the binding is cleared): + // the isolated continuation runs first and the saved message follows it. await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: f.issueId } }); expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) - .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace", delivery: "saved_input" }); + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace", delivery: "recorded" }); // No delivery path can reach the old directory: the task is no longer bound to it. expect(await issue(f.issueId)).toMatchObject({ executionWorkspaceId: null, workspaceBindingRevision: 3 }); const [kept] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace!.id)); diff --git a/server/src/services/fresh-continuation-fallback.ts b/server/src/services/fresh-continuation-fallback.ts index e5e5ab91c6c..adc6eb81df5 100644 --- a/server/src/services/fresh-continuation-fallback.ts +++ b/server/src/services/fresh-continuation-fallback.ts @@ -8,6 +8,8 @@ import { } from "@paperclipai/shared"; import { logger } from "../middleware/logger.js"; import { logActivity } from "./activity-log.js"; +import { undeliveredLegacyUserCommentIds } from "./explicit-native-continuation.js"; +import { queuedCommentIdsFromWakePayload } from "./issue-queued-comment-queue.js"; import { FRESH_CONTINUATION_SUPERSEDED_KEY } from "../agent-run-cancellation.js"; import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "./acknowledged-native-stop.js"; import { adapterExecutionControls } from "./adapter-execution-control.js"; @@ -305,6 +307,40 @@ export async function readFreshContinuationReadiness(db: Db, run: Pick | null | undefined }) { + if (typeof object(input.contextSnapshot).freshContinuationIsolation !== "string") return false; + return (await readFreshContinuationReadiness(db, { id: "", companyId: input.companyId, + contextSnapshot: input.contextSnapshot ?? {} }, input.issueId)) !== null; +} + +/** + * True when the fallback replaced this run and its continuation reuses none of + * the run's workspace: a new isolated workspace or an abandoned remote epoch. + * Holds that only protect the old executor's resources then no longer stand + * between the task and its next turn. + */ +export async function freshContinuationIsolatesRun(db: Db, input: { companyId: string; runId: string }): Promise { + const [record] = await db.select({ isolation: sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,isolation}'`, + delivery: sql`${issueRecoveryActions.evidence}->>'continuationDelivery'` }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, input.companyId), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,sourceRunId}' = ${input.runId}`, + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,isolation}' in ('fresh_isolated_workspace', 'remote_epoch')`)).limit(1); + if (!record) return false; + // Only the recorded continuation carries the isolation marker that prepares + // the new workspace, so while it is pending it must be the task's next run. + return { continuationPending: record.isolation === "fresh_isolated_workspace" && record.delivery === "pending" }; +} + export async function ensureFreshContinuation(db: Db, input: Input): Promise { return db.transaction(tx => continueFreshInTransaction(tx as unknown as Db, input)); } @@ -474,9 +510,20 @@ export async function continueFreshInTransaction(tx: Db, input: Input): Promise< // Saved user input (a message or a Retry the person pressed) continues the // task through normal admission once nothing blocks it; a second, automatic // continuation would run after it. - const [savedInput] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + const savedWakes = await tx.select({ id: agentWakeupRequests.id, payload: agentWakeupRequests.payload }).from(agentWakeupRequests).where(and( eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.status, "deferred_issue_execution"), - eq(agentWakeupRequests.requestedByActorType, "user"), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`)).limit(1); + eq(agentWakeupRequests.requestedByActorType, "user"), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`)).limit(5); + // Saved input continues the task only while it still holds something the + // agent has not received: a message the cut-off run already took into its + // turn is settled as delivered when promoted, and then nothing would run. + let savedInput: { id: string } | undefined; + for (const wake of savedWakes) { + const commentIds = queuedCommentIdsFromWakePayload(wake.payload); + if (!commentIds.length || (await undeliveredLegacyUserCommentIds(tx, companyId, issue.id, run.agentId, commentIds)).length) { + savedInput = wake; + break; + } + } let delivery: "recorded" | "caller_owns" | "saved_input" = input.delivery === "caller_owns" ? "caller_owns" : savedInput ? "saved_input" : "recorded"; @@ -492,10 +539,12 @@ export async function continueFreshInTransaction(tx: Db, input: Input): Promise< // Never claim a stop that was not proven: record what isolates the successor. const isolation: FreshContinuationIsolation = fenced || remoteSource ? "remote_epoch" : writer === "ended" && !waitBounded ? "writer_ended" : "fresh_isolated_workspace"; - // With no task workspace binding to move, only a run that carries the - // isolation in its context can avoid the shared directory: the recorded - // continuation runs first, and saved input follows it. - if (isolation === "fresh_isolated_workspace" && !issue.executionWorkspaceId && delivery === "saved_input") delivery = "recorded"; + // Only a run that carries the isolation in its context prepares the new + // workspace (create_new). Saved input carries no such marker: on a task with + // no project it would be refused at admission once the binding is cleared, + // and otherwise could resolve the old directory. So the recorded + // continuation runs first, binds the new workspace, and saved input follows. + if (isolation === "fresh_isolated_workspace" && delivery === "saved_input") delivery = "recorded"; const unverified = await unverifiedActions(tx, run); const note = freshContinuationNote({ runId: run.id, unverified, workspace: isolation === "writer_ended" ? "kept" : "restored_last_save" }); diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index f4d53e04744..fa0ff7b8b59 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -3,7 +3,7 @@ import { connectionIntentService } from "../connection-intents.js"; import { verifyBlockerStallWake } from "../recovery/blocker-stall-wakeups.js"; import { CONTEXT_COMPACTION_WAKE_REASON, ContextCompactionError, isContextCompactionRun, readContextCompactionRequest } from "../context-compaction.js"; import { isProcessRunAdmissionClosed } from "./run-admission.js"; -import { continueFreshInTransaction, hasPendingFreshContinuation, settleCoalescedFreshContinuationHolds } from "../fresh-continuation-fallback.js"; +import { continueFreshInTransaction, hasPendingFreshContinuation, isFreshIsolatedContinuationWake, settleCoalescedFreshContinuationHolds } from "../fresh-continuation-fallback.js"; import { refreshRunStartYieldIfStale } from "../run-start-handover.js"; import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js"; import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, recheckQueuedRunInteractions, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js"; @@ -4278,6 +4278,8 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende reusableExecutionWorkspaceAvailable: reuseRequest.existingExecutionWorkspaceAvailable, hasResolvablePriorSessionWorkspace, + freshIsolatedContinuation: await isFreshIsolatedContinuationWake(tx as unknown as Db, { + companyId: issue.companyId, issueId: issue.id, contextSnapshot: enrichedContextSnapshot }), }) ) { if (caseRequest) waitForCaseAdmission(WORKSPACE_WORKTREE_REQUIRES_PROJECT_CODE, WORKSPACE_WORKTREE_REQUIRES_PROJECT_MESSAGE); From d169dd5a90f9360c8057af4a47ad26a5b14e761c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:14:41 -0600 Subject: [PATCH 04/15] fix(presentation): offer Retry only when no automatic continuation or scheduled retry is pending (#21264, includes #21200) 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 run fails with a transient error, Paperclip schedules the next attempt by itself and shows "retrying automatically" with a countdown. > - The task presentation also offered the Retry button next to that countdown. > - The system owns the next attempt while the run is `scheduled_retry`, so the button is misleading: it suggests that a person must act. > - This pull request stops offering Retry while a scheduled retry is pending. Retry returns when the scheduled retry is past due with nothing pending, or when the retries are exhausted. > - The benefit is one clear message: Paperclip retries by itself, and Retry appears only when it is the way forward. ## Linked Issues or Issue Description **What happened?** A legacy run in status `scheduled_retry` (for example reason `transient_failure`, which is not a shared-resource wait and has no system recovery) projected `state: "retry_scheduled"` with `canRetry: true`. The UI then showed the Retry button beside "retrying automatically". The cause is in `projectTaskInterruptionState` in `server/src/services/task-interruption-presentation.ts`: the `retryAt > now` branch set `canRetry: !preparationPending && !nativeResumeAt`, which ignores that the run itself is the scheduled attempt. **Expected behavior** While a run is `scheduled_retry` and its retry time is in the future, the task shows the countdown and offers no Retry. When the scheduled retry is past due with nothing pending, or the retries are exhausted, Retry is offered. **Steps to reproduce** 1. Let a task's run fail with a transient failure that schedules an automatic retry. 2. Open the task before the retry time. 3. The task shows "retrying automatically" and the Retry button. **What a Retry click does today in this state** `requestTaskRetry` (`server/src/services/task-retry.ts`) treats a latest run in `scheduled_retry` as busy. It accepts the click (202), records the request as `coalesced` onto the scheduled run and returns `scheduledRetryRunId`. It does not start a second attempt next to the scheduled one. The button is therefore misleading but not unsafe, and this pull request changes only what the task shows. ## What Changed - `server/src/services/task-interruption-presentation.ts`: in the `retry_scheduled` branch, `canRetry` is now also false when `run.status === "scheduled_retry"`. - `server/src/services/task-interruption-presentation.test.ts`: three tests for a scheduled transient-failure retry. - This branch is based on current `master` and includes #21200, which has not merged yet and changes the same file. The diff of this pull request against #21200 is one line and the tests. ## Verification - `cd server && npx vitest run src/services/task-interruption-presentation.test.ts -t "automatic scheduled retry"` - "shows a pending transient-failure retry as scheduled without a competing Retry": red on `master` (`canRetry: true`), green with this change. - "offers Retry once the scheduled retry is past due with nothing else pending": green before and after. - "offers Retry once the scheduled retries are exhausted": green before and after. - Locally: `task-interruption-presentation.test.ts`, `task-interruption-query.test.ts` and `task-interruption-automatic-path.test.ts` pass (107 tests). Server typecheck: 0 errors. The wider suites that read the presentation run in CI; they were not repeated locally because the machine was under memory pressure. ## Risks - Low risk. The change affects presentation only. The Retry route still accepts a click and coalesces it onto the scheduled run, as before. - If a scheduled retry never dispatches, the task offers Retry again once the retry time passes, as before this change. - No schema, API or UI change. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used in Claude Code with tool use (shell, file edits, test execution). Extended reasoning was available. ## 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 --- .../task-interruption-automatic-path.test.ts | 108 ++++++++++++++++++ .../task-interruption-presentation.test.ts | 22 ++++ .../task-interruption-presentation.ts | 32 +++++- 3 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 server/src/__tests__/task-interruption-automatic-path.test.ts diff --git a/server/src/__tests__/task-interruption-automatic-path.test.ts b/server/src/__tests__/task-interruption-automatic-path.test.ts new file mode 100644 index 00000000000..17443fd2171 --- /dev/null +++ b/server/src/__tests__/task-interruption-automatic-path.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, applyPendingMigrations, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db"; +import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TASK_INTERRUPTION_TEST_DATABASE_URL"); +const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +vi.mock("../sentry.js", () => ({ captureTaskInterruptionFailure: vi.fn() })); + +describe.skipIf(!support.supported)("Retry is offered only when no automatic path exists", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + if (externalDatabaseUrl) await applyPendingMigrations(externalDatabaseUrl); + database = externalDatabaseUrl ? { connectionString: externalDatabaseUrl, cleanup: async () => {} } + : await startEmbeddedPostgresTestDatabase("interruption-automatic-"); + db = createDb(database.connectionString); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function seedTask(status = "in_progress") { + const companyId = randomUUID(), agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Swap company", issuePrefix: `S${companyId.slice(0, 7)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Swap agent", adapterType: "paperclip_runner" }); + const [issue] = await db.insert(issues).values({ companyId, title: "Work across a release swap", + status, assigneeAgentId: agentId }).returning(); + return { companyId, agentId, issue: issue! }; + } + + async function seedSwapEndedRun(finishedAt: Date) { + const task = await seedTask(); + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: task.companyId, agentId: task.agentId, + nativeIssueId: task.issue.id, scopeKind: "issue", status: "failed", runtimeMode: "native", + nativePhase: "terminal_failure", errorCode: "native_restart_recovery_blocked", + error: "controller_process_space_unverified", startedAt: new Date(finishedAt.getTime() - 60_000), finishedAt }); + await db.insert(nativeRunFinalizations).values({ companyId: task.companyId, issueId: task.issue.id, runId, + phase: "terminal_failure", attempt: 1, failureCode: "native_restart_recovery_blocked", recoveryState: "blocked" }); + const [hold] = await db.insert(issueRecoveryActions).values({ companyId: task.companyId, sourceIssueId: task.issue.id, + kind: "active_run_watchdog", status: "active", ownerType: "system", returnOwnerAgentId: task.agentId, + cause: "native_restart_recovery_blocked", fingerprint: `native-restart:${runId}`, + evidence: { runId, reason: "controller_process_space_unverified", executorStopEvidence: "unverified", providerAttempt: 1 }, + nextAction: "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work.", + maxAttempts: 3, createdAt: finishedAt, updatedAt: finishedAt }).returning(); + return { ...task, runId, hold: hold! }; + } + + it("shows a run ended by a release swap as working while its system hold awaits the automatic continuation", async () => { + const { issue, runId } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ responsibility: "system", state: "working", + canRetry: false, observedRunId: runId }); + }); + + it("still offers Retry when the system hold was not taken up by the continuation worker in time", async () => { + const { issue } = await seedSwapEndedRun(new Date(Date.now() - 10 * 60_000)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("still offers Retry once the continuation worker decided it cannot continue the task", async () => { + const { issue, hold } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold.evidence, + freshContinuationCheck: { kind: "not_applicable", reason: "task_changed", checks: 1, checkedAt: Date.now(), nextCheckAt: null } } }) + .where(eq(issueRecoveryActions.id, hold.id)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("still offers Retry when a person owns the hold", async () => { + const { issue, hold, companyId } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold.evidence, ownerGoneAttestation: { companyId } } }) + .where(eq(issueRecoveryActions.id, hold.id)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("still offers Retry when recovery gave up and handed the hold to the board", async () => { + const { issue, hold } = await seedSwapEndedRun(new Date(Date.now() - 5_000)); + await db.update(issueRecoveryActions).set({ ownerType: "board" }).where(eq(issueRecoveryActions.id, hold.id)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("shows a healthy task as working while the message queued during its succeeded run is delivered", async () => { + const { companyId, agentId, issue } = await seedTask(); + const runId = randomUUID(), finishedAt = new Date(Date.now() - 3_000); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue.id, scopeKind: "issue", + status: "succeeded", runtimeMode: "native", startedAt: new Date(Date.now() - 5 * 60_000), finishedAt }); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", reason: "issue_commented", + status: "deferred_issue_execution", requestedByActorType: "user", requestedAt: new Date(Date.now() - 2 * 60_000), + payload: { issueId: issue.id } }); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "working", canRetry: false }); + expect(await taskInterruptionPresentation(db, { ...issue, status: "in_review" })).toMatchObject({ state: "working", canRetry: false }); + expect(await taskInterruptionPresentation(db, { ...issue, status: "blocked" })).toMatchObject({ state: "failed", canRetry: true }); + await db.update(heartbeatRuns).set({ finishedAt: new Date(Date.now() - 10 * 60_000) }).where(eq(heartbeatRuns.id, runId)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: true }); + }); + + it("does not offer Retry on a parent whose run succeeded and that waits for its subtasks", async () => { + const { companyId, agentId, issue } = await seedTask(); + await db.insert(issues).values({ companyId, title: "Subtask", status: "in_progress", assigneeAgentId: agentId, parentId: issue.id }); + await db.insert(heartbeatRuns).values({ companyId, agentId, nativeIssueId: issue.id, scopeKind: "issue", + status: "succeeded", runtimeMode: "native", finishedAt: new Date(Date.now() - 3_000) }); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", reason: "issue_children_completed", + status: "queued", requestedByActorType: "system", payload: { issueId: issue.id } }); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: false }); + }); +}); diff --git a/server/src/services/task-interruption-presentation.test.ts b/server/src/services/task-interruption-presentation.test.ts index a48bd6bc763..2d7378f5658 100644 --- a/server/src/services/task-interruption-presentation.test.ts +++ b/server/src/services/task-interruption-presentation.test.ts @@ -544,3 +544,25 @@ describe("native cleanup quarantine presentation", () => { paused: false, approval: false })).toMatchObject({ state: "failed", canRetry: true }); }); }); + +describe("automatic scheduled retry", () => { + const now = Date.parse("2026-11-12T23:00:00Z"); + const scheduled = { ...run, status: "scheduled_retry", runtimeMode: "legacy", errorCode: null, resultJson: null, + scheduledRetryReason: "transient_failure", scheduledRetryAt: new Date(now + 60_000) }; + + it("shows a pending transient-failure retry as scheduled without a competing Retry", () => { + expect(projectTaskInterruption(issue, { run: scheduled, agent, paused: false, approval: false }, now)) + .toMatchObject({ state: "retry_scheduled", canRetry: false, nextRetryAt: new Date(now + 60_000).toISOString() }); + }); + + it("offers Retry once the scheduled retry is past due with nothing else pending", () => { + expect(projectTaskInterruption(issue, { run: { ...scheduled, scheduledRetryAt: new Date(now - 10 * 60_000) }, agent, + paused: false, approval: false }, now)).toMatchObject({ state: "failed", canRetry: true }); + }); + + it("offers Retry once the scheduled retries are exhausted", () => { + expect(projectTaskInterruption(issue, { run: { ...scheduled, status: "failed", errorCode: "transient_failure_retry_exhausted", + scheduledRetryAt: new Date(now - 60_000) }, agent, paused: false, approval: false }, now)) + .toMatchObject({ state: "failed", canRetry: true }); + }); +}); diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index abf793cada9..19e933cd2eb 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -7,7 +7,7 @@ import { nativeSessionCleanupBlock } from "../vendor/paperclip-runner/index.js"; import { agents, agentWakeupRequests, approvals, chatActions, companies, environmentLeases, heartbeatRuns, issueApprovals, issueRecoveryActions, issues, issueTreeHoldMembers, issueTreeHolds, nativeRunFinalizations, projects, type Db } from "@paperclipai/db"; import { unionAll } from "drizzle-orm/pg-core"; -import { HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared"; +import { EXECUTION_RECONCILIATION_CAUSES, HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared"; import { captureTaskInterruptionFailure } from "../sentry.js"; import { isAiAuthenticationBlocked } from "./ai-auth-failure.js"; import { readSystemRecovery } from "./system-recovery-state.js"; @@ -39,6 +39,8 @@ const NATIVE_RESUME_DISPATCH_GRACE_MS = 2 * 60_000; // A queued-message Interrupt waits for the stopped run's cleanup before its // successor starts. Past this, a hand-off that never started offers Retry. const QUEUED_INTERRUPT_HANDOFF_GRACE_MS = 5 * 60_000; +const QUEUED_INPUT_DISPATCH_GRACE_MS = 2 * 60_000; +const AUTOMATIC_DISPOSITION_GRACE_MS = 2 * 60_000; type ProjectionIssue = Pick; type ProjectionRun = Pick now) return { ...base, state: "retry_scheduled", nextRetryAt: new Date(input.freshContinuation.nextCheckAt).toISOString(), canRetry: false }; + if (input.automaticDispositionAt !== undefined && ["failed", "timed_out", "interrupted", "cancelled"].includes(run.status) + && now - Math.max(input.automaticDispositionAt, run.finishedAt?.getTime() ?? 0) < AUTOMATIC_DISPOSITION_GRACE_MS) + return { ...base, state: "working", canRetry: false }; const deniedProject = deniedProjectId(issue, run); let projectAccess: TaskInterruptionPresentation["projectAccess"]; if (deniedProject !== undefined) { @@ -316,7 +322,7 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS : "Paperclip couldn’t confirm shutdown. Your work is saved; continuation is paused." } }; } if (retryAt && retryAt > now) return { ...base, state: "retry_scheduled", - nextRetryAt: new Date(retryAt).toISOString(), canRetry: !preparationPending && !nativeResumeAt, + nextRetryAt: new Date(retryAt).toISOString(), canRetry: !preparationPending && !nativeResumeAt && run.status !== "scheduled_retry", ...(system?.nextAttemptAt && recoveryStep ? { recoveryStep } : {}) }; if (nativeResumeAt && !system && now - nativeResumeAt < NATIVE_RESUME_DISPATCH_GRACE_MS) return { ...base, state: "working" }; @@ -337,7 +343,9 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS && (reason !== "cleanup_quarantined" || !input.cleanupSettling), retryWait: { reason, message: retryWaitMessages[reason] ?? "Retry is waiting for execution checks. Your message is saved." } }; } - if (wait && wait.requestedAt.getTime() > now - 10_000 && system?.state !== "exhausted") + const queuedDuringRun = Boolean(wait && run.status === "succeeded" && ["todo", "in_progress", "in_review"].includes(issue.status) && run.finishedAt && wait.requestedAt.getTime() <= run.finishedAt.getTime() + && now - run.finishedAt.getTime() < QUEUED_INPUT_DISPATCH_GRACE_MS); + if (wait && (wait.requestedAt.getTime() > now - 10_000 || queuedDuringRun) && system?.state !== "exhausted") return { ...base, state: "working" }; if (run.errorCode === NATIVE_SESSION_CLEANUP_QUARANTINED) { // The provider turn completed and its work is saved; only shutdown of the @@ -586,6 +594,23 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i .map(row => Number(row.nextCheckAt)).sort((a, b) => a - b)[0]; return scheduled ? { state: "scheduled", nextCheckAt: scheduled } : undefined; }; + const dispositionRows = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, + runId: sql`${issueRecoveryActions.evidence}->>'runId'`, updatedAt: issueRecoveryActions.updatedAt }) + .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), + inArray(issueRecoveryActions.sourceIssueId, ids), inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds), + inArray(issueRecoveryActions.status, ["active", "escalated"]), eq(issueRecoveryActions.ownerType, "system"), + inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), isNull(issueRecoveryActions.ownerUserId), + sql`not (${issueRecoveryActions.evidence} ?| array['systemRecovery', 'executionReconciliation', 'freshContinuation', + 'freshContinuationCheck', 'ownerGoneAttestation', 'explicitUserContinuation'])`)) : []; + const automaticDispositionAt = new Map(); + if (dispositionRows.length) { + const { isPersonOwnedFailureCode } = await import("./fresh-continuation-fallback.js"); + for (const row of dispositionRows) { + const run = runs.find(candidate => candidate.issueId === row.issueId && candidate.id === row.runId); + if (!run || isPersonOwnedFailureCode(run.errorCode)) continue; + automaticDispositionAt.set(row.issueId, Math.max(automaticDispositionAt.get(row.issueId) ?? 0, row.updatedAt.getTime())); + } + } const ownerStops = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, runId: sql`${issueRecoveryActions.evidence}->>'runId'` }).from(issueRecoveryActions).where(and( eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), @@ -686,6 +711,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i retryWait: retryWaitMap.get(issue.id) }; const presentation = projectTaskInterruption(issue, { ...facts, freshContinuation: freshContinuationFor(issue.id, facts.run?.id), + automaticDispositionAt: automaticDispositionAt.get(issue.id), interruptWait: interruptWaitFor(issue.id), projectAccessAllowed: denied?.length === 0, projectAccessProjectId: denied?.includes(issue.projectId ?? "") ? issue.projectId : null, From 7154030ef6057e7ec704fc8610b9c2eec3859dd9 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:36:05 -0600 Subject: [PATCH 05/15] fix(heartbeat): draining/yielding servers claim no queued run, and closed tasks get no system continuation (#21258) 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 > - During a release swap, the outgoing server drains. It must not start new runs, because its own exit would cut them off. > - The drain gate (run admission closed at SIGTERM) and the hand-over gate (#21127, yield to a replacement that already dispatches) were checked only by the queued-run dispatch passes. > - Other start paths (executeRun of a queued run, delivered continuations, immediate wake starts) went straight to `claimQueuedRun`, so an outgoing server could still start runs after traffic moved. > - Also, a system continuation queued while its task was open started after another run had finished the task, and took an extra turn on a done task. > - This pull request makes `claimQueuedRun`, which every start path uses, honour the drain and hand-over gate, and cancel a system continuation whose task closed while it was queued. > - The benefit is fewer runs cut off by a swap, and no extra turns on finished tasks. ## Linked Issues or Issue Description Refs #21127, #21135 **What happened?** 1. An outgoing server kept starting runs minutes after traffic moved to its replacement. Each such run was cut off when the old server exited. The run start went through `executeRun` of a queued run, which called `claimQueuedRun` without the drain or hand-over check. 2. In release-swap waves, a continuation (execution reconciliation delivery, invariant or recovery continuation, blocker-stall wake) was queued while its task was open. Another run then finished the task. The continuation still started and took an extra turn on a done task. **Expected behavior** A draining or yielding server leaves a queued run queued for the serving server, on every start path. A system continuation does not start on a task that was closed while it was queued. A person's message on a done task still runs. **Steps to reproduce** 1. Close run admission (drain) or set the hand-over yield on a server. 2. Start a queued run through `executeRun` (for example a delivered continuation). 3. See the run claimed and started on the draining server. ## What Changed - `claimQueuedRun` (`server/src/services/heartbeat/queue.ts`) refreshes and checks the run-admission gate first. When admission is closed (draining or yielding), it leaves the run queued and returns. The dispatch passes already did this check; now every start path does. - `claimQueuedRun` re-reads the task for a system continuation (`issue_recovery_action_restored`, `issue_continuation_needed`, `issue_assignment_recovery`, blocker-stall wake). If the task is `done` or `cancelled`, it cancels the run as `issue_closed_before_start`, skips its wake, and releases the task. Other wake reasons, including a person's message, are not affected. - That cancel never consumes a person's message. Admission can attach deferred comments to a queued system continuation without changing its wake reason. The cancel locks the run's wake and the run (the order admission's coalescing uses), reads the run's current comment ids, and if any is a person's comment that no run of this agent has received yet (read-only use of `deliveredQueuedCommentIds`, which includes the history-read rule), the run is not cancelled: it is claimed as that person's follow-up, which may reopen the task through the normal path. A comment attached concurrently is either seen under the lock or, after the cancel commits, saved behind the cancelled run by admission. - Admission is checked again inside each claim transaction (ordinary claim, queued-comment claim, native review claim), right after the write that moves the run to `running`. If admission closed during the awaited checks, the transaction rolls back: the run stays queued with no `startedAt`, its wake and the task's execution lock are untouched, and nothing is charged. - Every cancellation `claimQueuedRun` makes from the caller's copy of the run is now a compare-and-set from `queued` (`setRunStatusFromLive(..., ["queued"])` through a new `cancelRunIfStillQueued` helper): the closed-task cancel, the refused-interaction cancel, the missing-@mention cancel, the daily-cap cancel and the blocked-dependency cancel. A run another dispatcher already started or finished keeps its status and result, and no wake or release follows. The queue module no longer receives the unconditional `setRunStatus`. - The closed-task cancel takes its decision under the wake and run locks, then cancels through `setRunStatusFromLive` fenced on the row version (`xmin`) the decision read. That saves the same never-started proof (`executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`) as every other queued-run cancel, so task release promotes a person's message saved behind it. A message attached after the decision changes the run, the cancel matches nothing and the decision is taken again. `HeartbeatRecoveryDependencies.setRunStatusFromLive` (`recovery.ts`) now types its existing `cancellationCondition` parameter as `SQL`. - The dispatch ranking in `startNextQueuedRunForAgent` is not changed. ### What I checked in `claimQueuedRun` for writes from the caller's copy - Cancellations through `setRunStatus`: all five now conditional on `queued` (above). - The final claims (ordinary, queued-comment, native review) already lock and re-read the run and update `where status = 'queued'`. - The case-handoff cancel and the chat-control stop already lock the run and update `where status = 'queued'`. - The budget-stamp update already writes `where status = run.status` (`queued`). - `cancelRunInternal` (agent removed, agent not invokable, board-owned budget stop, pause hold, budget cancel) re-reads the run and only cancels a non-terminal status, so it cannot overwrite a finished result. It can still stop a run another server has just started; that is a policy stop (agent removed, budget, hold) that would apply to that run anyway, and it is unchanged here. - `cancelStaleQueuedRun` already takes `expectedStatus: "queued"`. ## Verification Red-to-green tests in `server/src/services/heartbeat/queue.test.ts`: - "claims no queued run once run admission is closed, whatever path asks (draining or yielding server)": red before the gate was added to `claimQueuedRun`, green after. - "does not start a %s run whose task another run already finished": `issue_continuation_needed` and `issue_recovery_action_restored` are cancelled as `issue_closed_before_start`; `issue_commented` (a person's message, carrying its `wakeCommentId`) is claimed and the stored run is `running`. - "answers a person's message attached to a system continuation on a closed task once": still undelivered, the continuation is claimed and is the only unfinished run (red when the cancel ignores comment ids, green after); already received by the closing run, the continuation is cancelled as `issue_closed_before_start` and no other run exists. - "keeps the result of a continuation another dispatcher already started and finished": the stale queued copy is passed after the run succeeded; the stored run stays `succeeded` with its result, and no wake or release follows. Red before the compare-and-set (the run was overwritten to `cancelled`), green after. - "returns the claim to the queue when run admission closes while the claim is being checked": admission closes inside an awaited check; the run stays `queued` with no `startedAt`, the task's execution lock and the wake are unchanged. Red before the in-transaction re-check, green after. Red-to-green test through the real release path, in `server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts`: - "delivers a person's message saved behind a system continuation cancelled at claim because its task closed": a never-started legacy continuation on a done task, with a person's deferred message behind it. Red before the fix: the cancelled run had `resultJson: null`, with no never-started proof. Green after: the proof is present, the wake is skipped, and the message is promoted and runs once. Test expectations changed because they asserted the old behaviour: - `server/src/services/agent-interaction-delivery.test.ts` "cancels refused queued runs through the public queue claim without dispatch": now expects the cancel through `setRunStatusFromLive(runId, "cancelled", ["queued"], …)` instead of `setRunStatus`. - `server/src/services/heartbeat/queue.test.ts` (refused-assignment held case): asserts `setRunStatusFromLive` is not called, instead of `setRunStatus`. - The `issue_commented` case of "does not start a %s run…" now asserts the run is claimed and `running` (it previously asserted only that the error code was not `issue_closed_before_start`). Local command, on this branch based on current master (includes #21234; the dispatch ranking it changed is untouched here): - `cd server && pnpm exec vitest run src/services/heartbeat/queue.test.ts src/__tests__/recovery-wake-herd.test.ts`: 102 tests passed. After the proof fix, `queue.test.ts` again passed 97/97, and the new stale-queue test passed. (The file's `afterAll` database cleanup hook times out on this loaded machine on master too; it is not related to this change.) Why the local release-swap wave does not show the yield fix: - The "yield to the replacement" signal exists only when the run-start handover is created (`server/src/index.ts`, about line 1320). That happens only when a direct deployment listen URL exists, that is, with `PAPERCLIP_EPHEMERAL_SERVER=true` and `PAPERCLIP_DATABASE_LISTEN_URL` (the volume-free configuration). - The local short form of the wave leaves `--ephemeral-server` out, so the handover is disabled and `isRunAdmissionClosed()` becomes true only at SIGTERM. The wave therefore cannot exercise the yield. - The evidence for this fix is the unit test above and the reasoning that every start path now reaches the same gate in `claimQueuedRun`. Hosted confirmation must come from a volume-free instance. - The closed-task fix was found in release-swap waves (an extra turn on a done task in two tasks). ## Risks - `claimQueuedRun` can now await an admission refresh. The refresh returns at once when the cached state is fresh, so the normal path adds no wait before `turn.start`. - A system continuation for a closed task is cancelled. This matches admission, which already refuses such wakes for a closed task. - No migration. No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent 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 - [ ] I have updated relevant documentation to reflect my changes (no documented behavior or command 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 --- ...heartbeat-stale-queue-invalidation.test.ts | 38 +++++ .../src/__tests__/helpers/heartbeat-queue.ts | 14 +- .../agent-interaction-delivery.test.ts | 4 +- server/src/services/heartbeat.ts | 2 +- server/src/services/heartbeat/queue.test.ts | 126 ++++++++++++++- server/src/services/heartbeat/queue.ts | 144 ++++++++++++++++-- server/src/services/heartbeat/recovery.ts | 3 +- 7 files changed, 309 insertions(+), 22 deletions(-) diff --git a/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts b/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts index a23dff7c4f9..e77682e455d 100644 --- a/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts +++ b/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts @@ -1717,6 +1717,44 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => { expect(promotedRun?.agentId).toBe(peerAgentId); }); + it("delivers a person's message saved behind a system continuation cancelled at claim because its task closed", async () => { + // The claim-time closed-task cancel must leave the same never-started proof as every other + // queued-run cancel; without it task release treats the run as unfinished provider work and + // never promotes the person's message waiting behind it. + const { companyId, agentId } = await seedCompanyAndAgent(); + const [issue] = await db.insert(issues).values({ companyId, title: "Closed while its continuation waited", + status: "in_progress", assigneeAgentId: agentId }).returning(); + const { runId, wakeupRequestId } = await seedQueuedRun({ companyId, agentId, issueId: issue.id, + wakeReason: "issue_continuation_needed", invocationSource: "automation" }); + await db.update(issues).set({ status: "done", executionRunId: runId, executionLockedAt: new Date() }) + .where(eq(issues.id, issue.id)); + const [comment] = await db.insert(issueComments).values({ companyId, issueId: issue.id, authorType: "user", + authorUserId: "responsible-user", body: "Please also update the changelog" }).returning(); + const [saved] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "comment", + triggerDetail: "manual", reason: "issue_execution_deferred", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: "responsible-user", + payload: withQueuedCommentIdsInWakePayload({ issueId: issue.id, _paperclipWakeContext: { + issueId: issue.id, wakeReason: "issue_commented", wakeSource: "comment", + } }, [comment.id]), + }).returning(); + + await heartbeat.resumeQueuedRuns(); + await heartbeat.drainActiveRunExecutions(); + + const [cancelled] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(cancelled).toMatchObject({ status: "cancelled", errorCode: "issue_closed_before_start", + resultJson: expect.objectContaining({ executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }) }); + expect(countExecuteCallsForRun(runId)).toBe(0); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeupRequestId)))[0]?.status) + .toBe("skipped"); + await vi.waitFor(async () => { + const [promoted] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, saved.id)); + expect(promoted.status).not.toBe("deferred_issue_execution"); + expect(promoted.runId).toBeTruthy(); + expect(countExecuteCallsForRun(promoted.runId!)).toBe(1); + }, { timeout: 10_000 }); + }); + it("cancels queued max-turn continuations when another continuation owns the issue lock", async () => { const { companyId, agentId } = await seedCompanyAndAgent(); const issueId = randomUUID(); diff --git a/server/src/__tests__/helpers/heartbeat-queue.ts b/server/src/__tests__/helpers/heartbeat-queue.ts index 1ad69f87f68..bea3762cb23 100644 --- a/server/src/__tests__/helpers/heartbeat-queue.ts +++ b/server/src/__tests__/helpers/heartbeat-queue.ts @@ -1,6 +1,6 @@ import type { Db } from "@paperclipai/db"; import { heartbeatRuns } from "@paperclipai/db"; -import { eq } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; import { vi, type Mock, type Mocked } from "vitest"; import { createRunDispatch } from "../../modules/run-dispatch/index.js"; import type { createWakeQueue } from "../../modules/wake-queue/index.js"; @@ -9,7 +9,7 @@ import { createHeartbeatRunPreparation } from "../../services/heartbeat/run-prep import type { HeartbeatQueueDependencies } from "../../services/heartbeat/queue.js"; type Run = typeof heartbeatRuns.$inferSelect; -type MockedCallback = "getAgent" | "setRunStatus" | "setWakeupStatus" | "appendRunEvent" | "finalizeAgentStatus" | "getAgentInvokability" | "getWorktreeExecutionCutoff" | "applyRunDispatchPostCommitEffects" | "getSchedulingSuppression" | "canStartNewExternalBotWork" | "executeRun" | "applyWakeQueuePostCommitEffects" | "releaseIssueExecutionAndPromote" | "publishRunLifecyclePluginEvent" | "cancelRunInternal" | "cancelActiveForAgentInternal" | "resumeExecutionWaitComments" | "resumeQueuedCommentInterrupt" | "resumeSavedLegacyComments" | "sweepPendingCleanupLeases"; +type MockedCallback = "getAgent" | "setRunStatusFromLive" | "setWakeupStatus" | "appendRunEvent" | "finalizeAgentStatus" | "getAgentInvokability" | "getWorktreeExecutionCutoff" | "applyRunDispatchPostCommitEffects" | "getSchedulingSuppression" | "canStartNewExternalBotWork" | "executeRun" | "applyWakeQueuePostCommitEffects" | "releaseIssueExecutionAndPromote" | "publishRunLifecyclePluginEvent" | "cancelRunInternal" | "cancelActiveForAgentInternal" | "resumeExecutionWaitComments" | "resumeQueuedCommentInterrupt" | "resumeSavedLegacyComments" | "sweepPendingCleanupLeases"; type QueueTestDependencies = HeartbeatQueueDependencies & { [K in MockedCallback]: Mock } & { issuesSvc: Mocked; treeControlSvc: Mocked; @@ -27,8 +27,14 @@ export function createHeartbeatQueueTestDependencies(db: Db): QueueTestDependenc ...state, getAgent: vi.fn(async () => { throw new Error("Unexpected agent lookup"); }), options: {}, - setRunStatus: vi.fn(async (id, status, patch) => - db.update(heartbeatRuns).set({ ...patch, status }).where(eq(heartbeatRuns.id, id)).returning().then(rows => rows[0] ?? null)), + // Same compare-and-set contract as the run lifecycle: write only from one of fromStatuses. + setRunStatusFromLive: vi.fn(async (id, status, fromStatuses, patch) => { + const [updated] = await db.update(heartbeatRuns).set({ ...patch, status }) + .where(and(eq(heartbeatRuns.id, id), inArray(heartbeatRuns.status, fromStatuses))).returning(); + if (updated) return { run: updated, updated: true as const }; + const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)); + return { run: current ?? null, updated: false as const }; + }), setWakeupStatus: vi.fn(async () => undefined), appendRunEvent: vi.fn(async () => undefined), finalizeAgentStatus: vi.fn(async () => undefined), diff --git a/server/src/services/agent-interaction-delivery.test.ts b/server/src/services/agent-interaction-delivery.test.ts index 8b21607ec34..1514f9d7362 100644 --- a/server/src/services/agent-interaction-delivery.test.ts +++ b/server/src/services/agent-interaction-delivery.test.ts @@ -317,14 +317,12 @@ describe.skipIf(!support.supported)("pending agent interaction delivery", () => const f = await seed(); await wake(f); await restriction(f.recipient, { canReceiveAssignmentsFromAgents: false }); const callbacks = createHeartbeatQueueTestDependencies(db); - callbacks.setRunStatus.mockImplementation(async (id, status, values) => - (await db.update(heartbeatRuns).set({ ...values, status }).where(eq(heartbeatRuns.id, id)).returning())[0] ?? null); callbacks.setWakeupStatus.mockImplementation(async (id, status, values) => { if (id) await db.update(agentWakeupRequests).set({ ...values, status }).where(eq(agentWakeupRequests.id, id)); }); const queue = createHeartbeatQueue(db, callbacks); expect(await queue.claimQueuedRun(await readRun(f.run.id))).toBeNull(); - expect(callbacks.setRunStatus).toHaveBeenCalledWith(f.run.id, "cancelled", expect.objectContaining({ errorCode: "agent_interaction_delivery_denied" })); + expect(callbacks.setRunStatusFromLive).toHaveBeenCalledWith(f.run.id, "cancelled", ["queued"], expect.objectContaining({ errorCode: "agent_interaction_delivery_denied" })); expect(callbacks.executeRun).not.toHaveBeenCalled(); expect((await readRun(f.run.id)).status).toBe("cancelled"); expect(callbacks.releaseIssueExecutionAndPromote).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index dd08e34eed0..12de5b29fab 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -1324,7 +1324,7 @@ export function heartbeatService( readNonEmptyString(agent.adapterConfig.externalBindingId) ?? ""); }, applyWakeQueuePostCommitEffects, - setRunStatus, + setRunStatusFromLive, setWakeupStatus, appendRunEvent, releaseIssueExecutionAndPromote, diff --git a/server/src/services/heartbeat/queue.test.ts b/server/src/services/heartbeat/queue.test.ts index 6dee76c29f3..168b0558bf6 100644 --- a/server/src/services/heartbeat/queue.test.ts +++ b/server/src/services/heartbeat/queue.test.ts @@ -62,6 +62,19 @@ describe("heartbeat queue module boundary", () => { expect(deps.executeRun).not.toHaveBeenCalled(); }); + it("claims no queued run once run admission is closed, whatever path asks (draining or yielding server)", async () => { + // Release-swap wave: an old server started a delivered continuation 3 minutes after traffic + // had moved to its dispatching replacement, through executeRun of a queued run, which no gate covered. + const database = guardedDatabase(); + const deps = callbacks(database.db); + deps.isRunAdmissionClosed = () => true; + const queue = createHeartbeatQueue(database.db, deps); + const queued = { id: "run-1", status: "queued" } as Parameters[0]; + expect(await queue.claimQueuedRun(queued)).toBeNull(); + expect(database.access).not.toHaveBeenCalled(); + expect(deps.executeRun).not.toHaveBeenCalled(); + }); + it("honors the process-wide run admission gate in every heartbeat instance", async () => { const database = guardedDatabase(); const deps = callbacks(database.db); @@ -497,6 +510,117 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { return { ...f, source, lease, successor, deps, queue: createHeartbeatQueue(db, deps) }; } + it.each([ + ["issue_continuation_needed", "cancelled"], ["issue_recovery_action_restored", "cancelled"], ["issue_commented", "running"], + ] as const)("does not start a %s run whose task another run already finished (expected %s)", async (wakeReason, expected) => { + // Release-swap wave t011: a delivered continuation queued while its task was open started after + // another run marked the task done, and took an extra turn on a finished task. + const f = await fixture("queued"); + await db.update(issues).set({ status: "done", executionRunId: null }).where(eq(issues.id, f.issue.id)); + // A person's message wake carries the comment it answers. + const wakeCommentId = wakeReason === "issue_commented" + ? (await db.insert(issueComments).values({ companyId: f.company.id, issueId: f.issue.id, authorAgentId: f.agent.id, + body: "One more thing" }).returning())[0].id + : undefined; + const [queued] = await db.update(heartbeatRuns).set({ responsibleUserId: "queue-test-user", + contextSnapshot: { issueId: f.issue.id, wakeReason, ...(wakeCommentId ? { wakeCommentId } : {}) } }) + .where(eq(heartbeatRuns.id, f.run.id)).returning(); + const deps = callbacks(db); + deps.getAgent.mockResolvedValue(f.agent); + const queue = createHeartbeatQueue(db, deps); + const claimed = await queue.claimQueuedRun(queued); + if (expected === "cancelled") { + expect(claimed).toBeNull(); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queued.id)))[0]) + .toMatchObject({ status: "cancelled", errorCode: "issue_closed_before_start" }); + } else { + // A person's message on a done task still runs (and reopens it through the normal path). + expect(claimed).toMatchObject({ id: queued.id, status: "running" }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queued.id)))[0]) + .toMatchObject({ status: "running", errorCode: null }); + } + }); + + it.each([ + { label: "still undelivered", delivered: false }, + { label: "already read by the closing run", delivered: true }, + ])("answers a person's message attached to a system continuation on a closed task once ($label)", async ({ delivered }) => { + // Admission can attach a deferred comment to a queued system continuation without changing its + // wake reason. The claim-time closed-task cancel must not consume that person's message. + const f = await fixture("queued"); + const [comment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: f.issue.id, + authorType: "user", authorUserId: "queue-test-user", body: "Can you also update the changelog?" }).returning(); + if (delivered) { + // The run that closed the task received the message as its own wake input. + const startedAt = new Date(comment.createdAt.getTime() + 1_000); + await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status: "succeeded", + invocationSource: "assignment", startedAt, finishedAt: new Date(startedAt.getTime() + 1_000), + contextSnapshot: { issueId: f.issue.id, wakeReason: "issue_commented", wakeCommentIds: [comment.id] } }); + } + await db.update(issues).set({ status: "done", executionRunId: null }).where(eq(issues.id, f.issue.id)); + const [queued] = await db.update(heartbeatRuns).set({ responsibleUserId: "queue-test-user", + contextSnapshot: { issueId: f.issue.id, wakeReason: "issue_continuation_needed", wakeCommentIds: [comment.id] } }) + .where(eq(heartbeatRuns.id, f.run.id)).returning(); + // The continuation's wake is still queued and bound to the run, as admission leaves it. + await db.update(agentWakeupRequests).set({ status: "queued", claimedAt: null, runId: queued.id }) + .where(eq(agentWakeupRequests.id, f.wake.id)); + const deps = callbacks(db); + deps.getAgent.mockResolvedValue(f.agent); + const claimed = await createHeartbeatQueue(db, deps).claimQueuedRun(queued); + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agent.id)); + if (delivered) { + expect(claimed).toBeNull(); + expect(runs.find(row => row.id === queued.id)).toMatchObject({ status: "cancelled", errorCode: "issue_closed_before_start" }); + expect(runs).toHaveLength(2); + } else { + // Exactly one run answers it: this one, claimed as the person's follow-up. + expect(claimed).toMatchObject({ id: queued.id, status: "running" }); + expect(runs.filter(row => row.status !== "succeeded")).toEqual([expect.objectContaining({ id: queued.id, status: "running" })]); + } + }); + + it("keeps the result of a continuation another dispatcher already started and finished", async () => { + // Two servers overlap during a swap: both read the same queued continuation; one starts it and + // the run closes the task before the other reaches the closed-task check with its stale copy. + const f = await fixture("queued"); + const [staleQueued] = await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issue.id, wakeReason: "issue_continuation_needed" } }) + .where(eq(heartbeatRuns.id, f.run.id)).returning(); + const finishedAt = new Date(); + await db.update(heartbeatRuns).set({ status: "succeeded", startedAt: finishedAt, finishedAt, + resultJson: { summary: "Finished by the other server" } }).where(eq(heartbeatRuns.id, f.run.id)); + await db.update(issues).set({ status: "done", executionRunId: null }).where(eq(issues.id, f.issue.id)); + const deps = callbacks(db); + deps.getAgent.mockResolvedValue(f.agent); + expect(await createHeartbeatQueue(db, deps).claimQueuedRun(staleQueued)).toBeNull(); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0]).toMatchObject({ + status: "succeeded", errorCode: null, resultJson: { summary: "Finished by the other server" } }); + expect(deps.setWakeupStatus).not.toHaveBeenCalled(); + expect(deps.releaseIssueExecutionAndPromote).not.toHaveBeenCalled(); + }); + + it("returns the claim to the queue when run admission closes while the claim is being checked", async () => { + // SIGTERM (drain) or the hand-over yield can close admission during claimQueuedRun's awaited + // checks, after its first admission check passed. The run must stay exactly as it was. + const f = await fixture("queued"); + const [queued] = await db.update(heartbeatRuns).set({ responsibleUserId: "queue-test-user", + contextSnapshot: { issueId: f.issue.id, wakeReason: "issue_commented" } }) + .where(eq(heartbeatRuns.id, f.run.id)).returning(); + const [issueBefore] = await db.select().from(issues).where(eq(issues.id, f.issue.id)); + let admissionClosed = false; + const deps = callbacks(db); + deps.getAgent.mockResolvedValue(f.agent); + deps.isRunAdmissionClosed = () => admissionClosed; + deps.budgets.getInvocationBlock.mockImplementation(async () => { admissionClosed = true; return null; }); + expect(await createHeartbeatQueue(db, deps).claimQueuedRun(queued)).toBeNull(); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queued.id)); + expect(stored).toMatchObject({ status: "queued", startedAt: null, finishedAt: null, errorCode: null, + responsibleUserId: queued.responsibleUserId, runnerProfileJson: queued.runnerProfileJson }); + expect((await db.select().from(issues).where(eq(issues.id, f.issue.id)))[0]).toMatchObject({ + executionRunId: issueBefore.executionRunId, executionLockedAt: issueBefore.executionLockedAt }); + expect(deps.setWakeupStatus).not.toHaveBeenCalled(); + expect(deps.executeRun).not.toHaveBeenCalled(); + }); + it("keeps an automatic continuation queued while its legacy predecessor still owns cleanup", async () => { const { successor, lease, queue, deps, ...f } = await pendingPredecessorFixture(); expect(await queue.claimQueuedRun(successor)).toBeNull(); @@ -1011,7 +1135,7 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)))[0].status).toBe(wake.status); expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0].status).toBe("todo"); expect(deps.executeRun).not.toHaveBeenCalled(); - expect(deps.setRunStatus).not.toHaveBeenCalled(); + expect(deps.setRunStatusFromLive).not.toHaveBeenCalled(); }); it("admits the same queued input after the external connection is repaired", async () => { diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index fa0ff7b8b59..e55b996a0aa 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -184,7 +184,7 @@ import { WORKSPACE_WORKTREE_REQUIRES_PROJECT_REMEDIATION, } from "../execution-workspace-policy.js"; import { readContinuationAttempt } from "../recovery/index.js"; -import { allowsDependencyBlockedWake, wakeChatConversationsConflict } from "../../modules/run-dispatch/index.js"; +import { allowsDependencyBlockedWake, extractWakeCommentIds, wakeChatConversationsConflict } from "../../modules/run-dispatch/index.js"; import { withAgentStartLock } from "../agent-start-lock.js"; import { evaluateAgentInvokability, @@ -192,7 +192,7 @@ import { type AgentOrgRow, } from "../agent-invokability.js"; import { supportsUnscopedTimerHeartbeat } from "../heartbeat-policy.js"; -import { isUuidLike } from "@paperclipai/shared"; +import { ISSUE_BLOCKER_STALLED_WAKE_REASON, isUuidLike } from "@paperclipai/shared"; import { retryChatControlAdmission } from "../chat-control-admission-retry.js"; import type { HeartbeatServiceOptions } from "../heartbeat.js"; @@ -222,7 +222,7 @@ export interface HeartbeatQueueDependencies extends Pick, Pick, - Pick { + Pick { sweepPendingCleanupLeases: ReturnType["sweepPendingCleanupLeases"]; options: Pick; issuesSvc: Pick, "getDependencyReadiness" | "listDependencyReadiness" | "updateForCompany">; @@ -412,12 +412,15 @@ export async function claimDueTimerHeartbeatForAgent( /** Queue admission and dispatch share the service lifecycle callbacks and execution ownership. */ // Wake admissions that have not committed their wake and run yet. Process-wide, like // the pending-wake set: a server replacement loses these, and only these, pending wakes. +/** Rolls back a claim whose server closed run admission while it was being taken. */ +class RunAdmissionClosedDuringClaim extends Error {} + const unsavedWakeAdmissions = new Set(); export function unsavedWakeAdmissionCount() { return unsavedWakeAdmissions.size; } export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependencies) { const { - setRunStatus, + setRunStatusFromLive, setWakeupStatus, appendRunEvent, releaseIssueExecutionAndPromote, @@ -469,6 +472,15 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const { parseHeartbeatPolicy, getHeartbeatDailyCapBlock, hasActionableTimerWork, nextTimerHeartbeatAt } = createHeartbeatTimerPolicy(db); + // claimQueuedRun works from the caller's copy of a queued run. Another + // dispatcher (an overlapping server during a swap) may have started and even + // finished that run since, so every cancellation it makes is a + // compare-and-set from "queued": it never overwrites a newer outcome. + async function cancelRunIfStillQueued(runId: string, patch: Partial) { + const write = await setRunStatusFromLive(runId, "cancelled", ["queued"], patch); + return write.updated ? write.run : null; + } + async function cancelQueuedRunForHeartbeatDailyCap( run: typeof heartbeatRuns.$inferSelect, dailyCapBlock: NonNullable< @@ -478,7 +490,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const now = new Date(); const reason = "Cancelled because the agent reached a per-day heartbeat budget cap before adapter invocation"; - const cancelled = await setRunStatus(run.id, "cancelled", { + const cancelled = await cancelRunIfStillQueued(run.id, { finishedAt: now, error: reason, errorCode: dailyCapBlock.reason, @@ -869,6 +881,76 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende } } + // Run admission can close (SIGTERM drain, or the hand-over yield) while + // claimQueuedRun awaits its checks, after its first admission check passed. + // Checked again inside the claim's transaction, right after the write that + // moves the run to running: throwing rolls the whole claim back, so the run, + // its wake and the task's execution lock stay exactly as they were, queued + // for the serving server. + function confirmRunAdmissionStillOpen(claimedRun: unknown) { + if (claimedRun && isRunAdmissionClosed()) throw new RunAdmissionClosedDuringClaim(); + } + + /** System continuations that only make sense for an open task. */ + const SYSTEM_CONTINUATION_WAKE_REASONS = new Set(["issue_recovery_action_restored", "issue_continuation_needed", + "issue_assignment_recovery", ISSUE_BLOCKER_STALLED_WAKE_REASON]); + + /** + * Cancels a system continuation whose task closed while it was queued, + * unless it carries a person's message that no run of this agent has + * received yet (admission can attach deferred comments to a queued system + * continuation without changing its wake reason). Its wake and run are + * locked in the order admission's coalescing uses while the message check + * reads them. The cancel itself goes through the run lifecycle's + * compare-and-set, so it saves the same never-started proof as every other + * queued-run cancel (task release needs it to promote messages saved behind + * this run), and it is fenced on the row version the check saw: a message + * attached after the check changes the run, the cancel matches nothing, and + * the check runs again. + */ + async function cancelClosedTaskContinuation(run: typeof heartbeatRuns.$inferSelect, issueId: string) { + for (let attempt = 0; attempt < 3; attempt += 1) { + const decision = await checkClosedTaskContinuation(run, issueId); + if (decision.kind !== "cancel") return decision; + const write = await setRunStatusFromLive(run.id, "cancelled", ["queued"], { + finishedAt: new Date(), error: "The task was closed before this continuation started.", + errorCode: "issue_closed_before_start", + }, undefined, sql`${heartbeatRuns}.xmin::text = ${decision.rowVersion}`); + if (write.updated && write.run) return { kind: "cancelled" as const, run: write.run }; + if (write.run?.status !== "queued") return { kind: "not_queued" as const }; + } + // Still changing under us: leave it queued; the next dispatch pass checks again. + return { kind: "still_queued" as const }; + } + + async function checkClosedTaskContinuation(run: typeof heartbeatRuns.$inferSelect, issueId: string) { + return db.transaction(async (tx) => { + if (run.wakeupRequestId) await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.id, run.wakeupRequestId), eq(agentWakeupRequests.companyId, run.companyId), + )).for("update"); + const [locked] = await tx.select({ run: heartbeatRuns, rowVersion: sql`${heartbeatRuns}.xmin::text` }) + .from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.status, "queued"), + )).for("update"); + if (!locked) return { kind: "not_queued" as const }; + const current = locked.run; + const context = parseObject(current.contextSnapshot); + const commentIds = [...new Set([...extractWakeCommentIds(context), ...queuedCommentIdsFromRunContext(context), + readNonEmptyString(context.wakeCommentId), readNonEmptyString(context.commentId)] + .filter((id): id is string => Boolean(id)))]; + if (commentIds.length > 0) { + const personComments = await tx.select({ id: issueComments.id }).from(issueComments).where(and( + eq(issueComments.companyId, current.companyId), eq(issueComments.issueId, issueId), + inArray(issueComments.id, commentIds), eq(issueComments.authorType, "user"), + isNull(issueComments.createdByRunId), isNull(issueComments.deletedAt))); + const delivered = await deliveredQueuedCommentIds(tx as unknown as Db, { companyId: current.companyId, issueId, + agentId: current.agentId, commentIds: personComments.map(comment => comment.id) }); + if (personComments.some(comment => !delivered.has(comment.id))) return { kind: "carries_person_message" as const }; + } + return { kind: "cancel" as const, rowVersion: locked.rowVersion }; + }); + } + async function claimQueuedRun( run: typeof heartbeatRuns.$inferSelect, companyAgents?: AgentOrgRow[], @@ -876,12 +958,40 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende deferredCancellations?: Array<() => Promise>, ) { if (run.status !== "queued") return run; + // Every start path ends here (dispatch passes, executeRun of a queued run, + // a delivered continuation). A server whose run admission is closed (it + // received SIGTERM and is draining) or that yields new starts to a + // replacement already dispatching leaves the run queued for that server: + // anything it started now would be cut off by its own exit. + const refreshing = refreshRunAdmission(); + if (refreshing) await refreshing; + if (isRunAdmissionClosed()) return null; + // A system continuation queued while its task was open has nothing left to + // do once another run finished or cancelled the task before this one + // started. A person's message on a done task is not one of these reasons. + const systemContinuationReason = readNonEmptyString(parseObject(run.contextSnapshot).wakeReason); + const continuedIssueId = readNonEmptyString(parseObject(run.contextSnapshot).issueId); + if (systemContinuationReason && SYSTEM_CONTINUATION_WAKE_REASONS.has(systemContinuationReason) && continuedIssueId) { + const [target] = await db.select({ status: issues.status }).from(issues) + .where(and(eq(issues.companyId, run.companyId), eq(issues.id, continuedIssueId))); + if (target && ["done", "cancelled"].includes(target.status)) { + const closed = await cancelClosedTaskContinuation(run, continuedIssueId); + if (closed.kind === "cancelled") { + const cancelled = closed.run; + await setWakeupStatus(run.wakeupRequestId, "skipped", { finishedAt: cancelled.finishedAt ?? new Date(), error: "issue_closed_before_start" }); + await releaseIssueExecutionAndPromote(cancelled, { suppressImmediateRecovery: true, deferredPostCommitEffects }); + } + // A person's undelivered message rides on this run: it runs as their + // follow-up, which may reopen the task through the normal path. + if (closed.kind !== "carries_person_message") return null; + } + } const interactionDelivery = await recheckQueuedRunInteractions(db, run); if (interactionDelivery.run.status !== "queued") return null; run = { ...run, contextSnapshot: interactionDelivery.run.contextSnapshot, resultJson: interactionDelivery.run.resultJson, updatedAt: interactionDelivery.run.updatedAt }; if (interactionDelivery.denied) { - const cancelled = await setRunStatus(run.id, "cancelled", { + const cancelled = await cancelRunIfStillQueued(run.id, { finishedAt: new Date(), error: "Queued agent input is no longer permitted.", errorCode: INTERACTION_DELIVERY_DENIED, }); @@ -940,7 +1050,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const reason = "Message did not @mention the bot"; // This runs under the agent start lock. Do not use cancelRunInternal, // which recursively starts the next run and reacquires that lock. - const cancelled = await setRunStatus(run.id, "cancelled", { + const cancelled = await cancelRunIfStillQueued(run.id, { finishedAt: now, error: reason, errorCode: "chat_mention_required", @@ -1487,6 +1597,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende ) .returning(); await bindClaimedIssueExecution(tx as unknown as Db, issueClaim.ownsIssue, claimedRun); + confirmRunAdmissionStillOpen(claimedRun); return claimedRun ? { kind: "claimed" as const, run: claimedRun } : { kind: "stale" as const, run: null }; @@ -1598,12 +1709,13 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende ) .returning(); await bindClaimedIssueExecution(tx as unknown as Db, issueClaim.ownsIssue, claimedRun); + confirmRunAdmissionStillOpen(claimedRun); return claimedRun ? { kind: "claimed" as const, run: claimedRun } : { kind: "stale" as const, run: null }; }) .catch((error) => { - if (isExternalChatWaitAuthorizationContention(error)) + if (isExternalChatWaitAuthorizationContention(error) || error instanceof RunAdmissionClosedDuringClaim) return { kind: "stale" as const, run: null }; throw error; }) @@ -1658,9 +1770,13 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const predecessor = await lockIssueExecutionClaim(tx); if (predecessor.blocked) return null; } - return claimQueuedNativeReviewRun(tx, { - run, claimedAt, claimValues, - agentNameKey: normalizeAgentNameKey(agent.name), + return tx.transaction(async (reviewTx) => { + const reviewClaim = await claimQueuedNativeReviewRun(reviewTx as unknown as Db, { + run, claimedAt, claimValues, + agentNameKey: normalizeAgentNameKey(agent.name), + }); + confirmRunAdmissionStillOpen(reviewClaim); + return reviewClaim; }); } return tx.transaction(async (claimTx) => { @@ -1679,8 +1795,12 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "queued"), )).returning().then((rows) => rows[0] ?? null); await bindClaimedIssueExecution(claimTx as unknown as Db, issueClaim.ownsIssue, claimedRun); + confirmRunAdmissionStillOpen(claimedRun); return claimedRun; }); + }).catch((error: unknown) => { + if (error instanceof RunAdmissionClosedDuringClaim) return null; + throw error; }); if (!claimed) return null; @@ -1831,7 +1951,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const now = new Date(); const reason = "Cancelled because issue dependencies are still blocked; Paperclip will wake the assignee when blockers resolve"; - const cancelled = await setRunStatus(run.id, "cancelled", { + const cancelled = await cancelRunIfStillQueued(run.id, { finishedAt: now, error: reason, errorCode: "issue_dependencies_blocked", diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index d2f4fe09b02..bab1110db5a 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -72,6 +72,7 @@ import { ne, or, sql, + type SQL, } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { @@ -173,7 +174,7 @@ export interface HeartbeatRecoveryDependencies extends Pick Promise; setRunStatus: (runId: string, status: string, patch?: Partial) => Promise; setRunStatusFromLive: (runId: string, status: string, fromStatuses: string[], patch?: Partial, - failureReport?: undefined, cancellationCondition?: undefined, options?: { onlyWhileNativeLeaseLapsed?: true }) => Promise<{ + failureReport?: undefined, cancellationCondition?: SQL, options?: { onlyWhileNativeLeaseLapsed?: true }) => Promise<{ updated: boolean; run: HeartbeatRun | null; }>; From 3b4c3265ed8cbc00282aee2413349e4ae029b2bf Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:42:52 -0600 Subject: [PATCH 06/15] fix(recovery): offer Try again on a model-unavailable failure and recheck the model first (#21244) 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 fails, the task thread shows a failure marker, and some markers offer Try again > - A `native_provider_model_rejected` failure blocks the task for the person and shows "Model unavailable", but it has no Try again control > - Recovery must just work: after the person fixes the model, they need one obvious control that continues the task, and that control must not start a run that is sure to fail > - This pull request shows Try again on the "Model unavailable" marker and makes the retry recheck the selected model before it starts a run > - The benefit is that the person fixes the model, presses Try again, and the task completes, and a too-early press explains which setting to change instead of failing again ## Linked Issue or Issue Description Refs #21210 **What happened?** Paid run 43321773136, `recovery.retry-exhausted` (OpenCode, `openrouter/deepseek/deepseek-v4.1-flash-1017`). The run failed with `native_provider_model_rejected`. The task stayed blocked and the thread showed "Model unavailable", but no Try again control appeared (`task-chat-run-failed-try-again` not found in 30 s). Only the "Run failed" and "Usage limit reached" markers offer Try again. **Expected behavior** The "Model unavailable" marker offers Try again. Pressing it checks the selected model first. If the provider-rejected model is still selected, no run starts, and the person sees which setting to change with a link to it. After the person changes the model, Try again starts one retry of the original run. **Steps to reproduce** 1. Set an agent's model to an id the provider rejects. 2. Assign it a task. The run fails with `native_provider_model_rejected`. 3. Open the task. Before this change, the marker has no Try again. ## What Changed - `server/src/services/native-runtime/model-rejected-retry.ts`: `rejectedModelRetryRefusal` reads the model the failed run sent (`runnerProfileJson.nativeExecutionInput.provider.model`) and the model a new run would use (the task's model override for its assignee, else the agent's model). If they are the same, it returns a 409 refusal with code `native_provider_model_still_unavailable`, the setting to change (`agent_model` or `task_model_override`) and the rejected model. - `server/src/routes/agents.ts`: the exact failed-run retry (`POST /agents/:id/wakeup`, `reason: retry_failed_run`) applies this check before it queues anything. - `ui/src/components/task-chat/adjacent-errors.ts`, `TaskChatThreadView.tsx`: one `isRetryableFailureMarker` rule, now including "Model unavailable". - `ui/src/lib/model-retry-refusal.ts`, `ui/src/pages/IssueDetail.tsx`: a refused retry shows "Model still unavailable" with the server's message and an "Open model settings" link to `/agents//runtime`. A task override refusal names the override in the message. - Eval `recovery.retry-exhausted` (oracle `runtime.retry-exhausted.v7`): the rejected model stays selected after the failure. The person presses Try again (409, toast names the model, its link opens the agent's model settings, no run starts in 20 s, task stays blocked), restores the working model, presses Try again (202), and the one retry of the original run uses the working model, saves the brief and completes the task. 3 runs: failed 1, succeeded 2. The budget-hold and two follow-up chat phases are removed; the case now tests the model recheck. `recovery.yaml` context and expected outcome updated, recorded in `chat-full-catalog-testops-manifest.json` `changedFields`, pinned in its test, descriptors and inventory digest updated. ## Verification - RED on master: `TaskChatThread.test.tsx` "offers Try again on a model-unavailable failure and retries that run" fails (no control). `agent-live-run-routes.test.ts` "refuses a retry while the rejected model is still selected and starts no run" fails (the route queues the run). - GREEN: both pass. `agent-live-run-routes.test.ts` 101/101. - `server/src/services/native-runtime/model-rejected-retry.test.ts` (embedded PostgreSQL), 6/6: refuses while the agent still selects the rejected model (names the agent setting); names the task override; allows the retry when the agent or the override now selects another model, or the run failed for another reason; ignores another company's run. - `ui/src/lib/model-retry-refusal.test.ts`: names the setting and links to `/agents/morgan/runtime`; no link for a task override; other errors fall through to the generic toast. - Server `tsc --noEmit` clean. UI `tsc` clean apart from the pre-existing generated storybook catalog. `node scripts/check-token-gates.mjs`: clean. - Eval: `npx vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/chat-catalog tests/runner-e2e/chat-catalog-domains tests/runner-e2e/chat-*.test.ts`: 339 files pass. New calibration rejects an accepted early retry, a run started while the model is rejected, a refusal without the model, setting link or blocked task, a retry that used the old model, and duplicate or missing retries. `pnpm test:e2e:runner:typecheck`: pass. Manifest test 10/10. `source-sdk-public-inputs --check`: `changed: false`. - Paid run: Runner Full-Stack E2E 43338695850 on throwaway branch `chat-eval/qa-mr-paid`. Result to follow in a comment. ## Risks - The recheck compares the selected model with the model the provider rejected. It does not call the provider. A model the provider rejected stays refused until the person selects another one; a different but also unsupported model starts a run that fails with the same marker again. - The refusal message is a toast (15 s). The marker detail still says to choose a supported model. - No persisted shape changes; runs saved by older builds carry the same `runnerProfileJson` field. > 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 Opus 5.5 --- .../__tests__/agent-live-run-routes.test.ts | 19 +++ server/src/routes/agents.ts | 3 + .../model-rejected-retry.test.ts | 79 +++++++++ .../native-runtime/model-rejected-retry.ts | 62 +++++++ .../runner-e2e/chat-catalog-contract.test.ts | 2 +- .../runner-e2e/chat-catalog-descriptors.json | 10 +- .../runtime-infrastructure-retry.test.ts | 64 ++++---- .../runtime-infrastructure-retry.ts | 153 +++++++----------- .../chat-full-catalog-testops-manifest.json | 12 +- ...hat-full-catalog-testops-manifest.test.mjs | 4 + tests/runner-e2e/chat-scenarios/recovery.yaml | 19 ++- ui/src/components/TaskChatThread.test.tsx | 27 ++++ .../task-chat/TaskChatThreadView.tsx | 5 +- .../components/task-chat/adjacent-errors.ts | 9 +- ui/src/lib/model-retry-refusal.test.ts | 30 ++++ ui/src/lib/model-retry-refusal.ts | 28 ++++ ui/src/pages/IssueDetail.tsx | 6 +- 17 files changed, 387 insertions(+), 145 deletions(-) create mode 100644 server/src/services/native-runtime/model-rejected-retry.test.ts create mode 100644 server/src/services/native-runtime/model-rejected-retry.ts create mode 100644 ui/src/lib/model-retry-refusal.test.ts create mode 100644 ui/src/lib/model-retry-refusal.ts diff --git a/server/src/__tests__/agent-live-run-routes.test.ts b/server/src/__tests__/agent-live-run-routes.test.ts index 69e704a1099..227245c63f7 100644 --- a/server/src/__tests__/agent-live-run-routes.test.ts +++ b/server/src/__tests__/agent-live-run-routes.test.ts @@ -28,6 +28,7 @@ const mockIssueService = vi.hoisted(() => ({ getByIdentifier: vi.fn(), })); const mockNativeReviewAssignment = vi.hoisted(() => vi.fn()); +const mockRejectedModelRetryRefusal = vi.hoisted(() => vi.fn()); const mockExecutionProjection = vi.hoisted(() => ({ executionProjectionForRun: vi.fn(async () => null), @@ -84,6 +85,10 @@ const mockChatRunRetries = vi.hoisted(() => ({ })); function registerModuleMocks() { + vi.doMock("../services/native-runtime/model-rejected-retry.js", async () => ({ + ...(await vi.importActual("../services/native-runtime/model-rejected-retry.js")), + rejectedModelRetryRefusal: mockRejectedModelRetryRefusal, + })); vi.doMock("../services/native-runtime/native-review-participant.js", async () => ({ ...(await vi.importActual("../services/native-runtime/native-review-participant.js")), getNativeReviewAssignment: mockNativeReviewAssignment, @@ -302,6 +307,7 @@ describe("agent live run routes", () => { mockChatRunRetries.prepareFailedChatRunRetry.mockReset(); mockChatRunRetries.processFailedChatRunRetry.mockReset(); mockNativeReviewAssignment.mockReset().mockResolvedValue(null); + mockRejectedModelRetryRefusal.mockReset().mockResolvedValue(null); mockAccessService.canUser.mockResolvedValue(true); mockAccessService.decide.mockImplementation(async (input: { action?: string }) => ({ allowed: true, @@ -1144,6 +1150,19 @@ describe("agent live run routes", () => { expect(JSON.stringify(mockHeartbeatService.wakeup.mock.calls)).not.toContain("forged"); }); + it("refuses a retry while the rejected model is still selected and starts no run", async () => { + const fixture = createFailedChatRetryDb(false); + mockRejectedModelRetryRefusal.mockResolvedValue({ message: 'The provider rejected the model "bad/model", and it is still selected.', + details: { code: "native_provider_model_still_unavailable", setting: "agent_model", rejectedModel: "bad/model", agentId: routeAgentId, issueId: failedChatIssueId } }); + const res = await requestApp(await createApp(fixture.db), url => request(url).post(`/api/agents/${routeAgentId}/wakeup`).send(retryBody)); + expect(res.status, JSON.stringify(res.body)).toBe(409); + expect(res.body).toMatchObject({ error: expect.stringContaining("still selected"), + details: { code: "native_provider_model_still_unavailable", setting: "agent_model", rejectedModel: "bad/model" } }); + expect(mockRejectedModelRetryRefusal).toHaveBeenCalledExactlyOnceWith(fixture.db, expect.objectContaining({ + failedRun: expect.objectContaining({ id: failedChatRunId }), issue: expect.objectContaining({ id: failedChatIssueId }) })); + expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled(); + }); + it.each(["agent-caller", "denied-task", "foreign-company", "foreign-agent", "foreign-issue", "legacy", "unknown-error", "missing-context", "stale", "resolved", "changed-reviewer"])( "rejects an ineligible exact review retry (%s)", async scenario => { let actor: Record | undefined; diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 9f3bdfba4c3..94c9de65372 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -55,6 +55,7 @@ import { isAiConnectionCompatible } from "@paperclipai/shared"; import { applyConnectorSkills, resolveConnectorAssignments, annotateConnectorSkills, isConnectorSkill } from "../services/connector-runtime.js"; import { getExecutionBlocker } from "../services/execution-blocker.js"; import { canRetryStoppedRun } from "../services/cancelled-native-startup.js"; +import { rejectedModelRetryRefusal } from "../services/native-runtime/model-rejected-retry.js"; import { getNativeReviewAssignment, readNativeReviewAssignmentContext, type NativeReviewAssignmentContext } from "../services/native-runtime/native-review-participant.js"; import { paperclipRunnerTransitionConfig, normalizeLegacyRunnerProvider, isPaperclipRunnerProvider, PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils"; import { applyMcpReasoningEffort } from "../services/public-mcp/agent-config.js"; @@ -6304,6 +6305,8 @@ export function agentRoutes( if (issue.assigneeAgentId !== agent.id && !retryNativeReviewContext) { throw conflict("The task is no longer assigned to this agent."); } + const modelRefusal = await rejectedModelRetryRefusal(db, { failedRun, agent, issue }); + if (modelRefusal) throw conflict(modelRefusal.message, modelRefusal.details); if (issue.conversationAgentId) { // Agent Chat has no task description to replay. Recover the exact // request from the selected server-owned run, never caller markers. diff --git a/server/src/services/native-runtime/model-rejected-retry.test.ts b/server/src/services/native-runtime/model-rejected-retry.test.ts new file mode 100644 index 00000000000..74ee1713da2 --- /dev/null +++ b/server/src/services/native-runtime/model-rejected-retry.test.ts @@ -0,0 +1,79 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { rejectedModelRetryRefusal } from "./model-rejected-retry.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const REJECTED = "openrouter/paperclip-eval/unavailable"; +const WORKING = "openrouter/deepseek/deepseek-v4.1-flash-1017"; + +describe.skipIf(!support.supported)("retrying a run whose model the provider rejected", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-model-rejected-retry-"); + db = createDb(database.connectionString); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function seed(input: { agentModel: string; overrideModel?: string; errorCode?: string }) { + const [company] = await db.insert(companies).values({ name: "Model retry", issuePrefix: `M${randomUUID().slice(0, 4)}` }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Morgan", adapterType: "paperclip_runner", + adapterConfig: { provider: "opencode", model: input.agentModel } }).returning(); + const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Website task", status: "blocked", assigneeAgentId: agent!.id, + assigneeAdapterOverrides: input.overrideModel ? { adapterConfig: { model: input.overrideModel } } : null }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent!.id, status: "failed", runtimeMode: "native", + runtimeModeResolvedAt: new Date(), nativeIssueId: issue!.id, errorCode: input.errorCode ?? "native_provider_model_rejected", + contextSnapshot: { issueId: issue!.id }, + runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: REJECTED } } } }).returning(); + return { agent: agent!, issue: issue!, run: run! }; + } + + const check = (f: Awaited>) => rejectedModelRetryRefusal(db, { + failedRun: f.run, agent: f.agent, issue: f.issue }); + + it("refuses while the agent still selects the rejected model and names the agent setting", async () => { + const f = await seed({ agentModel: REJECTED }); + expect(await check(f)).toEqual({ + message: `The provider rejected the model "${REJECTED}", and it is still selected. Choose a supported model in Morgan's settings, then try again.`, + details: { code: "native_provider_model_still_unavailable", setting: "agent_model", rejectedModel: REJECTED, agentId: f.agent.id, issueId: f.issue.id }, + }); + }); + + it("names the task's model override when that override still selects the rejected model", async () => { + const f = await seed({ agentModel: WORKING, overrideModel: REJECTED }); + expect((await check(f))?.details.setting).toBe("task_model_override"); + }); + + it.each([ + { shape: "the agent now selects another model", agentModel: WORKING }, + { shape: "the task override selects another model", agentModel: REJECTED, overrideModel: WORKING }, + { shape: "the run failed for another reason", agentModel: REJECTED, errorCode: "adapter_failed" }, + ])("allows the retry when $shape", async ({ agentModel, overrideModel, errorCode }) => { + expect(await check(await seed({ agentModel, overrideModel, errorCode }))).toBeNull(); + }); + + it("compares the model a new run would resolve, including provider defaults", async () => { + const f = await seed({ agentModel: "" }); + await db.update(agents).set({ adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "grok-build" } }).where(eq(agents.id, f.agent.id)); + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: { provider: { kind: "acpx", model: "grok-4.7" } } } }).where(eq(heartbeatRuns.id, f.run.id)); + const [agent] = await db.select().from(agents).where(eq(agents.id, f.agent.id)); + expect((await rejectedModelRetryRefusal(db, { failedRun: f.run, agent: agent!, issue: f.issue }))?.details).toMatchObject({ setting: "agent_model", rejectedModel: "grok-4.7" }); + }); + + it("refuses when an omitted model resolves to the provider default that was rejected", async () => { + const f = await seed({ agentModel: "" }); + await db.update(agents).set({ adapterConfig: { provider: "acpx", acpxAgent: "claude" } }).where(eq(agents.id, f.agent.id)); + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: { provider: { kind: "acpx", model: "claude-opus-5-5" } } } }).where(eq(heartbeatRuns.id, f.run.id)); + const [agent] = await db.select().from(agents).where(eq(agents.id, f.agent.id)); + expect((await rejectedModelRetryRefusal(db, { failedRun: f.run, agent: agent!, issue: f.issue }))?.details.rejectedModel).toBe("claude-opus-5-5"); + }); + + it("ignores another company's run with the same id shape", async () => { + const f = await seed({ agentModel: REJECTED }); + const other = await seed({ agentModel: REJECTED }); + expect(await rejectedModelRetryRefusal(db, { failedRun: f.run, agent: other.agent, issue: other.issue })).toBeNull(); + }); +}); diff --git a/server/src/services/native-runtime/model-rejected-retry.ts b/server/src/services/native-runtime/model-rejected-retry.ts new file mode 100644 index 00000000000..de674252a85 --- /dev/null +++ b/server/src/services/native-runtime/model-rejected-retry.ts @@ -0,0 +1,62 @@ +import { and, eq, sql } from "drizzle-orm"; +import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { parseIssueAssigneeAdapterOverrides } from "../execution-workspace-policy.js"; +import { projectPaperclipRunnerTaskConfig, resolvePaperclipRunnerProviderProfile } from "./provider-profile.js"; + +export const NATIVE_PROVIDER_MODEL_STILL_UNAVAILABLE = "native_provider_model_still_unavailable"; + +export type RejectedModelSetting = "agent_model" | "task_model_override"; + +export interface RejectedModelRetryRefusal { + message: string; + details: { code: typeof NATIVE_PROVIDER_MODEL_STILL_UNAVAILABLE; setting: RejectedModelSetting; rejectedModel: string; agentId: string; issueId: string | null }; +} + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +function modelOf(value: unknown): string | null { + const model = record(value).model; + return typeof model === "string" && model.trim() ? model.trim() : null; +} + +function effectiveModel(agentConfig: Record, overrideConfig: Record, companyId: string): string | null { + const merged = { ...agentConfig, ...overrideConfig }; + try { + const profile = resolvePaperclipRunnerProviderProfile(merged, { companyId }); + const config = profile.backend === "codex_app_server" || profile.backend === "opencode_server" || profile.backend === "acpx_runtime" || profile.backend === "cursor_cloud_api" + ? projectPaperclipRunnerTaskConfig(profile.backend, agentConfig, overrideConfig) : merged; + return modelOf({ model: resolvePaperclipRunnerProviderProfile(config, { companyId }).model }); + } catch { + return modelOf(merged); + } +} + +export async function rejectedModelRetryRefusal(db: Pick, input: { + failedRun: { id: string; status: string; errorCode: string | null; runtimeMode?: string | null }; + agent: { id: string; companyId: string; name: string; adapterConfig: unknown }; + issue: { id: string; assigneeAgentId: string | null; assigneeAdapterOverrides: unknown } | null; +}): Promise { + const { agent, issue, failedRun } = input; + if (failedRun.runtimeMode !== "native" || failedRun.status !== "failed" || failedRun.errorCode !== "native_provider_model_rejected") return null; + const [failed] = await db.select({ + rejectedModel: sql`${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput'->'provider'->>'model'`, + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, agent.companyId), eq(heartbeatRuns.id, failedRun.id), + eq(heartbeatRuns.agentId, agent.id), eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "failed"), + eq(heartbeatRuns.errorCode, "native_provider_model_rejected"))); + const rejectedModel = modelOf({ model: failed?.rejectedModel }); + if (!rejectedModel) return null; + const overrideConfig = issue?.assigneeAgentId === agent.id ? parseIssueAssigneeAdapterOverrides(issue.assigneeAdapterOverrides)?.adapterConfig ?? null : null; + const override = modelOf(overrideConfig); + const configured = effectiveModel(record(agent.adapterConfig), record(overrideConfig), agent.companyId); + if (configured !== rejectedModel) return null; + const setting: RejectedModelSetting = override ? "task_model_override" : "agent_model"; + const change = setting === "task_model_override" + ? "Change or clear this task's model override" + : `Choose a supported model in ${agent.name}'s settings`; + return { + message: `The provider rejected the model "${rejectedModel}", and it is still selected. ${change}, then try again.`, + details: { code: NATIVE_PROVIDER_MODEL_STILL_UNAVAILABLE, setting, rejectedModel, agentId: agent.id, issueId: issue?.id ?? null }, + }; +} diff --git a/tests/runner-e2e/chat-catalog-contract.test.ts b/tests/runner-e2e/chat-catalog-contract.test.ts index fa74dd03fd1..e3216b8d7b1 100644 --- a/tests/runner-e2e/chat-catalog-contract.test.ts +++ b/tests/runner-e2e/chat-catalog-contract.test.ts @@ -36,7 +36,7 @@ describe("catalog oracle contract", () => { // execution-environments.choose-capable-target: the second computer is a saved SSH target advertised for Claude Code but never tested. // questions-and-approvals.necessary-question: the answer may shape the saved deliverable as well as the brief. // tasks.assignment-conflict: the query names the Website task, since "this task" in a chat can mean the chat. - expect(chatCatalogInventoryDigest).toBe("dcda709b646b20bdd75c833468d886a111040f130e6699c94fa437ce073bf853"); + expect(chatCatalogInventoryDigest).toBe("ce790541ea5969983f5faf0fafc00a63413684929a2fbd342423224c3ee4b12c"); for (const implementation of chatCatalogCases) expect(chatCatalogScenarios.some(row => row.id === implementation.scenarioId)).toBe(true); }); }); diff --git a/tests/runner-e2e/chat-catalog-descriptors.json b/tests/runner-e2e/chat-catalog-descriptors.json index 6b268176c3e..53434a786bf 100644 --- a/tests/runner-e2e/chat-catalog-descriptors.json +++ b/tests/runner-e2e/chat-catalog-descriptors.json @@ -4513,12 +4513,12 @@ "../../server/src/vendor/paperclip-runner/index.ts", "chat-scenarios/recovery.yaml" ], - "oracleVersion": "paperclip.chat-catalog.runtime.retry-exhausted.v6", + "oracleVersion": "paperclip.chat-catalog.runtime.retry-exhausted.v7", "coverageGaps": [], - "expectedRunCount": 5, - "expectedHumanMessageCount": 3, + "expectedRunCount": 3, + "expectedHumanMessageCount": 1, "turnTimeoutMs": 120000, - "attemptTimeoutMs": 1800000, + "attemptTimeoutMs": 1200000, "authentication": "human-session", "setupPolicy": { "readiness": "preserve-scenario", @@ -4531,7 +4531,7 @@ "kind": "terminal-counts", "terminalStatusCounts": { "failed": 1, - "succeeded": 4 + "succeeded": 2 } }, "modulePath": "./chat-catalog-domains/runtime-infrastructure-retry.js", diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.test.ts b/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.test.ts index 2e74102de60..86009fdf003 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.test.ts @@ -5,30 +5,45 @@ import path from "node:path"; import { gradeInfrastructureRetry, isHumanRetryRequest, releasedRetryListener, retriesOriginalRun } from "./runtime-infrastructure-retry.js"; function valid() { return { scenarioId: "recovery.retry-exhausted", origin: "http://paperclip.test", companyId: "company", leadId: "ceo", agents: [], links: ["/COM/issues/COM-2"], humanQueries: [], reply: "", tasks: [{ id: "website", status: "done" }], activity: [], - runs: [{ id: "exhausted", status: "failed" }, ...["canonical", "held", "retry", "final"].map(id => ({ id, status: "succeeded" }))], - state: { task: { id: "website", identifier: "COM-2", status: "blocked" }, queryRecoveryRead: true, heldRecoveryRead: true, finalRecoveryRead: true, worker: { id: "morgan" }, - failure: { id: "exhausted", companyId: "company", agentId: "morgan", status: "failed", errorCode: "native_provider_model_rejected" }, freshContinuationsBefore: 0, successorRunsBefore: 0, - queryReply: "Use the Retry button on the original failed run; this requires your human board session and rechecks current gates.", retryVisible: true, - budgetHeldBeforeRetry: true, heldRetryStatus: 202, noDuplicateRetryWhileHeld: true, noAdmissionUnderBudget: true, failedRunVisibleWhileHeld: true, heldReplyAttributed: true, - heldReply: "The retry could not start because Morgan's current budget hold blocks admission. The previous native failure remains visible.", - budgetRestoredByHuman: true, retryBoundToOriginal: true, retryRunCount: 1, retryAdmissionAfterGateClear: true, - originalFailureRetained: true, actualRetryResult: true, finalReplyAttributed: true, finalReply: "Website is complete after the eligible retry. The original exhausted attempt remains inspectable." } }; + runs: [{ id: "rejected", status: "failed" }, ...["canonical", "retry"].map(id => ({ id, status: "succeeded" }))], + state: { task: { id: "website", identifier: "COM-2", status: "blocked" }, queryRecoveryRead: true, worker: { id: "morgan" }, + failure: { id: "rejected", companyId: "company", agentId: "morgan", status: "failed", errorCode: "native_provider_model_rejected" }, freshContinuationsBefore: 0, successorRunsBefore: 0, + queryReply: "Use Try again on the Website task once Morgan's model is fixed.", retryVisible: true, + refusedRetryStatus: 409, refusalCode: "native_provider_model_still_unavailable", refusalNamedRejectedModel: true, refusalLinksModelSetting: true, + noRunWhileModelUnavailable: true, taskBlockedAfterRefusal: true, + modelFixedByHuman: true, fixedRetryStatus: 202, retryRunCount: 1, retryBoundToOriginal: true, retryAdmissionAfterFix: true, retryUsedFixedModel: true, + originalFailureRetained: true, actualRetryResult: true } }; } -it("accepts actual budget rejection, one eligible retry and retained failure", () => expect(gradeInfrastructureRetry(valid()).passed).toBe(true)); -it("accepts substantive natural human guidance and later factual reports", () => { const o = valid(); o.state.queryReply = "You can try again using the task's supported Retry control. It checks today's execution conditions."; o.state.heldReply = "Morgan has reached the spending cap, so no new execution was admitted."; o.state.finalReply = "The Website delivery is ready; its earlier failed attempts remain in the run history."; expect(gradeInfrastructureRetry(o).passed).toBe(true); }); +it("accepts a refused Try again while the model is rejected, then one retry after the fix that completes the task", () => expect(gradeInfrastructureRetry(valid()).passed).toBe(true)); +it("accepts reworded guidance on the same saved evidence", () => { const o = valid(); o.state.queryReply = "Fix the model in Morgan's settings and press Try again on COM-2."; expect(gradeInfrastructureRetry(o).passed).toBe(true); }); it("rejects guidance whose run never read the saved recovery record", () => { const o = valid(); o.state.queryRecoveryRead = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); it("rejects guidance that does not link the original task", () => { const o = valid(); o.links = []; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects a retry admitted under the actual hard stop", () => { const o = valid(); o.state.noAdmissionUnderBudget = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects a hidden original failure while Retry cannot start", () => { const o = valid(); o.state.failedRunVisibleWhileHeld = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects a held-phase answer that never read the task's runs", () => { const o = valid(); o.state.heldRecoveryRead = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects a final answer that never read the task's runs", () => { const o = valid(); o.state.finalRecoveryRead = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects an unbound held-phase reply", () => { const o = valid(); o.state.heldReplyAttributed = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); +it("rejects a model failure with no visible Try again", () => { const o = valid(); o.state.retryVisible = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); +it("rejects a Try again that starts a doomed run while the rejected model is still selected", () => { + const accepted = valid(); accepted.state.refusedRetryStatus = 202; expect(gradeInfrastructureRetry(accepted).passed).toBe(false); + const started = valid(); started.state.noRunWhileModelUnavailable = false; expect(gradeInfrastructureRetry(started).passed).toBe(false); +}); +it("rejects a refusal for another reason, or one that does not name the model or link its setting", () => { + const code = valid(); code.state.refusalCode = "conflict"; expect(gradeInfrastructureRetry(code).passed).toBe(false); + const named = valid(); named.state.refusalNamedRejectedModel = false; expect(gradeInfrastructureRetry(named).passed).toBe(false); + const linked = valid(); linked.state.refusalLinksModelSetting = false; expect(gradeInfrastructureRetry(linked).passed).toBe(false); +}); +it("rejects a refusal that unblocks the task", () => { const o = valid(); o.state.taskBlockedAfterRefusal = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); +it("rejects a retry the fixed model never reached", () => { + const unfixed = valid(); unfixed.state.modelFixedByHuman = false; expect(gradeInfrastructureRetry(unfixed).passed).toBe(false); + const model = valid(); model.state.retryUsedFixedModel = false; expect(gradeInfrastructureRetry(model).passed).toBe(false); + const early = valid(); early.state.retryAdmissionAfterFix = false; expect(gradeInfrastructureRetry(early).passed).toBe(false); +}); +it("rejects a refused retry after the fix", () => { for (const status of [200, 409, 500]) { const o = valid(); o.state.fixedRetryStatus = status; expect(gradeInfrastructureRetry(o).passed).toBe(false); } }); it("rejects retrying a different task or failed attempt", () => { const o = valid(); o.state.retryBoundToOriginal = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects duplicate eligible retries", () => { const o = valid(); o.state.retryRunCount = 2; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects admission predating actual gate restoration", () => { const o = valid(); o.state.retryAdmissionAfterGateClear = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects rewriting the exhausted attempt into success", () => { const o = valid(); o.state.originalFailureRetained = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); +it("rejects duplicate or missing retries", () => { + const two = valid(); two.state.retryRunCount = 2; expect(gradeInfrastructureRetry(two).passed).toBe(false); + const none = valid(); none.state.retryRunCount = 0; expect(gradeInfrastructureRetry(none).passed).toBe(false); + const extra = valid(); extra.runs.push({ id: "again", status: "succeeded" }); expect(gradeInfrastructureRetry(extra).passed).toBe(false); +}); +it("rejects rewriting the failed attempt into success", () => { const o = valid(); o.state.originalFailureRetained = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); it("rejects completion without the actual retry's saved output", () => { const o = valid(); o.state.actualRetryResult = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects borrowing the pre-retry reply for final completion", () => { const o = valid(); o.state.finalReplyAttributed = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); +it("rejects an unfinished task", () => { const o = valid(); o.tasks[0]!.status = "blocked"; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); it("rejects absent native retry evidence", () => expect(gradeInfrastructureRetry(undefined).passed).toBe(false)); it("rejects an infrastructure loss, which continues automatically, in place of a person-owned failure", () => { const o = valid(); o.state.failure.errorCode = "native_runner_process_exited"; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); @@ -51,17 +66,6 @@ it("accepts the task's own Retry request as the human Retry, for this task and a expect(isHumanRetryRequest(request("GET", "/api/issues/website/retry"), "website", "morgan")).toBe(false); expect(isHumanRetryRequest(request("POST", "/api/issues/website/retry-workspace-export"), "website", "morgan")).toBe(false); }); -it("requires the one held Retry to have been accepted, not refused", () => { - for (const status of [200, 409, 500]) { const o = valid(); o.state.heldRetryStatus = status; expect(gradeInfrastructureRetry(o).passed).toBe(false); } -}); -it("rejects a held Retry that dispatches before the gate clears", () => { - const early = valid(); early.state.noAdmissionUnderBudget = false; expect(gradeInfrastructureRetry(early).passed).toBe(false); - const predates = valid(); predates.state.retryAdmissionAfterGateClear = false; expect(gradeInfrastructureRetry(predates).passed).toBe(false); -}); -it("rejects a held Retry that never dispatches after the gate clears", () => { const o = valid(); o.state.retryRunCount = 0; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); -it("rejects a second Retry control offered while the saved Retry waits", () => { const o = valid(); o.state.noDuplicateRetryWhileHeld = false; expect(gradeInfrastructureRetry(o).passed).toBe(false); }); - - it("binds the brief to the released Retry's own workspace, and only that one", async () => { const root = await mkdtemp(path.join(tmpdir(), "retry-listener-")), outside = await mkdtemp(path.join(tmpdir(), "retry-outside-")); try { diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.ts b/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.ts index 4360e89ba23..978cf8fb7b5 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-infrastructure-retry.ts @@ -1,10 +1,9 @@ -import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely, chatCatalogNativePhaseRemainingBudget } from "../chat-catalog-contract.js"; +import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely } from "../chat-catalog-contract.js"; import { expect, type Page } from "@playwright/test"; import { writeFile } from "node:fs/promises"; import type { HeartbeatRun } from "../../../packages/shared/src/types/heartbeat.js"; import type { Issue } from "../../../packages/shared/src/types/issue.js"; import { pollUntil } from "../api.js"; -import { sendChatMessage } from "../chat-flow.js"; import { checks, type Entity } from "./internal-support.js"; import { prepareRuntimeWorkerGate, releasedRetryListener, releaseRuntimeWorker, retriesOriginalRun, type RuntimeBriefGate } from "./runtime-busy-worker.js"; import { controllerReadRecovery, linksSourceTask, sourceRunRecovery, type SourceRecoveryActions } from "./runtime-infrastructure.js"; @@ -35,6 +34,9 @@ export async function personOwnedNativeFailure(ctx: ChatCatalogContext) { return { issueId: task.id }; }); if (!task || failure.failedIssueId !== task.id) throw new Error("Person-owned failure did not stop the fixture's own Website task"); + const workingModel = String(failure.originalConfiguration.adapterConfig?.model ?? ""); + const kept = await ctx.input.api.patch(`/api/agents/${worker.id}`, { adapterConfig: { ...failure.originalConfiguration.adapterConfig, model: failure.failedModel } }); + if (kept.adapterConfig?.model !== failure.failedModel || !workingModel) throw new Error("The rejected model is not the agent's selected model before Retry"); const companyId = ctx.input.fixtures.company.id, failedRunId = failure.failedRun.id, websiteId = task.id; const load = async () => { const [current, run, recovery, runs] = await Promise.all([ctx.input.api.get(`/api/issues/${websiteId}`), ctx.input.api.get(`/api/heartbeat-runs/${failedRunId}`), @@ -54,34 +56,33 @@ export async function personOwnedNativeFailure(ctx: ChatCatalogContext) { activeRecovery: before.active ? { id: before.active.id, ownerType: before.active.ownerType, cause: before.active.cause, status: before.active.status } : null, freshContinuations: settled.freshContinuations, successorRuns: settled.successorRuns }); return { worker, gate, task: settled.current, workerRunId: failedRunId, failure: settled.run, recoveryBefore: before.active ?? null, - freshContinuationsBefore: settled.freshContinuations, successorRunsBefore: settled.successorRuns, failureKind: failure.failureKind }; + freshContinuationsBefore: settled.freshContinuations, successorRunsBefore: settled.successorRuns, failureKind: failure.failureKind, + rejectedModel: failure.failedModel, workingModel, originalAdapterConfig: failure.originalConfiguration.adapterConfig }; } +export const MODEL_STILL_UNAVAILABLE_CODE = "native_provider_model_still_unavailable"; +const MODEL_SETTINGS_PATH = /\/agents\/[^/]+\/runtime$/; export function gradeInfrastructureRetry(value: unknown) { const c = checks(), o = runtimeObservation(value); - c.add("actual-person-owned-failure-retry-and-current-gates", !!o, "The genuine person-owned native failure, real human Retry controls and independently observed admission gates are required."); if (!o) return c.result(); + c.add("actual-person-owned-failure-retry-and-model-recheck", !!o, "The genuine person-owned native failure, the real human Try again control and the independently observed model recheck are required."); if (!o) return c.result(); const s = o.state; c.add("actual-person-owned-failure-awaits-retry", isPersonOwnedRetryFailure({ run: s.failure as HeartbeatRun, companyId: o.companyId, agentId: (s.worker as Entity)?.id, taskStatus: (s.task as Issue)?.status, freshContinuations: Number(s.freshContinuationsBefore), successorRuns: Number(s.successorRunsBefore) }), - "The original task stopped for a reason only the person can resolve, stays blocked for the person, and the system starts no continuation of its own; an infrastructure loss continues automatically and is insufficient."); + "The original task stopped because the provider rejected its selected model, stays blocked for the person, and the system starts no continuation of its own."); c.add("ordinary-human-retry-guidance", s.queryRecoveryRead === true && s.retryVisible === true && linksSourceTask(o, s.task as Entity), - "The canonical reply comes from a run that read the saved recovery record and links the original task, where the real human Retry control is visible."); - c.add("actual-closed-gate-prevents-new-execution", s.budgetHeldBeforeRetry === true && [200, 202, 409].includes(Number(s.heldRetryStatus)) - && s.noAdmissionUnderBudget === true && s.failedRunVisibleWhileHeld === true && s.heldReplyAttributed === true && s.heldRecoveryRead === true, - "The first real Retry cannot start under the independently saved budget hold, retains failure visibly, and its own subsequent chat run reads the task's actual runs before replying."); - // The one accepted Retry is the held one: the product saves it and starts it - // once the gate clears. No second Retry exists, and none is offered. - c.add("one-accepted-eligible-retry-preserves-original-failure", s.budgetRestoredByHuman === true && Number(s.heldRetryStatus) === 202 && s.noDuplicateRetryWhileHeld === true - && s.retryBoundToOriginal === true && s.retryRunCount === 1 - && s.retryAdmissionAfterGateClear === true && s.originalFailureRetained === true && s.actualRetryResult === true + "The canonical reply comes from a run that read the saved recovery record and links the original task, where the real Try again control is visible on the model failure."); + c.add("retry-rechecks-the-still-rejected-model", Number(s.refusedRetryStatus) === 409 && s.refusalCode === MODEL_STILL_UNAVAILABLE_CODE + && s.refusalNamedRejectedModel === true && s.refusalLinksModelSetting === true && s.noRunWhileModelUnavailable === true && s.taskBlockedAfterRefusal === true, + "Try again while the rejected model is still selected starts no run, keeps the task blocked and tells the person which setting to change, with a working link to it."); + c.add("one-retry-after-model-fixed-completes", s.modelFixedByHuman === true && Number(s.fixedRetryStatus) === 202 && s.retryRunCount === 1 + && s.retryBoundToOriginal === true && s.retryAdmissionAfterFix === true && s.retryUsedFixedModel === true + && s.originalFailureRetained === true && s.actualRetryResult === true && o.tasks.length === 1 && o.tasks[0]?.id === (s.task as Entity).id && o.tasks[0]?.status === "done" - && o.runs.length === 5 && o.runs.filter(row => row.status === "failed").length === 1 && o.runs.filter(row => row.status === "succeeded").length === 4, - "Once the actual human restores the gate, exactly one eligible native retry uses the server-owned failed task context, retains that original failure and saves the real Website result."); - c.add("own-final-phase-reports-actual-result", s.finalReplyAttributed === true && s.finalRecoveryRead === true, - "A separately declared factual follow-up receives its own native reply from a run that read the task's actual runs."); + && o.runs.length === 3 && o.runs.filter(row => row.status === "failed").length === 1 && o.runs.filter(row => row.status === "succeeded").length === 2, + "After the person selects a working model, one Try again starts exactly one retry of the original run with that model, retains the original failure and saves the real Website result."); return c.result(); } export const runtimeInfrastructureRetryCases = [runtimeDefinition("recovery.retry-exhausted", personOwnedNativeFailure, gradeInfrastructureRetry, { - oracleVersion: "paperclip.chat-catalog.runtime.retry-exhausted.v6", authentication: "human-session", expectedHumanMessageCount: 3, expectedRunCount: 5, attemptTimeoutMs: 1_800_000, + oracleVersion: "paperclip.chat-catalog.runtime.retry-exhausted.v7", authentication: "human-session", expectedHumanMessageCount: 1, expectedRunCount: 3, attemptTimeoutMs: 1_200_000, setupPolicy: { readiness: "preserve-scenario", invariantCheckIds: ["lead-ready", "person-owned-failure-awaits-retry"] }, async verifySetup(ctx, state) { const c = checks(), lead = await ctx.input.api.get(`/api/agents/${ctx.input.fixtures.agent.id}`), task = state.task as Issue, worker = state.worker as Entity; const [current, run, recovery, runs] = await Promise.all([ctx.input.api.get(`/api/issues/${task.id}`), ctx.input.api.get(`/api/heartbeat-runs/${state.workerRunId}`), @@ -90,99 +91,69 @@ export const runtimeInfrastructureRetryCases = [runtimeDefinition("recovery.retr c.add("person-owned-failure-awaits-retry", isPersonOwnedRetryFailure({ run, companyId: ctx.input.fixtures.company.id, agentId: worker.id, taskStatus: current.status, freshContinuations: (recovery.actions ?? []).filter(action => !!(action.evidence as Record).freshContinuation).length, successorRuns: runs.filter(row => row.agentId === worker.id && row.id !== run.id).length }), "The original task waits for the person's Retry after a failure only the person can resolve."); return c.result(); }, - runPolicy: { kind: "terminal-counts", terminalStatusCounts: { failed: 1, succeeded: 4 } }, + runPolicy: { kind: "terminal-counts", terminalStatusCounts: { failed: 1, succeeded: 2 } }, sourceFiles: ["chat-catalog-domains/runtime-infrastructure-retry.ts", "chat-catalog-domains/runtime-infrastructure.ts", "chat-catalog-domains/api-read-receipts.ts", "chat-catalog-domains/runtime-native-fault.ts", "chat-catalog-domains/runtime-native-failure.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/runtime-support.ts", "../../server/src/services/hot-restart.ts", "../../server/src/vendor/paperclip-runner/index.ts", "chat-scenarios/recovery.yaml"], async act(ctx, state) { const task = state.task as Issue, worker = state.worker as RuntimeAgent; const initial = await pollUntil({ label: "Canonical human Retry guidance after the person-owned failure", 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 === 2 && v.runs.some(row => row.id === state.workerRunId && row.status === "failed") && v.runs.some(row => row.agentId === ctx.input.fixtures.agent.id && row.status === "succeeded")) }); - state.queryReply = (await observeRuntime(ctx, state)).reply; const source = ctx.input.page.url(), root = `/api/companies/${ctx.input.fixtures.company.id}`; + state.queryReply = (await observeRuntime(ctx, state)).reply; const source = ctx.input.page.url(); + state.queryRecoveryRead = await controllerReadRecovery(ctx, initial.runs.find(row => row.agentId === ctx.input.fixtures.agent.id)?.id, task.id, String(state.workerRunId), task.identifier); const taskURL = `/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`; await ctx.input.page.goto(taskURL, { waitUntil: "domcontentloaded" }); const retry = humanRetryControl(ctx.input.page); await expect(retry).toBeVisible(); state.retryVisible = true; - // A zero amount disables enforcement. Hold with a real cap and one explicit - // synthetic accounting receipt over it, imported through the public path; - // this is not model/provider spend. Restoring 500 cents later lifts it. - await ctx.input.api.post(`${root}/budgets/policies`, { scopeType: "agent", scopeId: worker.id, amount: 100, isActive: true, hardStopEnabled: true, unpricedUsagePolicy: "allow" }); - const budgetReceipt = await ctx.input.api.post<{ id: string }>(`${root}/cost-events`, { agentId: worker.id, provider: "synthetic-eval-import", biller: "synthetic-eval-import", - model: "imported-fixture-receipt", billingType: "metered_api", costStatus: "reported", costCents: 125, inputTokens: 0, outputTokens: 0, - occurredAt: new Date().toISOString(), idempotencyKey: `retry-exhausted-held:${ctx.input.nonce}` }); - if (typeof budgetReceipt.id !== "string" || !budgetReceipt.id) throw new Error("Missing public synthetic accounting fixture receipt"); - await ctx.input.evidence("runtime-retry-imported-budget-context.json", { agentId: worker.id, receiptId: budgetReceipt.id, origin: "public-imported-synthetic-fixture", - importedFixtureCostCents: 125, hardCapCents: 100, modelProviderUsage: "Not model/provider usage; explicit public synthetic accounting fixture" }); - const held = await pollUntil({ label: "Real current budget hold before first human Retry", deadlineAt: Date.now() + 45_000, load: () => ctx.input.api.get(`/api/agents/${worker.id}`), accept: row => row.lifecycleHolds?.includes("budget") === true }); - state.budgetHeldBeforeRetry = held.lifecycleHolds?.includes("budget") === true; - const rejected = ctx.input.page.waitForResponse(r => isHumanRetryRequest(r.request(), task.id, worker.id)); - await retry.click(); state.heldRetryStatus = (await rejected).status(); const workerRetryRuns = async () => (await ctx.allRuns()).filter(row => row.agentId === worker.id && row.id !== state.workerRunId).length; - const holdSamples = [await workerRetryRuns()]; - // Wait on the open page as a person would, without reloading: the task - // keeps the failure and names the budget wait. The saved Retry starts by - // itself later, so no second Retry control is offered. - const waiting = ctx.input.page.getByTestId("task-execution-waiting"); - await expect(waiting).toBeVisible({ timeout: 60_000 }); - const waitingText = await waiting.textContent() ?? ""; - state.failedRunVisibleWhileHeld = waitingText.includes("Couldn’t finish this attempt") && /budget/i.test(waitingText); - state.noDuplicateRetryWhileHeld = await humanRetryControl(ctx.input.page).count() === 0; - holdSamples.push(await workerRetryRuns()); - await ctx.input.capture("actual-retry-gate-held", "Original native failure remains visible when current budget prevents Retry admission", "runtime-retry-budget-held.png"); - await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); - const heldQuery = `I tried the supported Retry on Website ${task.identifier ?? task.id} while Morgan's actual budget is held. Did a new attempt start, and what current gate is stopping it?`; - await sendChatMessage(ctx.input.page, heldQuery, chatCatalogNativePhaseRemainingBudget(ctx)); - const heldPhase = await pollUntil({ label: "Own chat phase reports actual non-admission under current budget", 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 === 3 && v.runs.filter(row => row.agentId === ctx.input.fixtures.agent.id).every(row => row.status === "succeeded")) }); - const phaseReply = async (query: string, runId: string) => { - const comments = await ctx.input.api.get(`/api/issues/${ctx.issue()!.id}/comments?order=asc`), human = comments.filter(row => !row.authorAgentId && row.body === query), replies = comments.filter(row => row.authorAgentId === ctx.input.fixtures.agent.id && row.createdByRunId === runId); - const detail = await ctx.input.api.get<{ runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${runId}`); - return { attributed: human.length === 1 && replies.length > 0 && detail.runnerProfileJson?.nativeExecutionInput?.task?.prompt?.includes(human[0]!.id) === true, body: replies.map(row => row.body).join("\n") }; - }; - const heldRun = heldPhase.runs.find(row => !initial.runs.some(prior => prior.id === row.id) && row.agentId === ctx.input.fixtures.agent.id); - if (!heldRun) throw new Error("Held retry response lacks an actual subsequent native turn"); - const heldReply = await phaseReply(heldQuery, heldRun.id); state.heldReply = heldReply.body; state.heldReplyAttributed = heldReply.attributed; - state.queryRecoveryRead = await controllerReadRecovery(ctx, initial.runs.find(row => row.agentId === ctx.input.fixtures.agent.id)?.id, task.id, String(state.workerRunId), task.identifier); - state.heldRecoveryRead = await controllerReadRecovery(ctx, heldRun.id, task.id, String(state.workerRunId), task.identifier); - // Sampled at the click, on the waiting page, and after the held chat phase. - holdSamples.push(await workerRetryRuns()); state.heldWorkerRetryRunSamples = holdSamples; - state.noAdmissionUnderBudget = holdSamples.every(count => count === 0); - state.gatesClearedAt = Date.now(); - await ctx.input.api.post(`${root}/budgets/policies`, { scopeType: "agent", scopeId: worker.id, amount: 500, isActive: true, hardStopEnabled: true, unpricedUsagePolicy: "allow" }); - let restored = await ctx.input.api.get(`/api/agents/${worker.id}`); - if (restored.status === "error") { await ctx.input.api.post(`/api/agents/${worker.id}/clear-error`, {}); restored = await ctx.input.api.get(`/api/agents/${worker.id}`); } - state.budgetRestoredByHuman = !restored.lifecycleHolds?.includes("budget"); - // No second click: the held Retry is the one accepted Retry. A Retry may - // start in a fresh isolated workspace when the task does not own its - // directory, so bind the brief to the workspace the released run actually - // uses: wait for its listener there, then supply the brief. + const refused = ctx.input.page.waitForResponse(r => isHumanRetryRequest(r.request(), task.id, worker.id)); + await retry.click(); const refusal = await refused; state.refusedRetryStatus = refusal.status(); + const refusalBody = await refusal.json().catch(() => null) as { error?: unknown; details?: { code?: unknown; rejectedModel?: unknown } } | null; + state.refusalCode = refusalBody?.details?.code ?? null; + const notice = ctx.input.page.getByRole("listitem").filter({ hasText: "Model still unavailable" }).first(); + await expect(notice).toBeVisible({ timeout: 10_000 }); + state.refusalNamedRejectedModel = (await notice.textContent() ?? "").includes(String(state.rejectedModel)); + const settingsLink = notice.getByRole("link").first(); + const linked = await settingsLink.count() === 1; + await ctx.input.capture("model-still-unavailable-refusal", "Try again names the model setting while the rejected model is still selected", "runtime-retry-model-refused.png"); + const refusalSamples = [await workerRetryRuns()]; + if (linked) { + await settingsLink.click(); + await ctx.input.page.waitForURL(url => MODEL_SETTINGS_PATH.test(url.pathname), { timeout: 15_000 }).catch(() => undefined); + } + state.refusalLinksModelSetting = linked && MODEL_SETTINGS_PATH.test(new URL(ctx.input.page.url()).pathname) + && new URL(ctx.input.page.url()).pathname.includes(`/agents/${worker.urlKey ?? worker.id}/`); + await ctx.input.page.waitForTimeout(20_000); + refusalSamples.push(await workerRetryRuns()); state.refusalRunSamples = refusalSamples; + state.noRunWhileModelUnavailable = refusalSamples.every(count => count === 0); + state.taskBlockedAfterRefusal = (await ctx.input.api.get(`/api/issues/${task.id}`)).status === "blocked"; + const fixed = await ctx.input.api.patch(`/api/agents/${worker.id}`, { adapterConfig: { ...(state.originalAdapterConfig as Record), model: state.workingModel } }); + state.modelFixedByHuman = fixed.adapterConfig?.model === state.workingModel && fixed.adapterConfig?.model !== state.rejectedModel; + state.modelFixedAt = Date.now(); + await ctx.input.page.goto(taskURL, { waitUntil: "domcontentloaded" }); + const again = humanRetryControl(ctx.input.page); await expect(again).toBeVisible(); + const accepted = ctx.input.page.waitForResponse(r => isHumanRetryRequest(r.request(), task.id, worker.id)); + await again.click(); state.fixedRetryStatus = (await accepted).status(); const gateName = (state.gate as RuntimeBriefGate).gateName!; - const released = await pollUntil({ label: "Released Retry listens for the brief in its own workspace", deadlineAt: Date.now() + 180_000, + const released = await pollUntil({ label: "The Retry after the model fix listens for the brief in its own workspace", deadlineAt: Date.now() + 180_000, load: async () => { const retries = (await ctx.allRuns()).filter(row => row.agentId === worker.id && row.id !== state.workerRunId); const run = retries.length === 1 ? await ctx.input.api.get(`/api/heartbeat-runs/${retries[0]!.id}`) : null; - return { retries: retries.length, listener: run ? await releasedRetryListener(run, { companyId: ctx.input.fixtures.company.id, workerId: worker.id, + return { retries: retries.length, run, listener: run ? await releasedRetryListener(run, { companyId: ctx.input.fixtures.company.id, workerId: worker.id, taskId: task.id, originalRunId: String(state.workerRunId), gateName }) : null }; }, accept: v => v.retries === 1 && !!v.listener, - reject: v => v.retries > 1 ? "The held Retry started more than once" : undefined }); - const brief = { gate: released.listener!.gate }; - state.retryWorkspaceId = released.listener!.workspaceId; state.retryWorkspaceFresh = released.listener!.workspaceId !== (state.gate as RuntimeBriefGate).boundWorkspaceId; - await writeFile(brief.gate, `The authorized human has restored the execution gate. Use the preserved task context and save a non-plan website-delivery document with the exact reference Retry website ${ctx.input.nonce}, a semantic single-page Acorn website outline and an accessible signup action, then complete this original task normally. Do not create more tasks or external effects.`, "utf8"); - const completed = await pollUntil({ label: "The held Retry starts once, by itself, after actual gate restoration", deadlineAt: Date.now() + 240_000, + reject: v => v.retries > 1 ? "Try again started more than one run" : v.run && ["failed", "cancelled", "timed_out"].includes(v.run.status) ? "The retry after the model fix stopped" : undefined }); + state.retryWorkspaceId = released.listener!.workspaceId; + await writeFile(released.listener!.gate, `The authorized human fixed the model. Use the preserved task context and save a non-plan website-delivery document with the exact reference Retry website ${ctx.input.nonce}, a semantic single-page Acorn website outline and an accessible signup action, then complete this original task normally. Do not create more tasks or external effects.`, "utf8"); + const completed = await pollUntil({ label: "The one Retry after the model fix completes the original 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.runs.length === 4 && v.runs.filter(row => row.id !== state.workerRunId).every(row => row.status === "succeeded"), - reject: v => v.runs.length > 4 || v.runs.some(row => row.id !== state.workerRunId && ["failed", "cancelled", "timed_out"].includes(row.status)) ? "Eligible Retry failed or duplicated native work" : undefined }); + accept: v => v.task.status === "done" && v.runs.length === 3 && v.runs.filter(row => row.id !== state.workerRunId).every(row => row.status === "succeeded"), + reject: v => v.runs.length > 3 || v.runs.some(row => row.id !== state.workerRunId && ["failed", "cancelled", "timed_out"].includes(row.status)) ? "The retry failed or duplicated native work" : undefined }); const retried = completed.runs.filter(row => row.agentId === worker.id && row.id !== state.workerRunId); state.retryRunCount = retried.length; - const full = retried[0] && await ctx.input.api.get(`/api/heartbeat-runs/${retried[0].id}`); state.retryRunId = full?.id; + const full = retried[0] && await ctx.input.api.get(`/api/heartbeat-runs/${retried[0].id}`); state.retryRunId = full?.id; state.retryBoundToOriginal = !!full && retriesOriginalRun(full, String(state.workerRunId)) && [full.contextSnapshot?.issueId, full.contextSnapshot?.taskId].includes(task.id); - state.retryAdmissionAfterGateClear = !!full && Date.parse(String(full.createdAt)) >= Number(state.gatesClearedAt); + state.retryAdmissionAfterFix = !!full && Date.parse(String(full.createdAt)) >= Number(state.modelFixedAt); + state.retryUsedFixedModel = full?.runnerProfileJson?.nativeExecutionInput?.provider?.model === state.workingModel; await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); - const finalQuery = `I restored Morgan's budget and used the supported Retry for Website ${task.identifier ?? task.id}. What is the actual result now, and is the earlier failed attempt still retained?`; - await sendChatMessage(ctx.input.page, finalQuery, chatCatalogNativePhaseRemainingBudget(ctx)); - const final = await pollUntil({ label: "Own final source reply reports actual eligible Retry result", 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.filter(row => row.id !== state.workerRunId).every(row => row.status === "succeeded")) }); - const finalRun = final.runs.find(row => !completed.runs.some(prior => prior.id === row.id))!; - const finalReply = await phaseReply(finalQuery, finalRun.id); state.finalReply = finalReply.body; state.finalReplyAttributed = finalReply.attributed; - state.finalRecoveryRead = await controllerReadRecovery(ctx, finalRun.id, task.id, String(state.workerRunId), task.identifier); }, async observe(ctx, state) { const o = await observeRuntime(ctx, state); const before = state.failure as HeartbeatRun, retained = await ctx.input.api.get(`/api/heartbeat-runs/${state.workerRunId}`); diff --git a/tests/runner-e2e/chat-full-catalog-testops-manifest.json b/tests/runner-e2e/chat-full-catalog-testops-manifest.json index 18e7be05787..0188b251bf8 100644 --- a/tests/runner-e2e/chat-full-catalog-testops-manifest.json +++ b/tests/runner-e2e/chat-full-catalog-testops-manifest.json @@ -1205,7 +1205,13 @@ "key": "recovery.retry-exhausted", "field": "originalContext", "previous": "Automatic infrastructure attempts are exhausted and the source task exposes ordinary Retry to its authorized human.", - "current": "The website run stopped for a reason only a person can resolve (its selected model was rejected), and the person has since restored the configuration. The source task exposes ordinary Retry to its authorized human; an infrastructure fault would instead continue automatically." + "current": "The website run stopped for a reason only a person can resolve: the provider rejected its selected model, and that model is still selected. The source task exposes ordinary Retry to its authorized human; an infrastructure fault would instead continue automatically." + }, + { + "key": "recovery.retry-exhausted", + "field": "expectedOutcome", + "previous": "The response directs or presents the supported human Retry action and explains the current state. One accepted retry rechecks execution gates and preserves earlier attempt evidence. The person is not asked to certify internal infrastructure facts, and failure remains visible if the new attempt cannot start.", + "current": "The response directs or presents the supported human Retry action and explains the current state. Retry rechecks the selected model before it starts anything: while the rejected model is still selected, no new attempt starts, the failure stays visible, and the person is told which setting to change, with a link to it. After the person selects a working model, one accepted retry of the original run starts with that model, preserves the earlier attempt evidence and completes the task. The person is not asked to certify internal infrastructure facts." }, { "key": "recovery.source-action", @@ -10728,8 +10734,8 @@ "externalInput": null, "installedSource": null, "originalQuery": "Try the website task again.", - "expectedOutcome": "The response directs or presents the supported human Retry action and explains the current state. One accepted retry rechecks execution gates and preserves earlier attempt evidence. The person is not asked to certify internal infrastructure facts, and failure remains visible if the new attempt cannot start.", - "originalContext": "The website run stopped for a reason only a person can resolve (its selected model was rejected), and the person has since restored the configuration. The source task exposes ordinary Retry to its authorized human; an infrastructure fault would instead continue automatically.", + "expectedOutcome": "The response directs or presents the supported human Retry action and explains the current state. Retry rechecks the selected model before it starts anything: while the rejected model is still selected, no new attempt starts, the failure stays visible, and the person is told which setting to change, with a link to it. After the person selects a working model, one accepted retry of the original run starts with that model, preserves the earlier attempt evidence and completes the task. The person is not asked to certify internal infrastructure facts.", + "originalContext": "The website run stopped for a reason only a person can resolve: the provider rejected its selected model, and that model is still selected. The source task exposes ordinary Retry to its authorized human; an infrastructure fault would instead continue automatically.", "capabilities": [ "recovery/exhaustion" ], diff --git a/tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs b/tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs index b0ae99f389b..3f96d52131a 100644 --- a/tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs +++ b/tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs @@ -463,6 +463,10 @@ test('repair source metadata binds the corrected candidate and explicit changed "recovery.retry-exhausted", "originalContext" ], + [ + "recovery.retry-exhausted", + "expectedOutcome" + ], [ "recovery.source-action", "originalContext" diff --git a/tests/runner-e2e/chat-scenarios/recovery.yaml b/tests/runner-e2e/chat-scenarios/recovery.yaml index 44bed14bfc3..a84180042b9 100644 --- a/tests/runner-e2e/chat-scenarios/recovery.yaml +++ b/tests/runner-e2e/chat-scenarios/recovery.yaml @@ -52,17 +52,20 @@ scenarios: capabilities: - recovery/exhaustion context: >- - The website run stopped for a reason only a person can resolve (its selected model was - rejected), and the person has since restored the configuration. The source task exposes - ordinary Retry to its authorized human; an infrastructure fault would instead continue - automatically. + The website run stopped for a reason only a person can resolve: the provider + rejected its selected model, and that model is still selected. The source task + exposes ordinary Retry to its authorized human; an infrastructure fault would + instead continue automatically. query: >- Try the website task again. expected_outcome: >- - The response directs or presents the supported human Retry action and explains the current - state. One accepted retry rechecks execution gates and preserves earlier attempt evidence. - The person is not asked to certify internal infrastructure facts, and failure remains - visible if the new attempt cannot start. + The response directs or presents the supported human Retry action and explains the + current state. Retry rechecks the selected model before it starts anything: while + the rejected model is still selected, no new attempt starts, the failure stays + visible, and the person is told which setting to change, with a link to it. After + the person selects a working model, one accepted retry of the original run starts + with that model, preserves the earlier attempt evidence and completes the task. The + person is not asked to certify internal infrastructure facts. - id: recovery.workspace-repair capabilities: - recovery/workspace diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsx index e7b6728c56f..747f2d0ecac 100644 --- a/ui/src/components/TaskChatThread.test.tsx +++ b/ui/src/components/TaskChatThread.test.tsx @@ -2673,6 +2673,33 @@ describe("TaskChatThread runtime transcript selection", () => { expect(container.textContent).not.toContain("after returning a final response"); }); + it("offers Try again on a model-unavailable failure and retries that run", async () => { + const onRetryFailedRun = vi.fn(); + renderThread({ + comments: [], + onAdd: async () => {}, + issueStatus: "blocked", + onRetryFailedRun, + interruption: { intentId: null, responsibility: "user", state: "waiting_for_user", nextRetryAt: null, + canRetry: false, userAction: "choose_model", rejectedModel: "openrouter/missing", sourceRunIds: ["model-rejected"], observedRunId: "model-rejected" }, + linkedRuns: [{ + runId: "model-rejected", runtimeMode: "native", status: "failed", + errorCode: "native_provider_model_rejected", + error: "The selected model is not available.", + agentId: "agent-1", agentName: "Runner", adapterType: "paperclip_runner", + createdAt: "2026-08-25T18:00:00.000Z", startedAt: "2026-08-25T18:00:00.000Z", + finishedAt: "2026-08-25T18:00:02.000Z", + }], + }); + const marker = container.querySelector('[data-testid="task-chat-collapsible-marker"]'); + expect(marker?.textContent).toContain("Model unavailable"); + const retry = marker?.querySelector('[data-testid="task-chat-run-failed-try-again"]'); + expect(retry).not.toBeNull(); + flushSync(() => retry!.click()); + await Promise.resolve(); + expect(onRetryFailedRun).toHaveBeenCalledWith("model-rejected"); + }); + it("names the rejected model id that the task interruption carries", () => { renderThread({ comments: [], diff --git a/ui/src/components/task-chat/TaskChatThreadView.tsx b/ui/src/components/task-chat/TaskChatThreadView.tsx index fc93980dcf8..a33b045b397 100644 --- a/ui/src/components/task-chat/TaskChatThreadView.tsx +++ b/ui/src/components/task-chat/TaskChatThreadView.tsx @@ -29,7 +29,7 @@ import { TaskMessageScroller, type ScrollingHistory } from "./TaskMessageScrolle import { TaskChatProtocolCard } from "./TaskChatProtocolCard"; import { TaskChatProtocolActivityRow } from "./TaskChatProtocolActivityRow"; import { TaskChatPlanPreviewCard } from "./TaskChatPlanPreviewCard"; -import { compactAdjacentErrors } from "./adjacent-errors"; +import { compactAdjacentErrors, isRetryableFailureMarker } from "./adjacent-errors"; import { CoordinatorChatTaskHandoff } from "@/components/coordinator/CoordinatorChatTaskHandoffs"; import { CoordinatorChatDecisionReceipt } from "@/components/coordinator/CoordinatorChatDecisionReceipts"; import { CoordinatorChatPendingQuestion } from "@/components/coordinator/CoordinatorChatPendingQuestions"; @@ -347,8 +347,7 @@ export function TaskChatThreadView({ .find( (item) => { const marker = item.kind === "marker" ? item : retryMarkers.get(item.id); - return marker?.variant === "interrupted" && - (marker.label === "Run failed" || marker.label === "Usage limit reached"); + return !!marker && isRetryableFailureMarker(marker); }, )?.id : undefined; diff --git a/ui/src/components/task-chat/adjacent-errors.ts b/ui/src/components/task-chat/adjacent-errors.ts index e8ae81b86c9..3cf520086e1 100644 --- a/ui/src/components/task-chat/adjacent-errors.ts +++ b/ui/src/components/task-chat/adjacent-errors.ts @@ -54,8 +54,7 @@ export function compactAdjacentErrors(items: readonly TaskChatItem[]): { const latest = items[end - 1]; if (mixed && errorKind(latest) === "recovery") { const marker = items.slice(start, end).reverse().find( - (item): item is TaskChatMarkerItem => item.kind === "marker" - && (item.label === "Run failed" || item.label === "Usage limit reached"), + (item): item is TaskChatMarkerItem => item.kind === "marker" && isRetryableFailureMarker(item), ); // Preserve the retry target separately from the surviving error's text. // The renderer still applies the parent's permission and pending state. @@ -66,3 +65,9 @@ export function compactAdjacentErrors(items: readonly TaskChatItem[]): { } return { items: result, retryMarkers }; } + +const RETRYABLE_FAILURE_LABELS = new Set(["Run failed", "Usage limit reached", "Model unavailable"]); + +export function isRetryableFailureMarker(marker: Pick) { + return marker.variant === "interrupted" && RETRYABLE_FAILURE_LABELS.has(marker.label); +} diff --git a/ui/src/lib/model-retry-refusal.test.ts b/ui/src/lib/model-retry-refusal.test.ts new file mode 100644 index 00000000000..d7f1181959a --- /dev/null +++ b/ui/src/lib/model-retry-refusal.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { ApiError } from "../api/api-error"; +import { modelStillUnavailableToast } from "./model-retry-refusal"; + +const agent = { id: "agent-1", name: "Morgan", urlKey: "morgan" }; +const refusal = (setting: string) => new ApiError('The provider rejected the model "bad/model", and it is still selected.', 409, { + error: 'The provider rejected the model "bad/model", and it is still selected.', + details: { code: "native_provider_model_still_unavailable", setting, rejectedModel: "bad/model", agentId: "agent-1" }, +}); + +describe("modelStillUnavailableToast", () => { + it("names the setting and links to the agent's model settings", () => { + expect(modelStillUnavailableToast(refusal("agent_model"), agent)).toMatchObject({ + title: "Model still unavailable", tone: "error", + body: expect.stringContaining("still selected"), + action: { label: "Open Morgan model settings", href: "/agents/morgan/runtime" }, + }); + }); + + it("explains a task override without linking away from the task", () => { + const toast = modelStillUnavailableToast(refusal("task_model_override"), agent); + expect(toast?.title).toBe("Model still unavailable"); + expect(toast?.action).toBeUndefined(); + }); + + it("leaves other retry failures to the generic message", () => { + expect(modelStillUnavailableToast(new ApiError("Conflict", 409, { error: "Conflict" }), agent)).toBeNull(); + expect(modelStillUnavailableToast(new Error("network"), agent)).toBeNull(); + }); +}); diff --git a/ui/src/lib/model-retry-refusal.ts b/ui/src/lib/model-retry-refusal.ts new file mode 100644 index 00000000000..66dbc94cdc2 --- /dev/null +++ b/ui/src/lib/model-retry-refusal.ts @@ -0,0 +1,28 @@ +import type { ToastInput } from "../context/ToastContext"; +import { agentUrl } from "./utils"; + +export const MODEL_STILL_UNAVAILABLE_CODE = "native_provider_model_still_unavailable"; + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +export function modelStillUnavailableToast( + error: unknown, + agent: { id: string; name?: string | null; urlKey?: string | null } | undefined, +): ToastInput | null { + const details = record(record(record(error).body).details); + if (details.code !== MODEL_STILL_UNAVAILABLE_CODE) return null; + const body = error instanceof Error && error.message ? error.message : "The selected model is still unavailable."; + const agentSetting = details.setting !== "task_model_override"; + return { + title: "Model still unavailable", + body, + tone: "error", + ttlMs: 15_000, + dedupeKey: `model-still-unavailable:${String(details.agentId ?? agent?.id ?? "")}`, + ...(agentSetting && agent + ? { action: { label: `Open ${agent.name ?? "agent"} model settings`, href: `${agentUrl(agent)}/runtime` } } + : {}), + }; +} diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 52734f13868..fd6384fcfcf 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -208,6 +208,7 @@ import { } from "../lib/optimistic-issue-runs"; import { useProjectOrder } from "../hooks/useProjectOrder"; import { recordRecentTask } from "../lib/recent-tasks"; +import { modelStillUnavailableToast } from "../lib/model-retry-refusal"; import { relativeTime, cn, @@ -1687,8 +1688,9 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ queryKey: queryKeys.issues.activeRun(issueQueryRef), }); }, - onError: (error) => { - pushToast({ + onError: (error, runId) => { + const failedRun = resolvedLinkedRuns.find((run) => run.runId === runId); + pushToast(modelStillUnavailableToast(error, failedRun ? agentMap.get(failedRun.agentId) : undefined) ?? { title: "Run retry failed", body: error instanceof Error ? error.message : "Unable to retry run", tone: "error", From 9b613562b70b7bea9e7562ddc1087d4c1b1788b1 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Thu, 12 Nov 2026 19:52:02 -0800 Subject: [PATCH 07/15] feat(docker): split the Runner image into stable layers and add a slim variant (#21229) 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 Runner is the part that executes agent work: a daemon (`paperclip-runnerd`) and a provider pack of agent tools > - Part 2 of this stack builds the Runner alone as the image `runner-artifacts`, in one layer of about 850 MB > - Most of those bytes are provider binaries and Node. They change only with a provider version or the Node pin, but one layer means that every Runner source change makes all 850 MB new > - About half of the image is the pack's transport archives. A consumer that copies the pack as files does not need them > - This pull request splits the image into layers by how often their content changes, and adds a slim variant without the transport archives > - The benefit is that a new image shares about 93% of its bytes with the one before it, and a consumer that needs no transport archives pulls half as much ## Linked Issues or Issue Description Refs #21204 (part 2 of this stack) and #21167 (provider pack layers). No issue exists for this change. **Problem or motivation** The image from part 2 is one layer. A registry and a builder store and move layers, not files. A change to one Runner source file therefore makes a new 850 MB layer, although 790 MB of its content is the same as before. The image also holds the provider pack two times: as files, and as transport archives of those files. Some consumers need only the files. **Proposed solution** Write the image as four layers: the pack's large dependency files, everything else, the transport archives of those large files, and the other transport content. Make the two large layers byte-identical from build to build. Add the target `runner-artifacts-slim`, which is the first two layers. The full image is the slim image plus the two transport layers, as the same layer blobs. Check all of this on the built images. **Alternatives considered** - Two unrelated images. Then the registry stores the shared content two times unless the layers happen to match, and nothing ties the two together. - Split by path only, with all files of 1 MiB or more in the first layer. Six of those files are the Runner's own bundles under `dist`. They change with the Runner's source, so the first layer would change with it too. - Leave the transport archives as they were written. Their bytes then depended on timing (see "What Changed"), and the archive layer never repeated. **Roadmap alignment** This is build infrastructure. It adds no product feature and does not overlap an item in `ROADMAP.md`. This is part 3 of 4. Each part is on top of the one before it: 1. #21228 (merged): an optional field in the provider pack manifest 2. #21204: build and check the Runner image, with no publication 3. #21229: layers by change rate, and the slim variant (this pull request) 4. #21230: publish both variants from `master` ## What Changed - `Dockerfile`: two final stages. `runner-artifacts-slim` is two `COPY --link` layers. `runner-artifacts` starts from it and adds two more. The build stage sorts its output into the four layers. Every path is where it was in part 2: consumers copy by path and see no difference. | Layer | Content | Changes with | | --- | --- | --- | | 1 | The pack's dependency files of 1 MiB or more: provider binaries and Node | A provider version or the Node pin | | 2 | Everything else, with `runner-image.json` | Every Runner source change | | 3 (full only) | The transport archive of each file in layer 1 | The same as layer 1 | | 4 (full only) | The other transport archives, the overlay archive and the receipt | The same as layer 2 | - Stable bytes. The files of layers 1 and 3 get timestamp 0, and the large dependency files get it before their transport archives are written. A file under the pack's `dist` is the Runner's own output, so it and its archive are in layers 2 and 4. - `scripts/create-provider-pack-archive.mjs`, two separate commits. **This script also writes the application image's archives.** - The same file now gives the same archive every time. The script piped tar into Node's zstd compressor. When the pipe ended while the compressor still had its last chunk queued, Node finished the zstd stream two times, and the archive got an empty frame of nine bytes at its end. That depended on timing. In the pinned Linux base, 37 of 60 runs of the old code had the frame. The compressor is now ended only after it has taken every chunk. - Archive N holds file N of the receipt, and the receipt listed the files in path order. `dist` sorts before `node_modules`, so one more large file in the Runner's own output gave every dependency file another archive name, and layer 3 became a new blob with the same contents. The receipt now lists the files outside `dist` first. The readers (`provider-pack-layers.ts`, `retained-provider-pack-source.ts`) pair file N with `N.tar.zst` and do not use the path order, so they need no change. For the application image, the archive numbers change one time, and the bytes of each archive do not change. - `runner-image.json` is the same file in both variants. Its new field `fullImageOnly` names the two paths that only the full image has. `paths` did not change. - `scripts/runner-image-layout.mjs check` takes `--variant slim|full`. It is required and has no default. A slim tree that holds a transport path fails. A full tree without them fails. - `scripts/runner-image-oci.mjs` (new, 585 lines). It is not an input of the image, because the image build does not run it. - `unpack --out ` writes the tree of an image from the layers of its archive, in order. It checks every blob against its digest. It refuses a whiteout, an absolute path, a path with `..`, a path that is written two times, an entry behind a link, and every entry that is not a file, a directory or a link. - `check-layers --slim --full ` checks the table above on the built images. It reads the receipt to decide which archive belongs in which layer. It fails when the full image does not start with the slim image's layer blobs in the same order, when a path that is not a directory is in two layers, and when a shared layer holds transport content under any name or directory. - The script reads the archive and its layers itself. It does not use the system's `tar`, so every platform reads them the same way. It finds a member only under the name that buildx gives it. - `.github/workflows/runner-image.yml`: each leg builds each variant one time, as an OCI archive and nothing else. It unpacks both archives, runs `check` on each tree with its variant, runs `check-layers`, and runs the smoke matrix on the slim tree. The tree that is checked is therefore the bytes of the image, not a second export of the same build. Every step that builds has a time limit. The workflow still has no registry access. - Why one export: in the first runs of this pull request, the slim build stalled on all four legs. Each build command had two exports, a tree and an archive. The slim command, with every stage from the cache, wrote its archive and then made no progress on the tree for 50 minutes. A test now holds the rule of one export and a time limit for each build command. - The smoke matrix runs on the slim tree. The daemon is in a layer that both variants share, so one run covers both. - `server/src/__tests__/runner-image-identity.test.ts`: the test that holds the rules for the Runner stages now finds a stage wherever BuildKit starts one. It fails for `FROM x as name`, a flag on `FROM`, a lowercase or indented `COPY`, an `ADD` or `ONBUILD`, a `COPY` with another flag, and a `COPY` that continues on the next line. Nine samples show each case. - Two comments are corrected. The comment on `PAPERCLIP_RUNNER_INPUTS_DIGEST` in `build-provider-pack.mjs` said that no check reads the field. The `Dockerfile` comment on the publication argument named a workflow "that builds the image for publication". - `doc/runner-image-contract.md` (159 lines): the two variants, the section "Layers", how the checks get their tree, and the new checks. `doc/DOCKER.md` names the slim target. Script sizes: `runner-image-layout.mjs` 969 lines, `runner-image-oci.mjs` 585, `runner-image-identity.mjs` 166, `create-provider-pack-archive.mjs` 114. ## Verification Image identity at this commit: `a544fc9dde780963419ede0f34252f3a57de43a760d41d3eb8fcd4f577504f6a`. Linux (the pinned `node:24.22.3-bookworm` base with GNU tar 1.34 and zstd, the worktree mounted read-only): - `runner-image-identity.test.ts` (41), `runner-image-layout.test.ts` (100), `runner-image-oci.test.ts` (50), `runner-image-workflow.test.ts` (8), `provider-pack-archive.test.ts` (47, none skipped), `retained-provider-pack-source.test.ts` (19), `remote-provider-pack-verification.test.ts`, `docker-image-layer-reuse.test.ts`, `docker-build-stamp.test.ts`: 293 tests pass in 9 files. - The same files pass on macOS. The tests of `check-layers` failed on Linux in the first runs of this pull request: their fixtures named the archive members `./index.json`, which bsdtar finds and GNU tar does not. The fixtures now name the members as buildx does. `linux/arm64`, on a local Docker host, with the new export path: - Each variant builds as an OCI archive only: the full target in 156 seconds without a cache, the slim target in 5 seconds from the cache. - `unpack` writes the full image (10,519 entries that are not directories) in 4 seconds, and the slim image in 4 seconds. - `check --variant --expect-inputs-digest --expect-source-revision --expect-architecture arm64` passes on each unpacked tree. `runner-image.json` is the same file in both. - `check-layers --slim --full ` passes. - The smoke matrix passes on all five base images, from the unpacked slim tree. | Layer | Digest | Bytes | In | | --- | --- | --- | --- | | 1 | `sha256:3f21b15b3a99…70ac1c` | 379,609,589 | slim and full | | 2 | `sha256:d5567acc977f…b4f12a` | 43,906,956 | slim and full | | 3 | `sha256:6a340088ca2c…6ba5b5` | 410,938,259 | full | | 4 | `sha256:789e97f5db88…3eab44` | 15,656,249 | full | - The slim image is 423,516,545 bytes in two layers. The full image is 850,111,053 bytes in four. Stability, with three builds that share no cache for the build step: | Build | Source revision | Runner build output | Layer 1 | Layer 2 | Layer 3 | Layer 4 | | --- | --- | --- | --- | --- | --- | --- | | A | `aaaa…` | this commit: 6 files of 1 MiB or more under `dist` | `3f21b15b…` | `d5567acc…` | `6a340088…` | `789e97f5…` | | B | `bbbb…` | this commit | `3f21b15b…` | `a2f8a4fe…` | `6a340088…` | `4e6c492d…` | | D | `dddd…` | one new source file that adds two large files under `dist` | `3f21b15b…` | `33b0bdaf…` | `6a340088…` | `0ea322bf…` | - Layers 1 and 3 are byte-identical in all three: 790,547,848 of 850,111,053 bytes, 93%. Build D has two more large files under `dist`, eight in place of six, and another image identity. Its dependency files keep the archive numbers 0 to 20. With the earlier numbering, those numbers moved by two, and layer 3 was a new blob with the same contents. - Layer 1 has the same digest as before this round. Layer 3 has a new digest one time, because the archives have new numbers. Other checks: - `tests/runner-e2e` workflow tests: 39 pass. `node --test .github/scripts/tests/*.test.mjs`: 799 pass. `node --test` on the image contract scripts: 33 pass. `check-docker-deps-stage.mjs`, `check-node-version-policy.mjs` and `docker buildx build --check` report nothing. GitHub, at this head: - The `Runner image` workflow passes on both architectures with the new export path: `Build and check (amd64)` in 14m41s and `Build and check (arm64)` in 8m41s. Each leg builds both variants, checks both layouts and the layer rule, and runs the smoke matrix. The first runs of this pull request stalled in the slim export before any check. Never run: - `native-session-executor.test.ts`. It does not load on this host, with or without this change, because `@paperclipai/plugin-sdk` is not built here. It imports the reader of the retained pack and no archive number. - The full test suite and the full typecheck. CI must supply them. ## Risks - The two changes to `create-provider-pack-archive.mjs` change the application image's transport archives: about half of them lose nine bytes, and all of them get new numbers one time. An archive's content does not change. A reader pairs file N of a receipt with archive N of the same build. - The large dependency files in the pack, and in their transport archives, now have the modification time 0 (1970). Before, they had the build time. Nothing in this repository reads those times. - `unpack` is a reader of tar and gzip that this repository owns. It reads the layers that BuildKit, GNU tar and bsdtar write (tested with each), and it fails for a header it does not know. - The check on the built images, not the recipe, is what proves the layer rule; it runs in each leg of the workflow. - `check` now needs `--variant`. A caller that does not pass it fails with a clear message. No caller exists outside this repository yet. > 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 Fable 5.2 (`claude-fable-5-2`), Anthropic, used through Claude Code with tool use (shell, file edits, local Docker builds). ## 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 Fable 5.2 --- .github/workflows/runner-image.yml | 104 +++- Dockerfile | 64 +- doc/DOCKER.md | 7 +- doc/runner-image-contract.md | 68 +- .../scripts/build-provider-pack.mjs | 9 +- scripts/create-provider-pack-archive.mjs | 24 +- scripts/runner-image-layout.mjs | 61 +- scripts/runner-image-oci.mjs | 585 ++++++++++++++++++ .../__tests__/runner-image-identity.test.ts | 66 +- .../src/__tests__/runner-image-layout.test.ts | 70 ++- server/src/__tests__/runner-image-oci.test.ts | 360 +++++++++++ .../__tests__/runner-image-workflow.test.ts | 17 +- .../provider-pack-archive.test.ts | 50 ++ 13 files changed, 1391 insertions(+), 94 deletions(-) create mode 100644 scripts/runner-image-oci.mjs create mode 100644 server/src/__tests__/runner-image-oci.test.ts diff --git a/.github/workflows/runner-image.yml b/.github/workflows/runner-image.yml index ccbf4c69460..c8855371fad 100644 --- a/.github/workflows/runner-image.yml +++ b/.github/workflows/runner-image.yml @@ -1,8 +1,9 @@ name: Runner image # Builds and checks the Runner image: the `runner-artifacts` target of the -# Dockerfile, a plain file tree that other image builds copy the Runner from. -# doc/runner-image-contract.md is the contract. +# Dockerfile, a plain file tree that other image builds copy the Runner from, +# and its `runner-artifacts-slim` variant without the pack's transport +# archives. doc/runner-image-contract.md is the contract. # # This workflow builds and checks only. It has no access to a registry and # publishes nothing. @@ -28,6 +29,7 @@ on: - scripts/link-plugin-dev-sdk.mjs - scripts/runner-image-identity.mjs - scripts/runner-image-layout.mjs + - scripts/runner-image-oci.mjs - docker/runner-image/** workflow_dispatch: @@ -96,6 +98,7 @@ jobs: # files the image build never receives. - name: Compute the identity in the build context id: identity + timeout-minutes: 10 run: | set -euo pipefail out="$RUNNER_TEMP/runner-image-identity" @@ -185,44 +188,93 @@ jobs: mirrors = ["mirror.gcr.io"] # The build itself runs the frozen install, the Runner's own build, the - # provider pack integrity check and the layout check. The tree is - # exported for the checks below. + # provider pack integrity check and the layout check. + # + # Both variants come from one build: the second command only reads the + # cache of the first. Each is exported once, as an OCI archive and + # nothing else. A command with two exports, an archive and a tree, + # stalled on these runners when every stage came from the cache, so a + # command has one export, and the step has a time limit: a cold build + # takes about ten minutes. # # This is the publication form of the build, the only one whose pack # names the image (`runnerInputsDigest`), so the check below can bind # the tree to the digest the identity job resolved. Nothing here - # publishes it: the tree stays on this runner. - - name: Build the Runner image + # publishes it: the archives and trees stay on this runner. + - name: Build both variants of the Runner image + timeout-minutes: 30 run: | set -euo pipefail - docker buildx build \ - --target runner-artifacts \ - --platform "$PLATFORM" \ - --build-arg "PAPERCLIP_RUNNER_SOURCE_REVISION=$GITHUB_SHA" \ - --build-arg PAPERCLIP_RUNNER_IMAGE_PUBLICATION=1 \ - --provenance=false --sbom=false \ - --output "type=local,dest=$RUNNER_TEMP/runner-image/tree" \ - . + for variant in full slim; do + target=runner-artifacts + if [ "$variant" = slim ]; then target=runner-artifacts-slim; fi + docker buildx build \ + --target "$target" \ + --platform "$PLATFORM" \ + --build-arg "PAPERCLIP_RUNNER_SOURCE_REVISION=$GITHUB_SHA" \ + --build-arg PAPERCLIP_RUNNER_IMAGE_PUBLICATION=1 \ + --provenance=false --sbom=false \ + --output "type=oci,dest=$RUNNER_TEMP/runner-image/$variant.oci.tar" \ + . + done - # Against the exported tree, bound to this run: the digest the identity - # job resolved, this commit and this leg's architecture. Checks every - # documented path, the build stamp, every pack artifact and tree digest - # in provider-pack.json, and every transport archive. It also extracts - # the archives as a sandbox does and compares the result with the pack; - # that needs about as much free disk as the pack is large. - - name: Check the layout contract and pack integrity + # The trees the checks below read are the layers of those archives, + # written out in order. They are the bytes of the images themselves, + # not a second export of the build, and each blob is checked against + # its digest as it is read. + - name: Unpack both images + timeout-minutes: 10 run: | - node scripts/runner-image-layout.mjs check "$RUNNER_TEMP/runner-image/tree" \ - --expect-inputs-digest "$DIGEST" \ - --expect-source-revision "$GITHUB_SHA" \ - --expect-architecture "$ARCH" + set -euo pipefail + for variant in full slim; do + node scripts/runner-image-oci.mjs unpack "$RUNNER_TEMP/runner-image/$variant.oci.tar" \ + --out "$RUNNER_TEMP/runner-image/$variant" + done + # Against each unpacked tree, bound to this run: the digest the identity + # job resolved, this commit and this leg's architecture. Checks every + # documented path, the build stamp, and every pack artifact and tree + # digest in provider-pack.json. A slim tree must not hold the transport + # archives. A full tree must: the check verifies each one, extracts + # them as a sandbox does and compares the result with the pack; that + # needs about as much free disk as the pack is large. + - name: Check the layout contract and pack integrity + timeout-minutes: 10 + run: | + set -euo pipefail + for variant in full slim; do + node scripts/runner-image-layout.mjs check "$RUNNER_TEMP/runner-image/$variant" \ + --variant "$variant" \ + --expect-inputs-digest "$DIGEST" \ + --expect-source-revision "$GITHUB_SHA" \ + --expect-architecture "$ARCH" + done + + # The full image must be the slim image's layers, as the same blobs, + # then the transport layers, with nothing else in them. No file may be + # in two layers. + - name: Check the layers of both variants + timeout-minutes: 10 + run: | + set -euo pipefail + { + echo '```' + node scripts/runner-image-oci.mjs check-layers \ + --slim "$RUNNER_TEMP/runner-image/slim.oci.tar" \ + --full "$RUNNER_TEMP/runner-image/full.oci.tar" + echo '```' + } | tee -a "$GITHUB_STEP_SUMMARY" + + # On the slim tree: the daemon is in a layer both variants share, so + # one run covers both, and the slim tree is the smaller one to load. + # This command has one export, a few small files. - name: Run the daemon on every consumer base image + timeout-minutes: 20 run: | docker buildx build \ --file docker/runner-image/Dockerfile.smoke \ --platform "$PLATFORM" \ - --build-context "runner-artifacts=$RUNNER_TEMP/runner-image/tree" \ + --build-context "runner-artifacts=$RUNNER_TEMP/runner-image/slim" \ --output "type=local,dest=$RUNNER_TEMP/runner-image/smoke" \ docker/runner-image ls -l "$RUNNER_TEMP/runner-image/smoke" diff --git a/Dockerfile b/Dockerfile index f4905a76709..d30284ec19f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -206,8 +206,9 @@ RUN mkdir -p /provider-pack-large \ # stage, so a change outside the Runner's inputs leaves them cached, and the # default targets never build them. # -# Consumers must only `COPY --from=runner-artifacts `. A build can then -# replace the stage with an image built earlier: +# Consumers must only `COPY --from=runner-artifacts `, or from +# `runner-artifacts-slim`, the same tree without the pack's transport +# archives. A build can then replace the stage with an image built earlier: # --build-context runner-artifacts=docker-image://ghcr.io/paperclipai/paperclip-runner@sha256: # # The image identity is a digest of this whole file and of every file under @@ -302,10 +303,11 @@ COPY --from=runner-artifacts-identity /runner-image-identity.json /runner-image- # the Runner build but no provider pack, as in the `runner-provider-pack` stage. ARG PAPERCLIP_RUNNER_SOURCE_REVISION="" ARG PAPERCLIP_BUILD_COMMIT="" -# Set to 1 only by the workflow that builds the image for publication. Only -# then does the pack record `runnerInputsDigest`, the name of the published -# image. Another image build that runs this stage inline, with -# PAPERCLIP_BUILD_COMMIT, builds the same Runner but must not claim to be it. +# Set to 1 only by .github/workflows/runner-image.yml, which builds the +# publication form of the image. Only then does the pack record +# `runnerInputsDigest`, the identity of this image. Another image build that +# runs this stage inline, with PAPERCLIP_BUILD_COMMIT, builds the same Runner +# but must not claim to be this image. ARG PAPERCLIP_RUNNER_IMAGE_PUBLICATION="" # One layer: the install tree and the pnpm store are removed before the layer # is committed, and the pack is granted a+rX in the layer that writes it (see @@ -323,6 +325,12 @@ ARG PAPERCLIP_RUNNER_IMAGE_PUBLICATION="" # The install is frozen: the identity above covers pnpm-lock.yaml as the build # received it, and resolving again here would build from a lockfile the # identity never saw. +# +# The pack's large dependency files get a fixed timestamp before their +# transport archives are written, so each archive has the same bytes while its +# file does. The last commands sort the tree into the layers of the two final +# stages. `dist` is what the Runner's own build writes: its large files change +# with the Runner's source, so they stay with the content that does. RUN set -eu; \ revision="${PAPERCLIP_RUNNER_SOURCE_REVISION:-${PAPERCLIP_BUILD_COMMIT}}"; \ publication="${PAPERCLIP_RUNNER_IMAGE_PUBLICATION}"; \ @@ -340,13 +348,14 @@ RUN set -eu; \ pnpm run build:binary; \ node scripts/record-build-inputs.mjs --finish; \ cd /workspace; \ - mkdir -p /out; \ + mkdir -p /out /out-large /out-archives /out-transport; \ if [ -n "$revision" ]; then \ if [ -n "$publication" ]; then \ PAPERCLIP_RUNNER_INPUTS_DIGEST="$(node -p 'require("/runner-image-identity.json").digest')"; \ export PAPERCLIP_RUNNER_INPUTS_DIGEST; \ fi; \ PAPERCLIP_RUNNER_SOURCE_REVISION="$revision" node packages/paperclip-runner/scripts/build-provider-pack.mjs /out/provider-pack; \ + find /out/provider-pack -path /out/provider-pack/dist -prune -o -type f -size +1048575c -exec touch -d @0 {} +; \ node scripts/create-provider-pack-archive.mjs /out/provider-pack; \ node_modules/.bin/esbuild /out/provider-pack/dist/live/runnerd-codex-transport.js \ --bundle --platform=node --format=esm --log-level=warning \ @@ -354,20 +363,53 @@ RUN set -eu; \ --outfile=/out/bundles/runnerd-codex-transport.mjs; \ node scripts/runner-image-layout.mjs write --out /out --workspace /workspace --identity /runner-image-identity.json --source-revision "$revision" ${publication:+--publication}; \ chmod -R a+rX /out; \ - node scripts/runner-image-layout.mjs check /out --expect-source-revision "$revision" ${publication:+--expect-inputs-digest "$PAPERCLIP_RUNNER_INPUTS_DIGEST"}; \ + node scripts/runner-image-layout.mjs check /out --variant full --expect-source-revision "$revision" ${publication:+--expect-inputs-digest "$PAPERCLIP_RUNNER_INPUTS_DIGEST"}; \ cd / && /out/provider-pack/node_modules/node/bin/node --input-type=module -e 'const transport = await import("/out/bundles/runnerd-codex-transport.mjs"); if (typeof transport.createCapabilityRunnerdCodexTransport !== "function") process.exit(1);'; \ else \ echo "Skipping the provider pack: supply a full PAPERCLIP_RUNNER_SOURCE_REVISION or PAPERCLIP_BUILD_COMMIT to build a complete Runner image"; \ node scripts/runner-image-layout.mjs write --out /out --workspace /workspace --identity /runner-image-identity.json; \ chmod -R a+rX /out; \ - node scripts/runner-image-layout.mjs check /out --allow-unstamped; \ + node scripts/runner-image-layout.mjs check /out --variant full --allow-unstamped; \ fi; \ /out/paperclip-runnerd --build-metadata > /dev/null; \ + cd /out; \ + find provider-pack -path provider-pack/dist -prune -o -type f -size +1048575c \ + -exec sh -c 'mkdir -p "/out-large/$(dirname "$1")" && mv "$1" "/out-large/$1"' _ {} \; ; \ + if [ -f provider-pack.archive.json ]; then \ + mkdir -p /out-archives/provider-pack.archives /out-transport; \ + node -e 'for (const [index, file] of require("/out/provider-pack.archive.json").files.entries()) if (!file.path.startsWith("dist/")) console.log(index)' > /tmp/stable-archives; \ + while read -r index; do mv "provider-pack.archives/$index.tar.zst" /out-archives/provider-pack.archives/; done < /tmp/stable-archives; \ + rm /tmp/stable-archives; \ + mv provider-pack.archives provider-pack.archive.json /out-transport/; \ + fi; \ + find /out-large /out-archives -exec touch -h -d @0 {} +; \ cd /; \ rm -rf /workspace /root/.local/share/pnpm /root/.cache -FROM scratch AS runner-artifacts -COPY --from=runner-artifacts-build /out/ / +# Two variants of one build. Both are plain file trees, and each `COPY --link` +# is one layer, independent of the layers under it. The layers are split by +# how often their content changes, so a new image shares its large layers with +# the one before it; the stage above gives the files of layers 1 and 3 a fixed +# timestamp, so those layers have the same bytes whenever their files do. +# 1. provider pack dependency files of 1 MiB or more (provider binaries and +# Node), which change with a provider version or the Node pin; +# 2. everything else, which changes with every Runner source change. +# `runner-artifacts-slim` is these two layers: the Runner without the pack's +# transport form. `runner-artifacts` is the same two layers, then +# 3. the transport archive of each file in layer 1, as stable as layer 1; +# 4. the other transport archives, the overlay archive and the receipt, +# which change with layer 2. +# Layers 3 and 4 hold the transport archives and their receipt and nothing +# else, so a reader can fetch all of them without the pack. +# `runner-image-oci.mjs check-layers` checks all of this on built images. +# Every path is where it would be in a single layer; consumers copy by path. +FROM scratch AS runner-artifacts-slim +COPY --link --from=runner-artifacts-build /out-large/ / +COPY --link --from=runner-artifacts-build /out/ / + +FROM runner-artifacts-slim AS runner-artifacts +COPY --link --from=runner-artifacts-build /out-archives/ / +COPY --link --from=runner-artifacts-build /out-transport/ / FROM base AS production ARG USER_UID=1000 diff --git a/doc/DOCKER.md b/doc/DOCKER.md index f487b3a0c86..b208d6df269 100644 --- a/doc/DOCKER.md +++ b/doc/DOCKER.md @@ -81,9 +81,10 @@ image before rollout. Resolve immutable digests instead of deploying mutable tag The `runner-artifacts` target builds the Runner alone: the daemon, the Runner package's build output, the remote provider pack and its transport archives. -It does not depend on the server or UI build, and no other target depends on -it yet. `.github/workflows/runner-image.yml` builds and checks it on pull -requests, for Linux AMD64 and ARM64. See +The `runner-artifacts-slim` target is the same image without the transport +archives. Neither depends on the server or UI build, and no other target +depends on them yet. `.github/workflows/runner-image.yml` builds and checks +both on pull requests, for Linux AMD64 and ARM64. See [`doc/runner-image-contract.md`](runner-image-contract.md) for the layout, the identity rules and how to consume the image. diff --git a/doc/runner-image-contract.md b/doc/runner-image-contract.md index 9166512b91e..f6263aedba5 100644 --- a/doc/runner-image-contract.md +++ b/doc/runner-image-contract.md @@ -1,10 +1,14 @@ # Runner image contract The Runner image is the Runner built alone, as a plain file tree with no -entrypoint and no operating system: the `runner-artifacts` target of the -`Dockerfile`. An image build copies paths out of it instead of compiling the -Runner again. Its name is `ghcr.io/paperclipai/paperclip-runner`. Nothing in -this repository consumes it yet. +entrypoint and no operating system. An image build copies paths out of it +instead of compiling the Runner again. Nothing in this repository consumes it +yet. Its name is `ghcr.io/paperclipai/paperclip-runner`, and one build makes +two variants: + +- full, the `runner-artifacts` target of the `Dockerfile`: every path below; +- slim, the `runner-artifacts-slim` target: the same without the two paths + marked "full only", the provider pack's transport archives. Nothing publishes it yet: `.github/workflows/runner-image.yml` builds and checks it. @@ -19,8 +23,8 @@ Every path a consumer may copy (`RUNNER_IMAGE_PATHS` in | `/runner-image.json` | Identity and description of this image. | | `/paperclip-runnerd` | The daemon. A stripped release binary, mode `0755`. | | `/provider-pack/` | The remote provider pack, with `provider-pack.json`. | -| `/provider-pack.archive.json` | Receipt of the pack's transport archives. | -| `/provider-pack.archives/` | The transport archives the receipt lists. | +| `/provider-pack.archive.json` | Full only. Receipt of the pack's transport archives. | +| `/provider-pack.archives/` | Full only. The transport archives the receipt lists. | | `/runner-package/package.json` | The Runner package manifest. | | `/runner-package/dist/` | The Runner's complete build output. `dist/bin/paperclip-runnerd` is the same file as `/paperclip-runnerd`. | | `/runner-package/node_modules/.cache/paperclip-runner-build-inputs.json` | The build stamp the Runner's build recorded for that output. | @@ -31,7 +35,8 @@ Every path a consumer may copy (`RUNNER_IMAGE_PATHS` in | `/pnpm-lock.yaml` | The lockfile the image was installed from. | Paths under `/runner-package/` keep their place inside -`packages/paperclip-runner`. `runner-image.json` describes one platform: +`packages/paperclip-runner`. `runner-image.json` describes one platform, and +is the same file in both variants: - `inputsDigest` (the identity below) and `buildInputsDigest` (the digest in the Runner's build stamp); @@ -45,12 +50,28 @@ Paths under `/runner-package/` keep their place inside was compiled on (Debian bookworm, the oldest a consumer runs) and the newest glibc version it needs; - `providerPack`: the pack's digest and target; -- `paths` and `sha256`: the table above, and the digest of every single file. +- `paths` and `sha256`: the table above, and the digest of every single file; +- `fullImageOnly`: the names in `paths` that only the full image has. + +## Layers + +1. The pack's dependency files of 1 MiB or more: provider binaries and Node. +2. Everything else, with `runner-image.json`. +3. Full only: the transport archive of each file in layer 1. +4. Full only: the other transport archives, the overlay archive, the receipt. + +The slim image is layers 1 and 2. The full image is those same two layer +blobs, then layers 3 and 4, which hold transport content and nothing else. +Layers 1 and 3 have the same bytes in every build with the same dependency +files, so a new image shares them with the one before it. A large file under +the pack's `dist` is the Runner's own output: it and its archive are in +layers 2 and 4. An archive is named by its file's place in the receipt, which +lists the dependency files first, so their names do not depend on `dist`. ## Identity -An image is named `inputs-`. `scripts/runner-image-identity.mjs` -computes the digest from: +Both variants are named by one digest, `inputs-`: the variant is not +part of the identity. `scripts/runner-image-identity.mjs` computes it from: - every file under the paths the build copies from the build context (`RUNNER_IMAGE_CONTEXT_INPUTS`, which include `pnpm-lock.yaml`): path, @@ -76,8 +97,16 @@ pull-request runs resolve it first. For a local build, run ## Checks -`node scripts/runner-image-layout.mjs check ` runs in the build and -again on the exported tree. It fails unless: +CI builds each variant as an OCI archive and nothing else. +`node scripts/runner-image-oci.mjs unpack --out ` writes +the tree of an image from its layers, so the tree CI checks is the bytes of +the image. It refuses a whiteout, an absolute or `..` path, a path written +twice and an entry behind a link. + +`node scripts/runner-image-layout.mjs check --variant slim|full` runs +in the build and again on each unpacked tree. The variant has no default: a +slim tree with the transport paths fails, and so does a full tree without +them. The check fails unless: - every documented path exists, matches its digest in `runner-image.json`, and resolves inside the tree; @@ -87,12 +116,15 @@ again on the exported tree. It fails unless: image's revision and platform; - the pack names the inputs digest in a publication build and in no other. `--expect-inputs-digest` fails on any other build; -- every transport archive matches its receipt, and the archives - extract to the pack. The check extracts them as a sandbox does (GNU tar +- in a full image, every transport archive matches its receipt, and the + archives extract to the pack. The check extracts them as a sandbox does (GNU tar with the options in `provider-pack-layers.ts`) and compares paths, content, link targets and all twelve permission bits, after the `a+rX` grant the build makes once the archives are written. +`node scripts/runner-image-oci.mjs check-layers --slim --full ` +checks "Layers" on the two archives, and that no file is in two layers. + The build also runs `paperclip-runnerd --build-metadata` on every base image in `docker/runner-image/Dockerfile.smoke`. Add a base there before a consumer uses it. @@ -107,10 +139,10 @@ FROM debian:trixie-slim COPY --from=runner-artifacts /paperclip-runnerd /usr/local/bin/paperclip-runnerd ``` -A Dockerfile with a `runner-artifacts` stage of its own, as in this -repository, can take a built image or tree in its place with -`--build-context runner-artifacts=`. The stage is then -not built. +A Dockerfile with a `runner-artifacts` or `runner-artifacts-slim` stage of +its own, as in this repository, can take a built image or tree in its place +with `--build-context =`. The stage is then not +built. ## Known limits diff --git a/packages/paperclip-runner/scripts/build-provider-pack.mjs b/packages/paperclip-runner/scripts/build-provider-pack.mjs index e68ec58baf5..50c9b204a5a 100644 --- a/packages/paperclip-runner/scripts/build-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/build-provider-pack.mjs @@ -284,9 +284,12 @@ try { : spawnSync("git", ["diff", "--quiet", "--", "packages/paperclip-runner"], { cwd: workspaceRoot, }).status !== 0; - // Set only by the Runner image build (the `runner-artifacts` Dockerfile - // target): the identity of the inputs the image was built from, which is its - // `inputs-` tag. No check reads it. + // Set only by a publication build of the Runner image (the + // `runner-artifacts` Dockerfile target with + // PAPERCLIP_RUNNER_IMAGE_PUBLICATION=1): the identity of the inputs the image + // was built from, which is its `inputs-` tag. + // scripts/runner-image-layout.mjs checks it against the image, and refuses + // it in a pack from any other build. const runnerInputsDigest = process.env.PAPERCLIP_RUNNER_INPUTS_DIGEST?.trim(); if (runnerInputsDigest && !/^[0-9a-f]{64}$/.test(runnerInputsDigest)) { throw new Error("PAPERCLIP_RUNNER_INPUTS_DIGEST must be 64 hexadecimal characters"); diff --git a/scripts/create-provider-pack-archive.mjs b/scripts/create-provider-pack-archive.mjs index b599ea169ef..684849050de 100644 --- a/scripts/create-provider-pack-archive.mjs +++ b/scripts/create-provider-pack-archive.mjs @@ -62,6 +62,14 @@ export async function createProviderPackLayers(root) { } }; await visit(); + // Archive N holds file N, so a file's archive name is its place in this + // list. The pack's `dist` is the Runner's own build output; every other + // large file is a dependency. The dependencies come first, so that their + // archive names do not change when the Runner's build gains or loses a + // large file. `dist` sorts before `node_modules`: in path order alone, one + // more large file under it renamed every dependency archive. + const own = file => file.path.startsWith('dist/'); + files.splice(0, files.length, ...files.filter(file => !own(file)), ...files.filter(own)); const archive = async (name, paths) => { const target = resolve(directory, name); // Explicit NUL-separated names and no recursion avoid options, duplicate @@ -74,10 +82,20 @@ export async function createProviderPackLayers(root) { }); tar.stdin.on('error', () => {}); // The child/pipeline supplies the causal failure. tar.stdin.end(paths.map(path => `./${path}\0`).join('')); + // The compressor is ended only after it has taken every chunk. When end() + // arrives while the last chunk is still queued, Node finishes the zstd + // stream twice and the archive gets an empty frame at its end. Piping + // leaves that to timing, so the same files gave two different archives. + const compress = createZstdCompress({ params: { [constants.ZSTD_c_compressionLevel]: 3 } }); + const feed = async () => { + for await (const chunk of tar.stdout) { + await new Promise((resolve, reject) => compress.write(chunk, error => error ? reject(error) : resolve())); + } + compress.end(); + }; try { - await Promise.all([completed, pipeline(tar.stdout, - createZstdCompress({ params: { [constants.ZSTD_c_compressionLevel]: 3 } }), createWriteStream(target))]); - } catch (error) { tar.kill(); throw error; } + await Promise.all([completed, feed(), pipeline(compress, createWriteStream(target))]); + } catch (error) { tar.kill(); compress.destroy(); throw error; } const hash = createHash('sha256'); for await (const chunk of createReadStream(target)) hash.update(chunk); return { sha256: hash.digest('hex'), bytes: (await stat(target)).size }; diff --git a/scripts/runner-image-layout.mjs b/scripts/runner-image-layout.mjs index b1098914818..974e2c41f77 100644 --- a/scripts/runner-image-layout.mjs +++ b/scripts/runner-image-layout.mjs @@ -14,15 +14,20 @@ // check verifies a built tree: every documented path, runner-image.json, // the build stamp, the provider pack's integrity and its transport // archives. The image build runs it, and CI runs it again on the -// tree it exported. No checked path may resolve outside the tree. +// tree of each built image (scripts/runner-image-oci.mjs unpacks +// it). No checked path may resolve outside the tree. // It also extracts the transport archives the way a sandbox does and // compares the result with the provider pack, so an archive set that // has the recorded bytes but not the pack's files does not pass. // +// The image has two variants. `slim` is everything but the transport archives +// and their receipt; `full` adds those. `check` must be told which one it +// reads: a slim tree with archives fails, and so does a full tree without. +// // Usage: // node scripts/runner-image-layout.mjs write --out DIR --workspace DIR --identity FILE // [--source-revision SHA] [--publication] -// node scripts/runner-image-layout.mjs check DIR [--allow-unstamped] +// node scripts/runner-image-layout.mjs check DIR --variant slim|full [--allow-unstamped] // [--expect-inputs-digest HEX] [--expect-source-revision SHA] [--expect-architecture ARCH] // An unknown flag, a repeated flag or a flag with an empty value is an error: // an expectation that was not really given must not pass as one that held. @@ -89,6 +94,11 @@ export const RUNNER_IMAGE_PATHS = Object.freeze({ lockfile: "pnpm-lock.yaml", }); +/** The two variants of the image. `full` is `slim` plus the paths below. */ +export const RUNNER_IMAGE_VARIANTS = Object.freeze(["slim", "full"]); +/** Names in RUNNER_IMAGE_PATHS that only the full image has: the pack's transport form. */ +export const RUNNER_IMAGE_FULL_ONLY_PATHS = Object.freeze(["providerPackArchiveReceipt", "providerPackArchives"]); + const DIRECTORY_PATHS = new Set(["providerPack", "providerPackArchives", "runnerPackage", "runnerDist"]); /** Paths that exist only when the build was given a source revision. */ const STAMPED_ONLY_PATHS = new Set([ @@ -311,6 +321,8 @@ export function writeRunnerImageManifest({ libc: { family: "glibc", baseline: libc.baseline, buildVersion: libc.buildVersion, runnerdRequires: libc.runnerdRequires }, providerPack: pack === null ? null : { digest: pack.digest, target: pack.payload?.target ?? null }, paths: { ...RUNNER_IMAGE_PATHS }, + // This file is the same in both variants, so it names what only one has. + fullImageOnly: [...RUNNER_IMAGE_FULL_ONLY_PATHS], sha256, }; const manifestPath = resolveIn(outRoot, RUNNER_IMAGE_PATHS.manifest); @@ -387,6 +399,9 @@ function checkManifestShape(manifest, problems, { allowUnstamped }) { if (canonicalJson(manifest.paths ?? null) !== canonicalJson(RUNNER_IMAGE_PATHS)) { problems.push("paths does not match the documented layout (RUNNER_IMAGE_PATHS)"); } + if (canonicalJson(manifest.fullImageOnly ?? null) !== canonicalJson(RUNNER_IMAGE_FULL_ONLY_PATHS)) { + problems.push("fullImageOnly does not name the paths only the full image has (RUNNER_IMAGE_FULL_ONLY_PATHS)"); + } if (!manifest.sha256 || typeof manifest.sha256 !== "object") problems.push("sha256 must map file paths to their digests"); return stamped; } @@ -579,7 +594,7 @@ function treeEntries(root) { } /** Up to five examples and the count, so one wrong archive does not print the whole pack. */ -function summarize(problems, label, items) { +export function summarize(problems, label, items) { if (items.length === 0) return; const shown = items.slice(0, 5).join(", "); problems.push(`${label} (${items.length}): ${shown}${items.length > 5 ? ", ..." : ""}`); @@ -746,22 +761,27 @@ export async function checkProviderPackArchives(root) { * Verifies the tree at `root` against the layout contract. Returns every * problem found; an empty list means the tree is a valid Runner image. * It reads the transport archives' bytes but does not extract them: - * checkProviderPackArchives does, and the `check` command runs both. + * checkProviderPackArchives does, and the `check` command runs both on a + * full image. `variant` has no default: a slim image must not hold the + * transport archives, and a full image must. * @param {string} root * @param {{ + * variant: string, * allowUnstamped?: boolean, * expectInputsDigest?: string | null, * expectSourceRevision?: string | null, * expectArchitecture?: string | null, - * }} [options] + * }} options * @returns {string[]} */ export function checkRunnerImageLayout(root, { + variant, allowUnstamped = false, expectInputsDigest = null, expectSourceRevision = null, expectArchitecture = null, -} = {}) { +}) { + if (!RUNNER_IMAGE_VARIANTS.includes(variant)) throw new Error("the check must be told the variant: slim or full"); const problems = []; const manifestPath = resolveIn(root, RUNNER_IMAGE_PATHS.manifest); if (!existsSync(manifestPath)) return ["runner-image.json is missing"]; @@ -790,9 +810,14 @@ export function checkRunnerImageLayout(root, { try { stat = lstatSync(absolute); } catch { + if (variant === "slim" && RUNNER_IMAGE_FULL_ONLY_PATHS.includes(name)) continue; problems.push(`documented path ${relative} (${name}) is missing`); continue; } + if (variant === "slim" && RUNNER_IMAGE_FULL_ONLY_PATHS.includes(name)) { + problems.push(`${relative} (${name}) is in a slim image; only the full image has the transport archives`); + continue; + } if (locate(root, relative).state !== "inside") { problems.push(`documented path ${relative} (${name}) resolves outside the image`); continue; @@ -827,7 +852,7 @@ export function checkRunnerImageLayout(root, { if (stamped) { const pack = checkProviderPack(root, manifest, problems); - if (pack) checkArchives(root, pack, problems); + if (pack && variant === "full") checkArchives(root, pack, problems); } else if (manifest.providerPack !== null) { problems.push("an image without a source revision must not record a provider pack"); } @@ -837,6 +862,7 @@ export function checkRunnerImageLayout(root, { const COMMAND_FLAGS = Object.freeze({ write: { out: "value", workspace: "value", identity: "value", "source-revision": "value", publication: "boolean" }, check: { + variant: "value", "allow-unstamped": "boolean", "expect-inputs-digest": "value", "expect-source-revision": "value", @@ -847,11 +873,11 @@ const COMMAND_FLAGS = Object.freeze({ /** * Splits a command line into positional arguments and the flags the command * knows. Throws on an unknown or repeated flag and on a missing or empty value. - * @param {"write" | "check"} command + * @param {string} command * @param {string[]} argv + * @param {Record} [known] the command's flags: "value" or "boolean" */ -export function parseLayoutArguments(command, argv) { - const known = COMMAND_FLAGS[command]; +export function parseLayoutArguments(command, argv, known = COMMAND_FLAGS[command]) { /** @type {string[]} */ const positional = []; /** @type {Record} */ @@ -888,7 +914,7 @@ if (invoked === import.meta.url) { try { const [command, ...rest] = process.argv.slice(2); if (command !== "write" && command !== "check") { - throw new Error("Usage: runner-image-layout.mjs write ... | check DIR [...]"); + throw new Error("Usage: runner-image-layout.mjs write ... | check DIR --variant slim|full [...]"); } const { positional, flags } = parseLayoutArguments(command, rest); if (command === "write") { @@ -909,16 +935,21 @@ if (invoked === import.meta.url) { } else { if (positional.length !== 1) throw new Error("check takes exactly one directory"); const root = path.resolve(positional[0]); + const variant = flags.variant; + if (typeof variant !== "string" || !RUNNER_IMAGE_VARIANTS.includes(variant)) throw new Error("check needs --variant slim or --variant full"); const problems = checkRunnerImageLayout(root, { + variant, allowUnstamped: flags["allow-unstamped"] === true, expectInputsDigest: expectation(flags, "expect-inputs-digest", HEX_64, "64 hexadecimal characters"), expectSourceRevision: expectation(flags, "expect-source-revision", REVISION, "a full Git SHA"), expectArchitecture: expectation(flags, "expect-architecture", /^(?:amd64|arm64)$/, "amd64 or arm64"), }); - // Only a tree without a source revision has no archives; the layout - // check above has already refused that tree unless it was allowed. - let archives = "The tree has no provider pack, so there are no transport archives to extract."; - if (existsSync(resolveIn(root, RUNNER_IMAGE_PATHS.providerPackArchiveReceipt))) { + // A full tree without a source revision has no archives either; the + // layout check above has already refused that tree unless it was allowed. + let archives = variant === "slim" + ? "A slim image has no transport archives." + : "The tree has no provider pack, so there are no transport archives to extract."; + if (variant === "full" && existsSync(resolveIn(root, RUNNER_IMAGE_PATHS.providerPackArchiveReceipt))) { const roundTrip = await checkProviderPackArchives(root); problems.push(...roundTrip.problems); archives = roundTrip.tar === "GNU tar" diff --git a/scripts/runner-image-oci.mjs b/scripts/runner-image-oci.mjs new file mode 100644 index 00000000000..f698920eaa1 --- /dev/null +++ b/scripts/runner-image-oci.mjs @@ -0,0 +1,585 @@ +#!/usr/bin/env node +// OCI archives of the Runner image, as `docker buildx build --output type=oci` +// writes them for one platform. doc/runner-image-contract.md is the contract. +// +// unpack writes the file tree of the image in an archive: its layers, +// in order. The layout check and the smoke matrix then read +// the bytes of the archive, not a second export of the build, +// so what they accept is what a registry would receive. +// check-layers verifies the layers of the two variants: they are split by +// how often their content changes, the full image is the slim +// image plus the transport layers, and nothing else is in +// those. +// +// Usage: +// node scripts/runner-image-oci.mjs unpack IMAGE.oci.tar --out DIR +// node scripts/runner-image-oci.mjs check-layers [--slim SLIM.oci.tar] [--full FULL.oci.tar] +// +// The archive and its layers are read here, not with the system's tar, so +// every platform reads them the same way. Each blob is checked against its +// digest as it is read. The image is `FROM scratch` and every layer only adds +// files, so `unpack` refuses a whiteout, a path that is absolute or has `..`, +// a path written twice, an entry behind a link, and every entry that is not a +// file, a directory or a link. +// +// The image build does not run this file, so it is not an input of the image. + +import { createHash } from "node:crypto"; +import { + chmodSync, + closeSync, + createReadStream, + linkSync, + lstatSync, + mkdirSync, + openSync, + readSync, + readdirSync, + symlinkSync, + utimesSync, + writeSync, +} from "node:fs"; +import path from "node:path"; +import { Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { pathToFileURL } from "node:url"; +import { createGunzip } from "node:zlib"; +import { RUNNER_IMAGE_PATHS, canonicalJson, parseLayoutArguments, summarize } from "./runner-image-layout.mjs"; + +const BLOCK = 512; +const DIGEST = /^sha256:[0-9a-f]{64}$/; +const GZIP_LAYER = /^application\/vnd\.(?:oci\.image\.layer\.v1\.tar\+gzip|docker\.image\.rootfs\.diff\.tar\.gzip)$/; +const ENTRY_KINDS = Object.freeze({ 0: "file", "\0": "file", 1: "hardlink", 2: "link", 5: "directory" }); + +/** One tar header block, or null for the zero block that ends an archive. */ +function parseTarHeader(block) { + if (block.every((byte) => byte === 0)) return null; + const text = (start, length) => { + const field = block.subarray(start, start + length); + const end = field.indexOf(0); + return field.subarray(0, end === -1 ? length : end).toString("utf8"); + }; + const octal = (start, length, label) => { + const value = text(start, length).trim(); + if (!/^[0-7]*$/.test(value)) throw new Error(`tar header has a ${label} this reader does not support`); + return value === "" ? 0 : Number.parseInt(value, 8); + }; + let sum = 0; + for (let index = 0; index < BLOCK; index += 1) sum += index >= 148 && index < 156 ? 32 : block[index]; + if (sum !== octal(148, 8, "checksum")) throw new Error("tar header checksum does not match"); + // Only the POSIX format has a name prefix; GNU tar keeps other fields there. + const prefix = text(257, 6) === "ustar" && block[263] === 48 ? text(345, 155) : ""; + return { + name: prefix ? `${prefix}/${text(0, 100)}` : text(0, 100), + mode: octal(100, 8, "mode"), + size: octal(124, 12, "size"), + mtime: octal(136, 12, "time"), + type: String.fromCharCode(block[156]), + linkname: text(157, 100), + }; +} + +/** The records of a pax extended header: ` =\n`. */ +function parsePaxRecords(data) { + /** @type {Record} */ + const records = {}; + for (let offset = 0; offset < data.length;) { + const space = data.indexOf(32, offset); + const length = Number.parseInt(data.subarray(offset, space).toString("latin1"), 10); + if (space === -1 || !Number.isSafeInteger(length) || length <= 0 || offset + length > data.length) throw new Error("tar pax header is malformed"); + const record = data.subarray(space + 1, offset + length - 1).toString("utf8"); + const equals = record.indexOf("="); + if (equals === -1) throw new Error("tar pax header is malformed"); + records[record.slice(0, equals)] = record.slice(equals + 1); + offset += length; + } + return records; +} + +/** Header types that only describe the next entry: pax (`x`, and `g` for the whole archive) and GNU long names. */ +const DESCRIBING = new Set(["x", "g", "L", "K"]); + +/** Applies describing headers and returns the entry each other header stands for. */ +function tarEntryReader() { + /** @type {Record} */ + let pax = {}; + /** @type {{ name?: string, linkname?: string }} */ + let gnu = {}; + const cString = (data) => data.subarray(0, data.indexOf(0) === -1 ? data.length : data.indexOf(0)).toString("utf8"); + return { + describe(header, data) { + if (header.type === "x") pax = parsePaxRecords(data); + else if (header.type === "L") gnu.name = cString(data); + else if (header.type === "K") gnu.linkname = cString(data); + }, + entry(header) { + const entry = { + name: pax.path ?? gnu.name ?? header.name, + linkname: pax.linkpath ?? gnu.linkname ?? header.linkname, + size: pax.size === undefined ? header.size : Number(pax.size), + mtime: pax.mtime === undefined ? header.mtime : Number(pax.mtime), + mode: header.mode & 0o7777, + type: header.type, + }; + pax = {}; + gnu = {}; + if (!Number.isSafeInteger(entry.size) || entry.size < 0) throw new Error(`tar entry ${entry.name} has no usable size`); + return entry; + }, + }; +} + +/** Where each member of an uncompressed tar file is, by its exact name. */ +function indexTarFile(file) { + const fd = openSync(file, "r"); + try { + /** @type {Map} */ + const members = new Map(); + const reader = tarEntryReader(); + const block = Buffer.alloc(BLOCK); + for (let offset = 0; readSync(fd, block, 0, BLOCK, offset) === BLOCK;) { + const header = parseTarHeader(block); + if (header === null) break; + offset += BLOCK; + if (DESCRIBING.has(header.type)) { + const data = Buffer.alloc(header.size); + if (readSync(fd, data, 0, header.size, offset) !== header.size) throw new Error(`${file} ends inside a header`); + reader.describe(header, data); + offset += Math.ceil(header.size / BLOCK) * BLOCK; + continue; + } + const entry = reader.entry(header); + if (members.has(entry.name)) throw new Error(`${file} holds ${entry.name} twice`); + members.set(entry.name, { offset, size: entry.size }); + offset += Math.ceil(entry.size / BLOCK) * BLOCK; + } + return members; + } finally { + closeSync(fd); + } +} + +/** + * Calls `visit(entry, content)` for every entry of a tar stream. `content` + * yields the entry's bytes; what `visit` leaves unread is skipped. + * @param {AsyncIterable} source + * @param {(entry: ReturnType["entry"]>, content: () => AsyncGenerator) => Promise | void} visit + */ +async function readTarStream(source, visit) { + const iterator = source[Symbol.asyncIterator](); + let buffered = Buffer.alloc(0); + /** Some bytes, at most `limit`: what is buffered, or the next chunk. Empty at the end of the stream. */ + const some = async (limit) => { + while (buffered.length === 0) { + const next = await iterator.next(); + if (next.done) return buffered; + buffered = next.value; + } + const taken = buffered.subarray(0, limit); + buffered = buffered.subarray(taken.length); + return taken; + }; + /** Exactly `length` bytes, or fewer at the end of the stream. */ + const take = async (length) => { + const parts = []; + for (let missing = length; missing > 0;) { + const part = await some(missing); + if (part.length === 0) break; + parts.push(part); + missing -= part.length; + } + return parts.length === 1 ? parts[0] : Buffer.concat(parts); + }; + const exactly = async (length) => { + const taken = await take(length); + if (taken.length !== length) throw new Error("tar stream ends inside an entry"); + return taken; + }; + const reader = tarEntryReader(); + for (;;) { + const block = await take(BLOCK); + if (block.length === 0) break; + if (block.length !== BLOCK) throw new Error("tar stream ends inside a header"); + const header = parseTarHeader(block); + if (header === null) break; + if (DESCRIBING.has(header.type)) { + reader.describe(header, (await exactly(Math.ceil(header.size / BLOCK) * BLOCK)).subarray(0, header.size)); + continue; + } + const entry = reader.entry(header); + let remaining = entry.size; + const content = async function* () { + while (remaining > 0) { + const chunk = await some(remaining); + if (chunk.length === 0) throw new Error("tar stream ends inside an entry"); + remaining -= chunk.length; + yield chunk; + } + }; + await visit(entry, content); + for await (const _unread of content()) { /* skip what the visitor left */ } + await exactly((BLOCK - (entry.size % BLOCK)) % BLOCK); + } + // Read to the end, so the caller's digest covers the whole blob. + while (!(await iterator.next()).done) { /* trailing zero blocks */ } +} + +/** + * The one image in an OCI archive: its manifest descriptor and its layers. A + * member is found by its exact name (`index.json`, `blobs/sha256/`), as + * buildx writes them. The manifest is checked against its digest here, and + * each layer when `readLayer` reads it. + * @param {string} archive + */ +export function readOciArchive(archive) { + const members = indexTarFile(archive); + const located = (name) => { + const member = members.get(name); + if (!member) throw new Error(`${archive} has no member ${name}`); + return member; + }; + const bytes = (name) => { + const { offset, size } = located(name); + const data = Buffer.alloc(size); + const fd = openSync(archive, "r"); + try { + if (readSync(fd, data, 0, size, offset) !== size) throw new Error(`${archive} ends inside ${name}`); + } finally { + closeSync(fd); + } + return data; + }; + const blobName = (digest) => { + if (!DIGEST.test(digest ?? "")) throw new Error(`${archive} names a blob by something other than a sha256 digest`); + return `blobs/sha256/${digest.slice(7)}`; + }; + const sha256 = (data) => `sha256:${createHash("sha256").update(data).digest("hex")}`; + const index = JSON.parse(bytes("index.json").toString("utf8")); + if (!Array.isArray(index.manifests) || index.manifests.length !== 1) throw new Error(`${archive} must hold exactly one image manifest`); + const { mediaType, digest, size } = index.manifests[0]; + const manifestBytes = bytes(blobName(digest)); + if (sha256(manifestBytes) !== digest) throw new Error(`${archive}: the manifest does not have the digest the index names`); + const manifest = JSON.parse(manifestBytes.toString("utf8")); + if (!Array.isArray(manifest.layers)) throw new Error(`${archive} holds an index, not one platform's image; build without attestations`); + for (const layer of manifest.layers) { + if (!GZIP_LAYER.test(layer.mediaType ?? "")) throw new Error(`${archive}: layer ${layer.digest} is ${layer.mediaType}, not a gzip tar`); + located(blobName(layer.digest)); + } + return { + archive, + descriptor: { mediaType, digest, size }, + /** @type {{ mediaType: string, digest: string, size: number }[]} */ + layers: manifest.layers.map((layer) => ({ mediaType: layer.mediaType, digest: layer.digest, size: layer.size })), + /** Visits every entry of one layer and fails when the blob does not have its digest. */ + async readLayer(layer, visit) { + const { offset, size: bytesInArchive } = located(blobName(layer.digest)); + if (bytesInArchive !== layer.size || bytesInArchive === 0) { + throw new Error(`${archive}: layer ${layer.digest} is ${bytesInArchive} bytes, the manifest says ${layer.size}`); + } + const hash = createHash("sha256"); + const hashing = new Transform({ transform(chunk, _encoding, done) { hash.update(chunk); done(null, chunk); } }); + const gunzip = createGunzip({ chunkSize: 1024 * 1024 }); + const feeding = pipeline(createReadStream(archive, { start: offset, end: offset + bytesInArchive - 1 }), hashing, gunzip); + // A failure below destroys the streams; that rejection is not the cause. + feeding.catch(() => {}); + try { + await readTarStream(gunzip, visit); + } catch (error) { + gunzip.destroy(); + throw error; + } + await feeding; + if (`sha256:${hash.digest("hex")}` !== layer.digest) throw new Error(`${archive}: layer ${layer.digest} does not have its digest`); + }, + }; +} + +/** + * The path of a layer entry relative to the image root, and its kind. Throws + * for an entry an additive layer of a `FROM scratch` image cannot have. + * Returns null for the root directory itself. + */ +function layerEntry(entry) { + const kind = ENTRY_KINDS[entry.type]; + if (!kind) throw new Error(`layer entry ${entry.name} is of type ${JSON.stringify(entry.type)}, not a file, a directory or a link`); + const clean = (name, label) => { + if (name.startsWith("/")) throw new Error(`layer ${label} ${name} is absolute`); + const relative = name.replace(/^(?:\.\/)+/, "").replace(/\/+$/, ""); + if (relative === "" || relative === ".") return null; + const parts = relative.split("/"); + if (relative.includes("\0") || parts.some((part) => part === "" || part === "." || part === "..")) { + throw new Error(`layer ${label} ${name} is not a plain relative path`); + } + if (parts.some((part) => part.startsWith(".wh."))) throw new Error(`layer ${label} ${name} is a whiteout: the image only adds files`); + return relative; + }; + const name = clean(entry.name, "entry"); + if (name === null) { + if (kind !== "directory") throw new Error(`layer entry ${entry.name} replaces the image root`); + return null; + } + // A link's target is text and is never followed here. A hard link names a file of the image. + const target = kind === "hardlink" ? clean(entry.linkname, "hard link target") : kind === "link" ? entry.linkname : null; + if (kind === "hardlink" && target === null) throw new Error(`layer entry ${entry.name} is a hard link to the image root`); + return { name, kind, target, mode: entry.mode, size: entry.size, mtime: entry.mtime }; +} + +/** + * The entries of every layer of the image in an archive, in order. + * @param {string} archive + */ +export async function listOciLayers(archive) { + const image = readOciArchive(archive); + const layers = []; + for (const layer of image.layers) { + /** @type {NonNullable>[]} */ + const entries = []; + await image.readLayer(layer, (raw) => { + const entry = layerEntry(raw); + if (entry) entries.push(entry); + }); + layers.push({ digest: layer.digest, bytes: layer.size, entries }); + } + return { digest: image.descriptor.digest, layers }; +} + +/** + * Writes the file tree of the image in an archive to `destination`, which + * must be empty or absent: every layer in order. Returns the image digest. + * @param {string} archive + * @param {string} destination + */ +export async function unpackOciImage(archive, destination) { + const image = readOciArchive(archive); + mkdirSync(destination, { recursive: true }); + if (readdirSync(destination).length > 0) throw new Error(`${destination} is not empty`); + const stat = (file) => { + try { + return lstatSync(file); + } catch (error) { + if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") return null; + throw error; + } + }; + /** The place of an entry, after its parents are known to be real directories. */ + const place = (name) => { + let current = destination; + const parts = name.split("/"); + for (const part of parts.slice(0, -1)) { + current = path.join(current, part); + const parent = stat(current); + if (parent === null) mkdirSync(current, { mode: 0o755 }); + else if (!parent.isDirectory()) throw new Error(`layer entry ${name} is behind ${path.relative(destination, current)}, which is not a directory`); + } + return path.join(current, parts.at(-1)); + }; + /** @type {Map} */ + const directoryModes = new Map(); + let files = 0; + for (const layer of image.layers) { + await image.readLayer(layer, async (raw, content) => { + const entry = layerEntry(raw); + if (entry === null) return; + const target = place(entry.name); + const existing = stat(target); + if (entry.kind === "directory") { + if (existing === null) mkdirSync(target, { mode: 0o755 }); + else if (!existing.isDirectory()) throw new Error(`a layer writes ${entry.name} again, as a directory`); + directoryModes.set(target, entry.mode); + return; + } + if (existing !== null) throw new Error(`a layer writes ${entry.name} again: the image only adds files`); + files += 1; + if (entry.kind === "link") { + symlinkSync(/** @type {string} */ (entry.target), target); + } else if (entry.kind === "hardlink") { + const source = place(/** @type {string} */ (entry.target)); + if (!stat(source)?.isFile()) throw new Error(`layer entry ${entry.name} is a hard link to ${entry.target}, which is not a file of the image`); + linkSync(source, target); + } else { + const fd = openSync(target, "wx", 0o600); + try { + for await (const chunk of content()) writeSync(fd, chunk); + } finally { + closeSync(fd); + } + chmodSync(target, entry.mode); + utimesSync(target, entry.mtime, entry.mtime); + } + }); + } + // Last, and children first: a directory may not be writable by its owner. + for (const [directory, mode] of [...directoryModes].sort(([left], [right]) => right.length - left.length)) chmodSync(directory, mode); + return { digest: image.descriptor.digest, layers: image.layers.length, files }; +} + +const SLIM_LAYERS = Object.freeze([ + "provider pack dependency files of 1 MiB or more", + "everything else", +]); +/** + * The layers of each variant, in order. Content that changes rarely is apart + * from content that changes with every Runner source change, so a new image + * shares its large layers with the one before it. The full image is the slim + * image plus two layers that hold the transport archives and their receipt + * and nothing else, so a reader can fetch all of them without the pack. + * + * "Dependency files" are the pack's files outside `dist`, which the Runner's + * own build writes. A large file under `dist` changes with the Runner's + * source, so it and its transport archive are with the content that does. + */ +export const RUNNER_IMAGE_LAYERS = Object.freeze({ + slim: SLIM_LAYERS, + full: Object.freeze([ + ...SLIM_LAYERS, + "transport archives of the files in layer 1", + "the other transport archives, the overlay archive and the receipt", + ]), +}); + +/** + * Verifies the layer rule on OCI archives of one platform's image. With both + * variants it also verifies that the full image starts with the slim image's + * layers. + * @param {{ slim?: string | null, full?: string | null }} archives + * @returns {Promise<{ problems: string[], layers: Record }>} + */ +export async function checkRunnerImageLayers({ slim = null, full = null }) { + if (slim === null && full === null) throw new Error("check-layers needs --slim, --full or both"); + /** @type {string[]} */ + const problems = []; + /** @type {Record} */ + const layers = {}; + const pack = RUNNER_IMAGE_PATHS.providerPack; + const archivesDirectory = RUNNER_IMAGE_PATHS.providerPackArchives; + const receiptPath = RUNNER_IMAGE_PATHS.providerPackArchiveReceipt; + const transport = (name) => name === receiptPath || name === archivesDirectory || name.startsWith(`${archivesDirectory}/`); + // Transport content anywhere else: under another directory, or under another name. + const transportLike = (name) => name.split("/").some((part) => part === receiptPath || part === archivesDirectory || part.endsWith(".tar.zst")); + /** @type {Record} */ + const images = {}; + for (const [variant, archive] of Object.entries({ slim, full })) { + if (archive === null) continue; + const image = await listOciLayers(archive); + const roles = RUNNER_IMAGE_LAYERS[variant]; + layers[variant] = image.layers.map((layer, position) => ({ + role: roles[position] ?? "unexpected layer", digest: layer.digest, bytes: layer.bytes, entries: layer.entries.length, + })); + if (image.layers.length !== roles.length) { + problems.push(`the ${variant} image has ${image.layers.length} layers, not ${roles.length}`); + continue; + } + const listed = image.layers.map((layer) => ({ + digest: layer.digest, + names: [...new Set(layer.entries.map((entry) => entry.name))], + files: [...new Set(layer.entries.filter((entry) => entry.kind !== "directory").map((entry) => entry.name))], + })); + images[variant] = listed; + const [large, rest] = listed; + // Each layer only adds. A directory may be in several layers; a file or a link is in one. + /** @type {Map} */ + const written = new Map(); + for (const layer of listed) { + const files = new Set(layer.files); + for (const name of layer.names) { + const entry = written.get(name) ?? { layers: 0, file: false }; + written.set(name, { layers: entry.layers + 1, file: entry.file || files.has(name) }); + } + } + summarize(problems, `${variant}: more than one layer writes`, [...written].filter(([, entry]) => entry.file && entry.layers > 1).map(([name]) => name)); + summarize(problems, `${variant}: the first layer holds entries outside the pack's dependency files`, + large.names.filter((name) => name !== pack && (!name.startsWith(`${pack}/`) || name === `${pack}/dist` || name.startsWith(`${pack}/dist/`)))); + summarize(problems, `${variant}: transport content is in the layers both variants share`, + [...large.names, ...rest.names].filter((name) => transport(name) || transportLike(name))); + if (!rest.files.includes(RUNNER_IMAGE_PATHS.manifest)) problems.push(`${variant}: the second layer does not hold ${RUNNER_IMAGE_PATHS.manifest}`); + } + if (images.full) { + const [large, , stable, changing] = images.full; + const numbered = (layer) => layer.files.filter((name) => name !== `${archivesDirectory}/overlay.tar.zst` && name !== receiptPath); + summarize(problems, "full: the third layer holds something other than transport archives", + stable.names.filter((name) => name !== archivesDirectory && !numbered(stable).includes(name))); + summarize(problems, "full: the last layer holds something other than transport content", changing.names.filter((name) => !transport(name))); + summarize(problems, "full: the last layer lacks", [receiptPath, `${archivesDirectory}/overlay.tar.zst`].filter((name) => !changing.files.includes(name))); + /** @type {{ path: string }[] | null} */ + let files = null; + if (changing.files.includes(receiptPath)) { + try { + files = JSON.parse(await readLayerFile(/** @type {string} */ (full), 3, receiptPath)).files; + } catch { + problems.push("full: the receipt in the last layer is not readable"); + } + } + if (Array.isArray(files)) { + // Archive N holds file N of the receipt. The receipt decides the layer. + const own = (file) => file.path === "dist" || file.path.startsWith("dist/"); + const archiveOf = (file) => `${archivesDirectory}/${files.indexOf(file)}.tar.zst`; + const expect = (label, actual, expected) => { + summarize(problems, `full: ${label} lacks`, expected.filter((name) => !actual.includes(name))); + summarize(problems, `full: ${label} holds, against the receipt,`, actual.filter((name) => !expected.includes(name))); + }; + expect("the first layer", large.files, files.filter((file) => !own(file)).map((file) => `${pack}/${file.path}`)); + expect("the third layer", numbered(stable), files.filter((file) => !own(file)).map(archiveOf)); + expect("the last layer", numbered(changing), files.filter(own).map(archiveOf)); + } + } + if (images.slim && images.full) { + // The same blobs in the same order, not only the same files. + const shared = images.slim.map((layer) => layer.digest); + if (canonicalJson(images.full.slice(0, shared.length).map((layer) => layer.digest)) !== canonicalJson(shared)) { + problems.push("the full image does not start with the layers of the slim image"); + } + } + return { problems, layers }; +} + +/** The text of one file in one layer of an archive. */ +async function readLayerFile(archive, position, name) { + const image = readOciArchive(archive); + /** @type {Buffer[] | null} */ + let chunks = null; + await image.readLayer(image.layers[position], async (raw, content) => { + if (layerEntry(raw)?.name !== name) return; + chunks = []; + for await (const chunk of content()) chunks.push(chunk); + }); + if (chunks === null) throw new Error(`${name} is not in layer ${position + 1}`); + return Buffer.concat(chunks).toString("utf8"); +} + +const COMMAND_FLAGS = Object.freeze({ + unpack: { out: "value" }, + "check-layers": { slim: "value", full: "value" }, +}); + +const invoked = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : null; +if (invoked === import.meta.url) { + try { + const [command, ...rest] = process.argv.slice(2); + if (command !== "unpack" && command !== "check-layers") { + throw new Error("Usage: runner-image-oci.mjs unpack IMAGE.oci.tar --out DIR | check-layers [--slim TAR] [--full TAR]"); + } + const { positional, flags } = parseLayoutArguments(command, rest, COMMAND_FLAGS[command]); + if (command === "unpack") { + if (positional.length !== 1 || typeof flags.out !== "string") throw new Error("unpack takes exactly one OCI archive and --out DIR"); + const result = await unpackOciImage(path.resolve(positional[0]), path.resolve(flags.out)); + process.stdout.write(`Unpacked ${result.files} files from the ${result.layers} layers of ${result.digest} into ${path.resolve(flags.out)}.\n`); + } else { + if (positional.length > 0) throw new Error(`check-layers takes no positional argument: ${positional[0]}`); + const archive = (name) => (flags[name] === undefined ? null : path.resolve(String(flags[name]))); + const { problems, layers } = await checkRunnerImageLayers({ slim: archive("slim"), full: archive("full") }); + for (const [variant, rows] of Object.entries(layers)) { + for (const [position, layer] of rows.entries()) { + process.stdout.write(`${variant} layer ${position + 1}: ${layer.digest} ${String(layer.bytes).padStart(11)} bytes ${String(layer.entries).padStart(6)} entries ${layer.role}\n`); + } + } + if (problems.length > 0) { + process.stderr.write(`Runner image layer check failed:\n${problems.map((problem) => `- ${problem}`).join("\n")}\n`); + process.exit(1); + } + process.stdout.write("Runner image layer check passed.\n"); + } + } catch (error) { + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exit(1); + } +} diff --git a/server/src/__tests__/runner-image-identity.test.ts b/server/src/__tests__/runner-image-identity.test.ts index 2081c3963ef..af441f6b70a 100644 --- a/server/src/__tests__/runner-image-identity.test.ts +++ b/server/src/__tests__/runner-image-identity.test.ts @@ -189,17 +189,50 @@ describe("Runner image identity", () => { * the whole of what the build reads only while these three rules hold. */ describe("Runner image stages", () => { - const stages = [...dockerfile.matchAll(/^FROM (\S+)(?: AS (\S+))?$/gm)].map((match, index, all) => ({ - from: match[1], - name: match[2] ?? "", - lines: dockerfile.slice(match.index, all[index + 1]?.index ?? dockerfile.length).split("\n").filter((line) => !/^\s*#/.test(line)), + // BuildKit accepts an instruction in any case and with any indentation, and + // FROM with flags. A stage starts wherever BuildKit starts one; the first + // rule below then allows only the spelling the other rules can read. + const stagesOf = (text: string) => [...text.matchAll(/^[ \t]*from[ \t].*$/gim)].map((match, index, all) => ({ + from: /^FROM (\S+)(?: AS \S+)?$/.exec(match[0])?.[1] ?? "", + // The name BuildKit gives the stage, however the line is spelt. + name: (/\sas\s+(\S+)\s*$/i.exec(match[0])?.[1] ?? "").toLowerCase(), + lines: text.slice(match.index, all[index + 1]?.index ?? text.length).split("\n").filter((line) => !/^\s*#/.test(line)), })); + type Stage = ReturnType[number]; + /** The lines of a stage that read something and are not in the one spelling these rules read. */ + const misspelt = (stage: Stage) => stage.lines.filter((line, index) => (index === 0 + // No lowercase keyword, no indentation, no flag on FROM. + ? !/^FROM \S+ AS runner-artifacts[a-z-]*$/.test(line) + // No ADD or ONBUILD, no other flag, and no source on a continuation line. + : /^\s*(?:from|copy|add|onbuild)(?:\s|$)/i.test(line) + && !/^COPY (?:--link )?(?:--from=runner-artifacts[a-z-]* )?[^-\s]\S*(?: [^\s\\]+)+$/.test(line))); + const stages = stagesOf(dockerfile); const names = stages.map((stage) => stage.name); const runner = stages.filter((stage) => stage.name.startsWith("runner-artifacts")); - const copies = (stage: (typeof stages)[number]) => stage.lines.filter((line) => /^COPY\s/.test(line)); + const copies = (stage: Stage) => stage.lines.filter((line) => /^COPY\s/.test(line)); + + it("spell every FROM and COPY the one way these rules read, and use no ADD or ONBUILD", () => { + expect(runner.length).toBeGreaterThan(3); + for (const stage of runner) expect(misspelt(stage), stage.name).toEqual([]); + }); + + it.each([ + ["a lowercase stage keyword", "FROM scratch as runner-artifacts-extra\nCOPY secrets /\n"], + ["a lowercase from", "from scratch AS runner-artifacts-extra\n"], + ["a flag on FROM", "FROM --platform=linux/amd64 node:24 AS runner-artifacts-extra\n"], + ["a lowercase copy", "FROM scratch AS runner-artifacts-extra\ncopy secrets /\n"], + ["an indented COPY", "FROM scratch AS runner-artifacts-extra\n COPY secrets /\n"], + ["an ADD in any case", "FROM scratch AS runner-artifacts-extra\n add secrets /\n"], + ["a COPY continued on the next line", "FROM scratch AS runner-artifacts-extra\nCOPY package.json \\\n secrets /\n"], + ["a COPY with another flag", "FROM scratch AS runner-artifacts-extra\nCOPY --parents secrets /\n"], + ["an ONBUILD trigger", "FROM scratch AS runner-artifacts-extra\nONBUILD COPY secrets /\n"], + ])("would catch %s in a stage BuildKit reads as one of the Runner's", (_label, text) => { + const added = stagesOf(text).filter((stage) => stage.name.startsWith("runner-artifacts")); + expect(added).toHaveLength(1); + expect(misspelt(added[0])).not.toEqual([]); + }); it("start only from each other, from scratch, or from an image pinned by digest", () => { - expect(runner.length).toBeGreaterThan(3); for (const stage of runner) { if (stage.from === "scratch" || names.includes(stage.from)) { expect(stage.from === "scratch" || stage.from.startsWith("runner-artifacts"), stage.name).toBe(true); @@ -233,10 +266,23 @@ describe("Runner image stages", () => { expect([...sources].sort()).toEqual([...RUNNER_IMAGE_CONTEXT_INPUTS].sort()); }); - it("end in a file tree, and leave the default target and the application stages alone", () => { - const target = runner.find((stage) => stage.name === "runner-artifacts")!; - expect(target.from).toBe("scratch"); - expect(copies(target)).toEqual(["COPY --from=runner-artifacts-build /out/ /"]); + it("end in two file trees, the full one being the slim one plus the transport layers", () => { + // Each COPY --link is one layer that does not depend on the layers under + // it. The slim variant is the first two; the full variant starts from it, + // so it has the same two layers and then the transport archives. + const slim = runner.find((stage) => stage.name === "runner-artifacts-slim")!; + const full = runner.find((stage) => stage.name === "runner-artifacts")!; + const instructions = (stage: typeof slim) => stage.lines.filter((line) => /^[A-Z]+\s/.test(line)).slice(1); + expect(slim.from).toBe("scratch"); + expect(instructions(slim)).toEqual([ + "COPY --link --from=runner-artifacts-build /out-large/ /", + "COPY --link --from=runner-artifacts-build /out/ /", + ]); + expect(full.from).toBe("runner-artifacts-slim"); + expect(instructions(full)).toEqual([ + "COPY --link --from=runner-artifacts-build /out-archives/ /", + "COPY --link --from=runner-artifacts-build /out-transport/ /", + ]); // `docker build .` builds the last stage. expect(names.at(-1)).toBe("cloud"); for (const stage of stages) { diff --git a/server/src/__tests__/runner-image-layout.test.ts b/server/src/__tests__/runner-image-layout.test.ts index 3c2118400bf..1ef1b9babee 100644 --- a/server/src/__tests__/runner-image-layout.test.ts +++ b/server/src/__tests__/runner-image-layout.test.ts @@ -33,11 +33,15 @@ import { RUNNER_IMAGE_SCHEMA, canonicalJson, checkProviderPackArchives, - checkRunnerImageLayout, + checkRunnerImageLayout as checkLayout, parseLayoutArguments, writeRunnerImageManifest, } from "../../../scripts/runner-image-layout.mjs"; +/** The fixture is a full image, so most tests check it as one. */ +const checkRunnerImageLayout = (root: string, options: Omit[1], "variant"> = {}) => + checkLayout(root, { variant: "full", ...options }); + /** * The layout contract of the Runner image. Consumers copy the documented * paths out of the image and trust runner-image.json, so a tree that @@ -182,6 +186,7 @@ describe("Runner image layout contract", () => { platform: { os: "linux", architecture: "amd64" }, libc: { family: "glibc", baseline: "debian-bookworm", buildVersion: "2.36", runnerdRequires: "2.34" }, paths: RUNNER_IMAGE_PATHS, + fullImageOnly: ["providerPackArchiveReceipt", "providerPackArchives"], }); // One daemon, at the root for sandbox images and inside the build output // for a build that vendors the Runner. @@ -209,6 +214,7 @@ describe("Runner image layout contract", () => { ["a short inputs digest", (m) => { m.inputsDigest.digest = "abc"; }, /inputsDigest must be/], ["another build-inputs schema", (m) => { m.buildInputsDigest.schema = "paperclip.runner-build-inputs.v1"; }, /buildInputsDigest must be/], ["an abbreviated source revision", (m) => { m.sourceRevision = "abc1234"; }, /sourceRevision/], + ["transport paths claimed for both variants", (m) => { m.fullImageOnly = []; }, /fullImageOnly does not name the paths only the full image has/], ["no word on whether it is a publication build", (m) => { delete m.publication; }, /publication must say/], ["a publication build without a source revision", (m) => { m.sourceRevision = null; }, /publication build must have a source revision/], ["an unsupported platform", (m) => { m.platform = { os: "linux", architecture: "riscv64" }; }, /platform must be/], @@ -378,6 +384,59 @@ describe("Runner image layout contract", () => { }); }); + describe("variants", () => { + /** A slim tree: the full fixture without its transport archives and receipt. */ + function slim(tree: string) { + rmSync(path.join(tree, "provider-pack.archives"), { recursive: true }); + rmSync(path.join(tree, "provider-pack.archive.json")); + return tree; + } + + it("accepts a slim tree only as slim, and a full tree only as full", () => { + expect(checkLayout(out, { variant: "full" })).toEqual([]); + expect(checkLayout(out, { variant: "slim" })).toEqual([ + "provider-pack.archive.json (providerPackArchiveReceipt) is in a slim image; only the full image has the transport archives", + "provider-pack.archives (providerPackArchives) is in a slim image; only the full image has the transport archives", + ]); + slim(out); + expect(checkLayout(out, { variant: "slim", expectInputsDigest: INPUTS, expectSourceRevision: REVISION, expectArchitecture: "amd64" })).toEqual([]); + expect(checkLayout(out, { variant: "full" })).toEqual(expect.arrayContaining([ + "documented path provider-pack.archive.json (providerPackArchiveReceipt) is missing", + "documented path provider-pack.archives (providerPackArchives) is missing", + ])); + }); + + it("refuses a slim tree that holds only one of the two transport paths", () => { + rmSync(path.join(out, "provider-pack.archive.json")); + expect(checkLayout(out, { variant: "slim" }).join("\n")).toMatch(/provider-pack\.archives \(providerPackArchives\) is in a slim image/); + }); + + it("still checks everything else in a slim tree", () => { + appendFileSync(path.join(slim(out), "provider-pack/dist/cli/opencode-app-server-proxy.js"), "// later edit\n"); + expect(checkLayout(out, { variant: "slim" }).join("\n")).toMatch(/the provider pack dist tree does not match its tree digest/); + }); + + it("has no default: the variant is always given", () => { + // @ts-expect-error the variant is required + expect(() => checkLayout(out, {})).toThrow(/must be told the variant: slim or full/); + expect(() => checkLayout(out, { variant: "both" })).toThrow(/must be told the variant/); + const check = (...args: string[]) => spawnSync(process.execPath, [layoutScript, "check", out, ...args], { encoding: "utf8" }); + expect(check().stderr).toMatch(/check needs --variant slim or --variant full/); + expect(check("--variant", "both").stderr).toMatch(/check needs --variant slim or --variant full/); + expect(check("--variant", "slim").stderr).toMatch(/is in a slim image/); + const passed = spawnSync(process.execPath, [layoutScript, "check", slim(out), "--variant", "slim"], { encoding: "utf8" }); + expect(passed.status).toBe(0); + expect(passed.stdout).toMatch(/A slim image has no transport archives/); + }); + + it("writes one runner-image.json for both, which names the paths only the full image has", () => { + const manifest = manifestOf(out); + expect(manifest.fullImageOnly.map((name: keyof typeof RUNNER_IMAGE_PATHS) => RUNNER_IMAGE_PATHS[name])) + .toEqual(["provider-pack.archive.json", "provider-pack.archives"]); + expect(manifest.paths).toEqual(RUNNER_IMAGE_PATHS); + }); + }); + describe("transport archive round trip", () => { // The archives' bytes can match the receipt while the archives do not // hold the pack. Only extracting them, the way a sandbox does, shows it. @@ -555,7 +614,7 @@ describe("Runner image layout contract", () => { }); it("is part of the check command, which says which tar extracted the archives", async () => { - const check = (tree: string) => spawnSync(process.execPath, [layoutScript, "check", tree], { encoding: "utf8" }); + const check = (tree: string) => spawnSync(process.execPath, [layoutScript, "check", tree, "--variant", "full"], { encoding: "utf8" }); const passed = check(out); expect(passed.status).toBe(0); expect(passed.stdout).toMatch(/The transport archives were extracted with (GNU tar, as a sandbox extracts them,|bsdtar) and match the provider pack/); @@ -567,7 +626,7 @@ describe("Runner image layout contract", () => { expect(failed.stderr).toMatch(/transport archive overlay\.tar\.zst is not a zstd archive/); expect(failed.stdout).not.toMatch(/passed/); // A tree without a pack has nothing to extract, and the command says so. - const unstamped = spawnSync(process.execPath, [layoutScript, "check", await image({ stamped: false }), "--allow-unstamped"], { encoding: "utf8" }); + const unstamped = spawnSync(process.execPath, [layoutScript, "check", await image({ stamped: false }), "--variant", "full", "--allow-unstamped"], { encoding: "utf8" }); expect(unstamped.status).toBe(0); expect(unstamped.stdout).toMatch(/no provider pack, so there are no transport archives to extract/); }); @@ -634,7 +693,7 @@ describe("Runner image layout contract", () => { }); describe("command line", () => { - const check = (...args: string[]) => spawnSync(process.execPath, [layoutScript, "check", ...args], { encoding: "utf8" }); + const check = (...args: string[]) => spawnSync(process.execPath, [layoutScript, "check", ...args, "--variant", "full"], { encoding: "utf8" }); it("passes for a valid tree and fails for a wrong expectation", () => { expect(check(out, "--expect-inputs-digest", INPUTS, "--expect-source-revision", REVISION, "--expect-architecture", "amd64").status).toBe(0); @@ -675,6 +734,9 @@ describe("Runner image layout contract", () => { expect(() => parseLayoutArguments("write", ["--out", "o", "--source-revision", ""])).toThrow(/--source-revision needs a value/); expect(parseLayoutArguments("write", ["--out", "o", "--publication"]).flags).toEqual({ out: "o", publication: true }); expect(() => parseLayoutArguments("check", ["tree", "--publication"])).toThrow(/check does not take --publication/); + // Another script can give the same parser its own flags. + expect(parseLayoutArguments("unpack", ["a.tar", "--out", "d"], { out: "value" })).toEqual({ positional: ["a.tar"], flags: { out: "d" } }); + expect(() => parseLayoutArguments("unpack", ["--variant", "slim"], { out: "value" })).toThrow(/unpack does not take --variant/); expect(() => parseLayoutArguments("write", ["--expect-architecture", "arm64"])).toThrow(/write does not take/); }); }); diff --git a/server/src/__tests__/runner-image-oci.test.ts b/server/src/__tests__/runner-image-oci.test.ts new file mode 100644 index 00000000000..393fc2a3896 --- /dev/null +++ b/server/src/__tests__/runner-image-oci.test.ts @@ -0,0 +1,360 @@ +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + readlinkSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { gzipSync } from "node:zlib"; +import { afterAll, describe, expect, it } from "vitest"; +import { + RUNNER_IMAGE_LAYERS, + checkRunnerImageLayers, + listOciLayers, + readOciArchive, + unpackOciImage, +} from "../../../scripts/runner-image-oci.mjs"; + +/** + * The OCI archives of the Runner image. CI builds each variant as an archive + * only, unpacks it, and checks the tree that comes out, so the reader must + * give exactly the files of the image and must not write anything an additive + * layer of a `FROM scratch` image cannot hold. + */ + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); +const ociScript = path.join(repoRoot, "scripts", "runner-image-oci.mjs"); +const sha256 = (bytes: Buffer | string) => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; +const scratch = mkdtempSync(path.join(tmpdir(), "runner-image-oci-")); +afterAll(() => { + spawnSync("chmod", ["-R", "u+rwX", scratch]); + rmSync(scratch, { recursive: true, force: true }); +}); +let sequence = 0; +const fresh = () => path.join(scratch, String(sequence += 1)); + +type Entry = { name: string; type?: string; content?: string | Buffer; linkname?: string; mode?: number }; + +/** A tar stream of exactly these entries, in the POSIX format. Nothing is added or cleaned. */ +function tarOf(entries: Entry[]) { + const blocks: Buffer[] = []; + for (const entry of entries) { + const type = entry.type ?? (entry.name.endsWith("/") ? "5" : "0"); + const content = Buffer.from(entry.content ?? ""); + const header = Buffer.alloc(512); + const field = (value: string, start: number, length: number) => { header.write(value, start, length, "utf8"); }; + const octal = (value: number, start: number, length: number) => field(`${value.toString(8).padStart(length - 1, "0")}\0`, start, length); + expect(Buffer.byteLength(entry.name)).toBeLessThanOrEqual(100); + field(entry.name, 0, 100); + octal(entry.mode ?? (type === "5" ? 0o755 : 0o644), 100, 8); + octal(0, 108, 8); + octal(0, 116, 8); + octal(type === "0" ? content.length : 0, 124, 12); + octal(946684800, 136, 12); + field(" ", 148, 8); + field(type, 156, 1); + field(entry.linkname ?? "", 157, 100); + field("ustar\0", 257, 6); + field("00", 263, 2); + octal(header.reduce((sum, byte) => sum + byte, 0), 148, 7); + blocks.push(header); + if (type === "0") blocks.push(content, Buffer.alloc((512 - (content.length % 512)) % 512)); + } + return Buffer.concat([...blocks, Buffer.alloc(1024)]); +} + +/** Entries for a layer that holds these files, with every parent directory first. */ +function layerOf(files: Record): Entry[] { + const entries = new Map(); + for (const [name, content] of Object.entries(files)) { + const parts = name.split("/"); + for (let depth = 1; depth < parts.length; depth += 1) { + const directory = `${parts.slice(0, depth).join("/")}/`; + if (!entries.has(directory)) entries.set(directory, { name: directory }); + } + entries.set(name, { name, content }); + } + return [...entries.values()]; +} + +/** + * What `docker buildx build --output type=oci` writes for one platform, with + * these layers: tar streams, or the files of a layer. `members` names the + * members of the archive the way buildx does; a test can name them otherwise. + */ +function ociArchive(layers: (Buffer | Record)[], { members = ["blobs", "index.json", "oci-layout"], tamper = (_layout: string) => {} } = {}) { + const root = fresh(); + const layout = path.join(root, "layout"); + mkdirSync(path.join(layout, "blobs", "sha256"), { recursive: true }); + const blob = (bytes: Buffer) => { + writeFileSync(path.join(layout, "blobs", "sha256", sha256(bytes).slice(7)), bytes); + return { digest: sha256(bytes), size: bytes.length }; + }; + const descriptors = layers.map((layer) => ({ + mediaType: "application/vnd.oci.image.layer.v1.tar+gzip", + ...blob(gzipSync(Buffer.isBuffer(layer) ? layer : tarOf(layerOf(layer)))), + })); + const manifest = blob(Buffer.from(JSON.stringify({ schemaVersion: 2, config: blob(Buffer.from("{}")), layers: descriptors }))); + writeFileSync(path.join(layout, "index.json"), JSON.stringify({ schemaVersion: 2, manifests: [{ mediaType: "application/vnd.oci.image.manifest.v1+json", ...manifest }] })); + writeFileSync(path.join(layout, "oci-layout"), '{"imageLayoutVersion":"1.0.0"}'); + tamper(layout); + const archive = path.join(root, "image.oci.tar"); + expect(spawnSync("tar", ["-cf", archive, "-C", layout, ...members]).status).toBe(0); + return { archive, digest: manifest.digest, layers: descriptors }; +} + +describe("OCI archive reader", () => { + it("reads the image, its layers and their entries", async () => { + const image = ociArchive([{ "a/one": "1" }, { "a/two": "22", top: "t" }]); + const read = readOciArchive(image.archive); + expect(read.descriptor.digest).toBe(image.digest); + expect(read.layers.map((layer) => layer.digest)).toEqual(image.layers.map((layer) => layer.digest)); + const listed = await listOciLayers(image.archive); + expect(listed.digest).toBe(image.digest); + expect(listed.layers.map((layer) => layer.entries.map((entry) => `${entry.kind} ${entry.name}`))).toEqual([ + ["directory a", "file a/one"], + ["directory a", "file a/two", "file top"], + ]); + }); + + it("finds a member only under the name buildx gives it", () => { + // `tar -cf x -C layout .` names the members ./index.json and ./blobs/... + // A reader that accepted those would read archives no registry tool reads. + expect(() => readOciArchive(ociArchive([{ a: "1" }], { members: ["."] }).archive)).toThrow(/has no member index\.json/); + }); + + it("refuses a manifest or a layer that does not have its digest", async () => { + const swapped = ociArchive([{ a: "1" }], { + tamper: (layout) => { + const index = JSON.parse(readFileSync(path.join(layout, "index.json"), "utf8")); + writeFileSync(path.join(layout, "blobs", "sha256", index.manifests[0].digest.slice(7)), '{"schemaVersion":2,"layers":[]}'); + }, + }); + expect(() => readOciArchive(swapped.archive)).toThrow(/the manifest does not have the digest the index names/); + const other = gzipSync(tarOf(layerOf({ a: "another file of the same length?" }))); + const changed = ociArchive([{ a: "1" }], { + tamper: (layout) => { + const index = JSON.parse(readFileSync(path.join(layout, "index.json"), "utf8")); + const manifest = JSON.parse(readFileSync(path.join(layout, "blobs", "sha256", index.manifests[0].digest.slice(7)), "utf8")); + const layer = path.join(layout, "blobs", "sha256", manifest.layers[0].digest.slice(7)); + // Other bytes of the same length, so only the digest can tell. + writeFileSync(layer, Buffer.concat([other, Buffer.alloc(4096)]).subarray(0, readFileSync(layer).length)); + }, + }); + await expect(listOciLayers(changed.archive)).rejects.toThrow(); + const index = ociArchive([{ a: "1" }], { + tamper: (layout) => writeFileSync(path.join(layout, "index.json"), JSON.stringify({ schemaVersion: 2, manifests: [] })), + }); + expect(() => readOciArchive(index.archive)).toThrow(/must hold exactly one image manifest/); + }); + + it("reads layers the system's tar wrote, with long names and links", async () => { + // GNU tar and bsdtar write long names in two different ways. BuildKit uses a third. + const directory = fresh(); + const deep = `node_modules/.pnpm/${"a".repeat(60)}/node_modules/${"b".repeat(60)}/${"c".repeat(40)}`; + mkdirSync(path.join(directory, deep), { recursive: true }); + writeFileSync(path.join(directory, deep, "file.bin"), "long"); + symlinkSync(`${deep}/file.bin`, path.join(directory, "link")); + const tarball = spawnSync("tar", ["-cf", "-", "-C", directory, "."], { maxBuffer: 16 * 1024 * 1024 }); + expect(tarball.status).toBe(0); + const { archive } = ociArchive([tarball.stdout]); + const entries = (await listOciLayers(archive)).layers[0].entries; + expect(entries.find((entry) => entry.name === `${deep}/file.bin`)).toMatchObject({ kind: "file", size: 4 }); + expect(entries.find((entry) => entry.name === "link")).toMatchObject({ kind: "link", target: `${deep}/file.bin` }); + const out = fresh(); + await unpackOciImage(archive, out); + expect(readFileSync(path.join(out, deep, "file.bin"), "utf8")).toBe("long"); + expect(readFileSync(path.join(out, "link"), "utf8")).toBe("long"); + }); +}); + +describe("unpacking an image", () => { + it("writes every layer in order: files with their modes, directories, links and hard links", async () => { + const image = ociArchive([ + tarOf([ + { name: "bin/" }, + { name: "bin/tool", content: "#!/bin/sh\n", mode: 0o755 }, + { name: "bin/again", type: "1", linkname: "bin/tool" }, + { name: "current", type: "2", linkname: "bin/tool" }, + { name: "sealed/", mode: 0o555 }, + { name: "sealed/read-only", content: "ro", mode: 0o444 }, + ]), + tarOf([{ name: "./" }, { name: "./bin/" }, { name: "./bin/other", content: "x" }, { name: "new/deep/file", content: "made without its directories" }]), + ]); + const out = fresh(); + const result = await unpackOciImage(image.archive, out); + expect(result).toEqual({ digest: image.digest, layers: 2, files: 6 }); + expect(readFileSync(path.join(out, "bin/tool"), "utf8")).toBe("#!/bin/sh\n"); + expect(lstatSync(path.join(out, "bin/tool")).mode & 0o7777).toBe(0o755); + expect(lstatSync(path.join(out, "bin/again")).ino).toBe(lstatSync(path.join(out, "bin/tool")).ino); + expect(readlinkSync(path.join(out, "current"))).toBe("bin/tool"); + expect(lstatSync(path.join(out, "sealed")).mode & 0o7777).toBe(0o555); + expect(lstatSync(path.join(out, "sealed/read-only")).mode & 0o7777).toBe(0o444); + expect(readFileSync(path.join(out, "bin/other"), "utf8")).toBe("x"); + expect(readFileSync(path.join(out, "new/deep/file"), "utf8")).toBe("made without its directories"); + expect(Math.round(lstatSync(path.join(out, "bin/tool")).mtimeMs / 1000)).toBe(946684800); + }); + + it("writes large files whole", async () => { + const large = Buffer.alloc(3 * 1024 * 1024 + 17, "n"); + const { archive } = ociArchive([tarOf([{ name: "large.bin", content: large }, { name: "after", content: "still aligned" }])]); + const out = fresh(); + await unpackOciImage(archive, out); + expect(sha256(readFileSync(path.join(out, "large.bin")))).toBe(sha256(large)); + expect(readFileSync(path.join(out, "after"), "utf8")).toBe("still aligned"); + }); + + it.each<[string, Entry[][], RegExp]>([ + ["a whiteout", [[{ name: "a/" }, { name: "a/.wh.gone" }]], /is a whiteout: the image only adds files/], + ["an opaque directory marker", [[{ name: "a/" }, { name: "a/.wh..wh..opq" }]], /is a whiteout/], + ["an absolute path", [[{ name: "/etc/passwd", content: "x" }]], /is absolute/], + ["a path that leaves the tree", [[{ name: "../outside", content: "x" }]], /is not a plain relative path/], + ["a path that goes up inside the tree", [[{ name: "a/" }, { name: "a/../b", content: "x" }]], /is not a plain relative path/], + ["a file behind a link", [[{ name: "link", type: "2", linkname: "/tmp" }, { name: "link/file", content: "x" }]], /is behind link, which is not a directory/], + ["a file behind a link of an earlier layer", [[{ name: "link", type: "2", linkname: "." }], [{ name: "link/file", content: "x" }]], /is behind link/], + ["a file behind a file", [[{ name: "a", content: "x" }, { name: "a/b", content: "y" }]], /is behind a, which is not a directory/], + ["a file a later layer writes again", [[{ name: "a", content: "1" }], [{ name: "a", content: "2" }]], /a layer writes a again: the image only adds files/], + ["a link over a file", [[{ name: "a", content: "1" }], [{ name: "a", type: "2", linkname: "b" }]], /a layer writes a again/], + ["a directory over a file", [[{ name: "a", content: "1" }], [{ name: "a/" }]], /a layer writes a again, as a directory/], + ["a file over a directory", [[{ name: "a/" }], [{ name: "a", content: "1" }]], /a layer writes a again/], + ["a hard link to a path outside the tree", [[{ name: "a", type: "1", linkname: "../../etc/passwd" }]], /hard link target ..\/..\/etc\/passwd is not a plain relative path/], + ["a hard link to nothing", [[{ name: "a", type: "1", linkname: "missing" }]], /is a hard link to missing, which is not a file of the image/], + ["a hard link to a link", [[{ name: "l", type: "2", linkname: "/etc/passwd" }, { name: "a", type: "1", linkname: "l" }]], /which is not a file of the image/], + ["a device", [[{ name: "dev", type: "3" }]], /not a file, a directory or a link/], + ["a fifo", [[{ name: "pipe", type: "6" }]], /not a file, a directory or a link/], + ["a file in place of the root", [[{ name: "./", type: "0", content: "x" }]], /replaces the image root/], + ])("refuses %s", async (_label, layers, expected) => { + const out = fresh(); + await expect(unpackOciImage(ociArchive(layers.map(tarOf)).archive, out)).rejects.toThrow(expected); + // Nothing was written outside the destination. + expect(existsSync(path.join(path.dirname(out), "outside"))).toBe(false); + }); + + it("writes only into an empty directory", async () => { + const out = fresh(); + mkdirSync(out, { recursive: true }); + writeFileSync(path.join(out, "left-over"), "x"); + await expect(unpackOciImage(ociArchive([{ a: "1" }]).archive, out)).rejects.toThrow(/is not empty/); + }); + + it("is a command that says which image it unpacked", () => { + const image = ociArchive([{ "a/one": "1" }]); + const out = fresh(); + const run = (...args: string[]) => spawnSync(process.execPath, [ociScript, "unpack", ...args], { encoding: "utf8" }); + const passed = run(image.archive, "--out", out); + expect(passed.status).toBe(0); + expect(passed.stdout).toContain(`Unpacked 1 files from the 1 layers of ${image.digest}`); + expect(readFileSync(path.join(out, "a/one"), "utf8")).toBe("1"); + expect(run(image.archive).stderr).toMatch(/unpack takes exactly one OCI archive and --out DIR/); + expect(run(image.archive, "--out", out).stderr).toMatch(/is not empty/); + expect(run(image.archive, "--into", out).stderr).toMatch(/unpack does not take --into/); + expect(spawnSync(process.execPath, [ociScript, "extract", image.archive], { encoding: "utf8" }).stderr).toMatch(/Usage/); + }); +}); + +describe("image layers", () => { + // Archive N is file N of the receipt. The last file is the Runner's own output. + const receipt = JSON.stringify({ files: [{ path: "node_modules/big/big.bin" }, { path: "node_modules/node/bin/node" }, { path: "dist/cli/sidecar.cjs" }] }); + const large = { "provider-pack/node_modules/node/bin/node": "node", "provider-pack/node_modules/big/big.bin": "big" }; + const rest = { + "runner-image.json": "{}", "paperclip-runnerd": "elf", "pnpm-lock.yaml": "lock", + "provider-pack/provider-pack.json": "{}", "provider-pack/dist/cli/sidecar.cjs": "sidecar", + }; + const stable = { "provider-pack.archives/0.tar.zst": "0", "provider-pack.archives/1.tar.zst": "1" }; + const changing = { "provider-pack.archives/2.tar.zst": "2", "provider-pack.archives/overlay.tar.zst": "overlay", "provider-pack.archive.json": receipt }; + type Layers = Record[]; + const problemsOf = async (archives: { slim?: Layers; full?: Layers }) => (await checkRunnerImageLayers({ + slim: archives.slim ? ociArchive(archives.slim).archive : null, full: archives.full ? ociArchive(archives.full).archive : null, + })).problems.join("\n"); + + it("accepts a full image that is the slim image plus the two transport layers", async () => { + const result = await checkRunnerImageLayers({ slim: ociArchive([large, rest]).archive, full: ociArchive([large, rest, stable, changing]).archive }); + expect(result.problems).toEqual([]); + expect(result.layers.slim.map((layer) => layer.role)).toEqual(RUNNER_IMAGE_LAYERS.slim); + expect(result.layers.full.map((layer) => layer.role)).toEqual(RUNNER_IMAGE_LAYERS.full); + expect(RUNNER_IMAGE_LAYERS.full.slice(0, 2)).toEqual(RUNNER_IMAGE_LAYERS.slim); + // The same blobs, not only the same files. + expect(result.layers.full.slice(0, 2).map((layer) => layer.digest)).toEqual(result.layers.slim.map((layer) => layer.digest)); + }); + + it("checks one variant alone, and needs at least one", async () => { + expect(await problemsOf({ slim: [large, rest] })).toBe(""); + expect(await problemsOf({ full: [large, rest, stable, changing] })).toBe(""); + await expect(checkRunnerImageLayers({})).rejects.toThrow(/needs --slim, --full or both/); + }); + + it.each<[string, { slim?: Layers; full?: Layers }, RegExp]>([ + ["a full image whose shared layers are not the slim image's blobs", + { slim: [large, rest], full: [large, { ...rest, "paperclip-runnerd": "another build" }, stable, changing] }, + /the full image does not start with the layers of the slim image/], + ["a full image with the slim layers in another order", + { slim: [large, rest], full: [rest, large, stable, changing] }, /the full image does not start with the layers of the slim image/], + ["a slim image with the transport layers", { slim: [large, rest, stable, changing] }, /the slim image has 4 layers, not 2/], + ["a slim image that holds a transport archive", { slim: [large, { ...rest, "provider-pack.archives/1.tar.zst": "1" }] }, + /slim: transport content is in the layers both variants share \(2\): provider-pack\.archives, provider-pack\.archives\/1\.tar\.zst/], + ["a slim image that holds a transport archive under another directory", { slim: [large, { ...rest, "provider-pack/spare/0.tar.zst": "0" }] }, + /slim: transport content is in the layers both variants share \(1\): provider-pack\/spare\/0\.tar\.zst/], + ["a slim image that holds the archives directory somewhere else", { slim: [large, { ...rest, "backup/provider-pack.archives/overlay.bin": "x" }] }, + /slim: transport content is in the layers both variants share \(2\): backup\/provider-pack\.archives, backup\/provider-pack\.archives\/overlay\.bin/], + ["a slim image that holds a receipt inside the pack", { slim: [{ ...large, "provider-pack/node_modules/provider-pack.archive.json": "{}" }, rest] }, + /slim: transport content is in the layers both variants share \(1\): provider-pack\/node_modules\/provider-pack\.archive\.json/], + ["a file that two layers of the slim image write", { slim: [large, { ...rest, "provider-pack/node_modules/node/bin/node": "another node" }] }, + /slim: more than one layer writes \(1\): provider-pack\/node_modules\/node\/bin\/node/], + ["a file that a transport layer writes over a shared layer", { full: [large, rest, stable, { ...changing, "pnpm-lock.yaml": "another lock" }] }, + /full: more than one layer writes \(1\): pnpm-lock\.yaml/], + ["an archive that both transport layers write", { full: [large, rest, stable, { ...changing, "provider-pack.archives/1.tar.zst": "another 1" }] }, + /full: more than one layer writes \(1\): provider-pack\.archives\/1\.tar\.zst/], + ["a full image in a single layer", { full: [{ ...large, ...rest, ...stable, ...changing }] }, /the full image has 1 layers, not 4/], + ["the receipt in a shared layer", { full: [large, { ...rest, "provider-pack.archive.json": receipt }, stable, changing] }, + /full: transport content is in the layers both variants share/], + ["a file outside the pack in the first layer", { full: [{ ...large, "paperclip-runnerd": "elf" }, rest, stable, changing] }, + /full: the first layer holds entries outside the pack's dependency files/], + ["the Runner's own large output in the first layer", { full: [{ ...large, "provider-pack/dist/cli/sidecar.cjs": "sidecar" }, rest, stable, changing] }, + /full: the first layer holds entries outside the pack's dependency files/], + ["a large dependency file left in the layer that changes with every build", + { full: [{ "provider-pack/node_modules/node/bin/node": "node" }, { ...rest, "provider-pack/node_modules/big/big.bin": "big" }, stable, changing] }, + /full: the first layer lacks \(1\): provider-pack\/node_modules\/big\/big\.bin/], + ["the overlay archive in the stable transport layer", + { full: [large, rest, { ...stable, "provider-pack.archives/overlay.tar.zst": "overlay" }, changing] }, + /full: the third layer holds something other than transport archives/], + ["a pack file in the last layer", { full: [large, rest, stable, { ...changing, "provider-pack/extra.json": "{}" }] }, + /full: the last layer holds something other than transport content/], + ["a stable archive in the layer that changes with every build", + { full: [large, rest, { "provider-pack.archives/0.tar.zst": "0" }, { ...changing, "provider-pack.archives/1.tar.zst": "1" }] }, + /full: the third layer lacks \(1\): provider-pack\.archives\/1\.tar\.zst/], + ["the archive of the Runner's own output in the stable layer", + { full: [large, rest, { ...stable, "provider-pack.archives/2.tar.zst": "2" }, { "provider-pack.archives/overlay.tar.zst": "overlay", "provider-pack.archive.json": receipt }] }, + /full: the third layer holds, against the receipt, \(1\): provider-pack\.archives\/2\.tar\.zst/], + ["an archive the receipt does not list", { full: [large, rest, { ...stable, "provider-pack.archives/3.tar.zst": "3" }, changing] }, + /full: the third layer holds, against the receipt, \(1\): provider-pack\.archives\/3\.tar\.zst/], + ["no receipt in the last layer", + { full: [large, rest, stable, { "provider-pack.archives/2.tar.zst": "2", "provider-pack.archives/overlay.tar.zst": "overlay" }] }, + /full: the last layer lacks \(1\): provider-pack\.archive\.json/], + ])("refuses %s", async (_label, archives, expected) => { + expect(await problemsOf(archives)).toMatch(expected); + }); + + it("is a command that prints the layer table of each variant", () => { + const run = (...args: string[]) => spawnSync(process.execPath, [ociScript, "check-layers", ...args], { encoding: "utf8" }); + const slim = ociArchive([large, rest]).archive; + const passed = run("--slim", slim, "--full", ociArchive([large, rest, stable, changing]).archive); + expect(passed.status).toBe(0); + expect(passed.stdout).toMatch(/slim layer 2: sha256:[0-9a-f]{64} +\d+ bytes +\d+ entries +everything else/); + expect(passed.stdout).toMatch(/full layer 4: sha256:[0-9a-f]{64} +\d+ bytes +\d+ entries +the other transport archives, the overlay archive and the receipt/); + const failed = run("--slim", slim, "--full", ociArchive([large, rest, stable]).archive); + expect(failed.status).toBe(1); + expect(failed.stderr).toMatch(/the full image has 3 layers, not 4/); + expect(run().stderr).toMatch(/needs --slim, --full or both/); + expect(run(slim).stderr).toMatch(/takes no positional argument/); + expect(run("--variant", "slim").stderr).toMatch(/check-layers does not take --variant/); + }); +}); diff --git a/server/src/__tests__/runner-image-workflow.test.ts b/server/src/__tests__/runner-image-workflow.test.ts index 36cc97d438a..a1f9e565e68 100644 --- a/server/src/__tests__/runner-image-workflow.test.ts +++ b/server/src/__tests__/runner-image-workflow.test.ts @@ -47,13 +47,28 @@ describe("Runner image workflow", () => { for (const script of scripts) expect(script).not.toContain("${{"); }); + it("gives every image build one export and a time limit", () => { + // A command with two exports stalled on the hosted runners until the job + // was cancelled. One export for each command, and a limit on each step, + // so a stall fails in minutes. + const building = workflow.split(/\n(?= {6}- name: )/).filter((step) => step.includes("docker buildx build")); + expect(building.length).toBeGreaterThanOrEqual(3); + for (const step of building) { + expect(step).toMatch(/^ {8}timeout-minutes: \d+$/m); + for (const command of step.split("docker buildx build").slice(1)) expect(command.match(/--output /g) ?? []).toHaveLength(1); + } + // The trees the checks read come from the archives, not from a second export. + expect(workflow).toContain("node scripts/runner-image-oci.mjs unpack"); + expect(workflow.match(/type=local/g)).toHaveLength(2); + }); + it("runs for a pull request that changes any input of the image identity", () => { const paths = [...workflow.matchAll(/^ {6}- (\S+)$/gm)].map((match) => match[1]); const covered = (file: string) => paths.some((pattern) => pattern === file || (pattern.endsWith("/**") && (file === pattern.slice(0, -3) || file.startsWith(pattern.slice(0, -2))))); // .dockerignore is not in the identity, but it decides which files the build receives. for (const input of ["Dockerfile", ".dockerignore", ".github/workflows/runner-image.yml", "docker/runner-image/Dockerfile.smoke", - ...RUNNER_IMAGE_CONTEXT_INPUTS]) { + "scripts/runner-image-oci.mjs", ...RUNNER_IMAGE_CONTEXT_INPUTS]) { expect(covered(input), input).toBe(true); } }); diff --git a/server/src/services/native-runtime/provider-pack-archive.test.ts b/server/src/services/native-runtime/provider-pack-archive.test.ts index ec1b1ec1916..ee891ed4925 100644 --- a/server/src/services/native-runtime/provider-pack-archive.test.ts +++ b/server/src/services/native-runtime/provider-pack-archive.test.ts @@ -94,6 +94,56 @@ async function layeredFixture() { return { root, pack, receipt, archive }; } +it("writes the same archive for the same file every time, with nothing after the frame", async () => { + // Ending the compressor while its last chunk was still queued made Node + // finish the zstd stream twice, and about half the archives got an empty + // frame at their end. An image layer of these archives then never repeated. + const emptyFrame = Buffer.from("28b52ffd2000010000", "hex"); + const seen = new Set(); + for (let trial = 0; trial < 12; trial += 1) { + const { pack } = await fixture(); + const large = path.join(pack, "bin", "large"); + await fs.writeFile(large, Buffer.alloc(1024 * 1024, 42), { mode: 0o755 }); + await fs.utimes(large, 0, 0); + const receipt = await createProviderPackLayers(pack); + seen.add(receipt.files[0].archive.sha256); + for (const name of ["0.tar.zst", "overlay.tar.zst"]) { + const bytes = await fs.readFile(path.join(`${pack}.archives`, name)); + expect(bytes.subarray(-emptyFrame.length).equals(emptyFrame), name).toBe(false); + } + } + expect([...seen]).toHaveLength(1); +}); + +it("names the archives of dependency files without regard to the Runner's own large files", async () => { + // Archive N holds file N of the receipt. `dist` sorts before `node_modules`, + // so in path order one more large file in the Runner's build output renamed + // the archive of every dependency file. + const large = Buffer.alloc(1024 * 1024, 42); + const receiptOf = async (own: string[]) => { + const { pack } = await fixture(); + for (const file of ["node_modules/dependency/tool", "bin/large", ...own]) { + await fs.mkdir(path.dirname(path.join(pack, file)), { recursive: true }); + await fs.writeFile(path.join(pack, file), large, { mode: 0o755 }); + await fs.utimes(path.join(pack, file), 0, 0); + } + const receipt = await createProviderPackLayers(pack); + const archive = (await readProviderPackArchive(pack, digest))!; + if (!("kind" in archive)) throw Error("Expected layered archive"); + // What a reader pairs: file N of the receipt with N.tar.zst. + const paired = await Promise.all(archive.files.map(async (file: { path: string; archive: { sha256: string } }, index: number) => + [file.path, `${index}.tar.zst`, createHash("sha256").update(await fs.readFile(path.join(`${pack}.archives`, `${index}.tar.zst`))).digest("hex") === file.archive.sha256])); + return { paths: receipt.files.map((file: { path: string }) => file.path), paired }; + }; + const before = await receiptOf(["dist/cli/one.js"]); + const after = await receiptOf(["dist/cli/one.js", "dist/a-new-large-file.js", "dist/cli/two.js"]); + expect(before.paths).toEqual(["bin/large", "node_modules/dependency/tool", "dist/cli/one.js"]); + expect(after.paths).toEqual(["bin/large", "node_modules/dependency/tool", "dist/a-new-large-file.js", "dist/cli/one.js", "dist/cli/two.js"]); + // The dependency files keep their archive names, and every pairing a reader makes still holds. + expect(after.paired.slice(0, 2)).toEqual(before.paired.slice(0, 2)); + expect(after.paired.every(([, , matches]) => matches)).toBe(true); +}); + it.skipIf(!tar || !hasZstd)("reuses only byte-matched image files, keeps modes, and never shares writable hardlinks", async () => { const { root, pack, archive } = await layeredFixture(); const remote = await runner(root); From 497ccba8f1f3a4caf03887f5ee1d155c650bd6bf Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:06:24 -0600 Subject: [PATCH 08/15] fix(native): replace a reattached Runner that left its recovery read unanswered (#21272) 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 Codex runs execute in a remote Runner that the server controls over the durable PRP channel > - When a run is interrupted, a same-run retry reattaches the live Runner and reads its session (`session.snapshot`) before it continues > - On staging, the reattached Runner authenticated and restored its session, and then did not answer the read > - The recovery kept that Runner, so each later attempt adopted the same Runner and failed the same way until the attempt budget ended the run > - This pull request makes the next attempt replace that Runner with a fresh Runner over its saved journal, and makes a failed Codex history read say what failed > - The benefit is that an interrupted Codex run continues without a manual Retry, and its provider turn is not sent again ## Linked Issues or Issue Description Refs #21161, Refs #21053, Refs #20853 **What happened?** A Codex agent on Daytona ran recovery runs (wake `issue_recovery_action_restored`). In one hour, 11 of about 35 finished runs failed. All failed the same way: - `native_session_recovery_failed: HarnessCapabilityUnavailableError: read is unavailable: Error: runnerd exited while waiting for session.snapshot` (8 runs) - `native_session_recovery_failed: HarnessReconciliationError: codex_history_read_failed: thread/turns/list requires supported paginated history; Error: provider_transport_failed: PRP command session.snapshot timed out (runner connected; pending ahead 0; last runner event seq 338 76s ago)` (3 runs) The run log of each run shows one sequence: 1. Attempt 1 fails with `runnerd did not report the provider turn identity`. The close leaves the Runner alive and unsettled for the same-run reattachment. 2. Attempt 2 adopts that Runner (same PID). The Runner authenticates. The log shows `runnerd restored its durable PRP session and provider thread`. Then the driver's recovery read (`thread/read` or `thread/turns/list`, which both send `session.snapshot`) gets no answer. The Runner still answers WebSocket pings, but it sends no command result and almost no events (`pending ahead 0`, last event 76 s to 391 s earlier). The recovery treats this as transient and detaches. The Runner stays alive. 3. Attempt 3 adopts the same Runner again and fails the same way. In some runs a protocol fault (`thread_binding_mismatch`) closes the transport during the read, so the message is `runnerd exited while waiting for session.snapshot`. 4. The provider attempt budget ends the run. #21161 did not help. Its wait extension applies only while a queued answer is being committed. Here the Runner sent no answer at all. The `paginated history` text was also wrong. `codex-history.ts` called every failed history read unsupported, also a transport timeout. **Expected behavior** A Runner that left a recovery read unanswered is not adopted again. The next attempt starts a fresh Runner from the saved journal, resumes the provider session from the saved checkpoint, and does not send the provider turn again. A failed history read reports the real failure. A Codex build that refuses paginated history falls back to one complete thread read. **Steps to reproduce** 1. Start a Codex run in a remote (Daytona) Runner. 2. Let the first attempt fail at turn start, so that the close keeps the Runner alive. 3. Let the reattached Runner stop answering commands after it authenticates (for example, stop the Runner process after its first answer). 4. See `PRP command session.snapshot timed out (runner connected; pending ahead 0; ...)` on attempt 2 and the same failure on attempt 3, with the same Runner PID. **Paperclip version or commit** Staging Core `57aeda190b` (contains #21161 and #21120). Fixed on `master` after `53608bd1d6`. **Deployment mode** Hosted (staging), remote Daytona sandbox Runner. **Agent adapter(s) involved** Codex (native Runner, `paperclip-runnerd`, `codex_app_server`). ## What Changed - `nativeRecoveryCommandUnanswered` (executor) finds a `native_session_recovery_failed` whose Runner did not answer a recovery command (`PRP command timed out` or `runnerd exited while waiting for `). Identity, authority, integrity and incompatibility refusals do not match. - When such a failure ends a `reattach_remote_runner` attempt on a sandbox target, the failure detail records `adoptedRunnerUnanswered: true`. - `claimNativeRestartRecoveries` copies it to the next claim as `replaceUnansweredRunner: true`, in the same way as `exitedBeforeSessionOpen`. - `verifyRemoteRunnerOrSettledExit` with `replaceUnansweredRunner` keeps all identity checks. When the old Runner is still alive, it returns no adopted process, and the attempt launches a fresh Runner from the saved journal. The existing launch fence stops the old `paperclip-runnerd` on that state folder and its whole lineage, and fails the launch closed when it cannot prove them gone. A Runner that already exited mid-turn keeps the existing fail-closed path, because its provider or tool processes can survive where the fence cannot find them. The task then continues in a fresh session from the saved work. The attempt budget is unchanged. - `codex-history.ts`: a history read that fails without a provider answer is now `codex_history_read_failed: read failed; `. A provider refusal of the method (`-32601` or `-32600`) on the first page falls back to one `thread/read` with `includeTurns: true`. That fallback fails closed when the thread differs, or when turns, items or turn identities are missing. A refusal on a later page still fails closed. - `doc/execution-semantics.md` describes both rules. The launch-fence code comment now names the replacement case. ### Changed existing test `codex-history.test.ts` "does not turn an interrupted page or unsupported method into idle history" used a plain `Error("method not found")` on page 2 and expected the `supported paginated history` text. A plain error is now a failed read, not an unsupported method. The test now uses a real provider refusal (`CodexRpcError` `-32601`) on page 2 and still expects a fail-closed rejection. A new test covers the failed-read message. ## Verification - Red before the fix, green after: - `server/src/services/native-runtime/native-session-executor.test.ts` › "a same-run reattachment whose adopted Runner never answered its recovery read": the replacement and staging-message tests failed on the old code (the Runner was adopted again, the three staging messages were not recognized). Two further tests ("never resumes beside an exited unanswered Runner's lineage") failed on the first revision of this PR, which relaunched beside an exited mid-turn Runner, and pass now. All 15 pass. - `native-runner-restart-recovery.integration.test.ts` › "asks the same-run reattachment to replace a Runner that left its recovery read unanswered" (embedded Postgres): the claim had no `replaceUnansweredRunner` on the old code. Now passes. - `codex-history.test.ts`: 7 new tests failed on the old code. All 16 pass. - Real `paperclip-runnerd` and fake Codex: `runnerd-codex-transport-remote-retention.test.ts` › "continues the same provider thread from a fresh Runner over the journal of a retained Runner that stopped answering, without replaying its turn". It runs the staging sequence: turn started, close keeps the stopped Runner, a second controller adopts it, the Runner stops answering and the controller detaches, the Runner and provider are killed (the launch fence), and a fresh Runner over the same journal returns the same thread. The fake Codex call log shows one `thread/start` and one `turn/start`. - Focused suites: `packages/paperclip-runner` `src/drivers/codex/` plus the remote-retention, adoption and cold-restore transport suites (442 tests). Two suites timed out under parallel load and pass alone. Server: `native-session-executor`, `native-restart-recovery`, `native-runner-restart-recovery.integration`, `runner-lost-mid-turn-continuation` (1714 passed, 21 skipped). - `pnpm typecheck` in `server` (all layers) and `tsc` for `paperclip-runner` source and tests pass. - Not run locally: the container-gated remote Runner suites (`PAPERCLIP_TEST_RUNNER_CONTAINER`) and the full suite. CI covers the full suite. ## Risks - Medium. The replacement relaunches a Runner over a journal that is not settled, but only while the old Runner is alive. Safety comes from three facts: the launch fence stops the old Runner and its lineage with proof or fails the launch; the Runner restores its own durable journal (as local `resume_dead_runner` does); and the real-runnerd test shows that the turn is not sent again. An exited Runner is never relaunched beside its possible survivors. - If the previous close left a `runner.suspend` pending, a fresh Runner can execute it and exit. The attempt then fails as it does today. The usual detach path after an unanswered read sends no suspend. - The replacement uses the existing attempt budget. It does not add attempts. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, browser reads of staging run events and logs), 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 Opus 5.5 --- doc/execution-semantics.md | 32 ++++- .../src/drivers/codex/codex-history.test.ts | 60 ++++++++- .../src/drivers/codex/codex-history.ts | 122 ++++++++++++------ ...d-codex-transport-remote-retention.test.ts | 108 ++++++++++++++++ .../native-runtime/native-restart-recovery.ts | 3 + ...unner-restart-recovery.integration.test.ts | 33 +++++ .../native-session-executor.test.ts | 49 +++++++ .../native-runtime/native-session-executor.ts | 27 +++- 8 files changed, 389 insertions(+), 45 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 4f1daf6b540..29aefe9693b 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1782,6 +1782,35 @@ in-flight turn stay for the next same-run reattachment. An abort (a Stop or the recovery deadline), any identity or authority refusal, any other recovery failure, and a protocol integrity fault still stop it. +A kept Runner can answer its WebSocket pings but no recovery command. On +staging, a reattached Codex Runner authenticated and restored its session, then +left `session.snapshot` unanswered (`pending ahead 0; last runner event seq 338 +76s ago`), and each later attempt adopted the same Runner and failed the same +way until the attempt budget ended the run. When a same-run reattachment fails +because its Runner left a recovery command unanswered (`PRP command timed +out`, or `runnerd exited while waiting for `), and the failure is not an +identity, authority or integrity refusal, the run records +`adoptedRunnerUnanswered` on its failure and the next claim carries +`replaceUnansweredRunner`. That attempt does not adopt the Runner again. After +the usual identity checks it launches a fresh Runner from the Runner's saved +journal and resumes the provider session from the saved checkpoint. This applies +only while the old Runner is alive: the launch fence stops that +`paperclip-runnerd` on the state folder and its whole process lineage, and fails +the launch closed when it cannot prove them gone. A Runner that already exited +mid-turn can leave provider or tool processes that the fence cannot find, so it +keeps the fail-closed path below, and the task continues in a fresh session from +the saved work. The fresh Runner +restores the provider thread; its in-flight turn is reconciled from history and +never submitted again. The provider attempt budget still bounds these attempts. + +A paginated Codex history read (`thread/turns/list`, `thread/items/list`) that +fails without an answer is reported as `codex_history_read_failed: read +failed`, with the underlying error. Only a provider answer that refuses the method +on its first page means the build lacks paginated history. Then the driver reads +the complete thread once (`thread/read` with `includeTurns: true`) and uses its +turns and items, failing closed when that read names another thread or omits +turns, items or turn identities. A refusal on a later page still fails closed. + A failed close can leave its `runner.suspend` (or `runner.shutdown`) pending in the saved journal of a Runner it kept alive. The controller sends one command at a time, so neither that command nor any command queued after it reached the @@ -5896,7 +5925,8 @@ lifecycle `suspended`, an empty outbox and no pending terminal delivery, provide cleanup or warm transition, the retry launches a Runner from that state instead of adopting one. This matches a settled staged source. Any other exit stays fail-closed for reconciliation, and the provider attempt budget still bounds the -retries. +retries. A live Runner that left the previous attempt's recovery read unanswered +is replaced, not adopted (see above). The final admitted provider attempt may use this path; attempts above the limit cannot. Process verification and the final state read share one recovery deadline. A timeout, command failure, transport failure or invalid saved JSON on diff --git a/packages/paperclip-runner/src/drivers/codex/codex-history.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-history.test.ts index 4979549fa59..4a51c29a4ec 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-history.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-history.test.ts @@ -1,10 +1,13 @@ import { describe, it, expect, vi } from "vitest"; +import { CODEX_METHOD_NOT_FOUND, CodexRpcError } from "./app-server-transport.js"; import { readCodexThreadState, readCodexTurnMetadata, readCodexTurnItems, } from "./codex-history.js"; +const unsupported = (method: string) => new CodexRpcError(`${method} is not supported`, CODEX_METHOD_NOT_FOUND); + describe("Codex paginated history", () => { it("reads state without hydrating history", async () => { const request = vi.fn().mockResolvedValue({ thread: { id: "thread" } }); @@ -79,14 +82,67 @@ describe("Codex paginated history", () => { "codex_history_incomplete", ); }); - it("does not turn an interrupted page or unsupported method into idle history", async () => { + it("does not turn an unsupported later page into idle history", async () => { const request = vi .fn() .mockResolvedValueOnce({ data: [], nextCursor: "next" }) - .mockRejectedValueOnce(new Error("method not found")); + .mockRejectedValueOnce(unsupported("thread/turns/list")); await expect(readCodexTurnMetadata({ request }, "thread")).rejects.toThrow( "supported paginated history", ); + expect(request.mock.calls.map(call => call[0])).toEqual(["thread/turns/list", "thread/turns/list"]); + }); + it("names a failed history read as a failed read, not as unsupported history", async () => { + const timeout = new Error("provider_transport_failed: PRP command session.snapshot timed out (runner connected; pending ahead 0)"); + const request = vi.fn().mockRejectedValueOnce(timeout); + await expect(readCodexTurnMetadata({ request }, "thread")).rejects.toThrow( + `codex_history_read_failed: thread/turns/list read failed; Error: ${timeout.message}`, + ); + expect(request).toHaveBeenCalledTimes(1); + }); + it("reads complete turn history from the thread when paginated history is unsupported", async () => { + const request = vi.fn(async (method: string) => { + if (method === "thread/turns/list") throw unsupported(method); + return { thread: { id: "thread", turns: [ + { id: "one", status: "completed", items: [{ id: "answer", type: "agentMessage", text: "done" }] }, + { id: "two", status: "inProgress", items: [] }, + ] } }; + }); + expect(await readCodexTurnMetadata({ request }, "thread")).toEqual([ + { id: "one", status: "completed", items: [], itemsView: "notLoaded" }, + { id: "two", status: "inProgress", items: [], itemsView: "notLoaded" }, + ]); + expect(request).toHaveBeenLastCalledWith("thread/read", { threadId: "thread", includeTurns: true }); + }); + it("reads a turn's items from the thread when paginated items are unsupported", async () => { + const answer = { id: "answer", type: "agentMessage", text: "done" }; + const request = vi.fn(async (method: string) => { + if (method === "thread/items/list") throw unsupported(method); + return { thread: { id: "thread", turns: [ + { id: "one", status: "completed", items: [answer] }, + { id: "two", status: "inProgress", items: [{ id: "other" }] }, + ] } }; + }); + expect(await readCodexTurnItems({ request }, "thread", "one")).toEqual([answer]); + }); + it.each([ + ["another thread", { thread: { id: "other", turns: [] } }, "different driver session"], + ["no turns", { thread: { id: "thread" } }, "supported paginated history"], + ["a turn without a status", { thread: { id: "thread", turns: [{ id: "one" }] } }, "codex_history_incomplete"], + ["a turn without an id", { thread: { id: "thread", turns: [{ status: "completed" }] } }, "codex_history_incomplete"], + ])("fails closed when the unpaginated thread read returns %s", async (_case, thread, message) => { + const request = vi.fn(async (method: string) => { + if (method === "thread/turns/list") throw unsupported(method); + return thread; + }); + await expect(readCodexTurnMetadata({ request }, "thread")).rejects.toThrow(message); + }); + it("fails closed when the unpaginated thread read omits the requested turn's items", async () => { + const request = vi.fn(async (method: string) => { + if (method === "thread/items/list") throw unsupported(method); + return { thread: { id: "thread", turns: [{ id: "one", status: "completed" }] } }; + }); + await expect(readCodexTurnItems({ request }, "thread", "one")).rejects.toThrow("codex_history_incomplete"); }); it("rejects another thread or turn", async () => { await expect( diff --git a/packages/paperclip-runner/src/drivers/codex/codex-history.ts b/packages/paperclip-runner/src/drivers/codex/codex-history.ts index 438f067484e..091db4941b2 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-history.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-history.ts @@ -1,9 +1,13 @@ -import type { CodexAppServerTransport } from "./app-server-transport.js"; +import { isCodexMethodUnavailable, type CodexAppServerTransport } from "./app-server-transport.js"; import { HarnessReconciliationError } from "../../contracts/harness-driver.js"; import { record, text } from "./codex-driver-values.js"; type Requester = Pick; +const TURN_STATUSES = ["inProgress", "completed", "failed", "interrupted", "cancelled"]; + +class CodexPaginatedHistoryUnsupported extends HarnessReconciliationError {} + /** A partial or unsupported provider read is never evidence that work is idle. */ async function pages( transport: Requester, @@ -23,9 +27,14 @@ async function pages( ...(cursor ? { cursor } : {}), }); } catch (error) { - throw new HarnessReconciliationError( - `codex_history_read_failed: ${method} requires supported paginated history; ${String(error)}`, - ); + if (!isCodexMethodUnavailable(error)) + throw new HarnessReconciliationError( + `codex_history_read_failed: ${method} read failed; ${String(error)}`, + ); + const unsupported = `codex_history_read_failed: ${method} requires supported paginated history; ${String(error)}`; + throw page === 0 + ? new CodexPaginatedHistoryUnsupported(unsupported) + : new HarnessReconciliationError(unsupported); } if (!Array.isArray(response.data)) throw new HarnessReconciliationError( @@ -71,31 +80,57 @@ export async function readCodexThreadState( return snapshot; } -export function readCodexTurnMetadata( +function turnIdentity(value: Record): string { + if (!TURN_STATUSES.includes(text(value.status))) { + throw new HarnessReconciliationError( + "codex_history_incomplete: invalid turn status", + ); + } + return text(value.id); +} + +async function readCompleteThreadTurns( + transport: Requester, + threadId: string, + method: string, + cause: unknown, +): Promise[]> { + if (!(cause instanceof CodexPaginatedHistoryUnsupported)) throw cause; + const snapshot = await transport.request("thread/read", { threadId, includeTurns: true }); + const thread = record(snapshot.thread); + if (text(thread.id) !== threadId) + throw new HarnessReconciliationError( + "thread/read returned a different driver session", + ); + if (!Array.isArray(thread.turns)) + throw new HarnessReconciliationError( + `codex_history_read_failed: ${method} requires supported paginated history; thread/read omitted turns`, + ); + const turns = thread.turns.map(record); + for (const turn of turns) { + if (!turnIdentity(turn)) + throw new HarnessReconciliationError( + "codex_history_incomplete: thread/read omitted an identity", + ); + } + return turns; +} + +export async function readCodexTurnMetadata( transport: Requester, threadId: string, ): Promise[]> { - return pages( - transport, - "thread/turns/list", - { threadId, sortDirection: "asc", itemsView: "notLoaded" }, - (value) => { - if ( - ![ - "inProgress", - "completed", - "failed", - "interrupted", - "cancelled", - ].includes(text(value.status)) - ) { - throw new HarnessReconciliationError( - "codex_history_incomplete: invalid turn status", - ); - } - return text(value.id); - }, - ); + try { + return await pages( + transport, + "thread/turns/list", + { threadId, sortDirection: "asc", itemsView: "notLoaded" }, + turnIdentity, + ); + } catch (error) { + const turns = await readCompleteThreadTurns(transport, threadId, "thread/turns/list", error); + return turns.map((turn) => ({ ...turn, items: [], itemsView: "notLoaded" })); + } } export async function readCodexTurnItems( @@ -103,17 +138,28 @@ export async function readCodexTurnItems( threadId: string, turnId: string, ): Promise[]> { - const entries = await pages( - transport, - "thread/items/list", - { threadId, turnId, sortDirection: "asc" }, - (value) => { - if (text(value.turnId) !== turnId) - throw new HarnessReconciliationError( - "thread/items/list returned a different turn", - ); - return text(record(value.item).id); - }, - ); + let entries: Record[]; + try { + entries = await pages( + transport, + "thread/items/list", + { threadId, turnId, sortDirection: "asc" }, + (value) => { + if (text(value.turnId) !== turnId) + throw new HarnessReconciliationError( + "thread/items/list returned a different turn", + ); + return text(record(value.item).id); + }, + ); + } catch (error) { + const turns = await readCompleteThreadTurns(transport, threadId, "thread/items/list", error); + const items = turns.find((turn) => text(turn.id) === turnId)?.items; + if (!Array.isArray(items)) + throw new HarnessReconciliationError( + "codex_history_incomplete: thread/read omitted the turn's items", + ); + return items.map(record); + } return entries.map((entry) => record(entry.item)); } diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-remote-retention.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-remote-retention.test.ts index dd23825af1c..10dc17e21a3 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport-remote-retention.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-remote-retention.test.ts @@ -189,3 +189,111 @@ it("keeps a retained remote Runner for the reattaching controller, which continu await rm(root, { recursive: true, force: true }); } }, 30_000); + +it("continues the same provider thread from a fresh Runner over the journal of a retained Runner that stopped answering, without replaying its turn", async () => { + const root = await mkdtemp(join(tmpdir(), "runnerd-remote-retention-replace-")); + const callLog = join(root, "provider-calls.log"); + const server = createServer(); + let authority: DurablePrpControlPlane | null = null; + server.on("upgrade", (request, socket, head) => { + if (!authority) { socket.destroy(); return; } + authority.handleUpgrade(request, socket, "/runner", head); + }); + await new Promise(resolveListen => server.listen(0, "127.0.0.1", resolveListen)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing replacement test listener"); + const registration = async (next: DurablePrpControlPlane) => { + authority = next; + return { connectUrl: `ws://127.0.0.1:${address.port}/runner`, release: () => { if (authority === next) authority = null; } }; + }; + const children: ReturnType[] = []; + const launch = vi.fn((spec: durableControlPlane.RunnerProcessLaunchSpec) => { + const child = spawn(spec.command, [...spec.args], { cwd: spec.cwd, env: spec.environment, stdio: "ignore", detached: true }); + children.push(child); + return { + child, + completion: new Promise((resolveExit, rejectExit) => { + child.once("error", rejectExit); + child.once("exit", (code, exitSignal) => resolveExit({ code, signal: exitSignal, stdout: "", stderr: "" })); + }), + isExitConfirmed: () => child.exitCode !== null || child.signalCode !== null, + }; + }); + const shared = { + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: resolve(import.meta.dirname, "../../runner/target/debug/fake-codex-app-server"), + codexArgs: ["--state-file", join(root, "provider-state.json"), "--hold-first-durable-turn", "--call-log", callLog], + stateDirectory: root, + prpIdentity: { + runnerInstanceId: "runner-replaced", environmentLeaseId: "lease-replaced", runId: "run-replaced", + normalizedSessionId: "session-replaced", turnId: "turn-replaced", itemId: "item-replaced", + }, + runnerReconnectGraceMs: 5_000, + runnerProcessReconnectGraceMs: null, + controlPlaneRegistration: registration, + runnerProcessLauncher: launch, + }; + const first = createCapabilityRunnerdCodexTransport({ ...shared, closeGraceMs: 600 }); + let adopted: ReturnType | undefined; + let replacement: ReturnType | undefined; + const providerPids: number[] = []; + try { + const opened = await first.transport.request("thread/start", { cwd: root, dynamicTools: codexSemanticToolSpecs() }); + await first.transport.request("turn/start", { input: [{ type: "text", text: "Keep this task active." }] }); + for await (const notification of first.transport.notifications()) { + if (notification.method === "turn/started") break; + } + const wedged = children[0]!.pid!; + providerPids.push(first.evidence().codexPid!); + signal(wedged, "SIGSTOP"); + await expect(first.transport.close("native session execution complete", { retainUnsettledRemoteRunner: true })) + .rejects.toBeInstanceOf(NativeSessionCloseUnrecoverableError); + expect(processState(wedged)).toBe("alive"); + signal(wedged, "SIGCONT"); + const thread = opened.thread as Record; + const resume = { + resumeDynamicTools: codexSemanticToolSpecs(), + resumeProviderSession: { driverSessionId: String(thread.id), providerSessionId: String(thread.sessionId) }, + }; + adopted = createCapabilityRunnerdCodexTransport({ + ...shared, ...resume, + runnerProcessLauncher: vi.fn(() => { throw new Error("Must adopt the existing runner"); }), + adoptExistingRunner: { + pid: wedged, processGroupId: wedged, startedAt: new Date().toISOString(), + isAlive: () => processState(wedged) === "alive", + signal: name => { try { process.kill(-wedged, name); return true; } catch { return false; } }, + }, + }); + adopted.transport.setServerRequestHandler(async () => ({ success: true, contentItems: [] })); + await expect(adopted.transport.request("thread/read", {})).resolves.toEqual( + expect.objectContaining({ thread: expect.objectContaining({ id: thread.id }) })); + signal(wedged, "SIGSTOP"); + await adopted.transport.detachControllerForRestart!(); + expect(processState(wedged)).toBe("alive"); + const journal = JSON.parse(await readFile(join(root, "runner", "runner-state.json"), "utf8")) as Record; + expect(journal.lifecycle).not.toBe("suspended"); + signal(-wedged, "SIGKILL"); + for (const pid of providerPids) signal(pid, "SIGKILL"); + await vi.waitFor(() => expect(processState(wedged)).toBe("gone"), { timeout: 5_000 }); + replacement = createCapabilityRunnerdCodexTransport({ + ...shared, ...resume, + }); + replacement.transport.setServerRequestHandler(async () => ({ success: true, contentItems: [] })); + await expect(replacement.transport.request("thread/read", {})).resolves.toEqual( + expect.objectContaining({ thread: expect.objectContaining({ id: thread.id }) })); + if (replacement.evidence().codexPid) providerPids.push(replacement.evidence().codexPid!); + expect(launch).toHaveBeenCalledTimes(2); + expect(replacement.evidence().runnerPid).toBe(children[1]!.pid); + const calls = (await readFile(callLog, "utf8")).trim().split("\n"); + expect(calls.filter(call => call === "thread/start")).toHaveLength(1); + expect(calls.filter(call => call === "turn/start")).toHaveLength(1); + } finally { + await replacement?.transport.close().catch(() => undefined); + await adopted?.transport.close().catch(() => undefined); + for (const child of children) { signal(child.pid, "SIGCONT"); signal(child.pid ? -child.pid : null, "SIGKILL"); } + for (const pid of providerPids) signal(pid, "SIGKILL"); + server.closeAllConnections(); + if (server.listening) await new Promise(resolveClose => server.close(() => resolveClose())); + await rm(root, { recursive: true, force: true }); + } +}, 60_000); diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index ff976cc2d45..76ea996d941 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -103,6 +103,7 @@ export type NativeRestartRecoveryClaim = /** Discovery evidence only; executor revalidates the encrypted header. */ stagedAttachment?: Pick; exitedBeforeSessionOpen?: true; + replaceUnansweredRunner?: true; } | { kind: "resume_dead_runner"; @@ -2121,6 +2122,8 @@ export async function claimNativeRestartRecoveries(input: { }, ...(!pluginTask && row.coordinator.failureDetail?.runnerExitedBeforeSessionOpen === true ? { exitedBeforeSessionOpen: true as const } : {}), + ...(!pluginTask && row.coordinator.failureDetail?.adoptedRunnerUnanswered === true + ? { replaceUnansweredRunner: true as const } : {}), } satisfies NativeRestartRecoveryClaim; } if (claimKind === "reattach_existing_runner") { 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 9a01087d3e5..336971ff09f 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 @@ -1573,6 +1573,39 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); expect(run?.processPid).toBe(remotePid); }); + it.each([true, false])("asks the same-run reattachment to replace a Runner that left its recovery read unanswered: %s", async (unanswered) => { + const fixture = await seedRun(`remote-unanswered-${unanswered}`); + await fixture.db.update(heartbeatRuns).set({ + processPid: null, + processStartedAt: new Date("2020-01-01T00:00:00Z"), + runnerProfileJson: { + nativeWorkspaceSync: { + schema: "paperclip.native-workspace-sync/v1", state: "prepared", + descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), + workspaceId: "workspace", leaseId: "lease", providerLeaseId: "sandbox", + remoteCwd: "/workspace", + }, + sessionCheckpoint: { + identity: { companyId, agentId, issueId: fixture.issueId, runId: fixture.runId, + sessionId: fixture.native.normalizedSessionId }, + providerSessionId: "provider-session", + process: { providerPid: process.pid }, + }, + }, + }).where(eq(heartbeatRuns.id, fixture.runId)); + await fixture.db.update(nativeRunFinalizations).set({ attempt: 2, failureDetail: { + message: "native_session_recovery_failed: HarnessReconciliationError: codex_history_read_failed: thread/turns/list requires supported paginated history; Error: provider_transport_failed: PRP command session.snapshot timed out (runner connected; pending ahead 0; last runner event seq 337 111s ago)", + recoveryMode: "exact_checkpoint_resume", checkpointExists: true, + ...(unanswered ? { adoptedRunnerUnanswered: true } : {}), + } }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const [claim] = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "graceful", runIds: [fixture.runId] }); + expect(claim).toMatchObject({ kind: "reattach_remote_runner", runId: fixture.runId, providerAttempt: 2, + remote: { providerLeaseId: "sandbox", remoteCwd: "/workspace" } }); + expect(claim?.kind === "reattach_remote_runner" ? claim.replaceUnansweredRunner : "not remote") + .toBe(unanswered ? true : undefined); + }); + it("keeps a restart recovery's attempt credit while the agent directory is busy, then resumes at attempt 3", async () => { const fixture = await seedRun("remote-busy-directory"); await fixture.db.update(heartbeatRuns).set({ 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 06c2ec0115a..8f841d8be5a 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -476,6 +476,7 @@ import { verifyRemoteRunnerReattachment, stopStaleRemoteRunnerBeforeBootstrap, verifyRemoteRunnerOrSettledExit, + nativeRecoveryCommandUnanswered, readRemoteProviderPackManifest, verifyRemoteProviderPackManifest, prepareRemoteProviderPackOnTarget, @@ -1141,6 +1142,54 @@ describe("remote controller restart adoption", () => { target: exitedRunner(state) as never, identity, runId: "run", normalizedSessionId: "session", providerAttempt }).catch(caught => caught); expect(readRemoteRunnerRecoveryError(error)).toMatchObject({ stage: "process_verification", reason: "process_not_running" }); }); + describe("a same-run reattachment whose adopted Runner never answered its recovery read", () => { + const unanswered = { ...claim, replaceUnansweredRunner: true as const }; + const midTurn = { lifecycle: "turn_active", outbox: [{ id: 338 }], pendingTerminalDelivery: null, pendingProviderCleanup: null }; + it.each([2, 3])("launches a fresh Runner instead of adopting the live one again on attempt %i", async providerAttempt => { + const { target, execute } = fixture(midTurn); + await expect(verifyRemoteRunnerOrSettledExit({ claim: unanswered, target: target as never, identity, + runId: "run", normalizedSessionId: "session", providerAttempt })).resolves.toBeUndefined(); + expect(execute.mock.calls.some(([request]) => /kill -/.test(request.args.join(" ")))).toBe(false); + }); + it("adopts the live Runner when the earlier attempt did not report an unanswered read", async () => { + const { target } = fixture(midTurn); + const adopted = await verifyRemoteRunnerOrSettledExit({ claim, target: target as never, identity, + runId: "run", normalizedSessionId: "session", providerAttempt: 2 }); + expect(adopted?.pid).toBe(123); + }); + it.each([ + ["a mid-turn exit whose provider and tools may survive it", midTurn, 3], + ["a pending provider cleanup", { ...midTurn, pendingProviderCleanup: { pid: 7 } }, 3], + ["an exhausted attempt budget", midTurn, 4], + ] as const)("never resumes beside an exited unanswered Runner's lineage: %s", async (_case, state, providerAttempt) => { + const target = exitedRunner(state); + const error = await verifyRemoteRunnerOrSettledExit({ claim: unanswered, target: target as never, + identity, runId: "run", normalizedSessionId: "session", providerAttempt }).catch(caught => caught); + expect(readRemoteRunnerRecoveryError(error)).toMatchObject({ stage: "process_verification", reason: "process_not_running" }); + }); + it("keeps the live Runner's identity checks before replacing it", async () => { + const { target } = fixture({ ...midTurn, runnerInstanceId: "different" }); + await expect(verifyRemoteRunnerOrSettledExit({ claim: unanswered, target: target as never, identity, + runId: "run", normalizedSessionId: "session", providerAttempt: 2 })).rejects.toThrow("runner_remote_recovery_identity_mismatch"); + }); + it.each([ + "native_session_recovery_failed: HarnessReconciliationError: codex_history_read_failed: thread/turns/list requires supported paginated history; Error: provider_transport_failed: PRP command session.snapshot timed out (runner connected; pending ahead 0; last runner event seq 338 76s ago)", + "native_session_recovery_failed: HarnessCapabilityUnavailableError: read is unavailable: Error: runnerd exited while waiting for session.snapshot", + "native_session_recovery_failed: Error: runner_ingress_unavailable: PRP command runner.drain timed out (runner connected; pending ahead 0; last runner event seq 93 391s ago)", + ])("recognizes the staging recovery read that got no answer: %s", message => { + expect(nativeRecoveryCommandUnanswered(new Error(message))).toBe(true); + expect(nativeRecoveryCommandUnanswered(new Error("wrapped", { cause: new Error(message) }))).toBe(true); + }); + it.each([ + "runnerd did not report the provider turn identity", + "provider_transport_failed: PRP command session.snapshot timed out", + "native_session_recovery_failed: provider resumed a different session", + "native_session_recovery_failed: provider_transport_failed: PRP command session.snapshot timed out; native_adopted_provider_identity_mismatch", + "native_session_recovery_failed: restart interruption history is incomplete", + ])("does not replace a Runner for another failure: %s", message => { + expect(nativeRecoveryCommandUnanswered(new Error(message))).toBe(false); + }); + }); it.each([ ["an unsettled suspension", { ...settledSuspension, outbox: [{ id: 1 }] }, 2], ["a pending provider cleanup", { ...settledSuspension, pendingProviderCleanup: { pid: 7 } }, 2], diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 853df3f50b6..f8fc648a289 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -8860,6 +8860,16 @@ export function nativeRunnerExitedBeforeSessionOpen(error: unknown): boolean { return nativeRunnerExitConfirmed(error) && runnerExitBeforeSessionOpenMessage(error); } +export function nativeRecoveryCommandUnanswered(error: unknown, depth = 0): boolean { + if (!error || typeof error !== "object" || depth > 5) return false; + const value = error as Record; + const message = typeof value.message === "string" ? value.message : ""; + if (message.startsWith("native_session_recovery_failed:") + && /PRP command [\w.]+ timed out|runnerd exited while waiting for [\w.]+/.test(message) + && !/mismatch|different|identity|authority|integrity|incompatible/i.test(message)) return true; + return nativeRecoveryCommandUnanswered(value.cause, depth + 1); +} + /** Same provider, category and message (numbers ignored): a retry would meet the same fault. */ export function nativeStartupFailureSignature(failure: unknown): string | null { const value = record(failure); @@ -13054,6 +13064,9 @@ async function executePaperclipNativeSessionAttempt( ? { runnerExitConfirmed: true } : {}), ...(input.runnerExecutionTarget?.kind === "remote" && nativeRunnerExitedBeforeSessionOpen(error) ? { runnerExitedBeforeSessionOpen: true } : {}), + ...(input.runnerExecutionTarget?.kind === "remote" && input.restartRecovery?.kind === "reattach_remote_runner" + && input.restartRecovery.remote.kind !== "plugin_task" && nativeRecoveryCommandUnanswered(error) + ? { adoptedRunnerUnanswered: true } : {}), ...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}), ...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}), recoveryOwner: recoveryProjection.recoveryOwner, @@ -14987,7 +15000,8 @@ const REMOTE_RUNNER_PROCESS_STDERR_TRIM_SCRIPT = * A launch therefore stops a `paperclip-runnerd` that is still serving this * exact `--state-dir`. A launch only happens after the server chose not to * adopt a Runner: a same-run reattachment proves the marker's Runner gone - * first, and a transient reattachment failure never reaches a launch. + * first, or replaces a Runner that left the previous attempt's recovery read + * unanswered. Any other transient reattachment failure never reaches a launch. * * The stop runs in node ($1 the runnerd binary, $2 the state directory, then * candidate PIDs): @@ -15270,16 +15284,20 @@ async function readRemoteRunnerExitEvidence(runner: CommandManagedRuntimeRunner, export async function verifyRemoteRunnerOrSettledExit( input: Parameters[0] & { providerAttempt: number; - claim: { exitedBeforeSessionOpen?: true } }, + claim: { exitedBeforeSessionOpen?: true; replaceUnansweredRunner?: true } }, ) { const recoveryDeadline = Math.min(input.recoveryDeadline ?? Number.POSITIVE_INFINITY, Date.now() + REMOTE_RUNNER_RECOVERY_PROBE_BUDGET_MS); const stall = input.stall ?? remoteRunnerPluginStall(input.recoveryDeadline); + const target = input.target; + const replaceUnanswered = input.claim.replaceUnansweredRunner === true + && input.providerAttempt <= NATIVE_PROVIDER_RECOVERY_ATTEMPT_LIMIT + && target?.kind === "remote" && target.transport === "sandbox" && Boolean(target.runner); + let verified: Awaited>; try { - return await verifyRemoteRunnerReattachment({ ...input, recoveryDeadline, stall }); + verified = await verifyRemoteRunnerReattachment({ ...input, recoveryDeadline, stall }); } catch (error) { const diagnostic = readRemoteRunnerRecoveryError(error); - const target = input.target; const exitedBeforeSessionOpen = input.claim.exitedBeforeSessionOpen === true; if (input.providerAttempt > NATIVE_PROVIDER_RECOVERY_ATTEMPT_LIMIT || diagnostic?.stage !== "process_verification" || diagnostic.reason !== "process_not_running" || @@ -15292,6 +15310,7 @@ export async function verifyRemoteRunnerOrSettledExit( : state.lifecycle !== "suspended" || !describeExitedRemoteRunner(state).runnerSettled) throw error; return undefined; } + return replaceUnanswered ? undefined : verified; } function runnerStateAllowsFreshStart(state: Record): boolean { From b9308f9828e30785dbc119e810bdad20e5c26fee Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:15:04 -0600 Subject: [PATCH 09/15] fix(ui): keep long agent names inside task columns (#21155) ## Thinking Path > - Paperclip helps people manage AI agents and their work. > - Task views show the assignee and creator in fixed-width columns. > - Long names can extend past those columns and cover adjacent values. > - The identity labels already support text truncation but need a width limit. > - This pull request limits each identity to its task column. > - Names stay on one line, avatars keep their size, and adjacent values stay readable. ## Linked Issues or Issue Description **What happened?** Long agent and human names extend outside the Responsible and Kicked off by columns in task views. **Expected behavior** Names fit inside each column. Long names show an ellipsis. Avatars remain visible. The title attribute retains the full name. **Steps to reproduce** 1. Open a task view with Responsible and Kicked off by columns visible. 2. Use a long agent name for the assignee and creator. 3. Observe names covering adjacent columns. ## What Changed - Limit agent and human identity width to the containing task column. - Add a production-component Storybook example for long names, names without spaces, and short names. - Add browser layout checks for both identity columns, avatar size, full text, adjacent values, and row height in both themes at 640px and 1200px. ## Verification - The browser regression failed before the fix: an identity reached x=424 while its column ended at x=144. - The focused Chromium suite passes all four cases at 640px and 1200px in light and dark modes. - `pnpm --dir ui exec vitest run src/components/IssueColumns.test.tsx src/components/IssuesList.test.tsx`: 83 tests pass. - `pnpm --filter @paperclipai/ui typecheck`: passes. - `node scripts/check-token-gates.mjs` and `git diff --check`: pass. - `pnpm verify` returned exit 2 because the browser test requires broader CI coverage. The complete PR CI run supplies that coverage. - All tests, typecheck, build, and e2e gates pass on final commit `f73568822add60b4659f2cbdad0196fdfe010d3b`: https://github.com/paperclipai/paperclip/actions/runs/43271777908. - The separate commitperclip review passed: https://github.com/paperclipai/paperclip/actions/runs/43271777344. - Greptile gives this commit 5/5. There are no open findings or review threads. - All 61 checks are complete: 57 success, 1 neutral, and 3 skipped. The Storybook workflow was skipped; the focused browser suite passed locally. ## Risks Low risk. The width limit applies only to identity labels in shared task columns. The full name remains in the DOM and the existing title attribute. No API or stored-data changes. ## Model Used OpenAI Codex, based on GPT-6, with code tools and Chromium browser checks. The runtime does not expose a more specific model ID. ## 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 --------- Co-authored-by: Paperclip --- .../task-column-identities.spec.ts | 44 +++++++++++++ ui/src/components/IssueColumns.tsx | 8 +-- .../tasks/task-column-identities.stories.tsx | 62 +++++++++++++++++++ 3 files changed, 110 insertions(+), 4 deletions(-) create mode 100644 tests/storybook-visual/task-column-identities.spec.ts create mode 100644 ui/storybook/stories/tasks/task-column-identities.stories.tsx diff --git a/tests/storybook-visual/task-column-identities.spec.ts b/tests/storybook-visual/task-column-identities.spec.ts new file mode 100644 index 00000000000..30e9a46c8fa --- /dev/null +++ b/tests/storybook-visual/task-column-identities.spec.ts @@ -0,0 +1,44 @@ +import { expect, test } from "@playwright/test"; + +for (const width of [640, 1200]) { + for (const theme of ["light", "dark"]) { + test(`task identities fit their columns at ${width}px in ${theme} mode`, async ({ page }) => { + await page.setViewportSize({ width, height: 800 }); + await page.goto(`/iframe.html?id=task-column-identities--long-names&viewMode=story&globals=theme:${theme}`); + await expect(page.getByTestId("agent-spaces").locator('[data-slot="agent-avatar"]')).toHaveCount(2); + await page.evaluate(() => document.fonts.ready); + + for (const id of ["agent-spaces", "agent-unbroken", "human", "short"]) { + const row = page.getByTestId(id); + const cells = row.locator(":scope > span > span"); + await expect(cells).toHaveCount(4); + for (const index of [0, 1]) { + const cell = cells.nth(index); + const identity = cell.locator("[title]"); + const name = await identity.getAttribute("title"); + const metrics = await identity.evaluate(element => { + const cell = element.parentElement!.getBoundingClientRect(); + const identity = element.getBoundingClientRect(); + const avatar = element.firstElementChild!.getBoundingClientRect(); + const text = element.lastElementChild as HTMLElement; + return { + right: identity.right, cellRight: cell.right, + avatarWidth: avatar.width, avatarLeft: avatar.left, cellLeft: cell.left, + textWidth: text.clientWidth, textContentWidth: text.scrollWidth, + overflow: getComputedStyle(text).textOverflow, + }; + }); + expect(metrics.right, `${id} identity escapes column ${index}`).toBeLessThanOrEqual(metrics.cellRight + 1); + expect(metrics.avatarLeft).toBeGreaterThanOrEqual(metrics.cellLeft); + expect(metrics.avatarWidth).toBe(24); + expect(metrics.textWidth).toBeGreaterThan(0); + expect(metrics.textContentWidth > metrics.textWidth).toBe(id !== "short"); + expect(metrics.overflow).toBe("ellipsis"); + await expect(identity.locator(":scope > span").last()).toHaveText(name!); + } + await expect(cells.nth(2)).toHaveText("Paperclip"); + expect((await row.boundingBox())!.height).toBeLessThanOrEqual((await page.getByTestId("short").boundingBox())!.height); + } + }); + } +} diff --git a/ui/src/components/IssueColumns.tsx b/ui/src/components/IssueColumns.tsx index ce0d244856e..54be14b99f0 100644 --- a/ui/src/components/IssueColumns.tsx +++ b/ui/src/components/IssueColumns.tsx @@ -332,7 +332,7 @@ export function InboxIssueTrailingColumns({ ); @@ -345,7 +345,7 @@ export function InboxIssueTrailingColumns({ name={userLabel} avatarUrl={assigneeUserAvatarUrl} size="sm" - className="min-w-0" + className="min-w-0 max-w-full" /> ); @@ -368,7 +368,7 @@ export function InboxIssueTrailingColumns({ @@ -387,7 +387,7 @@ export function InboxIssueTrailingColumns({ name={creatorUserLabel} avatarUrl={creatorUserAvatarUrl} size="sm" - className="min-w-0" + className="min-w-0 max-w-full" /> diff --git a/ui/storybook/stories/tasks/task-column-identities.stories.tsx b/ui/storybook/stories/tasks/task-column-identities.stories.tsx new file mode 100644 index 00000000000..4cb7ddd66b2 --- /dev/null +++ b/ui/storybook/stories/tasks/task-column-identities.stories.tsx @@ -0,0 +1,62 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { InboxIssueTrailingColumns } from "@/components/IssueColumns"; +import { storybookIssues } from "../../fixtures/paperclipData"; + +const names = [ + { id: "agent-spaces", name: "Research and Engineering Agent With a Very Long Display Name", human: false }, + { id: "agent-unbroken", name: "ResearchAndEngineeringAgentWithAVeryLongUnbrokenDisplayName", human: false }, + { id: "human", name: "Alexandria Morgan With a Very Long Display Name", human: true }, + { id: "short", name: "Ada", human: false }, +]; + +function TaskColumnIdentities() { + return ( +
+ {names.map(({ id, name, human }) => ( +
+ +
+ ))} +
+ ); +} + +const meta = { + id: "task-column-identities", + title: "Tasks and conversations/Task creation and lifecycle/Column identities", + component: TaskColumnIdentities, + parameters: { + layout: "padded", + paperclip: { + capabilities: ["tasks/organize"], + status: "current", + implementation: "production", + boundary: "fixtures", + notes: "Production task columns with long agent and human names, unbroken names, and a fitting-name control. Verifies layout only; assignment and attribution persistence need live acceptance.", + }, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; +export const LongNames: Story = {}; From afe86e9dedf1197737f5cae3249017a1f4987a9f Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Thu, 12 Nov 2026 20:20:45 -0800 Subject: [PATCH 10/15] fix(runtime): record a plugin task's stop receipt when its stop is proven (#21237) 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 plugin environment runs each Paperclip Runner turn as a provider task, and a follow-up run can continue the same Claude/ACPX conversation from the saved checkpoint > - Core authorizes that continuation only when the predecessor run's remote execution has stopped (`remoteExecutionHasStopped`), so two Runners never write one checkpoint > - The predecessor's own settlement already proves the stop: the provider reports `executionStopped`, and Core then completes the task > - On a per-turn (ephemeral) lease, Core records the stop receipt only when it releases the lease, and that release can be held for a long time (for example by a pending workspace export) > - In that window, an ordinary follow-up fails with `adapter_failed: Plugin Runner retained session is not authorized`, even though the stop is already proven > - This pull request records the stop receipt when the stop is proven, and the stop check accepts it before the release > - The benefit is that follow-ups continue as soon as the predecessor is proven stopped, and the release gates keep their meaning ## Linked Issues or Issue Description Fixes #21211 Refs #21214 and #21223. Those cover the creation fence for same-run recovery, which still requires a released lease. Production evidence for this change: in both observed failures, the predecessor was a per-turn plugin run. Its `task.settle` completed with all provider calls successful. Core then did not release its lease for 30 minutes or more, and no release call was made in that time. The follow-up failed in checkpoint recovery (`recoverPluginRunnerCheckpoint` → `resolvePluginTaskResume`) within seconds of admission. ## What Changed - `server/src/services/environment-task-runtime.ts` - After a recorded provider stop, `complete` writes the bound stop receipt (`remoteTerminationReceipt(..., { state: "stopped" })`) on the current lease for every lease policy. Before, it did this only for `reuse_by_environment` leases. Reusable tasks still confirm every owner and still move retained owners to released. - New work on a lease (`submit`, `copilot_metadata`, first portable resume) removes the stop receipt in the same write that clears `runnerTaskExecutionStopped`. A replacement physical task does not copy the old receipt. - `server/src/services/remote-execution-termination.ts` - New `hasBoundRemoteStopReceipt` checks only the receipt binding (company, run, lease, provider and physical task). `hasRemoteTerminationReceipt` uses it and keeps its released-only semantics. Resource cleanup gates do not change. - `remoteExecutionHasStopped` and `stoppedRemoteCleanupScopes` accept a lease that is released with its receipt, or that is still `active` (not released) with a bound stop receipt. A lease whose release started and did not settle does not count. After release starts, the release owns the receipt. - New `remoteExecutionHasReleased` gives the release-based answer. - `server/src/services/environment-run-orchestrator.ts`: same-run plugin recovery uses `remoteExecutionHasReleased`. The same-run resume check after it requires released receipts, so its behavior does not change. - `resolvePluginTaskResume` keeps its checks and their order. Its refusal now names the first failing check: `Plugin Runner retained session is not authorized (reason: )`, for example `predecessor_not_stopped`, `scope_mismatch` or `identity_mismatch`. The old message stays as the prefix, and no ids go into it. The stale-availability recheck in `environment-task-runtime.ts` names its refusal the same way. Production telemetry for #21211 could not tell which check fired. The next occurrence will show it. - `doc/execution-semantics.md` and `doc/testing-native-remote-continuity.md` describe the stop receipt and when it is recorded. Caller audit for the changed meaning of `remoteExecutionHasStopped`: | Caller | Needs | Decision | | --- | --- | --- | | `agent-instruction-working-copies.ts` | stop | Accepts. Directory cleanup still requires a released "destroyed" receipt. | | `environment-run-orchestrator.ts` | release | Moved to `remoteExecutionHasReleased`. | | `plugin-task-resume.ts` | stop | Accepts. This is the fix. | | `native-runtime/native-runner-ownership.ts` | stop | Accepts. `hasPendingRunCleanup` still counts the active lease as pending. | | `native-runtime/preserved-native-result-finalization.ts` | stop | Accepts. Workspace recovery has its own gate. | | `heartbeat/case-handoff-lifecycle.ts` | stop | Accepts. `hasPendingRunCleanup` still holds active leases. | | `heartbeat/run-control.ts` (3 sites) | stop | Accepts. Stop acknowledgement and quarantined ownership retirement. Holds and blockers still apply on the normal path. | | `heartbeat/runtime-execution.ts` | stop | Accepts. Release errors still fail it. | ## Verification From `server/`, after `node scripts/agent-preflight.mjs`: - `npx vitest run src/__tests__/environment-task-authority.integration.test.ts`: 10/10 pass. The 2 new tests fail without the fix. - The plugin task and environment runtime suites (`environment-task-authority.integration`, `plugin-runner-task.integration`, `plugin-warm-tasks.integration`, `environment-task-runtime`, `plugin-task-source-recovery.integration`, `environment-runtime`): 6 files, 366 pass. - The audited caller suites (`agent-instruction-working-copies`, case handoff legacy and native, `environment-run-orchestrator`, `heartbeat-case-handoff`, `explicit-native-continuation`, `run-control`, `native-remote-retry-admission`, `preserved-native-response-wait`): 9 files, 806 pass. - `pnpm --filter @paperclipai/server typecheck`: pass. The new integration tests cover: - `complete` writes a bound stop receipt on a still-active ephemeral lease. `remoteExecutionHasStopped` is true and `hasRemoteTerminationReceipt` is still false. - `resolvePluginTaskResume` (inspect and launch) authorizes a follow-up's new task, and the real host `read_state` checkpoint read succeeds, while the predecessor's release is held. - Refusals: no provider stop, a receipt for another provider task, an unstopped sibling lease, and a release in progress. - New work on the lease removes the receipt. Release overwrites the receipt with its own receipt. Warm owners keep their behavior. I did not add an executor-level test. `native-session-executor.test.ts` mocks `resolvePluginTaskResume`, so the integration test runs the real checkpoint read path instead. I did not run the full suite locally. CI runs it. ## Risks - `remoteExecutionHasStopped` now returns true earlier for a run whose leases are still held. Each caller is audited above. Callers that need released resources use the release-based predicates. - The stop receipt can now be on an `active` lease. The SQL readers of `remoteExecutionTermination` (cost accounting, execution blockers, idle-work proof, orphan settlement) also require a released status. `pinFailedObservedWorkspace` treats an active ephemeral lease with a receipt as not pinnable. That path applies only to the remote-workspace flow and falls back to `preserveNativeFailedWorkspace`. - Leases that settled before this change have no early receipt. They continue to wait for their release. - Nothing compares the refusal message exactly. Matchers use substrings, and run failure classification does not use the message. - A follow-up still fails closed if the predecessor's stop was never proven. This change does not add a recoverable wait. - The reason the release was held in production is not addressed here. - No migration and no API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, sub-agents, Honeycomb trace queries) and extended thinking. One sub-agent wrote the change. A second session reviewed it before this pull request. ## 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/execution-semantics.md | 17 ++ doc/testing-native-remote-continuity.md | 8 +- ...ronment-task-authority.integration.test.ts | 251 +++++++++++++++++- .../services/environment-run-orchestrator.ts | 6 +- .../src/services/environment-task-runtime.ts | 29 +- server/src/services/plugin-task-resume.ts | 85 ++++-- .../services/remote-execution-termination.ts | 59 +++- 7 files changed, 396 insertions(+), 59 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 29aefe9693b..1bb81b0e687 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3483,6 +3483,23 @@ agent, workspace, retained session, and termination of prior execution. The checkpoint must match the exact Runner, lease, run, session, turn, and item. A missing restart claim does not remove these checks or authorize a fresh session. +A plugin task records its stop receipt when it settles. When the provider +reports that the task stopped, completing the task writes a receipt bound to +the exact company, run, lease, provider and task, even before the lease is +released. Lease release can be held long after that, for example by a pending +workspace export. A per-turn follow-up in a later run can then resume the +retained checkpoint: for continuation, every lease of the predecessor run must +be released with its termination receipt or still be active with this stop +receipt and its release not started. Once release or destroy of a lease starts, +release owns the receipt: the lease does not count until release settles with +its own receipt, because the provider can be releasing the task's resources +while the lease is still active. Dispatching new work on a lease removes its +stop receipt. Resource cleanup gates, and a same-run retry's replacement of earlier +leases, still require the released termination receipt. +When the server refuses the resume, the error keeps the message +`Plugin Runner retained session is not authorized` and names the first failed +check, for example `(reason: predecessor_not_stopped)`. + These checks can refuse the exact checkpoint before the retry claims a new provider attempt. For example, the interrupted attempt can leave the provider state not suspended. The run error then names the interrupted attempt first, as diff --git a/doc/testing-native-remote-continuity.md b/doc/testing-native-remote-continuity.md index 2e98d99556f..3631fa6dcb3 100644 --- a/doc/testing-native-remote-continuity.md +++ b/doc/testing-native-remote-continuity.md @@ -80,7 +80,13 @@ The executor tests cover Claude and Codex, including reopening blocked work. The lease-authority integration test uses PostgreSQL to check that checkpoint discovery cannot launch work or bypass a termination receipt. A stale negative availability flag requires a fresh provider status before the checkpoint can -be read for continuation. +be read for continuation. It also checks that a follow-up can resume while the +predecessor's lease release is held, using the stop receipt that the task +recorded when it settled. A receipt for another task, a second predecessor +lease without stop proof, or a release that has started and not settled still +refuses continuation. The test holds a real lease release inside the provider +call and checks that the follow-up is refused until that release settles. +Each refusal is checked by the reason that it names. The executor can restore one quarantined journal in the same session scope. It requires a terminal prior run, completed commands, a terminal event, and an diff --git a/server/src/__tests__/environment-task-authority.integration.test.ts b/server/src/__tests__/environment-task-authority.integration.test.ts index ffb37044169..4b0c151513e 100644 --- a/server/src/__tests__/environment-task-authority.integration.test.ts +++ b/server/src/__tests__/environment-task-authority.integration.test.ts @@ -3,7 +3,9 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { eq } from "drizzle-orm"; import { agents, companies, createDb, environmentLeases, environments, heartbeatRuns, plugins, sandboxCreationOperations } from "@paperclipai/db"; import { resolvePluginTaskResume } from "../services/environment-task-runtime.js"; -import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; +import type { PluginTaskResumeRefusal } from "../services/plugin-task-resume.js"; +import { hasBoundRemoteStopReceipt, hasRemoteTerminationReceipt, remoteExecutionHasReleased, remoteExecutionHasStopped, + remoteTerminationReceipt } from "../services/remote-execution-termination.js"; import { environmentRuntimeService } from "../services/environment-runtime.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; import { createPluginRunnerTaskOwner } from "../services/native-runtime/plugin-runner-task.js"; @@ -12,6 +14,8 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro const support = await getEmbeddedPostgresTestSupport(); const databaseSuite = support.supported ? describe : describe.skip; +/** A resume refusal keeps its original message and names the check that failed. */ +const refused = (reason: PluginTaskResumeRefusal) => `Plugin Runner retained session is not authorized (reason: ${reason})`; databaseSuite("environment task lease authority", () => { let db: ReturnType; @@ -227,17 +231,29 @@ databaseSuite("environment task lease authority", () => { await expect(authorize()).resolves.toBe("old-task"); for (const field of ["runnerInstanceId", "environmentLeaseId", "normalizedSessionId", "runId"]) { await expect(resolvePluginTaskResume(db, { companyId, leaseId: nextLeaseId, - priorIdentity: { ...priorIdentity, [field]: randomUUID() } })).rejects.toThrow("not authorized"); + priorIdentity: { ...priorIdentity, [field]: randomUUID() } })).rejects.toThrow(refused("predecessor_candidate_missing")); } await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, oldRunId)); - await expect(authorize()).rejects.toThrow("not authorized"); + await expect(authorize()).rejects.toThrow(refused("predecessor_run_active")); await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, oldRunId)); - await expect(resolvePluginTaskResume(db, { companyId: randomUUID(), leaseId: nextLeaseId, priorIdentity })).rejects.toThrow("not authorized"); + await expect(resolvePluginTaskResume(db, { companyId: randomUUID(), leaseId: nextLeaseId, priorIdentity })).rejects.toThrow(refused("next_lease_missing")); await db.update(environmentLeases).set({ metadata: { ...pin, pluginId: randomUUID() } }).where(eq(environmentLeases.id, nextLeaseId)); - await expect(authorize()).rejects.toThrow("not authorized"); + await expect(authorize()).rejects.toThrow(refused("provider_mismatch")); await db.update(environmentLeases).set({ metadata: pin }).where(eq(environmentLeases.id, nextLeaseId)); + await db.update(environmentLeases).set({ providerLeaseId: "old-task" }).where(eq(environmentLeases.id, nextLeaseId)); + await expect(authorize()).rejects.toThrow(refused("same_provider_task")); + await db.update(environmentLeases).set({ providerLeaseId: "new-task" }).where(eq(environmentLeases.id, nextLeaseId)); + const otherEnvironmentId = randomUUID(); + await db.insert(environments).values({ id: otherEnvironmentId, name: `Fixture ${otherEnvironmentId}`, driver: "plugin", config: {} }); + await db.update(environmentLeases).set({ environmentId: otherEnvironmentId }).where(eq(environmentLeases.id, nextLeaseId)); + await expect(authorize()).rejects.toThrow(refused("scope_mismatch")); + await db.update(environmentLeases).set({ environmentId }).where(eq(environmentLeases.id, nextLeaseId)); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, nextRunId)); + await expect(authorize()).rejects.toThrow(refused("next_run_not_running")); + await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, nextRunId)); + await expect(authorize()).resolves.toBe("old-task"); await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, oldLeaseId)); - await expect(authorize()).rejects.toThrow("not authorized"); + await expect(authorize()).rejects.toThrow(refused("predecessor_not_stopped")); await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, oldLeaseId)); let sessionStateAvailable = false; const operations: string[] = []; @@ -259,8 +275,8 @@ databaseSuite("environment task lease authority", () => { operation: { kind: "ensure_ownership", operationId: portableTargetLeaseId, sourceTaskId: "old-task", sourceGeneration: "source-generation", targetGeneration: "target-generation", policy: "ordinary", identity: checkpointIdentity }, } } }).where(eq(environmentLeases.id, oldLeaseId)); - await expect(authorize()).rejects.toThrow("not authorized"); - await expect(resolvePluginTaskResume(db, { companyId, leaseId: nextLeaseId, priorIdentity, inspectCheckpoint: true })).rejects.toThrow("not authorized"); + await expect(authorize()).rejects.toThrow(refused("predecessor_candidate_missing")); + await expect(resolvePluginTaskResume(db, { companyId, leaseId: nextLeaseId, priorIdentity, inspectCheckpoint: true })).rejects.toThrow(refused("predecessor_candidate_missing")); await expect(runtime.task({ companyId, leaseId: nextLeaseId, operation: { kind: "read_state", identity: checkpointIdentity, resumeFrom: "old-task", } })).rejects.toThrow("not authorized"); @@ -269,19 +285,19 @@ databaseSuite("environment task lease authority", () => { } })).rejects.toThrow("not authorized"); expect(call).not.toHaveBeenCalled(); await db.update(environmentLeases).set({ metadata: { ...source.metadata, runnerTaskSessionRetained: false } }).where(eq(environmentLeases.id, oldLeaseId)); - await expect(authorize()).rejects.toThrow("not authorized"); + await expect(authorize()).rejects.toThrow(refused("predecessor_candidate_missing")); await expect(resolvePluginTaskResume(db, { companyId, leaseId: nextLeaseId, priorIdentity, inspectCheckpoint: true })).resolves.toBe("old-task"); const inspect = () => runtime.task({ companyId, leaseId: nextLeaseId, operation: { kind: "read_state", identity: checkpointIdentity, resumeFrom: "old-task", } }); - await expect(inspect()).rejects.toThrow("not authorized"); - await expect(authorize()).rejects.toThrow("not authorized"); + await expect(inspect()).rejects.toThrow(refused("checkpoint_status_unconfirmed")); + await expect(authorize()).rejects.toThrow(refused("predecessor_candidate_missing")); // Discovery cannot launch, and cannot bypass the original termination receipt. await expect(runtime.task({ companyId, leaseId: nextLeaseId, operation: { kind: "submit", preparedLaunchId: "fixture", projectIds: [], bootstrapTicket: "fixture", runner, resumeFrom: "old-task", } })).rejects.toThrow("resume identity mismatch"); await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, oldLeaseId)); - await expect(inspect()).rejects.toThrow("not authorized"); + await expect(inspect()).rejects.toThrow(refused("predecessor_not_stopped")); expect(operations).toEqual(["status"]); await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, oldLeaseId)); sessionStateAvailable = true; @@ -350,4 +366,215 @@ databaseSuite("environment task lease authority", () => { }); + async function seedTaskPlugin(name: string) { + const companyId = randomUUID(), agentId = randomUUID(), environmentId = randomUUID(), pluginId = randomUUID(); + await db.insert(companies).values({ id: companyId, name, issuePrefix: `T${companyId.slice(0, 7).replace(/-/g, "").toUpperCase()}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", adapterType: "paperclip_runner" }); + await db.insert(environments).values({ id: environmentId, name: `Fixture ${environmentId}`, driver: "plugin", + config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } }); + await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: `fixture-${name}`, version: "1.0.0", status: "ready", manifestJson: { + capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }], + } as never }); + const pin = { driver: "plugin", pluginId, driverKey: "tasks", environmentId, runnerTaskLease: true, + runnerTaskProjectAuthValidation: { configurationId: "fixture", provider: "openai", projectIds: [] } }; + return { companyId, agentId, environmentId, pin }; + } + + it("records a per-turn task's stop receipt when it settles, before its held lease release", async () => { + const { companyId, agentId, environmentId, pin } = await seedTaskPlugin("per-turn-stop"); + const oldRunId = randomUUID(), nextRunId = randomUUID(), oldLeaseId = randomUUID(), nextLeaseId = randomUUID(); + await db.insert(heartbeatRuns).values([ + { id: oldRunId, companyId, agentId, invocationSource: "manual", status: "running" }, + { id: nextRunId, companyId, agentId, invocationSource: "manual", status: "running" }, + ]); + const prior = { id: oldLeaseId, companyId, environmentId, heartbeatRunId: oldRunId, provider: "plugin:fixture:tasks", providerLeaseId: "old-task" }; + const oldIdentity = { runnerId: "runner", leaseId: oldLeaseId, runId: oldRunId, sessionId: "session", turnId: "prior-turn", itemId: "prior-item" }; + await db.insert(environmentLeases).values([ + { ...prior, status: "active", leasePolicy: "ephemeral", metadata: { ...pin, runnerTaskDispatched: true, + runnerTaskExecutionStopped: false, runnerTaskSessionRetained: false, runnerTaskIdentity: oldIdentity } }, + { id: nextLeaseId, companyId, environmentId, heartbeatRunId: nextRunId, provider: prior.provider, providerLeaseId: "new-task", + status: "active", leasePolicy: "ephemeral", metadata: pin }, + ]); + let executionStopped = false; + const call = vi.fn(async (_id: string, method: string, params: any) => method !== "environmentTask" ? undefined + : ["read_state", "archive_state"].includes(params.operation.kind) + ? { kind: "state", taskId: params.taskId, state: { schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended", + ...(params.operation.identity ?? params.operation.priorIdentity) } } + : params.operation.kind === "status" + ? { kind: "status", taskId: params.taskId, phase: executionStopped ? "completed" : "running", executionStopped, sessionStateAvailable: executionStopped } + : { kind: "accepted", taskId: params.taskId }); + const workers = { isRunning: () => true, getWorker: () => ({ supportedMethods: ["environmentTask", "environmentReleaseLease"] }), call } as unknown as PluginWorkerManager; + const runtime = environmentRuntimeService(db, { pluginWorkerManager: workers }); + const readLease = async (id: string) => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, id)))[0]!; + const priorIdentity = { runnerInstanceId: "runner", normalizedSessionId: "session", environmentLeaseId: oldLeaseId, runId: oldRunId }; + const checkpointIdentity = { ...priorIdentity, turnId: "prior-turn", itemId: "prior-item" }; + const runner = { runnerId: "runner", leaseId: oldLeaseId, sessionId: "session", runId: nextRunId, + turnId: "turn", itemId: "item", harness: "codex", protocolMin: 1, protocolMax: 3 }; + const authorize = (inspectCheckpoint?: boolean) => resolvePluginTaskResume(db, { companyId, leaseId: nextLeaseId, priorIdentity, inspectCheckpoint }); + + // Neither a running status nor a completion without a provider stop is stop proof. + await runtime.task({ companyId, leaseId: oldLeaseId, operation: { kind: "status" } }); + await runtime.task({ companyId, leaseId: oldLeaseId, operation: { kind: "complete" } }); + expect((await readLease(oldLeaseId)).metadata).not.toHaveProperty("remoteExecutionTermination"); + expect(await remoteExecutionHasStopped(db, companyId, oldRunId)).toBe(false); + + // The turn checkpoint stops and completes the task; release of the lease is still held. + executionStopped = true; + await runtime.task({ companyId, leaseId: oldLeaseId, operation: { kind: "stop" } }); + await runtime.task({ companyId, leaseId: oldLeaseId, operation: { kind: "status" } }); + await runtime.task({ companyId, leaseId: oldLeaseId, operation: { kind: "complete" } }); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, oldRunId)); + const settled = await readLease(oldLeaseId); + expect(settled).toMatchObject({ status: "active", releasedAt: null, cleanupStatus: null, metadata: { + runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true, runnerTaskDispatched: false, + remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId, runId: oldRunId, leaseId: oldLeaseId, + provider: prior.provider, providerLeaseId: "old-task", state: "stopped" } } }); + expect(hasBoundRemoteStopReceipt(settled)).toBe(true); + expect(hasRemoteTerminationReceipt(settled)).toBe(false); + expect(await remoteExecutionHasStopped(db, companyId, oldRunId)).toBe(true); + expect(await remoteExecutionHasReleased(db, companyId, oldRunId)).toBe(false); + + // The follow-up can inspect and launch from the checkpoint while the predecessor is unreleased. + await expect(authorize(true)).resolves.toBe("old-task"); + await expect(authorize()).resolves.toBe("old-task"); + await expect(runtime.task({ companyId, leaseId: nextLeaseId, operation: { + kind: "read_state", identity: checkpointIdentity, resumeFrom: "old-task", + } })).resolves.toMatchObject({ kind: "state", state: { ...checkpointIdentity, lifecycle: "suspended" } }); + + // A receipt for another physical task, a second unstopped predecessor lease, or a release + // that started without settling still refuses authority. + await db.update(environmentLeases).set({ metadata: { ...settled.metadata, remoteExecutionTermination: + remoteTerminationReceipt({ ...prior, providerLeaseId: "other-task" }, { providerLeaseId: "other-task", state: "stopped" }) } }) + .where(eq(environmentLeases.id, oldLeaseId)); + await expect(authorize(true)).rejects.toThrow(refused("predecessor_not_stopped")); + await expect(authorize()).rejects.toThrow(refused("predecessor_not_stopped")); + await db.update(environmentLeases).set({ metadata: settled.metadata }).where(eq(environmentLeases.id, oldLeaseId)); + const siblingId = randomUUID(); + await db.insert(environmentLeases).values({ id: siblingId, companyId, environmentId, heartbeatRunId: oldRunId, + provider: prior.provider, providerLeaseId: "sibling-task", status: "active", leasePolicy: "ephemeral", metadata: pin }); + await expect(authorize(true)).rejects.toThrow(refused("predecessor_not_stopped")); + await expect(authorize()).rejects.toThrow(refused("predecessor_not_stopped")); + await db.delete(environmentLeases).where(eq(environmentLeases.id, siblingId)); + await db.update(environmentLeases).set({ status: "pending_cleanup", cleanupStatus: "failed", releasedAt: new Date() }) + .where(eq(environmentLeases.id, oldLeaseId)); + await expect(authorize()).rejects.toThrow(refused("predecessor_not_stopped")); + await db.update(environmentLeases).set({ status: "active", cleanupStatus: null, releasedAt: null }).where(eq(environmentLeases.id, oldLeaseId)); + await expect(authorize()).resolves.toBe("old-task"); + + // Dispatching new execution invalidates a stop receipt on that lease. + const next = await readLease(nextLeaseId); + await db.update(environmentLeases).set({ metadata: { ...next.metadata, runnerTaskExecutionStopped: true, + remoteExecutionTermination: remoteTerminationReceipt(next, { providerLeaseId: "new-task", state: "stopped" }) } }) + .where(eq(environmentLeases.id, nextLeaseId)); + expect(await remoteExecutionHasStopped(db, companyId, nextRunId)).toBe(true); + await expect(runtime.task({ companyId, leaseId: nextLeaseId, operation: { + kind: "submit", preparedLaunchId: "fixture", projectIds: [], bootstrapTicket: "fixture", runner, resumeFrom: "old-task", + } })).resolves.toMatchObject({ kind: "accepted" }); + expect((await readLease(nextLeaseId)).metadata).not.toHaveProperty("remoteExecutionTermination"); + expect(await remoteExecutionHasStopped(db, companyId, nextRunId)).toBe(false); + + // Release still writes its own receipt over the settlement receipt. + const releaseErrors: unknown[] = []; + await runtime.releaseRunLeases(oldRunId, "released", (_id, error) => { releaseErrors.push(error); }); + expect(releaseErrors).toEqual([]); + const released = await readLease(oldLeaseId); + expect(released).toMatchObject({ status: "released", cleanupStatus: "success", + metadata: { remoteExecutionTermination: { leaseId: oldLeaseId, providerLeaseId: "old-task", state: "stopped" } } }); + expect(hasRemoteTerminationReceipt(released)).toBe(true); + expect(await remoteExecutionHasReleased(db, companyId, oldRunId)).toBe(true); + }); + + it("stops counting a settled task's stop receipt once its lease release starts", async () => { + const { companyId, agentId, environmentId, pin } = await seedTaskPlugin("release-owns-receipt"); + const oldRunId = randomUUID(), nextRunId = randomUUID(), oldLeaseId = randomUUID(), nextLeaseId = randomUUID(); + await db.insert(heartbeatRuns).values([ + { id: oldRunId, companyId, agentId, invocationSource: "manual", status: "succeeded" }, + { id: nextRunId, companyId, agentId, invocationSource: "manual", status: "running" }, + ]); + const prior = { id: oldLeaseId, companyId, environmentId, heartbeatRunId: oldRunId, provider: "plugin:fixture:tasks", providerLeaseId: "old-task" }; + // The predecessor's task settled in its run: stopped, session retained, stop receipt recorded. + const settledMetadata = { ...pin, runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true, + runnerTaskIdentity: { runnerId: "runner", leaseId: oldLeaseId, runId: oldRunId, sessionId: "session", turnId: "turn", itemId: "item" }, + remoteExecutionTermination: remoteTerminationReceipt(prior, { providerLeaseId: "old-task", state: "stopped" }) }; + await db.insert(environmentLeases).values([ + { ...prior, status: "active", leasePolicy: "ephemeral", metadata: settledMetadata }, + { id: nextLeaseId, companyId, environmentId, heartbeatRunId: nextRunId, provider: prior.provider, providerLeaseId: "new-task", + status: "active", leasePolicy: "ephemeral", metadata: pin }, + ]); + let releaseEntered!: () => void, finishRelease!: () => void; + const entered = new Promise(resolve => { releaseEntered = resolve; }); + const held = new Promise(resolve => { finishRelease = resolve; }); + const call = vi.fn(async (_id: string, method: string) => { + if (method !== "environmentReleaseLease") throw new Error(`unexpected ${method}`); + releaseEntered(); + await held; + }); + const workers = { isRunning: () => true, getWorker: () => ({ supportedMethods: ["environmentTask", "environmentReleaseLease"] }), call } as unknown as PluginWorkerManager; + const runtime = environmentRuntimeService(db, { pluginWorkerManager: workers }); + const priorIdentity = { runnerInstanceId: "runner", normalizedSessionId: "session", environmentLeaseId: oldLeaseId, runId: oldRunId }; + const authorize = (inspectCheckpoint?: boolean) => resolvePluginTaskResume(db, { companyId, leaseId: nextLeaseId, priorIdentity, inspectCheckpoint }); + await expect(authorize()).resolves.toBe("old-task"); + + // Each marker that release, destroy, or startup and creation cleanup write first takes the receipt over. + for (const marker of [{ pluginLeaseCleanupMethod: "release" }, { pluginLeaseCleanupMethod: "destroy" }, { runnerTaskRetiring: true }]) { + await db.update(environmentLeases).set({ metadata: { ...settledMetadata, ...marker } }).where(eq(environmentLeases.id, oldLeaseId)); + expect(await remoteExecutionHasStopped(db, companyId, oldRunId)).toBe(false); + await expect(authorize()).rejects.toThrow(refused("predecessor_not_stopped")); + } + await db.update(environmentLeases).set({ metadata: settledMetadata }).where(eq(environmentLeases.id, oldLeaseId)); + + // Hold the real release inside the provider call: the lease is still active with its settlement receipt. + const releaseErrors: unknown[] = []; + const releasing = runtime.releaseRunLeases(oldRunId, "released", (_id, error) => { releaseErrors.push(error); }); + await entered; + const inFlight = (await db.select().from(environmentLeases).where(eq(environmentLeases.id, oldLeaseId)))[0]!; + expect(inFlight).toMatchObject({ status: "active", releasedAt: null, + metadata: { pluginLeaseCleanupMethod: "release", runnerTaskRetiring: true } }); + expect(hasBoundRemoteStopReceipt(inFlight)).toBe(true); + expect(await remoteExecutionHasStopped(db, companyId, oldRunId)).toBe(false); + await expect(authorize(true)).rejects.toThrow(refused("predecessor_not_stopped")); + await expect(authorize()).rejects.toThrow(refused("predecessor_not_stopped")); + + // Release settles with its own receipt, which authorizes the follow-up. + finishRelease(); + await releasing; + expect(releaseErrors).toEqual([]); + const released = (await db.select().from(environmentLeases).where(eq(environmentLeases.id, oldLeaseId)))[0]!; + expect(released).toMatchObject({ status: "released", cleanupStatus: "success" }); + expect(hasRemoteTerminationReceipt(released)).toBe(true); + expect(await remoteExecutionHasStopped(db, companyId, oldRunId)).toBe(true); + await expect(authorize(true)).resolves.toBe("old-task"); + await expect(authorize()).resolves.toBe("old-task"); + }); + + it("still records stop receipts for every warm owner and retires retained owners", async () => { + const { companyId, agentId, environmentId, pin } = await seedTaskPlugin("warm-stop"); + const priorRunId = randomUUID(), currentRunId = randomUUID(), priorLeaseId = randomUUID(), currentLeaseId = randomUUID(); + await db.insert(heartbeatRuns).values([ + { id: priorRunId, companyId, agentId, invocationSource: "manual", status: "succeeded" }, + { id: currentRunId, companyId, agentId, invocationSource: "manual", status: "running" }, + ]); + const shared = { companyId, environmentId, provider: "plugin:fixture:tasks", providerLeaseId: "warm-task", leasePolicy: "reuse_by_environment" as const }; + await db.insert(environmentLeases).values([ + { ...shared, id: priorLeaseId, heartbeatRunId: priorRunId, status: "retained", metadata: pin }, + { ...shared, id: currentLeaseId, heartbeatRunId: currentRunId, status: "active", metadata: { ...pin, runnerTaskDispatched: true } }, + ]); + const call = vi.fn(async (_id: string, _method: string, params: any) => params.operation.kind === "status" + ? { kind: "status", taskId: params.taskId, phase: "completed", executionStopped: true, sessionStateAvailable: false } + : { kind: "accepted", taskId: params.taskId }); + const runtime = environmentRuntimeService(db, { pluginWorkerManager: { getWorker: () => ({ supportedMethods: ["environmentTask"] }), call } as unknown as PluginWorkerManager }); + await runtime.task({ companyId, leaseId: currentLeaseId, operation: { kind: "status" } }); + await runtime.task({ companyId, leaseId: currentLeaseId, operation: { kind: "complete" } }); + const leases = await db.select().from(environmentLeases).where(eq(environmentLeases.providerLeaseId, "warm-task")); + const priorLease = leases.find(lease => lease.id === priorLeaseId)!, currentLease = leases.find(lease => lease.id === currentLeaseId)!; + expect(priorLease).toMatchObject({ status: "released", cleanupStatus: "success", + metadata: { remoteExecutionTermination: { leaseId: priorLeaseId, runId: priorRunId, state: "stopped" } } }); + expect(currentLease).toMatchObject({ status: "active", + metadata: { remoteExecutionTermination: { leaseId: currentLeaseId, runId: currentRunId, state: "stopped" } } }); + expect(hasRemoteTerminationReceipt(priorLease)).toBe(true); + expect(await remoteExecutionHasStopped(db, companyId, priorRunId)).toBe(true); + expect(await remoteExecutionHasStopped(db, companyId, currentRunId)).toBe(true); + expect(await remoteExecutionHasReleased(db, companyId, currentRunId)).toBe(false); + }); + }); diff --git a/server/src/services/environment-run-orchestrator.ts b/server/src/services/environment-run-orchestrator.ts index 77abc489223..50a33190335 100644 --- a/server/src/services/environment-run-orchestrator.ts +++ b/server/src/services/environment-run-orchestrator.ts @@ -20,7 +20,7 @@ import { prepareRemoteWorkspace, readRemoteWorkspaceAuthority, remoteWorkspaceRe import { environmentLeases, type Db } from "@paperclipai/db"; import { and, eq } from "drizzle-orm"; -import { remoteExecutionHasStopped } from "./remote-execution-termination.js"; +import { remoteExecutionHasReleased } from "./remote-execution-termination.js"; import { remoteRecoveryLeaseMismatch, type RemoteRecoveryLeaseMismatchField } from "./native-runtime/remote-recovery-lease-mismatch.js"; import { EnvironmentProviderUnavailableError, readTransientLeaseAcquisitionFailure } from "./environment-provider-unavailable-error.js"; import { injectLeaseAcquisitionFault } from "./environment-lease-fault-injection.js"; @@ -347,7 +347,9 @@ export function environmentRunOrchestrator( lease.metadata?.agentId !== input.agentId)) throw new Error("native_plugin_recovery_lease_mismatch"); const errors: unknown[] = []; await environmentRuntime.releaseRunLeases(input.heartbeatRunId, "released", (_id, error) => { errors.push(error); }); - if (errors.length || (prior.length && !await remoteExecutionHasStopped(db, input.companyId, input.heartbeatRunId))) { + // Same-run task resume requires every prior lease released with its receipt; + // a stop recorded before a held release is not enough here. + if (errors.length || (prior.length && !await remoteExecutionHasReleased(db, input.companyId, input.heartbeatRunId))) { throw new Error("native_plugin_recovery_termination_unconfirmed", { cause: errors[0] }); } } diff --git a/server/src/services/environment-task-runtime.ts b/server/src/services/environment-task-runtime.ts index 87020bb274f..f6c40f8fb63 100644 --- a/server/src/services/environment-task-runtime.ts +++ b/server/src/services/environment-task-runtime.ts @@ -1,4 +1,4 @@ -import { resolvePluginTaskResume } from "./plugin-task-resume.js"; +import { pluginTaskResumeRefused, resolvePluginTaskResume } from "./plugin-task-resume.js"; export { resolvePluginTaskResume } from "./plugin-task-resume.js"; import { attachSandboxCreation, environmentService } from "./environments.js"; import { createOwnedSandbox, queueSandboxCreationCleanup, recordSandboxCreationResource } from "./sandbox-creation-operations.js"; @@ -198,11 +198,13 @@ export async function executeEnvironmentTask(db: Db, workers: Pick>'runnerTaskRetiring', 'false') != 'true'`, requiredProjectAuthProof ? sql`${environmentLeases.metadata}->'runnerTaskProjectAuthValidation' = ${JSON.stringify(requiredProjectAuthProof)}::jsonb` : undefined, @@ -420,7 +423,7 @@ export async function executeEnvironmentTask(db: Db, workers: Pick 1) return "predecessor_candidate_ambiguous"; + const old = candidates[0]!; + const identity = old.lease.metadata?.runnerTaskIdentity as Record | undefined; + if (!old.lease.providerLeaseId) return "predecessor_task_missing"; + if (!identity || identity.runnerId !== priorIdentity.runnerInstanceId || identity.leaseId !== priorIdentity.environmentLeaseId || + identity.sessionId !== priorIdentity.normalizedSessionId || identity.runId !== priorIdentity.runId) return "identity_mismatch"; + if (old.lease.metadata?.driver !== "plugin" || next.lease.metadata?.driver !== "plugin") return "provider_mismatch"; + if (!next.lease.providerLeaseId) return "next_task_missing"; + if (next.lease.providerLeaseId === old.lease.providerLeaseId) return "same_provider_task"; + if (old.run.id !== next.run.id && !TERMINAL_RUN_STATUSES.includes(old.run.status)) return "predecessor_run_active"; + if (old.run.agentId !== next.run.agentId || old.lease.issueId !== next.lease.issueId || + old.lease.executionWorkspaceId !== next.lease.executionWorkspaceId || + !old.lease.environmentId || old.lease.environmentId !== next.lease.environmentId) return "scope_mismatch"; + if (!next.lease.provider?.startsWith("plugin:") || old.lease.provider !== next.lease.provider || + old.lease.metadata?.pluginId !== next.lease.metadata?.pluginId || + old.lease.metadata?.driverKey !== next.lease.metadata?.driverKey) return "provider_mismatch"; + if (next.lease.status !== "active" || next.lease.releasedAt || + (next.lease.expiresAt && next.lease.expiresAt.getTime() <= Date.now())) return "next_lease_inactive"; + if (next.run.status !== "running") return "next_run_not_running"; + return null; +} + /** A saved provider task can resume only within the same authorized agent workspace. */ export async function resolvePluginTaskResume(db: Db, input: { companyId: string; leaseId: string; - priorIdentity: { runnerInstanceId: string; environmentLeaseId: string; runId: string; normalizedSessionId: string }; + priorIdentity: PriorIdentity; /** Read-only discovery; launching still requires an attested retained checkpoint. */ inspectCheckpoint?: boolean; }): Promise { @@ -28,25 +82,12 @@ export async function resolvePluginTaskResume(db: Db, input: { !rows.some(successor => successor.lease.id !== input.leaseId && successor.lease.metadata?.runnerTaskResumeFrom === row.lease.providerLeaseId); }); - const old = candidates.length === 1 ? candidates[0] : undefined; - const identity = old?.lease.metadata?.runnerTaskIdentity as Record | undefined; - if (!old || !next || !old.lease.providerLeaseId || !identity || - identity.runnerId !== input.priorIdentity.runnerInstanceId || identity.leaseId !== input.priorIdentity.environmentLeaseId || - identity.sessionId !== input.priorIdentity.normalizedSessionId || identity.runId !== input.priorIdentity.runId || - old.lease.metadata?.driver !== "plugin" || next.lease.metadata?.driver !== "plugin" || - !next.lease.providerLeaseId || next.lease.providerLeaseId === old.lease.providerLeaseId || - (old.run.id !== next.run.id && !["succeeded", "interrupted", "failed", "cancelled", "timed_out"].includes(old.run.status)) || - old.run.agentId !== next.run.agentId || old.lease.issueId !== next.lease.issueId || - old.lease.executionWorkspaceId !== next.lease.executionWorkspaceId || - !old.lease.environmentId || old.lease.environmentId !== next.lease.environmentId || - !next.lease.provider?.startsWith("plugin:") || old.lease.provider !== next.lease.provider || - old.lease.metadata?.pluginId !== next.lease.metadata?.pluginId || old.lease.metadata?.driverKey !== next.lease.metadata?.driverKey || - next.lease.status !== "active" || next.lease.releasedAt || next.run.status !== "running" || - (next.lease.expiresAt && next.lease.expiresAt.getTime() <= Date.now()) || - !(old.run.id === next.run.id - ? rows.filter(row => row.lease.id !== next.lease.id).every(row => hasRemoteTerminationReceipt(row.lease)) - : await remoteExecutionHasStopped(db, input.companyId, old.run.id))) { - throw new Error("Plugin Runner retained session is not authorized"); - } - return old.lease.providerLeaseId; + const refusal = resumeRefusal(input.priorIdentity, next, candidates); + if (refusal) throw pluginTaskResumeRefused(refusal); + const old = candidates[0]!; + const stopped = old.run.id === next!.run.id + ? rows.filter(row => row.lease.id !== next!.lease.id).every(row => hasRemoteTerminationReceipt(row.lease)) + : await remoteExecutionHasStopped(db, input.companyId, old.run.id); + if (!stopped) throw pluginTaskResumeRefused("predecessor_not_stopped"); + return old.lease.providerLeaseId!; } diff --git a/server/src/services/remote-execution-termination.ts b/server/src/services/remote-execution-termination.ts index e18a6fdaae9..147982f4746 100644 --- a/server/src/services/remote-execution-termination.ts +++ b/server/src/services/remote-execution-termination.ts @@ -24,19 +24,47 @@ export function remoteTerminationReceipt(lease: LeaseIdentity, value: unknown) { }; } -export function hasRemoteTerminationReceipt(lease: LeaseIdentity & { +type ReceiptLease = LeaseIdentity & { releasedAt: unknown; cleanupStatus: string | null; status: string; metadata: Record | null; -}): boolean { +}; + +/** The lease carries a provider stop receipt bound to its exact company, run, + * lease, provider and physical task. It proves execution there stopped, not + * that the lease's resources were released. */ +export function hasBoundRemoteStopReceipt(lease: Pick): boolean { const receipt = lease.metadata?.remoteExecutionTermination as Record | undefined; - return Boolean(lease.releasedAt && lease.cleanupStatus === "success" && - ["released", "expired", "failed"].includes(lease.status) && receipt && - receipt.schema === "paperclip.remote-termination.v1" && + return Boolean(receipt && receipt.schema === "paperclip.remote-termination.v1" && receipt.companyId === lease.companyId && receipt.runId === lease.heartbeatRunId && receipt.leaseId === lease.id && receipt.provider === lease.provider && remoteTerminationReceipt(lease, receipt)); } +/** The lease was released with successful cleanup and its bound stop receipt. + * Resource cleanup gates use this; it never accepts an unreleased lease. */ +export function hasRemoteTerminationReceipt(lease: ReceiptLease): boolean { + return Boolean(lease.releasedAt && lease.cleanupStatus === "success" && + ["released", "expired", "failed"].includes(lease.status) && hasBoundRemoteStopReceipt(lease)); +} + +/** Release or destroy of this lease has started: plugin release and destroy + * record their cleanup method first, and task settlement, startup cleanup and + * interrupted-creation cleanup mark the task retiring. The provider can then be + * releasing the task's resources while the lease row is still active. */ +function leaseReleaseStarted(lease: Pick): boolean { + return lease.metadata?.pluginLeaseCleanupMethod !== undefined || lease.metadata?.runnerTaskRetiring === true; +} + +/** Execution on this lease has stopped: it was released with its termination + * receipt, or it is still active, its release has not started, and its plugin + * task recorded the provider's stop when it settled. Release can be held long + * after that stop (for example by a pending workspace export); once release + * starts, it owns the receipt until the lease is released. */ +function remoteLeaseExecutionStopped(lease: ReceiptLease): boolean { + return hasRemoteTerminationReceipt(lease) || + lease.status === "active" && !lease.releasedAt && !leaseReleaseStarted(lease) && hasBoundRemoteStopReceipt(lease); +} + /** Workspace recovery saved this run's files, re-stopped its sandbox, and then * queued the stopped sandbox for destroy. The destroy is resource cleanup: the * stop receipt it carried forward still proves no provider can run there. */ @@ -77,16 +105,27 @@ export async function resolveRemoteTerminationLease(db: Db, lease: Lease): Promi } } }; } -export async function stoppedRemoteCleanupScopes(db: Db, companyId: string, runId: string) { +async function runRemoteLeases(db: Db, companyId: string, runId: string) { const leases = await db.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId), )); - if (leases.length === 0) return null; - const resolved = await Promise.all(leases.map(lease => resolveRemoteTerminationLease(db, lease))); - if (!resolved.every(hasRemoteTerminationReceipt)) return null; - return [...new Set(resolved.map(lease => remoteLeaseCleanupScope(lease)!))]; + return Promise.all(leases.map(lease => resolveRemoteTerminationLease(db, lease))); } +/** Cleanup scopes of a run whose every lease has stopped execution, or null. */ +export async function stoppedRemoteCleanupScopes(db: Db, companyId: string, runId: string) { + const leases = await runRemoteLeases(db, companyId, runId); + if (leases.length === 0 || !leases.every(remoteLeaseExecutionStopped)) return null; + return [...new Set(leases.map(lease => remoteLeaseCleanupScope(lease)!))]; +} + +/** Every lease of the run has stopped execution. Its resources can still be held. */ export async function remoteExecutionHasStopped(db: Db, companyId: string, runId: string) { return await stoppedRemoteCleanupScopes(db, companyId, runId) !== null; } + +/** Every lease of the run was released with its termination receipt. */ +export async function remoteExecutionHasReleased(db: Db, companyId: string, runId: string) { + const leases = await runRemoteLeases(db, companyId, runId); + return leases.length > 0 && leases.every(hasRemoteTerminationReceipt); +} From 4dc5492c2d15f290702ba03753bb6155b91cd920 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:20:55 -0600 Subject: [PATCH 11/15] fix(recovery): retry a failed Retry run's sandbox resume failure when the sweep reaches it first (#21124) 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 runs on a reusable cloud sandbox resumes the same sandbox on its next run > - When the resume fails before provider work (`reusable_sandbox_resume_failed`), the run gets a bounded automatic retry > - On a hosted staging server, 8 of 14 such failures in 10 hours did not get that retry. Each task ended `blocked` and needed a person to press Retry > - In all 8, the stranded-task sweep blocked the task between the failed write and the run's own retry scheduling. The block cleared the claim that the retry needed > - This pull request makes the sweep give such a run to the same bounded retry scheduler, not escalate it > - The benefit is that a transient sandbox resume failure no longer costs the task, also when settlement is slow or the server stops during an upgrade ## Linked Issues or Issue Description Refs #21108, #21113, #21078 **What happened?** A person pressed Retry on a task. The run tried to resume the task's saved Daytona sandbox before provider work. The resume failed (`cause=transport_timeout`, or `provider_unavailable status=503`), and the run was written `failed` with `reusable_sandbox_resume_failed`. Then the stranded-task sweep moved the task to `blocked` and cleared its claim. This happened 1 to 43 seconds after the failed write. The run's executor scheduled its bounded retry 2 to 81 seconds after the failed write, and the gate refused it ("The automatic retry could not revalidate the original user continuation."). Read-only audit of 14 failures (all legacy runtime, `executionRecovery: bootstrap, providerWorkStarted: false`): 6 got their retry, and the 5 most recent ones recovered. 8 were refused this way and wait for a person. In one example the run was written failed at 14:23:31, the task was blocked at 14:24:14, and the retry was refused at 14:24:52. The server was being replaced at that time. **Expected behavior** A transient preparation failure before provider work continues with its bounded retry. The sweep must not take the claim away from that retry. When the retry budget is spent, or the continuation is refused, the task escalates once, as before. **Steps to reproduce** 1. Press Retry on a task whose reusable sandbox resume fails before provider work. 2. Let the run's executor be slow to settle the failure (more than the remaining controller lease, at most 60 seconds), or stop its server after the failed write. 3. Let the stranded-task sweep run on another server. The task becomes `blocked`, and no retry is scheduled. **Root cause** `classifyContinuationFailure` lists `reusable_sandbox_resume_failed` and the other transient preparation codes in `NON_RETRYABLE_CONTINUATION_ERROR_CODES`. The sweep assumes that the executor already scheduled the dedicated bounded retry, so it escalates at once and never asks the scheduler. #21108 added a skip while the executor still settles the run. That skip uses a live local execution or an unexpired controller lease. The lease stops renewing when the run is written terminal (renewal requires `status = 'running'`). So the skip covers at most about 60 seconds after the last renewal, and it covers nothing when the executor's server stops during settlement. **Paperclip version or commit** Staging at `a65644d1e1`. Current `master` has the same code path. **Deployment mode** Hosted (cloud), two servers alive during each upgrade. **Agent adapter(s) involved** `codex_local` on a Daytona sandbox environment. The change is adapter-independent. ## What Changed - `server/src/services/heartbeat/retries.ts`: add `failedPreparationOwnsBoundedRetry(run)`. It is the persisted form of the run-completion decision: a failed legacy run with no native session, bootstrap evidence that provider work did not start, and a transient preparation code. A restore failure counts only when its owner marked it retryable. Codes that an accepted interaction retries itself are excluded. - `server/src/services/recovery/service.ts`: when the latest run is such a run, the sweep does not escalate it as non-retryable. It goes to `scheduleRecoveryRetry`, which is the run's own bounded scheduler. The scheduler reuses a successor that already exists, so the executor and the sweep create one successor. The task escalates when the scheduler reports exhaustion or a refused continuation. When the scheduler declines the retry for another reason (for example a permanent refusal), the task escalates once as a non-retryable failure, as before. The #21108 settling skip still runs first. - `server/src/services/heartbeat.ts`: pass the predicate to the recovery service. - `doc/execution-semantics.md`: document the rule. ## Verification - New tests in `server/src/services/task-retry.test.ts`, in the staging shape: a Retry-admitted run failed with `reusable_sandbox_resume_failed`, bootstrap evidence, and an expired controller lease from another server. - "retries a failed Retry run's transient preparation failure when the sweep reaches it first" (`slow_executor`, `executor_gone`). Red before the fix: the task became `blocked`, as on staging. Green after the fix: the task stays `in_progress` with one `scheduled_retry` successor (`transient_failure`, attempt 1), and dispatch accepts it. For `slow_executor`, the executor's own scheduling then reuses the same successor, and there is still one successor. - "still escalates a failed Retry run's transient preparation failure once its bounded retries are spent": the task becomes `blocked` with no successor. - "escalates a failed Retry run's transient preparation failure once when the scheduler declines it permanently" (review finding): red before the follow-up commit (the task stayed `in_progress` with no run), green after (the task is `blocked` once, and a second sweep adds no notice). - `pnpm exec vitest run src/services/task-retry.test.ts`: 114/114 pass. - `pnpm exec vitest run src/__tests__/heartbeat-retry-scheduling.test.ts src/__tests__/heartbeat-process-recovery.test.ts` (with task-retry): 631 of 633 passed. The 2 failures were 15-second timeouts under parallel load in native Board-wait tests that this change does not touch. They passed when run alone. - `tsc -p server/tsconfig.json --noEmit` passes. - Not run: a live staging reproduction. The staging evidence is read-only (run events, task activity, run records). ## Risks - The sweep can now schedule the bounded retry before the executor does. The scheduler locks the task and the run and reuses an existing successor, so there is never a second successor. All continuation gate checks still apply. - The sweep acts only after the #21108 settling skip lapses, so a healthy run is not affected. No wait is added before a normal turn start. - No schema change. Rows from older releases follow the same rule because the predicate reads only persisted fields. - Out of scope: the provider-side causes (Daytona 503 at 14:21Z, resume calls that time out). #21113 handles the in-run wait for idle transport timeouts. > 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 (code search, shell, read-only API reads, Vitest on embedded PostgreSQL) 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 | 2 +- server/src/services/heartbeat.ts | 2 + server/src/services/heartbeat/retries.ts | 23 ++++++++++ server/src/services/recovery/service.ts | 58 +++++++++++++++++++----- server/src/services/task-retry.test.ts | 55 ++++++++++++++++++++++ 5 files changed, 127 insertions(+), 13 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 1bb81b0e687..19fed8d72d4 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1718,7 +1718,7 @@ or the exact provenance inside its verified committed saved snapshot. The latter uses one temporary read-only archive verification per preparation when needed. Task relationships alone do not authorize importing or retaining files. -When a legacy turn admitted by an explicit user message fails or times out, a bounded transient retry needs its own durable continuation authorization. Initial admission binds the message's exact body digest and revision. Scheduling requires that original binding and revalidates the human author, source task, assignee, and execution ownership, then records the successor's receipt in the same transaction as its run. Historical receipts without a message binding cannot authorize automatic retries and are not backfilled. The parent receipt remains intact. Dispatch checks the exact successor, retry parent, and unchanged message binding again. Deleted or edited input, changed actors or ownership, superseded work, and duplicate successors cannot renew authority. Chat, queued-message and fresh-workspace Retries, failed-run retries, and Interrupt intents retain their separate one-run admission contracts; they are not renewable authority. A plain task Retry that continues in the saved workspace renews the same way: the successor's receipt names the same Retry request and actor, while the Retry request stays bound to the run it admitted. A graceful server shutdown (an upgrade or restart, `server_shutdown_interrupted`) that stops such a turn while it is still preparing, with bootstrap evidence that provider work did not start, is not a failure: the original user authorization still covers the work, so the turn continues automatically in the uncharged `interrupted_preparation` lane (or `server_restart` once its failure budget is spent) with its own receipt. When a release without this rule refused that continuation and released the task's claim, the stranded-task sweep restores the claim to the stopped run and admits the continuation once; it refuses when another run holds the claim. A fresh-workspace Retry (selected at admission, or by its preparation when the saved files could not be restored) is renewable only on this shutdown path: the person asked for that fresh attempt and it never ran, so the successor's receipt records the same workspace selection and the successor prepares the same attempt (a remote fresh workspace is keyed by the Retry, so it is reused). The stranded-task sweep offers every such stopped Retry or message turn to the scheduler before its generic checks, because the person's Retry started a fresh session: state the replaced session left behind (an unfinished session goal, or a native finalization that the Retry already replaced) does not own the task. While a terminal run's own executor still settles it (a live local execution or an unexpired controller lease), the sweep leaves the task alone, so it cannot clear the claim that run's bounded retry needs. When admission refuses, the sweep escalates the task once to `blocked` with a plain notice that asks for Retry, instead of refusing again on every pass. All other checks still apply: a changed assignee or Retry actor, a cancelled or completed task, newer or live work on the task, a revoked or missing receipt, a different interruption cause, and a turn whose provider work started keep refusing. Other retry policies cannot borrow this receipt: their scheduling fails closed. Successful explicit turns do not create a prose-only missing-comment follow-up with spent authority. +When a legacy turn admitted by an explicit user message fails or times out, a bounded transient retry needs its own durable continuation authorization. Initial admission binds the message's exact body digest and revision. Scheduling requires that original binding and revalidates the human author, source task, assignee, and execution ownership, then records the successor's receipt in the same transaction as its run. Historical receipts without a message binding cannot authorize automatic retries and are not backfilled. The parent receipt remains intact. Dispatch checks the exact successor, retry parent, and unchanged message binding again. Deleted or edited input, changed actors or ownership, superseded work, and duplicate successors cannot renew authority. Chat, queued-message and fresh-workspace Retries, failed-run retries, and Interrupt intents retain their separate one-run admission contracts; they are not renewable authority. A plain task Retry that continues in the saved workspace renews the same way: the successor's receipt names the same Retry request and actor, while the Retry request stays bound to the run it admitted. A graceful server shutdown (an upgrade or restart, `server_shutdown_interrupted`) that stops such a turn while it is still preparing, with bootstrap evidence that provider work did not start, is not a failure: the original user authorization still covers the work, so the turn continues automatically in the uncharged `interrupted_preparation` lane (or `server_restart` once its failure budget is spent) with its own receipt. When a release without this rule refused that continuation and released the task's claim, the stranded-task sweep restores the claim to the stopped run and admits the continuation once; it refuses when another run holds the claim. A fresh-workspace Retry (selected at admission, or by its preparation when the saved files could not be restored) is renewable only on this shutdown path: the person asked for that fresh attempt and it never ran, so the successor's receipt records the same workspace selection and the successor prepares the same attempt (a remote fresh workspace is keyed by the Retry, so it is reused). The stranded-task sweep offers every such stopped Retry or message turn to the scheduler before its generic checks, because the person's Retry started a fresh session: state the replaced session left behind (an unfinished session goal, or a native finalization that the Retry already replaced) does not own the task. While a terminal run's own executor still settles it (a live local execution or an unexpired controller lease), the sweep leaves the task alone, so it cannot clear the claim that run's bounded retry needs. The controller lease stops renewing once the run is written terminal, so a slow settlement, or a server that stops before scheduling, can outlast it. A failed run that stopped before provider work with a transient preparation failure (for example a reusable sandbox that could not be resumed) is then offered to its own bounded retry scheduler, which reuses a successor that already exists; the task escalates only when that retry is exhausted or refused. When admission refuses, the sweep escalates the task once to `blocked` with a plain notice that asks for Retry, instead of refusing again on every pass. All other checks still apply: a changed assignee or Retry actor, a cancelled or completed task, newer or live work on the task, a revoked or missing receipt, a different interruption cause, and a turn whose provider work started keep refusing. Other retry policies cannot borrow this receipt: their scheduling fails closed. Successful explicit turns do not create a prose-only missing-comment follow-up with spent authority. Explicit retry admission checks the local parent adapter controller and verified environment cleanup. The existing queue-first release policy may retain only its own terminal execution claim while that cleanup is pending; finalization and the periodic stale-lock sweep reconsider the same policy after cleanup. Generic terminal-lock cleanup and stale checkout adoption leave these claims for that settlement. New user input, reassignment, and a successor's claim take precedence. Exhausted retries and revoked or missing authorization release the terminal claim without requesting another retry. Pending or failed environment cleanup cannot mint a successor receipt. diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 12de5b29fab..a860dae7cc9 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -121,6 +121,7 @@ import { createHeartbeatRecovery, } from "./heartbeat/recovery.js"; import { + failedPreparationOwnsBoundedRetry, failedRunRetryBudgetSpent, isWorkspaceBusyDeferral, createHeartbeatRetries, @@ -1045,6 +1046,7 @@ export function heartbeatService( // or interrupted run that has already consumed every bounded transient // attempt cannot be retried again through this lane. transientRetryBudgetSpent: failedRunRetryBudgetSpent, + ownsPreparationRetry: failedPreparationOwnsBoundedRetry, }); const runDispatch = createRunDispatch(db); const { diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.ts index 806c866f2af..0dbe6a94803 100644 --- a/server/src/services/heartbeat/retries.ts +++ b/server/src/services/heartbeat/retries.ts @@ -160,6 +160,29 @@ export function isTransientWorkspacePreparationCode(code: string | null | undefi || code === STORAGE_UNAVAILABLE_CODE; } +/** + * The persisted form of the setup-failure decision in run completion: this + * failed legacy run stopped before provider work with a transient preparation + * code, so its own bounded retry (scheduleBoundedRetryForRun) continues it. + * The stranded-task sweep uses it to offer a run whose executor has not + * scheduled that retry (still settling, or its server stopped) to the same + * idempotent scheduler instead of escalating it. + */ +export function failedPreparationOwnsBoundedRetry(run: Pick): boolean { + if (run.status !== "failed" || run.runtimeMode !== "legacy" || run.nativeSessionId !== null || run.runnerInstanceId !== null + || !isTransientWorkspacePreparationCode(run.errorCode)) return false; + const recovery = parseObject(run.resultJson?.executionRecovery); + if (recovery.kind !== "bootstrap" || recovery.providerWorkStarted !== false) return false; + // A restore failure is retried only when its owner proved it retryable. + if (run.errorCode === REMOTE_WORKSPACE_RESTORE_FAILED_CODE) + return parseObject(run.resultJson?.remoteWorkspaceRestore).retryable === true; + // An accepted interaction keeps its own continuation retry. + return !((run.errorCode === PLUGIN_WORKER_UNAVAILABLE_CODE || run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE + || run.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE || run.errorCode === REVIEWED_CHAT_BINDING_NOT_READY) + && isResolvedInteractionContinuationWakeContext(run.contextSnapshot)); +} + export const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS = BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length; diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index dc5eaffb7fb..56c6698ddc6 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -893,6 +893,17 @@ function isOperatorCancelledRun( ); } +function nonRetryableContinuationNotice(errorCode: string | null) { + return { + body: + "Paperclip detected a non-retryable failure on this issue's continuation run " + + `(\`${errorCode}\`). Skipping automatic retries and moving it to \`blocked\` ` + + "so it is visible for intervention.", + title: "Continuation failed", + tone: "danger" as const, + }; +} + function isUnsuccessfulTerminalIssueRun(latestRun: LatestIssueRun) { return Boolean( latestRun && @@ -965,6 +976,14 @@ export function recoveryService( transientRetryBudgetSpent?: ( run: typeof heartbeatRuns.$inferSelect, ) => boolean; + /** + * Whether a failed run stopped before provider work with a transient + * preparation failure that its own bounded retry continues. The sweep + * offers such a run to `scheduleRecoveryRetry` instead of escalating it. + */ + ownsPreparationRetry?: ( + run: typeof heartbeatRuns.$inferSelect, + ) => boolean; liveRunExecutions?: Readonly<{ has(id: string): boolean }>; /** * The one settle path for a `running` legacy run whose adapter child is @@ -1133,6 +1152,13 @@ export function recoveryService( return run?.leaseExpiresAt ?? null; } + async function failedRunOwnsPreparationRetry(companyId: string, runId: string): Promise { + if (!deps.ownsPreparationRetry || !deps.scheduleRecoveryRetry) return false; + const [run] = await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId))); + return Boolean(run && deps.ownsPreparationRetry(run)); + } + async function hasActiveExecutionPath( companyId: string, issueId: string, @@ -5814,6 +5840,7 @@ export function recoveryService( } continue; } + let preparationRetry = false; if (isUnsuccessfulTerminalIssueRun(latestRun)) { const classification = classifyContinuationFailure(latestRun); @@ -5841,19 +5868,22 @@ export function recoveryService( continue; } - if (classification.kind === "non_retryable") { + // A failed run that stopped before provider work with a transient + // preparation failure is continued by its own bounded retry. Its + // executor schedules that retry after the failed write, and a slow + // settlement or a stopped server can leave it unscheduled once the + // settling check above lapses. Offer it to the same idempotent + // scheduler below (one successor, the same budget); only exhaustion + // or a refused continuation escalates it, and any other refusal + // escalates it as before. + preparationRetry = latestRun!.agentId === agentId + && await failedRunOwnsPreparationRetry(issue.companyId, latestRun!.id); + if (classification.kind === "non_retryable" && !preparationRetry) { const updated = await escalateStrandedAssignedIssue({ issue, previousStatus: "in_progress", latestRun, - notice: { - body: - "Paperclip detected a non-retryable failure on this issue's continuation run " + - `(\`${classification.errorCode}\`). Skipping automatic retries and moving it to \`blocked\` ` + - "so it is visible for intervention.", - title: "Continuation failed", - tone: "danger", - }, + notice: nonRetryableContinuationNotice(classification.errorCode), }); if (updated) { result.escalated += 1; @@ -5864,7 +5894,7 @@ export function recoveryService( continue; } - if (didAutomaticRecoveryFail(latestRun, "issue_continuation_needed")) { + if (!preparationRetry && didAutomaticRecoveryFail(latestRun, "issue_continuation_needed")) { const { consecutive, latestFinishedAt } = await summarizeRecentContinuationRetries( issue.companyId, @@ -5930,7 +5960,7 @@ export function recoveryService( result.continuationRequeued += 1; result.issueIds.push(issue.id); } else if ( - (recoveryOutcome.retryExhausted || recoveryOutcome.continuationRefused) && + (recoveryOutcome.retryExhausted || recoveryOutcome.continuationRefused || preparationRetry) && !(await hasActiveExecutionPath(issue.companyId, issue.id, null)) ) { // The failed run's bounded transient retries are all spent, so no @@ -5950,7 +5980,11 @@ export function recoveryService( "Moving it to `blocked` so it is visible for intervention.", title: "No live execution path", tone: "danger", - } : CONTINUATION_REFUSED_NOTICE, + } : recoveryOutcome.continuationRefused ? CONTINUATION_REFUSED_NOTICE + // The scheduler declined the preparation retry for another + // reason (for example a durable owner or a permanent refusal): + // escalate it as a non-retryable failure, as before. + : nonRetryableContinuationNotice(latestRun?.errorCode ?? null), }); if (updated) { result.escalated += 1; diff --git a/server/src/services/task-retry.test.ts b/server/src/services/task-retry.test.ts index 84b4232cbf1..c3145dc846d 100644 --- a/server/src/services/task-retry.test.ts +++ b/server/src/services/task-retry.test.ts @@ -436,6 +436,61 @@ describe("durable task Retry admission", () => { if (retry.outcome !== "scheduled") return; await expect(dispatchRun(f.input, retry.run)).resolves.toMatchObject({ interruptedRunId: f.parent.id }); }); + // Staging shape: a person's Retry failed before provider work because the + // saved sandbox resume timed out. The run is already `failed`, but its + // executor has not scheduled the bounded retry yet: settling took longer than + // the controller lease that stopped renewing at the failed write, or the + // server running it stopped. Another server's sweep then reads the task. + it.each(["slow_executor", "executor_gone"] as const)( + "retries a failed Retry run's transient preparation failure when the sweep reaches it first: %s", async executor => { + const f = await seedFailedRetryAdmittedRun(); + await db.update(heartbeatRuns).set({ errorCode: "reusable_sandbox_resume_failed", controllerBootId: randomUUID(), + controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`, + resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }, + }).where(eq(heartbeatRuns.id, f.parent.id)); + const heartbeat = heartbeatService(db); + await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.input.companyId }); + expect((await db.select().from(issues).where(eq(issues.id, f.input.issueId)))[0]).toMatchObject({ status: "in_progress" }); + const successors = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, f.parent.id)); + expect(successors).toHaveLength(1); + expect(successors[0]).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: "transient_failure", + scheduledRetryAttempt: 1 }); + if (executor === "slow_executor") { + // The executor's own scheduling adopts the sweep's successor. + expect(await heartbeat.scheduleBoundedRetry(f.parent.id, { now: new Date() })).toMatchObject({ + outcome: "scheduled", run: { id: successors[0].id } }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, f.parent.id))).toHaveLength(1); + } + await expect(dispatchRun(f.input, successors[0])).resolves.toMatchObject({ interruptedRunId: f.parent.id }); + }); + it.each(["reusable_sandbox_resume_failed", "repository_catalog_unavailable"])( + "escalates a failed Retry run's transient preparation failure once when the scheduler declines it permanently: %s", async errorCode => { + const f = await seedFailedRetryAdmittedRun(); + // An external Dot execution is never retried by the bounded scheduler. + await db.update(heartbeatRuns).set({ errorCode, + runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" }, + nativeExecutionInput: { provider: { kind: "openai_dot" } } }, + resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }, + }).where(eq(heartbeatRuns.id, f.parent.id)); + const heartbeat = heartbeatService(db); + await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.input.companyId }); + expect((await db.select().from(issues).where(eq(issues.id, f.input.issueId)))[0]).toMatchObject({ status: "blocked" }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, f.parent.id))).toHaveLength(0); + const notices = async () => (await db.select().from(issueComments).where(eq(issueComments.issueId, f.input.issueId))).length; + const escalated = await notices(); + await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.input.companyId }); + expect(await notices()).toBe(escalated); + }); + it("still escalates a failed Retry run's transient preparation failure once its bounded retries are spent", async () => { + const f = await seedFailedRetryAdmittedRun(); + await db.update(heartbeatRuns).set({ errorCode: "reusable_sandbox_resume_failed", + scheduledRetryReason: "transient_failure", scheduledRetryAttempt: 2, + resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }, + }).where(eq(heartbeatRuns.id, f.parent.id)); + await heartbeatService(db).reconcileStrandedAssignedIssues({ companyId: f.input.companyId }); + expect((await db.select().from(issues).where(eq(issues.id, f.input.issueId)))[0]).toMatchObject({ status: "blocked" }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, f.parent.id))).toHaveLength(0); + }); async function seedRefusedRetry() { const input = await seed(); const now = Date.now(); From 717aae060a12d10238540e90b76abeaad2781d64 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Thu, 12 Nov 2026 20:24:34 -0800 Subject: [PATCH 12/15] fix(environments): let same-run recovery create a replacement once its sandbox is proven stopped (#21223) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agent runs execute on environment leases, and `createOwnedSandbox` records each sandbox creation so that a lost reply never creates a second sandbox > - The record key is company, environment, run and request key. The plugin request key is the environment fingerprint, so it is the same for every attempt of one run > - A same-run recovery can need a new environment after the first lease is closed with successful cleanup and a termination receipt > - The old record is still `attached` to the closed lease, so the recovery fails with "Sandbox creation has already transferred ownership" before the provider is called > - This pull request lets the creation fence accept the same stop proof that recovery already requires. A creation record whose sandbox is proven stopped becomes resolved, and a resolved record no longer holds its key > - The benefit is that same-run recovery gets one replacement sandbox, while unconfirmed cleanup still blocks a second sandbox ## Linked Issues or Issue Description Fixes #21214 Refs #20755. That pull request fixes the same failure with a different rule. It retries under a new key generation (`#2`, `#3`, ...) when the recorded lease has ended, and it accepts any ended status, including `failed`, without a termination receipt. A lease whose cleanup is not confirmed can then produce a second sandbox while the first one can still run. This pull request keeps the original key and requires the same stop proof that Core uses elsewhere (`hasRemoteTerminationReceipt`). It does not add a key generation. ## What Changed - `server/src/services/sandbox-creation-operations.ts`: when `createOwnedSandbox` finds the key held by an `attached` operation whose lease is not active, it checks the same stop proof that same-run recovery requires before it acquires: `hasRemoteTerminationReceipt(resolveRemoteTerminationLease(lease))`, for the sandbox that this operation created (`creationProviderLeaseId`, or the lease's `providerLeaseId`). - With that proof, it runs the same admission transaction one more time. That transaction first marks the old operation `resolved` (`WHERE id AND state = 'attached' AND lease_id`), and then inserts the new operation. - Without that proof, it throws exactly as before. - The check covers every source of a stop receipt: `releaseLease`, the Runner `complete` operation (which writes receipts with direct SQL for reusable leases), stop-and-retain settlement, and the receipt that `resolveRemoteTerminationLease` derives for an expired reusable lease. - A task replacement can leave an earlier operation attached to a lease that now holds another sandbox. That operation is not proven and keeps its key. - Concurrent recoveries serialize on the row update. The second one updates nothing, finds the first one's unresolved operation through the partial index, and replays or refuses as before. There is one provider call. - Migration `0475_sandbox_creation_owner_unresolved.sql` recreates `sandbox_creation_operations_owner_idx` under the same name as a partial unique index (`state <> 'resolved'`). The drop and the create are in one migration transaction. The Drizzle schema matches. - The conflict lookup in `createOwnedSandbox` ignores resolved rows. An active attached lease is still replayed. Pending and `needs_reconciliation` rows still refuse. `releaseLease` does not change. - `doc/DATABASE.md` and `doc/idle-environment-cleanup.md` describe the operation lifecycle. ## Verification - `pnpm --filter @paperclipai/db generate` - `pnpm --filter @paperclipai/db typecheck` and `pnpm --filter @paperclipai/server typecheck` - `vitest run src/migration-snapshot-drift.test.ts` (db) - `vitest run src/__tests__/sandbox-creation-operations.test.ts`: 48/48. With the service change reverted, the 5 replacement tests fail. - The 9 other server test files that read `sandbox_creation_operations`, plus `environment-runtime.test.ts`: 564/564 - `pnpm check:migrations` passes New tests in `sandbox-creation-operations.test.ts`: - A stop receipt from `releaseLease` (sandbox driver, and the plugin driver through `acquireRunLease` in the #21214 sequence), from the `complete` operation's direct write on a retained reusable lease, and derived only from the destroyed successor of an expired reusable lease each let the next creation resolve the old operation and create exactly one replacement. A retry replays that replacement. These tests fail before the fix. - Failed cleanup, success without a receipt, a receipt for another lease or another provider task, a retained lease, and pending cleanup each still throw "transferred ownership" with no provider call. - An earlier task's operation that a task replacement left attached keeps its key. - Two concurrent recoveries make one provider call. This test fails before the fix. - Reapplying migration 0418 keeps the partial index. I did not run `pnpm verify` or the full suite locally. CI runs them. ## Risks - Migration: the drop and the rebuild of the index take an exclusive lock on `sandbox_creation_operations`. The table has one small row for each sandbox creation, so the lock is short. - Rolling deploy: the migration is marked `online_compatible`. The previous release uses an untargeted `ON CONFLICT DO NOTHING`, which also matches a partial unique index. Its conflict lookup has no state filter, so it can find a resolved row and throw. That fails closed and never creates a second sandbox. - A legacy runner-task operation without `creationProviderLeaseId` matches any lease it is attached to. Runner-task operations record this field before they attach, so this is only a theoretical gap. - An operation stays `attached` until the next creation with the same key checks it. This is the same as before when no recovery comes. - Stop-and-retain settlement is not tested directly. The shared receipt check covers it. - The fence is unchanged for every case without a stop receipt. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, sub-agents) and extended thinking. One sub-agent wrote the change. A second session reviewed it before this pull request. ## 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/DATABASE.md | 9 +- doc/idle-environment-cleanup.md | 14 +- ...0475_sandbox_creation_owner_unresolved.sql | 3 + ...{0470_snapshot.json => 0475_snapshot.json} | 619 +++++++++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + .../src/schema/sandbox_creation_operations.ts | 5 +- .../sandbox-creation-operations.test.ts | 130 ++++ .../services/sandbox-creation-operations.ts | 29 +- 8 files changed, 806 insertions(+), 10 deletions(-) create mode 100644 packages/db/src/migrations/0475_sandbox_creation_owner_unresolved.sql rename packages/db/src/migrations/meta/{0470_snapshot.json => 0475_snapshot.json} (99%) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 0b5a64bffd6..5b9623f1be0 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -2422,8 +2422,13 @@ the optional live environment FK uses SET NULL. Company/run deletion must not erase an outstanding remote-resource obligation. The unique company/environment/run/request index fences duplicate creation and -ambiguous successful lease commits. Normal lease attachment and operation transfer -share a transaction. Recovery transfers one claimed cleanup lease after provider +ambiguous successful lease commits. Since migration 0475 it covers only operations +that are not `resolved`. A later attempt for the same run and request that meets an +`attached` operation whose lease is closed checks the same stop proof same-run +recovery requires (a termination receipt for that sandbox, stored or derived from a +destroyed reusable successor); with it, one transaction resolves the operation and +records the replacement. +Normal lease attachment and operation transfer share a transaction. Recovery transfers one claimed cleanup lease after provider ownership lookup. The pending deadline index drives the existing cleanup worker. `needs_reconciliation` is a durable manual outcome, not an automatic retry or an idle blocker. See [cleanup ownership](idle-environment-cleanup.md). diff --git a/doc/idle-environment-cleanup.md b/doc/idle-environment-cleanup.md index d999536cdfc..8ff92df65bb 100644 --- a/doc/idle-environment-cleanup.md +++ b/doc/idle-environment-cleanup.md @@ -70,8 +70,18 @@ writers and another server process are not covered by these process-local signal A creation operation retains company, original environment, run, request identity, provider, and nonsecret configuration references. Its environment FK uses SET NULL; company/run/task identifiers remain after those records are removed. One operation -owns each company/environment/run/request. A retry of an attached operation returns -its active lease. Pending or unresolved ownership never authorizes another create. +owns each company/environment/run/request until it is resolved. A retry of an +attached operation returns its active lease. Pending or unresolved ownership never +authorizes another create. An attached operation resolves when its lease is proven +stopped, checked at the next creation with the same key: the closed lease must +carry the stop proof same-run recovery requires (`remoteExecutionHasStopped`), a +termination receipt for the sandbox this operation created, whether release, the +Runner `complete` operation, or a destroyed reusable successor supplied it. That +creation resolves the operation and records its replacement in one transaction, +so concurrent recoveries make one provider call. A recovered cleanup operation +resolves when its cleanup lease settles. Failed cleanup, success without a +receipt, a receipt for another sandbox, a retained lease, and pending cleanup keep +the operation and its key. Normal success transfers operation ownership and the lease in one transaction. Current company binding and run authority are checked again at attachment. Declared secret-reference fields retain only their references and nonsecret value diff --git a/packages/db/src/migrations/0475_sandbox_creation_owner_unresolved.sql b/packages/db/src/migrations/0475_sandbox_creation_owner_unresolved.sql new file mode 100644 index 00000000000..a753f04184a --- /dev/null +++ b/packages/db/src/migrations/0475_sandbox_creation_owner_unresolved.sql @@ -0,0 +1,3 @@ +-- paperclip:migration-compat online_compatible: The new index is the same unique key restricted to rows whose state is not 'resolved', so every write the previous release can make still satisfies it, and that release's untargeted ON CONFLICT DO NOTHING matches a partial unique index as well. The drop and rebuild share one transaction, so no write sees the key unfenced; the table holds one small row per sandbox creation, so the exclusive lock lasts only for that index build. +DROP INDEX "sandbox_creation_operations_owner_idx";--> statement-breakpoint +CREATE UNIQUE INDEX "sandbox_creation_operations_owner_idx" ON "sandbox_creation_operations" USING btree ("company_id","original_environment_id","run_id","request_key") WHERE "sandbox_creation_operations"."state" <> 'resolved'; diff --git a/packages/db/src/migrations/meta/0470_snapshot.json b/packages/db/src/migrations/meta/0475_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0470_snapshot.json rename to packages/db/src/migrations/meta/0475_snapshot.json index 5cc01ce9202..7b5ecc397be 100644 --- a/packages/db/src/migrations/meta/0470_snapshot.json +++ b/packages/db/src/migrations/meta/0475_snapshot.json @@ -1,6 +1,6 @@ { - "id": "f0e17e47-6217-4080-b6b6-9d83b33e9ced", - "prevId": "ac25715a-74c6-4988-8525-63ad14781c74", + "id": "ee1f1f66-0cbe-4b18-b364-5e96708a1f0b", + "prevId": "a7108924-4d75-41e2-9139-f43f9396c02d", "version": "7", "dialect": "postgresql", "tables": { @@ -22342,6 +22342,18 @@ "type": "timestamp with time zone", "primaryKey": false, "notNull": false + }, + "dispatching_at": { + "name": "dispatching_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "dispatch_lease_expires_at": { + "name": "dispatch_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false } }, "indexes": { @@ -53674,6 +53686,12 @@ "primaryKey": false, "notNull": true }, + "pending_delete_object_key": { + "name": "pending_delete_object_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -53697,6 +53715,21 @@ "concurrently": false, "method": "btree", "with": {} + }, + "runner_api_response_reservations_asset_idx": { + "name": "runner_api_response_reservations_asset_idx", + "columns": [ + { + "expression": "asset_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -53909,6 +53942,7 @@ } ], "isUnique": true, + "where": "\"sandbox_creation_operations\".\"state\" <> 'resolved'", "concurrently": false, "method": "btree", "with": {} @@ -57502,6 +57536,12 @@ "notNull": true, "default": "'{}'::jsonb" }, + "ui_meta": { + "name": "ui_meta", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "risk_level": { "name": "risk_level", "type": "text", @@ -59627,6 +59667,253 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.tool_mcp_app_views": { + "name": "tool_mcp_app_views", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "invocation_id": { + "name": "invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "catalog_entry_id": { + "name": "catalog_entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "application_name": { + "name": "application_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "upstream_tool_name": { + "name": "upstream_tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_uri": { + "name": "resource_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_input": { + "name": "tool_input", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "tool_result": { + "name": "tool_result", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_app_views_issue_idx": { + "name": "tool_mcp_app_views_issue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_app_views_connection_idx": { + "name": "tool_mcp_app_views_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_app_views_company_id_companies_id_fk": { + "name": "tool_mcp_app_views_company_id_companies_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_app_views_invocation_id_tool_invocations_id_fk": { + "name": "tool_mcp_app_views_invocation_id_tool_invocations_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "tool_invocations", + "columnsFrom": [ + "invocation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tool_mcp_app_views_issue_id_issues_id_fk": { + "name": "tool_mcp_app_views_issue_id_issues_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_app_views_run_id_heartbeat_runs_id_fk": { + "name": "tool_mcp_app_views_run_id_heartbeat_runs_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "heartbeat_runs", + "columnsFrom": [ + "run_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tool_mcp_app_views_agent_id_agents_id_fk": { + "name": "tool_mcp_app_views_agent_id_agents_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tool_mcp_app_views_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_app_views_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_app_views_catalog_entry_id_tool_catalog_entries_id_fk": { + "name": "tool_mcp_app_views_catalog_entry_id_tool_catalog_entries_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "tool_catalog_entries", + "columnsFrom": [ + "catalog_entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.tool_mcp_gateway_tokens": { "name": "tool_mcp_gateway_tokens", "schema": "", @@ -60341,6 +60628,334 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.tool_mcp_skill_files": { + "name": "tool_mcp_skill_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "file_uri": { + "name": "file_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "digest": { + "name": "digest", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "content_base64": { + "name": "content_base64", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_skill_files_digest_idx": { + "name": "tool_mcp_skill_files_digest_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_uri", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "digest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_skill_files_company_id_companies_id_fk": { + "name": "tool_mcp_skill_files_company_id_companies_id_fk", + "tableFrom": "tool_mcp_skill_files", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_skill_files_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_skill_files_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_skill_files", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tool_mcp_skills": { + "name": "tool_mcp_skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "skill_uri": { + "name": "skill_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "frontmatter": { + "name": "frontmatter", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "manifest": { + "name": "manifest", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_review'" + }, + "status_reason": { + "name": "status_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_manifest_digest": { + "name": "approved_manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_tools_approved": { + "name": "allowed_tools_approved", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reviewed_by_user_id": { + "name": "reviewed_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_skills_connection_uri_idx": { + "name": "tool_mcp_skills_connection_uri_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_uri", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_skills_company_status_idx": { + "name": "tool_mcp_skills_company_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_skills_company_id_companies_id_fk": { + "name": "tool_mcp_skills_company_id_companies_id_fk", + "tableFrom": "tool_mcp_skills", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_skills_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_skills_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_skills", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.tool_oauth_states": { "name": "tool_oauth_states", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 6e6a9dde60f..0d61b8089e7 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3312,6 +3312,13 @@ "when": 1794524253117, "tag": "0474_milky_wolf_cub", "breakpoints": true + }, + { + "idx": 475, + "version": "7", + "when": 1794532772498, + "tag": "0475_sandbox_creation_owner_unresolved", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/sandbox_creation_operations.ts b/packages/db/src/schema/sandbox_creation_operations.ts index bb81e503793..949f2f34b04 100644 --- a/packages/db/src/schema/sandbox_creation_operations.ts +++ b/packages/db/src/schema/sandbox_creation_operations.ts @@ -23,5 +23,8 @@ export const sandboxCreationOperations = pgTable("sandbox_creation_operations", updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, table => ({ pendingDeadline: index("sandbox_creation_operations_pending_deadline_idx").on(table.nextAttemptAt).where(sql`${table.state} = 'pending'`), - owner: uniqueIndex("sandbox_creation_operations_owner_idx").on(table.companyId, table.originalEnvironmentId, table.runId, table.requestKey), + // A resolved operation's sandbox is proven stopped, so it no longer holds its + // creation key: a later attempt for the same run and request may create again. + owner: uniqueIndex("sandbox_creation_operations_owner_idx").on(table.companyId, table.originalEnvironmentId, table.runId, table.requestKey) + .where(sql`${table.state} <> 'resolved'`), })); diff --git a/server/src/__tests__/sandbox-creation-operations.test.ts b/server/src/__tests__/sandbox-creation-operations.test.ts index af31da1b260..6a34fe65298 100644 --- a/server/src/__tests__/sandbox-creation-operations.test.ts +++ b/server/src/__tests__/sandbox-creation-operations.test.ts @@ -18,6 +18,8 @@ import * as secretOwner from "../services/secrets.js"; import { readIdleSleepSafety } from "../services/idle-sleep-safety.js"; import { nextEnvironmentCleanupAt } from "../services/environment-cleanup-state.js"; import { readProcessStartedAt } from "../services/hot-restart.js"; +import { hasRemoteTerminationReceipt, remoteTerminationReceipt, resolveRemoteTerminationLease } from "../services/remote-execution-termination.js"; +import { createReusableLeaseHandoff } from "../services/environment-lease-handoff.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; const external = resolveExternalTestDatabaseUrl("PAPERCLIP_HISTORY_TEST_DATABASE_URL"); @@ -164,6 +166,11 @@ describe("durable sandbox creation through the runtime entry point", () => { } expect(await db.select().from(sandboxCreationOperations)).toEqual([before]); expect(creates).toBe(1); + // The later migration narrowed the key to unresolved operations; a reapply keeps that. + const indexes = await db.execute(sql`select indexdef from pg_indexes where indexname = 'sandbox_creation_operations_owner_idx'`); + expect([...indexes].map(row => String((row as { indexdef: unknown }).indexdef))).toEqual([ + expect.stringContaining("WHERE (state <> 'resolved'::text)"), + ]); }); it("fails before the external action when the durable admission write fails", async () => { await rejectWrites("sandbox_creation_operations", "reject_fixture_creation"); @@ -178,6 +185,129 @@ describe("durable sandbox creation through the runtime entry point", () => { expect(await db.select().from(environmentLeases)).toHaveLength(1); expect(await nextEnvironmentCleanupAt(db)).toBeNull(); }); + describe("same-run recovery after the attached lease closes", () => { + type Lease = Awaited>["lease"]; + const stopReceipt = (lease: Lease) => remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }); + const operations = () => db.select().from(sandboxCreationOperations); + async function acquirePlugin() { + await db.update(environments).set({ driver: "plugin", config: { pluginKey: "paperclip.creation-fixture", driverKey: "creation-fixture", driverConfig: {} } }).where(eq(environments.id, environmentId)); + const [plugin] = await db.select().from(plugins).where(eq(plugins.id, pluginId)); + await db.update(plugins).set({ manifestJson: { ...plugin.manifestJson, environmentDrivers: [{ driverKey: "creation-fixture", kind: "environment_driver", displayName: "Computer", creationOperationVersion: 1, configSchema: { type: "object" } }] } }).where(eq(plugins.id, pluginId)); + return runtime().acquireRunLease({ companyId, environment: (await environmentService(db).getById(environmentId))!, + heartbeatRunId: runId, issueId: null, persistedExecutionWorkspace: null }); + } + /** The closing write left the operation attached; the next creation with the + * same key proves the stop, resolves it, and creates exactly one replacement. */ + async function expectOneReplacement(first: { lease: Lease }, acquireLease: () => Promise<{ lease: Lease }>) { + const [before] = await operations(); + expect(before).toMatchObject({ state: "attached", leaseId: first.lease.id }); + const second = await acquireLease(); + expect(second.lease.id).not.toBe(first.lease.id); + expect(second.lease.providerLeaseId).not.toBe(first.lease.providerLeaseId); + expect(creates).toBe(2); + expect(await operations()).toEqual(expect.arrayContaining([ + expect.objectContaining({ id: before!.id, state: "resolved", leaseId: first.lease.id }), + expect.objectContaining({ state: "attached", leaseId: second.lease.id, runId, requestKey: before!.requestKey }), + ])); + // A retry of the replacement replays it instead of creating again. + expect((await acquireLease()).lease.id).toBe(second.lease.id); + expect(creates).toBe(2); + } + + it.each([["sandbox", acquire], ["plugin", acquirePlugin]] as const)("creates one replacement once a stop receipt closes the %s lease", async (_driver, acquireLease) => { + const first = await acquireLease(); + expect(await environmentService(db).releaseLease(first.lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: stopReceipt(first.lease) })) + .toMatchObject({ status: "released" }); + await expectOneReplacement(first, acquireLease); + }); + + it("creates one replacement after the Runner complete operation stops a retained reusable lease", async () => { + const first = await acquirePlugin(); + await db.update(environmentLeases).set({ status: "retained", leasePolicy: "reuse_by_environment", releasedAt: null }) + .where(eq(environmentLeases.id, first.lease.id)); + // The same write the `complete` operation makes for each reusable owner of a + // stopped task: no releaseLease call. + const [owner] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, first.lease.id)); + await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success", + metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ + remoteExecutionTermination: remoteTerminationReceipt(owner!, { providerLeaseId: owner!.providerLeaseId, state: "stopped" }), + runnerTaskExecutionStopped: true })}::jsonb` }).where(eq(environmentLeases.id, first.lease.id)); + await expectOneReplacement(first, acquirePlugin); + }); + + it("creates one replacement when only the destroyed successor proves an expired reusable lease stopped", async () => { + const first = await acquire(); + const [{ agentId }] = await db.select({ agentId: agents.id }).from(agents).where(eq(agents.companyId, companyId)); + const issueId = randomUUID(), successorRunId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Reused sandbox", status: "done" }); + await db.insert(heartbeatRuns).values({ id: successorRunId, companyId, agentId, invocationSource: "on_demand", status: "succeeded" }); + const acquiredAt = new Date(Date.now() - 2000), handoffAt = new Date(Date.now() - 1000); + const [previous] = await db.update(environmentLeases).set({ status: "expired", leasePolicy: "reuse_by_environment", issueId, + acquiredAt, releasedAt: handoffAt, cleanupStatus: "success", metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({ agentId })}::jsonb` }) + .where(eq(environmentLeases.id, first.lease.id)).returning(); + const successor = { ...previous!, id: randomUUID(), heartbeatRunId: successorRunId, acquiredAt: handoffAt, + status: "released" as const, releasedAt: new Date(), metadata: { agentId } }; + const handoff = createReusableLeaseHandoff(previous!, successor); + await db.update(environmentLeases).set({ metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({ reusableLeaseSuccessor: handoff })}::jsonb` }) + .where(eq(environmentLeases.id, first.lease.id)); + await db.insert(environmentLeases).values({ ...successor, metadata: { agentId, reusableLeasePredecessor: handoff, + remoteExecutionTermination: remoteTerminationReceipt(successor, { providerLeaseId: successor.providerLeaseId, state: "destroyed" }) } }); + const [stored] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, first.lease.id)); + // No receipt is stored on the expired lease; recovery computes it from the successor. + expect(hasRemoteTerminationReceipt(stored!)).toBe(false); + expect(hasRemoteTerminationReceipt(await resolveRemoteTerminationLease(db, stored!))).toBe(true); + await expectOneReplacement(first, acquire); + }); + + it.each([ + ["failed cleanup", "failed", { cleanupStatus: "failed", receipt: true }], + ["cleanup success without a receipt", "released", { cleanupStatus: "success", receipt: false }], + ["a receipt for another lease", "released", { cleanupStatus: "success", receipt: "foreign" }], + ["a receipt for another provider task", "released", { cleanupStatus: "success", receipt: "other-task" }], + ["a retained lease", "retained", { cleanupStatus: "success", receipt: true }], + ["pending cleanup", "pending_cleanup", { cleanupStatus: "failed", receipt: false }], + ] as const)("keeps the creation key after %s", async (_case, status, options) => { + const first = await acquire(); + const receipt = options.receipt === "foreign" ? stopReceipt({ ...first.lease, id: randomUUID() }) + : options.receipt === "other-task" ? { ...stopReceipt(first.lease), providerLeaseId: "other-task" } + : options.receipt ? stopReceipt(first.lease) : undefined; + await environmentService(db).releaseLease(first.lease.id, status, { cleanupStatus: options.cleanupStatus, + ...(receipt ? { remoteExecutionTermination: receipt } : {}) }); + await expect(acquire()).rejects.toThrow("Sandbox creation has already transferred ownership"); + expect(await operations()).toEqual([expect.objectContaining({ state: "attached", leaseId: first.lease.id })]); + expect(creates).toBe(1); + }); + + it("keeps an earlier task's operation when the lease now holds a replacement task", async () => { + const first = await acquire(); + await db.update(sandboxCreationOperations).set({ metadata: sql`metadata || '{"creationProviderLeaseId":"earlier-task"}'::jsonb` }); + await environmentService(db).releaseLease(first.lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: stopReceipt(first.lease) }); + await expect(acquire()).rejects.toThrow("Sandbox creation has already transferred ownership"); + expect(await operations()).toEqual([expect.objectContaining({ state: "attached", leaseId: first.lease.id })]); + expect(creates).toBe(1); + }); + + it("lets only one of two concurrent recoveries create the replacement", async () => { + const first = await acquire(); + await environmentService(db).releaseLease(first.lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: stopReceipt(first.lease) }); + // Hold whichever recovery reaches the provider until the other one has settled. + let settleOther!: () => void; + const otherSettled = new Promise(resolve => { settleOther = resolve; }); + beforeReply = () => otherSettled; + const outcomes = [acquire(), acquire()].map(attempt => attempt.then( + value => ({ value, error: undefined }), (error: unknown) => ({ value: undefined, error }))); + const loser = await Promise.race(outcomes); + settleOther(); + const settled = await Promise.all(outcomes); + expect(loser.error).toEqual(expect.objectContaining({ message: "Sandbox creation requires reconciliation before another attempt" })); + expect(settled.filter(outcome => outcome.value)).toHaveLength(1); + expect(creates).toBe(2); + expect((await operations()).filter(operation => operation.state !== "resolved")).toEqual([ + expect.objectContaining({ state: "attached", leaseId: settled.find(outcome => outcome.value)!.value!.lease.id }), + ]); + expect(await operations()).toHaveLength(2); + }); + }); it("recovers a failed lease write with a fresh receiver and empty web disk", async () => { await rejectWrites("environment_leases", "reject_fixture_lease"); await expect(acquire()).rejects.toThrow(); diff --git a/server/src/services/sandbox-creation-operations.ts b/server/src/services/sandbox-creation-operations.ts index 4ab1d20048b..dd8ec2af093 100644 --- a/server/src/services/sandbox-creation-operations.ts +++ b/server/src/services/sandbox-creation-operations.ts @@ -1,14 +1,15 @@ import { collectSecretRefPaths, isUuidSecretRef, parseSecretRefBindingObject, readConfigValueAtPath } from "./json-schema-secret-refs.js"; import { createHash, randomUUID } from "node:crypto"; -import { and, eq, lte, or, sql } from "drizzle-orm"; +import { and, eq, lte, ne, or, sql } from "drizzle-orm"; import { currentControllerProcess } from "./controller-process-identity.js"; -import { companies, environments, heartbeatRuns, sandboxCreationOperations, type Db } from "@paperclipai/db"; +import { companies, environmentLeases, environments, heartbeatRuns, sandboxCreationOperations, type Db } from "@paperclipai/db"; import { readEnvironmentCreationCleanupError, type PluginEnvironmentLease, type PluginEnvironmentLeaseObservation } from "@paperclipai/plugin-sdk"; import { assertEnvironmentCompanyBinding, environmentService } from "./environments.js"; import { ENVIRONMENT_CLEANUP_RETRY_MS, recoverableSandboxCreationCondition } from "./environment-cleanup-state.js"; import { logger } from "../middleware/logger.js"; import { notifyEnvironmentCleanup, writeEnvironmentCleanup } from "./environment-cleanup-notifications.js"; import { crashPoint } from "@paperclipai/shared/crash-points"; +import { hasRemoteTerminationReceipt, resolveRemoteTerminationLease } from "./remote-execution-termination.js"; export type SandboxCreationOperation = typeof sandboxCreationOperations.$inferSelect; @@ -70,9 +71,14 @@ export async function createOwnedSandbox( const runId = owner.heartbeatRunId ?? randomUUID(); const settleAt = new Date(Date.now() + Math.max(CREATION_SETTLE_FLOOR_MS, (owner.timeoutMs ?? 0) + 60_000)); const creationController = await currentControllerProcess(); - const operation = await db.transaction(async tx => { + const admit = (stopped?: SandboxCreationOperation) => db.transaction(async tx => { await notifyEnvironmentCleanup(tx, { companyId: owner.companyId, runId: owner.heartbeatRunId ?? undefined }); await assertEnvironmentCompanyBinding(tx as unknown as Db, owner.environmentId, owner.companyId); + // Only one concurrent attempt resolves the stopped operation; any other one + // then meets the replacement below and is fenced exactly as before. + if (stopped) await tx.update(sandboxCreationOperations).set({ state: "resolved", updatedAt: new Date() }).where(and( + eq(sandboxCreationOperations.id, stopped.id), eq(sandboxCreationOperations.state, "attached"), + eq(sandboxCreationOperations.leaseId, stopped.leaseId!))); const [inserted] = await tx.insert(sandboxCreationOperations).values({ id, companyId: owner.companyId, environmentId: owner.environmentId, originalEnvironmentId: owner.environmentId, runId, requestKey: owner.requestKey ?? "run", issueId: owner.issueId, executionWorkspaceId: owner.executionWorkspaceId, @@ -85,10 +91,13 @@ export async function createOwnedSandbox( const [existing] = await tx.select().from(sandboxCreationOperations).where(and( eq(sandboxCreationOperations.companyId, owner.companyId), eq(sandboxCreationOperations.originalEnvironmentId, owner.environmentId), eq(sandboxCreationOperations.runId, runId), eq(sandboxCreationOperations.requestKey, owner.requestKey ?? "run"), + ne(sandboxCreationOperations.state, "resolved"), )); if (!existing) throw new Error("Sandbox creation ownership was not recorded"); return existing; }); + let operation = await admit(); + if (operation.id !== id && await createdSandboxStopped(db, operation)) operation = await admit(operation); if (operation.id !== id) { if (operation.state !== "attached" || !operation.leaseId) throw new Error("Sandbox creation requires reconciliation before another attempt"); const existing = await environmentService(db).getLeaseById(operation.leaseId); @@ -116,6 +125,20 @@ export async function createOwnedSandbox( } } +/** An attached operation is finished once its closed lease carries the same + * stop proof same-run recovery requires (remoteExecutionHasStopped) for the + * sandbox this operation created. A task replacement can leave an earlier + * operation attached to a lease that now holds another sandbox; that operation + * is not proven and keeps its key. */ +async function createdSandboxStopped(db: Db, operation: SandboxCreationOperation): Promise { + if (operation.state !== "attached" || !operation.leaseId) return false; + const [lease] = await db.select().from(environmentLeases).where(and( + eq(environmentLeases.id, operation.leaseId), eq(environmentLeases.companyId, operation.companyId))); + if (!lease || lease.status === "active" || !lease.providerLeaseId) return false; + const created = operation.metadata.creationProviderLeaseId ?? lease.providerLeaseId; + return created === lease.providerLeaseId && hasRemoteTerminationReceipt(await resolveRemoteTerminationLease(db, lease)); +} + /** Keep an already returned resource identity even when task attachment fails. * This enriches the existing owner; it never transfers or reopens ownership. */ export async function recordSandboxCreationResource(db: Db, input: { From 25e9a9c2e9277f3be8649be8c809cc81bde6f0c5 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Thu, 12 Nov 2026 20:27:36 -0800 Subject: [PATCH 13/15] feat(ci): publish both variants of the Runner image from master (#21230) 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 Runner is the part that executes agent work: a daemon (`paperclip-runnerd`) and a provider pack of agent tools > - Parts 2 and 3 of this stack build the Runner alone as an image with two variants, and check it on pull requests. Nothing publishes it > - Downstream sandbox and VM images can copy the Runner only from a registry, and they must be able to verify where it came from > - A published image must be exactly the bytes that were checked, and its name must never point at something else later > - This pull request publishes both variants from `master` as `ghcr.io/paperclipai/paperclip-runner`, one time for each distinct set of inputs, and attests them > - Nothing consumes the image in this pull request. The application image build does not change > - The benefit is one verified, attested Runner that later changes can copy by digest ## Linked Issues or Issue Description Refs #21204 (part 2 of this stack) and #21096 (the merge-queue image build). No issue exists for this change. **Problem or motivation** The Runner image exists only inside a pull-request check. A consumer cannot pull it. There is no rule for which commit publishes an image, no protection for its tags, and no way to verify a copied Runner. **Proposed solution** Publish from a `master` push in this repository, and from nothing else. Build only when no image has the digest of the commit's inputs. Let the build legs hold no write access. Push the bytes that the legs checked by digest, attest each multi-platform index, and write the tags last. Write the full tag after the slim tag, so that the full tag means "both exist". **Alternatives considered** - Publish from `docker.yml`. That workflow holds one concurrency slot for each ref, and the Runner image needs its own signer identity, so that its attestation cannot stand in for the application image's. - Resolve the lockfile in the workflow before a `master` build, as `docker.yml` does. Then the published Runner depends on the state of the npm registry at run time, and the digest cannot be computed again from a commit. - Hand each variant to the publish job as its own OCI archive. The two archives hold the two shared layers two times: 1.27 GB for each architecture in place of 0.85 GB. - Write the full tag first. Then a consumer can see a full image whose slim image does not exist yet. **Roadmap alignment** This is build infrastructure. It adds no product feature and does not overlap an item in `ROADMAP.md`. This is part 4 of 4. Each part is on top of the one before it: 1. #21228 (merged): an optional field in the provider pack manifest 2. #21204: build and check the Runner image, with no publication 3. #21229: layers by change rate, and the slim variant 4. #21230: publish both variants from `master` (this pull request) ## What Changed - `.github/workflows/runner-image.yml`: adds the trigger `push` to `master` and the job `publish`. - `identity` checks the committed lockfile against the Runner's manifests, computes the digest in the build context, and asks the registry whether these inputs are published. - `build` is the job of part 3. It also records what it built, on every event. On a canonical `master` push it uploads that. It cannot write to the registry on any event. The only token in the job can read packages, and only the lookup step receives it. - `publish` runs only for a `master` push in this repository. It builds nothing and runs no dependency code. - Lockfile rule. A `master` push builds from the committed `pnpm-lock.yaml` and resolves nothing, so the digest is a function of the commit. When the committed lockfile is behind the manifests that the Runner build reads, the run writes a notice, publishes nothing, and stays green. The commit that merges the lockfile refresh publishes the image. Pull requests and manual runs resolve the lockfile first, always build, and never publish. - Hand-off. Each leg joins its two OCI archives into one OCI layout that names the images `slim` and `full`. The layout stores the two shared layers one time. `record` then reads the layout back, each image by its name, and checks every blob against its digest. The leg's record binds the layout to both image digests, the architecture, the inputs digest, and the commit. Those digests are the digests of the archives that part 3 unpacks and checks, so the tree that is checked and the image that is pushed are the same bytes. The publish job accepts only records for its own inputs and commit, and only a layout that still has the recorded bytes. - `record` runs on pull requests too. Only the upload is for a `master` push. A pull request therefore runs the hand-off on real build output. - Publication order. The publish job pushes the four images by digest (`skopeo copy --preserve-digests`). It makes a candidate index for the slim variant, then one for the full variant that names the slim index in the annotation `io.paperclip.runner.slim-digest`. It verifies that each index names exactly the recorded images, attests both, and then writes `inputs--slim` and, last, `inputs-`. - The full tag is the completion marker. Every "is it published" lookup reads the full tag. `publication-state` reports one of: | State | Registry | What a run does | | --- | --- | --- | | `absent` | Neither tag | Builds and publishes | | `incomplete` | The slim tag alone | Builds and publishes. It replaces the slim tag with its own image, then writes the full tag | | `published` | The full tag, and the slim tag at the digest that the full index names | Nothing | | broken | The full tag, and a slim tag that is missing or points at another image | Fails, with the steps for an operator | | `unknown` | No clear answer | Builds. The publish job fails before it writes a final tag | - Recovery rule. A run that stops between the two tags leaves the state `incomplete`. It does not block those inputs. The next run never keeps the earlier slim image: it writes its own slim tag immediately before its full tag, verifies both against its own index digests, and then reads the pair back as every later run will see it. The broken state cannot be repaired by a run, because no run moves a full tag. An operator must delete the two package versions and re-run the workflow run of a `master` push with those inputs. - Pairing rule for consumers, in the contract: resolve the full tag first, take the slim digest from the annotation of the full index, and pull the slim image by that digest. - `verify-index` accepts `linux/arm64` with the variant `v8`, which some BuildKit versions record, and no other variant. - `scripts/runner-image-publish.mjs` (533 lines): the commands `lock-state`, `record`, `verify-legs`, `publication-state` and `verify-index`. It reads archives with the reader of `scripts/runner-image-oci.mjs` (607 lines here), which can now read one named image of a layout. `lock-state` refuses a checkout, because pnpm can rewrite the lockfile of the tree that it checks. The workflow gives it an export that no build reads. - The workflow test pins the build arguments of the image build. Build arguments are not part of the image identity. - `doc/runner-image-contract.md` (197 lines): the section "Publication": the lockfile rule, the order, the pairing rule, the recovery rule, the create-only tags, the internal `candidate-` tags, the command that verifies provenance, and the step to make the package public. `doc/DOCKER.md` says where the image is published. ## Verification Tests, and the build jobs of the workflow on GitHub. Nothing in this pull request ran against a registry, and no publish job has run. - Linux (the pinned `node:24.22.3-bookworm` base with GNU tar 1.34 and zstd): `runner-image-publish.test.ts` (75), `runner-image-workflow.test.ts` (12), the three other Runner image test files, the provider pack archive tests and the existing Dockerfile tests: 372 tests pass in 10 files. The same files pass on macOS. - The tests of the leg record failed on Linux in the first runs of this pull request: their fixtures named the archive members `./index.json`, which bsdtar finds and GNU tar does not. The fixtures now name the members as buildx does, and the publish script uses the one reader of part 3. - Leg records: both variants are accepted for this run's inputs and commit; other inputs, another commit, a changed layout, a record without a variant, an archive that lacks a blob, a full image that does not start with the slim image's layers, and a build that is not a publication build are refused. - Publication state: all five states, and the half-finished publication end to end. A slim tag alone lets the next run publish. A full image that is left with another run's slim tag is reported as broken. - Index: exactly the recorded images of one variant; the full index must name its slim index, and the slim index must name none; `v8` is accepted on arm64 only. - Registry lookups: a missing tag only when the registry says so; every refused, failed, or unreachable request is `unknown`. - Workflow: job permissions; the publish job and the upload are behind the canonical `master` push; the build steps receive no credential; the full tag is written last, after a strict lookup and both attestations; one export and a time limit for each build command; the two build arguments; actions pinned by commit; no expression inside a shell script. - `record` on the two OCI archives of a real `linux/arm64` build from part 3: the joined layout is 850,149,376 bytes, and both images read back by name with every blob under its digest. The two archives together are 1,273,646,592 bytes. The image digests in the record are the digests that `unpack` reports for the trees that were checked. - `tests/runner-e2e` workflow tests: 39 pass. `node --test .github/scripts/tests/*.test.mjs`: 799 pass. `node --test` on the image contract scripts: 33 pass. `docker buildx build --check` reports nothing. The image identity is the same as in part 3 (`a544fc9dde780963419ede0f34252f3a57de43a760d41d3eb8fcd4f577504f6a`), because this pull request changes no input of the image. GitHub, at this head: - The `Runner image` workflow passes with these changes: `Build and check (amd64)` in 18m30s and `Build and check (arm64)` in 7m48s. Each leg builds both variants, checks them, and writes the leg record. `Publish and attest` is skipped, as it must be on a pull request. Never run: - The publish job. It runs only for a `master` push. - The publish path: the registry lookups with a workflow token, `skopeo copy` from `oci-archive::` by digest, `docker buildx imagetools create` with index annotations, and the tag writes. - The attestations, and the `gh attestation verify` command in the document. - `actionlint`. It is not installed on the local host. - The full test suite and the full typecheck. CI must supply them. ## Risks - **Manual step.** GitHub creates the `paperclip-runner` package private on the first publication. A maintainer must make it public one time. Until then, consumers cannot pull the image without credentials. - The first `master` runs of the workflow are the first test of the publish path. A failure before the tags publishes nothing. A failure between the two tags leaves the `incomplete` state, and the next run with those inputs repairs it. - A slim tag can move while its publication is incomplete. A consumer must resolve the full tag first and take the slim digest from the annotation of the full index. It must never resolve `inputs--slim` by tag on its own. The contract says so. - `candidate-` tags are written before the attestations and can name an index that is not attested. They are internal. - The broken state needs an operator, and it fails every `master` run with those inputs until then. It can arise only when someone changes or deletes a tag outside the workflow. - **Known residual.** Two `master` runs that both start before a new digest is published can each build the image. Each build leg and the publish job look again before they work, and the publish job runs one at a time for each digest. The cost is runner time, not correctness. - A commit whose lockfile is behind the Runner's manifests has no published Runner image until the lockfile refresh merges. A lockfile that the refresh cannot fix leaves every `master` run green with only a notice, for as long as it lasts. - The tags are create-only because the workflow never moves a tag of a complete publication. The registry does not enforce that. Consumers must pin the digest and verify the attestation. - `payload.runnerSourceRevision` in a pack from this image is the commit that published the image. Code that reads it as the application's commit must change before it consumes the image. > 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 Fable 5.2 (`claude-fable-5-2`), Anthropic, used through Claude Code with tool use (shell, file edits, local Docker builds). ## 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 Fable 5.2 --- .github/workflows/runner-image.yml | 419 ++++++++++++- doc/DOCKER.md | 3 +- doc/runner-image-contract.md | 52 +- scripts/runner-image-oci.mjs | 32 +- scripts/runner-image-publish.mjs | 533 +++++++++++++++++ .../__tests__/runner-image-publish.test.ts | 548 ++++++++++++++++++ .../__tests__/runner-image-workflow.test.ts | 116 +++- 7 files changed, 1660 insertions(+), 43 deletions(-) create mode 100644 scripts/runner-image-publish.mjs create mode 100644 server/src/__tests__/runner-image-publish.test.ts diff --git a/.github/workflows/runner-image.yml b/.github/workflows/runner-image.yml index c8855371fad..c98a189724e 100644 --- a/.github/workflows/runner-image.yml +++ b/.github/workflows/runner-image.yml @@ -1,13 +1,29 @@ name: Runner image -# Builds and checks the Runner image: the `runner-artifacts` target of the -# Dockerfile, a plain file tree that other image builds copy the Runner from, -# and its `runner-artifacts-slim` variant without the pack's transport -# archives. doc/runner-image-contract.md is the contract. +# Builds the Runner once for each distinct set of its inputs and publishes it +# as ghcr.io/paperclipai/paperclip-runner, a multi-platform image that other +# image builds copy from, in two variants: `inputs-` (full) and +# `inputs--slim` (without the pack's transport archives). +# doc/runner-image-contract.md is the contract. # -# This workflow builds and checks only. It has no access to a registry and -# publishes nothing. +# Every master push computes the digest from the commit's own build context, +# with the committed pnpm-lock.yaml. The build runs only when no image has +# that digest yet. When the committed lockfile is behind the manifests the +# Runner build reads, the run says so, publishes nothing and stays green: the +# repository's lockfile refresh brings the commit that publishes. +# +# Pull requests that touch the Runner's inputs, its recipe or this pipeline, +# and manual runs, always build and check the image and never publish it. +# They resolve the lockfile first, because a contributor cannot edit it. +# +# This is a workflow of its own, not a job in docker.yml: docker.yml has no +# pull-request trigger and holds one concurrency slot per ref, and the Runner +# image needs its own signer identity so its attestation cannot stand in for +# the application image's. on: + push: + branches: + - master pull_request: # Every input of scripts/runner-image-identity.mjs, .dockerignore (it # decides which of those files the build receives), and the pipeline's @@ -30,27 +46,40 @@ on: - scripts/runner-image-identity.mjs - scripts/runner-image-layout.mjs - scripts/runner-image-oci.mjs + - scripts/runner-image-publish.mjs + - scripts/standard-image-contract.mjs - docker/runner-image/** workflow_dispatch: -# Least privilege: nothing at the workflow level, and read-only contents in -# each job. +# Least privilege: nothing at the workflow level. Only the publish job, which +# runs no build, can write to the registry or sign. permissions: {} -# A newer push to a pull request replaces its older run. +# A newer push to a pull request replaces its older run. A master run has a +# group of its own, so no other run cancels it here. The publish job has a +# second group, one for each digest; see there for what that group can cancel. concurrency: group: runner-image-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + IMAGE: ghcr.io/paperclipai/paperclip-runner + jobs: identity: name: Resolve the Runner image identity + # A fork's own pushes do not run this workflow. Pull requests and manual + # runs are not affected. + if: github.event_name != 'push' || (github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064') runs-on: ubuntu-latest timeout-minutes: 15 permissions: contents: read + packages: read outputs: + lock: ${{ steps.lock.outputs.state }} digest: ${{ steps.identity.outputs.digest }} + exists: ${{ steps.lookup.outputs.exists }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -63,7 +92,7 @@ jobs: version: 9.15.4 run_install: false - # No dependency cache: a restored cache must not reach the image. + # No dependency cache: a restored cache must not reach a published image. - name: Setup Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: @@ -73,7 +102,13 @@ jobs: # A contributor cannot edit pnpm-lock.yaml, so a pull request that # changes the Runner's dependencies is built against a lockfile resolved # here. The image build installs from it frozen. + # + # Never on a master push. The lockfile refresh owns pnpm-lock.yaml on + # master and holds new package versions until they are old enough, so + # the published image installs from the committed file and its digest + # is a function of the commit alone. - name: Resolve the lockfile + if: github.event_name != 'push' run: | set -euo pipefail pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile @@ -84,7 +119,10 @@ jobs: echo "$changed" exit 1 fi - echo "This run built from a \`pnpm-lock.yaml\` resolved for it${changed:+ (it differs from the committed file)}." >> "$GITHUB_STEP_SUMMARY" + { + echo "This run built from a \`pnpm-lock.yaml\` resolved for it${changed:+ (it differs from the committed file)}." + echo "A master push publishes only from the committed lockfile." + } >> "$GITHUB_STEP_SUMMARY" - name: Set up Docker Buildx uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 @@ -93,11 +131,40 @@ jobs: [registry."docker.io"] mirrors = ["mirror.gcr.io"] + # The files the Runner build receives, after .dockerignore: the root + # manifest and the manifests of the Runner and the eval kernel are the + # only ones in it. + - name: Export the Runner build context + timeout-minutes: 10 + run: docker buildx build --target runner-artifacts-context --output "type=local,dest=$RUNNER_TEMP/runner-image-context" . + + # The image build installs with a frozen lockfile. This asks the same + # question first, offline and without installing, so that a lockfile + # that is merely behind is told apart from a broken build. pnpm can + # rewrite the lockfile it checks. It checks the exported copy above, + # which no build reads: the builds read the checkout. + - name: Check the lockfile against the Runner's manifests + id: lock + run: node scripts/runner-image-publish.mjs lock-state --context "$RUNNER_TEMP/runner-image-context" + + # On master this is expected between a dependency change and the next + # lockfile refresh. It is not a failure, and there is nothing to build. + - name: Report a lockfile that is behind the Runner's manifests + if: steps.lock.outputs.state == 'behind' + run: | + set -euo pipefail + message="pnpm-lock.yaml is behind the Runner's manifests at $GITHUB_SHA; no Runner image for this commit; the next lockfile refresh will publish one." + echo "::notice title=No Runner image for this commit::$message" + echo "$message" >> "$GITHUB_STEP_SUMMARY" + # A run that resolved its own lockfile cannot be behind it. + test "$GITHUB_EVENT_NAME" = "push" + # Computed inside the build, from the files the build context supplies # after .dockerignore. A digest computed from the checkout would cover # files the image build never receives. - name: Compute the identity in the build context id: identity + if: steps.lock.outputs.state == 'current' timeout-minutes: 10 run: | set -euo pipefail @@ -115,8 +182,10 @@ jobs: } >> "$GITHUB_STEP_SUMMARY" # The legs must build from the file the identity was computed from, not - # from a second resolution. + # from a second resolution. Only for runs that resolved one: a master + # push builds from the committed file, which every job checks out. - name: Keep the resolved lockfile for the build legs + if: steps.lock.outputs.state == 'current' && github.event_name != 'push' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: runner-image-lockfile @@ -124,14 +193,34 @@ jobs: if-no-files-found: error retention-days: 1 + # An image that exists is never rebuilt on master. It exists when its + # full tag does: that tag is written last. An inconclusive answer + # builds: the publish job decides again, strictly, before it writes a + # tag. Other events build whether or not the image exists. + - name: Look for the published image + id: lookup + if: steps.lock.outputs.state == 'current' && github.event_name == 'push' + env: + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + DIGEST: ${{ steps.identity.outputs.digest }} + run: node scripts/runner-image-publish.mjs publication-state --inputs-digest "$DIGEST" + # Multi-arch by native runner, not QEMU, as in docker.yml. GitHub-hosted # runners: the protected release fleets admit only docker.yml on master. # - # These legs hold no credential and use no registry build cache. The install - # runs dependency lifecycle scripts. + # These legs cannot write to the registry on any event, and they read and + # write no registry build cache. The install runs dependency lifecycle + # scripts; the only token in the job can read packages, and only the lookup + # step receives it. + # + # A master push builds only when the image does not exist. A pull request + # and a manual run always build, so a change to the smoke matrix or to the + # pipeline is exercised even when the Runner's inputs did not change. build: name: Build and check (${{ matrix.arch }}) needs: identity + if: needs.identity.outputs.lock == 'current' && (github.event_name != 'push' || (github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && needs.identity.outputs.exists != 'true')) strategy: fail-fast: false matrix: @@ -146,7 +235,10 @@ jobs: timeout-minutes: 60 permissions: contents: read + packages: read env: + # Only a canonical master push keeps its image for publication. + KEEP_IMAGE: ${{ github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs/heads/master' }} DIGEST: ${{ needs.identity.outputs.digest }} ARCH: ${{ matrix.arch }} PLATFORM: ${{ matrix.platform }} @@ -162,16 +254,33 @@ jobs: node-version: 24 package-manager-cache: false + # Another master run can have published these inputs since the identity + # job looked, most often the run of the push just before this one. Then + # this leg has nothing to do. Master only: other events always build. + # An inconclusive answer builds. + - name: Look again for the published image + id: published + if: github.event_name == 'push' + env: + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + run: node scripts/runner-image-publish.mjs publication-state --inputs-digest "$DIGEST" + - name: Download the resolved lockfile + if: github.event_name != 'push' uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: name: runner-image-lockfile path: ${{ runner.temp }}/runner-image-lockfile + # Build from the lockfile the identity was computed from, not from a + # second resolution that a registry change could make different. - name: Use the resolved lockfile + if: github.event_name != 'push' run: cp "$RUNNER_TEMP/runner-image-lockfile/pnpm-lock.yaml" pnpm-lock.yaml - name: Free runner disk + if: steps.published.outputs.exists != 'true' run: | set -euo pipefail sudo apt-get clean || true @@ -181,6 +290,7 @@ jobs: df -h - name: Set up Docker Buildx + if: steps.published.outputs.exists != 'true' uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 with: buildkitd-config-inline: | @@ -199,9 +309,11 @@ jobs: # # This is the publication form of the build, the only one whose pack # names the image (`runnerInputsDigest`), so the check below can bind - # the tree to the digest the identity job resolved. Nothing here - # publishes it: the archives and trees stay on this runner. + # the tree to the digest the identity job resolved. This job cannot + # publish it. On a canonical master push the archives are the images + # the publish job pushes, byte for byte. - name: Build both variants of the Runner image + if: steps.published.outputs.exists != 'true' timeout-minutes: 30 run: | set -euo pipefail @@ -215,6 +327,7 @@ jobs: --build-arg PAPERCLIP_RUNNER_IMAGE_PUBLICATION=1 \ --provenance=false --sbom=false \ --output "type=oci,dest=$RUNNER_TEMP/runner-image/$variant.oci.tar" \ + --metadata-file "$RUNNER_TEMP/runner-image/$variant.metadata.json" \ . done @@ -223,6 +336,7 @@ jobs: # not a second export of the build, and each blob is checked against # its digest as it is read. - name: Unpack both images + if: steps.published.outputs.exists != 'true' timeout-minutes: 10 run: | set -euo pipefail @@ -239,6 +353,7 @@ jobs: # them as a sandbox does and compares the result with the pack; that # needs about as much free disk as the pack is large. - name: Check the layout contract and pack integrity + if: steps.published.outputs.exists != 'true' timeout-minutes: 10 run: | set -euo pipefail @@ -254,6 +369,7 @@ jobs: # then the transport layers, with nothing else in them. No file may be # in two layers. - name: Check the layers of both variants + if: steps.published.outputs.exists != 'true' timeout-minutes: 10 run: | set -euo pipefail @@ -269,6 +385,7 @@ jobs: # one run covers both, and the slim tree is the smaller one to load. # This command has one export, a few small files. - name: Run the daemon on every consumer base image + if: steps.published.outputs.exists != 'true' timeout-minutes: 20 run: | docker buildx build \ @@ -278,3 +395,273 @@ jobs: --output "type=local,dest=$RUNNER_TEMP/runner-image/smoke" \ docker/runner-image ls -l "$RUNNER_TEMP/runner-image/smoke" + + # Written only after every check passed. The publish job accepts nothing + # without it. The two archives become one OCI layout that holds both + # variants and stores the layers they share once, so the upload is the + # size of the full image, not of both. The command reads the layout + # back and checks every blob against its digest. + # + # On every event, so that a pull request exercises the hand-off on + # real build output. Only the upload below is for a master push. + - name: Record the verified images + if: steps.published.outputs.exists != 'true' + timeout-minutes: 10 + run: | + node scripts/runner-image-publish.mjs record \ + --arch "$ARCH" \ + --slim-archive "$RUNNER_TEMP/runner-image/slim.oci.tar" \ + --slim-metadata "$RUNNER_TEMP/runner-image/slim.metadata.json" \ + --full-archive "$RUNNER_TEMP/runner-image/full.oci.tar" \ + --full-metadata "$RUNNER_TEMP/runner-image/full.metadata.json" \ + --tree "$RUNNER_TEMP/runner-image/full" \ + --layout "$RUNNER_TEMP/runner-image/images.oci.tar" \ + --out "$RUNNER_TEMP/runner-image/record.json" + + - name: Upload the verified images + if: env.KEEP_IMAGE == 'true' && steps.published.outputs.exists != 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: runner-image-${{ matrix.arch }} + path: | + ${{ runner.temp }}/runner-image/images.oci.tar + ${{ runner.temp }}/runner-image/record.json + if-no-files-found: error + # Layers are already compressed. + compression-level: 0 + retention-days: 1 + + - name: Report an image another run published first + if: steps.published.outputs.exists == 'true' + run: echo "\`$IMAGE:inputs-$DIGEST\` and its slim variant already exist. This leg built nothing." >> "$GITHUB_STEP_SUMMARY" + + # Pushes the verified bytes, names them and attests them. Only a master push + # in the canonical repository reaches this job; it builds nothing and runs no + # dependency code. + # + # It writes two tags, `inputs--slim` and then `inputs-`. The + # full tag is last, so it marks a complete publication: when it exists, both + # exist, and the full index names its slim index by digest. A run that stops + # between the two tags leaves a slim tag alone. The inputs are then not + # published; the next run for them builds again, replaces that slim tag with + # its own, and writes the full tag. It never keeps another run's slim image. + publish: + name: Publish and attest + needs: [identity, build] + if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs/heads/master' && needs.identity.outputs.lock == 'current' && needs.identity.outputs.exists != 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + packages: write + id-token: write + attestations: write + # One publication per digest at a time, so the strict check below and the + # tag writes cannot interleave with another run for the same inputs. + # GitHub keeps one waiting job for a group. When three runs for one digest + # reach this job, the second is cancelled as the third arrives. That does + # no harm: the third publishes the digest if the first did not. + concurrency: + group: runner-image-publish-${{ needs.identity.outputs.digest }} + cancel-in-progress: false + env: + DIGEST: ${{ needs.identity.outputs.digest }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24 + package-manager-cache: false + + # A build leg that found the image published uploaded nothing. Ask + # before the downloads, so that run ends here and not on a missing + # artifact. + - name: Look for an image another run published + id: early + env: + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + run: node scripts/runner-image-publish.mjs publication-state --inputs-digest "$DIGEST" + + - name: Download the verified amd64 images + if: steps.early.outputs.exists != 'true' + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: runner-image-amd64 + path: ${{ runner.temp }}/runner-image/amd64 + + - name: Download the verified arm64 images + if: steps.early.outputs.exists != 'true' + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: runner-image-arm64 + path: ${{ runner.temp }}/runner-image/arm64 + + - name: Accept only this run's verified images + id: legs + if: steps.early.outputs.exists != 'true' + run: | + node scripts/runner-image-publish.mjs verify-legs \ + --dir "$RUNNER_TEMP/runner-image" \ + --inputs-digest "$DIGEST" \ + --source-revision "$GITHUB_SHA" + + - name: Login to GitHub Container Registry + if: steps.early.outputs.exists != 'true' + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + if: steps.early.outputs.exists != 'true' + uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + + # The downloads take a while. Ask once more immediately before the + # pushes, so that a run that lost the race does not upload its images. + - name: Look again immediately before pushing + id: prepush + if: steps.early.outputs.exists != 'true' + env: + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + run: node scripts/runner-image-publish.mjs publication-state --inputs-digest "$DIGEST" + + # By digest and untagged. --preserve-digests fails rather than re-encode, + # so the registry holds exactly the images the build legs verified. Each + # leg's layout names its two images `slim` and `full`. + - name: Push the verified images by digest + if: steps.prepush.outputs.exists == 'false' + timeout-minutes: 15 + env: + SLIM_AMD64: ${{ steps.legs.outputs.slim_amd64 }} + SLIM_ARM64: ${{ steps.legs.outputs.slim_arm64 }} + FULL_AMD64: ${{ steps.legs.outputs.full_amd64 }} + FULL_ARM64: ${{ steps.legs.outputs.full_arm64 }} + run: | + set -euo pipefail + command -v skopeo >/dev/null || { echo "skopeo is not installed on this runner"; exit 1; } + echo "Pushing with $(skopeo --version)" + layout="$RUNNER_TEMP/runner-image" + skopeo copy --preserve-digests "oci-archive:$layout/amd64/images.oci.tar:slim" "docker://$IMAGE@$SLIM_AMD64" + skopeo copy --preserve-digests "oci-archive:$layout/arm64/images.oci.tar:slim" "docker://$IMAGE@$SLIM_ARM64" + skopeo copy --preserve-digests "oci-archive:$layout/amd64/images.oci.tar:full" "docker://$IMAGE@$FULL_AMD64" + skopeo copy --preserve-digests "oci-archive:$layout/arm64/images.oci.tar:full" "docker://$IMAGE@$FULL_ARM64" + + # The tags are create-only. Another run can have published these inputs + # since the lookups above. Only a clear answer goes on: `absent`, or + # `incomplete` (a slim tag alone, which this run replaces). `published` + # skips the rest. An inconclusive answer fails, and so does a full tag + # whose slim image is missing or is another image. + - name: Confirm the images are not published + id: gate + if: steps.prepush.outputs.exists == 'false' + env: + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + run: node scripts/runner-image-publish.mjs publication-state --inputs-digest "$DIGEST" --strict + + # Candidate tags first, so a final tag appears only after its digest is + # attested. Candidate tags are internal and may be overwritten. + - name: Create the slim multi-platform candidate + if: steps.gate.outputs.publish == 'true' + env: + AMD64: ${{ steps.legs.outputs.slim_amd64 }} + ARM64: ${{ steps.legs.outputs.slim_arm64 }} + run: | + set -euo pipefail + docker buildx imagetools create \ + --annotation "index:org.opencontainers.image.source=https://github.com/paperclipai/paperclip" \ + --annotation "index:org.opencontainers.image.revision=$GITHUB_SHA" \ + --annotation "index:io.paperclip.runner.inputs-digest=$DIGEST" \ + --annotation "index:io.paperclip.runner.variant=slim" \ + -t "$IMAGE:candidate-$DIGEST-slim" \ + "$IMAGE@$AMD64" "$IMAGE@$ARM64" + + - name: Verify the slim candidate names exactly the verified images + id: slim + if: steps.gate.outputs.publish == 'true' + env: + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + run: node scripts/runner-image-publish.mjs verify-index "candidate-$DIGEST-slim" --variant slim --dir "$RUNNER_TEMP/runner-image" + + # The full index names the slim index of this same run by digest, so a + # consumer can tell that the two belong together. + - name: Create the full multi-platform candidate + if: steps.gate.outputs.publish == 'true' + env: + AMD64: ${{ steps.legs.outputs.full_amd64 }} + ARM64: ${{ steps.legs.outputs.full_arm64 }} + SLIM_INDEX: ${{ steps.slim.outputs.digest }} + run: | + set -euo pipefail + docker buildx imagetools create \ + --annotation "index:org.opencontainers.image.source=https://github.com/paperclipai/paperclip" \ + --annotation "index:org.opencontainers.image.revision=$GITHUB_SHA" \ + --annotation "index:io.paperclip.runner.inputs-digest=$DIGEST" \ + --annotation "index:io.paperclip.runner.variant=full" \ + --annotation "index:io.paperclip.runner.slim-digest=$SLIM_INDEX" \ + -t "$IMAGE:candidate-$DIGEST" \ + "$IMAGE@$AMD64" "$IMAGE@$ARM64" + + - name: Verify the full candidate names exactly the verified images and its slim index + id: full + if: steps.gate.outputs.publish == 'true' + env: + SLIM_INDEX: ${{ steps.slim.outputs.digest }} + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + run: | + node scripts/runner-image-publish.mjs verify-index "candidate-$DIGEST" --variant full \ + --slim-digest "$SLIM_INDEX" --dir "$RUNNER_TEMP/runner-image" + + - name: Attest the slim Runner image + if: steps.gate.outputs.publish == 'true' + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4 + with: + subject-name: ghcr.io/paperclipai/paperclip-runner + subject-digest: ${{ steps.slim.outputs.digest }} + push-to-registry: true + + - name: Attest the full Runner image + if: steps.gate.outputs.publish == 'true' + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4 + with: + subject-name: ghcr.io/paperclipai/paperclip-runner + subject-digest: ${{ steps.full.outputs.digest }} + push-to-registry: true + + # Slim first, full last. Writing the slim tag replaces the one a run + # that stopped here left behind. The last command checks the pair as + # every later run will see it. + - name: Publish the tags + if: steps.gate.outputs.publish == 'true' + env: + SLIM_INDEX: ${{ steps.slim.outputs.digest }} + FULL_INDEX: ${{ steps.full.outputs.digest }} + RUNNER_IMAGE_REGISTRY_USERNAME: ${{ github.actor }} + RUNNER_IMAGE_REGISTRY_PASSWORD: ${{ github.token }} + run: | + set -euo pipefail + layout="$RUNNER_TEMP/runner-image" + docker buildx imagetools create -t "$IMAGE:inputs-$DIGEST-slim" "$IMAGE@$SLIM_INDEX" + node scripts/runner-image-publish.mjs verify-index "inputs-$DIGEST-slim" --variant slim --dir "$layout" --expect "$SLIM_INDEX" + docker buildx imagetools create -t "$IMAGE:inputs-$DIGEST" "$IMAGE@$FULL_INDEX" + node scripts/runner-image-publish.mjs verify-index "inputs-$DIGEST" --variant full --slim-digest "$SLIM_INDEX" --dir "$layout" --expect "$FULL_INDEX" + node scripts/runner-image-publish.mjs publication-state --inputs-digest "$DIGEST" --strict | grep -Fx "state=published" + { + echo "Published from \`$GITHUB_SHA\`:" + echo "- full: \`$IMAGE:inputs-$DIGEST\` at \`$IMAGE@$FULL_INDEX\`" + echo "- slim: \`$IMAGE:inputs-$DIGEST-slim\` at \`$IMAGE@$SLIM_INDEX\`" + } >> "$GITHUB_STEP_SUMMARY" + + - name: Report images another run published first + if: steps.early.outputs.exists == 'true' || steps.prepush.outputs.exists == 'true' || steps.gate.outputs.state == 'published' + run: echo "\`$IMAGE:inputs-$DIGEST\` and its slim variant already exist. Another run published first; this run published nothing." >> "$GITHUB_STEP_SUMMARY" diff --git a/doc/DOCKER.md b/doc/DOCKER.md index b208d6df269..771f800779b 100644 --- a/doc/DOCKER.md +++ b/doc/DOCKER.md @@ -84,7 +84,8 @@ package's build output, the remote provider pack and its transport archives. The `runner-artifacts-slim` target is the same image without the transport archives. Neither depends on the server or UI build, and no other target depends on them yet. `.github/workflows/runner-image.yml` builds and checks -both on pull requests, for Linux AMD64 and ARM64. See +both on pull requests, for Linux AMD64 and ARM64, and publishes them from +`master` as `ghcr.io/paperclipai/paperclip-runner`. See [`doc/runner-image-contract.md`](runner-image-contract.md) for the layout, the identity rules and how to consume the image. diff --git a/doc/runner-image-contract.md b/doc/runner-image-contract.md index f6263aedba5..3a535ff5b8a 100644 --- a/doc/runner-image-contract.md +++ b/doc/runner-image-contract.md @@ -10,9 +10,6 @@ two variants: - slim, the `runner-artifacts-slim` target: the same without the two paths marked "full only", the provider pack's transport archives. -Nothing publishes it yet: `.github/workflows/runner-image.yml` builds and -checks it. - ## Layout Every path a consumer may copy (`RUNNER_IMAGE_PATHS` in @@ -40,8 +37,9 @@ is the same file in both variants: - `inputsDigest` (the identity below) and `buildInputsDigest` (the digest in the Runner's build stamp); -- `sourceRevision`: the commit given to the build, also in the pack as - `payload.runnerSourceRevision`; +- `sourceRevision`: the commit that built the image, also in the pack as + `payload.runnerSourceRevision`. An image is published once for its + inputs, so later commits with the same inputs keep this revision; - `publication`: `true` only for a build with the build argument `PAPERCLIP_RUNNER_IMAGE_PUBLICATION=1`. Only then does the pack carry the identity, as `payload.runnerInputsDigest`. Another image build that runs @@ -70,8 +68,10 @@ lists the dependency files first, so their names do not depend on `dist`. ## Identity -Both variants are named by one digest, `inputs-`: the variant is not -part of the identity. `scripts/runner-image-identity.mjs` computes it from: +Both variants are named by one digest: the variant is not part of the +identity. The full image has the tag `inputs-` and the slim image +`inputs--slim`. `scripts/runner-image-identity.mjs` computes the +digest from: - every file under the paths the build copies from the build context (`RUNNER_IMAGE_CONTEXT_INPUTS`, which include `pnpm-lock.yaml`): path, @@ -144,6 +144,41 @@ its own, as in this repository, can take a built image or tree in its place with `--build-context =`. The stage is then not built. +## Publication + +`.github/workflows/runner-image.yml` publishes on a `master` push in this +repository and nowhere else. Other runs build and check, and publish nothing. + +- **Lockfile.** A `master` push builds from the committed `pnpm-lock.yaml`, + so the digest is a function of the commit. When that file is behind the + Runner's manifests, the run writes a notice, publishes nothing and stays + green. The commit that merges the lockfile refresh publishes the image. +- **Once.** The build runs only when `inputs-` does not exist. +- **Verified bytes.** The build legs cannot write to the registry. The + publish job pushes the images they checked by digest and joins each + variant into a multi-platform index under a `candidate-` tag. It attests + both indexes, and only then writes the two `inputs-` tags. `candidate-` + tags are internal: one can name an index that is not attested, and the + next run overwrites it. Do not consume them. +- **Order.** It writes `inputs--slim` first and `inputs-` + last, so the full tag marks a complete publication. The full index names + its slim index in the annotation `io.paperclip.runner.slim-digest`. +- **Pairing.** Resolve the full tag first. Take the slim digest from that + annotation of the full index, and pull the slim image by that digest. Never + resolve `inputs--slim` by tag on its own: while a publication is + incomplete, that tag can name the slim image of another run. +- **Recovery.** A run that stops between the two tags leaves a slim tag + alone. Those inputs are not published. The next run for them builds again, + replaces that tag with its own slim image and then writes the full tag. A + full tag whose slim tag is missing or names another image fails every run + for those inputs. An operator must then delete both package versions and + re-run the workflow run of a `master` push with those inputs. +- **Create-only.** The workflow never moves a tag of a complete publication, + but the registry does not enforce that. Pin the index digest and verify it: + `gh attestation verify oci://ghcr.io/paperclipai/paperclip-runner@sha256: --repo paperclipai/paperclip --signer-workflow paperclipai/paperclip/.github/workflows/runner-image.yml --source-ref refs/heads/master` +- **First publication.** GitHub creates the package private. A maintainer + must make it public once. + ## Known limits - A build without `PAPERCLIP_RUNNER_SOURCE_REVISION` or @@ -157,3 +192,6 @@ built. does not change the identity. - The archive check does not tell a directory with its own archive member from one created only as a file's parent. +- A lockfile that the lockfile refresh cannot bring up to the Runner's + manifests leaves every `master` run green with only a notice, for as long + as it lasts. No image is published in that time, and nothing fails. diff --git a/scripts/runner-image-oci.mjs b/scripts/runner-image-oci.mjs index f698920eaa1..45a1538ca7f 100644 --- a/scripts/runner-image-oci.mjs +++ b/scripts/runner-image-oci.mjs @@ -225,13 +225,18 @@ async function readTarStream(source, visit) { } /** - * The one image in an OCI archive: its manifest descriptor and its layers. A + * One image in an OCI archive: its manifest descriptor and its layers. A * member is found by its exact name (`index.json`, `blobs/sha256/`), as * buildx writes them. The manifest is checked against its digest here, and - * each layer when `readLayer` reads it. + * each layer when `readLayer` or `verifyBlobs` reads it. + * + * An archive from buildx holds one image. A layout that holds several names + * each with the annotation `org.opencontainers.image.ref.name`; `ref` then + * says which one to read. * @param {string} archive + * @param {{ ref?: string | null }} [options] */ -export function readOciArchive(archive) { +export function readOciArchive(archive, { ref = null } = {}) { const members = indexTarFile(archive); const located = (name) => { const member = members.get(name); @@ -255,12 +260,23 @@ export function readOciArchive(archive) { }; const sha256 = (data) => `sha256:${createHash("sha256").update(data).digest("hex")}`; const index = JSON.parse(bytes("index.json").toString("utf8")); - if (!Array.isArray(index.manifests) || index.manifests.length !== 1) throw new Error(`${archive} must hold exactly one image manifest`); - const { mediaType, digest, size } = index.manifests[0]; + if (!Array.isArray(index.manifests)) throw new Error(`${archive} has no list of manifests`); + const named = ref === null ? index.manifests : index.manifests.filter((entry) => entry.annotations?.["org.opencontainers.image.ref.name"] === ref); + if (named.length !== 1) { + throw new Error(ref === null ? `${archive} must hold exactly one image manifest` : `${archive} must hold exactly one image named ${ref}`); + } + const { mediaType, digest, size } = named[0]; const manifestBytes = bytes(blobName(digest)); if (sha256(manifestBytes) !== digest) throw new Error(`${archive}: the manifest does not have the digest the index names`); const manifest = JSON.parse(manifestBytes.toString("utf8")); if (!Array.isArray(manifest.layers)) throw new Error(`${archive} holds an index, not one platform's image; build without attestations`); + /** The digest of a blob's bytes as the archive holds them. */ + const blobDigest = async (name) => { + const { offset, size: length } = located(name); + const hash = createHash("sha256"); + if (length > 0) for await (const chunk of createReadStream(archive, { start: offset, end: offset + length - 1 })) hash.update(chunk); + return `sha256:${hash.digest("hex")}`; + }; for (const layer of manifest.layers) { if (!GZIP_LAYER.test(layer.mediaType ?? "")) throw new Error(`${archive}: layer ${layer.digest} is ${layer.mediaType}, not a gzip tar`); located(blobName(layer.digest)); @@ -270,6 +286,12 @@ export function readOciArchive(archive) { descriptor: { mediaType, digest, size }, /** @type {{ mediaType: string, digest: string, size: number }[]} */ layers: manifest.layers.map((layer) => ({ mediaType: layer.mediaType, digest: layer.digest, size: layer.size })), + /** Fails unless the config and every layer of the image are in the archive with their digests. */ + async verifyBlobs() { + for (const blob of [manifest.config, ...manifest.layers]) { + if (await blobDigest(blobName(blob?.digest)) !== blob.digest) throw new Error(`${archive}: blob ${blob.digest} does not have its digest`); + } + }, /** Visits every entry of one layer and fails when the blob does not have its digest. */ async readLayer(layer, visit) { const { offset, size: bytesInArchive } = located(blobName(layer.digest)); diff --git a/scripts/runner-image-publish.mjs b/scripts/runner-image-publish.mjs new file mode 100644 index 00000000000..48974f95404 --- /dev/null +++ b/scripts/runner-image-publish.mjs @@ -0,0 +1,533 @@ +#!/usr/bin/env node +// Publication checks for the Runner image (.github/workflows/runner-image.yml). +// +// The build legs run without write access to the registry. Each one records +// the two variants it built and verified, slim and full; the publish job +// pushes exactly those bytes, names each variant under one multi-platform +// tag and attests both. +// +// lock-state whether pnpm-lock.yaml matches the manifests in an exported +// `runner-artifacts-context` tree: `current` or `behind`. It +// runs the image build's own frozen install as a lockfile-only, +// offline check. Any other failure is an error. pnpm can +// rewrite the lockfile of the tree it checks, so the command +// refuses a checkout +// record a build leg, after its checks passed: joins the OCI archives +// of the two variants into one OCI layout, in which their +// shared layers are stored once, and binds it to the image +// digests, the architecture, the inputs digest and the source +// revision +// verify-legs the publish job, before any push: accepts only one record per +// architecture, for this run's inputs digest and commit, whose +// layout still has the recorded bytes +// publication-state whether these inputs are published. The full tag +// `inputs-` is written last, so it alone says +// `published`; a slim tag without it is `incomplete` and the +// next publication replaces it. A full tag whose slim tag is +// missing or names another image is an error. --strict also +// fails on `unknown` instead of guessing +// verify-index the pushed tag names exactly the recorded images of one +// variant; the full index must also name its slim index +// +// Registry credentials come from RUNNER_IMAGE_REGISTRY_USERNAME and +// RUNNER_IMAGE_REGISTRY_PASSWORD when both are set; lookups are anonymous +// otherwise. An unknown flag, a repeated flag or a flag with an empty value is +// an error. + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { createReadStream, existsSync } from "node:fs"; +import { appendFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { RUNNER_IMAGE_NAME, RUNNER_IMAGE_PLATFORMS } from "./runner-image-identity.mjs"; +import { RUNNER_IMAGE_PATHS, RUNNER_IMAGE_VARIANTS } from "./runner-image-layout.mjs"; +import { readOciArchive } from "./runner-image-oci.mjs"; +import { assertIndexUsesVerifiedImages, standardImageDigest } from "./standard-image-contract.mjs"; + +export const RUNNER_IMAGE_RECORD_SCHEMA = "paperclip.runner-image-leg.v2"; +/** On the full index: the digest of the slim index published with it. */ +export const SLIM_DIGEST_ANNOTATION = "io.paperclip.runner.slim-digest"; +/** The tag of each variant. The full tag is written last and marks a complete publication. */ +export const runnerImageTags = (inputsDigest) => ({ slim: `inputs-${inputsDigest}-slim`, full: `inputs-${inputsDigest}` }); +const ARCHITECTURES = RUNNER_IMAGE_PLATFORMS.map((platform) => platform.split("/")[1]); +const DIGEST = /^sha256:[0-9a-f]{64}$/; +const HEX_64 = /^[0-9a-f]{64}$/; +const REVISION = /^[0-9a-f]{40}$/; +const MANIFEST_TYPES = [ + "application/vnd.oci.image.index.v1+json", + "application/vnd.docker.distribution.manifest.list.v2+json", + "application/vnd.oci.image.manifest.v1+json", + "application/vnd.docker.distribution.manifest.v2+json", +].join(", "); + +async function sha256File(file) { + const hash = createHash("sha256"); + for await (const chunk of createReadStream(file)) hash.update(chunk); + return `sha256:${hash.digest("hex")}`; +} + +function tar(args, options = {}) { + const result = spawnSync("tar", args, { maxBuffer: 64 * 1024 * 1024, ...options }); + assert.equal(result.status, 0, `tar ${args[0]} failed: ${String(result.stderr).trim().slice(-300)}`); + return result.stdout; +} + +/** + * What a build leg hands to the publish job: one OCI layout with both + * variants, named `slim` and `full`, and a record read from the tree the leg + * verified. The layout stores the layers the variants share once. + * @param {{ + * architecture: string, + * archives: { slim: string, full: string }, + * metadataFiles: { slim: string, full: string }, + * tree: string, + * layout: string, + * }} input + */ +export async function createLegRecord({ architecture, archives, metadataFiles, tree, layout }) { + assert.ok(ARCHITECTURES.includes(architecture), `Unsupported architecture ${architecture}`); + const manifest = JSON.parse(await readFile(path.join(tree, RUNNER_IMAGE_PATHS.manifest), "utf8")); + assert.equal(manifest.platform?.architecture, architecture, "The verified tree is for another architecture"); + assert.match(manifest.inputsDigest?.digest ?? "", HEX_64); + assert.match(manifest.sourceRevision ?? "", REVISION); + assert.equal(manifest.publication, true, "Only a publication build can be recorded"); + /** @type {Record} */ + const images = {}; + for (const variant of RUNNER_IMAGE_VARIANTS) { + const image = readOciArchive(archives[variant]); + images[variant] = { descriptor: image.descriptor, layers: image.layers.map((layer) => layer.digest) }; + const reported = JSON.parse(await readFile(metadataFiles[variant], "utf8"))["containerimage.digest"]; + assert.match(reported ?? "", DIGEST, `The ${variant} build reported no image digest`); + assert.equal(images[variant].descriptor.digest, reported, `The ${variant} archive is not the image its build reported`); + } + // The same blobs in the same order: the full image is the slim image plus layers. + assert.deepEqual(images.full.layers.slice(0, images.slim.layers.length), images.slim.layers, + "The full image does not start with the layers of the slim image"); + assert.ok(images.full.layers.length > images.slim.layers.length, "The full image has no layer of its own"); + + const directory = await mkdtemp(path.join(tmpdir(), "runner-image-layout-")); + try { + for (const variant of RUNNER_IMAGE_VARIANTS) tar(["-xf", archives[variant], "-C", directory]); + await writeFile(path.join(directory, "index.json"), JSON.stringify({ + schemaVersion: 2, + mediaType: "application/vnd.oci.image.index.v1+json", + manifests: RUNNER_IMAGE_VARIANTS.map((variant) => ({ + ...images[variant].descriptor, + annotations: { "org.opencontainers.image.ref.name": variant }, + })), + })); + tar(["-cf", layout, "-C", directory, "blobs", "index.json", "oci-layout"]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + // Read the layout back the way the publish job's push does: each image by + // its name, with every blob it needs under its digest. + for (const variant of RUNNER_IMAGE_VARIANTS) { + const image = readOciArchive(layout, { ref: variant }); + assert.equal(image.descriptor.digest, images[variant].descriptor.digest, `The layout names another image as ${variant}`); + await image.verifyBlobs(); + } + return { + schema: RUNNER_IMAGE_RECORD_SCHEMA, + architecture, + images: { slim: images.slim.descriptor.digest, full: images.full.descriptor.digest }, + inputsDigest: manifest.inputsDigest.digest, + sourceRevision: manifest.sourceRevision, + layoutSha256: await sha256File(layout), + }; +} + +/** + * The image digest of each variant and architecture, as `_`, + * accepted only when every leg built this run's inputs at this run's commit + * and its layout is unchanged. + * @param {{ directory: string, inputsDigest: string, sourceRevision: string, layoutName?: string }} input + * @returns {Promise>} + */ +export async function verifyLegRecords({ directory, inputsDigest, sourceRevision, layoutName = "images.oci.tar" }) { + assert.match(inputsDigest ?? "", HEX_64); + assert.match(sourceRevision ?? "", REVISION); + /** @type {Record} */ + const digests = {}; + for (const architecture of ARCHITECTURES) { + const legDirectory = path.join(directory, architecture); + const record = JSON.parse(await readFile(path.join(legDirectory, "record.json"), "utf8")); + assert.equal(record.schema, RUNNER_IMAGE_RECORD_SCHEMA, `${architecture}: unknown record schema`); + assert.equal(record.architecture, architecture, `${architecture}: the record is for another architecture`); + assert.equal(record.inputsDigest, inputsDigest, `${architecture}: the image was built from other inputs`); + assert.equal(record.sourceRevision, sourceRevision, `${architecture}: the image was built at another commit`); + for (const variant of RUNNER_IMAGE_VARIANTS) { + assert.match(record.images?.[variant] ?? "", DIGEST, `${architecture}: the record has no ${variant} image digest`); + digests[`${variant}_${architecture}`] = record.images[variant]; + } + assert.notEqual(record.images.slim, record.images.full, `${architecture}: the record names one image for both variants`); + assert.equal(await sha256File(path.join(legDirectory, layoutName)), record.layoutSha256, + `${architecture}: the image layout does not match its record`); + } + return digests; +} + +function repositoryOf(image) { + const match = /^ghcr\.io\/([a-z0-9][a-z0-9._/-]*)$/.exec(image); + assert.ok(match, `Not a ghcr.io image name: ${image}`); + return match[1]; +} + +async function request(url, headers, fetchImpl, sleep) { + for (let attempt = 1; ; attempt += 1) { + let response; + try { + response = await fetchImpl(url, { headers, redirect: "error", signal: AbortSignal.timeout(30_000) }); + } catch (error) { + if (attempt === 5) throw error; + await sleep(attempt * 1000); + continue; + } + const transient = [408, 425, 429].includes(response.status) || response.status >= 500; + if (!transient || attempt === 5) return response; + await response.body?.cancel(); + await sleep(attempt * 1000); + } +} + +/** + * Reads a manifest. `state` is `present` with the registry bytes, `absent` + * when the registry says the manifest does not exist, and `unknown` for every + * other answer: a refused token, a package that is private to this caller, or + * a registry error that outlasted the retries. + * @param {string} reference + * @param {{ + * image?: string, + * credentials?: { username: string, password: string } | null, + * fetchImpl?: (url: string, init: { headers: Record, redirect: "error", signal: AbortSignal }) => Promise, + * sleep?: (ms: number) => Promise, + * }} [options] + * @returns {Promise<{ state: "present", bytes: Buffer, digest: string } | { state: "absent" } | { state: "unknown", detail: string }>} + */ +export async function readRunnerImageManifest(reference, { + image = RUNNER_IMAGE_NAME, + credentials = null, + fetchImpl = fetch, + sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), +} = {}) { + const repository = repositoryOf(image); + /** @type {Record} */ + const basic = credentials ? { authorization: `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString("base64")}` } : {}; + // A registry that cannot be reached, or that answers with something other + // than a token, leaves the question open. It is not an answer. + let token; + try { + const tokenResponse = await request(`https://ghcr.io/token?service=ghcr.io&scope=repository:${repository}:pull`, basic, fetchImpl, sleep); + if (!tokenResponse.ok) { + await tokenResponse.body?.cancel(); + return { state: "unknown", detail: `token request: HTTP ${tokenResponse.status}` }; + } + ({ token } = await tokenResponse.json()); + } catch (error) { + return { state: "unknown", detail: `token request failed: ${error instanceof Error ? error.message : String(error)}` }; + } + if (typeof token !== "string" || !token) return { state: "unknown", detail: "token request returned no token" }; + let response; + let bytes; + try { + response = await request(`https://ghcr.io/v2/${repository}/manifests/${reference}`, + { authorization: `Bearer ${token}`, accept: MANIFEST_TYPES }, fetchImpl, sleep); + if (response.status === 404) { + await response.body?.cancel(); + return { state: "absent" }; + } + if (!response.ok) { + await response.body?.cancel(); + return { state: "unknown", detail: `manifest request: HTTP ${response.status}` }; + } + bytes = Buffer.from(await response.arrayBuffer()); + } catch (error) { + return { state: "unknown", detail: `manifest request failed: ${error instanceof Error ? error.message : String(error)}` }; + } + assert.ok(bytes.length <= 1024 * 1024, "Registry manifest exceeds its size limit"); + const digest = `sha256:${createHash("sha256").update(bytes).digest("hex")}`; + const reported = response.headers.get("docker-content-digest"); + assert.ok(!reported || reported === digest, "Registry digest does not match the manifest bytes"); + return { state: "present", bytes, digest }; +} + +/** + * The digest of the pushed index, accepted only when it names exactly the + * recorded images. `slimDigest` is given for the full index, which must name + * the slim index published with it, and for no other. + * @param {Buffer} bytes + * @param {Record} legDigests one image digest for each architecture + * @param {{ slimDigest?: string | null }} [options] + */ +export function verifyPublishedIndex(bytes, legDigests, { slimDigest = null } = {}) { + assert.deepEqual(Object.keys(legDigests).sort(), [...ARCHITECTURES].sort(), "Expected one recorded image for each architecture"); + const digest = standardImageDigest(bytes); + assertIndexUsesVerifiedImages(bytes, new Set(Object.values(legDigests))); + const index = JSON.parse(bytes.toString("utf8")); + // Exactly the two images, and nothing beside them: no attestation manifest, + // no entry without a platform, no other operating system. + assert.equal(index.manifests.length, ARCHITECTURES.length, `Expected exactly ${ARCHITECTURES.length} manifests in the index, found ${index.manifests.length}`); + for (const entry of index.manifests) { + const architecture = entry.platform?.architecture; + // BuildKit records linux/arm64 with or without the variant `v8`; both are + // the one arm64 platform. No other variant is one of the two platforms. + const variant = entry.platform?.variant; + assert.ok(entry.platform?.os === "linux" && ARCHITECTURES.includes(architecture) + && (variant === undefined || (architecture === "arm64" && variant === "v8")), + `The index names an unexpected platform: ${JSON.stringify(entry.platform ?? null)}`); + assert.equal(entry.digest, legDigests[architecture], `linux/${architecture} is not the image its build leg recorded`); + } + assert.equal(index.annotations?.[SLIM_DIGEST_ANNOTATION] ?? null, slimDigest, + slimDigest === null ? "Only the full index may name a slim index" : "The full index does not name the slim index published with it"); + return digest; +} + +/** + * Whether the images of these inputs are published. The publish job writes + * the slim tag, then the full tag, so the full tag is the completion marker: + * + * - `absent`: neither tag exists; + * - `incomplete`: only the slim tag exists. A publication stopped between the + * two tags. Nothing may use that slim image; the next publication replaces + * the tag with its own slim image before it writes the full tag; + * - `published`: the full tag exists and names, by digest, the image the slim + * tag points at; + * - `broken`: the full tag exists, but the slim tag is missing or points at + * another image. No run can repair that: the full tag is never moved; + * - `unknown`: the registry gave no clear answer. + * @param {string} inputsDigest + * @param {(reference: string) => ReturnType} read + * @returns {Promise<{ state: "absent" | "incomplete" | "published" | "broken" | "unknown", detail: string, full?: string, slim?: string }>} + */ +export async function runnerPublicationState(inputsDigest, read) { + assert.match(inputsDigest ?? "", HEX_64); + const tags = runnerImageTags(inputsDigest); + const full = await read(tags.full); + if (full.state === "unknown") return { state: "unknown", detail: `${tags.full}: ${full.detail}` }; + const slim = await read(tags.slim); + if (slim.state === "unknown") return { state: "unknown", detail: `${tags.slim}: ${slim.detail}` }; + if (full.state === "absent") { + return slim.state === "absent" + ? { state: "absent", detail: `${tags.full} does not exist` } + : { state: "incomplete", detail: `${tags.slim} exists without ${tags.full}: an earlier publication did not finish`, slim: slim.digest }; + } + let named = null; + try { + named = JSON.parse(full.bytes.toString("utf8")).annotations?.[SLIM_DIGEST_ANNOTATION] ?? null; + } catch { + // Not JSON: it names no slim image. + } + if (slim.state === "present" && slim.digest === named) { + return { state: "published", detail: `${tags.full} and ${tags.slim} exist`, full: full.digest, slim: slim.digest }; + } + return { + state: "broken", + detail: `${tags.full} exists and names the slim image ${named ?? "(none)"}, but ${tags.slim} ${slim.state === "present" ? `is ${slim.digest}` : "does not exist"}`, + full: full.digest, + }; +} + +/** pnpm reports a lockfile that the manifests have moved past with one of these codes. */ +const LOCK_BEHIND_CODES = ["ERR_PNPM_OUTDATED_LOCKFILE", "ERR_PNPM_LOCKFILE_CONFIG_MISMATCH"]; + +/** + * Whether pnpm-lock.yaml in an exported `runner-artifacts-context` tree + * matches the manifests in that tree. This is the image build's frozen, + * filtered install with --lockfile-only and --offline: it downloads nothing + * and installs nothing. pnpm can still write `pnpm-lock.yaml` in that tree + * again, so `context` must be a copy no build reads: the workflow gives it an + * export of the build context, and a checkout is refused. `behind` means the + * manifests the Runner build reads were changed after the lockfile was. Every + * other failure throws. + * @param {string} context + * @param {{ run?: (command: string, args: string[], options: object) => { status: number | null, stdout: string, stderr: string, error?: Error } }} [options] + * @returns {{ state: "current" | "behind", detail: string }} + */ +export function runnerLockState(context, { run = (command, args, options) => spawnSync(command, args, options) } = {}) { + assert.ok(existsSync(path.join(context, "pnpm-lock.yaml")), `${context} has no pnpm-lock.yaml`); + assert.ok(existsSync(path.join(context, "packages", "paperclip-runner", "package.json")), `${context} is not a Runner build context`); + assert.ok(!existsSync(path.join(context, ".git")), `${context} is a checkout: pnpm can rewrite its pnpm-lock.yaml. Check an exported build context`); + const result = run("pnpm", ["install", "--frozen-lockfile", "--lockfile-only", "--offline", "--ignore-scripts", + "--filter", "@paperclipai/paperclip-runner..."], { cwd: context, encoding: "utf8" }); + if (result.error) throw result.error; + const output = `${result.stdout ?? ""}${result.stderr ?? ""}`; + if (result.status === 0) return { state: "current", detail: "pnpm-lock.yaml matches the Runner's manifests" }; + const code = LOCK_BEHIND_CODES.find((candidate) => output.includes(candidate)); + if (code) { + const line = output.split("\n").find((candidate) => candidate.includes(code)) ?? code; + return { state: "behind", detail: line.trim().slice(0, 500) }; + } + throw new Error(`The lockfile check failed for another reason (exit ${result.status}):\n${output.trim().slice(-2000)}`); +} + +const COMMAND_FLAGS = Object.freeze({ + "lock-state": { context: "value" }, + record: { + arch: "value", "slim-archive": "value", "slim-metadata": "value", "full-archive": "value", "full-metadata": "value", + tree: "value", layout: "value", out: "value", + }, + "verify-legs": { dir: "value", "inputs-digest": "value", "source-revision": "value" }, + "publication-state": { "inputs-digest": "value", strict: "boolean" }, + "verify-index": { dir: "value", variant: "value", expect: "value", "slim-digest": "value" }, +}); +const REQUIRED_FLAGS = Object.freeze({ + "lock-state": ["context"], + record: ["arch", "slim-archive", "slim-metadata", "full-archive", "full-metadata", "tree", "layout", "out"], + "verify-legs": ["dir", "inputs-digest", "source-revision"], + "publication-state": ["inputs-digest"], + "verify-index": ["dir", "variant"], +}); + +/** + * Splits a command line into positional arguments and the flags the command + * knows. Throws on an unknown command, an unknown or repeated flag, a missing + * or empty value, and a missing required flag. + * @param {string | undefined} command + * @param {string[]} argv + */ +export function parsePublishArguments(command, argv) { + if (!command || !Object.hasOwn(COMMAND_FLAGS, command)) { + throw new Error("Usage: runner-image-publish.mjs lock-state|record|verify-legs|publication-state|verify-index ..."); + } + const known = COMMAND_FLAGS[command]; + /** @type {string[]} */ + const positional = []; + /** @type {Record} */ + const flags = {}; + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (!argument.startsWith("--")) { + positional.push(argument); + continue; + } + const name = argument.slice(2); + if (!Object.hasOwn(known, name)) throw new Error(`${command} does not take ${argument}`); + if (Object.hasOwn(flags, name)) throw new Error(`${argument} is given twice`); + if (known[name] === "boolean") { + flags[name] = true; + continue; + } + const value = argv[index += 1]; + if (value === undefined || value === "" || value.startsWith("--")) throw new Error(`${argument} needs a value`); + flags[name] = value; + } + for (const name of REQUIRED_FLAGS[command]) { + if (!Object.hasOwn(flags, name)) throw new Error(`${command} needs --${name}`); + } + const takesReference = command === "verify-index"; + if (positional.length !== (takesReference ? 1 : 0)) { + throw new Error(takesReference ? `${command} takes exactly one tag or digest` : `${command} takes no positional argument`); + } + if (takesReference && !/^(?:[A-Za-z0-9_][A-Za-z0-9._-]{0,127}|sha256:[0-9a-f]{64})$/.test(positional[0])) { + throw new Error(`${command}: not a tag or digest: ${positional[0]}`); + } + return { positional, flags }; +} + +/** + * Runs one command. Returns the values it reports; throws when the command's + * check does not hold. + * @param {string[]} argv + * @param {{ env?: NodeJS.ProcessEnv, read?: typeof readRunnerImageManifest, lockState?: typeof runnerLockState, log?: (line: string) => void }} [options] + * @returns {Promise>} + */ +export async function runPublishCommand(argv, { + env = process.env, + read = readRunnerImageManifest, + lockState = runnerLockState, + log = console.log, +} = {}) { + const [command, ...rest] = argv; + const { positional, flags } = parsePublishArguments(command, rest); + const value = (name) => /** @type {string} */ (flags[name]); + if (command === "lock-state") { + const result = lockState(path.resolve(value("context"))); + log(result.detail); + return { state: result.state }; + } + if (command === "record") { + const record = await createLegRecord({ + architecture: value("arch"), + archives: { slim: value("slim-archive"), full: value("full-archive") }, + metadataFiles: { slim: value("slim-metadata"), full: value("full-metadata") }, + tree: value("tree"), + layout: value("layout"), + }); + await writeFile(value("out"), `${JSON.stringify(record, null, 2)}\n`); + return { slim: record.images.slim, full: record.images.full }; + } + if (command === "verify-legs") { + return verifyLegRecords({ + directory: value("dir"), inputsDigest: value("inputs-digest"), sourceRevision: value("source-revision"), + }); + } + const credentials = environmentCredentials(env); + if (command === "publication-state") { + const tags = runnerImageTags(value("inputs-digest")); + const result = await runnerPublicationState(value("inputs-digest"), (reference) => read(reference, { credentials })); + // Only an operator can repair this, so it fails every run that meets it. + assert.notEqual(result.state, "broken", `${result.detail}. No run can repair this: the workflow never moves ${tags.full}. ` + + `Delete the package versions tagged ${tags.full} and ${tags.slim}, then re-run the workflow run of a master push with these inputs.`); + if (result.state === "unknown") { + const message = `Could not determine whether ${RUNNER_IMAGE_NAME}:${tags.full} is published (${result.detail}).`; + // A create-only tag is never written on a guess. + assert.ok(flags.strict !== true, message); + log(`::notice title=Runner image lookup inconclusive::${message}`); + } + if (result.state === "incomplete") log(`::notice title=Runner image publication incomplete::${result.detail}.`); + return { + state: result.state, + exists: result.state === "published", + // What a publish job may do next: write the tags, slim first. + publish: result.state === "absent" || result.state === "incomplete", + }; + } + const reference = positional[0]; + const variant = value("variant"); + assert.ok(RUNNER_IMAGE_VARIANTS.includes(variant), "--variant must be slim or full"); + if (Object.hasOwn(flags, "slim-digest")) assert.match(value("slim-digest"), DIGEST, "--slim-digest must be a sha256 digest"); + assert.equal(Object.hasOwn(flags, "slim-digest"), variant === "full", "--slim-digest is given for the full index, and only for it"); + const result = await read(reference, { credentials }); + assert.equal(result.state, "present", `${RUNNER_IMAGE_NAME}:${reference} is ${result.state}`); + assert.ok(result.state === "present"); + const digest = verifyPublishedIndex(result.bytes, await legDigests(value("dir"), variant), + { slimDigest: variant === "full" ? value("slim-digest") : null }); + if (Object.hasOwn(flags, "expect")) { + assert.match(value("expect"), DIGEST, "--expect must be a sha256 digest"); + assert.equal(digest, value("expect"), `${reference} resolves to ${digest}, expected ${value("expect")}`); + } + return { digest }; +} + +async function output(values) { + const lines = Object.entries(values).map(([key, value]) => `${key}=${value}`); + for (const line of lines) console.log(line); + if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `${lines.join("\n")}\n`); +} + +function environmentCredentials(env = process.env) { + const username = env.RUNNER_IMAGE_REGISTRY_USERNAME; + const password = env.RUNNER_IMAGE_REGISTRY_PASSWORD; + return username && password ? { username, password } : null; +} + +async function legDigests(directory, variant) { + /** @type {Record} */ + const digests = {}; + for (const architecture of ARCHITECTURES) { + digests[architecture] = JSON.parse(await readFile(path.join(directory, architecture, "record.json"), "utf8")).images?.[variant]; + } + return digests; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + try { + await output(await runPublishCommand(process.argv.slice(2))); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); + } +} diff --git a/server/src/__tests__/runner-image-publish.test.ts b/server/src/__tests__/runner-image-publish.test.ts new file mode 100644 index 00000000000..f7eb9a74e67 --- /dev/null +++ b/server/src/__tests__/runner-image-publish.test.ts @@ -0,0 +1,548 @@ +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { + SLIM_DIGEST_ANNOTATION, + createLegRecord, + parsePublishArguments, + readRunnerImageManifest, + runPublishCommand, + runnerImageTags, + runnerLockState, + runnerPublicationState, + verifyLegRecords, + verifyPublishedIndex, +} from "../../../scripts/runner-image-publish.mjs"; +import { readOciArchive } from "../../../scripts/runner-image-oci.mjs"; + +/** + * The checks the Runner image workflow runs around publication. The image has + * two variants under two tags, and consumers verify their attestations. So + * the bytes published must be the ones the build legs checked, a tag must + * never be written on a guess, and a publication that stopped half way must + * neither block its inputs nor leave a full image paired with another run's + * slim image. + */ + +const INPUTS = "1".repeat(64); +const REVISION = "a".repeat(40); +const TAGS = runnerImageTags(INPUTS); +const sha256 = (bytes: Buffer | string) => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; +const scratch = mkdtempSync(path.join(tmpdir(), "runner-image-publish-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); +let sequence = 0; + +/** What `docker buildx build --output type=oci --metadata-file` writes for one image with these layers. */ +function ociArchive(directory: string, name: string, layers: string[]) { + const layout = path.join(directory, `${name}-layout`); + mkdirSync(path.join(layout, "blobs", "sha256"), { recursive: true }); + const blob = (bytes: string) => { + writeFileSync(path.join(layout, "blobs", "sha256", sha256(bytes).slice(7)), bytes); + return { digest: sha256(bytes), size: bytes.length }; + }; + const manifest = blob(JSON.stringify({ + schemaVersion: 2, config: blob(`config of ${name}`), + layers: layers.map((layer) => ({ mediaType: "application/vnd.oci.image.layer.v1.tar+gzip", ...blob(layer) })), + })); + writeFileSync(path.join(layout, "index.json"), JSON.stringify({ + schemaVersion: 2, manifests: [{ mediaType: "application/vnd.oci.image.manifest.v1+json", ...manifest }], + })); + writeFileSync(path.join(layout, "oci-layout"), '{"imageLayoutVersion":"1.0.0"}'); + const archive = path.join(directory, `${name}.oci.tar`); + // The members buildx writes. `tar -C layout .` would name them ./index.json and ./blobs/... + expect(spawnSync("tar", ["-cf", archive, "-C", layout, "blobs", "index.json", "oci-layout"]).status).toBe(0); + writeFileSync(path.join(directory, `${name}.metadata.json`), JSON.stringify({ "containerimage.digest": manifest.digest })); + return manifest.digest; +} + +/** What one build leg uploads: one layout with both variants, and the record of what it verified. */ +async function leg(directory: string, architecture: string, options: { + inputsDigest?: string; sourceRevision?: string; publication?: boolean; slim?: string[]; full?: string[]; +} = {}) { + const { inputsDigest = INPUTS, sourceRevision = REVISION, publication = true } = options; + const slim = options.slim ?? [`large ${architecture}`, `rest ${architecture}`]; + const full = options.full ?? [...slim, `archives ${architecture}`, `overlay ${architecture}`]; + const root = path.join(directory, architecture); + mkdirSync(path.join(root, "tree"), { recursive: true }); + const images = { slim: ociArchive(root, "slim", slim), full: ociArchive(root, "full", full) }; + writeFileSync(path.join(root, "tree", "runner-image.json"), JSON.stringify({ + inputsDigest: { digest: inputsDigest }, sourceRevision, publication, platform: { os: "linux", architecture }, + })); + const record = await createLegRecord({ + architecture, + archives: { slim: path.join(root, "slim.oci.tar"), full: path.join(root, "full.oci.tar") }, + metadataFiles: { slim: path.join(root, "slim.metadata.json"), full: path.join(root, "full.metadata.json") }, + tree: path.join(root, "tree"), + layout: path.join(root, "images.oci.tar"), + }); + writeFileSync(path.join(root, "record.json"), JSON.stringify(record)); + return { record, images }; +} + +async function legs(options: Record = {}) { + const directory = path.join(scratch, String(sequence += 1)); + const images: Record = {}; + for (const architecture of ["amd64", "arm64"]) ({ images: images[architecture] } = await leg(directory, architecture, options[architecture])); + return { directory, images }; +} + +describe("verified build legs", () => { + it("accepts both variants of each architecture for this run's inputs and commit", async () => { + const { directory, images } = await legs(); + await expect(verifyLegRecords({ directory, inputsDigest: INPUTS, sourceRevision: REVISION })).resolves.toEqual({ + slim_amd64: images.amd64.slim, full_amd64: images.amd64.full, slim_arm64: images.arm64.slim, full_arm64: images.arm64.full, + }); + }); + + it("hands over one layout that names both variants and stores their shared layers once", async () => { + const { directory, images } = await legs(); + const layout = path.join(directory, "amd64", "images.oci.tar"); + const read = (member: string) => spawnSync("tar", ["-xOf", layout, member], { encoding: "utf8" }).stdout; + expect(JSON.parse(read("index.json")).manifests.map((entry: { digest: string; annotations: Record }) => + [entry.annotations["org.opencontainers.image.ref.name"], entry.digest])).toEqual([["slim", images.amd64.slim], ["full", images.amd64.full]]); + const blobs = spawnSync("tar", ["-tf", layout], { encoding: "utf8" }).stdout.split("\n").filter((name) => /^blobs\/sha256\/[0-9a-f]{64}$/.test(name)); + // Two manifests, two configs, and four layers: the two shared ones are not stored twice. + expect(blobs).toHaveLength(8); + expect(new Set(blobs).size).toBe(8); + expect(JSON.parse(read(`blobs/sha256/${images.amd64.full.slice(7)}`)).layers.slice(0, 2)) + .toEqual(JSON.parse(read(`blobs/sha256/${images.amd64.slim.slice(7)}`)).layers); + // Each image can be read alone by its name, with every blob under its digest: what a push does. + for (const variant of ["slim", "full"] as const) { + const image = readOciArchive(layout, { ref: variant }); + expect(image.descriptor.digest).toBe(images.amd64[variant]); + await expect(image.verifyBlobs()).resolves.toBeUndefined(); + } + expect(() => readOciArchive(layout)).toThrow(/must hold exactly one image manifest/); + expect(() => readOciArchive(layout, { ref: "candidate" })).toThrow(/must hold exactly one image named candidate/); + }); + + it("does not record an archive that lacks a blob of its image, or whose members have other names", async () => { + const directory = path.join(scratch, String(sequence += 1)); + await leg(directory, "amd64"); + const root = path.join(directory, "amd64"); + const input = { + architecture: "amd64", + archives: { slim: path.join(root, "slim.oci.tar"), full: path.join(root, "full.oci.tar") }, + metadataFiles: { slim: path.join(root, "slim.metadata.json"), full: path.join(root, "full.metadata.json") }, + tree: path.join(root, "tree"), + layout: path.join(root, "again.oci.tar"), + }; + // The full archive without one of its layers. + const layer = readOciArchive(input.archives.full).layers[3].digest; + rmSync(path.join(root, "full-layout", "blobs", "sha256", layer.slice(7))); + expect(spawnSync("tar", ["-cf", input.archives.full, "-C", path.join(root, "full-layout"), "blobs", "index.json", "oci-layout"]).status).toBe(0); + await expect(createLegRecord(input)).rejects.toThrow(/has no member blobs\/sha256\//); + // An archive of `.`: the names a registry tool does not find. + expect(spawnSync("tar", ["-cf", input.archives.slim, "-C", path.join(root, "slim-layout"), "."]).status).toBe(0); + await expect(createLegRecord(input)).rejects.toThrow(/has no member index\.json/); + }); + + it("refuses a leg that built other inputs or another commit", async () => { + const otherInputs = await legs({ arm64: { inputsDigest: "2".repeat(64) } }); + await expect(verifyLegRecords({ directory: otherInputs.directory, inputsDigest: INPUTS, sourceRevision: REVISION })) + .rejects.toThrow(/arm64: the image was built from other inputs/); + const otherCommit = await legs({ amd64: { sourceRevision: "b".repeat(40) } }); + await expect(verifyLegRecords({ directory: otherCommit.directory, inputsDigest: INPUTS, sourceRevision: REVISION })) + .rejects.toThrow(/amd64: the image was built at another commit/); + }); + + it("refuses a layout that changed after its leg recorded it, a record without a variant, and a missing leg", async () => { + const { directory } = await legs(); + appendFileSync(path.join(directory, "amd64", "images.oci.tar"), "tampered"); + await expect(verifyLegRecords({ directory, inputsDigest: INPUTS, sourceRevision: REVISION })) + .rejects.toThrow(/amd64: the image layout does not match its record/); + const oneVariant = await legs(); + const recordPath = path.join(oneVariant.directory, "arm64", "record.json"); + const record = JSON.parse(readFileSync(recordPath, "utf8")); + writeFileSync(recordPath, JSON.stringify({ ...record, images: { full: record.images.full } })); + await expect(verifyLegRecords({ directory: oneVariant.directory, inputsDigest: INPUTS, sourceRevision: REVISION })) + .rejects.toThrow(/arm64: the record has no slim image digest/); + const missing = await legs(); + rmSync(path.join(missing.directory, "arm64"), { recursive: true }); + await expect(verifyLegRecords({ directory: missing.directory, inputsDigest: INPUTS, sourceRevision: REVISION })).rejects.toThrow(); + }); + + it.each<[string, object, RegExp]>([ + ["a full image that does not start with the slim image's layers", { full: ["another large", "rest amd64", "archives", "overlay"] }, /does not start with the layers of the slim image/], + ["a full image with the slim layers in another order", { full: ["rest amd64", "large amd64", "archives", "overlay"] }, /does not start with the layers of the slim image/], + ["a full image that is the slim image", { full: ["large amd64", "rest amd64"] }, /has no layer of its own/], + ["a build that is not a publication build", { publication: false }, /Only a publication build can be recorded/], + ])("does not record %s", async (_label, options, expected) => { + await expect(leg(path.join(scratch, String(sequence += 1)), "amd64", options)).rejects.toThrow(expected); + }); + + it("does not record a tree that is for another architecture, or an archive that is not the image the build reported", async () => { + const directory = path.join(scratch, String(sequence += 1)); + await leg(directory, "amd64"); + const root = path.join(directory, "amd64"); + const input = { + architecture: "amd64", + archives: { slim: path.join(root, "slim.oci.tar"), full: path.join(root, "full.oci.tar") }, + metadataFiles: { slim: path.join(root, "slim.metadata.json"), full: path.join(root, "full.metadata.json") }, + tree: path.join(root, "tree"), + layout: path.join(root, "again.oci.tar"), + }; + await expect(createLegRecord({ ...input, architecture: "arm64" })).rejects.toThrow(/another architecture/); + await expect(createLegRecord({ ...input, archives: { slim: input.archives.full, full: input.archives.full } })) + .rejects.toThrow(/The slim archive is not the image its build reported/); + }); +}); + +describe("registry lookups", () => { + const index = Buffer.from(JSON.stringify({ schemaVersion: 2, mediaType: "application/vnd.oci.image.index.v1+json", manifests: [] })); + const respond = (status: number, body: Buffer | string = "", headers: Record = {}) => + new Response(typeof body === "string" ? body : new Uint8Array(body), { status, headers }); + function registry(manifest: () => Response, token: () => Response = () => respond(200, JSON.stringify({ token: "t" }))) { + const requests: { url: string; headers: Record }[] = []; + const fetchImpl = async (url: string, init: { headers: Record }) => { + requests.push({ url, headers: init.headers }); + return url.includes("/token?") ? token() : manifest(); + }; + return { requests, options: { fetchImpl, sleep: async () => {} } }; + } + + it("reports a tag that exists, with the digest of the registry bytes", async () => { + const { requests, options } = registry(() => respond(200, index, { "docker-content-digest": sha256(index) })); + const result = await readRunnerImageManifest(`inputs-${INPUTS}`, options); + expect(result).toMatchObject({ state: "present", digest: sha256(index) }); + expect(requests.map((request) => request.url)).toEqual([ + "https://ghcr.io/token?service=ghcr.io&scope=repository:paperclipai/paperclip-runner:pull", + `https://ghcr.io/v2/paperclipai/paperclip-runner/manifests/inputs-${INPUTS}`, + ]); + expect(requests[0].headers.authorization).toBeUndefined(); + expect(requests[1].headers.authorization).toBe("Bearer t"); + }); + + it("reports a missing tag only when the registry says it is missing", async () => { + await expect(readRunnerImageManifest("inputs-x", registry(() => respond(404)).options)).resolves.toEqual({ state: "absent" }); + }); + + it.each<[string, () => Response, (() => Response) | undefined]>([ + ["the token request is refused", () => respond(200, index), () => respond(403)], + ["the token response has no token", () => respond(200, index), () => respond(200, "{}")], + ["the manifest request is unauthorized", () => respond(401), undefined], + ["the manifest request is denied", () => respond(403), undefined], + ["the registry keeps failing", () => respond(503), undefined], + ])("does not guess when %s", async (_label, manifest, token) => { + const result = await readRunnerImageManifest("inputs-x", registry(manifest, token).options); + expect(result.state).toBe("unknown"); + }); + + it("retries a transient registry error", async () => { + let calls = 0; + const { options } = registry(() => ((calls += 1) < 3 ? respond(502) : respond(404))); + await expect(readRunnerImageManifest("inputs-x", options)).resolves.toEqual({ state: "absent" }); + expect(calls).toBe(3); + }); + + it.each<[string, () => Promise]>([ + ["the registry cannot be reached", async () => { throw new TypeError("fetch failed"); }], + ["the token response is not JSON", async () => respond(200, "gateway")], + ])("does not guess, and does not crash, when %s", async (_label, token) => { + let calls = 0; + const fetchImpl = async () => { calls += 1; return token(); }; + const result = await readRunnerImageManifest("inputs-x", { fetchImpl, sleep: async () => {} }); + expect(result.state).toBe("unknown"); + expect(calls).toBeGreaterThanOrEqual(1); + }); + + it("does not guess when the manifest request cannot be completed", async () => { + let manifests = 0; + const fetchImpl = async (url: string) => { + if (url.includes("/token?")) return respond(200, JSON.stringify({ token: "t" })); + manifests += 1; + throw new TypeError("fetch failed"); + }; + await expect(readRunnerImageManifest("inputs-x", { fetchImpl, sleep: async () => {} })).resolves.toMatchObject({ state: "unknown" }); + expect(manifests).toBe(5); + }); + + it("authenticates with the credentials it is given and rejects bytes that do not match their digest", async () => { + const { requests, options } = registry(() => respond(200, index, { "docker-content-digest": sha256("other") })); + await expect(readRunnerImageManifest("inputs-x", { ...options, credentials: { username: "u", password: "p" } })) + .rejects.toThrow(/does not match the manifest bytes/); + expect(requests[0].headers.authorization).toBe(`Basic ${Buffer.from("u:p").toString("base64")}`); + }); +}); + +describe("published index", () => { + const legDigests = { amd64: sha256("manifest amd64"), arm64: sha256("manifest arm64") }; + const entry = (architecture: string, digest: string) => ({ + mediaType: "application/vnd.oci.image.manifest.v1+json", digest, size: 500, platform: { os: "linux", architecture }, + }); + const bytes = (manifests: object[]) => Buffer.from(JSON.stringify({ + schemaVersion: 2, mediaType: "application/vnd.oci.image.index.v1+json", manifests, + })); + + it("accepts an index of exactly the two verified images and returns its digest", () => { + const index = bytes([entry("amd64", legDigests.amd64), entry("arm64", legDigests.arm64)]); + expect(verifyPublishedIndex(index, legDigests)).toBe(sha256(index)); + }); + + it("requires the full index, and no other, to name its slim index", () => { + const slimDigest = sha256("slim index"); + const manifests = [entry("amd64", legDigests.amd64), entry("arm64", legDigests.arm64)]; + const full = Buffer.from(JSON.stringify({ + schemaVersion: 2, mediaType: "application/vnd.oci.image.index.v1+json", manifests, annotations: { [SLIM_DIGEST_ANNOTATION]: slimDigest }, + })); + expect(verifyPublishedIndex(full, legDigests, { slimDigest })).toBe(sha256(full)); + expect(() => verifyPublishedIndex(full, legDigests, { slimDigest: sha256("an earlier run's slim index") })) + .toThrow(/The full index does not name the slim index published with it/); + expect(() => verifyPublishedIndex(bytes(manifests), legDigests, { slimDigest })).toThrow(/does not name the slim index/); + expect(() => verifyPublishedIndex(full, legDigests)).toThrow(/Only the full index may name a slim index/); + }); + + const both = [entry("amd64", legDigests.amd64), entry("arm64", legDigests.arm64)]; + const extra = (platform: object | undefined) => ({ + mediaType: "application/vnd.oci.image.manifest.v1+json", digest: sha256("extra"), size: 500, ...(platform ? { platform } : {}), + }); + + it.each<[string, object[]]>([ + ["an image no leg verified", [entry("amd64", legDigests.amd64), entry("arm64", sha256("unverified"))]], + ["the images under the wrong architectures", [entry("amd64", legDigests.arm64), entry("arm64", legDigests.amd64)]], + ["one architecture only", [entry("amd64", legDigests.amd64)]], + ["one architecture twice", [entry("amd64", legDigests.amd64), entry("amd64", legDigests.amd64), entry("arm64", legDigests.arm64)]], + ["an attestation manifest beside the images", [...both, extra({ os: "unknown", architecture: "unknown" })]], + ["an entry without a platform", [...both, extra(undefined)]], + ["an image for another operating system", [...both, extra({ os: "windows", architecture: "amd64" })]], + ["an image for another architecture", [...both, extra({ os: "linux", architecture: "riscv64" })]], + ["a variant on the amd64 image", [{ ...entry("amd64", legDigests.amd64), platform: { os: "linux", architecture: "amd64", variant: "v8" } }, + entry("arm64", legDigests.arm64)]], + ["another arm64 variant", [entry("amd64", legDigests.amd64), + { ...entry("arm64", legDigests.arm64), platform: { os: "linux", architecture: "arm64", variant: "v7" } }]], + ])("refuses an index with %s", (_label, manifests) => { + expect(() => verifyPublishedIndex(bytes(manifests), legDigests)).toThrow(); + }); + + it("accepts linux/arm64 with the variant v8, which some BuildKit versions record", () => { + const index = bytes([entry("amd64", legDigests.amd64), + { ...entry("arm64", legDigests.arm64), platform: { os: "linux", architecture: "arm64", variant: "v8" } }]); + expect(verifyPublishedIndex(index, legDigests)).toBe(sha256(index)); + }); + + it("needs a recorded image for each architecture, and no other", () => { + expect(() => verifyPublishedIndex(bytes(both), { amd64: legDigests.amd64 })).toThrow(/one recorded image for each architecture/); + expect(() => verifyPublishedIndex(bytes(both), { ...legDigests, riscv64: sha256("extra") })).toThrow(/one recorded image for each architecture/); + }); +}); + +describe("lockfile state", () => { + function context() { + const directory = path.join(scratch, String(sequence += 1)); + mkdirSync(path.join(directory, "packages", "paperclip-runner"), { recursive: true }); + writeFileSync(path.join(directory, "pnpm-lock.yaml"), "lockfileVersion: '9.0'\n"); + writeFileSync(path.join(directory, "packages", "paperclip-runner", "package.json"), "{}\n"); + return directory; + } + const answer = (status: number | null, stderr = "", extra: object = {}) => { + const calls: { command: string; args: string[]; options: { cwd?: string } }[] = []; + const run = (command: string, args: string[], options: object) => { + calls.push({ command, args, options }); + return { status, stdout: "", stderr, ...extra }; + }; + return { calls, run }; + }; + + it("asks pnpm the image build's own question, offline and without installing", () => { + const directory = context(); + const { calls, run } = answer(0); + expect(runnerLockState(directory, { run }).state).toBe("current"); + expect(calls).toHaveLength(1); + expect(calls[0].command).toBe("pnpm"); + expect(calls[0].options.cwd).toBe(directory); + expect(calls[0].args).toEqual(["install", "--frozen-lockfile", "--lockfile-only", "--offline", "--ignore-scripts", + "--filter", "@paperclipai/paperclip-runner..."]); + }); + + it.each([ + [" ERR_PNPM_OUTDATED_LOCKFILE Cannot install with \"frozen-lockfile\" because pnpm-lock.yaml is not up to date with /packages/paperclip-runner/package.json"], + [" ERR_PNPM_LOCKFILE_CONFIG_MISMATCH Cannot proceed with the frozen installation. The current \"patchedDependencies\" configuration doesn't match the value found in the lockfile"], + ])("reports a lockfile the manifests have moved past as behind: %s", (stderr) => { + const result = runnerLockState(context(), { run: answer(1, stderr).run }); + expect(result.state).toBe("behind"); + expect(result.detail).toContain("ERR_PNPM_"); + }); + + it.each<[string, number | null, string, object]>([ + ["a broken lockfile", 1, " ERR_PNPM_BROKEN_LOCKFILE The lockfile is broken", {}], + ["a failure pnpm does not name", 1, "Killed", {}], + ["a pnpm that was killed", null, "", {}], + ["a pnpm that cannot be started", null, "", { error: new Error("spawn pnpm ENOENT") }], + ])("fails for %s instead of calling it behind", (_label, status, stderr, extra) => { + expect(() => runnerLockState(context(), { run: answer(status, stderr, extra).run })).toThrow(); + }); + + it("fails for a directory that is not a Runner build context", () => { + const directory = context(); + rmSync(path.join(directory, "pnpm-lock.yaml")); + expect(() => runnerLockState(directory, { run: answer(0).run })).toThrow(/no pnpm-lock\.yaml/); + }); + + it("refuses a checkout, whose lockfile pnpm could rewrite, and does not start pnpm there", () => { + const directory = context(); + mkdirSync(path.join(directory, ".git")); + const { calls, run } = answer(0); + expect(() => runnerLockState(directory, { run })).toThrow(/is a checkout: pnpm can rewrite its pnpm-lock\.yaml/); + expect(calls).toEqual([]); + }); +}); + +describe("publication state", () => { + type Manifest = Awaited>; + const index = (label: string, slimDigest?: string) => { + const bytes = Buffer.from(JSON.stringify({ schemaVersion: 2, label, ...(slimDigest ? { annotations: { [SLIM_DIGEST_ANNOTATION]: slimDigest } } : {}) })); + return { state: "present" as const, bytes, digest: sha256(bytes) }; + }; + const registry = (tags: Record) => async (reference: string): Promise => tags[reference] ?? { state: "absent" }; + const slim = index("slim of this run"); + const full = index("full of this run", slim.digest); + const unknown = { state: "unknown" as const, detail: "manifest request: HTTP 503" }; + + it("is published only when the full tag exists and names the image the slim tag points at", async () => { + await expect(runnerPublicationState(INPUTS, registry({ [TAGS.slim]: slim, [TAGS.full]: full }))) + .resolves.toMatchObject({ state: "published", slim: slim.digest, full: full.digest }); + await expect(runnerPublicationState(INPUTS, registry({}))).resolves.toMatchObject({ state: "absent" }); + }); + + it("treats a slim tag without the full tag as a publication that did not finish", async () => { + // A run stopped between the two tags. The inputs are not published, so + // the next run builds, and its publish job replaces the slim tag. + const orphan = index("slim of the run that stopped"); + await expect(runnerPublicationState(INPUTS, registry({ [TAGS.slim]: orphan }))) + .resolves.toMatchObject({ state: "incomplete", slim: orphan.digest }); + await expect(runPublishCommand(["publication-state", "--inputs-digest", INPUTS, "--strict"], { env: {}, read: registry({ [TAGS.slim]: orphan }), log: () => {} })) + .resolves.toEqual({ state: "incomplete", exists: false, publish: true }); + }); + + it.each<[string, Record]>([ + ["the slim tag is missing", { [TAGS.full]: full }], + ["the slim tag points at another run's image", { [TAGS.full]: full, [TAGS.slim]: index("slim of another run") }], + ["the full index names no slim image", { [TAGS.full]: index("full without the annotation"), [TAGS.slim]: slim }], + ["the full tag is not an index", { [TAGS.full]: { state: "present", bytes: Buffer.from("not JSON"), digest: sha256("not JSON") }, [TAGS.slim]: slim }], + ])("is broken, and fails every run, when the full tag exists but %s", async (_label, tags) => { + await expect(runnerPublicationState(INPUTS, registry(tags))).resolves.toMatchObject({ state: "broken" }); + // Also without --strict: no run can repair it, and the message says what an operator must do. + await expect(runPublishCommand(["publication-state", "--inputs-digest", INPUTS], { env: {}, read: registry(tags), log: () => {} })) + .rejects.toThrow(/No run can repair this.*Delete the package versions tagged inputs-1{64} and inputs-1{64}-slim, then re-run/); + }); + + it.each<[string, Record]>([ + ["the full tag", { [TAGS.full]: unknown }], + ["the slim tag, with the full tag absent", { [TAGS.slim]: unknown }], + ["the slim tag, with the full tag present", { [TAGS.full]: full, [TAGS.slim]: unknown }], + ])("does not guess when the registry gives no clear answer for %s", async (_label, tags) => { + await expect(runnerPublicationState(INPUTS, registry(tags))).resolves.toMatchObject({ state: "unknown" }); + }); + + it("lets a run whose own slim tag is already written finish, and never pairs a full image with another run's slim", async () => { + // What the publish job does, against a registry a stopped run left behind. + const tags: Record = { [TAGS.slim]: index("slim of the run that stopped") }; + const read = registry(tags); + const gate = await runPublishCommand(["publication-state", "--inputs-digest", INPUTS, "--strict"], { env: {}, read, log: () => {} }); + expect(gate.publish).toBe(true); + // It writes its own slim tag over the orphan, then the full tag that names that slim. + tags[TAGS.slim] = slim; + tags[TAGS.full] = full; + await expect(runPublishCommand(["publication-state", "--inputs-digest", INPUTS, "--strict"], { env: {}, read, log: () => {} })) + .resolves.toEqual({ state: "published", exists: true, publish: false }); + // Had it kept the orphan, the pair would not hold. + tags[TAGS.slim] = index("slim of the run that stopped"); + await expect(runPublishCommand(["publication-state", "--inputs-digest", INPUTS, "--strict"], { env: {}, read, log: () => {} })).rejects.toThrow(/No run can repair this/); + }); +}); + +describe("command line", () => { + const unknown = async () => ({ state: "unknown" as const, detail: "token request: HTTP 403" }); + const absent = async () => ({ state: "absent" as const }); + const quiet = { env: {}, log: () => {} }; + const state = ["publication-state", "--inputs-digest", INPUTS]; + + it("builds on an inconclusive lookup and fails on one when it is strict", async () => { + const lines: string[] = []; + await expect(runPublishCommand(state, { env: {}, read: unknown, log: (line) => lines.push(line) })) + .resolves.toEqual({ state: "unknown", exists: false, publish: false }); + expect(lines.join("\n")).toMatch(/::notice title=Runner image lookup inconclusive::/); + await expect(runPublishCommand([...state, "--strict"], { ...quiet, read: unknown })) + .rejects.toThrow(/Could not determine whether .*paperclip-runner:inputs-1{64} is published \(inputs-1{64}: token request: HTTP 403\)/); + await expect(runPublishCommand([...state, "--strict"], { ...quiet, read: absent })) + .resolves.toEqual({ state: "absent", exists: false, publish: true }); + }); + + it("stays inconclusive, not failed, when the registry cannot be reached", async () => { + const offline = (reference: string) => readRunnerImageManifest(reference, { + fetchImpl: async () => { throw new TypeError("fetch failed"); }, sleep: async () => {}, + }); + await expect(runPublishCommand(state, { ...quiet, read: offline })).resolves.toEqual({ state: "unknown", exists: false, publish: false }); + await expect(runPublishCommand([...state, "--strict"], { ...quiet, read: offline })).rejects.toThrow(/Could not determine/); + }); + + it("passes the registry credentials from the environment, and none when one is missing", async () => { + const seen: unknown[] = []; + const read = async (_reference: string, options?: { credentials?: unknown }) => { seen.push(options?.credentials); return { state: "absent" as const }; }; + await runPublishCommand(state, { env: { RUNNER_IMAGE_REGISTRY_USERNAME: "u", RUNNER_IMAGE_REGISTRY_PASSWORD: "p" }, read, log: () => {} }); + await runPublishCommand(state, { env: { RUNNER_IMAGE_REGISTRY_USERNAME: "u" }, read, log: () => {} }); + expect(new Set(seen.map((credentials) => JSON.stringify(credentials)))).toEqual(new Set(['{"username":"u","password":"p"}', "null"])); + }); + + it("verifies the index of each variant against the recorded legs and against the expected digest", async () => { + const { directory, images } = await legs(); + const indexOf = (variant: "slim" | "full", annotations?: Record) => Buffer.from(JSON.stringify({ + schemaVersion: 2, mediaType: "application/vnd.oci.image.index.v1+json", + manifests: ["amd64", "arm64"].map((architecture) => ({ + mediaType: "application/vnd.oci.image.manifest.v1+json", digest: images[architecture][variant], size: 500, + platform: { os: "linux", architecture }, + })), + ...(annotations ? { annotations } : {}), + })); + const slim = indexOf("slim"); + const full = indexOf("full", { [SLIM_DIGEST_ANNOTATION]: sha256(slim) }); + const serve = (bytes: Buffer) => async () => ({ state: "present" as const, bytes, digest: sha256(bytes) }); + const verify = (...args: string[]) => ["verify-index", ...args, "--dir", directory]; + await expect(runPublishCommand(verify("candidate-x-slim", "--variant", "slim"), { ...quiet, read: serve(slim) })).resolves.toEqual({ digest: sha256(slim) }); + await expect(runPublishCommand(verify("candidate-x", "--variant", "full", "--slim-digest", sha256(slim), "--expect", sha256(full)), { ...quiet, read: serve(full) })) + .resolves.toEqual({ digest: sha256(full) }); + // The slim index is not the full one, and the other way round. + await expect(runPublishCommand(verify("inputs-x", "--variant", "full", "--slim-digest", sha256(slim)), { ...quiet, read: serve(slim) })).rejects.toThrow(); + await expect(runPublishCommand(verify("inputs-x-slim", "--variant", "slim"), { ...quiet, read: serve(full) })).rejects.toThrow(); + await expect(runPublishCommand(verify("inputs-x", "--variant", "full"), { ...quiet, read: serve(full) })) + .rejects.toThrow(/--slim-digest is given for the full index, and only for it/); + await expect(runPublishCommand(verify("inputs-x-slim", "--variant", "slim", "--slim-digest", sha256(slim)), { ...quiet, read: serve(slim) })) + .rejects.toThrow(/--slim-digest is given for the full index, and only for it/); + await expect(runPublishCommand(verify("inputs-x-slim", "--variant", "slim", "--expect", sha256("another index")), { ...quiet, read: serve(slim) })) + .rejects.toThrow(/inputs-x-slim resolves to sha256:[0-9a-f]{64}, expected sha256:[0-9a-f]{64}/); + await expect(runPublishCommand(verify("inputs-x-slim", "--variant", "slim", "--expect", "latest"), { ...quiet, read: serve(slim) })) + .rejects.toThrow(/--expect must be a sha256 digest/); + await expect(runPublishCommand(verify("inputs-x-slim", "--variant", "both"), { ...quiet, read: serve(slim) })).rejects.toThrow(/--variant must be slim or full/); + await expect(runPublishCommand(verify("inputs-x-slim", "--variant", "slim"), { ...quiet, read: absent })).rejects.toThrow(/is absent/); + }); + + it("reports the lockfile state and fails when the check itself fails", async () => { + await expect(runPublishCommand(["lock-state", "--context", "/context"], { ...quiet, lockState: () => ({ state: "behind", detail: "ERR_PNPM_OUTDATED_LOCKFILE" }) })) + .resolves.toEqual({ state: "behind" }); + await expect(runPublishCommand(["lock-state", "--context", "/context"], { ...quiet, lockState: () => { throw new Error("broken"); } })) + .rejects.toThrow("broken"); + }); + + it.each<[string, string[], RegExp]>([ + ["an empty --expect", ["verify-index", "inputs-x", "--dir", "d", "--variant", "slim", "--expect", ""], /--expect needs a value/], + ["an --expect with no value", ["verify-index", "inputs-x", "--dir", "d", "--variant", "slim", "--expect"], /--expect needs a value/], + ["an index check without a variant", ["verify-index", "inputs-x", "--dir", "d"], /verify-index needs --variant/], + ["a misspelt flag", [...state, "--strikt"], /publication-state does not take --strikt/], + ["a flag of another command", [...state, "--expect", "sha256:x"], /publication-state does not take --expect/], + ["a repeated flag", ["verify-index", "inputs-x", "--dir", "a", "--dir", "b"], /--dir is given twice/], + ["a missing required flag", ["verify-legs", "--dir", "d", "--inputs-digest", INPUTS], /verify-legs needs --source-revision/], + ["an empty required value", ["verify-legs", "--dir", "d", "--inputs-digest", "", "--source-revision", REVISION], /--inputs-digest needs a value/], + ["a lookup without the inputs digest", ["publication-state", "--strict"], /publication-state needs --inputs-digest/], + ["a lookup by tag", ["publication-state", "inputs-x", "--inputs-digest", INPUTS], /takes no positional argument/], + ["a missing tag", ["verify-index", "--dir", "d", "--variant", "slim"], /takes exactly one tag or digest/], + ["an empty tag", ["verify-index", "", "--dir", "d", "--variant", "slim"], /not a tag or digest/], + ["a record of one variant", ["record", "--arch", "amd64", "--full-archive", "f", "--full-metadata", "m", "--tree", "t", "--layout", "l", "--out", "o"], /record needs --slim-archive/], + ["an unknown command", ["tag-state", "inputs-x"], /Usage/], + ["no command", [], /Usage/], + ])("rejects %s", (_label, argv, expected) => { + expect(() => parsePublishArguments(argv[0], argv.slice(1))).toThrow(expected); + }); +}); diff --git a/server/src/__tests__/runner-image-workflow.test.ts b/server/src/__tests__/runner-image-workflow.test.ts index a1f9e565e68..fba9724ad60 100644 --- a/server/src/__tests__/runner-image-workflow.test.ts +++ b/server/src/__tests__/runner-image-workflow.test.ts @@ -6,9 +6,9 @@ import { RUNNER_IMAGE_CONTEXT_INPUTS } from "../../../scripts/runner-image-ident /** * Security properties of the Runner image workflow. The build runs dependency - * lifecycle scripts, so what the jobs may do matters more than how their - * steps are worded: these tests pin permissions, credentials and triggers, - * not step names or order. + * lifecycle scripts and the workflow publishes a signed image, so what each + * job may do matters more than how its steps are worded: these tests pin + * permissions, credentials and gating, not step names or order. */ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); @@ -25,17 +25,89 @@ const permissions = (job: string) => const scripts = [...workflow.matchAll(/^( +)run: (\|\n((?:\1 {2,}.*\n|\n)+)|.+\n)/gm)].map((match) => match[3] ?? match[2]); describe("Runner image workflow", () => { - it("grants nothing at the workflow level and only read access to contents in each job", () => { + const repository = "github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064'"; + const canonical = `${repository} && github.event_name == 'push' && github.ref == 'refs/heads/master'`; + const jobCondition = (job: string) => /^ {4}if: (.+)$/m.exec(job)?.[1] ?? ""; + /** The steps of a job, without the job's own header. */ + const steps = (job: string) => job.slice(job.indexOf("\n steps:\n")).split(/\n(?= {6}- )/).slice(1); + const credential = /github\.token|secrets\.|GITHUB_TOKEN|REGISTRY_PASSWORD/; + + it("lets only the publish job write to the registry or sign", () => { expect(workflow).toMatch(/^permissions: \{\}$/m); - expect(Object.keys(jobs)).toEqual(["identity", "build"]); - for (const job of Object.values(jobs)) expect(permissions(job)).toEqual(["contents: read"]); + expect(Object.keys(jobs)).toEqual(["identity", "build", "publish"]); + expect(permissions(jobs.identity)).toEqual(["contents: read", "packages: read"]); + expect(permissions(jobs.build)).toEqual(["contents: read", "packages: read"]); + expect(permissions(jobs.publish)).toEqual(["contents: read", "packages: write", "id-token: write", "attestations: write"]); + for (const job of [jobs.identity, jobs.build]) { + expect(job).not.toMatch(/docker\/login-action|skopeo|imagetools create|actions\/attest|secrets\.|--push|push=true/); + } + expect(workflow).not.toMatch(/pull_request_target|workflow_run/); }); - it("has no credential, no registry access and no way to publish", () => { - expect(workflow).not.toMatch(/github\.token|secrets\.|GITHUB_TOKEN|docker\/login-action|packages:|id-token|attestations/); - expect(workflow).not.toMatch(/--push|push=true|skopeo|imagetools|type=image|type=registry|cache-to|cache-from|type=gha/); - const triggers = workflow.slice(workflow.indexOf("\non:\n"), workflow.indexOf("\npermissions:")); - expect([...triggers.matchAll(/^ {2}([a-z_]+):/gm)].map((match) => match[1])).toEqual(["pull_request", "workflow_dispatch"]); + it("publishes, and keeps the images for publication, only for a master push in the canonical repository", () => { + expect(jobCondition(jobs.publish).startsWith(`${canonical} && `)).toBe(true); + expect(jobs.publish).toContain(" needs: [identity, build]\n"); + expect(jobs.build).toContain(`KEEP_IMAGE: \${{ ${canonical} }}`); + // The one step that hands the images to the publish job is behind that switch. + const uploading = steps(jobs.build).filter((step) => step.includes("upload-artifact")); + expect(uploading).toHaveLength(1); + expect(uploading[0]).toMatch(/^ {8}if: env\.KEEP_IMAGE == 'true' && /m); + // The record is written on every event, so a pull request exercises it. It needs no credential. + const recording = steps(jobs.build).filter((step) => step.includes("runner-image-publish.mjs record")); + expect(recording).toHaveLength(1); + expect(recording[0]).not.toMatch(/KEEP_IMAGE/); + expect(recording[0]).not.toMatch(credential); + // A fork's own pushes run nothing; no job overrides a skipped or failed dependency. + expect(jobCondition(jobs.identity)).toBe(`github.event_name != 'push' || (${repository})`); + expect(workflow).not.toMatch(/always\(\)|!cancelled\(\)|failure\(\)|continue-on-error/); + }); + + it("keeps the build legs free of credentials and of any registry build cache", () => { + // No job-level token: the block before the steps holds none, in any job. + for (const job of Object.values(jobs)) expect(job.slice(0, job.indexOf("\n steps:\n"))).not.toMatch(credential); + // The steps that build, check and smoke the image never receive one. + const working = steps(jobs.build).filter((step) => /docker buildx build|runner-image-layout\.mjs|pnpm |upload-artifact/.test(step)); + expect(working.length).toBeGreaterThanOrEqual(4); + for (const step of working) expect(step).not.toMatch(credential); + // The one token the legs can see only reads packages, and only a lookup gets it. + for (const step of steps(jobs.build).filter((entry) => credential.test(entry))) { + expect(step).toContain("runner-image-publish.mjs publication-state"); + expect(step).not.toContain("--strict"); + } + expect(workflow).not.toMatch(/cache-to|cache-from|type=registry|type=gha/); + }); + + it("writes the full tag last, after a strict lookup and after both images are attested", () => { + // The full tag marks a complete publication, so nothing may follow it + // that can fail to write a tag, and no tag is written on a guess. + const publish = jobs.publish; + const order = [ + "publication-state --inputs-digest \"$DIGEST\" --strict\n", + "subject-digest: ${{ steps.slim.outputs.digest }}", + "subject-digest: ${{ steps.full.outputs.digest }}", + 'imagetools create -t "$IMAGE:inputs-$DIGEST-slim" "$IMAGE@$SLIM_INDEX"', + 'imagetools create -t "$IMAGE:inputs-$DIGEST" "$IMAGE@$FULL_INDEX"', + ].map((text) => publish.indexOf(text)); + expect(order.every((position) => position >= 0)).toBe(true); + expect([...order].sort((a, b) => a - b)).toEqual(order); + // The final tags are written in one place each; every other tag is a candidate. + expect([...workflow.matchAll(/-t "\$IMAGE:([a-z]+)-/g)].map((match) => match[1])).toEqual(["candidate", "candidate", "inputs", "inputs"]); + // Every step that writes a tag or signs runs only after the strict lookup allowed it. + const writing = steps(publish).filter((step) => /imagetools create|actions\/attest/.test(step)); + expect(writing).toHaveLength(5); + for (const step of writing) expect(step).toMatch(/^ {8}if: steps\.gate\.outputs\.publish == 'true'$/m); + expect(publish).toContain("group: runner-image-publish-${{ needs.identity.outputs.digest }}\n cancel-in-progress: false"); + }); + + it("never resolves the lockfile on a master push, and neither builds nor publishes when it is behind", () => { + const resolving = steps(jobs.identity).filter((step) => step.includes("pnpm install")); + expect(resolving).toHaveLength(1); + expect(resolving[0]).toMatch(/^ {8}if: github\.event_name != 'push'$/m); + expect(workflow.match(/pnpm install/g)).toHaveLength(1); + expect(jobCondition(jobs.build).startsWith("needs.identity.outputs.lock == 'current' && ")).toBe(true); + expect(jobCondition(jobs.publish)).toContain("needs.identity.outputs.lock == 'current'"); + // Pull requests and manual runs always build; only a push skips an image that exists. + expect(jobCondition(jobs.build)).toContain("github.event_name != 'push' || ("); }); it("pins every action by commit and keeps expressions out of shell scripts", () => { @@ -52,14 +124,30 @@ describe("Runner image workflow", () => { // was cancelled. One export for each command, and a limit on each step, // so a stall fails in minutes. const building = workflow.split(/\n(?= {6}- name: )/).filter((step) => step.includes("docker buildx build")); - expect(building.length).toBeGreaterThanOrEqual(3); + expect(building.length).toBeGreaterThanOrEqual(4); for (const step of building) { expect(step).toMatch(/^ {8}timeout-minutes: \d+$/m); for (const command of step.split("docker buildx build").slice(1)) expect(command.match(/--output /g) ?? []).toHaveLength(1); } // The trees the checks read come from the archives, not from a second export. expect(workflow).toContain("node scripts/runner-image-oci.mjs unpack"); - expect(workflow.match(/type=local/g)).toHaveLength(2); + expect(workflow.match(/type=local/g)).toHaveLength(3); + }); + + it("passes the image build exactly two build arguments", () => { + // Build arguments are not part of the image identity, so a new one would + // change what is published under an unchanged digest. + const image = steps(jobs.build).filter((step) => step.includes("--target \"$target\"")); + expect(image).toHaveLength(1); + expect([...image[0].matchAll(/--build-arg (\S+)/g)].map((match) => match[1])).toEqual([ + '"PAPERCLIP_RUNNER_SOURCE_REVISION=$GITHUB_SHA"', + "PAPERCLIP_RUNNER_IMAGE_PUBLICATION=1", + ]); + expect(image[0]).toContain("target=runner-artifacts\n"); + expect(image[0]).toContain('if [ "$variant" = slim ]; then target=runner-artifacts-slim; fi'); + // No other command passes a build argument, and the identity is computed without one. + expect(workflow.match(/--build-arg /g)).toHaveLength(2); + expect(workflow).not.toMatch(/build-args:|BUILDX_BUILD_ARG|--build-arg-file/); }); it("runs for a pull request that changes any input of the image identity", () => { @@ -68,7 +156,7 @@ describe("Runner image workflow", () => { || (pattern.endsWith("/**") && (file === pattern.slice(0, -3) || file.startsWith(pattern.slice(0, -2))))); // .dockerignore is not in the identity, but it decides which files the build receives. for (const input of ["Dockerfile", ".dockerignore", ".github/workflows/runner-image.yml", "docker/runner-image/Dockerfile.smoke", - "scripts/runner-image-oci.mjs", ...RUNNER_IMAGE_CONTEXT_INPUTS]) { + "scripts/runner-image-oci.mjs", "scripts/runner-image-publish.mjs", "scripts/standard-image-contract.mjs", ...RUNNER_IMAGE_CONTEXT_INPUTS]) { expect(covered(input), input).toBe(true); } }); From af1c685f5f6b6f2e6b4c356c3d4ff0bb0c38eeda Mon Sep 17 00:00:00 2001 From: Awss Date: Fri, 13 Nov 2026 04:31:42 +0000 Subject: [PATCH 14/15] fix(secrets): return 422 for secret proposals missing a required field (#15348) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - An agent can propose a company secret or a secret binding through the API. > - The proposal route reads the request body and passes it to the service. > - The service trimmed required string fields before it checked them. > - A request that omitted name or justification threw a TypeError. > - The route then returned 500 instead of a validation error. > - This pull request checks the required fields first and returns 422. > - The benefit is that a client can tell a bad request from a server fault. ## Linked Issues or Issue Description Closes #15334 ## What Changed - Check `name` and `justification` in `createSecret` before `trim`, and return 422 when either is missing. - Check `justification` in `createBinding` the same way. - Keep the existing empty-value and malformed-value checks and the optional `key` field unchanged. - Add a regression test that covers the missing-field cases for both proposal kinds and keeps the complete-body case at 201. No documentation change is needed. The OpenAPI document already lists 422 for this route, so the server now matches the documented contract. ## Verification - Run the route suite. It passes. `./node_modules/.bin/vitest run server/src/__tests__/secret-proposals-routes.test.ts` gives 26 passed. - Revert only the service change and run the new test. It fails with `expected 500 to be 422`, which proves the test catches the bug. Restore the change and it passes again. - Run the server typecheck. It passes. `pnpm --filter @paperclipai/server run typecheck` exits 0 with no errors. - A `POST /api/agents/me/secret-proposals` that omits `justification` returns 422 after the fix and returned 500 before it. A complete body still returns 201. ## Risks - Low risk. The change adds two field checks before an existing `trim` call. Valid requests still return 201. A missing required field now returns 422, which the route already documents. ## Model Used Claude Opus 4.8 (`claude-opus-4-8`), with extended thinking and tool use. I chose the issue, set the evidence bar, directed each step, and reviewed the code, the tests, and the results before this PR. The model traced the route and the service, wrote the fix and the regression test, and ran the checks under that direction. ## 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 Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> --- .../__tests__/secret-proposals-routes.test.ts | 24 +++++++++++++++++++ server/src/services/secret-proposals.ts | 6 ++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/secret-proposals-routes.test.ts b/server/src/__tests__/secret-proposals-routes.test.ts index 2ea6f49f634..a9028b4cb5f 100644 --- a/server/src/__tests__/secret-proposals-routes.test.ts +++ b/server/src/__tests__/secret-proposals-routes.test.ts @@ -228,6 +228,30 @@ describeEmbeddedPostgres("secret proposal routes", () => { return app; } + it("returns 422, not 500, when a proposal omits a required field", async () => { + const fixture = await seedRun(); + + const secretMissingJustification = await request(createAgentApp(fixture)) + .post("/api/agents/me/secret-proposals") + .send({ kind: "secret", name: "dev/missing/justification", value: "a-32-character-or-longer-secret", description: "x" }); + expect(secretMissingJustification.status).toBe(422); + + const secretMissingName = await request(createAgentApp(fixture)) + .post("/api/agents/me/secret-proposals") + .send({ kind: "secret", value: "a-32-character-or-longer-secret", justification: "Needed by the task" }); + expect(secretMissingName.status).toBe(422); + + const bindingMissingJustification = await request(createAgentApp(fixture)) + .post("/api/agents/me/secret-proposals") + .send({ kind: "binding", sourceConfigPath: "env.SOURCE_TOKEN", configPath: "env.TARGET_TOKEN" }); + expect(bindingMissingJustification.status).toBe(422); + + const complete = await request(createAgentApp(fixture)) + .post("/api/agents/me/secret-proposals") + .send({ kind: "secret", name: "dev/missing/ok", value: "a-32-character-or-longer-secret", justification: "Needed by the task" }); + expect(complete.status).toBe(201); + }); + describe("expiry scheduling", () => { let coordinator: ReturnType | undefined; let proposals: ReturnType; diff --git a/server/src/services/secret-proposals.ts b/server/src/services/secret-proposals.ts index b098946ce7f..562fc285177 100644 --- a/server/src/services/secret-proposals.ts +++ b/server/src/services/secret-proposals.ts @@ -324,6 +324,8 @@ export function createSecretProposalsService(db: Db) { value: string; justification: string; }) { + if (typeof input.name !== "string") throw unprocessable("Secret name is required"); + if (typeof input.justification !== "string") throw unprocessable("Justification is required"); const name = input.name.trim(); const justification = input.justification.trim(); if (!SECRET_NAME_RE.test(name)) throw unprocessable("Secret name must be a slash-separated path without empty segments"); @@ -381,7 +383,9 @@ export function createSecretProposalsService(db: Db) { if (input.sourceConfigPath && !CONFIG_PATH_RE.test(input.sourceConfigPath)) { throw unprocessable("sourceConfigPath must use env. or access."); } - if (!input.justification.trim()) throw unprocessable("Justification is required"); + if (typeof input.justification !== "string" || !input.justification.trim()) { + throw unprocessable("Justification is required"); + } if (input.justification.trim().length > 20_000) throw unprocessable("Justification must be at most 20000 characters"); const { run, originIssueId } = await loadRunContext(db, context); const targetAgentId = input.targetAgentId ?? run.agentId; From c4f639ed1b01985593f1c70bb31f9cd1da441ecb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:31:50 -0600 Subject: [PATCH 15/15] fix(ci): re-run cancelled runs that lost a runner, and let runner-loss evidence win (#21291) 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 > - PR CI runs about 50 jobs per run on AWS spot instances. AWS can reclaim a machine mid-job, and the job dies. > - `ci-runner-loss-rerun.yml` re-runs such a run once, automatically, when every failed job lost its runner. > - In a 17-hour sample, 42 runs lost a runner and were still the PR's current head. The automation rescued only 14. > - Two gaps caused most of the misses. A spot reclaim on RunsOn v3.2.3 usually ends the job, and the run, as `cancelled`; the workflow and script only look at `failure`. Also, the Runner support suite always carries `gateway_indexing_incomplete` error annotations from a passing test, so a lost runner there reads as a real failure. > - On-demand fallback for the fleet was turned off on 2026-11-13, so reclaims will happen more often. About 20% of runs are expected to lose at least one job. > - This pull request makes the re-run act on cancelled runs and jobs, but only with positive runner-loss evidence, and lets that evidence win over other error annotations. > - The benefit is fewer manual "Re-run failed jobs" clicks: an estimated 34 of 42 instead of 14 of 42 in the sample. ## Linked Issues or Issue Description No public issue exists. **What happened?** Run [43285064435](https://github.com/paperclipai/paperclip/actions/runs/43285064435) lost the runner of `ci / General tests (server (8/12))`. The job concluded `cancelled` (its log has `##[error]The runner has received a shutdown signal`). The run concluded `cancelled`, so the re-run workflow's `if:` skipped it. Run [43325855069](https://github.com/paperclipai/paperclip/actions/runs/43325855069) lost the runners of `ci / Runner support suite` and `ci / General tests (server (2/12))`. Both logs have the shutdown signal. The re-run bot ([decision log](https://github.com/paperclipai/paperclip/actions/runs/43327873358)) said "1 of 1 failed jobs did not lose their runner", with evidence `gateway_indexing_incomplete`. It ignored the cancelled job. It read the annotation as a real failure. **Expected behavior** Both runs get one automatic re-run of their failed jobs. **Steps to reproduce** The new tests replay trimmed snapshots of both runs (`.github/scripts/tests/fixtures/runner-loss-rerun/run-43285064435.json` and `run-43325855069.json`) through the script. In a 17-hour sample on 2026-11-12, 42 runs lost a runner and were still the PR's current head. Only 14 were re-run automatically. 16 stayed red because the run concluded `cancelled`. 4 stayed red because an error annotation in the lost job was read as a test failure. **Additional context** The `gateway_indexing_incomplete` annotation does not come from the shutdown. `scheduled-gateway-indexing.test.ts` prints `::error` lines while it passes, 84 seconds before the shutdown signal in this run. Attempt 2 of the same run passed with the same two failure annotations. So, before this change, a lost runner in the Runner support suite could never be re-run. ## What Changed - `ci-runner-loss-rerun.yml`: the job also runs when the PR run concluded `cancelled`. The trigger type, `permissions`, the repository, path, event and attempt-1 conditions do not change. - `runner-loss-rerun.mjs`, `eligibleRun`: accepts `completed/cancelled` as well as `completed/failure`. - `runner-loss-rerun.mjs`, `decide()`: classifies jobs that concluded `cancelled` as well as `failure`. It still skips the `ci / verify` and `ci / e2e` aggregates, and a failed or cancelled routing gate still blocks the re-run. - `decide()` now runs `staleReason` (open PR, current head, no newer run) before it reads any annotation or log, and again just before the re-run, as on master. A run cancelled by a new push has about 40 cancelled jobs; it now costs two API listings and no log reads. The final check closes the window where a push lands during the log reads: a re-run of the old run would join the PR's `cancel-in-progress` concurrency group (`pr-` in `pr-trusted.yml`) and cancel the new commit's CI. - Following CONTRIBUTING.md ("Do not submit a PR that includes code comments"), this PR adds no new code comments. The reasons for each rule are in this description and in `doc/DEVELOPING.md`. - `classifyJob`: runner-loss evidence wins. A lost-communication annotation means lost. A cancellation annotation plus a shutdown signal in the log means lost, even if the job also has other error annotations. A cancelled job without this evidence (for example, a person cancelled the run) counts as a real failure and blocks the re-run. - Fixtures: two new trimmed snapshots from the example runs (jobs with `id`, `name`, `status`, `conclusion`; failure annotations; `##[error]` log lines only). The two older fixtures get the real annotations and log error lines of their cancelled jobs. Those jobs were spot-reclaimed too (each log has the shutdown signal), but the old code ignored them. - `doc/DEVELOPING.md`: the runner-loss paragraph describes the new rules. ## Verification - Red first. Against the unchanged script, the new tests fail for the reasons above: 43285064435 gives `run is completed/cancelled, not completed/failure`; 43325855069 gives `1 of 1 failed jobs did not lose their runner` with evidence `gateway_indexing_incomplete`, the same decision the bot logged. - Green: `node --test .github/scripts/tests/runner-loss-rerun.test.mjs`: 25 of 25 pass. - Push during log reads: the PR head moves after the first log read. With the final freshness check removed, this test fails (the script re-runs); with it, there is no re-run and the reason is `no open pull request still has this run's head commit`. - Guard cases, all with no re-run and no POST: - Superseded run: 52 jobs cancelled, the PR head moved. The test asserts zero annotation and log reads. - Person cancelled the run: cancelled jobs with only "The operation was canceled." in the annotation and log, and some never-started jobs with no annotation. - Mixed: one cancelled lost job and one real test failure (`1 of 2 failed jobs did not lose their runner`). - Once only: a cancelled run on attempt 2 is refused after one API read. The workflow condition test still requires `run_attempt == 1`. - Cancelled routing gate: left for a person. - Policy job command: `node --test '.github/scripts/tests/*.test.mjs'`: 806 of 806 pass. - `pnpm verify`: exit 2 ("Global CI input changed: .github/scripts/runner-loss-rerun.mjs"). It selects no local Vitest files and asks for required CI coverage. I did not run `pnpm verify --full`; required CI on this PR supplies that coverage. - This workflow runs on `workflow_run` from the default branch. This PR's own CI cannot exercise the new behavior. The fixture tests are the evidence. I did not dry-run the script against live runs. ## Risks - A test that really fails, and then a spot reclaim of the same job a minute later, now gets one wasted re-run. Attempt 2 then fails for real. It cannot loop: the workflow `if:` and `eligibleRun` both accept attempt 1 only. - A run a person cancels on the current head now starts the re-run job. The job reads the annotations, and the log of each job with a cancellation annotation, and then does not re-run. This costs some API calls on a GitHub-hosted runner. - A concurrency cancel by a label event that does not request CI (the newer run is `skipped`) passes the head check. Its cancelled jobs have no runner-loss evidence, so it is not re-run. - Trust: no change to `permissions`, the trigger, the accepted repository, event, workflow path, attempt, or the routing-gate rule. A cancelled run reuses its attempt-1 gate output, the same as a failed run does today. - Estimated effect, from a 17-hour sample: 14 of 42 rescued before; 16 cancelled runs and 4 runs with error-annotation noise become eligible (about 34 of 42). The other 8 stay skipped on purpose (a real test failure in the same run, a person re-ran first, or the PR closed). > 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), Claude Code agent. Model ID claude-opus-5-5, with tool use (shell, GitHub CLI) 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 - [ ] I will address all Greptile and reviewer comments before requesting merge šŸ¤– Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 --- .github/scripts/runner-loss-rerun.mjs | 28 +- .../runner-loss-rerun/run-42271918832.json | 42 +- .../runner-loss-rerun/run-42277969418.json | 122 +++++- .../runner-loss-rerun/run-43285064435.json | 360 +++++++++++++++++ .../runner-loss-rerun/run-43325855069.json | 363 ++++++++++++++++++ .../scripts/tests/runner-loss-rerun.test.mjs | 170 +++++++- .github/workflows/ci-runner-loss-rerun.yml | 8 +- doc/DEVELOPING.md | 23 +- 8 files changed, 1073 insertions(+), 43 deletions(-) create mode 100644 .github/scripts/tests/fixtures/runner-loss-rerun/run-43285064435.json create mode 100644 .github/scripts/tests/fixtures/runner-loss-rerun/run-43325855069.json diff --git a/.github/scripts/runner-loss-rerun.mjs b/.github/scripts/runner-loss-rerun.mjs index 8a94ece7ddd..f581cdbbca5 100644 --- a/.github/scripts/runner-loss-rerun.mjs +++ b/.github/scripts/runner-loss-rerun.mjs @@ -3,7 +3,7 @@ * runner-loss-rerun.mjs * * Re-runs the failed jobs of a first PR CI attempt once, but only when every - * failed job failed because its runner was lost. Runs from + * failed or cancelled job ended because its runner was lost. Runs from * .github/workflows/ci-runner-loss-rerun.yml on workflow_run. It reads GitHub * API metadata only and never touches the PR's code or artifacts. * @@ -26,6 +26,7 @@ export const AGGREGATE_JOBS = new Set(["ci / verify", "ci / e2e"]); // ci-routing.yml checks the attempt's triggering actor. A bot-triggered attempt // would move the whole run to GitHub-hosted runners, so leave it to a human. export const GATE_JOB_PREFIX = "ci / gate / "; +export const RERUN_CONCLUSIONS = new Set(["failure", "cancelled"]); // A shutdown signal often reaches the check run only as this annotation; the // signal itself is logged as an error line in the job log. const CANCELLED_MESSAGE = "The operation was canceled."; @@ -80,20 +81,14 @@ export function logShowsRunnerLoss(log) { export async function classifyJob(job, { annotations, readLog }) { const failures = annotations.filter((annotation) => annotation.annotation_level === "failure"); const isRunnerLoss = (annotation) => RUNNER_LOSS_PATTERN.test(annotation.message ?? ""); - // A step can fail for a real reason before the runner is lost (for example a - // test failure, then a loss during an always() upload step). Any failure - // annotation other than runner loss or cancellation marks a real failure. - const real = failures.find((annotation) => !isRunnerLoss(annotation) && annotation.message !== CANCELLED_MESSAGE); - if (real) return { lost: false, evidence: firstLine(real.message) }; const match = failures.find(isRunnerLoss); if (match) return { lost: true, evidence: firstLine(match.message) }; - // Only cancellations are left: the shutdown signal, if any, is in the log. - if (failures.length > 0) { - if (logShowsRunnerLoss(await readLog(job))) { - return { lost: true, evidence: "job log: runner received a shutdown signal or lost communication" }; - } - return { lost: false, evidence: `${CANCELLED_MESSAGE} (no runner-loss error in the job log)` }; + if (failures.some((annotation) => annotation.message === CANCELLED_MESSAGE) && logShowsRunnerLoss(await readLog(job))) { + return { lost: true, evidence: "job log: runner received a shutdown signal or lost communication" }; } + const real = failures.find((annotation) => annotation.message !== CANCELLED_MESSAGE); + if (real) return { lost: false, evidence: firstLine(real.message) }; + if (failures.length > 0) return { lost: false, evidence: `${CANCELLED_MESSAGE} (no runner-loss error in the job log)` }; return { lost: false, evidence: "no failure annotation" }; } @@ -106,7 +101,9 @@ export function eligibleRun(run) { if (run.repository?.full_name !== REPOSITORY || run.repository?.id !== REPOSITORY_ID) return "run is not in the canonical repository"; if (run.path !== PR_WORKFLOW_PATH) return `workflow is ${run.path}, not ${PR_WORKFLOW_PATH}`; if (run.event !== "pull_request") return `event is ${run.event}, not pull_request`; - if (run.status !== "completed" || run.conclusion !== "failure") return `run is ${run.status}/${run.conclusion}, not completed/failure`; + if (run.status !== "completed" || !RERUN_CONCLUSIONS.has(run.conclusion)) { + return `run is ${run.status}/${run.conclusion}, not completed/failure or completed/cancelled`; + } // One automatic re-run only. A higher attempt also means someone re-ran it. if (run.run_attempt !== 1) return `run is on attempt ${run.run_attempt}; only attempt 1 is re-run automatically`; return undefined; @@ -137,9 +134,12 @@ export async function decide(client, run) { if (ineligible) return { ...decision, reason: ineligible }; const jobs = await client.paginate(`/repos/${REPOSITORY}/actions/runs/${run.id}/attempts/1/jobs?per_page=100`, "jobs"); - const failed = jobs.filter((job) => job.conclusion === "failure" && !AGGREGATE_JOBS.has(job.name)); + const failed = jobs.filter((job) => RERUN_CONCLUSIONS.has(job.conclusion) && !AGGREGATE_JOBS.has(job.name)); if (failed.length === 0) return { ...decision, reason: "no failed jobs other than the verify/e2e aggregates" }; + const staleBefore = await staleReason(client, run); + if (staleBefore) return { ...decision, reason: staleBefore }; + for (const job of failed) { if (job.name.startsWith(GATE_JOB_PREFIX)) { decision.jobs.push({ id: job.id, name: job.name, lost: false, evidence: "routing gate failed; a bot re-run would lose AWS routing" }); diff --git a/.github/scripts/tests/fixtures/runner-loss-rerun/run-42271918832.json b/.github/scripts/tests/fixtures/runner-loss-rerun/run-42271918832.json index 2dca8cc8caa..9be00e01728 100644 --- a/.github/scripts/tests/fixtures/runner-loss-rerun/run-42271918832.json +++ b/.github/scripts/tests/fixtures/runner-loss-rerun/run-42271918832.json @@ -1042,7 +1042,7 @@ "end_line": 123, "annotation_level": "failure", "title": "[paperclipai] src/__tests__/company-import-transfer.test.ts > resolveChunkedImportZip > takes the chunked path for a small zip whose entries inflate past the threshold", - "message": "Error: Test timed out in 5000ms.\nIf this is a long-running test, pass a timeout value as the last argument or configure it globally with \"testTimeout\".\n āÆ src/__tests__/company-import-transfer.test.ts:123:3\n\n", + "message": "Error: Test timed out in 5000ms.\nIf this is a long-running test, pass a timeout value as the last argument or configure it globally with \"testTimeout\".\n \u276f src/__tests__/company-import-transfer.test.ts:123:3\n\n", "raw_details": "" }, { @@ -1051,7 +1051,7 @@ "end_line": 280, "annotation_level": "failure", "title": "[paperclipai] src/__tests__/company-import-export-e2e.test.ts > paperclipai company import/export e2e", - "message": "Error: Timed out waiting for the child server recorded in /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/paperclip-home/instances/company-cli-e2e/runtime-info.json.\nstdout:\nUpdate available: 2026.1023.0 — run `paperclipai update`\nā”Œ paperclipai run \n│\n│ Home: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/paperclip-home\n│\n│ Instance: company-cli-e2e\n│\n│ Config: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/config.json\n│\nā—‡ Running doctor checks...\nUpdate available: 2026.1023.0 — run `paperclipai update`\n\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•— ā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— \nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•\nā–ˆā–ˆā•”ā•ā•ā•ā• ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā• ā–ˆā–ˆā•”ā•ā•ā• ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā• \nā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ \nā•šā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā• ā•šā•ā•ā•ā•ā•ā•ā•ā•šā•ā• ā•šā•ā• ā•šā•ā•ā•ā•ā•ā•ā•šā•ā•ā•ā•ā•ā•ā•ā•šā•ā•ā•šā•ā• \n ───────────────────────────────────────────────────────\n The app people use to manage AI agents for work\n\nā”Œ paperclip doctor \n│\n│ āœ“ Config file: Valid config at /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/config.json\n│\n│ āœ“ Deployment/auth mode: local_trusted mode is configured for loopback-only access\n│\n│ āœ— Agent JWT secret: PAPERCLIP_AGENT_JWT_SECRET missing from environment and /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/.env\n│\n│ Run with --repair to create /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/.env containing PAPERCLIP_AGENT_JWT_SECRET\n│\nā—† Repaired: Agent JWT secret\n│\n│ āœ“ Agent JWT secret: PAPERCLIP_AGENT_JWT_SECRET is set in environment\n│\n│ ! Secrets adapter: Secrets key file does not exist yet: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/secrets/master.key; strict secret mode is disabled for postgres deployment\n│\n│ Run with --repair to create a local encrypted secrets key file. Consider enabling secrets.strictMode\n│\nā—† Repaired: Secrets adapter\n│\n│ ! Secrets adapter: Local encrypted provider configured with key file /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/secrets/master.key; strict secret mode is disabled for postgres deployment\n│\n│ Consider enabling secrets.strictMode\n│\n│ āœ“ Storage: Local disk storage is writable: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/storage\n│\n│ āœ“ Database: PostgreSQL connection successful\n│\n│ āœ“ LLM provider: No LLM provider configured (optional)\n│\n│ āœ“ Log directory: Log directory is writable: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/logs\n│\n│ ! Server port: Port 37925 is already in use\n│\n│ Check what's using port 37925 with: lsof -i :37925\n│\n│ āœ“ Node.js runtime: Node.js 24.22.2\n│\n│ āœ“ Managed install: Not present (optional for npx, global npm, and source-checkout usage)\n│\n│ āœ“ Background service: No usable systemd user manager was detected (common in containers and WSL1). Use paperclipai run instead.\n│\nā—‡ Summary ───────────────╮\n│ │\n│ 10 passed, 2 warnings │\n│ │\nā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā•Æ\n│\nā”” All critical checks passed with some warnings.\n\n│\nā—‡ Start", + "message": "Error: Timed out waiting for the child server recorded in /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/paperclip-home/instances/company-cli-e2e/runtime-info.json.\nstdout:\nUpdate available: 2026.1023.0 \u2014 run `paperclipai update`\n\u250c paperclipai run \n\u2502\n\u2502 Home: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/paperclip-home\n\u2502\n\u2502 Instance: company-cli-e2e\n\u2502\n\u2502 Config: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/config.json\n\u2502\n\u25c7 Running doctor checks...\nUpdate available: 2026.1023.0 \u2014 run `paperclipai update`\n\n\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \n\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255d\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\n\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\n\u2588\u2588\u2554\u2550\u2550\u2550\u255d \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u255d \u2588\u2588\u2554\u2550\u2550\u255d \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u255d \n\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u255a\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \n\u255a\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d\u255a\u2550\u255d \n \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n The app people use to manage AI agents for work\n\n\u250c paperclip doctor \n\u2502\n\u2502 \u2713 Config file: Valid config at /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/config.json\n\u2502\n\u2502 \u2713 Deployment/auth mode: local_trusted mode is configured for loopback-only access\n\u2502\n\u2502 \u2717 Agent JWT secret: PAPERCLIP_AGENT_JWT_SECRET missing from environment and /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/.env\n\u2502\n\u2502 Run with --repair to create /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/config/.env containing PAPERCLIP_AGENT_JWT_SECRET\n\u2502\n\u25c6 Repaired: Agent JWT secret\n\u2502\n\u2502 \u2713 Agent JWT secret: PAPERCLIP_AGENT_JWT_SECRET is set in environment\n\u2502\n\u2502 ! Secrets adapter: Secrets key file does not exist yet: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/secrets/master.key; strict secret mode is disabled for postgres deployment\n\u2502\n\u2502 Run with --repair to create a local encrypted secrets key file. Consider enabling secrets.strictMode\n\u2502\n\u25c6 Repaired: Secrets adapter\n\u2502\n\u2502 ! Secrets adapter: Local encrypted provider configured with key file /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/secrets/master.key; strict secret mode is disabled for postgres deployment\n\u2502\n\u2502 Consider enabling secrets.strictMode\n\u2502\n\u2502 \u2713 Storage: Local disk storage is writable: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/storage\n\u2502\n\u2502 \u2713 Database: PostgreSQL connection successful\n\u2502\n\u2502 \u2713 LLM provider: No LLM provider configured (optional)\n\u2502\n\u2502 \u2713 Log directory: Log directory is writable: /tmp/pv-KMcoQP/t/paperclip-company-cli-e2e-8VX8vL/logs\n\u2502\n\u2502 ! Server port: Port 37925 is already in use\n\u2502\n\u2502 Check what's using port 37925 with: lsof -i :37925\n\u2502\n\u2502 \u2713 Node.js runtime: Node.js 24.22.2\n\u2502\n\u2502 \u2713 Managed install: Not present (optional for npx, global npm, and source-checkout usage)\n\u2502\n\u2502 \u2713 Background service: No usable systemd user manager was detected (common in containers and WSL1). Use paperclipai run instead.\n\u2502\n\u25c7 Summary \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 \u2502\n\u2502 10 passed, 2 warnings \u2502\n\u2502 \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\u2502\n\u2514 All critical checks passed with some warnings.\n\n\u2502\n\u25c7 Start", "raw_details": "" }, { @@ -1085,10 +1085,46 @@ "message": "Process completed with exit code 1.", "raw_details": "" } + ], + "128079212951": [ + { + "path": ".github", + "start_line": 130, + "end_line": 130, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128079213109": [ + { + "path": ".github", + "start_line": 130, + "end_line": 130, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128079213211": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } ] }, "logs": { - "128078674151": "2026-11-06T18:42:31.0413375Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T18:42:43.5529901Z ##[error]The operation was canceled.\n2026-11-06T18:42:43.5656287Z Cleaning up orphan processes\n" + "128078674151": "2026-11-06T18:42:31.0413375Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T18:42:43.5529901Z ##[error]The operation was canceled.\n2026-11-06T18:42:43.5656287Z Cleaning up orphan processes\n", + "128079212951": "2026-11-06T18:42:41.1643719Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T18:42:53.6869870Z ##[error]The operation was canceled.\n", + "128079213109": "2026-11-06T18:42:35.0486149Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T18:42:47.5624672Z ##[error]The operation was canceled.\n", + "128079213211": "2026-11-06T18:42:38.0453932Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T18:42:50.5615051Z ##[error]The operation was canceled.\n" }, "total_count": 48 } diff --git a/.github/scripts/tests/fixtures/runner-loss-rerun/run-42277969418.json b/.github/scripts/tests/fixtures/runner-loss-rerun/run-42277969418.json index 77461a61e12..ee38d22d965 100644 --- a/.github/scripts/tests/fixtures/runner-loss-rerun/run-42277969418.json +++ b/.github/scripts/tests/fixtures/runner-loss-rerun/run-42277969418.json @@ -970,10 +970,130 @@ "message": "Process completed with exit code 1.", "raw_details": "" } + ], + "128101015916": [ + { + "path": ".github", + "start_line": 130, + "end_line": 130, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101015978": [ + { + "path": ".github", + "start_line": 130, + "end_line": 130, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016153": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016200": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016304": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016340": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016402": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016432": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016453": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } + ], + "128101016461": [ + { + "path": ".github", + "start_line": 133, + "end_line": 133, + "annotation_level": "failure", + "title": "", + "message": "The operation was canceled.", + "raw_details": "" + } ] }, "logs": { - "128101016102": "2026-11-06T19:24:29.1450769Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:29.1898916Z ##[error]The operation was canceled.\n2026-11-06T19:24:29.1977091Z Cleaning up orphan processes\n" + "128101016102": "2026-11-06T19:24:29.1450769Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:29.1898916Z ##[error]The operation was canceled.\n2026-11-06T19:24:29.1977091Z Cleaning up orphan processes\n", + "128101015916": "2026-11-06T19:24:29.1391073Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.6585509Z ##[error]The operation was canceled.\n", + "128101015978": "2026-11-06T19:24:29.1982327Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.7170843Z ##[error]The operation was canceled.\n", + "128101016153": "2026-11-06T19:24:29.1786229Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.6972420Z ##[error]The operation was canceled.\n", + "128101016200": "2026-11-06T19:24:29.1721198Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.6975527Z ##[error]The operation was canceled.\n", + "128101016304": "2026-11-06T19:24:29.1377822Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.6673266Z ##[error]The operation was canceled.\n", + "128101016340": "2026-11-06T19:24:29.1341317Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.6500655Z ##[error]The operation was canceled.\n", + "128101016402": "2026-11-06T19:24:29.1167345Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.6423716Z ##[error]The operation was canceled.\n", + "128101016432": "2026-11-06T19:24:29.0692803Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.5851488Z ##[error]The operation was canceled.\n", + "128101016453": "2026-11-06T19:24:29.2339015Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.7586244Z ##[error]The operation was canceled.\n", + "128101016461": "2026-11-06T19:24:29.1057916Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-06T19:24:41.6269036Z ##[error]The operation was canceled.\n" }, "total_count": 48 } diff --git a/.github/scripts/tests/fixtures/runner-loss-rerun/run-43285064435.json b/.github/scripts/tests/fixtures/runner-loss-rerun/run-43285064435.json new file mode 100644 index 00000000000..c0b9b6f7d69 --- /dev/null +++ b/.github/scripts/tests/fixtures/runner-loss-rerun/run-43285064435.json @@ -0,0 +1,360 @@ +{ + "source": "GET /repos/paperclipai/paperclip/actions/runs/43285064435/attempts/1 (+ jobs, annotations and job-log error lines), trimmed", + "run": { + "id": 43285064435, + "name": "PR", + "head_sha": "cd287efba2ff0c557f0c63fc78d5ad1d48f192e8", + "path": ".github/workflows/pr.yml", + "event": "pull_request", + "status": "completed", + "conclusion": "cancelled", + "html_url": "https://github.com/paperclipai/paperclip/actions/runs/43285064435", + "run_attempt": 1, + "repository": { + "id": 1170821064, + "full_name": "paperclipai/paperclip" + }, + "head_repository": { + "id": 1170821064, + "full_name": "paperclipai/paperclip" + } + }, + "jobs": [ + { + "id": 131416164450, + "name": "ci / gate / Select trusted runner", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492147, + "name": "ci / policy", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492206, + "name": "ci / Typecheck + Release Registry", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492248, + "name": "ci / Verify Paperclip Runner (static checks)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492288, + "name": "ci / Runner support suite", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492337, + "name": "ci / Verify Paperclip Runner (rust)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492390, + "name": "ci / Build", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492402, + "name": "ci / Canary Dry Run", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492420, + "name": "ci / Verify Paperclip Runner (vitest package (3/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492421, + "name": "ci / Sandbox provider tests", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492424, + "name": "ci / Docker context integrity", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492430, + "name": "ci / Verify Paperclip Runner (vitest native server)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492442, + "name": "ci / Verify Paperclip Runner (vitest package (2/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492489, + "name": "ci / Verify Paperclip Runner (vitest package (1/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492538, + "name": "ci / e2e shard (5/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492565, + "name": "ci / e2e shard (1/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492568, + "name": "ci / e2e shard (2/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492582, + "name": "ci / e2e shard (6/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492588, + "name": "ci / e2e shard (7/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492592, + "name": "ci / e2e shard (4/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416492708, + "name": "ci / e2e shard (3/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493348, + "name": "ci / e2e shard (8/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493582, + "name": "ci / Verify serialized server suites (3/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493601, + "name": "ci / Verify serialized server suites (4/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493630, + "name": "ci / Verify serialized server suites (2/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493633, + "name": "ci / Verify serialized server suites (1/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493669, + "name": "ci / Verify serialized server suites (5/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493759, + "name": "ci / Verify serialized server suites (7/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493766, + "name": "ci / Verify serialized server suites (9/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493829, + "name": "ci / Verify serialized server suites (8/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416493947, + "name": "ci / General tests (server (5/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494052, + "name": "ci / General tests (server (1/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494077, + "name": "ci / General tests (server (3/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494102, + "name": "ci / General tests (server (7/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494186, + "name": "ci / General tests (server (4/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494194, + "name": "ci / General tests (workspaces-c)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494201, + "name": "ci / General tests (chat (3/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494251, + "name": "ci / General tests (server (12/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494281, + "name": "ci / General tests (server (2/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494286, + "name": "ci / General tests (chat (1/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494333, + "name": "ci / General tests (workspaces-a (1/2))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494339, + "name": "ci / General tests (server (10/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494340, + "name": "ci / General tests (server (9/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494376, + "name": "ci / General tests (chat (2/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494446, + "name": "ci / General tests (server (6/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494459, + "name": "ci / General tests (server (8/12))", + "status": "completed", + "conclusion": "cancelled" + }, + { + "id": 131416494489, + "name": "ci / General tests (workspaces-b)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494538, + "name": "ci / Verify serialized server suites (6/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494546, + "name": "ci / General tests (server (11/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494552, + "name": "ci / General tests (workspaces-a (2/2))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131416494939, + "name": "ci / Select Vitest files", + "status": "completed", + "conclusion": "skipped" + }, + { + "id": 131421415244, + "name": "ci / e2e", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131424041299, + "name": "ci / verify", + "status": "completed", + "conclusion": "failure" + } + ], + "annotations": { + "131416494459": [ + { + "annotation_level": "failure", + "message": "The operation was canceled." + } + ], + "131424041299": [ + { + "annotation_level": "failure", + "message": "Process completed with exit code 1." + } + ] + }, + "logs": { + "131416494459": "2026-11-12T19:03:20.1001059Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-12T19:03:32.6527460Z ##[error]The operation was canceled.\n" + }, + "total_count": 53 +} diff --git a/.github/scripts/tests/fixtures/runner-loss-rerun/run-43325855069.json b/.github/scripts/tests/fixtures/runner-loss-rerun/run-43325855069.json new file mode 100644 index 00000000000..314dc2cd82d --- /dev/null +++ b/.github/scripts/tests/fixtures/runner-loss-rerun/run-43325855069.json @@ -0,0 +1,363 @@ +{ + "source": "GET /repos/paperclipai/paperclip/actions/runs/43325855069/attempts/1 (+ jobs, annotations and job-log error lines), trimmed", + "run": { + "id": 43325855069, + "name": "PR", + "head_sha": "4b4f6b2ad0fac4ede9f4e20a56e3c93fac5577d5", + "path": ".github/workflows/pr.yml", + "event": "pull_request", + "status": "completed", + "conclusion": "failure", + "html_url": "https://github.com/paperclipai/paperclip/actions/runs/43325855069", + "run_attempt": 1, + "repository": { + "id": 1170821064, + "full_name": "paperclipai/paperclip" + }, + "head_repository": { + "id": 1170821064, + "full_name": "paperclipai/paperclip" + } + }, + "jobs": [ + { + "id": 131557987038, + "name": "ci / gate / Select trusted runner", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292300, + "name": "ci / Docker context integrity", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292349, + "name": "ci / Canary Dry Run", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292381, + "name": "ci / Runner support suite", + "status": "completed", + "conclusion": "failure" + }, + { + "id": 131558292405, + "name": "ci / Typecheck + Release Registry", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292466, + "name": "ci / policy", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292573, + "name": "ci / Build", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292627, + "name": "ci / Verify Paperclip Runner (vitest package (1/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292664, + "name": "ci / Verify Paperclip Runner (static checks)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292669, + "name": "ci / Verify Paperclip Runner (vitest package (2/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292679, + "name": "ci / e2e shard (8/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292686, + "name": "ci / Verify Paperclip Runner (vitest native server)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292707, + "name": "ci / Verify Paperclip Runner (vitest package (3/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292731, + "name": "ci / e2e shard (5/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292738, + "name": "ci / e2e shard (2/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292751, + "name": "ci / e2e shard (1/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292779, + "name": "ci / e2e shard (4/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292841, + "name": "ci / e2e shard (3/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558292887, + "name": "ci / e2e shard (7/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293043, + "name": "ci / e2e shard (6/8)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293328, + "name": "ci / Verify serialized server suites (4/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293330, + "name": "ci / Verify serialized server suites (2/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293380, + "name": "ci / Verify serialized server suites (7/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293389, + "name": "ci / Verify serialized server suites (3/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293399, + "name": "ci / Verify serialized server suites (8/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293420, + "name": "ci / Verify serialized server suites (1/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293433, + "name": "ci / Verify serialized server suites (5/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293450, + "name": "ci / Verify serialized server suites (6/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293683, + "name": "ci / Verify serialized server suites (9/9)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293690, + "name": "ci / General tests (server (12/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293701, + "name": "ci / General tests (server (11/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293710, + "name": "ci / General tests (server (8/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293784, + "name": "ci / General tests (server (3/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293818, + "name": "ci / General tests (server (2/12))", + "status": "completed", + "conclusion": "cancelled" + }, + { + "id": 131558293819, + "name": "ci / General tests (workspaces-a (1/2))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293825, + "name": "ci / General tests (server (4/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293835, + "name": "ci / General tests (server (5/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293844, + "name": "ci / General tests (server (9/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293850, + "name": "ci / General tests (workspaces-a (2/2))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293852, + "name": "ci / General tests (server (1/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293858, + "name": "ci / General tests (chat (2/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293865, + "name": "ci / General tests (server (10/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293875, + "name": "ci / General tests (workspaces-b)", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293940, + "name": "ci / General tests (server (6/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558293992, + "name": "ci / General tests (chat (3/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558294007, + "name": "ci / General tests (chat (1/3))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558294057, + "name": "ci / General tests (server (7/12))", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131558294396, + "name": "ci / Sandbox provider tests", + "status": "completed", + "conclusion": "skipped" + }, + { + "id": 131558294604, + "name": "ci / Select Vitest files", + "status": "completed", + "conclusion": "skipped" + }, + { + "id": 131562309925, + "name": "ci / e2e", + "status": "completed", + "conclusion": "success" + }, + { + "id": 131564602271, + "name": "ci / verify", + "status": "completed", + "conclusion": "failure" + } + ], + "annotations": { + "131558292381": [ + { + "annotation_level": "failure", + "message": "The operation was canceled." + }, + { + "annotation_level": "failure", + "message": "gateway_indexing_incomplete" + }, + { + "annotation_level": "failure", + "message": "gateway_indexing_incomplete" + } + ], + "131558293818": [ + { + "annotation_level": "failure", + "message": "The operation was canceled." + } + ], + "131564602271": [ + { + "annotation_level": "failure", + "message": "Process completed with exit code 1." + } + ] + }, + "logs": { + "131558292381": "2026-11-12T23:13:37.4339910Z ##[error]gateway_indexing_incomplete\n2026-11-12T23:13:37.4368921Z ##[error]gateway_indexing_incomplete\n2026-11-12T23:15:01.1805404Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-12T23:15:13.7401251Z ##[error]The operation was canceled.\n", + "131558293818": "2026-11-12T23:15:36.1981336Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n2026-11-12T23:15:48.7226826Z ##[error]The operation was canceled.\n" + }, + "total_count": 51 +} diff --git a/.github/scripts/tests/runner-loss-rerun.test.mjs b/.github/scripts/tests/runner-loss-rerun.test.mjs index bdc89f1d986..819f160881e 100644 --- a/.github/scripts/tests/runner-loss-rerun.test.mjs +++ b/.github/scripts/tests/runner-loss-rerun.test.mjs @@ -13,10 +13,13 @@ import { const fixture = (runId) => JSON.parse(readFileSync( new URL(`./fixtures/runner-loss-rerun/run-${runId}.json`, import.meta.url), "utf8", )); -const MIXED = 42271918832; // six lost runners, one shutdown in the log, one real test timeout +const MIXED = 42271918832; // six lost runners, four shutdowns in the log, one real test timeout const REAL = 42264785415; // a real assertion failure const ALL_LOST = 42272083862; // one lost runner -const LOG_ONLY = 42277969418; // shutdown signal visible only in the job log +const LOG_ONLY = 42277969418; // shutdown signals visible only in the job logs +const CANCELLED_RUN = 43285064435; +const NOISY_LOST = 43325855069; +const CANCELLED_MESSAGE = "The operation was canceled."; const workflow = readFileSync(new URL("../../workflows/ci-runner-loss-rerun.yml", import.meta.url), "utf8"); const json = (body, headers = {}) => new Response(JSON.stringify(body), { @@ -58,7 +61,7 @@ function fakeGithub(data, { if (match) return json(data.annotations[match[1]] ?? []); match = route.match(/^\/actions\/jobs\/(\d+)\/logs$/); if (match) return new Response(data.logs[match[1]] ?? "", { status: 200 }); - if (route === `/commits/${run.head_sha}/pulls`) return json(pulls ?? [openPr]); + if (route === `/commits/${run.head_sha}/pulls`) return json((typeof pulls === "function" ? pulls(calls) : pulls) ?? [openPr]); if (route === "/actions/workflows/pr.yml/runs") { const runs = prRuns ?? [{ id: run.id, conclusion: "failure" }]; return json({ total_count: runs.length, workflow_runs: runs }); @@ -106,19 +109,131 @@ test("a shutdown signal found only in the job log counts as runner loss", async assert.deepEqual(data.annotations["128101016102"].map((annotation) => annotation.message), ["The operation was canceled."]); const { decision, calls } = await runMain(data); assert.equal(decision.rerun, true); - assert.match(decision.jobs[0].evidence, /job log/); + assert.equal(decision.jobs.length, 11); + assert.ok(decision.jobs.every((job) => job.lost && /job log/.test(job.evidence))); assert.ok(calls.some((call) => call.path.endsWith("/actions/jobs/128101016102/logs"))); assert.equal(posted(calls).length, 1); }); +test("a cancelled run whose cancelled job lost its runner is re-run once", async () => { + const data = fixture(CANCELLED_RUN); + assert.equal(data.run.conclusion, "cancelled"); + const { decision, calls } = await runMain(data, {}, { conclusion: "cancelled" }); + assert.equal(decision.rerun, true); + assert.deepEqual(decision.jobs.map((job) => [job.name, job.lost]), [["ci / General tests (server (8/12))", true]]); + assert.match(decision.jobs[0].evidence, /job log/); + assert.deepEqual(posted(calls).map((call) => call.path), + [`/repos/paperclipai/paperclip/actions/runs/${CANCELLED_RUN}/rerun-failed-jobs`]); +}); + +test("runner loss in the log wins over error annotations the workload printed", async () => { + const data = fixture(NOISY_LOST); + const suite = data.jobs.find((job) => job.name === "ci / Runner support suite"); + assert.ok(data.annotations[suite.id].some((annotation) => annotation.message === "gateway_indexing_incomplete")); + const { decision, calls } = await runMain(data); + assert.equal(decision.rerun, true); + assert.deepEqual(decision.jobs.map((job) => [job.name, job.lost]), [ + ["ci / Runner support suite", true], + ["ci / General tests (server (2/12))", true], + ]); + assert.equal(posted(calls).length, 1); +}); + +function cancelEverything(data, { log = `2026-11-12T19:03:32.0000000Z ##[error]${CANCELLED_MESSAGE}\n` } = {}) { + data.annotations = {}; + data.logs = {}; + for (const [index, job] of data.jobs.entries()) { + if (job.name.startsWith("ci / gate / ")) continue; + job.conclusion = "cancelled"; + if (index % 4 === 3) continue; + data.annotations[job.id] = [{ annotation_level: "failure", message: CANCELLED_MESSAGE }]; + data.logs[job.id] = log; + } + return data; +} + +test("a run superseded by a new push is not re-run, and no job is classified", async () => { + const data = cancelEverything(fixture(CANCELLED_RUN)); + assert.ok(data.jobs.filter((job) => job.conclusion === "cancelled").length >= 40); + const { decision, calls } = await runMain(data, { + pulls: [{ state: "open", base: { repo: { id: 1170821064 } }, head: { sha: "0".repeat(40), repo: { id: 1170821064 } } }], + }, { conclusion: "cancelled" }); + assert.equal(decision.rerun, false); + assert.match(decision.reason, /no open pull request/); + assert.equal(calls.some((call) => call.path.includes("/check-runs/") || call.path.endsWith("/logs")), false); + assert.equal(posted(calls).length, 0); +}); + +test("a push while job logs are read stops the re-run", async () => { + const data = fixture(CANCELLED_RUN); + const moved = [{ state: "open", base: { repo: { id: 1170821064 } }, head: { sha: "0".repeat(40), repo: { id: 1170821064 } } }]; + const { decision, calls } = await runMain(data, { + pulls: (seen) => (seen.some((call) => call.path.endsWith("/logs")) ? moved : undefined), + }, { conclusion: "cancelled" }); + assert.equal(decision.rerun, false); + assert.match(decision.reason, /no open pull request/); + assert.equal(decision.jobs[0].lost, true); + assert.equal(calls.filter((call) => call.path.endsWith("/pulls")).length, 2); + assert.equal(posted(calls).length, 0); +}); + +test("a run a person cancelled is not re-run", async () => { + const data = cancelEverything(fixture(CANCELLED_RUN)); + const { decision, calls } = await runMain(data, {}, { conclusion: "cancelled" }); + assert.equal(decision.rerun, false); + assert.ok(decision.jobs.length >= 40); + assert.equal(decision.jobs.some((job) => job.lost), false); + assert.match(decision.reason, /failed jobs did not lose their runner/); + assert.equal(posted(calls).length, 0); +}); + +test("a cancelled run with one lost job and one real test failure is not re-run", async () => { + const data = fixture(CANCELLED_RUN); + const failing = data.jobs.find((job) => job.name === "ci / General tests (server (1/12))"); + failing.conclusion = "failure"; + data.annotations[failing.id] = [ + { annotation_level: "failure", message: "AssertionError: expected 'queued' to be 'running'" }, + { annotation_level: "failure", message: "Process completed with exit code 1." }, + ]; + const { decision, calls } = await runMain(data, {}, { conclusion: "cancelled" }); + assert.equal(decision.rerun, false); + assert.deepEqual(decision.jobs.map((job) => [job.name, job.lost]), [ + ["ci / General tests (server (1/12))", false], + ["ci / General tests (server (8/12))", true], + ]); + assert.match(decision.reason, /1 of 2 failed jobs did not lose their runner/); + assert.equal(posted(calls).length, 0); +}); + +test("a cancelled run is re-run at most once", async () => { + const { decision, calls } = await runMain(fixture(CANCELLED_RUN), { + mutateRun: (run) => ({ ...run, run_attempt: 2 }), + }, { conclusion: "cancelled" }); + assert.equal(decision.rerun, false); + assert.match(decision.reason, /attempt 2/); + assert.deepEqual(calls.map((call) => call.path), [`/repos/paperclipai/paperclip/actions/runs/${CANCELLED_RUN}`]); +}); + +test("a cancelled routing gate is left for a human re-run", async () => { + const data = fixture(CANCELLED_RUN); + const gate = data.jobs.find((job) => job.name === "ci / gate / Select trusted runner"); + gate.conclusion = "cancelled"; + data.annotations[gate.id] = [{ annotation_level: "failure", message: CANCELLED_MESSAGE }]; + data.logs[gate.id] = data.logs[Object.keys(data.logs)[0]]; + const { decision, calls } = await runMain(data, {}, { conclusion: "cancelled" }); + assert.equal(decision.rerun, false); + assert.match(decision.jobs.find((job) => job.id === gate.id).evidence, /routing gate/); + assert.equal(posted(calls).length, 0); +}); + test("mixed runner loss and a real test failure: no re-run", async () => { const { decision, calls, summary } = await runMain(fixture(MIXED)); assert.equal(decision.rerun, false); - assert.equal(decision.jobs.length, 8); + assert.equal(decision.jobs.length, 11); assert.deepEqual(decision.jobs.filter((job) => !job.lost).map((job) => job.name), ["ci / General tests (workspaces-a (1/2))"]); assert.equal(decision.jobs.find((job) => job.name === "ci / Verify Paperclip Runner (vitest package)").lost, true); assert.equal(posted(calls).length, 0); - assert.match(decision.reason, /1 of 8 failed jobs did not lose their runner/); + assert.match(decision.reason, /1 of 11 failed jobs did not lose their runner/); assert.match(summary, /\*\*No automatic re-run\*\*/); }); @@ -209,7 +324,7 @@ test("job listing follows Link pagination across pages", async () => { const pages = github.calls.filter((call) => call.path.endsWith("/attempts/1/jobs")); assert.deepEqual(pages.map((call) => new URLSearchParams(call.query).get("page")), [null, "2", "3"]); // Failed jobs on pages 2 and 3 are all classified. - assert.equal(decision.jobs.length, 8); + assert.equal(decision.jobs.length, 11); assert.equal(decision.rerun, false); }); @@ -236,9 +351,20 @@ test("classification is conservative about cancelled jobs", async () => { // A job timeout also cancels the step, but adds its own failure annotation. const timedOut = await classifyJob({ id: 1 }, { annotations: [{ annotation_level: "failure", message: "The job has exceeded the maximum execution time of 30m0s" }, ...cancelled], - readLog: async () => { throw new Error("log must not be read"); }, + readLog: async () => "##[error]The job has exceeded the maximum execution time of 30m0s\n##[error]The operation was canceled.\n", }); assert.equal(timedOut.lost, false); + assert.match(timedOut.evidence, /maximum execution time/); + const notStarted = await classifyJob({ id: 1, conclusion: "cancelled" }, { + annotations: [], + readLog: async () => { throw new Error("log must not be read"); }, + }); + assert.equal(notStarted.lost, false); + const exitOnly = await classifyJob({ id: 1 }, { + annotations: [{ annotation_level: "failure", message: "Process completed with exit code 1." }], + readLog: async () => { throw new Error("log must not be read"); }, + }); + assert.equal(exitOnly.lost, false); // Notices and warnings are not failure evidence. const warning = await classifyJob({ id: 1 }, { annotations: [{ annotation_level: "warning", message: "The self-hosted runner lost communication with the server." }], @@ -250,7 +376,7 @@ test("classification is conservative about cancelled jobs", async () => { assert.equal(logShowsRunnerLoss(fixture(MIXED).logs["128078674151"]), true); }); -test("a real failure before the runner was lost is not counted as runner loss", async () => { +test("runner-loss evidence wins over other failure annotations in the same job", async () => { const lostMessage = "The self-hosted runner lost communication with the server. Verify the machine is running."; const noLog = async () => { throw new Error("log must not be read"); }; // A test fails, then the runner is lost during an always() upload step. @@ -262,8 +388,8 @@ test("a real failure before the runner was lost is not counted as runner loss", ], readLog: noLog, }); - assert.equal(testThenLost.lost, false); - assert.match(testThenLost.evidence, /Test timed out/); + assert.equal(testThenLost.lost, true); + assert.match(testThenLost.evidence, /lost communication/); // The order of the annotations does not matter. const lostThenExit = await classifyJob({ id: 1 }, { annotations: [ @@ -272,7 +398,22 @@ test("a real failure before the runner was lost is not counted as runner loss", ], readLog: noLog, }); - assert.equal(lostThenExit.lost, false); + assert.equal(lostThenExit.lost, true); + const noisy = [ + { annotation_level: "failure", message: "gateway_indexing_incomplete" }, + { annotation_level: "failure", message: CANCELLED_MESSAGE }, + ]; + const noisyLost = await classifyJob({ id: 1 }, { + annotations: noisy, + readLog: async () => "##[error]gateway_indexing_incomplete\n##[error]The runner has received a shutdown signal.\n", + }); + assert.equal(noisyLost.lost, true); + const noisyCancelled = await classifyJob({ id: 1 }, { + annotations: noisy, + readLog: async () => "##[error]gateway_indexing_incomplete\n##[error]The operation was canceled.\n", + }); + assert.equal(noisyCancelled.lost, false); + assert.match(noisyCancelled.evidence, /gateway_indexing_incomplete/); // Runner loss with a cancellation only is still runner loss. const lostAndCancelled = await classifyJob({ id: 1 }, { annotations: [ @@ -292,14 +433,15 @@ test("summary cells cannot break the table", () => { assert.match(summary, /\| ci \/ a\\\|b \| no \| line one line \\\| two \|/); }); -test("workflow acts only on failed first attempts of the canonical PR workflow", () => { +test("workflow acts only on failed or cancelled first attempts of the canonical PR workflow", () => { const condition = workflow.match(/^ {4}if: >-\n((?: {6}.+\n)+)/m)?.[1].replace(/\s+/g, " ").trim(); assert.equal(condition, [ "github.repository == 'paperclipai/paperclip' &&", "github.repository_id == '1170821064' &&", "github.event.workflow_run.event == 'pull_request' &&", "github.event.workflow_run.path == '.github/workflows/pr.yml' &&", - "github.event.workflow_run.conclusion == 'failure' &&", + "(github.event.workflow_run.conclusion == 'failure' ||", + "github.event.workflow_run.conclusion == 'cancelled') &&", "github.event.workflow_run.run_attempt == 1", ].join(" ")); assert.match(workflow, /^on:\n {2}workflow_run:\n {4}workflows: \[PR\]\n {4}types: \[completed\]$/m); diff --git a/.github/workflows/ci-runner-loss-rerun.yml b/.github/workflows/ci-runner-loss-rerun.yml index bc718fdb95b..4278198db61 100644 --- a/.github/workflows/ci-runner-loss-rerun.yml +++ b/.github/workflows/ci-runner-loss-rerun.yml @@ -1,7 +1,8 @@ name: CI runner-loss rerun -# Self-hosted AWS runners are sometimes lost mid-job. When every failed job of -# a first PR CI attempt lost its runner, re-run the failed jobs once. This is +# Self-hosted AWS runners are sometimes lost mid-job. When every failed or +# cancelled job of a first PR CI attempt lost its runner, re-run the failed +# jobs once. A spot reclaim often concludes the run `cancelled`. This is # what a maintainer's "Re-run failed jobs" click does; github-actions[bot] # becomes attempt 2's triggering actor. See "Trusted PR Workflow" in # doc/DEVELOPING.md. @@ -31,7 +32,8 @@ jobs: github.repository_id == '1170821064' && github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.path == '.github/workflows/pr.yml' && - github.event.workflow_run.conclusion == 'failure' && + (github.event.workflow_run.conclusion == 'failure' || + github.event.workflow_run.conclusion == 'cancelled') && github.event.workflow_run.run_attempt == 1 # GitHub-hosted on purpose: this job must not depend on the fleet it repairs. runs-on: ubuntu-latest diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 95a99fa0132..7bb129325df 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -187,14 +187,21 @@ AWS fleet. A stale admission roster can allocate only the short metadata gate; the fresh CODEOWNERS check still denies PR execution for a removed owner. AWS runners are sometimes lost mid-job. `ci-runner-loss-rerun.yml` re-runs the -failed jobs of a PR's first CI attempt once when every failed job lost its -runner. A lost runner is recognized by the check-run annotation "lost -communication with the server" or "received a shutdown signal". When the only -annotation is "The operation was canceled.", the job log is checked for the -same messages. The `verify` and `e2e` aggregates are not counted. Any other -failure, a failed routing gate, or a PR whose head has moved prevents the -automatic re-run. The workflow job summary lists each failed job and its -evidence. Like a maintainer's "Re-run failed jobs", the re-run reuses the +failed jobs of a PR's first CI attempt once when every failed or cancelled job +lost its runner. A spot reclaim often ends the job, and the run, as +`cancelled`. A lost runner is recognized by the check-run annotation "lost +communication with the server" or "received a shutdown signal". When a job has +the annotation "The operation was canceled.", the job log is checked for the +same messages. This evidence counts even if the job also has other error +annotations, so a test that really failed just before a reclaim gets one +wasted re-run. A cancelled job without this evidence, such as a job a person +cancelled, counts as a real failure. The `verify` and `e2e` aggregates are not +counted. Any other failure, a failed or cancelled routing gate, or a PR whose +head has moved prevents the automatic re-run. The head check runs before any +job is classified, so a run cancelled by a newer push costs no log reads. It +runs again just before the re-run, because a re-run of an old run joins the +PR's `cancel-in-progress` concurrency group and would cancel the newer CI. The +workflow job summary lists each failed or cancelled job and its evidence. Like a maintainer's "Re-run failed jobs", the re-run reuses the gate's successful outputs, including its AWS admission. Attempt 2's triggering actor is `github-actions[bot]`, so `profile-ci` does not export that attempt. Later attempts are never re-run automatically.