From 081dacba1d44e5b2b357d7f5105adda82f99e450 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 08:23:49 -0600 Subject: [PATCH 01/19] perf(workspaces): inspect only due workspaces and wait for a holding run's release (#21617) 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 terminal workspace sweep stores one deadline per workspace: cooldown end, compaction, cleanup retry, Git idle. > - When any deadline was due, the worker ran a full rotation over every open candidate workspace. That costs a task tree read and more for each one. > - A workspace held by a `running` run kept a past deadline, so the 5-minute deadline rotation came back for it forever. A run that never finishes would keep the instance awake indefinitely. > - This pull request makes a due deadline inspect only the due workspaces. A held workspace waits for its run instead of for a timer. > - The benefit is that an idle instance does work only for workspaces whose deadline really arrived. The cost no longer grows with the number of open workspaces. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** How the terminal workspace worker (`server/src/services/terminal-workspace-work.ts`) acts on due deadlines and on workspaces held by an active run. **Current behavior** `hasPending` reads `nextTerminalWorkspaceSweepAt`. When the earliest deadline is past, the next run starts a full keyset rotation, 50 workspaces per page with 1 second between pages, over every candidate. A workspace whose issue still has a `queued` or `running` run is skipped, but the archive deadline set earlier in the same pass stays. It is already past, so the rotation repeats every 5 minutes. **Proposed behavior** - When the run fires for a due deadline, the worker takes the due workspace ids from the service (`takeDueTerminalWorkspaceTargets`) and runs a targeted inspection of only those workspaces. The service first clears the deadlines of the targeted workspaces; the inspection sets fresh ones. - If more than 50 workspaces are due, or a due deadline belongs to the isolated source, nested clone or task directory work, the worker still runs a full rotation. Startup still runs a full rotation. - A workspace skipped because a run holds it drops its deadline. - `writeRunStatus` (`server/src/services/heartbeat/run-lifecycle.ts`) publishes `issue:` to the terminal workspace queue when a run reaches a terminal status. That targeted inspection reaches the workspace the run held. - **Backstop.** About 200 code paths write `heartbeat_runs` directly (reapers, recovery terminalization, bulk cancels), and they do not pass through `writeRunStatus`. So the worker keeps a full rotation as a backstop, armed only by activity, like the recovery backstop from #21552: - Any terminal-workspace hint arms it. - Once armed, a full rotation runs at most once per hour (`TERMINAL_WORKSPACE_BACKSTOP_MS`) after the previous full rotation. - An idle instance with no hint schedules nothing. - A missed release hint therefore delays archiving by at most one hour after activity, without a restart. - The hour is a compromise. On master today, the 5-minute rotation re-reads every candidate. On the hosted instance that is about 1,000 finished remote workspaces, roughly 3,000 statements per lap. The hourly backstop re-reads them at most once per hour while there is activity, about 1 statement per second averaged. **Reason and benefit** Background work must be driven by deadlines and change notifications, and its cost must not grow with the backlog. Every guarantee keeps a named trigger: - cooldown end, compaction, retry backoff and Git idle each have a stored deadline, and a due deadline inspects exactly that workspace; - the release of a holding run publishes a hint; - task status changes and workspace writes still publish hints; - startup still reconciles everything. ## What Changed - `server/src/services/execution-workspaces.ts`: - New `takeDueTerminalWorkspaceTargets()`. - A targeted inspection clears the deadlines of its targets before it inspects them. - A workspace skipped for an active run drops its deadline. - `server/src/services/terminal-workspace-work.ts`: a due run uses the due targets instead of a full rotation, unless they overflow or a non-workspace deadline is due. A due run that finds nothing due does nothing. Any hint arms the hourly backstop rotation. - `server/src/services/heartbeat/run-lifecycle.ts`: a terminal run status hints the run's task to the terminal workspace queue. - `server/src/__tests__/terminal-workspace-deadlines.test.ts`: four new tests on real PostgreSQL. They use the real coordinator and worker on a fake clock. - `server/src/__tests__/terminal-workspace-idle.test.ts` (from #21616): its idle window now bounds the number of sweeps instead of requiring zero targeted sweeps, because a due deadline is now a targeted inspection. ## Verification - `inspects only the workspace whose cooldown ends, however many trees stay open`: 60 workspaces with open task trees and 1 done workspace whose 1-day cooldown ends 1 hour later. - Before the change: after startup, every due deadline starts a full rotation (27 full sweeps in 2 hours). - After the change: no full rotation; the done workspace is inspected alone (`checked: 1`) once its cooldown ends; fewer than 200 statements in 2 hours. - `waits for the release of the run that holds a workspace instead of rechecking it`: a done workspace held by a `running` run. - Before the change: a full rotation every 5 minutes (22 sweeps in 2 hours). - After the change: 0 statements in 2 idle hours. When the run is set to `succeeded` through the lifecycle, the workspace is inspected (`checked: 1`, `skippedActiveRun: 0`). - `leaves a thousand finished remote workspaces unread at idle`. This is the hosted state: 1,000 `active` remote workspaces with a location, a committed snapshot and a task done 5 days ago, and zero runs. - After startup and 2 idle hours: no full rotation. No remote workspace is read again; the only inspections are of the one due local workspace. Statements stay within 10 per inspection. - On master, every due deadline re-reads all 1,000. - `archives a workspace whose run ended outside the run lifecycle within the activity-armed backstop`: - A workspace held by a `running` run. The run is set to `failed` by a direct `UPDATE`, so no release hint is published, and one unrelated hint arrives. - The workspace is archived within one hour and one minute, without a restart. - With the backstop scheduling disabled, it stays `active`. - `npx vitest run src/__tests__/terminal-workspace-deadlines.test.ts src/__tests__/terminal-workspace-work.test.ts src/__tests__/execution-workspaces-service.test.ts src/__tests__/isolated-task-directory-retention.test.ts src/__tests__/git-workspace-expiration.test.ts src/__tests__/workspace-delivery-cleanup.integration.test.ts src/__tests__/nested-clone-migration.test.ts src/__tests__/execution-workspace-compaction.test.ts src/__tests__/git-restore-point-expiration.test.ts` (in `server/`): 333 tests pass. - `pnpm check:module-boundaries` passes. Local fixture with #21616 applied as the base, 30 idle minutes on a fake clock, real PostgreSQL. Each fixture holds open trees, a stranded `running` holder, cooldown, done local workspaces with missing files, closed remote workspaces with and without a committed snapshot: | Workspaces | Before: sweeps | Before: statements | After: sweeps | After: statements | | --- | --- | --- | --- | --- | | 140 | 20 (full rotations) | 1,371 | 21 (targeted only) | 866 | | 420 | 84 (full rotations) | 6,597 | 33 (targeted only) | 3,272 | After the change, no sweep reads the task tree of a workspace whose tree is still open (`skippedNonTerminalTree` falls from 1,440 to 0 at 420 workspaces). What remains comes only from workspaces with a due retry or inspection backoff, so it grows with the number of stuck workspaces, not open ones. Per inspected workspace a pass issues the same 3–6 statements as before; batching them per page is a separate pull request. ## Risks - **A run that leaves `running` without `writeRunStatus`** does not hint. The activity-armed backstop catches it within one hour of activity, and startup reconciles. This pull request does not decide that a stranded run is gone; it waits for a status change. - **A workspace whose deadline is reset to "now"** (a reopen-pending flag within its grace period, task directory budget overflow) is inspected alone on each due run. The inspection backoff in `nextTerminalWorkspaceSweepAt` still spaces these runs. - **Workspaces without a stored deadline** (for example an undelivered workspace whose deadline was deleted) are inspected again only when a hint or the startup rotation reaches them. Before this change they were also reached by the rotation that a different workspace's deadline started. ## Open decision **Should a terminal workspace whose local files are gone be archived, or should it wait?** This pull request does not change the behaviour; it leaves the decision to the owner. Today such a workspace fails its close-readiness inspection and is reported as `skippedUndelivered`. A non-remote workspace keeps its past deadline, so the 5-minute inspection backoff re-inspects it again and again. That costs about 3–4 statements per stuck workspace every 5 minutes (from the local fixture: 255 inspections, 866 statements), and it never ends while the files stay missing. The cause is typically a replaced container. The two options: - **Archive it.** Nothing remains on disk to keep. - **Store a "files missing" state.** It is then inspected again only when a write announces a change. Either option removes this cost. Archiving also removes the row from later rotations. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] 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 --- .../terminal-workspace-deadlines.test.ts | 177 ++++++++++++++++++ .../__tests__/terminal-workspace-idle.test.ts | 2 +- server/src/services/execution-workspaces.ts | 10 + .../src/services/heartbeat/run-lifecycle.ts | 3 + .../src/services/terminal-workspace-work.ts | 33 +++- 5 files changed, 221 insertions(+), 4 deletions(-) create mode 100644 server/src/__tests__/terminal-workspace-deadlines.test.ts diff --git a/server/src/__tests__/terminal-workspace-deadlines.test.ts b/server/src/__tests__/terminal-workspace-deadlines.test.ts new file mode 100644 index 00000000000..e1d70a53efb --- /dev/null +++ b/server/src/__tests__/terminal-workspace-deadlines.test.ts @@ -0,0 +1,177 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, companies, createDb, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, issues, projects, type Db } from "@paperclipai/db"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { executionWorkspaceService } from "../services/execution-workspaces.js"; +import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from "../services/heartbeat/run-lifecycle.js"; +import { notifyTerminalWorkspaceWork, registerTerminalWorkspaceWork, TERMINAL_WORKSPACE_BACKSTOP_MS, TERMINAL_WORKSPACE_RETRY_MS } from "../services/terminal-workspace-work.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_TERMINAL_WORKSPACE_DEADLINE_TEST_DATABASE_URL"); +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const HOUR = 3_600_000; +const realSetTimeout = globalThis.setTimeout; +const realSleep = (ms: number) => new Promise(resolve => realSetTimeout(resolve, ms)); + +(support.supported ? describe : describe.skip)("terminal workspace deadlines", () => { + let temporary: Awaited> | undefined; + let db: Db; + let meter: ReturnType; + beforeAll(async () => { + if (!external) temporary = await startEmbeddedPostgresTestDatabase("terminal-workspace-deadlines-"); + const url = external ?? temporary!.connectionString; + db = createDb(url); + db.$client.options.onnotice = () => {}; + meter = meterDatabaseStatements(db, url); + }, 120_000); + afterEach(async () => { vi.useRealTimers(); await db.execute(sql`truncate companies cascade`); }); + afterAll(async () => { meter?.uninstall(); await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + + async function seed(input: { open: number; cooldownEndsInMs?: number; heldByRunningRun?: boolean }) { + const companyId = randomUUID(), projectId = randomUUID(), agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Deadlines", issuePrefix: `D${companyId.slice(0, 6)}` }); + await db.insert(projects).values({ id: projectId, companyId, name: "Project", status: "in_progress" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Agent", role: "engineer", status: "idle", adapterType: "process" }); + const old = new Date(Date.now() - 48 * HOUR); + const workspace = async (status: string, completedAt: Date | null, runId: string | null) => { + const id = randomUUID(), issueId = randomUUID(); + await db.insert(executionWorkspaces).values({ id, companyId, projectId, mode: "shared_workspace", strategyType: "project_primary", + name: id, status: "active", providerType: "local_fs", cwd: `/missing/${id}`, createdAt: old, updatedAt: old }); + await db.insert(issues).values({ id: issueId, companyId, projectId, title: status, status, executionWorkspaceId: id, + executionRunId: runId, completedAt, updatedAt: old }); + await db.update(executionWorkspaces).set({ sourceIssueId: issueId, updatedAt: old }).where(eq(executionWorkspaces.id, id)); + return { id, issueId }; + }; + for (let index = 0; index < input.open; index++) await workspace("in_progress", null, null); + let runId: string | null = null; + if (input.heldByRunningRun) { + runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running" }); + } + const target = await workspace("done", new Date(Date.now() - 24 * HOUR + (input.cooldownEndsInMs ?? -HOUR)), runId); + if (runId) await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: target.issueId } }).where(eq(heartbeatRuns.id, runId)); + return { companyId, runId, target }; + } + + function start(options: Parameters[1] = {}) { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + const service = executionWorkspaceService(db, { workspaceReaperCooldownDays: 1, workspaceCompactionDelayMs: HOUR, + terminalWorkspaceInspectionBackoffMs: TERMINAL_WORKSPACE_RETRY_MS, ...options }); + const sweeps: Array<{ targets: string[] | null; checked: number; skippedCooldown: number; skippedActiveRun: number }> = []; + let inFlight = 0; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => {} }); + const worker = registerTerminalWorkspaceWork(coordinator, { ...service, + sweepTerminalWorkspaces: async (limit, signal, options) => { + inFlight += 1; + const result = await service.sweepTerminalWorkspaces(limit, signal, options).finally(() => { inFlight -= 1; }); + sweeps.push({ targets: options?.targets ? [...options.targets.workspaceIds, ...options.targets.issueIds] : null, + checked: result.checked, skippedCooldown: (result as { skippedCooldown: number }).skippedCooldown, + skippedActiveRun: (result as { skippedActiveRun: number }).skippedActiveRun }); + return result; + } }, () => true); + const advance = async (ms: number) => { + for (let elapsed = 0; elapsed < ms; elapsed += 10_000) { + await vi.advanceTimersByTimeAsync(10_000); + do { await realSleep(10); await vi.advanceTimersByTimeAsync(1); } while (inFlight > 0); + } + }; + const settle = async (operation: Promise) => { + let done = false; + const result = operation.finally(() => { done = true; }); + while (!done) { await realSleep(5); await vi.advanceTimersByTimeAsync(1); } + return result; + }; + return { sweeps, coordinator, worker, advance, settle, stop: async () => { vi.useRealTimers(); await worker.stop(); await coordinator.stop(); } }; + } + + it("inspects only the workspace whose cooldown ends, however many trees stay open", async () => { + const f = await seed({ open: 60, cooldownEndsInMs: HOUR }); + const work = start(); + try { + await work.advance(5 * 60_000); + const startup = work.sweeps.length; + expect(startup).toBeGreaterThan(0); + expect(work.sweeps.at(-1)).toMatchObject({ targets: null }); + const before = meter.read().statements; + await work.advance(2 * HOUR); + const window = work.sweeps.slice(startup); + expect(window.filter(sweep => sweep.targets === null)).toEqual([]); + expect(window.some(sweep => sweep.targets?.includes(f.target.id) && sweep.checked === 1 && sweep.skippedCooldown === 0)).toBe(true); + expect(window.reduce((sum, sweep) => sum + sweep.checked, 0)).toBeLessThanOrEqual(window.length); + expect(meter.read().statements - before).toBeLessThan(200); + } finally { await work.stop(); } + }, 300_000); + + it("leaves a thousand finished remote workspaces unread at idle", async () => { + const f = await seed({ open: 0, cooldownEndsInMs: 30 * 60_000 }); + const [target] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.target.id)); + const old = new Date(Date.now() - 5 * 24 * HOUR); + const rows = Array.from({ length: 1000 }, () => ({ workspaceId: randomUUID(), issueId: randomUUID(), snapshotId: randomUUID() })); + for (let index = 0; index < rows.length; index += 250) { + const page = rows.slice(index, index + 250); + await db.insert(executionWorkspaces).values(page.map(row => ({ id: row.workspaceId, companyId: f.companyId, projectId: target!.projectId, + mode: "isolated_workspace", strategyType: "git_worktree", name: row.workspaceId, status: "active", providerType: "remote", + createdAt: old, updatedAt: old, metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: 1, + snapshotId: row.snapshotId, source: { kind: "empty" }, writerRunId: null, dirty: false, + location: { environmentId: randomUUID(), leaseId: randomUUID(), providerLeaseId: `sandbox-${row.workspaceId}`, remoteCwd: "/workspace" } } } }))); + await db.insert(issues).values(page.map(row => ({ id: row.issueId, companyId: f.companyId, projectId: target!.projectId, title: "done", + status: "done", executionWorkspaceId: row.workspaceId, completedAt: old, updatedAt: old }))); + await db.insert(executionWorkspaceSnapshots).values(page.map(row => ({ id: row.snapshotId, companyId: f.companyId, + executionWorkspaceId: row.workspaceId, sourceOperationId: randomUUID(), generation: 1, epoch: 1, status: "committed" as const }))); + for (const row of page) await db.update(executionWorkspaces).set({ sourceIssueId: row.issueId, updatedAt: old }) + .where(eq(executionWorkspaces.id, row.workspaceId)); + } + const work = start(); + try { + await work.advance(5 * 60_000); + const startup = work.sweeps.length; + expect(work.sweeps.reduce((sum, sweep) => sum + sweep.checked, 0)).toBe(1001); + const before = meter.read().statements; + await work.advance(2 * HOUR); + const window = work.sweeps.slice(startup); + expect(window.filter(sweep => sweep.targets === null)).toEqual([]); + expect(window.every(sweep => sweep.targets?.length === 1 && sweep.targets[0] === f.target.id && sweep.checked === 1)).toBe(true); + expect(meter.read().statements - before).toBeLessThan(10 * Math.max(window.length, 1)); + } finally { await work.stop(); } + }, 300_000); + + it("archives a workspace whose run ended outside the run lifecycle within the activity-armed backstop", async () => { + const f = await seed({ open: 10, heldByRunningRun: true }); + const work = start({ inspectGitCloseReadiness: async workspace => ({ statusInspectionSucceeded: true, warnings: [], git: { + repoRoot: null, workspacePath: workspace.cwd, branchName: null, baseRef: null, hasDirtyTrackedFiles: false, hasUntrackedFiles: false, + dirtyEntryCount: 0, untrackedEntryCount: 0, aheadCount: 0, behindCount: 0, isMergedIntoBase: true, createdByRuntime: false } }) }); + try { + await work.advance(5 * 60_000); + expect(work.sweeps.at(-1)).toMatchObject({ targets: null, skippedActiveRun: 1 }); + await work.settle(db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.runId!))); + await work.settle(db.transaction(tx => notifyTerminalWorkspaceWork(tx, `workspace:${randomUUID()}`))); + const releasedAt = Date.now(); + await work.advance(TERMINAL_WORKSPACE_BACKSTOP_MS + 60_000); + const [row] = await work.settle(db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.target.id))); + expect(row!.status).toBe("archived"); + expect(row!.closedAt!.getTime() - releasedAt).toBeLessThanOrEqual(TERMINAL_WORKSPACE_BACKSTOP_MS + 60_000); + } finally { await work.stop(); } + }, 300_000); + + it("waits for the release of the run that holds a workspace instead of rechecking it", async () => { + const f = await seed({ open: 10, heldByRunningRun: true }); + const work = start(); + try { + await work.advance(5 * 60_000); + expect(work.sweeps.at(-1)).toMatchObject({ targets: null, skippedActiveRun: 1 }); + const startup = work.sweeps.length; + const before = meter.read().statements; + await work.advance(2 * HOUR); + expect(work.sweeps.slice(startup)).toEqual([]); + expect(meter.read().statements - before).toBe(0); + vi.useRealTimers(); + await createHeartbeatLifecycle(db, { emitTerminalAgentTaskRun: vi.fn() } as unknown as HeartbeatLifecycleDependencies) + .setRunStatus(f.runId!, "succeeded", { finishedAt: new Date() }); + await vi.waitFor(() => expect(work.sweeps.slice(startup).some(sweep => sweep.targets?.includes(f.target.issueId) + && sweep.checked === 1 && sweep.skippedActiveRun === 0)).toBe(true), { timeout: 20_000 }); + } finally { await work.stop(); } + }, 300_000); +}); diff --git a/server/src/__tests__/terminal-workspace-idle.test.ts b/server/src/__tests__/terminal-workspace-idle.test.ts index c1bef7fc449..5abda8fe837 100644 --- a/server/src/__tests__/terminal-workspace-idle.test.ts +++ b/server/src/__tests__/terminal-workspace-idle.test.ts @@ -118,7 +118,7 @@ const realSleep = (ms: number) => new Promise(resolve => realSetTimeout(resolve, vi.useRealTimers(); const window = sweeps.slice(before.sweeps); expect(destroyCalls.length).toBe(before.destroys); - expect(window.filter(sweep => sweep.targeted)).toEqual([]); + expect(window.length).toBeLessThanOrEqual(12); expect(meter.read().statements - before.statements).toBeLessThan(5_000); for (const id of remote) { const [row] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, id)); diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 6ec8deb869e..7eeb921e750 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -3660,6 +3660,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic compacted: 0, compactionFailed: 0, }; + if (targets) for (const id of [...targets.workspaceIds, ...candidates.map(candidate => candidate.workspace.id)]) terminalWorkspaceDeadlines.delete(id); const readinessByWorkingTree = new Map>(); const backOffTerminalWorkspace = async (snapshot: ExecutionWorkspaceRow, failure: TerminalWorkspaceFailure) => { const [target] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, snapshot.id)); @@ -3914,6 +3915,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic if (await workspaceHasActiveRun(workspace)) { if (reopenPending) result.skippedReopened += 1; else result.skippedActiveRun += 1; + terminalWorkspaceDeadlines.delete(workspace.id); continue; } if (remoteWorkspace && isClosedExecutionWorkspaceStatus(workspace.status)) { @@ -4154,6 +4156,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } if (await workspaceHasActiveRun(workspace)) { result.skippedActiveRun += 1; + terminalWorkspaceDeadlines.delete(workspace.id); continue; } result.eligible += 1; @@ -4364,6 +4367,13 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } }, + takeDueTerminalWorkspaceTargets: (): { workspaceIds: string[]; rotation: boolean } => { + const at = now().getTime(); + const due = (deadlines: Map) => [...deadlines].filter(([, deadline]) => deadline <= at).map(([id]) => id); + const rotation = due(isolatedRehomeDeadlines).length + due(nestedCloneMigrationDeadlines).length + due(taskDirectoryDeadlines).length > 0; + return { workspaceIds: due(terminalWorkspaceDeadlines), rotation }; + }, + nextTerminalWorkspaceSweepAt: async () => { if (terminalWorkspaceDeadlines.size === 0 && isolatedRehomeDeadlines.size === 0 && nestedCloneMigrationDeadlines.size === 0 && taskDirectoryDeadlines.size === 0) return null; diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index e4cfaa222cc..103dfe8f709 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -1,3 +1,4 @@ +import { notifyTerminalWorkspaceWork } from "../terminal-workspace-work.js"; import { settleReattachRun } from "./run-admission.js"; import { readNativeStartupCleanup } from "../native-runtime/native-startup-cleanup.js"; import { isContextCompactionRun } from "../context-compaction.js"; @@ -1122,6 +1123,8 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl if (previous && isHeartbeatRunTerminalStatus(status)) await notifyRetainedNativeSessionCleanup(tx, { companyId: previous.companyId, runId: previous.id }); if (isHeartbeatRunTerminalStatus(status)) await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, companyId); + const runIssueId = previous ? previous.nativeIssueId ?? previous.issueId ?? readNonEmptyString(parseObject(previous.contextSnapshot).issueId) : null; + if (previous && isHeartbeatRunTerminalStatus(status) && runIssueId) await notifyTerminalWorkspaceWork(tx, `issue:${runIssueId}`); await notifyExecutionRunWork(tx, previous ? { companyId: previous.companyId, runId: previous.id, issueId: previous.nativeIssueId ?? previous.issueId ?? readNonEmptyString(parseObject(previous.contextSnapshot).issueId) ?? undefined } : undefined); if (previous) await notifyChatRunMilestones(tx, { companyId: previous.companyId, runId: previous.id, diff --git a/server/src/services/terminal-workspace-work.ts b/server/src/services/terminal-workspace-work.ts index d7248aae517..b9845bdbb5d 100644 --- a/server/src/services/terminal-workspace-work.ts +++ b/server/src/services/terminal-workspace-work.ts @@ -3,6 +3,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio export const TERMINAL_WORKSPACE_RETRY_MS = 5 * 60 * 1000; export const MAX_TERMINAL_WORKSPACE_TARGETS = 50; +export const TERMINAL_WORKSPACE_BACKSTOP_MS = 60 * 60 * 1000; export function notifyTerminalWorkspaceWork(transaction: object, hint?: string) { return notifyDeliveryWork(transaction, DELIVERY_QUEUES.terminalWorkspaces, hint); @@ -36,6 +37,7 @@ export function registerTerminalWorkspaceWork( nextTerminalWorkspaceSweepAt(): Promise; hasTerminalWorkspaceSweepContinuation(): boolean; terminalWorkspaceWorkSettled?(hints?: ReadonlySet, options?: { targeted?: boolean }): void; + takeDueTerminalWorkspaceTargets?(): { workspaceIds: string[]; rotation: boolean }; }, canRun: () => boolean, ) { @@ -49,10 +51,14 @@ export function registerTerminalWorkspaceWork( let rotationRequested = false; let dueAt: number | null = null; let lastRotationPageAt = 0; + let backstopArmed = false; + let lastFullRotationAt = Date.now(); + let continuing = false; const targetWorkspaceIds = new Set(), targetIssueIds = new Set(); const worker = coordinator.register(DELIVERY_QUEUES.terminalWorkspaces, { retryMs: TERMINAL_WORKSPACE_RETRY_MS, onSettled: hints => { + backstopArmed = true; const targets = terminalWorkspaceTargetsFromHints(hints); for (const id of targets?.workspaceIds ?? []) targetWorkspaceIds.add(id); for (const id of targets?.issueIds ?? []) targetIssueIds.add(id); @@ -70,12 +76,26 @@ export function registerTerminalWorkspaceWork( next = Date.now() + TERMINAL_WORKSPACE_RETRY_MS; const startup = !startupSweepStarted; startupSweepStarted = true; + let dueRotation = due; + if (due && !startup && service.takeDueTerminalWorkspaceTargets) { + const dueTargets = service.takeDueTerminalWorkspaceTargets(); + dueRotation = dueTargets.rotation; + for (const id of dueTargets.workspaceIds) targetWorkspaceIds.add(id); + if (targetWorkspaceIds.size + targetIssueIds.size > MAX_TERMINAL_WORKSPACE_TARGETS) { + dueRotation = true; + targetWorkspaceIds.clear(); targetIssueIds.clear(); + } + } const options = { compact: !startup, allowRemoteDeliveryChecks: !startup }; const targeted = targetWorkspaceIds.size + targetIssueIds.size > 0; - if (startup || due || rotationRequested || !targeted + const backstopDue = backstopArmed && Date.now() >= lastFullRotationAt + TERMINAL_WORKSPACE_BACKSTOP_MS; + if (due && service.takeDueTerminalWorkspaceTargets && !startup && !dueRotation && !targeted && !rotationRequested && !backstopDue + && !service.hasTerminalWorkspaceSweepContinuation()) return { checked: 0 }; + if (startup || dueRotation || rotationRequested || backstopDue || !targeted || (service.hasTerminalWorkspaceSweepContinuation() && Date.now() >= lastRotationPageAt + 1000)) { rotationRequested = false; lastRotationPageAt = Date.now(); + if (!continuing) { lastFullRotationAt = Date.now(); backstopArmed = false; } return service.sweepTerminalWorkspaces(50, signal, options); } const targets = { workspaceIds: [...targetWorkspaceIds], issueIds: [...targetIssueIds] }; @@ -88,9 +108,12 @@ export function registerTerminalWorkspaceWork( } }, hasPending: async () => { + continuing = false; if (!canRun()) next = Date.now() + TERMINAL_WORKSPACE_RETRY_MS; - else if (service.hasTerminalWorkspaceSweepContinuation()) next = Math.max(Date.now(), lastRotationPageAt + 1000); - else if (rotationRequested || targetWorkspaceIds.size + targetIssueIds.size > 0) next = Date.now(); + else if (service.hasTerminalWorkspaceSweepContinuation()) { + continuing = true; + next = Math.max(Date.now(), lastRotationPageAt + 1000); + } else if (rotationRequested || targetWorkspaceIds.size + targetIssueIds.size > 0) next = Date.now(); else { const deadline = await service.nextTerminalWorkspaceSweepAt(); next = deadline === null ? null : deadline > Date.now() @@ -98,6 +121,10 @@ export function registerTerminalWorkspaceWork( dueAt = next; recovered = true; } + if (backstopArmed && canRun()) { + const backstopAt = lastFullRotationAt + TERMINAL_WORKSPACE_BACKSTOP_MS; + next = next === null ? backstopAt : Math.min(next, backstopAt); + } return false; }, nextRunAt: () => next, From 7db92ea3194f7afdd82ce0c37681203dcc4ed8f6 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 08:51:28 -0600 Subject: [PATCH 02/19] perf(workspaces): read a sweep page's task trees and active runs in two statements (#21618) 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 terminal workspace sweep inspects candidate workspaces 50 per page. For each workspace it read the task tree with its own recursive query. For many of them it also ran one or two queries to check for an active run. > - The cost of a page therefore grew with the page: about 50 to 110 statements. On the hosted instance, building the SQL text of these statements costs about as much main-thread time as parsing their results. > - The archive statement re-checks the terminal tree and the absence of a live run in the same statement, and the remote and plugin cleanups re-check active runs under the lifecycle lock. So these early reads are only pre-filters. > - This pull request reads the task trees and the active-run workspaces of a whole page in two fixed-text statements. > - The benefit is that a page costs a constant number of these reads, whatever its size. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** The per-page reads of the terminal workspace sweep (`sweepTerminalWorkspaces` in `server/src/services/execution-workspaces.ts`). **Current behavior** Each candidate calls `listWorkspaceIssueTree`, one recursive query. A candidate that reaches the active-run checks calls `workspaceHasActiveRun`: one query for the linked tasks' run ids, then one for live runs. **Proposed behavior** - `readPageIssueTrees` reads the tree rows of every root on the page in one statement. Its SQL text is fixed: the roots are one `jsonb` parameter. The trees are then built in memory and keep the same row shape. - `readPageActiveRunWorkspaces` returns, in one fixed-text statement, the page workspaces that have a `queued` or `running` run on a linked task. - The two pre-filter checks in the loop use these results. A workspace whose source task changed earlier in the same pass (rehome) still reads its own tree. - The authoritative checks are unchanged: the archive `UPDATE` with its terminal-tree and live-run predicates, the active-run check inside the remote and plugin cleanup under the lifecycle lock, and the per-workspace check before a stale reopen flag is cleared. **Reason and benefit** One rotation pass should issue a bounded number of statements per page. For a page of 50 workspaces (40 with open trees, 10 held by a run), the tree reads fall from 50 to 1 and the active-run reads from 20 to 1. ## What Changed - `server/src/services/execution-workspaces.ts`: add `readPageIssueTrees` and `readPageActiveRunWorkspaces`, and use them for the per-page pre-filter. - `server/src/__tests__/terminal-workspace-page-batch.test.ts`: two new tests on real PostgreSQL. ## Verification - `reads the task trees and active runs of a page in a fixed number of statements`: 2 companies, 50 workspaces, each with a child task, 10 held by a `running` run. - Before the change it fails: 50 tree reads. - After the change: one tree read, one active-run read, fewer than 10 statements for the page. The results are the same (`checked: 50`, `skippedNonTerminalTree: 40`, `skippedActiveRun: 10`). - `does not archive a workspace whose run starts after the page was read`: - The page is read first. Then, during that workspace's close-readiness check, a `running` run is inserted and set as its task's checkout run. - The sweep counts the workspace `eligible: 1`, `archived: 0`, `skippedRace: 1`, and it stays `active`. - After the run succeeds, the next sweep archives it (`archived: 1`). - `npx vitest run src/__tests__/terminal-workspace-page-batch.test.ts src/__tests__/execution-workspaces-service.test.ts src/__tests__/isolated-task-directory-retention.test.ts src/__tests__/git-workspace-expiration.test.ts src/__tests__/workspace-delivery-cleanup.integration.test.ts src/__tests__/nested-clone-migration.test.ts src/__tests__/execution-workspace-compaction.test.ts src/__tests__/git-restore-point-expiration.test.ts src/__tests__/plugin-workspaces.integration.test.ts` (in `server/`). - `pnpm check:module-boundaries` passes. ## Risks - **The pre-filter reads happen once, at the start of the page.** A page can take long, because cleanups do remote and Git I/O. A run that starts mid-page on a workspace the pre-filter saw as idle is still caught by a check made at the destructive step itself, in the same statement or under a lock. Line numbers are on this head: - **Archive** of an active workspace: the archive `UPDATE` in `sweepTerminalWorkspaces` carries `NOT EXISTS (… live_run.status IN ('queued', 'running'))` (`server/src/services/execution-workspaces.ts:4291`). It changes 0 rows and the workspace counts as `skippedRace` (`:4340`). - **Remote cleanup** (destroying the sandbox): `runTerminalWorkspaceCleanup` re-runs `workspaceHasActiveRun` under the lifecycle lock before `cleanupRemoteWorkspaceAllocation` (`:2702`). - **Plugin workspace removal**: the same check under the lifecycle lock before `removePluginWorkspace` (`:2706`). - **Git cache expiration** and **isolated task directory expiry**: `isGitWorkspaceExpirationEligible` re-reads the tree and refuses any run that is not finished, inside the locked transaction (`server/src/services/git-workspace-expiration.ts:311` and `:416`, `server/src/services/isolated-task-directory-retention.ts:244` and `:290`). - A run that ends mid-page leaves its workspace for the run-release hint or the next inspection. - **Tree rows are now deduplicated** (`UNION` instead of `UNION ALL`). Parent cycles therefore cannot repeat rows. - Low risk otherwise. No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] 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-workspaces-service.test.ts | 2 +- .../terminal-workspace-page-batch.test.ts | 94 +++++++++++++++++++ server/src/services/execution-workspaces.ts | 71 +++++++++++++- 3 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 server/src/__tests__/terminal-workspace-page-batch.test.ts diff --git a/server/src/__tests__/execution-workspaces-service.test.ts b/server/src/__tests__/execution-workspaces-service.test.ts index 71341434ea9..64d2e4e1851 100644 --- a/server/src/__tests__/execution-workspaces-service.test.ts +++ b/server/src/__tests__/execution-workspaces-service.test.ts @@ -606,7 +606,7 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => { expect(scan.mock.calls.filter(([input]) => input.operation === "execution_workspaces.close_readiness_status")) .toHaveLength(3); expect(select.mock.calls.filter(([fields]) => fields && "completedAt" in fields && "cancelledAt" in fields)) - .toHaveLength(4); + .toHaveLength(1); } finally { scan.mockRestore(); select.mockRestore(); diff --git a/server/src/__tests__/terminal-workspace-page-batch.test.ts b/server/src/__tests__/terminal-workspace-page-batch.test.ts new file mode 100644 index 00000000000..038708b7e65 --- /dev/null +++ b/server/src/__tests__/terminal-workspace-page-batch.test.ts @@ -0,0 +1,94 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { agents, companies, createDb, executionWorkspaces, heartbeatRuns, issues, projects, type Db } from "@paperclipai/db"; +import { executionWorkspaceService } from "../services/execution-workspaces.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_TERMINAL_WORKSPACE_PAGE_TEST_DATABASE_URL"); +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const DAY = 86_400_000; + +(support.supported ? describe : describe.skip)("terminal workspace page reads", () => { + let temporary: Awaited> | undefined; + let db: Db; + let meter: ReturnType; + beforeAll(async () => { + if (!external) temporary = await startEmbeddedPostgresTestDatabase("terminal-workspace-page-"); + const url = external ?? temporary!.connectionString; + db = createDb(url); + db.$client.options.onnotice = () => {}; + meter = meterDatabaseStatements(db, url); + }, 120_000); + afterEach(async () => { await db.execute(sql`truncate companies cascade`); }); + afterAll(async () => { meter?.uninstall(); await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + + async function seed(input: { open: number; held: number; companies: number }) { + const old = new Date(Date.now() - 10 * DAY); + const held: string[] = []; + for (let company = 0; company < input.companies; company++) { + const companyId = randomUUID(), projectId = randomUUID(), agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Page", issuePrefix: `P${companyId.slice(0, 6)}` }); + await db.insert(projects).values({ id: projectId, companyId, name: "Project", status: "in_progress" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Agent", role: "engineer", status: "idle", adapterType: "process" }); + for (const kind of [...Array(input.open).fill("open"), ...Array(input.held).fill("held")] as Array<"open" | "held">) { + const id = randomUUID(), issueId = randomUUID(), childId = randomUUID(); + const runId = kind === "held" ? randomUUID() : null; + if (runId) await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running" }); + await db.insert(executionWorkspaces).values({ id, companyId, projectId, mode: "shared_workspace", strategyType: "project_primary", + name: id, status: "active", providerType: "local_fs", cwd: `/missing/${id}`, createdAt: old, updatedAt: old }); + await db.insert(issues).values([ + { id: issueId, companyId, projectId, title: kind, status: "done", executionWorkspaceId: id, checkoutRunId: runId, completedAt: old, updatedAt: old }, + { id: childId, companyId, projectId, parentId: issueId, title: `${kind} child`, status: kind === "open" ? "todo" : "done", + completedAt: kind === "open" ? null : old, updatedAt: old }, + ]); + await db.update(executionWorkspaces).set({ sourceIssueId: issueId, updatedAt: old }).where(eq(executionWorkspaces.id, id)); + if (kind === "held") held.push(id); + } + } + return { held }; + } + + it("does not archive a workspace whose run starts after the page was read", async () => { + await seed({ open: 3, held: 0, companies: 1 }); + const [workspace] = await db.select().from(executionWorkspaces).limit(1); + const [source] = await db.select().from(issues).where(eq(issues.id, workspace!.sourceIssueId!)); + await db.update(issues).set({ status: "done", completedAt: new Date(Date.now() - 10 * DAY) }).where(eq(issues.parentId, source!.id)); + const [agent] = await db.select().from(agents).limit(1); + let started: string | null = null; + const service = executionWorkspaceService(db, { workspaceReaperCooldownDays: 1, + inspectGitCloseReadiness: async inspected => { + if (inspected.id === workspace!.id && !started) { + started = randomUUID(); + await db.insert(heartbeatRuns).values({ id: started, companyId: workspace!.companyId, agentId: agent!.id, status: "running" }); + await db.update(issues).set({ checkoutRunId: started }).where(eq(issues.id, source!.id)); + } + return { statusInspectionSucceeded: true, warnings: [], git: { repoRoot: null, workspacePath: inspected.cwd, branchName: null, + baseRef: null, hasDirtyTrackedFiles: false, hasUntrackedFiles: false, dirtyEntryCount: 0, untrackedEntryCount: 0, + aheadCount: 0, behindCount: 0, isMergedIntoBase: true, createdByRuntime: false } }; + } }); + const result = await service.sweepTerminalWorkspaces(50); + expect(started).not.toBeNull(); + expect(result).toMatchObject({ eligible: 1, archived: 0, skippedRace: 1 }); + const [row] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace!.id)); + expect(row!.status).toBe("active"); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, started!)); + expect(await service.sweepTerminalWorkspaces(50)).toMatchObject({ archived: 1 }); + }); + + it("reads the task trees and active runs of a page in a fixed number of statements", async () => { + await seed({ open: 20, held: 5, companies: 2 }); + const service = executionWorkspaceService(db, { workspaceReaperCooldownDays: 1 }); + meter.startLog(); + const result = await service.sweepTerminalWorkspaces(50); + const statements = meter.stopLog(); + expect(result).toMatchObject({ checked: 50, skippedNonTerminalTree: 40, skippedActiveRun: 10 }); + const treeReads = statements.filter(entry => /issue_tree/i.test(entry.sql)); + const runReads = statements.filter(entry => /"checkout_run_id", "execution_run_id"|live_run/.test(entry.sql)); + expect(treeReads).toHaveLength(1); + expect(runReads).toHaveLength(1); + expect(statements.length).toBeLessThan(10); + }); +}); diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 7eeb921e750..999a2424f70 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -2234,6 +2234,67 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } } + type IssueTreeRow = Awaited>[number]; + + async function readPageIssueTrees(workspaces: Array>) { + const trees = new Map(); + const roots = workspaces.filter(workspace => workspace.sourceIssueId) + .map(workspace => ({ companyId: workspace.companyId, issueId: workspace.sourceIssueId! })); + if (roots.length === 0) return trees; + const rows = await retryIdempotentDatabaseOperation(() => db + .select({ id: issues.id, companyId: issues.companyId, parentId: issues.parentId, status: issues.status, + completedAt: issues.completedAt, cancelledAt: issues.cancelledAt, updatedAt: issues.updatedAt }) + .from(issues) + .where(sql`(${issues.companyId}, ${issues.id}) IN ( + WITH RECURSIVE issue_tree(company_id, id) AS ( + SELECT (root->>'companyId')::uuid, (root->>'issueId')::uuid FROM jsonb_array_elements(${JSON.stringify(roots)}::jsonb) root + UNION + SELECT child.company_id, child.id FROM ${issues} child + JOIN issue_tree parent ON child.parent_id = parent.id AND child.company_id = parent.company_id + ) + SELECT company_id, id FROM issue_tree + )`)); + const byId = new Map(rows.map(row => [row.id, row])); + const children = new Map(); + for (const row of rows) { + if (!row.parentId) continue; + const siblings = children.get(row.parentId); + if (siblings) siblings.push(row); else children.set(row.parentId, [row]); + } + for (const workspace of workspaces) { + const root = workspace.sourceIssueId ? byId.get(workspace.sourceIssueId) : undefined; + if (!root || root.companyId !== workspace.companyId) { trees.set(workspace.id, []); continue; } + const tree: IssueTreeRow[] = []; + const seen = new Set(); + const stack = [root]; + while (stack.length) { + const row = stack.pop()!; + if (seen.has(row.id)) continue; + seen.add(row.id); + tree.push({ id: row.id, status: row.status, completedAt: row.completedAt, cancelledAt: row.cancelledAt, updatedAt: row.updatedAt }); + for (const child of children.get(row.id) ?? []) if (child.companyId === workspace.companyId) stack.push(child); + } + trees.set(workspace.id, tree); + } + return trees; + } + + async function readPageActiveRunWorkspaces(workspaces: Array>) { + if (workspaces.length === 0) return new Set(); + const pairs = workspaces.map(workspace => ({ id: workspace.id, companyId: workspace.companyId, sourceIssueId: workspace.sourceIssueId })); + const rows = await db.execute<{ id: string }>(sql`SELECT workspace.id::text AS id + FROM jsonb_to_recordset(${JSON.stringify(pairs)}::jsonb) AS workspace(id uuid, "companyId" uuid, "sourceIssueId" uuid) + WHERE EXISTS ( + SELECT 1 FROM ${issues} linked + JOIN ${heartbeatRuns} live_run ON live_run.company_id = linked.company_id + AND live_run.id IN (linked.checkout_run_id, linked.execution_run_id) + AND live_run.status IN ('queued', 'running') + WHERE linked.company_id = workspace."companyId" + AND (linked.execution_workspace_id = workspace.id OR linked.id = workspace."sourceIssueId") + )`); + return new Set(rows.map(row => row.id)); + } + async function workspaceHasActiveRun(workspace: Pick) { const linkedIssues = await db .select({ @@ -3662,6 +3723,9 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic }; if (targets) for (const id of [...targets.workspaceIds, ...candidates.map(candidate => candidate.workspace.id)]) terminalWorkspaceDeadlines.delete(id); const readinessByWorkingTree = new Map>(); + const pageWorkspaces = candidates.map(candidate => candidate.workspace); + const [pageIssueTrees, pageActiveRunWorkspaces] = await Promise.all([ + readPageIssueTrees(pageWorkspaces), readPageActiveRunWorkspaces(pageWorkspaces)]); const backOffTerminalWorkspace = async (snapshot: ExecutionWorkspaceRow, failure: TerminalWorkspaceFailure) => { const [target] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, snapshot.id)); if (!target) return; @@ -3787,7 +3851,8 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic await expireTaskDirectory(workspace, now()); continue; } - const issueTree = await listWorkspaceIssueTree(workspace); + const issueTree = workspace.sourceIssueId === candidate.workspace.sourceIssueId + ? pageIssueTrees.get(workspace.id) ?? await listWorkspaceIssueTree(workspace) : await listWorkspaceIssueTree(workspace); const sourceIssue = issueTree.find((issue) => issue.id === workspace.sourceIssueId); const reopenPending = metadataHasReopenPendingConsumption( workspace.metadata as Record | null, @@ -3912,7 +3977,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic result.skippedBackoff += 1; continue; } - if (await workspaceHasActiveRun(workspace)) { + if (pageActiveRunWorkspaces.has(workspace.id)) { if (reopenPending) result.skippedReopened += 1; else result.skippedActiveRun += 1; terminalWorkspaceDeadlines.delete(workspace.id); @@ -4154,7 +4219,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } continue; } - if (await workspaceHasActiveRun(workspace)) { + if (pageActiveRunWorkspaces.has(workspace.id)) { result.skippedActiveRun += 1; terminalWorkspaceDeadlines.delete(workspace.id); continue; From 68d5c9c1205f1f1629d76a1ec703bcb1c38fc48d Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 14 Nov 2026 08:16:24 -0800 Subject: [PATCH 03/19] feat(runner): let a caller ask the transport for provider-started turns (#21607) 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. > - Core runs Claude Code through Paperclip Runner. Claude can start a shell command in the background and end its turn. When the command finishes, Claude Code starts a cycle of its own to continue. > - Today the run ends when the turn ends. The command stops, and the run fails with `native_finalization_missing`. > - The Runner can already keep Claude while a background shell is running and give the cycle of Claude to the controller as a turn that the provider started (#21423, #21316). Core can already wait for that turn (#21453, #21454, #21455). No run does this yet, because no controller asks the Runner for it. > - The request goes through the transport of the Runner package. This pull request gives the transport an option for it and the behavior that the option needs. > - No caller sets the option in this pull request. It changes no production run. > - The benefit is a small base for the two pull requests after it: the recovery after a controller restart, and the switch that turns the behavior on. ## Linked Issues or Issue Description No public issue exists. The issue is described here. #21456 turned the behavior on and had grown too large to review. It is now three stacked pull requests: 1. **This pull request:** the transport can ask the Runner for provider-started turns. No caller asks. 2. #21612: the recovery after a controller restart during a wait or during a provider-started turn. 3. #21456: Core sets the option for native ACPX Claude runs. Only that part changes what a production run does. Refs #19912 (design), #21456. **What existing behavior does this improve?** None in production. It adds the support that parts 2 and 3 use. **Subsystem affected** Paperclip Runner package, the controller side: `src/live/runnerd-codex-transport.ts`. ACPX Claude only, and only for a caller that sets the new option. **Current behavior** - The transport has no way to ask the Runner for provider-started turns. **Proposed behavior** - The transport options have a new field, `providerStartedTurns`. The transport uses it only for ACPX with the agent `claude`. In each other case the field has no effect. - With the option, the transport sends `providerStartedTurns: true` in `turn.start`. It does not send it for a compaction turn. - With the option, a tool call in a provider-started turn waits until the transport gave each earlier event to the driver. Without this, a `paperclip_finish` of that turn could reach the driver before the `turn.started` of that turn, and the driver would refuse it. - With the option, the transport gives a `run.terminal` of the Runner to the driver as a marked internal notification (`paperclip/runTerminal`). The driver uses it only during a wait, so a wait ends at once when the Runner says that the run is over. - With no option, the transport does the same as before this pull request. Live sessions, evals, the CLI runner and the probes do not set the option. **Reason and benefit** - The opt-in is a choice of the caller, not a property of the agent. Only a consumer that can wait for a provider-started turn must ask for one. `CapabilityLiveSession` completes a turn at the first `turn/completed`, so it must not get the behavior because its agent is Claude. ## What Changed - `src/live/runnerd-codex-transport.ts` (31 lines added, 1 removed): the option, the field in `turn.start`, the order of the tool call, and the `paperclip/runTerminal` notification. - `src/live/provider-turn-tool-order.ts` (new, 16 lines): finds the source sequence of a tool call that belongs to a provider-started turn. - `src/live/runnerd-acpx-provider-turn.test.ts` (new, 239 lines): 7 cases with the real `paperclip-runnerd`, the fake ACPX sidecar, and the real consumer of Core. - `src/live/live-session.test.ts` (12 lines added): a Claude live session gives the transport no such option. - `runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs` (test binary only): the mode `provider-result-resolved`. In this mode the provider-started turn calls `paperclip_finish` and waits for the answer of Core through the Runner (`tool.resolve`), as the real sidecar does. The mode `provider-result` is not changed. ## State saved by the previous release - No persisted state changes in this part. - **A Runner that does not know the field** ignores it. - **Rollback of the Runner package:** the previous transport does not send the field, so the Runner does not wait. ## Verification At the head of this branch (`2f2cb14b9c`), with nothing from parts 2 and 3: - `npx tsc --noEmit -p tsconfig.json`, `npx tsc --noEmit -p tsconfig.test.json`, `pnpm run typecheck:typescript` and `pnpm run build:typescript` in `packages/paperclip-runner`; `pnpm typecheck` and `node scripts/verify-runner-vendor-dependencies.mjs` in `server`; `node --test scripts/__tests__/runner-release-crate-cache.test.mjs`; `node --test test/acpx-sidecar-contract.test.mjs` (18 passed): all passed. - `src/live/runnerd-acpx-provider-turn.test.ts`, 3 runs, 7 of 7 passed in each. The cases: - background work, then the turn of Claude calls `paperclip_finish`; Core answers; the Runner gives the answer to the sidecar with exactly one `tool.resolve`; the turn completes; the run finalizes with one `run.result.accepted`; - a Claude run with no option from the caller takes the path of today: no `providerStartedTurns` in `turn.start`, no `paperclip/runTerminal`, no wait, and no `session.provider_turn` to the sidecar; - the limit ends the wait, the run takes the path of today, and the provider processes had exited before the cleanup of the test; - the provider process is lost during the wait, and the run settles in seconds; - the sidecar exits during the wait, and the run settles in seconds; - a turn with no background work does not wait; - an ACPX agent that is not Claude is never opted in, also when the caller sets the option. - Each case asserts the result of the close of the session: clean in 6 cases, and a named failure in the case where the sidecar is killed. Each clean case also asserts that there is no `native_session_settlement_incomplete` diagnostic and no "conflicting duplicate tool result" in the durable state. - `src/live/live-session.test.ts`, `src/live/runnerd-codex-transport.test.ts`, `src/live/runnerd-acpx-provider-turn-wait.test.ts`, `src/native-session-runtime.provider-turn.test.ts`: 434 passed. - Rust, because the fake sidecar changed: `cargo fmt --check`, `cargo build`, the `acpx_*` suites (244 passed) and the `acpx` unit tests (102 passed). - Mutation checks, run on the full change before the split: with the option ignored, 6 of the 7 assertions of the case with no option fail; with the old mode of the fake, the case with the result fails at the close of the session. Not run: the full suite. CI supplies that coverage. ## Risks - **No production effect.** No caller sets the option. Core sets it in part 3. - **The transport is shared by each provider.** The three new behaviors are behind one condition: the option, ACPX, and the agent `claude`. With the condition false, the code path is the path of today. - **The tool-call ordering uses a 10 ms poll** while earlier events are not delivered, only in a provider-started turn. - **A controller restart during a wait or during a provider-started turn is not handled in this part.** Part 2 handles it. Part 3 must not merge before part 2. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change and the split, reviewed the diff, and ran a part of the verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), wrote the change and the tests and cut this slice from the full change. ## 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 --- .../runner-core/src/bin/fake-acpx-sidecar.rs | 66 ++++- .../src/live/live-session.test.ts | 12 + .../src/live/provider-turn-tool-order.ts | 16 ++ .../live/runnerd-acpx-provider-turn.test.ts | 239 ++++++++++++++++++ .../src/live/runnerd-codex-transport.ts | 32 ++- 5 files changed, 361 insertions(+), 4 deletions(-) create mode 100644 packages/paperclip-runner/src/live/provider-turn-tool-order.ts create mode 100644 packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs index c66ae154349..a3232e33050 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs @@ -269,7 +269,12 @@ fn run() -> Result<(), Box> { .any(|token| token == "provider-turn-after-disarm") { if let Some(run) = pending_provider_run.take() { - next_sequence = write_provider_turn(&mut stdout, next_sequence, &run)?; + next_sequence = write_provider_turn( + &mut stdout, + next_sequence, + &run, + &mut source_pending_completion, + )?; } } if armed @@ -299,7 +304,12 @@ fn run() -> Result<(), Box> { continue; } if let (true, Some(run)) = (armed, pending_provider_run.take()) { - next_sequence = write_provider_turn(&mut stdout, next_sequence, &run)?; + next_sequence = write_provider_turn( + &mut stdout, + next_sequence, + &run, + &mut source_pending_completion, + )?; provider_rearmable = tokens.iter().any(|token| token == "provider-terminal-live"); } else { provider_rearmable = false; @@ -547,8 +557,19 @@ fn run() -> Result<(), Box> { next_sequence, &source_run, &mut pending_provider_run, + &mut source_pending_completion, )?; } + if command == "tool.resolve" && request["params"]["callId"] == "call-provider-finish" { + let turn = source_pending_completion + .take() + .ok_or("missing provider completion")?; + if request["params"]["turnId"] != turn { + return Err("provider completion identity mismatch".into()); + } + next_sequence = finish_provider_turn(&mut stdout, next_sequence, &source_run)?; + continue; + } if command == "tool.resolve" { let turn = source_pending_completion .take() @@ -1084,6 +1105,7 @@ fn run() -> Result<(), Box> { next_sequence, "run-1", &mut pending_provider_run, + &mut None, )?; } if command == "turn.start" && mode == "turns-multiple-tool-results-terminal" { @@ -1574,13 +1596,14 @@ fn offer_provider_turn( sequence: u64, default_run: &str, pending: &mut Option, + pending_finish: &mut Option, ) -> io::Result { let tokens = provider_turn_tokens(); if !tokens.iter().any(|token| token == "provider-turn") { return Ok(sequence); } if tokens.iter().any(|token| token == "provider-turn-unarmed") { - return write_provider_turn(output, sequence, default_run); + return write_provider_turn(output, sequence, default_run, pending_finish); } *pending = Some(default_run.to_owned()); Ok(sequence) @@ -1590,6 +1613,7 @@ fn write_provider_turn( output: &mut impl Write, mut sequence: u64, default_run: &str, + pending_finish: &mut Option, ) -> io::Result { let tokens = provider_turn_tokens(); if !tokens.iter().any(|token| token == "provider-turn") { @@ -1650,6 +1674,42 @@ fn write_provider_turn( )?; sequence += 2; } + if tokens + .iter() + .any(|token| token == "provider-result-resolved") + { + write_json( + output, + &frame( + sequence, + "runtime.tool_called", + json!({"callId":"call-provider-finish","operationId":"paperclip_finish","input":valid_reserved_completion_result()}), + ), + )?; + *pending_finish = Some(turn_id); + return Ok(sequence + 1); + } + finish_provider_turn(output, sequence, default_run) +} + +fn finish_provider_turn( + output: &mut impl Write, + mut sequence: u64, + default_run: &str, +) -> io::Result { + let tokens = provider_turn_tokens(); + let value = |prefix: &str, fallback: &str| { + tokens + .iter() + .find_map(|token| token.strip_prefix(prefix).map(str::to_owned)) + .unwrap_or_else(|| fallback.to_owned()) + }; + let turn_id = value("provider-turn-id=", "provider-1"); + let run_id = value("provider-run=", default_run); + let frame = |sequence: u64, event_type: &str, payload: Value| { + json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,"sequence":sequence, + "eventType":event_type,"runId":run_id,"turnId":turn_id,"payload":payload}) + }; write_json( output, &frame( diff --git a/packages/paperclip-runner/src/live/live-session.test.ts b/packages/paperclip-runner/src/live/live-session.test.ts index d561769867e..a88c850b28c 100644 --- a/packages/paperclip-runner/src/live/live-session.test.ts +++ b/packages/paperclip-runner/src/live/live-session.test.ts @@ -53,6 +53,18 @@ it("admits Pi live sessions without candidate opt-in while preserving the exact } finally { await session.shutdown("test complete"); } }); +it("leaves provider-started turns off for a Claude ACPX live session", async () => { + const factory = fakeTransportFactory(providerState()); + const options: Parameters[0][] = []; + const service = new CapabilityLiveSessionService({ transportFactory: next => { options.push(next); return factory(next); } }); + const session = await service.create({ provider: "acpx", acpxAgent: "claude", requestedModel: "claude-sonnet-4-6" }); + try { + await session.sendMessage("hello"); + expect(options[0]).toMatchObject({ provider: "acpx", acpxAgent: "claude" }); + for (const option of options) expect(option).not.toHaveProperty("providerStartedTurns"); + } finally { await session.shutdown("test complete"); } +}); + class AsyncNotifications implements AsyncIterable { #values: CodexRpcNotification[] = []; #waiters: Array<(value: IteratorResult) => void> = []; diff --git a/packages/paperclip-runner/src/live/provider-turn-tool-order.ts b/packages/paperclip-runner/src/live/provider-turn-tool-order.ts new file mode 100644 index 00000000000..95a93446d98 --- /dev/null +++ b/packages/paperclip-runner/src/live/provider-turn-tool-order.ts @@ -0,0 +1,16 @@ +import type { DurableRecoveryCommittedEvent } from "../control-plane/prp-transport-types.js"; + +const record = (value: unknown): Record => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +export function providerTurnToolCallSourceSeq( + events: readonly Pick[], + sourceEventId: string, +): number | null { + const index = events.findIndex(event => event.sourceEventId === sourceEventId); + for (let at = index - 1; at >= 0; at -= 1) { + if (events[at]!.eventType !== "turn.started") continue; + return record(record(events[at]!.envelope.payload).payload).origin === "provider" ? events[index]!.sourceSeq : null; + } + return null; +} diff --git a/packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts b/packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts new file mode 100644 index 00000000000..d1db45947a4 --- /dev/null +++ b/packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts @@ -0,0 +1,239 @@ +import { createHash } from "node:crypto"; +import { execFileSync, spawn } from "node:child_process"; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { closeSync, openSync } from "node:fs"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { expect, it, vi } from "vitest"; +import type { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js"; +import { QUALIFIED_ACPX_PROFILES, resolveQualifiedAcpxProfile } from "../drivers/acpx/qualified-profiles.js"; +import { createCapabilityRunnerdCodexTransport, readRunnerdArtifactBinding } from "./runnerd-codex-transport.js"; +import { createRunnerProviderLaunch, runnerLaunchRequirementsDigest } from "./runner-provider-launch.js"; +import { defaultCapabilityRunnerdBinary } from "../../test/support/runnerd-transport.js"; +import type { PrpEvent } from "../protocol/replay-contract.js"; +import { createNativeSessionBackend } from "../backends/native-backend-factory.js"; +import type { NativeExecutionInput } from "../contracts/native-execution.js"; +import { executeNativeSession } from "../native-session-runtime.js"; + +const sha = (value: string | Buffer) => `sha256:${createHash("sha256").update(value).digest("hex")}`; +const quote = (value: string) => `'${value.replaceAll("'", "'\"'\"'")}'`; +const kill = (pid: number) => { try { process.kill(-pid, "SIGKILL"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } }; +const alive = (pid: number) => { + try { process.kill(pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; throw error; } + try { return !execFileSync("ps", ["-p", String(pid), "-o", "stat="], { encoding: "utf8" }).trim().startsWith("Z"); } + catch (error) { if ((error as { status?: number }).status === 1) return false; throw error; } +}; + +function qualifiedProfile(agent: "claude" | "codex") { + const qualified = resolveQualifiedAcpxProfile(agent, "explicit-source-model"); + return { driverKind: qualified.driverKind, protocolVersion: qualified.protocolVersion, acpxVersion: qualified.acpxVersion, + agent: qualified.agent, agentProfileVersion: qualified.agentProfileVersion, + agentServerPackage: qualified.agentServerPackage, agentServerVersion: qualified.agentServerVersion, + agentRuntimePackage: qualified.agentRuntimePackage, agentRuntimeVersion: qualified.agentRuntimeVersion, + commandDigest: qualified.commandDigest }; +} + +let scenario = 0; +const durableState = async (root: string) => (await Promise.all(["control-plane/control-plane-state.json", "runner/runner-state.json"] + .map(path => readFile(join(root, path), "utf8").catch(() => "")))).join("\n"); + +async function runProviderTurnScenario(tokens: string, options: { agent?: "claude" | "codex"; capMs?: number; providerStartedTurns?: boolean } = {}) { + const agent = options.agent ?? "claude"; + const providerStartedTurns = options.providerStartedTurns ?? agent === "claude"; + const turnStarts: Array> = []; + const notificationMethods: string[] = []; + const diagnostics: string[] = []; + const n = ++scenario; + const root = await realpath(await mkdtemp(join(tmpdir(), "runner-acpx-provider-turn-"))); + const journal = join(root, "calls"), fault = join(root, "fault"), wrapper = join(root, "sidecar"), script = join(root, "sidecar-entry"); + const background = join(root, "background"); + const binary = defaultCapabilityRunnerdBinary(), sidecar = resolve(import.meta.dirname, "../../runner/target/debug/fake-acpx-sidecar"); + await mkdir(join(root, "acpx"), { mode: 0o700 }); await mkdir(join(root, "diagnostics"), { mode: 0o700 }); + await writeFile(script, "qualified fixture entry"); + await writeFile(background, tokens); + await writeFile(wrapper, `#!/bin/sh\nexec ${quote(sidecar)} --mode source-reconcile --profile-digest ${quote(QUALIFIED_ACPX_PROFILES[agent].commandDigest)} --journal ${quote(journal)} --source-fault ${quote(fault)} --background-tasks ${quote(background)} --spawn-owned-child\n`, { mode: 0o700 }); + let authority: DurablePrpControlPlane | null = null; + const server = createServer(); + server.on("upgrade", (request, socket, head) => authority ? authority.handleUpgrade(request, socket, "/runner", head) : socket.destroy()); + await new Promise(done => server.listen(0, "127.0.0.1", done)); + const address = server.address(); if (!address || typeof address === "string") throw new Error("missing fixture listener"); + const identity = { runnerInstanceId: `runner-provider-turn-${n}`, environmentLeaseId: `lease-provider-turn-${n}`, runId: `run-provider-turn-${n}`, + normalizedSessionId: `session-provider-turn-${n}`, turnId: `turn-provider-turn-${n}`, itemId: `item-provider-turn-${n}` }; + const nativeIdentity = { companyId: `company-${n}`, agentId: "agent", issueId: "issue", runId: identity.runId, sessionId: identity.normalizedSessionId }; + const execution: NativeExecutionInput = { schema: "paperclip.native-execution-input.v1", + binding: { companyId: nativeIdentity.companyId, agentId: nativeIdentity.agentId, issueId: nativeIdentity.issueId, runId: identity.runId, executionWorkspaceId: "workspace" }, + task: { identifier: "TASK-1", title: "Install and test", description: null, prompt: "Install and test", workMode: "standard" }, + workspace: { cwd: root, repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: identity.normalizedSessionId, driverKind: "acpx_runtime", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + provider: { kind: "acpx", agent, model: "explicit-source-model", permissionPolicy: "interactive", profile: qualifiedProfile(agent) }, + completionContract: { id: "contract", sha256: sha("contract"), schemaVersion: "paperclip.completion-contract.v1", + contract: { revision: "acpx-provider-turns-v1", objective: "Install and test", criteria: [{ id: "objective", requirement: "Install and test" }] } }, + interactionResponses: [], credentialBindings: [] }; + const runnerPids = new Set(); + const bundle = createCapabilityRunnerdCodexTransport({ + provider: "acpx", acpxAgent: agent, ...(providerStartedTurns ? { providerStartedTurns: true } : {}), + onDiagnostic: message => diagnostics.push(message), runnerBinary: binary, stateDirectory: root, prpIdentity: identity, + runnerArtifact: readRunnerdArtifactBinding(binary), codexSourceRecoveryVersion: 1, acpxSourceRecoveryVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, runnerProcessReconnectGraceMs: null, runnerReconnectGraceMs: 3_000, + controlPlaneRegistration: async next => { + authority = next; + const queueCommand = next.queueCommand.bind(next); + next.queueCommand = (type, payload, ...rest) => { + if (type === "turn.start") turnStarts.push(structuredClone(payload ?? {})); + return queueCommand(type, payload, ...rest); + }; + return { connectUrl: `ws://127.0.0.1:${address.port}/runner`, release: () => { authority = null; } }; }, + prepareLaunch: async launch => ({ configurationId: `initial-${launch.identity.runId}`, requirementsDigest: runnerLaunchRequirementsDigest(launch), + provider: createRunnerProviderLaunch(launch, { options: {}, root, cwd: root, codexHome: root, codexCommand: "", providerNodeCommand: wrapper, opencodeProxyPath: "", acpxSidecarPath: script }) }), + runnerProcessLauncher: spec => { + const stderr = openSync(join(root, "native.stderr"), "a", 0o600); + const child = spawn(binary, [...spec.args, "--acpx-launch-authority-digest", sha("fixture authority"), + "--acpx-sidecar-command", wrapper, "--acpx-sidecar-command-sha256", sha(execFileSync("cat", [wrapper])), + "--acpx-sidecar-script", script, "--acpx-sidecar-script-sha256", sha("qualified fixture entry")], + { env: { PATH: process.env.PATH, HOME: root, ...spec.environment }, stdio: ["ignore", "ignore", stderr], detached: true }); + closeSync(stderr); + if (child.pid) runnerPids.add(child.pid); + return { child, completion: new Promise((done, reject) => { child.once("error", reject); child.once("exit", (code, signal) => done({ code, signal, stdout: "", stderr: "" })); }) }; + }, + }); + const notifications = bundle.transport.notifications.bind(bundle.transport); + bundle.transport.notifications = () => ({ async *[Symbol.asyncIterator]() { + for await (const notification of notifications()) { notificationMethods.push(notification.method); yield notification; } + } }); + const calls = async () => (await readFile(journal, "utf8").catch(() => "")).trim().split("\n").filter(Boolean) + .flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } }); + const appended: PrpEvent[] = []; + const completeRun = vi.fn(async () => undefined); + const resolveMissingResult = vi.fn(async () => null); + try { + const backend = createNativeSessionBackend(execution, { codexTransportFactory: () => bundle.transport, + environment: { PAPERCLIP_WORKSPACE_CWD: root }, dynamicTools: [] }); + const started = Date.now(); + const outcome = await executeNativeSession({ + input: execution, backend, runnerInstanceId: identity.runnerInstanceId, controlPlaneInstanceId: "control-provider-turn", + controlPlane: { + async openRun() {}, async checkpointSession() {}, + async appendEvent(value: PrpEvent) { + appended.push(structuredClone(value)); + return { cursor: value.sourceSeq, highestContiguousSourceSeq: value.sourceSeq, disposition: "committed" }; + }, + async replayEvents() { return { events: [], highestContiguousSourceSeq: 0 }; }, + completeRun, + }, + timeoutMs: 30_000, resolveMissingResult, + providerTurnWait: options.capMs === undefined ? undefined : { capMs: options.capMs }, + }).then(() => "finalized", (error: unknown) => String(error instanceof Error ? error.message : error)); + const elapsedMs = Date.now() - started; + const closeOutcome = await bundle.transport.close().then(() => "closed", (error: unknown) => String(error instanceof Error ? error.message : error)); + const durable = await durableState(root); + const journalled = await calls(); + const providerPids = journalled.flatMap(entry => [entry.processStart, entry.childPid]).filter((pid): pid is number => typeof pid === "number"); + await vi.waitFor(() => { for (const pid of providerPids) expect(alive(pid)).toBe(false); }, { timeout: 5_000, interval: 50 }).catch(() => undefined); + const providerProcesses = providerPids.map(pid => ({ pid, exited: !alive(pid) })); + return { outcome, appended, completeRun, resolveMissingResult, journalled, providerProcesses, root, elapsedMs, turnStarts, notificationMethods, closeOutcome, diagnostics, durable }; + } catch (error) { + const diagnostics = (await readFile(join(root, "native.stderr"), "utf8").catch(() => "")) + + (await readFile(join(root, "diagnostics", "runnerd.stderr.log"), "utf8").catch(() => "")); + throw new Error(`${String(error)}\n${diagnostics}`, { cause: error }); + } finally { + await bundle.transport.close().catch(() => undefined); + for (const pid of runnerPids) kill(pid); + for (const entry of await calls()) if (entry.processStart) kill(entry.processStart); + server.closeAllConnections(); await new Promise(done => server.close(() => done())); + await rm(root, { recursive: true, force: true }); + } +} + +const sidecarCommands = (journalled: Array>) => journalled.filter(entry => typeof entry.command === "string").map(entry => entry.command); +const unsettled = (messages: string[]) => messages.filter(message => message.startsWith("native_session_settlement_incomplete")); +const expectCleanClose = (run: Awaited>) => { + expect(run.closeOutcome).toBe("closed"); + expect(unsettled(run.diagnostics)).toEqual([]); + expect(run.durable).not.toContain("conflicting duplicate"); +}; + +it.skipIf(process.platform === "win32")("continues a run in the provider's own turn after background work and settles its result", async () => { + const run = await runProviderTurnScenario("live provider-turn provider-result-resolved"); + expect(run.outcome).toBe("finalized"); + expect(run.completeRun).toHaveBeenCalledOnce(); + expect(run.resolveMissingResult).not.toHaveBeenCalled(); + const awaited = run.appended.find(event => event.eventType === "turn.completed" && event.payload.awaitingProviderTurn === true); + expect(awaited).toBeDefined(); + const started = run.appended.filter(event => event.eventType === "turn.started"); + expect(started).toHaveLength(2); + expect(started[1]).toMatchObject({ turnId: "provider-1", payload: { origin: "provider" } }); + expect(run.appended.filter(event => event.payload.kind === "usage").map(event => event.turnId)).toContain("provider-1"); + expect(sidecarCommands(run.journalled)).toContain("session.provider_turn"); + expect(run.turnStarts).toEqual([expect.objectContaining({ providerStartedTurns: true })]); + expect(run.notificationMethods).toContain("paperclip/runTerminal"); + expect(run.appended.filter(event => event.eventType === "run.result.accepted")).toHaveLength(1); + expect(run.appended.filter(event => event.eventType === "run.result.proposed").map(event => event.turnId)).toEqual(["provider-1"]); + expect(run.appended.filter(event => event.eventType === "turn.completed").map(event => event.turnId)).toContain("provider-1"); + const resolved = run.journalled.filter(entry => entry.command === "tool.resolve"); + expect(resolved.map(entry => [entry.params.turnId, entry.params.callId, entry.params.error ?? null])).toEqual([["provider-1", "call-provider-finish", null]]); + expectCleanClose(run); +}, 60_000); + +it.skipIf(process.platform === "win32")("keeps a Claude run on today's path when the caller does not ask for provider-started turns", async () => { + const run = await runProviderTurnScenario("live provider-turn provider-result", { providerStartedTurns: false }); + expect(run.outcome).toContain("native_finalization_missing"); + expect(run.turnStarts).toHaveLength(1); + expect(run.turnStarts[0]).not.toHaveProperty("providerStartedTurns"); + expect(run.notificationMethods).not.toContain("paperclip/runTerminal"); + expect(run.appended.some(event => event.payload.awaitingProviderTurn === true)).toBe(false); + expect(run.appended.some(event => event.payload.origin === "provider")).toBe(false); + expect(sidecarCommands(run.journalled)).not.toContain("session.provider_turn"); + expectCleanClose(run); +}, 60_000); + +it.skipIf(process.platform === "win32")("ends the wait at the cap and takes today's missing-result path when the provider never starts its turn", async () => { + const run = await runProviderTurnScenario("live provider-turn provider-turn-hold", { capMs: 300 }); + expect(run.outcome).toContain("native_finalization_missing"); + expect(run.completeRun).not.toHaveBeenCalled(); + expect(run.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ + terminalEvent: expect.objectContaining({ eventType: "turn.completed", payload: expect.objectContaining({ awaitingProviderTurn: true }) }) })); + expect(run.appended.some(event => event.payload.status === "provider_turn_wait_ended")).toBe(true); + expect(run.appended.some(event => event.payload.origin === "provider")).toBe(false); + expect(run.providerProcesses.length).toBeGreaterThan(1); + expect(run.providerProcesses.filter(entry => !entry.exited)).toEqual([]); + expectCleanClose(run); +}, 60_000); + +it.skipIf(process.platform === "win32")("ends the wait in seconds, not at the cap, when the provider process is lost while awaiting", async () => { + const run = await runProviderTurnScenario("live provider-turn provider-turn-hold provider-lost-after-arm", { capMs: 30_000 }); + expect(run.outcome).toContain("native_finalization_missing"); + expect(run.completeRun).not.toHaveBeenCalled(); + expect(run.appended.some(event => event.payload.awaitingProviderTurn === true)).toBe(true); + expect(run.elapsedMs).toBeLessThan(15_000); + expectCleanClose(run); +}, 60_000); + +it.skipIf(process.platform === "win32")("ends the wait in seconds, not at the cap, when the sidecar exits while awaiting", async () => { + const run = await runProviderTurnScenario("live provider-turn provider-turn-hold provider-sidecar-exit-after-arm", { capMs: 30_000 }); + expect(run.completeRun).not.toHaveBeenCalled(); + expect(run.appended.some(event => event.payload.awaitingProviderTurn === true)).toBe(true); + expect(run.elapsedMs).toBeLessThan(15_000); + expect(run.closeOutcome).toBe("provider_transport_failed: runner did not durably suspend before checkpoint"); + expect(unsettled(run.diagnostics)).toEqual([expect.stringContaining('"proofWindowEnd":"suspend_not_completed"')]); + expect(run.durable).not.toContain("conflicting duplicate"); +}, 60_000); + +it.skipIf(process.platform === "win32")("leaves a Claude turn without background work exactly as before", async () => { + const run = await runProviderTurnScenario("quiet provider-turn"); + expect(run.outcome).toContain("native_finalization_missing"); + expect(run.appended.some(event => event.payload.awaitingProviderTurn === true)).toBe(false); + expect(run.appended.some(event => event.payload.status === "provider_turn_wait_ended")).toBe(false); + expect(sidecarCommands(run.journalled)).not.toContain("session.provider_turn"); + expectCleanClose(run); +}, 60_000); + +it.skipIf(process.platform === "win32")("never opts a non-Claude ACPX agent in", async () => { + const run = await runProviderTurnScenario("live provider-turn provider-result", { agent: "codex", providerStartedTurns: true }); + expect(run.outcome).toContain("native_finalization_missing"); + expect(run.turnStarts[0]).not.toHaveProperty("providerStartedTurns"); + expect(run.notificationMethods).not.toContain("paperclip/runTerminal"); + expect(run.appended.some(event => event.payload.awaitingProviderTurn === true)).toBe(false); + expect(sidecarCommands(run.journalled)).not.toContain("session.provider_turn"); + expectCleanClose(run); +}, 60_000); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 6fc75db84f2..d42325ca874 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -1,3 +1,4 @@ +import { providerTurnToolCallSourceSeq } from "./provider-turn-tool-order.js"; import type { RunnerAttachmentDownloadGrant } from "../contracts/harness-driver.js"; import { readProviderFailure } from "../contracts/provider-failure.generated.js"; import { confirmAntigravityProbeNativeRetirement } from "../drivers/acpx/antigravity-probe-retirement.js"; @@ -104,7 +105,7 @@ import { releaseMaterializedNativeRuntimeSkills, } from "../drivers/runtime-context-materializer.js"; import { resolvePackagedRunnerBinary, resolvePackagedRunnerBinaryAsync } from "./runner-binary.js"; -import { RUNNERD_CANONICAL_ITEM, RUNNERD_RUNTIME_ACTIVITY } from "../drivers/codex/codex-driver-values.js"; +import { RUNNERD_CANONICAL_ITEM, RUNNERD_RUN_TERMINAL, RUNNERD_RUNTIME_ACTIVITY } from "../drivers/codex/codex-driver-values.js"; import { crashPoint } from "../crash-point.js"; import { isTerminalOperation, settleEarlierToolCalls, staleTerminalCallResult } from "./terminal-call-freshness.js"; @@ -1708,6 +1709,7 @@ export interface CapabilityRunnerdCodexTransportOptions extends RunnerExecutionD recoveryLaunch?: { requirements: RunnerProviderLaunchRequirements }; opencodePermissionMode?: NativeOpenCodePermissionMode; acpxAgent?: QualifiedAcpxAgent; + providerStartedTurns?: boolean; /** Explicit evaluation-only candidate selection, never derived from persisted session input. */ acpxCandidateProfile?: "pi" | "cursor" | "copilot" | "kimi"; /** Server/operator authority; never derived from persisted agent or provider input. */ @@ -7712,6 +7714,10 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#closedSignal.then(() => { throw new SemanticToolNotDispatchedError(); }), ]).catch(() => { throw new SemanticToolNotDispatchedError(); }); } + if (this.#providerStartedTurns()) { + const providerTurnCallSeq = providerTurnToolCallSourceSeq(core?.store.state.committedEvents ?? [], call.sourceEventId); + if (providerTurnCallSeq !== null) await this.#deliverNotificationsBefore(providerTurnCallSeq); + } try { this.#throwIfFailed(); } catch { @@ -7778,6 +7784,26 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { return this.#bindSemanticToolOutcome(call, outcome); } + #providerStartedTurns() { + return this.options.providerStartedTurns === true && this.options.provider === "acpx" && this.options.acpxAgent === "claude"; + } + + async #deliverNotificationsBefore(sourceSeq: number) { + while (this.#eventSourceSeq < sourceSeq - 1 || this.#deferredTurnStartEvents.some(event => event.sourceSeq < sourceSeq)) { + if (this.#closed || this.#failure) throw new SemanticToolNotDispatchedError(); + this.#pumpEvents(); + await new Promise(resolveWait => setTimeout(resolveWait, 10)); + } + let delivered!: () => void; + const barrier = new Promise(resolveBarrier => { delivered = resolveBarrier; }); + this.#queue.pushControl({ id: `provider-turn-order:${sourceSeq}`, method: "paperclip/providerTurnOrder", params: {} }, () => delivered()); + await Promise.race([ + barrier, + this.#failureSignal, + this.#closedSignal.then(() => { throw new SemanticToolNotDispatchedError(); }), + ]).catch(() => { throw new SemanticToolNotDispatchedError(); }); + } + #bindSemanticToolOutcome(call: { operationId: string; callId: string }, outcome: { result: unknown; isError?: boolean }) { if (call.operationId === "call_api") { const result = record(outcome.result); @@ -7945,6 +7971,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ...((this.options.provider ?? "codex") === "codex" && params.effort !== undefined ? { effort: params.effort } : {}), ...(reasoningMode === undefined ? {} : { reasoningMode }), ...(skills.length ? { skills } : {}), + ...(!compactionTurn && this.#providerStartedTurns() ? { providerStartedTurns: true } : {}), turnId: pendingTurnId, }, commandDeadline, @@ -8549,6 +8576,9 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { }); continue; } + if (event.eventType === "run.terminal" && this.#providerStartedTurns()) { + this.#queue.push({ method: "paperclip/runTerminal", params: { [RUNNERD_RUN_TERMINAL]: true, threadId: this.#threadId } }); + } const sessionUpdatePayload = record(eventPayload); const canonicalMethod = runnerdCanonicalNotificationMethod( event.eventType, From 45531b719eab6b2af25c18b35a882b4cc1aeebd6 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:30:03 -0600 Subject: [PATCH 04/19] perf(recovery): stop re-asserting a failed legacy run whose decision is recorded (#21621) 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 > - Stranded-work recovery checks tasks that are assigned to an agent but have no live run. It runs as a scoped-deadline queue that a change notification or a stored deadline wakes. > - For a failed legacy run, the check calls `terminalizeLegacyExecution` with the run's current status. When the run's recovery decision is already recorded (for example "continue in a fresh run from saved work"), that call changes nothing. But it still updated the run row and notified about 18 delivery queues, including the run's own recovery graph. > - The graph notification re-checked the same task, which re-asserted the same run again. The loop ran about once a second per waiting task, forever, with zero runs active. On a hosted instance this shows up as constant idle transactions. > - This pull request makes a re-assertion that changes nothing return before it writes or notifies. > - The benefit is that an idle instance does no stranded-recovery work for tasks that wait on a recorded decision. A real change (another run fails, a comment, a status change) still notifies and recovers at once. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/bug_report.yml`. **What happened?** With zero runs active, the server runs many transactions per second. A CPU profile groups most samples under `reconcileStrandedAssignedIssues` (`server/src/services/recovery/service.ts`). A local fixture on real PostgreSQL reproduces it: a task in `in_progress`, assigned to an agent, whose latest legacy run failed and whose recovery decision is recorded. Each check reaches the branch that terminalizes a failed legacy run that needs reconciliation (`service.ts`, the `legacyExecutionNeedsReconciliationWithEvidence` branch, and the same call in `enqueueStrandedIssueRecovery`). `terminalizeLegacyExecution` then: - updates the run with the same status (only `updated_at` changes); - calls `notifyExecutionRunWork`, `notifyInstructionCollection` and `notifyUnsafeWorkspaceExportRecovery`, which hint the run graph of the task and about 18 queues; - finds the recorded decision and returns. The graph hint re-checks the same task after the queue's 1-second pass interval, so the loop never ends. **Expected behavior** A check that finds nothing to change stores nothing and wakes nothing. Only a real change re-checks the task. **Steps to reproduce** 1. Create a task in `in_progress` assigned to an agent, with a failed legacy run (`adapter_failed`). 2. Start the issue-state recovery work. The boot pass records a fresh-continuation decision for the run. 3. Leave the instance idle. On master: 591,045 statements in 30 minutes for 10 such tasks (fake clock, real PostgreSQL), and one no-op `update "heartbeat_runs"` per task per second. **Paperclip version or commit** master at 7db92ea319. ## What Changed - `server/src/services/legacy-execution-recovery.ts`: - `terminalizeLegacyExecution` returns the unchanged run, without a write or a notification, when all of these are true: the call re-asserts the current status with no patch; the run has no workspace restore failure or required workspace recovery; the task's execution and checkout locks do not point at the run; and either the run needs no reconciliation (`reconcileIfNeeded`), no assignee or reviewer owns a decision, or the decision is already recorded. - Why the short-circuit is safe: stranded-work and quota checks re-assert the run's unchanged terminal status each time they revisit its task. Once the decision is recorded, that re-assertion changes nothing. If it wrote or notified anyway, the notifications would re-check the same task, which would re-assert the run again, about once a second for as long as the task waits. - `findRecordedLegacyDecision` returns the resolved decision already recorded for the run (a reconciliation for this run, an explicit user continuation with a real successor, or a no-replay hold). `decisionOwner` says whether the task's assignee or current reviewer owns a decision about the run. - The recorded-decision query moves into `findRecordedLegacyDecision`, and the owner condition into `decisionOwner`. The full path uses both helpers, so its behavior does not change. - `server/src/__tests__/issue-recovery-recorded-decision-idle.test.ts`: two new tests on real PostgreSQL. They use the real coordinator, the real issue-state recovery work and the production 5-minute backstop on a fake clock. ## Verification - `stays quiet for half an hour once each failed run has its decision`: 10 waiting tasks, zero runs. The test first checks that each failed run has a recorded decision, then counts statements over 30 idle minutes. - master: 591,045 statements (red). - this branch: 0 statements (green). No run is re-written or started, and no task moves. - `still recovers promptly when another run of a waiting task fails`: after 10 idle minutes, a new legacy run of one task fails and notifies like a finished run. - this branch: within 5 seconds, recovery creates the run's `legacy-execution:` hold. Within the next 6 minutes, the fresh-continuation fallback resolves that hold with `executionReconciliation.runId` set to the new run. Over the next 30 minutes there is no `update "heartbeat_runs"` and fewer than 5,000 statements (the assigned-work invariant keeps its own spaced re-checks). - master: 18,000 no-op `update "heartbeat_runs"` statements in the same window (red). - Neighbouring suites pass locally: `legacy-workspace-restore-recovery`, `legacy-workspace-restore-lock-contention`, `legacy-continuation-authority`, `heartbeat-process-recovery`, `issue-recovery-assignments`, `recovery-deadline-ordinary-bootstrap`, `issue-recovery-deadlines` (600 of 601 in one parallel run; `resolves a run's task graph through index lookups` failed once under machine load on a planner row count, and passes alone; it does not use the changed code). - `npx tsc --noEmit -p server/tsconfig.json` passes. ## Risks - Low risk. The short-circuit applies only when the full path would also write nothing except `updated_at`. Every other case (status change, patch, workspace restore evidence, an owned lock, no recorded decision) takes the unchanged full path. - A re-assertion no longer re-sends notifications. Queues that relied on that repeated hint as a side effect lose it. The first terminalization of a run still sends all notifications, and run, comment and status writes still send their own. - No schema or API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, local PostgreSQL test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Related: #21552, #21616, #21617. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ...ue-recovery-recorded-decision-idle.test.ts | 88 ++++++++++++++ .../src/services/legacy-execution-recovery.ts | 113 ++++++++++-------- 2 files changed, 154 insertions(+), 47 deletions(-) create mode 100644 server/src/__tests__/issue-recovery-recorded-decision-idle.test.ts diff --git a/server/src/__tests__/issue-recovery-recorded-decision-idle.test.ts b/server/src/__tests__/issue-recovery-recorded-decision-idle.test.ts new file mode 100644 index 00000000000..3cbbd7d2504 --- /dev/null +++ b/server/src/__tests__/issue-recovery-recorded-decision-idle.test.ts @@ -0,0 +1,88 @@ +import { setImmediate as immediate } from "node:timers/promises"; +import { and, eq, sql } from "drizzle-orm"; +import { expect, it, vi } from "vitest"; +import { agents, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db"; +import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; + +describeIssueRecovery("stranded recovery of runs with a recorded decision", () => { + const state = issueRecoveryFixture(); + const TASKS = 10; + + async function seed() { + const f = await state.fixture(); + const db = state.db; + await db.update(agents).set({ status: "error" }).where(eq(agents.id, f.agentId)); + const tasks = await db.insert(issues).values(Array.from({ length: TASKS }, (_, index) => ({ + companyId: f.companyId, title: `Waiting task ${index}`, status: "in_progress", assigneeAgentId: f.agentId, + }))).returning({ id: issues.id }); + await db.insert(heartbeatRuns).values(tasks.map(task => ({ companyId: f.companyId, agentId: f.agentId, + status: "failed", errorCode: "adapter_failed", finishedAt: new Date(Date.now() - 60 * 60_000), + contextSnapshot: { issueId: task.id } }))); + return { ...f, tasks }; + } + + async function advance(ms: number) { + const until = Date.now() + ms; + while (Date.now() < until) { + await vi.advanceTimersByTimeAsync(Math.min(500, until - Date.now())); + await Promise.allSettled([...state.passes]); await immediate(); + } + } + + async function countStatements(work: () => Promise) { + const statements: string[] = [], prior = state.db.$client.options.debug; + state.db.$client.options.debug = (_connection, query) => { statements.push(query); }; + try { await work(); } finally { state.db.$client.options.debug = prior; } + return statements; + } + + async function startAndRecordDecisions(f: Awaited>) { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + await state.start({}); + await advance(6 * 60_000); + const decided = await state.db.select({ issueId: issueRecoveryActions.sourceIssueId }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, f.companyId), eq(issueRecoveryActions.status, "resolved"), + sql`${issueRecoveryActions.evidence} ? 'executionReconciliation'`)); + expect(new Set(decided.map(row => row.issueId))).toEqual(new Set(f.tasks.map(task => task.id))); + } + + it("stays quiet for half an hour once each failed run has its decision", async () => { + const f = await seed(); + await startAndRecordDecisions(f); + const runsBefore = await state.db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, updatedAt: heartbeatRuns.updatedAt }) + .from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId)); + const idle = await countStatements(() => advance(30 * 60_000)); + expect(idle).toHaveLength(0); + const runsAfter = await state.db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, updatedAt: heartbeatRuns.updatedAt }) + .from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId)); + const byId = (a: { id: string }, b: { id: string }) => a.id.localeCompare(b.id); + expect(runsAfter.sort(byId)).toEqual(runsBefore.sort(byId)); + const statuses = await state.db.select({ status: issues.status }).from(issues).where(eq(issues.companyId, f.companyId)); + expect(statuses.every(row => row.status === "in_progress")).toBe(true); + }, 300_000); + + it("still recovers promptly when another run of a waiting task fails", async () => { + const f = await seed(); + await startAndRecordDecisions(f); + await advance(10 * 60_000); + const target = f.tasks[0].id; + const [failed] = await state.db.transaction(async tx => { + const rows = await tx.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "failed", + errorCode: "adapter_failed", finishedAt: new Date(), contextSnapshot: { issueId: target } }).returning(); + await notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: rows[0].id }); + return rows; + }); + const actionFor = async () => (await state.db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, f.companyId), eq(issueRecoveryActions.sourceIssueId, target), + eq(issueRecoveryActions.fingerprint, `legacy-execution:${failed.id}`))))[0]; + await advance(5_000); + expect(await actionFor()).toMatchObject({ kind: "active_run_watchdog", evidence: expect.objectContaining({ runId: failed.id }) }); + await advance(6 * 60_000); + expect(await actionFor()).toMatchObject({ status: "resolved", + evidence: expect.objectContaining({ executionReconciliation: expect.objectContaining({ runId: failed.id }) }) }); + const after = await countStatements(() => advance(30 * 60_000)); + expect(after.filter(query => query.startsWith("update \"heartbeat_runs\""))).toEqual([]); + expect(after.length).toBeLessThan(TASKS * 500); + }, 300_000); +}); diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index 6d48112de2d..0f9fe34c63d 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -111,6 +111,58 @@ export async function legacyExecutionNeedsReconciliationWithEvidence(db: Db, run && !(await isPreDispatchExecutionWaitVerified(db, run))); } +async function findRecordedLegacyDecision(db: Db, run: Run, taskId: string, resultJson: Run["resultJson"]) { + const [reconciled] = await db.select({ id: issueRecoveryActions.id }) + .from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, run.companyId), + eq(issueRecoveryActions.sourceIssueId, taskId), + eq(issueRecoveryActions.status, "resolved"), + ...(hasRequiredWorkspaceRecovery(resultJson) ? [ + sql`${issueRecoveryActions.evidence}->'workspaceRestoreRecovery'->>'schema' = ${LEGACY_WORKSPACE_RECOVERY_SCHEMA}`, + ] : []), + or( + sql`${issueRecoveryActions.evidence}->'executionReconciliation'->>'runId' = ${run.id}`, + and( + sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, + sql`exists ( + select 1 from heartbeat_runs successor + where successor.id = ${canonicalExecutionUuid(sql`${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'runId'`)} + and successor.company_id = ${run.companyId} and successor.agent_id = ${run.agentId} + and coalesce(successor.native_issue_id::text, successor.issue_id::text, + successor.context_snapshot->>'issueId') = ${taskId} + and successor.context_snapshot->>'previousRunId' = ${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'previousRunId' + and successor.context_snapshot->'explicitUserContinuation'->>'previousRunId' = ${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'previousRunId' + and successor.context_snapshot->'explicitUserContinuation'->>'commentId' is not distinct from + ${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'commentId' + )`, + ), + and( + sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, + or(sql`${issueRecoveryActions.evidence}->>'workspaceRestoreFailure' = 'restore_unsafe_archive'`, + sql`${issueRecoveryActions.evidence}->'workspaceRestoreRecovery'->>'schema' = ${LEGACY_WORKSPACE_RECOVERY_SCHEMA}`), + sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, + ), + and( + eq(issueRecoveryActions.cause, LEGACY_RECOVERY_CAUSE), + eq(issueRecoveryActions.fingerprint, `legacy-execution:${run.id}`), + sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, + sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, + ), + ), + )).limit(1); + return reconciled ?? null; +} + +function decisionOwner(task: typeof issues.$inferSelect, run: Run, retainedLeaseCount: number) { + const review = task.status === "in_review" ? parseIssueExecutionState(task.executionState) : null; + const isCurrentReviewer = review?.status === "pending" && + review.currentParticipant?.type === "agent" && review.currentParticipant.agentId === run.agentId; + const owns = !isSupersededConversationRun(task, run) && + (task.assigneeAgentId === run.agentId || isCurrentReviewer) && + (!["done", "cancelled"].includes(task.status) || retainedLeaseCount > 0); + return { owns, isCurrentReviewer }; +} + /** Persist the failed legacy run, owned lock release and operator decision together. */ export async function terminalizeLegacyExecution(input: { db: Db; @@ -152,6 +204,16 @@ export async function terminalizeLegacyExecution(input: { )).for("update"); if (!current || (current.runtimeMode !== "legacy" && !(input.recordRestoreFailureOnly && current.runtimeMode === "native")) || (!input.recordRestoreFailureOnly && !(input.fromStatuses ?? [run.status]).includes(current.status))) return null; + if (!input.recordRestoreFailureOnly && current.status === status && Object.keys(patch ?? {}).length === 0 + && !hasWorkspaceRestoreFailure(current.resultJson) && !hasRequiredWorkspaceRecovery(current.resultJson) + && task?.executionRunId !== run.id && task?.checkoutRunId !== run.id) { + const [unchanged] = await tx.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId))); + if (input.reconcileIfNeeded && !(await legacyExecutionNeedsReconciliationWithEvidence(tx as unknown as Db, unchanged))) + return unchanged; + if (!task || !decisionOwner(task, unchanged, 0).owns) return unchanged; + if (await findRecordedLegacyDecision(tx as unknown as Db, run, task.id, unchanged.resultJson)) return unchanged; + } if (patch?.resultJson !== undefined) patch = { ...patch, resultJson: preserveWorkspaceRestoreRecoveryMetadata(current.resultJson, input.recordRestoreFailureOnly ? { ...current.resultJson, ...patch.resultJson } : patch.resultJson), @@ -255,58 +317,15 @@ export async function terminalizeLegacyExecution(input: { fingerprint, attemptCount: 1 }); return updated; } - const review = task?.status === "in_review" ? parseIssueExecutionState(task.executionState) : null; - const isCurrentReviewer = review?.status === "pending" && - review.currentParticipant?.type === "agent" && review.currentParticipant.agentId === run.agentId; - if ( - task && - !isSupersededConversationRun(task, updated) && - (task.assigneeAgentId === run.agentId || isCurrentReviewer) && - (!["done", "cancelled"].includes(task.status) || retainedLeaseIds.length > 0) - ) { + const owner = task ? decisionOwner(task, updated, retainedLeaseIds.length) : null; + if (task && owner?.owns) { + const { isCurrentReviewer } = owner; // Periodic stranded-work checks may revisit this terminal run before its // reconciled or explicitly requested continuation is dispatched. Preserve // its recorded decision instead of creating another hold. The explicit // receipt must identify an actual successor under the same task/agent; // retained user intent remains authoritative after that successor finishes. - const [reconciled] = await tx.select({ id: issueRecoveryActions.id }) - .from(issueRecoveryActions).where(and( - eq(issueRecoveryActions.companyId, run.companyId), - eq(issueRecoveryActions.sourceIssueId, task.id), - eq(issueRecoveryActions.status, "resolved"), - ...(hasRequiredWorkspaceRecovery(updated.resultJson) ? [ - sql`${issueRecoveryActions.evidence}->'workspaceRestoreRecovery'->>'schema' = ${LEGACY_WORKSPACE_RECOVERY_SCHEMA}`, - ] : []), - or( - sql`${issueRecoveryActions.evidence}->'executionReconciliation'->>'runId' = ${run.id}`, - and( - sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, - sql`exists ( - select 1 from heartbeat_runs successor - where successor.id = ${canonicalExecutionUuid(sql`${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'runId'`)} - and successor.company_id = ${run.companyId} and successor.agent_id = ${run.agentId} - and coalesce(successor.native_issue_id::text, successor.issue_id::text, - successor.context_snapshot->>'issueId') = ${task.id} - and successor.context_snapshot->>'previousRunId' = ${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'previousRunId' - and successor.context_snapshot->'explicitUserContinuation'->>'previousRunId' = ${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'previousRunId' - and successor.context_snapshot->'explicitUserContinuation'->>'commentId' is not distinct from - ${issueRecoveryActions.evidence}->'explicitUserContinuation'->>'commentId' - )`, - ), - and( - sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, - or(sql`${issueRecoveryActions.evidence}->>'workspaceRestoreFailure' = 'restore_unsafe_archive'`, - sql`${issueRecoveryActions.evidence}->'workspaceRestoreRecovery'->>'schema' = ${LEGACY_WORKSPACE_RECOVERY_SCHEMA}`), - sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, - ), - and( - eq(issueRecoveryActions.cause, LEGACY_RECOVERY_CAUSE), - eq(issueRecoveryActions.fingerprint, `legacy-execution:${run.id}`), - sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, - sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, - ), - ), - )).limit(1); + const reconciled = await findRecordedLegacyDecision(tx as unknown as Db, run, task.id, updated.resultJson); if (reconciled) return updated; await issueRecoveryActionService(tx as unknown as Db).upsertSourceScoped({ companyId: run.companyId, From 890dcbdd66f177dcdd6fc724f7a87b590060589b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:59:17 -0600 Subject: [PATCH 05/19] fix(native): wait for a live warm session owner during a deploy overlap (#21627) 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 deploy swaps servers with an overlap: the outgoing server still serves while the incoming server starts new runs > - A warm agent session stays open in the server process that ran the last turn, after that run finished > - The incoming server took over a warm session while the outgoing server was alive and still held it, because the finished run's finalization lease ends at commit > - The takeover then failed, the task went blocked with a Retry, and in one case a retry loop ran 27 times on the same sandbox > - This pull request makes the incoming server wait while the server that holds the warm session is alive, makes the outgoing server close idle warm sessions as soon as it leaves new runs to the replacement, and stops the retry loop when the promised fresh sandbox does not come > - The benefit is that a follow-up during a deploy finishes without a person, and no Runner ever gets two controllers ## Linked Issues or Issue Description **What happened?** A zero-downtime release-swap test (Gate B, wave B1, master aaec67b891) found two failures with one cause. Task 1: run A finished on the outgoing server at 15:13:56. Its warm session stayed idle in that server. The incoming server claimed the follow-up at 15:13:57. `inspectRemoteWarmSessionRecovery` asked `evaluateNativeControllerTakeover`, which allowed the takeover with `remote_controller_lease_released_or_expired`. That lease covers the finished run, not the warm session. The outgoing server was alive until 15:18:18. `runner.prp.authenticate` failed after 62.3 s, the run failed with `remote_warm_session_unproven`, the failure was saved as ambiguous and owned by the board, and the task stayed blocked with a Retry. Task 2: the same shape on a later swap started 27 automatic runs in 13 minutes. Fourteen of them said "The next attempt starts on a fresh sandbox", but each one resumed the same sandbox and got the same refusal (`journal_unsettled`). **Expected behavior** A follow-up claimed during an overlap waits for the warm session owner to let go, then continues with no Retry banner and no second controller. If the outgoing server dies with the session open, the takeover continues after its ownership ends. A message that promises a fresh sandbox is true, or the retries stop after a bounded number with a true state. **Steps to reproduce** 1. Run the restart-chaos release-swap preset with a warm (opencode or codex) staging mix. 2. Let a run finish on the outgoing server after the traffic switch, with a follow-up comment already queued. 3. See the follow-up fail with `remote_warm_session_unproven` and the task go blocked. **Paperclip version or commit** master aaec67b891 and 45531b719e. **Deployment mode** Hosted deploy overlap (release swap) with Daytona sandboxes. ## What Changed - `remote-warm-session-recovery.ts`: before live adoption, the run proves that the server process that ran the finished turn is gone. It uses the shared owner proof (`proveOwnerGone`): a PID check in the same process space, or the `controller_instances` lease in another process space. While that server is alive, the run defers with the existing `native_controller_recovery_waiting_for_owner` wait and checks again after 5 s. The wait ends when the server exits or is fenced, or when the finished turn's warm window (idle timeout plus two minutes) ends. - `native-session-executor.ts` and `run-start-handover.ts`: a server that leaves new run starts to a replacement closes its idle warm sessions after 1 s, through the existing idle-timeout close. A session that becomes idle after that closes after 1 s too. This is the same close that shutdown already does, done earlier. - `predecessor-retirement-fallback.ts`: when a retry meets an unretired owner on the same sandbox that its source already asked to replace, it does not ask again. The run fails without another automatic retry, and the task shows a Retry. - `predecessor-retirement.ts`: the error no longer says "The next attempt starts on a fresh sandbox", because the replacement is only a request. - `doc/execution-semantics.md`: documents the owner wait, the hand-off at the swap, and the retry stop. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-controller-recovery.integration.test.ts` - New: "waits while the outgoing server that ran the finished turn still holds its warm session, then takes it over once that server exits" (red on master: master returned a takeover while the owner was alive). - New: "waits for a live outgoing server in another process space until its controller lease ends" (red on master). - New: "stops waiting for a live outgoing server once the finished turn's warm window has closed" (bound check). - `cd server && npx vitest run src/__tests__/heartbeat-native-predispatch-retry.test.ts` - New: "stops retrying with a truthful failure when the next attempt met the same unretired sandbox instead of a fresh one" (red on master: master scheduled another retry on the same sandbox). - `cd server && npx vitest run src/services/native-runtime/native-session-executor.test.ts -t "replacement server starts"` - New: "closes a warm session promptly when a replacement server starts this server's runs (before/after the turn ends)" (both red on master). - Focused suites: native-session-executor, remote-warm-session-recovery, native-controller-recovery, native-recovered-owner-followup, native-runner-restart-recovery, heartbeat-native-predispatch-retry, environment-runtime-reusable-resume-replacement, task-interruption-presentation, sandbox-runner-port-holders. - `npx tsc --noEmit -p server/tsconfig.json` passes. `pnpm verify` exits 2 (a doc is a global CI input), so required CI supplies broad coverage. - Not run here: the restart-chaos release-swap wave. The maintainer runs it after merge. ## Risks - A follow-up can now wait up to the outgoing server's remaining overlap when that server cannot close its idle session. Before, it failed and needed a Retry. The wait is bounded by the owner's exit or the warm window. - The outgoing server closes idle warm sessions earlier during an overlap. The next turn then resumes from a suspended Runner instead of a live one, as it already does after a shutdown. - A retry chain that meets the same unretired sandbox twice now stops one attempt earlier than the shared cap. The task shows a Retry instead of looping. - Rows without a recorded process space keep the existing one-release local proof, so they behave as before outside the same host. - Previous-release state: this change adds no persisted field. Finalization rows saved by the previous release already record the controller boot, PID, process space and start time, so they carry forward. A follow-up already deferred by the previous release resumes through the same wait code. - Runtime cost: the owner proof adds one `ps` start-time read (same process space) or one `controller_instances` row read (other process space) per inspection. It runs once per attempt, at most every 5 s while a live owner holds the session. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), agentic coding with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/execution-semantics.md | 19 +++ ...heartbeat-native-predispatch-retry.test.ts | 40 ++++++- .../predecessor-retirement-fallback.ts | 12 +- ...ve-controller-recovery.integration.test.ts | 111 +++++++++++++++++- .../native-session-executor.test.ts | 45 ++++++- .../native-runtime/native-session-executor.ts | 20 +++- .../native-runtime/predecessor-retirement.ts | 2 +- .../remote-warm-session-recovery.ts | 33 ++++++ server/src/services/run-start-handover.ts | 5 + 9 files changed, 277 insertions(+), 10 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index c5801b8d8ec..ae94ee4e86f 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3823,6 +3823,25 @@ in the sandbox, and only the killed server could have adopted it. A refusal because the new run itself is no longer admitted (stopped, reassigned, paused or no longer owned by this controller) stays an ordinary failure. +The finished run's finalization lease ends at commit, but its warm session +stays with the server process that ran it. Before live adoption, the new run +proves that process gone with the shared owner proof: a dead PID in the same +process space, or a stopped or fenced controller instance lease in another one. +While that server is still alive, the run defers with +`native_controller_recovery_waiting_for_owner` and checks again every few +seconds. It never opens a second controller on the same Runner. The wait ends +when that server exits, closes the session, or the finished run's warm window +(its idle timeout plus two minutes) ends. A server that leaves new run starts +to a replacement during a deploy overlap closes its idle warm sessions within +a second, and closes each session that becomes idle after that, so the +replacement usually waits only for that close. + +A fresh sandbox is only requested, not guaranteed: the next acquisition +replaces the marked sandbox only when the saved workspace and harness backup +allow it. When the next attempt meets an unretired owner again on the same +sandbox, that attempt stops the automatic retries. It fails without another +fallback, and the task shows a Retry. + A follow-up on a warm session starts with its predecessor's Runner process identity. That inherited identity alone does not count as a process of the follow-up when it proves that it left the workspace unchanged. The identity diff --git a/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts b/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts index a99d4ca48c1..0a6c76312d5 100644 --- a/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts +++ b/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts @@ -44,7 +44,7 @@ type AdmissionFailure = { remaining: number; turnNeverIssued: boolean; environme sessionRoots: string[] }; function nativeBackend(db: ReturnType, options: { failDescriptorOnce?: { failed: boolean }; - unretiredPredecessorOnce?: { failed: boolean; environmentId: string; taskBlocked?: boolean }; turnMessages?: Map; + unretiredPredecessorOnce?: { failed: boolean; environmentId: string; taskBlocked?: boolean; repeat?: string[] }; turnMessages?: Map; admissionFailure?: AdmissionFailure } = {}): NonNullable { return execution => { @@ -87,7 +87,8 @@ function nativeBackend(db: ReturnType, options: { failDescripto throw Object.assign(new Error("could not serialize access due to concurrent update"), { name: "PostgresError", code: "40001" }); } const unretired = options.unretiredPredecessorOnce; - if (unretired && !unretired.failed) { + if (unretired && (!unretired.failed || unretired.repeat)) { + unretired.repeat?.push(execution.binding.runId); // Staging: this run resumed the task's reused sandbox, where // the previous run's warm Runner could not be retired before any // provider work. The executor reports that after its coordinator claim. @@ -242,6 +243,41 @@ describe.skipIf(!support.supported)("heartbeat native pre-dispatch failure retry } }, 90_000); + it("stops retrying with a truthful failure when the next attempt met the same unretired sandbox instead of a fresh one", async () => { + const { companyId } = fixture.current; + const db = createDb(fixture.current.temporary.connectionString, { maxConnections: 4 }); + const [environment] = await db.insert(environments).values({ name: `reused-${randomUUID()}`, driver: "sandbox" }).returning(); + const attempts: string[] = []; + const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db, + { unretiredPredecessorOnce: { failed: false, environmentId: environment!.id, repeat: attempts } }) }); + try { + const { issueId, runId } = await startTask(db, heartbeat); + const [first] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.retryOfRunId, runId))); + expect(first).toMatchObject({ scheduledRetryReason: "interrupted_preparation", scheduledRetryAttempt: 1 }); + expect(await heartbeat.promoteDueScheduledRetries()).toMatchObject({ promoted: 1 }); + await heartbeat.resumeQueuedRuns(); + await waitForCondition("the second attempt to end", async () => + (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, first!.id)))[0]?.status === "failed"); + await waitForCondition("the second attempt to settle", () => heartbeat.getTaskDrainStatus().quiescent); + expect(attempts).toEqual([runId, first!.id]); + const [second] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, first!.id)); + expect(second?.resultJson ?? {}).not.toHaveProperty("predecessorRetirementFallback"); + expect(second?.error ?? "").not.toMatch(/fresh sandbox/i); + expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.retryOfRunId, first!.id)))).toHaveLength(0); + expect(await heartbeat.promoteDueScheduledRetries()).toMatchObject({ promoted: 0 }); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ canRetry: true }); + } finally { + await heartbeat.drainActiveRunExecutions(); + await closeIdleWarmNativeSessionsForRestart(); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(and( + eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"]))); + await db.$client.end(); + } + }, 90_000); + it.each([ { title: "continues a follow-up on a blocked task whose predecessor could not be retired", blockedAfter: false }, { title: "does not continue a task that was blocked only after its run failed", blockedAfter: true }, diff --git a/server/src/services/heartbeat/predecessor-retirement-fallback.ts b/server/src/services/heartbeat/predecessor-retirement-fallback.ts index 648ce5aee87..354406f9da3 100644 --- a/server/src/services/heartbeat/predecessor-retirement-fallback.ts +++ b/server/src/services/heartbeat/predecessor-retirement-fallback.ts @@ -4,7 +4,7 @@ import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema } from import { persistActivity } from "../activity-log.js"; import { hasNativeExecutionStartEvidence } from "../native-runtime/native-restart-recovery.js"; import { - findNativePredecessorRetirementUnproven, REPLACE_BEFORE_REUSE_KEY, REPLACE_BEFORE_REUSE_SCHEMA, + findNativePredecessorRetirementUnproven, readPredecessorRetirementFallback, REPLACE_BEFORE_REUSE_KEY, REPLACE_BEFORE_REUSE_SCHEMA, type PredecessorRetirementFallback, type ReplaceBeforeReuseMarker, } from "../native-runtime/predecessor-retirement.js"; import { FAILED_BEFORE_PROVIDER_TURN_KEY, FAILED_BEFORE_PROVIDER_TURN_SCHEMA, findNativeFailedBeforeProviderTurn, @@ -47,6 +47,7 @@ export async function preparePredecessorRetirementFallback(db: Db, run: Run, err : eq(environmentLeases.leasePolicy, "reuse_by_environment"), isNotNull(environmentLeases.providerLeaseId), )).for("update")).filter(lease => !failure.providerLeaseId || lease.providerLeaseId === failure.providerLeaseId); if (leases.length === 0 && !beforeProviderTurn) return null; + if (await replacementAlreadyMissed(tx as unknown as Db, current, leases.map(lease => lease.providerLeaseId!))) return null; if (beforeProviderTurn) await tx.update(heartbeatRuns).set({ runnerProfileJson: sql`coalesce(${heartbeatRuns.runnerProfileJson}, '{}'::jsonb) || ${JSON.stringify({ [FAILED_BEFORE_PROVIDER_TURN_KEY]: { schema: FAILED_BEFORE_PROVIDER_TURN_SCHEMA, cause: beforeProviderTurn.code, proof: beforeProviderTurn.proof, technicalCause: beforeProviderTurn.technicalCause } })}::jsonb` }) @@ -68,6 +69,15 @@ export async function preparePredecessorRetirementFallback(db: Db, run: Run, err }); } +async function replacementAlreadyMissed(db: Db, run: Pick, + providerLeaseIds: string[]): Promise { + if (!run.retryOfRunId || providerLeaseIds.length === 0) return false; + const [source] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.id, run.retryOfRunId))); + const replaced = readPredecessorRetirementFallback(source?.resultJson)?.replacedProviderLeaseIds ?? []; + return providerLeaseIds.some(id => replaced.includes(id)); +} + /** * After the failed run ended: hand its prepared remote workspace on at the * saved version, but only through the shared unchanged-files proof (no runner diff --git a/server/src/services/native-runtime/native-controller-recovery.integration.test.ts b/server/src/services/native-runtime/native-controller-recovery.integration.test.ts index e91afae1b21..739a56e3895 100644 --- a/server/src/services/native-runtime/native-controller-recovery.integration.test.ts +++ b/server/src/services/native-runtime/native-controller-recovery.integration.test.ts @@ -10,7 +10,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { agentTaskSessions, agents, companies, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, nativeRunnerCheckpoints } from "@paperclipai/db"; +import { agentTaskSessions, agents, companies, controllerInstances, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, nativeRunnerCheckpoints } from "@paperclipai/db"; import { DurablePrpControlPlane, parseNativeExecutionInput, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js"; import { startRecoveryPostgres, recoveryPostgresSupport } from "../../__tests__/helpers/recovery-postgres.js"; import { createIsolatedTestHome } from "../../__tests__/helpers/isolated-test-home.js"; @@ -24,6 +24,9 @@ import { AgentDirectoryPreparationDeferral, deferRunForBusyAgentDirectory, prepa import { AgentDirectoryOperationBusyError } from "../agent-directory-working-copies.js"; import { readNativeControllerRecoveryInventory } from "./native-controller-recovery-inventory.js"; import { inspectRemoteWarmSessionRecovery } from "./remote-warm-session-recovery.js"; +import { currentProcessSpaceHash } from "../controller-process-identity.js"; +import { registerControllerInstanceDb, resetControllerInstanceLeaseForTests } from "../controller-instance-lease.js"; +import { readProcessStartedAt } from "../hot-restart.js"; describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable discovery and import", () => { let database: Awaited>; @@ -535,6 +538,112 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "duplicate", runIds: [runId], now: deadline })).toEqual([]); }); + async function seedWarmFollowUpOnOldServer() { + const fixture = await seed(), runId = randomUUID(), environmentId = randomUUID(); + const previous = parseNativeExecutionInput({ + schema: "paperclip.native-execution-input.v1", provider: { kind: "codex", model: null }, + binding: { companyId, agentId, issueId: fixture.scope.issueId, runId: fixture.scope.runId, executionWorkspaceId: randomUUID() }, + task: { identifier: "NCD-9", title: "Answer the follow-up", description: null, prompt: "Continue.", workMode: "standard" }, + workspace: { cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: fixture.scope.normalizedSessionId, driverKind: "codex_app_server", + protocolVersion: 1, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 600_000 } }, + completionContract: { id: randomUUID(), sha256: "fixture", schemaVersion: "paperclip.completion-contract.v1", + contract: { revision: "1", objective: "Continue.", criteria: [{ id: "objective", requirement: "Save the result." }] } }, + credentialBindings: [], interactionResponses: [], + }); + const current = { ...previous, binding: { ...previous.binding, runId } }; + const checkpoint: PersistedNativeSession = { ...fixture.snapshot, driverKind: "codex_app_server", + providerSessionId: "warm-provider-session", activeTurnId: null, pendingRuntimeRequests: [] }; + await db.update(heartbeatRuns).set({ finishedAt: new Date(), runnerProfileJson: { ...fixture.profile, nativeExecutionInput: previous, + sessionCheckpoint: checkpoint, nativeControllerRecovery: createNativeControllerRecovery(checkpoint, compatibility, + { runId: fixture.scope.runId, runnerInstanceId: fixture.native.runnerInstanceId, normalizedSessionId: fixture.scope.normalizedSessionId }) } }) + .where(eq(heartbeatRuns.id, fixture.scope.runId)); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: fixture.scope.issueId, + nativeSessionId: fixture.scope.normalizedSessionId, status: "running", runtimeMode: "native", + runnerProfileJson: { nativeExecutionInput: current, sessionCheckpoint: { ...checkpoint, identity: { ...checkpoint.identity, runId } } } }); + await db.insert(nativeRunFinalizations).values({ companyId, issueId: fixture.scope.issueId, runId, phase: "observed" }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, fixture.scope.issueId)); + await db.insert(environments).values({ id: environmentId, name: `Warm ${environmentId}`, driver: "sandbox" }); + await db.insert(environmentLeases).values({ companyId, environmentId, issueId: fixture.scope.issueId, + heartbeatRunId: fixture.scope.runId, provider: "daytona", providerLeaseId: "warm-sandbox", status: "released", + metadata: { remoteCwd: "/workspace" } }); + const identity = { runId: fixture.scope.runId, normalizedSessionId: fixture.scope.normalizedSessionId, + runnerInstanceId: fixture.native.runnerInstanceId, environmentLeaseId: fixture.native.environmentLeaseId, + turnId: fixture.native.turnId, itemId: fixture.native.itemId }; + const inspect = () => inspectRemoteWarmSessionRecovery({ db, execution: current, identity, + target: { kind: "remote", transport: "sandbox", environmentId, leaseId: randomUUID(), providerKey: "daytona", + remoteCwd: "/workspace", sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "warm-sandbox" } } as never, + readControlState: () => ({ identity, commands: [{ type: "turn.start", status: "completed" }], + committedEvents: [{ eventType: "run.terminal", envelope: identity }] }), + matchesExecution: saved => saved.binding.runId === fixture.scope.runId, + loadCheckpoint: () => checkpoint, canReuseProcess: () => true, + }); + const recordOwner = (owner: Partial) => db.update(nativeRunFinalizations) + .set(owner).where(eq(nativeRunFinalizations.runId, fixture.scope.runId)); + return { fixture, runId, current, identity, inspect, recordOwner }; + } + + it("waits while the outgoing server that ran the finished turn still holds its warm session, then takes it over once that server exits", async () => { + const oldServer = spawn(process.execPath, ["-e", "setInterval(() => {}, 60_000)"], { stdio: "ignore" }); + try { + await new Promise(resolve => oldServer.once("spawn", resolve)); + const startedAt = await readProcessStartedAt(oldServer.pid!); + expect(startedAt).toBeTruthy(); + const { inspect, recordOwner, runId, current } = await seedWarmFollowUpOnOldServer(); + await recordOwner({ controllerBootId: randomUUID(), controllerPid: oldServer.pid!, controllerHostHash: currentProcessSpaceHash(), + controllerProcessStartedAt: new Date(startedAt!), leaseOwner: null, leaseExpiresAt: null }); + const before = Date.now(); + const waiting = await inspect().catch(error => error); + expect(waiting).toBeInstanceOf(NativeControllerRecoveryWaitingError); + expect(waiting.retryAt.getTime()).toBeGreaterThan(before); + expect(waiting.retryAt.getTime()).toBeLessThanOrEqual(Date.now() + 10_000); + await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt }); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0]) + .toMatchObject({ phase: "retryable_failure", attempt: 0, failureCode: NATIVE_RETAINED_OWNER_WAIT, resultId: null }); + const [task] = await db.select().from(issues).where(eq(issues.executionRunId, runId)); + expect(task?.status).toBe("in_progress"); + + const exited = new Promise(resolve => oldServer.once("exit", resolve)); + oldServer.kill("SIGKILL"); + await exited; + const recovered = await inspect(); + expect(recovered?.identity.runId).not.toBe(runId); + expect(recovered?.reuseProcess).toBe(true); + } finally { + oldServer.kill("SIGKILL"); + } + }); + + it("waits for a live outgoing server in another process space until its controller lease ends", async () => { + const { inspect, recordOwner } = await seedWarmFollowUpOnOldServer(); + const oldBoot = randomUUID(); + await recordOwner({ controllerBootId: oldBoot, controllerPid: 7, controllerHostHash: "outgoing-container", + controllerProcessStartedAt: new Date(Date.now() - 600_000), leaseOwner: null, leaseExpiresAt: null }); + await db.insert(controllerInstances).values({ bootId: oldBoot, processSpace: "outgoing-container", pid: 7, + leaseExpiresAt: new Date(Date.now() + 90_000) }); + registerControllerInstanceDb(db); + try { + await expect(inspect()).rejects.toBeInstanceOf(NativeControllerRecoveryWaitingError); + await db.update(controllerInstances).set({ stoppedAt: new Date() }).where(eq(controllerInstances.bootId, oldBoot)); + await expect(inspect()).resolves.not.toBeNull(); + } finally { resetControllerInstanceLeaseForTests(); } + }); + + it("stops waiting for a live outgoing server once the finished turn's warm window has closed", async () => { + const oldServer = spawn(process.execPath, ["-e", "setInterval(() => {}, 60_000)"], { stdio: "ignore" }); + try { + await new Promise(resolve => oldServer.once("spawn", resolve)); + const startedAt = await readProcessStartedAt(oldServer.pid!); + const { inspect, recordOwner, fixture } = await seedWarmFollowUpOnOldServer(); + await recordOwner({ controllerBootId: randomUUID(), controllerPid: oldServer.pid!, controllerHostHash: currentProcessSpaceHash(), + controllerProcessStartedAt: new Date(startedAt!), leaseOwner: null, leaseExpiresAt: null }); + await db.update(heartbeatRuns).set({ finishedAt: new Date(Date.now() - 3_600_000) }).where(eq(heartbeatRuns.id, fixture.scope.runId)); + await expect(inspect()).resolves.not.toBeNull(); + } finally { + oldServer.kill("SIGKILL"); + } + }); + it("sends a re-wake after a crash restart to a fresh sandbox when the parked predecessor's warm Runner cannot be adopted", async () => { const fixture = await seed(), runId = randomUUID(), environmentId = randomUUID(), leaseId = randomUUID(); const previous = parseNativeExecutionInput({ 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 81aba3bf4c1..cb08e585392 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -22,6 +22,7 @@ import { configuredEnvironment, configuredEnvironmentProjection } from "../../ve import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { enableReattachPhase, isReattachPhaseActive, joinReattachPhase, onReattachPhaseEnd, resetReattachPhaseForTests, type ReattachPhaseSummary } from "../heartbeat/run-admission.js"; import { createSystemRecovery, failSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure } from "../system-recovery-state.js"; +import { registerRunStartHandover } from "../run-start-handover.js"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { once } from "node:events"; import { PgDialect } from "drizzle-orm/pg-core"; @@ -11465,6 +11466,41 @@ describe("native warm session supervision", () => { } }); + it.each(["before", "after"] as const)("closes a warm session promptly when a replacement server starts this server's runs (%s the turn ends)", async when => { + const identity = `warm-handoff-${when}`; + const warmExecution = { ...execution, binding: { ...execution.binding, runId: identity, executionWorkspaceId: `${identity}-workspace` }, + session: { ...execution.session, normalizedSessionId: identity, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 600_000 } }, + } as NativeExecutionInputV1; + const session = { close: vi.fn(async () => undefined) }; + state.execute.mockReset().mockImplementation(async (options) => { + await options.onSession?.(session); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, + turnId: identity, normalizedSessionId: identity, providerSessionId: identity, + driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + const listeners = new Set<() => void>(); + let leaving = when === "before"; + registerRunStartHandover({ isLeavingRunStarts: () => leaving, subscribe: (listener: () => void) => { + listeners.add(listener); + return () => { listeners.delete(listener); }; + } } as unknown as Parameters[0]); + try { + await executePaperclipNativeSession({ db: leaseDb(warmExecution), execution: warmExecution, runnerInstanceId: identity, + runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId: identity, remoteCwd: `/tmp/${identity}` } }); + if (when === "after") { + await new Promise(resolve => setTimeout(resolve, 1_500)); + expect(session.close).not.toHaveBeenCalled(); + leaving = true; + for (const listener of listeners) listener(); + } + await vi.waitFor(() => expect(session.close).toHaveBeenCalledTimes(1), { timeout: 3_000 }); + await vi.waitFor(() => expect(readNativeSessionIdleWork()).toBe("none")); + } finally { + registerRunStartHandover(null); + await closeWarmNativeSessionsForEnvironment({ environmentId: identity, reason: "test cleanup" }); + } + }); + it("a follow-up that arrives while the idle timeout is closing the warm session waits for that close instead of failing busy", async () => { const identity = "warm-idle-close-follow-up"; const warmExecution = { ...execution, binding: { ...execution.binding, runId: identity, executionWorkspaceId: `${identity}-workspace` }, @@ -18955,7 +18991,7 @@ describe("runnerd provider runtime wiring", () => { it.each((["codex", "claude"] as const).flatMap(provider => [ ...[[false, false, false, false], [true, false, false, false], [false, true, false, false], [false, false, true, false], ...(provider === "codex" ? [[false, false, false, true]] : [])] .map(([unknown, shutdown, journalFailure, deadline]) => [provider, unknown, shutdown, journalFailure, deadline, "idle timeout"] as const), - ...(["controller restart", "detach failure", "environment deletion"] as const) + ...(["controller restart", "detach failure", "environment deletion", "replacement hand-off"] as const) .map(retirement => [provider, false, false, false, false, retirement] as const), ]))( "releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, journalFailure=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, journalFailure, deadline, retirement) => { @@ -18965,6 +19001,8 @@ describe("runnerd provider runtime wiring", () => { process.env.PAPERCLIP_HOME = isolatedStateDirectory; const current = scopedNativeExecution(`released-${provider}-${unknown}`); current.session.lifecyclePolicy = { mode: "warm", idleTimeoutMs: retirement === "idle timeout" ? unknown ? 750 : 250 : 60_000 }; + if (retirement === "replacement hand-off") registerRunStartHandover({ isLeavingRunStarts: () => true, + subscribe: () => () => undefined } as unknown as Parameters[0]); if (provider === "claude") current.provider = { kind: "acpx", agent: "claude", model: "fixture", permissionMode: "deny-all" } as never; const source = { runnerInstanceId: "released-runner", environmentLeaseId: "released-lease", runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!, turnId: "settled-turn", itemId: "settled-item" }; @@ -19119,10 +19157,10 @@ describe("runnerd provider runtime wiring", () => { } detachControllerForRestart.mockResolvedValue(undefined); } - if (retirement !== "idle timeout") { + if (retirement !== "idle timeout" && retirement !== "replacement hand-off") { expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] }); expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] }); - } else await vi.waitFor(() => expect(detachControllerForRestart).toHaveBeenCalledOnce()); + } else await vi.waitFor(() => expect(detachControllerForRestart).toHaveBeenCalledOnce(), { timeout: 3_000 }); expect(readNativeSessionIdleWork()).toBe("none"); expect(close).not.toHaveBeenCalled(); expect(task.mock.calls.map(([operation]) => (operation as { kind: string }).kind)).toEqual(["describe"]); @@ -19157,6 +19195,7 @@ describe("runnerd provider runtime wiring", () => { expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(replacement.releasedRunner); } finally { detachControllerForRestart.mockResolvedValue(undefined); + registerRunStartHandover(null); allowRelease(); allowPhysicalStop(); await execute.catch(() => undefined); await closeIdleWarmNativeSessionsForRestart(); owners.mockRestore(); if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome; } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 3f33a94c005..914ceded34a 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -41,6 +41,7 @@ import { notifyExternalAgentSettlement } from "../../modules/external-agents/ind import { notifyNativeResultCommit } from "../native-result-commit-notifications.js"; import { releaseRetainedNativeSessionCleanup } from "../retained-native-session-cleanup-notifications.js"; import { registerIdleLocalWorkProbe, type IdleLocalWork } from "../idle-local-work.js"; +import { isLeavingRunStartsToReplacement, subscribeRunStartHandoverChanges } from "../run-start-handover.js"; import type { NativeCleanupOutcome } from "./retained-native-session-cleanup.js"; import { notifyNativeStatusReassessment } from "../native-status-reassessment-notifications.js"; import { notifyNativeFinalizationWork } from "../native-finalization-notifications.js"; @@ -930,6 +931,21 @@ export function readNativeSessionIdleWork(): IdleLocalWork { } registerIdleLocalWorkProbe(readNativeSessionIdleWork); +export const WARM_HANDOFF_CLOSE_DELAY_MS = 1_000; + +function warmIdleCloseDelay(idleTimeoutMs: number): number { + return isLeavingRunStartsToReplacement() ? Math.min(idleTimeoutMs, WARM_HANDOFF_CLOSE_DELAY_MS) : idleTimeoutMs; +} + +subscribeRunStartHandoverChanges(() => { + if (!isLeavingRunStartsToReplacement()) return; + for (const [sessionId, entry] of warmNativeSessions) { + if (entry.busy || entry.idleTimer === null) continue; + clearTimeout(entry.idleTimer); + armWarmNativeSessionIdleTimer(sessionId, entry, WARM_HANDOFF_CLOSE_DELAY_MS); + } +}); + /** * How long a new run's admission waits for the warm session to stop being busy. * A follow-up comment can wake the next run within milliseconds of the previous @@ -8775,7 +8791,7 @@ async function releaseWarmNativeSession( } finally { entry.busy = false; } return; } - armWarmNativeSessionIdleTimer(sessionId, entry, idleTimeoutMs); + armWarmNativeSessionIdleTimer(sessionId, entry, warmIdleCloseDelay(idleTimeoutMs)); } function armWarmNativeSessionIdleTimer( @@ -13774,7 +13790,7 @@ async function executePaperclipNativeSessionAttempt( if (current()) { delete entry.finishRelease; entry.busy = false; - armWarmNativeSessionIdleTimer(scope, entry, lifecyclePolicy.idleTimeoutMs); + armWarmNativeSessionIdleTimer(scope, entry, warmIdleCloseDelay(lifecyclePolicy.idleTimeoutMs)); } } }; diff --git a/server/src/services/native-runtime/predecessor-retirement.ts b/server/src/services/native-runtime/predecessor-retirement.ts index 8882a12f3e1..b3b397be9ec 100644 --- a/server/src/services/native-runtime/predecessor-retirement.ts +++ b/server/src/services/native-runtime/predecessor-retirement.ts @@ -21,7 +21,7 @@ export class NativePredecessorRetirementUnprovenError extends Error { cause: unknown, ) { super(`The previous run's session on this sandbox could not be retired (${ - cause instanceof Error ? cause.message : String(cause)}). The next attempt starts on a fresh sandbox.`, { cause }); + cause instanceof Error ? cause.message : String(cause)}).`, { cause }); this.name = "NativePredecessorRetirementUnprovenError"; } } diff --git a/server/src/services/native-runtime/remote-warm-session-recovery.ts b/server/src/services/native-runtime/remote-warm-session-recovery.ts index 65c4bd151e9..ebb21f0ac33 100644 --- a/server/src/services/native-runtime/remote-warm-session-recovery.ts +++ b/server/src/services/native-runtime/remote-warm-session-recovery.ts @@ -6,6 +6,36 @@ import { currentNativeControllerIdentity, evaluateNativeControllerTakeover, reco import { NativeControllerRecoveryWaitingError, readNativeControllerRecovery } from "./native-controller-recovery.js"; import { NativePredecessorRetirementUnprovenError } from "./predecessor-retirement.js"; import { readyPortableTaskSource } from "../plugin-task-ownership.js"; +import { PAPERCLIP_RUNNER_IDLE_TIMEOUT_MAX_MS } from "@paperclipai/adapter-utils"; +import { currentControllerBootId } from "../controller-process-identity.js"; +import { currentProcessProbe, proveOwnerGone } from "../owner-proof.js"; + +export const WARM_OWNER_RECHECK_MS = 5_000; +const WARM_OWNER_CLOSE_MARGIN_MS = 2 * 60_000; + +export async function liveWarmSessionOwnerRetryAt(input: { + owner: Pick; + finishedAt: Date | null; + idleTimeoutMs: number | null; + now?: Date; +}): Promise { + const { owner } = input; + const now = input.now ?? new Date(); + if (!owner.controllerBootId || owner.controllerBootId === currentControllerBootId()) return null; + const releasedAt = (input.finishedAt ?? owner.updatedAt).getTime(); + const closesBy = releasedAt + (input.idleTimeoutMs ?? PAPERCLIP_RUNNER_IDLE_TIMEOUT_MAX_MS) + WARM_OWNER_CLOSE_MARGIN_MS; + if (closesBy <= now.getTime()) return null; + const proof = await proveOwnerGone({ + kind: "local", scope: "native_warm_session", generation: null, host: null, + processSpace: owner.controllerHostHash, processSpaceUnrecorded: owner.controllerHostHash == null, + bootId: owner.controllerBootId, pid: owner.controllerPid, + processStartedAt: owner.controllerProcessStartedAt?.toISOString() ?? null, + touchedAt: owner.updatedAt.toISOString(), + }, { ...currentProcessProbe(), readOnly: true }); + if (proof.verdict !== "alive") return null; + return new Date(Math.min(now.getTime() + WARM_OWNER_RECHECK_MS, closesBy)); +} export type RemoteWarmSessionRecovery = { identity: Record; @@ -176,6 +206,9 @@ export async function inspectRemoteWarmSessionRecovery(input: { throw new NativeControllerRecoveryWaitingError(prior.owner.leaseExpiresAt); } if (prior.owner.phase !== "committed" || prior.owner.leaseOwner) return deny("owner_unsettled"); + const liveOwnerRetryAt = await liveWarmSessionOwnerRetryAt({ owner: prior.owner, finishedAt: prior.run.finishedAt, + idleTimeoutMs: previous.session?.lifecyclePolicy?.idleTimeoutMs ?? null }); + if (liveOwnerRetryAt) throw new NativeControllerRecoveryWaitingError(liveOwnerRetryAt); if (sourceProviderLeaseId === providerLeaseId) settledPredecessor = { runId: identity.runId, providerLeaseId }; const checkpoint = input.loadCheckpoint(previous); if (!checkpoint || checkpoint.identity.runId !== identity.runId || diff --git a/server/src/services/run-start-handover.ts b/server/src/services/run-start-handover.ts index 1fef8c812ac..4109a9e75d8 100644 --- a/server/src/services/run-start-handover.ts +++ b/server/src/services/run-start-handover.ts @@ -347,6 +347,7 @@ export function createRunStartHandover(input: { refresh, /** This server holds a hand-over an older server may be reading. */ isHandingOver: () => handingOver(), + isLeavingRunStarts: () => yieldingTo !== null, /** A hand-over involves this server (either side). Pure read, no refresh. */ isActive: () => handingOver() || yieldingTo !== null, subscribe(listener: () => void) { @@ -387,6 +388,10 @@ export function refreshRunStartYieldIfStale(): Promise | null { return current?.refreshIfStale() ?? null; } +export function isLeavingRunStartsToReplacement(): boolean { + return current?.isLeavingRunStarts() ?? false; +} + /** Either side of a hand-over is in progress here; a pure read for listeners. */ export function isRunStartHandoverActive(): boolean { return current?.isActive() ?? false; From a18479bbba222e8e95d0cdf1fbd4043328c0d28d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:19:43 -0600 Subject: [PATCH 06/19] perf(workspaces): start a full terminal workspace pass only at startup and on the hourly backstop (#21630) 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 terminal workspace sweep walks every candidate workspace in a full pass. On staging that is about 4,000 finished remote workspaces, and each one costs a persistence probe and a work product read. > - #21617 limited full passes to startup and an hourly backstop that only activity arms. But three other paths in the worker still started a full pass at once: > - a wake whose hints do not parse to workspace or task targets; > - more than 50 pending targets; > - any run that finds no targets. > - Across one staging deploy the probe count rose by about 2.8 full passes in 26 minutes. At 1,000 concurrent agents, more than 50 run-finish hints between passes would be normal, so the overflow path alone would bring back passes proportional to history. > - This pull request works through targets in batches of 50 and turns hintless wakes into the backstop. It gives the one caller that needs a broad look, a workspace provider plugin becoming ready, its own hint that inspects only plugin workspaces. > - The benefit is that a full pass happens only at startup and at most once per backstop hour, whatever the activity. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/bug_report.yml`. **What happened?** On staging, the hourly steady state holds (one full pass per hour, no probes between). But across a deploy the probe count rose by 11,351 in under 26 minutes, about 2.8 full passes over the roughly 4,000 finished remote workspaces. **Steps to reproduce** The new test file `server/src/__tests__/terminal-workspace-rotation-limits.test.ts` runs the real coordinator and worker against real PostgreSQL on a fake clock, with finished remote workspaces that cannot be archived (the staging state). These are the counts on master. The numbers are workspaces checked by full passes; a pass over N workspaces checks N: | Scenario | Full-pass checks on master | Expected | | --- | --- | --- | | A burst of 120 run-finish `issue:` hints, 300 workspaces | 600 (2 extra passes) | 0 | | One hintless wake and one unparseable hint, 120 workspaces, 30 minutes | 1,490 (about 12 passes) | 0, then 1 at the backstop | | A workspace provider plugin becomes ready (hintless notify from `plugin-registry`), 123 workspaces | 123 (1 pass) | 0; only the 3 plugin workspaces | | Restart: old instance drains while hints arrive, new instance starts and gets the plugin hint and 120 run-finish hints, 202 workspaces, 30 minutes | 2,424 (12 passes) | 202 (the startup pass) | **Cause of the passes across a deploy:** - The new instance runs its startup pass. - Each workspace provider plugin that turns `ready` sends a hintless notification (`plugin-registry.ts`), which started a full pass. - Run recovery at startup finishes many runs, and their `issue:` hints overflow 50, which started another full pass. - Any later wake without targets also started a full pass, including the coordinator's 5-minute retry timer. In the fixture this produced two back-to-back passes every 5 minutes. - The draining old instance starts nothing, because the worker's `canRun` is false during drain. The test confirms this. **Expected behavior** A full pass runs only at startup and when the activity-armed backstop is due, at most once per hour. Targets are worked through in targeted batches. ## What Changed - `server/src/services/terminal-workspace-work.ts`: - **Pending targets.** Workspace and task targets go into pending sets with no cap. Each run inspects at most 50 of them, and the rest stay queued for the next run, which is scheduled at once. A failed targeted run puts its targets back. - **Hintless or unparseable wakes** only arm the hourly backstop. - **No targets, nothing due:** the run does nothing. - **Due deadlines:** the due workspaces are queued as targets, including isolated re-home and nested clone deadlines keyed by a workspace. A due non-workspace deadline (the isolated source orphan sweep, task directory work) runs a targeted sweep for its prelude and arms the backstop. - **A failed plugin workspace listing** restores the plugin refresh flag, so the coordinator's retry lists again. - **Full passes** happen only at startup, when the backstop is due, and on continuation pages of a pass already under way. - **New hint `plugin-workspaces`** (`TERMINAL_WORKSPACE_PLUGIN_HINT`): it queues the ids of plugin-provider candidate workspaces from `listPluginTerminalWorkspaceIds`. - The worker now always tells the service `targeted: true`, so a hint during a pass no longer requests a rescan lap. - `server/src/services/execution-workspaces.ts`: - New `listPluginTerminalWorkspaceIds` reads the plugin-provider candidates. - A targeted sweep reads all matches of its at most 50 targets, with no page limit and no rescan request. - A failed targeted sweep no longer requests a rescan lap, because the worker re-queues its targets. - `server/src/services/plugin-registry.ts`: the two workspace-provider notifications send `plugin-workspaces` instead of no hint. - `server/src/__tests__/terminal-workspace-work.test.ts`: a new test, `retries the plugin workspace listing after it fails instead of waiting for the backstop`, fails without the retry fix. Three existing tests now describe the new behaviour: - unscoped commits go to the backstop; - more than 50 hinted workspaces are inspected in batches of 50 and 1; - a due deadline on a service without targeting still runs a full pass. - `server/src/__tests__/terminal-workspace-rotation-limits.test.ts`: four new tests, the scenarios above. The startup pass stays. The 1,000-workspace test in `terminal-workspace-deadlines.test.ts` shows that durable deadlines keep an idle instance quiet after startup. But only the startup pass reconciles workspaces whose hints were lost while no instance was running, so removing it would need a stored "last full pass" marker first. ## Verification - The four new tests fail on master with the counts in the table and pass after the change: - 0 full-pass checks for the burst, worked as targeted batches of at most 50 (120 checks in total); - 0 full-pass checks for 30 minutes after hintless and unparseable wakes, then 1 pass at the backstop; - only the 3 plugin workspaces are inspected after the plugin hint; - exactly 1 full pass across the restart: none on the draining instance, only the startup pass on the new one. - Prompt archiving and the missed-hint backstop keep their existing tests in `terminal-workspace-deadlines.test.ts`: - the release of a holding run inspects its workspace at once; - a run made terminal outside `writeRunStatus` is archived within 1 hour 1 minute; - 1,000 finished remote workspaces stay unread at idle. - `npx vitest run` in `server/` on `terminal-workspace-rotation-limits`, `terminal-workspace-work`, `terminal-workspace-deadlines`, `terminal-workspace-idle`, `terminal-workspace-page-batch`, `execution-workspaces-service`, `plugin-workspaces.integration`, `workspace-operations-reconciliation`, `execution-workspace-reopen`, `isolated-task-directory-retention`, `git-workspace-expiration` and `workspace-delivery-cleanup.integration`. - `pnpm check:module-boundaries` passes. ## Risks - **A notification that relied on an immediate broad pass now waits up to an hour.** The only caller I found that sent such a notification on purpose is the workspace provider readiness in `plugin-registry.ts`, and it now has its own targeted hint. Other hintless notifications arm the backstop. - **The isolated source orphan sweep** runs only at the start of a full pass. Its due deadline now arms the backstop instead of starting a pass at once. This only matters when the isolated source re-home feature is enabled. - **A targeted sweep has no page limit.** Its at most 50 targets bound the matched workspaces to those tasks, their ancestors and their execution workspaces. - **A burst of N hints costs N/50 targeted runs, back to back.** The cost scales with activity, not with history. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] 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 --- ...terminal-workspace-rotation-limits.test.ts | 172 ++++++++++++++++++ .../__tests__/terminal-workspace-work.test.ts | 38 ++-- server/src/services/execution-workspaces.ts | 30 ++- server/src/services/plugin-registry.ts | 5 +- .../src/services/terminal-workspace-work.ts | 73 ++++---- 5 files changed, 263 insertions(+), 55 deletions(-) create mode 100644 server/src/__tests__/terminal-workspace-rotation-limits.test.ts diff --git a/server/src/__tests__/terminal-workspace-rotation-limits.test.ts b/server/src/__tests__/terminal-workspace-rotation-limits.test.ts new file mode 100644 index 00000000000..892ce9624f5 --- /dev/null +++ b/server/src/__tests__/terminal-workspace-rotation-limits.test.ts @@ -0,0 +1,172 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { companies, createDb, executionWorkspaceSnapshots, executionWorkspaces, issues, projects, type Db } from "@paperclipai/db"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../services/delivery-work-notifications.js"; +import { executionWorkspaceService } from "../services/execution-workspaces.js"; +import { + notifyTerminalWorkspaceWork, registerTerminalWorkspaceWork, TERMINAL_WORKSPACE_BACKSTOP_MS, TERMINAL_WORKSPACE_PLUGIN_HINT, + TERMINAL_WORKSPACE_RETRY_MS, +} from "../services/terminal-workspace-work.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_TERMINAL_WORKSPACE_ROTATION_TEST_DATABASE_URL"); +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const HOUR = 3_600_000; +const realSetTimeout = globalThis.setTimeout; +const realSleep = (ms: number) => new Promise(resolve => realSetTimeout(resolve, ms)); + +(support.supported ? describe : describe.skip)("terminal workspace full rotation limits", () => { + let temporary: Awaited> | undefined; + let db: Db; + beforeAll(async () => { + if (!external) temporary = await startEmbeddedPostgresTestDatabase("terminal-workspace-rotation-"); + db = createDb(external ?? temporary!.connectionString); + db.$client.options.onnotice = () => {}; + }, 120_000); + afterEach(async () => { vi.useRealTimers(); await db.execute(sql`truncate companies cascade`); }); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + + async function seed(input: { remote: number; plugin?: number }) { + const companyId = randomUUID(), projectId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Rotation", issuePrefix: `R${companyId.slice(0, 6)}` }); + await db.insert(projects).values({ id: projectId, companyId, name: "Project", status: "in_progress" }); + const old = new Date(Date.now() - 5 * 24 * HOUR); + const remote = Array.from({ length: input.remote }, () => ({ workspaceId: randomUUID(), issueId: randomUUID(), snapshotId: randomUUID() })); + const plugin = Array.from({ length: input.plugin ?? 0 }, () => ({ workspaceId: randomUUID(), issueId: randomUUID() })); + for (let index = 0; index < remote.length; index += 250) { + const page = remote.slice(index, index + 250); + await db.insert(executionWorkspaces).values(page.map(row => ({ id: row.workspaceId, companyId, projectId, mode: "isolated_workspace", + strategyType: "git_worktree", name: row.workspaceId, status: "active", providerType: "remote", createdAt: old, updatedAt: old, + metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: 1, snapshotId: row.snapshotId, source: { kind: "empty" }, + writerRunId: null, dirty: false, location: { environmentId: randomUUID(), leaseId: randomUUID(), + providerLeaseId: `sandbox-${row.workspaceId}`, remoteCwd: "/workspace" } } } }))); + await db.insert(executionWorkspaceSnapshots).values(page.map(row => ({ id: row.snapshotId, companyId, executionWorkspaceId: row.workspaceId, + sourceOperationId: randomUUID(), generation: 1, epoch: 1, status: "committed" as const }))); + } + if (plugin.length) await db.insert(executionWorkspaces).values(plugin.map(row => ({ id: row.workspaceId, companyId, projectId, + mode: "isolated_workspace", strategyType: "git_worktree", name: row.workspaceId, status: "active", providerType: "plugin", + createdAt: old, updatedAt: old }))); + const all = [...remote, ...plugin]; + for (let index = 0; index < all.length; index += 250) { + const page = all.slice(index, index + 250); + await db.insert(issues).values(page.map(row => ({ id: row.issueId, companyId, projectId, title: "done", status: "done", + executionWorkspaceId: row.workspaceId, completedAt: old, updatedAt: old }))); + } + await db.execute(sql`update execution_workspaces set source_issue_id = issues.id, updated_at = ${old.toISOString()}::timestamptz + from issues where issues.execution_workspace_id = execution_workspaces.id and issues.company_id = ${companyId}::uuid`); + return { companyId, remote, plugin }; + } + + function start(canRun: () => boolean = () => true) { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + const service = executionWorkspaceService(db, { workspaceReaperCooldownDays: 1, terminalWorkspaceInspectionBackoffMs: TERMINAL_WORKSPACE_RETRY_MS }); + const sweeps: Array<{ targeted: boolean; checked: number; workspaceIds: number }> = []; + let inFlight = 0; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun, onError: () => {} }); + const worker = registerTerminalWorkspaceWork(coordinator, { ...service, + sweepTerminalWorkspaces: async (limit, signal, options) => { + inFlight += 1; + const result = await service.sweepTerminalWorkspaces(limit, signal, options).finally(() => { inFlight -= 1; }); + sweeps.push({ targeted: Boolean(options?.targets), checked: result.checked, + workspaceIds: (options?.targets?.workspaceIds.length ?? 0) + (options?.targets?.issueIds.length ?? 0) }); + return result; + } }, canRun); + const advance = async (ms: number) => { + for (let elapsed = 0; elapsed < ms; elapsed += 10_000) { + await vi.advanceTimersByTimeAsync(10_000); + do { await realSleep(10); await vi.advanceTimersByTimeAsync(1); } while (inFlight > 0); + } + }; + const settle = async (operation: Promise) => { + let done = false; + const result = operation.finally(() => { done = true; }); + while (!done) { await realSleep(5); await vi.advanceTimersByTimeAsync(1); } + return result; + }; + const fullChecked = (from = 0) => sweeps.slice(from).filter(sweep => !sweep.targeted).reduce((sum, sweep) => sum + sweep.checked, 0); + return { sweeps, advance, settle, fullChecked, stop: async () => { vi.useRealTimers(); await worker.stop(); await coordinator.stop(); } }; + } + + it("works through a burst of run-finish hints in targeted batches without a full pass", async () => { + const f = await seed({ remote: 300 }); + const work = start(); + try { + await work.advance(60_000); + expect(work.fullChecked()).toBe(300); + const mark = work.sweeps.length; + const burst = f.remote.slice(0, 120); + for (let index = 0; index < burst.length; index += 40) { + await work.settle(db.transaction(async tx => { + for (const row of burst.slice(index, index + 40)) await notifyTerminalWorkspaceWork(tx, `issue:${row.issueId}`); + })); + } + await work.advance(5 * 60_000); + const window = work.sweeps.slice(mark); + expect(work.fullChecked(mark)).toBe(0); + expect(window.every(sweep => sweep.targeted && sweep.workspaceIds <= 50)).toBe(true); + expect(window.reduce((sum, sweep) => sum + sweep.checked, 0)).toBe(120); + } finally { await work.stop(); } + }, 300_000); + + it("arms the hourly backstop for a hint without a target instead of starting a pass", async () => { + await seed({ remote: 120 }); + const work = start(); + try { + await work.advance(60_000); + const mark = work.sweeps.length; + await work.settle(db.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.terminalWorkspaces))); + await work.settle(db.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.terminalWorkspaces, "not-a-target"))); + await work.advance(30 * 60_000); + expect(work.fullChecked(mark)).toBe(0); + await work.advance(TERMINAL_WORKSPACE_BACKSTOP_MS); + expect(work.fullChecked(mark)).toBe(120); + } finally { await work.stop(); } + }, 300_000); + + it("inspects plugin workspaces when a workspace provider becomes ready without a full pass", async () => { + await seed({ remote: 120, plugin: 3 }); + const work = start(); + try { + await work.advance(60_000); + const mark = work.sweeps.length; + await work.settle(db.transaction(tx => notifyTerminalWorkspaceWork(tx, TERMINAL_WORKSPACE_PLUGIN_HINT))); + await work.advance(60_000); + expect(work.fullChecked(mark)).toBe(0); + expect(work.sweeps.slice(mark).reduce((sum, sweep) => sum + sweep.checked, 0)).toBe(3); + } finally { await work.stop(); } + }, 300_000); + + it("runs one full pass across a restart: none while the old instance drains and one at the new start", async () => { + const f = await seed({ remote: 200, plugin: 2 }); + let draining = false; + const old = start(() => !draining); + try { + await old.advance(60_000); + const mark = old.sweeps.length; + draining = true; + for (let index = 0; index < 120; index += 40) { + await old.settle(db.transaction(async tx => { + for (const row of f.remote.slice(index, index + 40)) await notifyTerminalWorkspaceWork(tx, `issue:${row.issueId}`); + })); + } + await old.settle(db.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.terminalWorkspaces))); + await old.advance(5 * 60_000); + expect(old.sweeps.slice(mark)).toEqual([]); + } finally { await old.stop(); } + const fresh = start(); + try { + await fresh.advance(10_000); + await fresh.settle(db.transaction(tx => notifyTerminalWorkspaceWork(tx, TERMINAL_WORKSPACE_PLUGIN_HINT))); + for (let index = 0; index < 120; index += 40) { + await fresh.settle(db.transaction(async tx => { + for (const row of f.remote.slice(index, index + 40)) await notifyTerminalWorkspaceWork(tx, `issue:${row.issueId}`); + })); + } + await fresh.advance(30 * 60_000); + expect(fresh.fullChecked()).toBe(202); + } finally { await fresh.stop(); } + }, 300_000); +}); diff --git a/server/src/__tests__/terminal-workspace-work.test.ts b/server/src/__tests__/terminal-workspace-work.test.ts index 4ac80c30906..5189bc03eb0 100644 --- a/server/src/__tests__/terminal-workspace-work.test.ts +++ b/server/src/__tests__/terminal-workspace-work.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; -import { notifyTerminalWorkspaceWork, registerTerminalWorkspaceWork, TERMINAL_WORKSPACE_RETRY_MS, type TerminalWorkspaceTargets } from "../services/terminal-workspace-work.js"; +import { notifyTerminalWorkspaceWork, registerTerminalWorkspaceWork, TERMINAL_WORKSPACE_BACKSTOP_MS, TERMINAL_WORKSPACE_PLUGIN_HINT, TERMINAL_WORKSPACE_RETRY_MS, type TerminalWorkspaceTargets } from "../services/terminal-workspace-work.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; const coordinators: ReturnType[] = []; @@ -88,18 +88,21 @@ describe("terminal workspace work", () => { } finally { release?.(); } }); - it("restores the cooldown deadline, lets commits preempt it, and parks after cleanup", async () => { + it("restores the cooldown deadline, leaves unscoped commits to the hourly backstop, and parks after cleanup", async () => { const s = setup(), due = Date.now() + 86_400_000; s.service.nextTerminalWorkspaceSweepAt.mockResolvedValue(due); const worker = s.start(); await worker.ready; expect(worker.hasUnrecoveredWork()).toBe(false); - await vi.advanceTimersByTimeAsync(3_600_000); + await vi.advanceTimersByTimeAsync(30 * 60_000); expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(1); await s.owner.transaction(tx => notifyTerminalWorkspaceWork(tx)); await s.owner.transaction(tx => notifyTerminalWorkspaceWork(tx)); await vi.advanceTimersByTimeAsync(1); + expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(TERMINAL_WORKSPACE_BACKSTOP_MS); expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(2); + expect(s.service.sweepTerminalWorkspaces.mock.calls[1]?.[2]?.targets).toBeUndefined(); expect(s.coordinator.nextWakeAt()).toBe(due); s.service.nextTerminalWorkspaceSweepAt.mockResolvedValue(null); await vi.advanceTimersByTimeAsync(due - Date.now()); @@ -107,7 +110,7 @@ describe("terminal workspace work", () => { expect(vi.getTimerCount()).toBe(0); }); - it("inspects only hinted workspaces after a commit, and keeps unscoped commits and deadlines on the full rotation", async () => { + it("inspects only hinted workspaces after a commit, and leaves an unscoped commit to the backstop", async () => { const s = setup(), due = Date.now() + 60_000; s.service.nextTerminalWorkspaceSweepAt.mockResolvedValue(due); await s.start().ready; @@ -121,21 +124,34 @@ describe("terminal workspace work", () => { expect(s.service.sweepTerminalWorkspaces.mock.calls[1]?.[2]).toMatchObject({ targets: { workspaceIds: [workspaceId], issueIds: [issueId] } }); await s.owner.transaction(tx => notifyTerminalWorkspaceWork(tx)); await vi.advanceTimersByTimeAsync(1); + expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(due - Date.now()); expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(3); expect(s.service.sweepTerminalWorkspaces.mock.calls[2]?.[2]?.targets).toBeUndefined(); - await vi.advanceTimersByTimeAsync(due - Date.now()); - expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(4); - expect(s.service.sweepTerminalWorkspaces.mock.calls[3]?.[2]?.targets).toBeUndefined(); }); - it("falls back to the full rotation when more workspaces are hinted than one inspection reads", async () => { + it("retries the plugin workspace listing after it fails instead of waiting for the backstop", async () => { + const s = setup(); + const pluginWorkspaceId = "6b1f9c2e-8a4d-4f3b-9c1e-2d7a5b8e0f13"; + const listPluginTerminalWorkspaceIds = vi.fn<() => Promise>() + .mockRejectedValueOnce(new Error("database unavailable")).mockResolvedValue([pluginWorkspaceId]); + await registerTerminalWorkspaceWork(s.coordinator, { ...s.service, listPluginTerminalWorkspaceIds }, s.enabled).ready; + await s.owner.transaction(tx => notifyTerminalWorkspaceWork(tx, TERMINAL_WORKSPACE_PLUGIN_HINT)); + await vi.advanceTimersByTimeAsync(1); + expect(listPluginTerminalWorkspaceIds).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(TERMINAL_WORKSPACE_RETRY_MS); + expect(listPluginTerminalWorkspaceIds).toHaveBeenCalledTimes(2); + expect(s.service.sweepTerminalWorkspaces.mock.calls.at(-1)?.[2]?.targets).toEqual({ workspaceIds: [pluginWorkspaceId], issueIds: [] }); + }); + + it("works through more hinted workspaces than one inspection reads in targeted batches", async () => { const s = setup(); await s.start().ready; const ids = Array.from({ length: 51 }, (_, index) => `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`); await s.owner.transaction(async tx => { for (const id of ids) await notifyTerminalWorkspaceWork(tx, `workspace:${id}`); }); - await vi.advanceTimersByTimeAsync(1); - expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(2); - expect(s.service.sweepTerminalWorkspaces.mock.calls[1]?.[2]?.targets).toBeUndefined(); + await vi.advanceTimersByTimeAsync(10); + expect(s.service.sweepTerminalWorkspaces).toHaveBeenCalledTimes(3); + expect(s.service.sweepTerminalWorkspaces.mock.calls.slice(1).map(call => call[2]?.targets?.workspaceIds.length)).toEqual([50, 1]); }); it("keeps the pause between rotation pages while hinted workspaces wait", async () => { diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 999a2424f70..9bb81f59c19 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -39,7 +39,7 @@ import { authorizationService, executionWorkspaceReadSqlCondition, projectReadSq import type { SQL } from "drizzle-orm"; import { nativeSessionProviderEvidence } from "./native-runtime/native-session-resume.js"; import { hasWorkspaceRestoreFailure } from "@paperclipai/shared"; -import { notifyTerminalWorkspaceWork, terminalWorkspaceTargetsFromHints, type TerminalWorkspaceTargets } from "./terminal-workspace-work.js"; +import { notifyTerminalWorkspaceWork, type TerminalWorkspaceTargets } from "./terminal-workspace-work.js"; import { clearTerminalWorkspaceRetry, readTerminalWorkspaceRetry, recordTerminalWorkspaceFailure, terminalWorkspaceFailure, TERMINAL_WORKSPACE_RETRY_KEY, type TerminalWorkspaceFailure, @@ -3688,16 +3688,15 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic : undefined; const scanFilter = targets ? and(baseCandidateFilter, terminalWorkspaceTargetFilter(targets)) : and(baseCandidateFilter, boundaryFilter, cursorFilter); - const candidates = await db + const candidateQuery = db .select({ workspace: executionWorkspaces, cursorAt: sql`${executionWorkspaces.updatedAt}::text` }) .from(executionWorkspaces) .where(scanFilter) - .orderBy(asc(executionWorkspaces.updatedAt), asc(executionWorkspaces.id)) - .limit(limit); + .orderBy(asc(executionWorkspaces.updatedAt), asc(executionWorkspaces.id)); + const candidates = await (targets ? candidateQuery : candidateQuery.limit(limit)); // Advance the cursor to this page's last row. A short page means the scan // reached the end of the bounded candidate set, so reset the cursor and // the bound to start a new rotation on the next sweep. - if (targets && candidates.length >= limit) terminalSweepRescanRequested = true; if (!targets && candidates.length < limit) { terminalSweepCursor = null; terminalSweepBoundary = null; @@ -4398,8 +4397,8 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic if (!options.targets) { terminalSweepCursor = previousCursor; terminalSweepBoundary = previousBoundary; + terminalSweepRescanRequested = true; } - terminalSweepRescanRequested = true; throw error; } finally { terminalSweepInProgress = false; @@ -4409,7 +4408,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic hasTerminalWorkspaceSweepContinuation: () => terminalSweepCursor !== null || terminalSweepRescanRequested, terminalWorkspaceWorkSettled: (hints?: ReadonlySet, options: { targeted?: boolean } = {}) => { - if ((terminalSweepInProgress || terminalSweepCursor !== null) && !(options.targeted && terminalWorkspaceTargetsFromHints(hints))) { + if ((terminalSweepInProgress || terminalSweepCursor !== null) && !options.targeted) { terminalSweepRescanRequested = true; } pullRequestStateCache.clear(); @@ -4432,11 +4431,24 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } }, + listPluginTerminalWorkspaceIds: async () => { + const rows = await db.select({ id: executionWorkspaces.id }).from(executionWorkspaces).where(and( + eq(executionWorkspaces.providerType, "plugin"), + sql`${executionWorkspaces.sourceIssueId} IS NOT NULL`, + or(and(inArray(executionWorkspaces.status, ["active", "idle", "in_review"]), isNull(executionWorkspaces.closedAt)), + and(inArray(executionWorkspaces.status, ["archived", "cleanup_failed"]), + sql`(${executionWorkspaces.metadata}->>'workspaceProviderRemoved') IS DISTINCT FROM 'true'`)), + )); + return rows.map(row => row.id); + }, + takeDueTerminalWorkspaceTargets: (): { workspaceIds: string[]; rotation: boolean } => { const at = now().getTime(); const due = (deadlines: Map) => [...deadlines].filter(([, deadline]) => deadline <= at).map(([id]) => id); - const rotation = due(isolatedRehomeDeadlines).length + due(nestedCloneMigrationDeadlines).length + due(taskDirectoryDeadlines).length > 0; - return { workspaceIds: due(terminalWorkspaceDeadlines), rotation }; + const workspaceKey = (key: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(key); + const migrations = [...due(isolatedRehomeDeadlines), ...due(nestedCloneMigrationDeadlines)]; + const rotation = due(taskDirectoryDeadlines).length > 0 || migrations.some(key => !workspaceKey(key)); + return { workspaceIds: [...new Set([...due(terminalWorkspaceDeadlines), ...migrations.filter(workspaceKey)])], rotation }; }, nextTerminalWorkspaceSweepAt: async () => { diff --git a/server/src/services/plugin-registry.ts b/server/src/services/plugin-registry.ts index ab9eabc658d..30f2259d958 100644 --- a/server/src/services/plugin-registry.ts +++ b/server/src/services/plugin-registry.ts @@ -32,6 +32,7 @@ import type { } from "@paperclipai/shared"; import { conflict, notFound } from "../errors.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { TERMINAL_WORKSPACE_PLUGIN_HINT } from "./terminal-workspace-work.js"; function sameBundledPluginRegistration(existing: typeof plugins.$inferSelect, packageName: string, manifest: PaperclipPluginManifestV1): boolean { return existing.pluginKey === manifest.id && existing.packageName === packageName && existing.version === manifest.version && isDeepStrictEqual(existing.manifestJson, manifest); @@ -92,7 +93,7 @@ export function pluginRegistryService(db: Db) { async function writeWorkspaceProviderChange(reconsiderWorkspaces: boolean, write: (database: Db) => Promise): Promise { return db.transaction(async tx => { await notifyExternalObjectRefresh(tx); - if (reconsiderWorkspaces) await notifyDeliveryWork(tx, DELIVERY_QUEUES.terminalWorkspaces); + if (reconsiderWorkspaces) await notifyDeliveryWork(tx, DELIVERY_QUEUES.terminalWorkspaces, TERMINAL_WORKSPACE_PLUGIN_HINT); return write(tx as unknown as Db); }); } @@ -517,7 +518,7 @@ export function pluginRegistryService(db: Db) { .then((rows) => rows[0] ?? null); if (plugin.manifestJson.workspaceProvider && existing?.enabled === false && input.enabled === true) { - await notifyDeliveryWork(db, DELIVERY_QUEUES.terminalWorkspaces); + await notifyDeliveryWork(db, DELIVERY_QUEUES.terminalWorkspaces, TERMINAL_WORKSPACE_PLUGIN_HINT); } if (existing) { diff --git a/server/src/services/terminal-workspace-work.ts b/server/src/services/terminal-workspace-work.ts index b9845bdbb5d..6f8220f0854 100644 --- a/server/src/services/terminal-workspace-work.ts +++ b/server/src/services/terminal-workspace-work.ts @@ -4,6 +4,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio export const TERMINAL_WORKSPACE_RETRY_MS = 5 * 60 * 1000; export const MAX_TERMINAL_WORKSPACE_TARGETS = 50; export const TERMINAL_WORKSPACE_BACKSTOP_MS = 60 * 60 * 1000; +export const TERMINAL_WORKSPACE_PLUGIN_HINT = "plugin-workspaces"; export function notifyTerminalWorkspaceWork(transaction: object, hint?: string) { return notifyDeliveryWork(transaction, DELIVERY_QUEUES.terminalWorkspaces, hint); @@ -38,6 +39,7 @@ export function registerTerminalWorkspaceWork( hasTerminalWorkspaceSweepContinuation(): boolean; terminalWorkspaceWorkSettled?(hints?: ReadonlySet, options?: { targeted?: boolean }): void; takeDueTerminalWorkspaceTargets?(): { workspaceIds: string[]; rotation: boolean }; + listPluginTerminalWorkspaceIds?(): Promise; }, canRun: () => boolean, ) { @@ -48,26 +50,31 @@ export function registerTerminalWorkspaceWork( // can take seconds per workspace, so the first sweep skips it and later // sweeps do it. let startupSweepStarted = false; - let rotationRequested = false; let dueAt: number | null = null; let lastRotationPageAt = 0; let backstopArmed = false; let lastFullRotationAt = Date.now(); let continuing = false; - const targetWorkspaceIds = new Set(), targetIssueIds = new Set(); + let pluginRefresh = false; + const pendingWorkspaceIds = new Set(), pendingIssueIds = new Set(); + const pendingCount = () => pendingWorkspaceIds.size + pendingIssueIds.size; + const takeTargets = (): TerminalWorkspaceTargets => { + const workspaceIds = [...pendingWorkspaceIds].slice(0, MAX_TERMINAL_WORKSPACE_TARGETS); + for (const id of workspaceIds) pendingWorkspaceIds.delete(id); + const issueIds = [...pendingIssueIds].slice(0, MAX_TERMINAL_WORKSPACE_TARGETS - workspaceIds.length); + for (const id of issueIds) pendingIssueIds.delete(id); + return { workspaceIds, issueIds }; + }; const worker = coordinator.register(DELIVERY_QUEUES.terminalWorkspaces, { retryMs: TERMINAL_WORKSPACE_RETRY_MS, onSettled: hints => { backstopArmed = true; - const targets = terminalWorkspaceTargetsFromHints(hints); - for (const id of targets?.workspaceIds ?? []) targetWorkspaceIds.add(id); - for (const id of targets?.issueIds ?? []) targetIssueIds.add(id); - const overflow = targetWorkspaceIds.size + targetIssueIds.size > MAX_TERMINAL_WORKSPACE_TARGETS; - service.terminalWorkspaceWorkSettled?.(hints, { targeted: Boolean(targets) && !overflow }); - if (!targets || overflow) { - rotationRequested = true; - targetWorkspaceIds.clear(); targetIssueIds.clear(); - } + if (hints?.has(TERMINAL_WORKSPACE_PLUGIN_HINT)) pluginRefresh = true; + const scoped = hints ? new Set([...hints].filter(hint => hint !== TERMINAL_WORKSPACE_PLUGIN_HINT)) : undefined; + const targets = terminalWorkspaceTargetsFromHints(scoped); + for (const id of targets?.workspaceIds ?? []) pendingWorkspaceIds.add(id); + for (const id of targets?.issueIds ?? []) pendingIssueIds.add(id); + service.terminalWorkspaceWorkSettled?.(hints, { targeted: true }); }, run: async signal => { recovered = false; @@ -76,44 +83,44 @@ export function registerTerminalWorkspaceWork( next = Date.now() + TERMINAL_WORKSPACE_RETRY_MS; const startup = !startupSweepStarted; startupSweepStarted = true; - let dueRotation = due; + const options = { compact: !startup, allowRemoteDeliveryChecks: !startup }; + let prelude = false; + const legacyDue = due && !startup && !service.takeDueTerminalWorkspaceTargets; if (due && !startup && service.takeDueTerminalWorkspaceTargets) { const dueTargets = service.takeDueTerminalWorkspaceTargets(); - dueRotation = dueTargets.rotation; - for (const id of dueTargets.workspaceIds) targetWorkspaceIds.add(id); - if (targetWorkspaceIds.size + targetIssueIds.size > MAX_TERMINAL_WORKSPACE_TARGETS) { - dueRotation = true; - targetWorkspaceIds.clear(); targetIssueIds.clear(); + for (const id of dueTargets.workspaceIds) pendingWorkspaceIds.add(id); + if (dueTargets.rotation) { prelude = true; backstopArmed = true; } + } + if (pluginRefresh && !startup && service.listPluginTerminalWorkspaceIds) { + pluginRefresh = false; + try { + for (const id of await service.listPluginTerminalWorkspaceIds()) pendingWorkspaceIds.add(id); + } catch (error) { + pluginRefresh = true; + throw error; } } - const options = { compact: !startup, allowRemoteDeliveryChecks: !startup }; - const targeted = targetWorkspaceIds.size + targetIssueIds.size > 0; const backstopDue = backstopArmed && Date.now() >= lastFullRotationAt + TERMINAL_WORKSPACE_BACKSTOP_MS; - if (due && service.takeDueTerminalWorkspaceTargets && !startup && !dueRotation && !targeted && !rotationRequested && !backstopDue - && !service.hasTerminalWorkspaceSweepContinuation()) return { checked: 0 }; - if (startup || dueRotation || rotationRequested || backstopDue || !targeted - || (service.hasTerminalWorkspaceSweepContinuation() && Date.now() >= lastRotationPageAt + 1000)) { - rotationRequested = false; + if (startup || backstopDue || legacyDue || (continuing && Date.now() >= lastRotationPageAt + 1000)) { lastRotationPageAt = Date.now(); - if (!continuing) { lastFullRotationAt = Date.now(); backstopArmed = false; } + if (!continuing) { lastFullRotationAt = Date.now(); backstopArmed = false; pluginRefresh = false; } return service.sweepTerminalWorkspaces(50, signal, options); } - const targets = { workspaceIds: [...targetWorkspaceIds], issueIds: [...targetIssueIds] }; - targetWorkspaceIds.clear(); targetIssueIds.clear(); + if (pendingCount() === 0 && !prelude) return { checked: 0 }; + const targets = takeTargets(); try { return await service.sweepTerminalWorkspaces(50, signal, { ...options, targets }); } catch (error) { - rotationRequested = true; + for (const id of targets.workspaceIds) pendingWorkspaceIds.add(id); + for (const id of targets.issueIds) pendingIssueIds.add(id); throw error; } }, hasPending: async () => { - continuing = false; + if (canRun()) continuing = service.hasTerminalWorkspaceSweepContinuation(); if (!canRun()) next = Date.now() + TERMINAL_WORKSPACE_RETRY_MS; - else if (service.hasTerminalWorkspaceSweepContinuation()) { - continuing = true; - next = Math.max(Date.now(), lastRotationPageAt + 1000); - } else if (rotationRequested || targetWorkspaceIds.size + targetIssueIds.size > 0) next = Date.now(); + else if (continuing) next = Math.max(Date.now(), lastRotationPageAt + 1000); + else if (pendingCount() > 0 || pluginRefresh) next = Date.now(); else { const deadline = await service.nextTerminalWorkspaceSweepAt(); next = deadline === null ? null : deadline > Date.now() From 163d9f323c2e7e723fa4d594e69d7c234e93bbe3 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:42:06 -0600 Subject: [PATCH 07/19] perf(github): reuse repository installation tokens until shortly before expiry (#21641) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The GitHub chat channel lets an agent review pull requests and answer comments through a GitHub App > - Each GitHub call gets a repository-scoped installation token from `githubBotRepositoryToken` > - That function minted a new token on every call. To mint, it resolved every App secret through the secret service, and each resolution wrote one audit row > - The review-check head poll calls it about every 5 minutes for each waiting check. On staging this made the secret audit insert one of the busiest statements in the database > - This pull request keeps a minted token in memory until shortly before it expires, and checks the connection's current state on every call > - The benefit is far fewer database writes and reads, fewer GitHub token mints, and an audit log that records real secret use ## Linked Issues or Issue Description **What happened?** On paperclip.staging (commit a18479bbba, measured at 19:05Z on 2026-11-14), `secret_access_events` got about 285 rows in 60 s. These were 44 resolutions each of the GitHub App connection's `credentials.appId`, `privateKey`, `installationId`, `webhookSecret`, `clientId` and `clientSecret` (+21 `slug`), with `consumer_type` `tool_connection` and actor `system`. That is about 4.7 audit inserts/s. The matching `secret_versions` and binding reads ran at about 3.6/s each in Neon. These were among the busiest statements on the database. **Expected behavior** A GitHub installation token is valid for one hour. Paperclip should reuse it and resolve the App secrets only when it mints a new token. **Steps to reproduce** 1. Connect a GitHub App chat endpoint and get pull request reviews into the `received` review-check state (staging had 84 `github_review_check` actions). 2. Let the review-check worker poll the pull request head (23 polls/min measured on staging). 3. Count `secret_access_events` rows per minute. Each poll adds one row per App secret and mints a new token at GitHub. **Paperclip version or commit** master at a18479bbba (the commit serving paperclip.staging at the time of measurement). **Where in the code** `githubBotRepositoryToken` in `server/src/services/chat-github-client.ts`. Callers: `chat-github-checks.ts` (review-check head poll), `chat-github-response-comments.ts` and `chat-github-reviews.ts`. ## What Changed - `githubBotRepositoryToken` keeps a minted token in a per-process, in-memory cache (at most 512 entries, least recently used first out). It never persists or logs tokens. - The cache uses the token until 5 minutes before GitHub's `expires_at` (capped at one hour). If GitHub does not give a usable expiry, the token is not kept. - The cache key holds the company, endpoint, repository id, the exact permission set, and an authority revision. The revision holds the connection id, the endpoint's runtime generation (pause, revoke and availability changes advance it), and for each mint credential its secret ref, version selector, secret status, current version, `updatedAt`, and binding. The installation id is a secret, so its secret ref and version identify it in the key. - Each call reads the current authority from the database in two narrow statements: one row from the endpoint and connection join (status, enabled, refs, runtime generation), and the three mint secrets with their bindings (status and version columns only, no secret values). The endpoint and connection status checks run on every call, as before. - If a status check fails, all cached tokens for that endpoint are dropped. A token cannot survive a revoke, pause, disable or credential change. - Secrets are resolved only when a token is minted, and only the three that minting uses (`appId`, `privateKey`, `installationId`). So the audit log gets three rows per mint instead of one row per App secret per call. - New `githubBotRepositoryClient` sends repository requests. If GitHub returns 401 for a cached token, it drops that token, mints a new one, and sends the request once more. A 401 for a newly minted token is not retried. The review-check, response-comment and review paths use this client. - The token policy stays in the GitHub chat client module (`rules/module-boundaries.mdc`). The callers only change how they get a request function. ## Verification - New test file `server/src/__tests__/github-repository-token-cache.test.ts` (embedded Postgres, real secret service, mocked GitHub fetch): - `mints once and resolves the App's secrets only when it mints`: red on master (second call minted `installation-token-2`), green now. It also checks that only the three mint secrets are audited. - `refreshes a token shortly before GitHub's expiry`: reused at +54 min, minted again at +56 min. - `never keeps a token GitHub issues for less than the safety margin` - `mints again after a credential rotation and uses the new credential`: rotates the installation id secret and checks that the new mint uses it. - `mints again after the connection's credential refs change` - `never serves a cached token across a pause, revoke or disabled connection`: includes a pause and resume with no call in between. - `mints a separate token for each repository` - `replaces a cached token GitHub rejects and retries the request once`: also checks that a 401 for a new token is not retried. - On master, 5 of the 8 tests fail. All 8 pass with this change. - Focused suites pass locally: every server test file that matches `github`, plus `chat-sdk-runtime.adapters`, `chat-provider-inventory`, `idle-completed-history` and `connection-management.integration` (41 of 42 files, 955 of 956 tests). The one failure, `github-connection-enrollment-work.test.ts`, also fails on unchanged master (`expected +0 to be 1`), so this change did not cause it. - `pnpm --filter @paperclipai/server typecheck` passes. - CI supplies the full typecheck, build and test coverage for the final revision. ## Risks - Low risk. A cached token is used only while the endpoint, connection and mint secrets are unchanged, and the status checks still read current database state on every call. - A GitHub-side revoke of a token (for example, an App uninstall) makes GitHub return 401. The client then mints again once. If the installation is gone, the mint fails as before. - The cache is per process. Each server process mints its own token, at most once per hour per repository and permission set. - Two concurrent first calls for the same key can both mint. This is the same as before and is rare. - No schema, migration or API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../github-repository-token-cache.test.ts | 217 ++++++++++++ server/src/services/chat-github-checks.ts | 12 +- server/src/services/chat-github-client.ts | 333 ++++++++++++++++-- .../services/chat-github-response-comments.ts | 6 +- server/src/services/chat-github-reviews.ts | 6 +- 5 files changed, 522 insertions(+), 52 deletions(-) create mode 100644 server/src/__tests__/github-repository-token-cache.test.ts diff --git a/server/src/__tests__/github-repository-token-cache.test.ts b/server/src/__tests__/github-repository-token-cache.test.ts new file mode 100644 index 00000000000..457838bb1d8 --- /dev/null +++ b/server/src/__tests__/github-repository-token-cache.test.ts @@ -0,0 +1,217 @@ +import { generateKeyPairSync, randomUUID } from "node:crypto"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { and, eq, sql } from "drizzle-orm"; +import { + agents, + chatEndpoints, + companies, + companySecretBindings, + createDb, + secretAccessEvents, + toolApplications, + toolConnections, +} from "@paperclipai/db"; +import type { ToolCredentialSecretRef } from "@paperclipai/shared"; +import { + githubBotRepositoryClient, + githubBotRepositoryToken, +} from "../services/chat-github-client.js"; +import { secretService } from "../services/secrets.js"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeDatabase = support.supported ? describe : describe.skip; + +const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString(); +const HOUR = 60 * 60_000; + +describeDatabase("GitHub repository token reuse", () => { + let database: Awaited>; + let db: ReturnType; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-github-token-cache-"); + db = createDb(database.connectionString); + }, 30_000); + afterEach(() => vi.restoreAllMocks()); + afterAll(async () => { + await db?.$client.end({ timeout: 0 }); + await database?.cleanup(); + }); + + async function fixture() { + const companyId = randomUUID(), applicationId = randomUUID(), connectionId = randomUUID(), endpointId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "GitHub token reuse", issuePrefix: randomUUID().slice(0, 8).toUpperCase() }); + const agentId = randomUUID(); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" }); + await db.insert(toolApplications).values({ id: applicationId, companyId, name: "GitHub", type: "chat" }); + const secrets = secretService(db); + const values = { appId: "1234", privateKey: privateKeyPem, installationId: "2468", webhookSecret: "webhook-secret" }; + const refs: ToolCredentialSecretRef[] = []; + const secretIds: Record = {}; + for (const [key, value] of Object.entries(values)) { + const secret = await secrets.create(companyId, { + name: `github.${key}.${randomUUID().slice(0, 8)}`, + key: `CHAT_GITHUB_${key}_${randomUUID()}`.replaceAll("-", "_").toUpperCase(), + provider: "local_encrypted", + value, + }); + secretIds[key] = secret.id; + refs.push({ secretId: secret.id, versionSelector: "latest", configPath: `credentials.${key}`, required: true }); + } + await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "GitHub", uid: connectionId, + transport: "chat_sdk", connectionPurpose: "channel", enabled: true, status: "active", credentialSecretRefs: refs }); + await db.insert(companySecretBindings).values(refs.map(ref => ({ companyId, secretId: ref.secretId, + targetType: "tool_connection", targetId: connectionId, configPath: ref.configPath }))); + await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "github", + publicId: endpointId, assignedAgentId: agentId, status: "active" }); + + const mints: Array<{ installationId: string; repositoryIds: number[]; permissions: unknown }> = []; + const requests: Array<{ path: string; token: string }> = []; + const rejected = new Set(); + let expiresIn = HOUR; + const fetchImpl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input)); + const token = String(new Headers(init?.headers).get("authorization") ?? "").replace(/^Bearer /, ""); + const mint = url.pathname.match(/^\/app\/installations\/(\d+)\/access_tokens$/); + if (mint) { + const body = JSON.parse(String(init?.body)) as { repository_ids: number[]; permissions: unknown }; + mints.push({ installationId: mint[1]!, repositoryIds: body.repository_ids, permissions: body.permissions }); + return Response.json({ token: `installation-token-${mints.length}`, + expires_at: new Date(Date.now() + expiresIn).toISOString() }, { status: 201 }); + } + requests.push({ path: url.pathname, token }); + if (rejected.has(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + return Response.json({ head: { sha: "abc" } }); + }) as unknown as typeof fetch & ReturnType; + const audits = async () => (await db.select({ configPath: secretAccessEvents.configPath }).from(secretAccessEvents) + .where(and(eq(secretAccessEvents.companyId, companyId), eq(secretAccessEvents.consumerId, connectionId)))) + .map(row => row.configPath).sort(); + const token = (repositoryId = "101") => githubBotRepositoryToken(db, companyId, endpointId, repositoryId, fetchImpl); + return { companyId, connectionId, endpointId, secretIds, mints, requests, rejected, fetchImpl, audits, token, + setExpiresIn: (ms: number) => { expiresIn = ms; } }; + } + + it("mints once and resolves the App's secrets only when it mints", async () => { + const f = await fixture(); + const first = await f.token(); + const second = await f.token(); + expect(second).toBe(first); + expect(f.mints).toEqual([{ installationId: "2468", repositoryIds: [101], + permissions: { contents: "read", metadata: "read", issues: "write", pull_requests: "write", checks: "write" } }]); + // One audited read per mint credential; the webhook secret is never read to mint. + expect(await f.audits()).toEqual(["credentials.appId", "credentials.installationId", "credentials.privateKey"]); + }); + + it("refreshes a token shortly before GitHub's expiry", async () => { + const f = await fixture(); + const start = Date.now(); + const now = vi.spyOn(Date, "now").mockReturnValue(start); + const first = await f.token(); + now.mockReturnValue(start + 54 * 60_000); + expect(await f.token()).toBe(first); + now.mockReturnValue(start + 56 * 60_000); + const refreshed = await f.token(); + expect(refreshed).not.toBe(first); + expect(f.mints).toHaveLength(2); + expect(await f.token()).toBe(refreshed); + }); + + it("never keeps a token GitHub issues for less than the safety margin", async () => { + const f = await fixture(); + f.setExpiresIn(2 * 60_000); + await f.token(); + await f.token(); + expect(f.mints).toHaveLength(2); + }); + + it("mints again after a credential rotation and uses the new credential", async () => { + const f = await fixture(); + const first = await f.token(); + await secretService(db).rotate(f.secretIds.installationId!, { value: "1357" }); + const rotated = await f.token(); + expect(rotated).not.toBe(first); + expect(f.mints.map(mint => mint.installationId)).toEqual(["2468", "1357"]); + expect(await f.token()).toBe(rotated); + expect(f.mints).toHaveLength(2); + }); + + it("mints again after the connection's credential refs change", async () => { + const f = await fixture(); + const first = await f.token(); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connectionId)); + // Same secrets under a pinned version: a different authority, so a different token. + await db.update(toolConnections).set({ credentialSecretRefs: connection!.credentialSecretRefs + .map(ref => ({ ...ref, versionSelector: 1 })) }).where(eq(toolConnections.id, f.connectionId)); + expect(await f.token()).not.toBe(first); + expect(f.mints).toHaveLength(2); + }); + + it("never serves a cached token across a pause, revoke or disabled connection", async () => { + const f = await fixture(); + const endpoint = eq(chatEndpoints.id, f.endpointId); + const first = await f.token(); + + await db.update(chatEndpoints).set({ status: "paused" }).where(endpoint); + await expect(f.token()).rejects.toThrow("GitHub bot connection is unavailable"); + await db.update(chatEndpoints).set({ status: "active" }).where(endpoint); + const afterPause = await f.token(); + expect(afterPause).not.toBe(first); + + // A pause and resume with no call in between still drops the token: pausing + // advances the endpoint's runtime generation. + await db.update(chatEndpoints).set({ status: "paused", + setup: sql`jsonb_set(${chatEndpoints.setup}, '{runtimeGeneration}', to_jsonb(coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::int, 0) + 1))` }) + .where(endpoint); + await db.update(chatEndpoints).set({ status: "active" }).where(endpoint); + const afterResume = await f.token(); + expect(afterResume).not.toBe(afterPause); + + await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connectionId)); + await expect(f.token()).rejects.toThrow("GitHub bot connection is not active"); + await db.update(toolConnections).set({ enabled: true }).where(eq(toolConnections.id, f.connectionId)); + const afterDisable = await f.token(); + expect(afterDisable).not.toBe(afterResume); + + await db.update(chatEndpoints).set({ status: "revoked" }).where(endpoint); + await expect(f.token()).rejects.toThrow("GitHub bot connection is unavailable"); + expect(f.mints).toHaveLength(4); + }); + + it("mints a separate token for each repository", async () => { + const f = await fixture(); + const first = await f.token("101"); + const second = await f.token("202"); + expect(second).not.toBe(first); + expect(await f.token("101")).toBe(first); + expect(await f.token("202")).toBe(second); + expect(f.mints.map(mint => mint.repositoryIds)).toEqual([[101], [202]]); + }); + + it("replaces a cached token GitHub rejects and retries the request once", async () => { + const f = await fixture(); + const cached = await f.token(); + f.rejected.add(cached); + const request = await githubBotRepositoryClient(db, f.companyId, f.endpointId, "101", f.fetchImpl); + await expect(request<{ head: { sha: string } }>("/repos/o/r/pulls/1")).resolves.toEqual({ head: { sha: "abc" } }); + expect(f.requests).toEqual([ + { path: "/repos/o/r/pulls/1", token: cached }, + { path: "/repos/o/r/pulls/1", token: "installation-token-2" }, + ]); + // The replacement is the cached token from now on. + expect(await f.token()).toBe("installation-token-2"); + expect(f.mints).toHaveLength(2); + + // A freshly minted token that GitHub rejects is not retried. + const other = await fixture(); + other.rejected.add("installation-token-1"); + const fresh = await githubBotRepositoryClient(db, other.companyId, other.endpointId, "101", other.fetchImpl); + await expect(fresh("/repos/o/r/pulls/1")).rejects.toMatchObject({ details: { providerStatus: 401 } }); + expect(other.requests).toHaveLength(1); + expect(other.mints).toHaveLength(1); + }); +}); diff --git a/server/src/services/chat-github-checks.ts b/server/src/services/chat-github-checks.ts index be799375918..5a273636fa6 100644 --- a/server/src/services/chat-github-checks.ts +++ b/server/src/services/chat-github-checks.ts @@ -17,7 +17,7 @@ import { import type { GitHubReviewEventContext } from "@paperclipai/shared"; import { runtimePublicOrigin } from "./cloud-runtime-identity.js"; import { - githubBotRepositoryToken, + githubBotRepositoryClient, githubBotRequest, } from "./chat-github-client.js"; @@ -132,7 +132,7 @@ export function githubReviewCheckService(db: Db, fetchImpl = fetch) { : state === "running" ? "Agent is reviewing this commit" : "Waiting for the assigned agent"; - const token = await githubBotRepositoryToken( + const github = await githubBotRepositoryClient( db, action.companyId, action.endpointId, @@ -143,13 +143,7 @@ export function githubReviewCheckService(db: Db, fetchImpl = fetch) { const request = ( path: string, options?: Parameters[3], - ) => - githubBotRequest( - lease.fetch, - token, - `${prefix}${path}`, - options, - ); + ) => github(`${prefix}${path}`, options); const current = await request<{ head: { sha: string } }>( `/pulls/${event.pullNumber}`, ); diff --git a/server/src/services/chat-github-client.ts b/server/src/services/chat-github-client.ts index 65d93445111..25a1ea893e9 100644 --- a/server/src/services/chat-github-client.ts +++ b/server/src/services/chat-github-client.ts @@ -1,8 +1,14 @@ import { createPrivateKey, createSign } from "node:crypto"; -import { and, eq } from "drizzle-orm"; -import { chatEndpoints, toolConnections, type Db } from "@paperclipai/db"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { + chatEndpoints, + companySecretBindings, + companySecrets, + toolConnections, + type Db, +} from "@paperclipai/db"; import { secretService } from "./secrets.js"; -import { conflict, forbidden, unprocessable } from "../errors.js"; +import { HttpError, conflict, forbidden, unprocessable } from "../errors.js"; import { githubPublicationRetry, githubProviderRetry, GITHUB_INLINE_RETRY_WINDOW_MS, GITHUB_INLINE_MAX_ATTEMPTS } from "./chat-channels/github/retry.js"; export function githubAppJwt( @@ -200,7 +206,238 @@ export async function githubBotCredentials( }; } -/** Least-privilege short-lived token restricted to the single task repository. */ +const GITHUB_REPOSITORY_TOKEN_PERMISSIONS = { + contents: "read", + metadata: "read", + issues: "write", + pull_requests: "write", + checks: "write", +} as const; +/** Only these secrets are needed to mint; the App's other credentials are not read here. */ +const GITHUB_MINT_CREDENTIALS = ["appId", "privateKey", "installationId"] as const; +const GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS = 5 * 60_000; +const GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS = 60 * 60_000; +const GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT = 512; + +type CachedRepositoryToken = { token: string; endpointId: string; refreshAt: number }; +type RepositoryToken = { token: string; key: string; cached: boolean }; + +// Per process and in memory only. Tokens are never persisted or logged. +const repositoryTokens = new Map(); + +function forgetEndpointRepositoryTokens(endpointId: string) { + for (const [key, entry] of repositoryTokens) + if (entry.endpointId === endpointId) repositoryTokens.delete(key); +} + +function rememberRepositoryToken(key: string, entry: CachedRepositoryToken) { + repositoryTokens.delete(key); + if (repositoryTokens.size >= GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) { + const now = Date.now(); + for (const [stale, cached] of repositoryTokens) + if (cached.refreshAt <= now) repositoryTokens.delete(stale); + } + // Map order is least recently used first. + for (const oldest of repositoryTokens.keys()) { + if (repositoryTokens.size < GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) break; + repositoryTokens.delete(oldest); + } + repositoryTokens.set(key, entry); +} + +/** + * Current minting authority, read from the database on every call. The + * revision covers everything that changes what a token may do: the endpoint's + * runtime generation (bumped on pause, revoke and availability changes), the + * connection, and each mint credential's secret ref, selected version, state + * and binding. Any change makes every token cached under the old revision + * unreachable. Secret values are not read here. + */ +async function githubBotRepositoryAuthority( + db: Db, + companyId: string, + endpointId: string, +) { + const [row] = await db + .select({ + endpointStatus: chatEndpoints.status, + runtimeGeneration: sql`${chatEndpoints.setup}->'runtimeGeneration'`, + connectionId: toolConnections.id, + enabled: toolConnections.enabled, + connectionStatus: toolConnections.status, + refs: toolConnections.credentialSecretRefs, + }) + .from(chatEndpoints) + .innerJoin( + toolConnections, + and( + eq(toolConnections.id, chatEndpoints.connectionId), + eq(toolConnections.companyId, companyId), + ), + ) + .where( + and( + eq(chatEndpoints.companyId, companyId), + eq(chatEndpoints.id, endpointId), + eq(chatEndpoints.provider, "github"), + ), + ); + if (!row || ["archived", "revoked", "paused"].includes(row.endpointStatus)) + throw conflict("GitHub bot connection is unavailable"); + const [appId, privateKey, installationId] = GITHUB_MINT_CREDENTIALS.map( + (key) => row.refs.find((ref) => ref.configPath === `credentials.${key}`), + ); + if (!appId || !privateKey) + throw conflict("Connect the GitHub App before continuing"); + if ( + !row.enabled || + row.connectionStatus !== "active" || + !["active", "verifying"].includes(row.endpointStatus) + ) + throw conflict("GitHub bot connection is not active"); + if (!installationId) throw conflict("Verify the GitHub App installation first"); + const refs = [appId, privateKey, installationId]; + const secrets = await db + .select({ + id: companySecrets.id, + status: companySecrets.status, + latestVersion: companySecrets.latestVersion, + updatedAt: companySecrets.updatedAt, + bindingId: companySecretBindings.id, + bindingPath: companySecretBindings.configPath, + bindingSelector: companySecretBindings.versionSelector, + bindingUpdatedAt: companySecretBindings.updatedAt, + }) + .from(companySecrets) + .leftJoin( + companySecretBindings, + and( + eq(companySecretBindings.secretId, companySecrets.id), + eq(companySecretBindings.companyId, companyId), + eq(companySecretBindings.targetType, "tool_connection"), + eq(companySecretBindings.targetId, row.connectionId), + ), + ) + .where( + and( + eq(companySecrets.companyId, companyId), + inArray(companySecrets.id, [...new Set(refs.map((ref) => ref.secretId))]), + ), + ); + const revision = JSON.stringify([ + row.connectionId, + row.runtimeGeneration ?? 0, + refs.map((ref) => { + const selector = ref.versionSelector ?? "latest"; + const secret = secrets.find((candidate) => candidate.id === ref.secretId); + const binding = secrets.find( + (candidate) => + candidate.id === ref.secretId && candidate.bindingPath === ref.configPath, + ); + return [ + ref.configPath, + ref.secretId, + selector, + secret + ? [ + secret.status, + selector === "latest" ? secret.latestVersion : selector, + secret.updatedAt.getTime(), + ] + : null, + binding + ? [binding.bindingId, binding.bindingSelector, binding.bindingUpdatedAt?.getTime()] + : null, + ]; + }), + ]); + return { connectionId: row.connectionId, refs, revision }; +} + +async function githubBotRepositoryTokenFor( + db: Db, + companyId: string, + endpointId: string, + repositoryId: string, + fetchImpl: typeof fetch, + options: { refresh?: boolean } = {}, +): Promise { + let authority: Awaited>; + try { + authority = await githubBotRepositoryAuthority(db, companyId, endpointId); + } catch (error) { + // A connection that cannot mint must not keep its earlier tokens either. + forgetEndpointRepositoryTokens(endpointId); + throw error; + } + if (!/^[1-9][0-9]*$/.test(repositoryId) || !Number.isSafeInteger(Number(repositoryId))) + throw conflict("Verify the GitHub App installation first"); + const key = JSON.stringify([ + companyId, + endpointId, + repositoryId, + GITHUB_REPOSITORY_TOKEN_PERMISSIONS, + authority.revision, + ]); + const cached = repositoryTokens.get(key); + if (cached && !options.refresh && cached.refreshAt > Date.now()) { + rememberRepositoryToken(key, cached); + return { token: cached.token, key, cached: true }; + } + if (cached) repositoryTokens.delete(key); + // Resolve (and audit) the App's secrets only when a token is actually minted. + const secrets = secretService(db); + const values: string[] = []; + for (const ref of authority.refs) + values.push( + await secrets.resolveSecretValue( + companyId, + ref.secretId, + ref.versionSelector ?? "latest", + { + consumerType: "tool_connection", + consumerId: authority.connectionId, + configPath: ref.configPath, + actorType: "system", + actorId: null, + }, + ), + ); + const [appId, privateKey, installationId] = values; + if (!appId || !privateKey) + throw conflict("Connect the GitHub App before continuing"); + if (!installationId) throw conflict("Verify the GitHub App installation first"); + const issued = await githubBotRequest<{ token?: string; expires_at?: string }>( + fetchImpl, + githubAppJwt(appId, privateKey), + `/app/installations/${encodeURIComponent(installationId)}/access_tokens`, + { + method: "POST", + body: { + repository_ids: [Number(repositoryId)], + permissions: GITHUB_REPOSITORY_TOKEN_PERMISSIONS, + }, + }, + ); + if (!issued.token) + throw unprocessable("GitHub did not issue an installation token"); + const now = Date.now(); + const refreshAt = + Math.min( + Date.parse(issued.expires_at ?? ""), + now + GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS, + ) - GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS; + // Without a usable expiry the token serves this call only. + if (Number.isFinite(refreshAt) && refreshAt > now) + rememberRepositoryToken(key, { token: issued.token, endpointId, refreshAt }); + return { token: issued.token, key, cached: false }; +} + +/** + * Least-privilege short-lived token restricted to the single task repository. + * Reused until shortly before GitHub's expiry while the connection's current + * authority is unchanged. + */ export async function githubBotRepositoryToken( db: Db, companyId: string, @@ -208,38 +445,60 @@ export async function githubBotRepositoryToken( repositoryId: string, fetchImpl = fetch, ) { - const result = await githubBotCredentials(db, companyId, endpointId); - if ( - !result.connection.enabled || - result.connection.status !== "active" || - !["active", "verifying"].includes(result.endpoint.status) - ) - throw conflict("GitHub bot connection is not active"); - if ( - !result.credentials.installationId || - !/^[1-9][0-9]*$/.test(repositoryId) || - !Number.isSafeInteger(Number(repositoryId)) - ) - throw conflict("Verify the GitHub App installation first"); - const issued = await githubBotRequest<{ token?: string }>( - fetchImpl, - result.appJwt, - `/app/installations/${encodeURIComponent(result.credentials.installationId)}/access_tokens`, - { - method: "POST", - body: { - repository_ids: [Number(repositoryId)], - permissions: { - contents: "read", - metadata: "read", - issues: "write", - pull_requests: "write", - checks: "write", - }, - }, - }, + return ( + await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl) + ).token; +} + +export type GitHubBotRepositoryRequest = ( + path: string, + options?: Parameters[3], +) => Promise; + +function githubUnauthorized(error: unknown) { + return ( + error instanceof HttpError && + !!error.details && + typeof error.details === "object" && + (error.details as { providerStatus?: unknown }).providerStatus === 401 ); - if (!issued.token) - throw unprocessable("GitHub did not issue an installation token"); - return issued.token; +} + +/** + * GitHub requests with a repository token. When GitHub rejects a cached token + * (401), that token is dropped and the request is sent once more with a newly + * minted one. GitHub did not act on the rejected request, so the retry is safe. + */ +export async function githubBotRepositoryClient( + db: Db, + companyId: string, + endpointId: string, + repositoryId: string, + fetchImpl = fetch, +): Promise { + let current = Promise.resolve( + await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl), + ); + return async (path: string, options?: Parameters[3]) => { + const used = current; + const issued = await used; + try { + return await githubBotRequest(fetchImpl, issued.token, path, options); + } catch (error) { + if (!issued.cached || !githubUnauthorized(error)) throw error; + if (current === used) { + if (repositoryTokens.get(issued.key)?.token === issued.token) + repositoryTokens.delete(issued.key); + current = githubBotRepositoryTokenFor( + db, + companyId, + endpointId, + repositoryId, + fetchImpl, + { refresh: true }, + ); + } + return githubBotRequest(fetchImpl, (await current).token, path, options); + } + }; } diff --git a/server/src/services/chat-github-response-comments.ts b/server/src/services/chat-github-response-comments.ts index 2bb0ecbc5c1..a69812614bf 100644 --- a/server/src/services/chat-github-response-comments.ts +++ b/server/src/services/chat-github-response-comments.ts @@ -13,7 +13,7 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator. import { conflict, forbidden, HttpError } from "../errors.js"; import { githubChatPrincipalAccess } from "./chat-github-access.js"; import { githubAutomaticAdmission } from "./chat-github-events.js"; -import { githubBotRepositoryToken, githubBotRequest } from "./chat-github-client.js"; +import { githubBotRepositoryClient } from "./chat-github-client.js"; import { withGitHubPublicationLease } from "./chat-github-publication-lease.js"; import { projectSafeChatPublicationText } from "./chat-publication-projection.js"; import type { GitHubAutomaticPolicyContext } from "./chat-github-review-policy.js"; @@ -276,9 +276,9 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) { ["pending", "retry"].includes(fast.publicationState ?? ""))))) return; } } - const token = await githubBotRepositoryToken(db, source.endpoint.companyId, source.endpoint.id, source.repositoryId, lease.fetch); + const github = await githubBotRepositoryClient(db, source.endpoint.companyId, source.endpoint.id, source.repositoryId, lease.fetch); const prefix = `/repos/${source.repository.split("/").map(encodeURIComponent).join("/")}`; - const api: Api = { request: (path, options) => githubBotRequest(lease.fetch, token, `${prefix}${path}`, options) }; + const api: Api = { request: (path, options) => github(`${prefix}${path}`, options) }; if (onlyExisting && !(await findResponseComment(source, api))) { const existing = await stageResponse(db, source); await lease.commit(async tx => { await tx.update(chatActions).set({ status: "cancelled", result: { final: true, code: "run_already_answered" }, updatedAt: new Date() }).where(eq(chatActions.id, existing.id)); }); diff --git a/server/src/services/chat-github-reviews.ts b/server/src/services/chat-github-reviews.ts index 77d4477fb20..ddd190aba1b 100644 --- a/server/src/services/chat-github-reviews.ts +++ b/server/src/services/chat-github-reviews.ts @@ -43,7 +43,7 @@ import { } from "@paperclipai/shared"; import { HttpError, conflict, forbidden, notFound } from "../errors.js"; import { - githubBotRepositoryToken, + githubBotRepositoryClient, githubBotRequest, } from "./chat-github-client.js"; import { githubChatPrincipalAccess } from "./chat-github-access.js"; @@ -316,7 +316,7 @@ export function githubChatReviewService(db: Db, fetchImpl = fetch) { source: Awaited>, requestFetch = fetchImpl, ) { - const token = await githubBotRepositoryToken( + const github = await githubBotRepositoryClient( db, source.endpoint.companyId, source.endpoint.id, @@ -330,7 +330,7 @@ export function githubChatReviewService(db: Db, fetchImpl = fetch) { path: string, options?: Parameters[3], ) => - githubBotRequest(requestFetch, token, `${prefix}${path}`, options), + github(`${prefix}${path}`, options), }; } async function reviewForHead( From 95a6ab31e606a8ffe7dd59e3ac65666688078806 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:54:00 -0600 Subject: [PATCH 08/19] feat(db): attribute work signals by caller behind a debug flag (#21640) 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 > - Background queues wake from work signals. A transaction calls `signalDatabaseWork(topic, hint)`, and the delivery coordinator wakes the queue for that topic with that hint. > - On a hosted instance with zero runs, the stranded-assignment recovery queue re-checks tasks about 7 times a second. About 2.6 hinting commits per second drive it. HTTP traffic, chat review polls and local fixtures with all heartbeat workers do not explain the writer. > - Statement statistics show what runs, but not who signalled it. Nothing records the caller of a work signal or why a queue woke. > - This pull request adds an opt-in attribution log for work signals and recovery-queue wakes, off by default. > - The benefit is that one short run on an affected instance names the writer of any idle signal loop, without code changes. ## Linked Issues or Issue Description No issue exists. This describes the gap with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** Observability of `signalDatabaseWork` (`packages/db/src/work-signals.ts`) and of the issue recovery queues (`server/src/services/recovery/work.ts`). **Current behavior** A queue that wakes several times a second at idle shows up only as repeated statements. Nothing tells you which caller published the hint, whether the wake came from another process, a reconnect, a direct settled publish or a stored deadline, or which load and check it caused. **Proposed behavior** An environment variable, `PAPERCLIP_DEBUG_WORK_SIGNALS`, read once when the module loads. It holds a comma-separated topic allowlist, and each topic can carry `:N` for its stack sampling rate. When it is unset or empty, the signal path only checks one boolean and does nothing else. **Reason and benefit** Several idle-load loops this week took hours of statement analysis before the writer was found. Attribution by caller turns that into one log query. ## What Changed - `packages/db/src/work-signal-debug.ts` (new): - `parseWorkSignalDebugSpec` reads `topic[:N],…`. An optional numeric suffix is parsed from the right, so topics that contain colons (for example `live:`) work with or without `:N`. N defaults to 20; malformed entries are ignored. - `createWorkSignalDebug` returns `enabled`, `allows(topic)`, `signal(topic, hint, entry)`, `event(topic, name, fields, stack, entry)` and `flush()`. A disabled instance constructs no `Error`, captures no stack, builds no line and starts no timer. - Stack capture (`captureWorkSignalStack(entry)`) raises `Error.stackTraceLimit` to 40 and restores it in a `finally`. It calls `Error.captureStackTrace(holder, entry)`, so V8 cuts every frame above the public entry (`signalDatabaseWork`, `publishDatabaseWorkSettled`, or the recovery `wake()`). - Frames are dropped by file (`node_modules`, `node:internal`, the signal wrapper files) and by function name (`signalDatabaseWork`, `notifyDeliveryWork`, …), so trimming works on the bundled `index.mjs`. Positions are kept raw (`index.mjs:L:C`) for offline source-map lookup. At most 10 frames are kept. - Each (topic, event) pair has its own budget of 10 lines per second, checked BEFORE any stack is captured. A `suppressed` line names the topic, the dropped event and the count. Frequent `check` lines therefore never drop `signal` or `direct_wake` lines. - Stack sampling (1 in N) counts per (topic, event), so `check` and `load` do not shift the phase of `signal` sampling. `direct_wake` always captures its caller's stack. - Lines go to an in-memory buffer that an unref'd 1-second timer flushes to stderr. The signal path does no I/O and no await. - `workSignalDebug` is the process instance, built from `process.env.PAPERCLIP_DEBUG_WORK_SIGNALS` once at module load. - `packages/db/src/work-signals.ts`: when enabled, it records: - `signal` in `signalDatabaseWork`; - `remote_notification` and `notification_reconnect`; - `settled_publish` (with a sampled stack) for `publishDatabaseWorkSettled`; - `uncertain_settled` when an uncertain transaction resolves. - `server/src/services/recovery/work.ts`: under the same flag: - each task-queue `load` logs its scope key; - each `check` logs the issue and company id, `dueAt`, and `wake: "deadline"` or `"load"`. The marker rides on the queued entry itself, and only while the flag is on, so nothing is tracked otherwise and nothing outlives the entry; - `wake()` logs ONE `direct_wake` line listing the queues it actually invalidates (assigned-work only when registered), under the first allowlisted one, with its caller's stack. - **No request route is logged.** The server has no request async context to read one synchronously, and this change does not add one. - `docs/deploy/environment-variables.md`: documents the flag, internal ids only, raw positions, and that enabling or changing it requires a restart. - Tests: - `packages/db/src/work-signal-debug.test.ts`, 12 tests: - strict no-op when unset or empty (no `Error`, no `captureStackTrace`, no stack capture, no sink); - the process instance is disabled without the env; - allowlist filtering, and spec parsing including colon topics; - per-(topic, event) sampling, and always-on direct-wake stacks; - source-tree trimming, and a synthetic single-file bundle stack with raw positions kept and wrappers dropped by name; - real capture below the entry with the limit raised and restored; - checks at about 8/s alongside signals at about 3/s for 5 seconds, with every signal line kept; - suppressed records never capture a stack; - buffered, timer-driven output. - `packages/db/src/work-signals.test.ts`: on real PostgreSQL, the signal and settled-publish paths never call the debug log while the flag is off. - `server/src/__tests__/issue-recovery-work-debug-attribution.test.ts`, on the recovery fixture with real PostgreSQL: - no recovery log calls while the flag is off; - with the flag on, a run graph hint logs its signal, the graph-scoped load and the check; - `wake()` logs exactly one `direct_wake` that lists the queues and carries the caller's stack. ## Verification - `packages/db`: `vitest run src/work-signal-debug.test.ts src/work-signals.test.ts`: 39 passed. `tsc --noEmit` passes. - `server`: `vitest run src/__tests__/issue-recovery-work-debug-attribution.test.ts src/__tests__/issue-recovery-deadlines.test.ts`: 17 passed. `tsc --noEmit` passes. - Staging values: `PAPERCLIP_DEBUG_WORK_SIGNALS=stranded-assignments:10`, then restart. - Sample output from the synthetic single-file bundle test: ``` {"msg":"paperclip work signal debug","at":1000000,"event":"signal","topic":"stranded-assignments","hint":"{\"companyId\":\"c\",\"graphRunId\":\"r\"}","stack":["at notifyIssueGraphRecovery (file:///app/server/dist-runtime/index.mjs:120456:11)","at async notifyRunDispatch (file:///app/server/dist-runtime/index.mjs:120501:3)","at async PostgresJsDatabase.connection.transaction [as transaction] (file:///app/server/dist-runtime/index.mjs:4021:22)","at async Object.settleRunProjection (file:///app/server/dist-runtime/index.mjs:300777:5)","at async file:///app/server/dist-runtime/index.mjs:310002:17"]} {"msg":"paperclip work signal debug","at":1000000,"event":"check","topic":"stranded-assignments","issueId":"i","companyId":"c","wake":"load","dueAt":1} {"msg":"paperclip work signal debug","at":1000000,"event":"direct_wake","topic":"stranded-assignments","queues":"stranded-assignments,orphan-blockers","stack":["at notifyIssueGraphRecovery (file:///app/server/dist-runtime/index.mjs:120456:11)","…"]} {"msg":"paperclip work signal debug","at":1001000,"event":"suppressed","topic":"stranded-assignments","suppressedEvent":"check","count":17} ``` ## Risks - Low risk. It is off by default. While off, each signal costs one property read and one boolean check. - While on, the log can show internal ids from hints (company, issue, run). It holds no secrets and no user identifiers, and the topic allowlist limits what is logged. - Stack capture costs CPU. Sampling (default 1 in 20) and the 10 lines per second cap bound it. - The file owner of `packages/db/src/work-signals.ts` reviews this before merge. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, local PostgreSQL test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Related: #21621. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- docs/deploy/environment-variables.md | 1 + packages/db/src/work-signal-debug.test.ts | 187 ++++++++++++++++++ packages/db/src/work-signal-debug.ts | 139 +++++++++++++ packages/db/src/work-signals.test.ts | 15 ++ packages/db/src/work-signals.ts | 14 +- ...ue-recovery-work-debug-attribution.test.ts | 65 ++++++ server/src/services/recovery/work.ts | 19 +- 7 files changed, 435 insertions(+), 5 deletions(-) create mode 100644 packages/db/src/work-signal-debug.test.ts create mode 100644 packages/db/src/work-signal-debug.ts create mode 100644 server/src/__tests__/issue-recovery-work-debug-attribution.test.ts diff --git a/docs/deploy/environment-variables.md b/docs/deploy/environment-variables.md index eb60708a670..0460ab91346 100644 --- a/docs/deploy/environment-variables.md +++ b/docs/deploy/environment-variables.md @@ -28,6 +28,7 @@ All environment variables that Paperclip uses for server configuration. | `PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH` | `/opt/paperclip-runner/provider-pack` in Docker; otherwise unset | Host-local path to the immutable provider pack built by `pnpm --filter @paperclipai/paperclip-runner build:provider-pack`. Stamped standard Docker images include the pack; downstream compositions and the `cloud` target inherit it. Unstamped local Docker builds skip pack generation. The pack includes its target-built Node 24.11+ runtime, locked production dependencies, OpenCode proxy/executable, and ACPX sidecar. Remote OpenCode and ACPX fail closed without it. A preinstalled pack is accepted only when its complete digested manifest matches this build-owned pack; otherwise Paperclip stages this pack into the sandbox. | | `PAPERCLIP_HIDDEN_SETTINGS` | (unset) | Comma-separated settings surfaces to hide from the UI and floor at the API, for operators hosting Paperclip for others (managed cloud, internal shared server). See [Hiding settings surfaces](#hiding-settings-surfaces). | | `PAPERCLIP_SETTING_DEFAULTS` | (unset) | JSON object replacing the schema default of selected instance settings, for hosting operators. See [Operator setting defaults](#operator-setting-defaults). | +| `PAPERCLIP_DEBUG_WORK_SIGNALS` | (unset) | Diagnostic only. Comma-separated allowlist of work-signal topics, each optionally followed by `:N` (for example `stranded-assignments:10,run-dispatch`). For each listed topic the server writes JSON lines to stderr: every work signal (topic and hint), with the caller stack on one signal in N (default 20); remote and reconnect notifications; direct settled publishes; and the recovery queues' loads, checks and direct wakes (direct wakes always carry the caller stack). Logged values are internal ids only (company, issue, run), never secrets or user identifiers. Stack frames keep their raw file and line positions, so bundled builds map them offline with that build's source map. Each topic and event pair is capped at 10 lines per second; a `suppressed` line names the dropped event and its count. The value is read once at startup, so enabling or changing it requires a restart. Unset or empty disables it completely. | Daytona connectivity for `paperclip_runner` uses authenticated provider WebSocket ingress and follows the instance experimental setting diff --git a/packages/db/src/work-signal-debug.test.ts b/packages/db/src/work-signal-debug.test.ts new file mode 100644 index 00000000000..aa3038f5e66 --- /dev/null +++ b/packages/db/src/work-signal-debug.test.ts @@ -0,0 +1,187 @@ +import { appendFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { captureWorkSignalStack, createWorkSignalDebug, parseWorkSignalDebugSpec, trimWorkSignalStack, workSignalDebug } from "./work-signal-debug.js"; + +const SOURCE_STACK = [ + "Error", + " at notifyDeliveryWork (/app/server/src/services/delivery-work-notifications.ts:169:3)", + " at notifyIssueGraphRecovery (/app/server/src/services/issue-recovery-notifications.ts:44:5)", + " at process.processTicksAndRejections (node:internal/process/task_queues:104:5)", + " at someLibrary (/app/node_modules/postgres/src/index.js:1:1)", + " at writer (/app/server/src/services/writer.ts:12:7)", +].join("\n"); + +const BUNDLE = "file:///app/server/dist-runtime/index.mjs"; +const BUNDLED_STACK = [ + "Error", + ` at notifyDeliveryWork (${BUNDLE}:91234:9)`, + ` at notifyIssueGraphRecovery (${BUNDLE}:120456:11)`, + ` at async notifyRunDispatch (${BUNDLE}:120501:3)`, + ` at async PostgresJsDatabase.connection.transaction [as transaction] (${BUNDLE}:4021:22)`, + ` at async Object.settleRunProjection (${BUNDLE}:300777:5)`, + ` at async ${BUNDLE}:310002:17`, + " at process.processTicksAndRejections (node:internal/process/task_queues:104:5)", +].join("\n"); + +function harness(spec: string | undefined, options: { maxLinesPerSecond?: number; stack?: string } = {}) { + let clock = 1_000_000; + const lines: string[] = []; + const sink = vi.fn((text: string) => { lines.push(...text.trim().split("\n")); }); + const captureStack = vi.fn((_entry: Function) => options.stack ?? SOURCE_STACK); + const debug = createWorkSignalDebug({ spec, sink, captureStack, now: () => clock, flushIntervalMs: 0, ...options }); + return { debug, sink, captureStack, lines, entries: () => lines.map(line => JSON.parse(line)), + advance: (ms: number) => { clock += ms; } }; +} + +afterEach(() => { vi.restoreAllMocks(); }); + +describe("work signal debug attribution", () => { + it("is a strict no-op when the flag is unset or empty", () => { + for (const spec of [undefined, "", " , "]) { + const { debug, sink, captureStack } = harness(spec); + const errors = vi.spyOn(globalThis, "Error"); + const capture = vi.spyOn(Error, "captureStackTrace"); + expect(debug.enabled).toBe(false); + for (let index = 0; index < 50; index++) { + debug.signal("stranded-assignments", "{\"companyId\":\"c\"}"); + debug.event("stranded-assignments", "direct_wake", { queues: "a" }, "always"); + } + debug.flush(); + expect(captureStack).not.toHaveBeenCalled(); + expect(errors).not.toHaveBeenCalled(); + expect(capture).not.toHaveBeenCalled(); + expect(sink).not.toHaveBeenCalled(); + } + }); + + it("leaves the process-wide instance disabled when the environment does not set it", () => { + expect(process.env.PAPERCLIP_DEBUG_WORK_SIGNALS ?? "").toBe(""); + expect(workSignalDebug.enabled).toBe(false); + }); + + it("logs only allowlisted topics", () => { + const { debug, entries } = harness("stranded-assignments,run-dispatch:5"); + debug.signal("stranded-assignments", "{\"companyId\":\"c\",\"graphRunId\":\"r\"}"); + debug.signal("issue-monitors", "{\"companyId\":\"c\"}"); + debug.event("run-dispatch", "load", { scope: "*" }); + debug.event("orphan-blockers", "load", { scope: "*" }); + debug.flush(); + expect(entries().map(entry => [entry.event, entry.topic])).toEqual([ + ["signal", "stranded-assignments"], ["load", "run-dispatch"]]); + expect(entries()[0].hint).toBe("{\"companyId\":\"c\",\"graphRunId\":\"r\"}"); + expect(debug.allows("run-dispatch")).toBe(true); + expect(debug.allows("orphan-blockers")).toBe(false); + }); + + it("parses per-topic sampling and ignores malformed entries", () => { + expect([...parseWorkSignalDebugSpec("stranded-assignments:3, run-dispatch,bad topic!, :4,x:0,live:7f3e-11,live:7f3e-12:4")]) + .toEqual([["stranded-assignments", 3], ["run-dispatch", 20], ["x", 20], ["live:7f3e-11", 20], ["live:7f3e-12", 4]]); + const { debug, entries } = harness("live:7f3e-11"); + debug.event("live:7f3e-11", "remote_notification"); + debug.flush(); + expect(entries()).toEqual([expect.objectContaining({ topic: "live:7f3e-11", event: "remote_notification" })]); + }); + + it("samples stacks one in N per topic and event, independent of other events", () => { + const { debug, entries, captureStack } = harness("stranded-assignments:3"); + for (let index = 0; index < 7; index++) { + debug.signal("stranded-assignments", undefined); + debug.event("stranded-assignments", "check", { issueId: `i${index}` }, "sampled"); + debug.event("stranded-assignments", "load", { scope: "*" }, "sampled"); + } + debug.flush(); + const signals = entries().filter(entry => entry.event === "signal"); + expect(signals.map(entry => Boolean(entry.stack))).toEqual([true, false, false, true, false, false, true]); + expect(captureStack).toHaveBeenCalledTimes(9); + }); + + it("captures an always-on stack for direct wakes on every call", () => { + const { debug, entries, captureStack } = harness("stranded-assignments:20"); + for (let index = 0; index < 3; index++) debug.event("stranded-assignments", "direct_wake", { queues: "a,b" }, "always"); + debug.flush(); + expect(captureStack).toHaveBeenCalledTimes(3); + expect(entries().every(entry => Array.isArray(entry.stack) && entry.queues === "a,b")).toBe(true); + }); + + it("trims a source-tree stack by file and by function name", () => { + expect(trimWorkSignalStack(SOURCE_STACK)).toEqual([ + "at notifyIssueGraphRecovery (/app/server/src/services/issue-recovery-notifications.ts:44:5)", + "at writer (/app/server/src/services/writer.ts:12:7)", + ]); + const deep = ["Error", ...Array.from({ length: 30 }, (_, index) => ` at f${index} (/app/server/src/f.ts:${index}:1)`)].join("\n"); + expect(trimWorkSignalStack(deep)).toHaveLength(10); + }); + + it("keeps raw bundle positions and drops wrappers by function name when every frame is in one bundled file", () => { + const { debug, entries } = harness("stranded-assignments:1", { stack: BUNDLED_STACK }); + debug.signal("stranded-assignments", "{\"companyId\":\"c\",\"graphRunId\":\"r\"}"); + debug.event("stranded-assignments", "check", { issueId: "i", companyId: "c", wake: "load", dueAt: 1 }); + debug.event("stranded-assignments", "direct_wake", { queues: "stranded-assignments,orphan-blockers" }, "always"); + debug.flush(); + expect(entries()[0].stack).toEqual([ + `at notifyIssueGraphRecovery (${BUNDLE}:120456:11)`, + `at async notifyRunDispatch (${BUNDLE}:120501:3)`, + `at async PostgresJsDatabase.connection.transaction [as transaction] (${BUNDLE}:4021:22)`, + `at async Object.settleRunProjection (${BUNDLE}:300777:5)`, + `at async ${BUNDLE}:310002:17`, + ]); + if (process.env.WORK_SIGNAL_DEBUG_SAMPLE_OUT) appendFileSync(process.env.WORK_SIGNAL_DEBUG_SAMPLE_OUT, + entries().map(entry => JSON.stringify(entry)).join("\n") + "\n"); + }); + + it("captures frames below the entry function with a raised and restored stack limit", () => { + const before = Error.stackTraceLimit; + function signalEntry() { return captureWorkSignalStack(signalEntry); } + function nest(depth: number): string | undefined { return depth === 0 ? signalEntry() : nest(depth - 1); } + const stack = nest(25); + expect(Error.stackTraceLimit).toBe(before); + const frames = (stack ?? "").split("\n").slice(1); + expect(frames.some(frame => frame.includes("signalEntry"))).toBe(false); + expect(frames.filter(frame => frame.includes("nest")).length).toBeGreaterThan(before); + }); + + it("budgets each topic and event separately so frequent checks never drop signals", () => { + const { debug, entries, advance } = harness("stranded-assignments:1000", { maxLinesPerSecond: 10 }); + let signals = 0; + for (let second = 0; second < 5; second++) { + for (let tick = 0; tick < 24; tick++) { + debug.event("stranded-assignments", "check", { issueId: `i${tick}` }); + if (tick % 8 === 0) { debug.signal("stranded-assignments", `h${second}-${tick}`); signals++; } + if (tick % 3 === 0) debug.event("stranded-assignments", "check", { issueId: `x${tick}` }); + advance(1000 / 24); + } + } + debug.flush(); + expect(entries().filter(entry => entry.event === "signal")).toHaveLength(signals); + expect(entries().filter(entry => entry.event === "check").length).toBeLessThanOrEqual(5 * 10 + 10); + const suppressed = entries().filter(entry => entry.event === "suppressed"); + expect(suppressed).toEqual([expect.objectContaining({ topic: "stranded-assignments", suppressedEvent: "check" })]); + expect(suppressed[0].count).toBeGreaterThan(0); + }); + + it("captures no stack for a record the cap suppresses", () => { + const { debug, captureStack, entries } = harness("stranded-assignments:1", { maxLinesPerSecond: 3 }); + for (let index = 0; index < 20; index++) { + debug.signal("stranded-assignments", undefined); + debug.event("stranded-assignments", "direct_wake", { queues: "a" }, "always"); + } + debug.flush(); + expect(captureStack).toHaveBeenCalledTimes(6); + expect(entries().filter(entry => entry.event === "suppressed").map(entry => [entry.suppressedEvent, entry.count])) + .toEqual([["signal", 17], ["direct_wake", 17]]); + }); + + it("writes nothing on the signal path and flushes later from a timer", () => { + vi.useFakeTimers(); + try { + const sink = vi.fn(); + const debug = createWorkSignalDebug({ spec: "stranded-assignments", sink, captureStack: () => SOURCE_STACK }); + debug.signal("stranded-assignments", undefined); + expect(sink).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1000); + expect(sink).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(5000); + expect(sink).toHaveBeenCalledTimes(1); + } finally { vi.useRealTimers(); } + }); +}); diff --git a/packages/db/src/work-signal-debug.ts b/packages/db/src/work-signal-debug.ts new file mode 100644 index 00000000000..fc604790dba --- /dev/null +++ b/packages/db/src/work-signal-debug.ts @@ -0,0 +1,139 @@ +export type WorkSignalDebugOptions = { + spec?: string; + defaultSampleEvery?: number; + maxLinesPerSecond?: number; + flushIntervalMs?: number; + sink?: (text: string) => void; + now?: () => number; + captureStack?: (entry: Function) => string | undefined; +}; + +export type WorkSignalDebugFields = Record; +export type WorkSignalDebugStack = "none" | "sampled" | "always"; + +const DROPPED_FILES = /node_modules|node:internal|work-signals\.(ts|js)|work-signal-debug\.(ts|js)|delivery-work-notifications\.(ts|js)/; +const DROPPED_FUNCTIONS = new Set(["signalDatabaseWork", "publishDatabaseWorkSettled", "notifyDeliveryWork", + "captureWorkSignalStack", "processTicksAndRejections"]); +const STACK_LIMIT = 40; + +export function parseWorkSignalDebugSpec(spec: string | undefined, defaultSampleEvery = 20): Map { + const topics = new Map(); + for (const part of (spec ?? "").split(",")) { + const match = /^(.+?)(?::(\d+))?$/.exec(part.trim()); + const topic = match?.[1]?.trim(); + if (!topic || !/^[a-z0-9:_-]{1,200}$/i.test(topic) || topic.startsWith(":") || topic.endsWith(":")) continue; + const every = Number(match?.[2]); + topics.set(topic, Number.isInteger(every) && every >= 1 ? every : defaultSampleEvery); + } + return topics; +} + +function frameFunction(line: string) { + const match = /^at (?:async )?(?:new )?([^\s(]+)(?: \[as [^\]]+\])? \(/.exec(line); + if (!match) return null; + const name = match[1]!; + return name.slice(name.lastIndexOf(".") + 1); +} + +export function trimWorkSignalStack(stack: string | undefined, frames = 10): string[] { + if (!stack) return []; + return stack.split("\n").slice(1).map(line => line.trim()) + .filter(line => line.startsWith("at ") && !DROPPED_FILES.test(line) && !DROPPED_FUNCTIONS.has(frameFunction(line) ?? "")) + .slice(0, frames); +} + +export function captureWorkSignalStack(entry: Function): string | undefined { + const holder: { stack?: string } = {}; + const limit = Error.stackTraceLimit; + try { + Error.stackTraceLimit = STACK_LIMIT; + Error.captureStackTrace(holder, entry); + } finally { + Error.stackTraceLimit = limit; + } + return holder.stack; +} + +export function createWorkSignalDebug(options: WorkSignalDebugOptions = {}) { + const topics = parseWorkSignalDebugSpec(options.spec, options.defaultSampleEvery); + const enabled = topics.size > 0; + const now = options.now ?? Date.now; + const maxLines = options.maxLinesPerSecond ?? 10; + const sink = options.sink ?? ((text: string) => { process.stderr.write(text); }); + const captureStack = options.captureStack ?? captureWorkSignalStack; + const counts = new Map(); + const budgets = new Map(); + const pending: string[] = []; + let timer: ReturnType | null = null; + + function admit(topic: string, event: string) { + const at = now(); + const key = `${topic}\u0000${event}`; + let budget = budgets.get(key); + if (!budget) budgets.set(key, budget = { windowStart: at, lines: 0, suppressed: 0, topic, event }); + if (at - budget.windowStart >= 1000) { budget.windowStart = at; budget.lines = 0; } + schedule(); + if (budget.lines >= maxLines) { budget.suppressed += 1; return false; } + budget.lines += 1; + return true; + } + + function emit(topic: string, event: string, entry: Record) { + pending.push(JSON.stringify({ msg: "paperclip work signal debug", at: now(), event, topic, ...entry })); + } + + function schedule() { + if (timer || options.flushIntervalMs === 0) return; + timer = setInterval(flush, options.flushIntervalMs ?? 1000); + timer.unref?.(); + } + + function sampled(topic: string, event: string) { + const key = `${topic}\u0000${event}`; + const count = counts.get(key) ?? 0; + counts.set(key, count + 1); + return count % (topics.get(topic) ?? 1) === 0; + } + + function stackFor(topic: string, event: string, mode: WorkSignalDebugStack, entry: Function) { + if (mode === "none" || (mode === "sampled" && !sampled(topic, event))) return undefined; + return trimWorkSignalStack(captureStack(entry)); + } + + function flush() { + for (const budget of budgets.values()) { + if (budget.suppressed === 0) continue; + pending.push(JSON.stringify({ msg: "paperclip work signal debug", at: now(), event: "suppressed", + topic: budget.topic, suppressedEvent: budget.event, count: budget.suppressed })); + budget.suppressed = 0; + } + if (pending.length === 0) { + if (timer) { clearInterval(timer); timer = null; } + return; + } + sink(pending.splice(0).join("\n") + "\n"); + } + + function signal(topic: string, hint: string | undefined, entry: Function = signal) { + if (!enabled || !topics.has(topic) || !admit(topic, "signal")) return; + const stack = stackFor(topic, "signal", "sampled", entry); + emit(topic, "signal", { ...(hint === undefined ? {} : { hint }), ...(stack ? { stack } : {}) }); + } + + function event(topic: string, name: string, fields: WorkSignalDebugFields = {}, + stack: WorkSignalDebugStack = "none", entry: Function = event) { + if (!enabled || !topics.has(topic) || !admit(topic, name)) return; + const frames = stackFor(topic, name, stack, entry); + emit(topic, name, { ...fields, ...(frames ? { stack: frames } : {}) }); + } + + return { + get enabled() { return enabled; }, + allows(topic: string) { return enabled && topics.has(topic); }, + signal, + event, + flush, + }; +} + +export const workSignalDebug = createWorkSignalDebug({ spec: process.env.PAPERCLIP_DEBUG_WORK_SIGNALS }); diff --git a/packages/db/src/work-signals.test.ts b/packages/db/src/work-signals.test.ts index b4d652eec08..fdfb9202233 100644 --- a/packages/db/src/work-signals.test.ts +++ b/packages/db/src/work-signals.test.ts @@ -3,6 +3,7 @@ import { drizzle } from "drizzle-orm/postgres-js"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { createDb, withDedicatedDbConnection } from "./client.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; +import { workSignalDebug } from "./work-signal-debug.js"; import { DATABASE_WORK_CHANNEL, databaseWorkScopeKey, databaseWorkPending, enableDatabaseWorkNotifications, installDatabaseWorkSignals, notifyDatabaseWorkOnCommit, primeDatabaseWorkTransactionId, publishDatabaseWorkSettled, reconcileDatabaseWork, signalDatabaseWork, subscribeDatabaseWork } from "./work-signals.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -16,6 +17,20 @@ const support = await getEmbeddedPostgresTestSupport(); }, 90_000); afterAll(async () => { await temporary?.cleanup(); }); + it("does not touch the debug attribution log on the signal path when the flag is off", async () => { + const signal = vi.spyOn(workSignalDebug, "signal"); + const event = vi.spyOn(workSignalDebug, "event"); + try { + await db.transaction(async tx => { + await signalDatabaseWork(tx, "debug-off", "{\"companyId\":\"c\"}"); + await tx.execute(sql`insert into work_signal_test values ('debug-off')`); + }); + publishDatabaseWorkSettled(db, "debug-off"); + expect(signal).not.toHaveBeenCalled(); + expect(event).not.toHaveBeenCalled(); + } finally { signal.mockRestore(); event.mockRestore(); } + }); + it("defers nested savepoint notifications until the outer commit and preserves return values", async () => { const events: string[] = []; const unsubscribe = subscribeDatabaseWork(db, "nested", event => events.push(event)); diff --git a/packages/db/src/work-signals.ts b/packages/db/src/work-signals.ts index 6b4bdbd126a..42be2669622 100644 --- a/packages/db/src/work-signals.ts +++ b/packages/db/src/work-signals.ts @@ -1,5 +1,6 @@ import { sql } from "drizzle-orm"; import { randomUUID } from "node:crypto"; +import { workSignalDebug } from "./work-signal-debug.js"; // Hints about existing durable queues; process-local by default, with optional // commit-bound PostgreSQL notifications during controller replacement. No SQL @@ -72,6 +73,7 @@ export async function signalDatabaseWork(connection: object, topic: string, hint if (!context) return; // Lightweight service test doubles have no DB lifecycle. const state = context.transaction; if (!state) throw new Error("Database work must be registered inside a transaction"); + if (workSignalDebug.enabled) workSignalDebug.signal(topic, hint, signalDatabaseWork); state.topics.add(topic); if (hint !== undefined) { let hints = state.hints.get(topic); @@ -138,6 +140,7 @@ export function databaseWorkCommitNotification(owner: object, topic: string): st export function publishDatabaseWorkSettled(owner: object, topic: string, hint?: string): void { const context = contexts.get(owner); if (!context) return; + if (workSignalDebug.enabled) workSignalDebug.event(topic, "settled_publish", { hint }, "sampled", publishDatabaseWorkSettled); if (!context.transaction) { publish(context.scope, topic, "settled", hint === undefined ? undefined : new Set([hint])); return; @@ -159,12 +162,16 @@ export function receiveDatabaseWorkNotification(owner: object, payload: string): try { value = JSON.parse(payload); } catch { return; } if (!value || value.version !== 1 || typeof value.origin !== "string" || value.origin === scope.notificationOrigin || typeof value.topic !== "string" || !validTopic(value.topic)) return; + if (workSignalDebug.enabled) workSignalDebug.event(value.topic, "remote_notification"); publish(scope, value.topic); } /** Reconnect can lose hints. Reconstruct existing durable queues once; no poll. */ export function reconcileDatabaseWorkNotifications(owner: object): void { const scope = contexts.get(owner)?.scope; - if (scope) for (const topic of scope.listeners.keys()) publish(scope, topic); + if (scope) for (const topic of scope.listeners.keys()) { + if (workSignalDebug.enabled) workSignalDebug.event(topic, "notification_reconnect"); + publish(scope, topic); + } } export function databaseWorkPending(owner: object, topic: string): boolean { @@ -188,7 +195,10 @@ export async function reconcileDatabaseWork(owner: object, topic: string): Promi throw new Error("Unexpected database transaction status"); } scope.transactions.delete(state); - for (const affected of state.topics) publish(scope, affected, "settled", state.hints.get(affected)); + for (const affected of state.topics) { + if (workSignalDebug.enabled) workSignalDebug.event(affected, "uncertain_settled", { status: rows[0]?.status ?? null }); + publish(scope, affected, "settled", state.hints.get(affected)); + } } } diff --git a/server/src/__tests__/issue-recovery-work-debug-attribution.test.ts b/server/src/__tests__/issue-recovery-work-debug-attribution.test.ts new file mode 100644 index 00000000000..8b0282ac0e5 --- /dev/null +++ b/server/src/__tests__/issue-recovery-work-debug-attribution.test.ts @@ -0,0 +1,65 @@ +import { expect, it, vi } from "vitest"; +import { agents, heartbeatRuns, issues } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { workSignalDebug } from "@paperclipai/db/work-signal-debug"; +import { signalDatabaseWork } from "@paperclipai/db/work-signals"; +import { notifyIssueGraphRecovery } from "../services/issue-recovery-notifications.js"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; + +describeIssueRecovery("issue recovery work signal attribution", () => { + const state = issueRecoveryFixture(); + + it("logs nothing from recovery loads and checks while the flag is off", async () => { + const f = await state.fixture(); + await state.db.insert(issues).values({ companyId: f.companyId, title: "Waiting", status: "in_review", assigneeAgentId: f.agentId }); + const event = vi.spyOn(workSignalDebug, "event"); + const signal = vi.spyOn(workSignalDebug, "signal"); + await state.start(); await state.settled(); + expect(event).not.toHaveBeenCalled(); + expect(signal).not.toHaveBeenCalled(); + }); + + it("ties each stranded check to the load and hint that caused it when the flag is on", async () => { + const f = await state.fixture(); + await state.db.update(agents).set({ status: "error" }).where(eq(agents.id, f.agentId)); + const [task] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Waiting", status: "in_review", + assigneeAgentId: f.agentId }).returning(); + const [run] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "succeeded", + runtimeMode: "native", nativeIssueId: task.id, finishedAt: new Date(), contextSnapshot: { issueId: task.id } }).returning(); + await state.start(); await state.settled(); + const enabled = vi.spyOn(workSignalDebug, "enabled", "get").mockReturnValue(true); + const event = vi.spyOn(workSignalDebug, "event").mockImplementation(() => {}); + const signal = vi.spyOn(workSignalDebug, "signal").mockImplementation(() => {}); + try { + await state.db.transaction(tx => notifyIssueGraphRecovery(tx, { companyId: f.companyId, runId: run.id })); + await state.settled({ backstopPending: true }); + expect(signal).toHaveBeenCalledWith("stranded-assignments", + JSON.stringify({ companyId: f.companyId, graphRunId: run.id }), signalDatabaseWork); + const stranded = event.mock.calls.filter(([topic]) => topic === "stranded-assignments"); + expect(stranded).toContainEqual(["stranded-assignments", "load", + { scope: JSON.stringify([f.companyId, null, run.id, null, null]) }]); + expect(stranded).toContainEqual(["stranded-assignments", "check", + expect.objectContaining({ issueId: task.id, companyId: f.companyId, wake: "load" })]); + } finally { enabled.mockRestore(); event.mockRestore(); signal.mockRestore(); } + }); + + it("logs one direct wake listing the woken queues with its caller's stack", async () => { + await state.fixture(); + await state.start(); await state.settled(); + const enabled = vi.spyOn(workSignalDebug, "enabled", "get").mockReturnValue(true); + const allows = vi.spyOn(workSignalDebug, "allows").mockImplementation(topic => topic === "stranded-assignments"); + const event = vi.spyOn(workSignalDebug, "event").mockImplementation(() => {}); + try { + state.worker.wake(); + const wakes = event.mock.calls.filter(([, name]) => name === "direct_wake"); + expect(wakes).toHaveLength(1); + const [topic, , fields, stack, entry] = wakes[0]!; + expect(topic).toBe("stranded-assignments"); + expect(String(fields?.queues).split(",")).toEqual(expect.arrayContaining(["stranded-assignments", + "orphan-blockers", "assigned-work-invariant"])); + expect(stack).toBe("always"); + expect(entry).toBe(state.worker.wake); + await state.settled(); + } finally { enabled.mockRestore(); allows.mockRestore(); event.mockRestore(); } + }); +}); diff --git a/server/src/services/recovery/work.ts b/server/src/services/recovery/work.ts index 06a9baf803a..7c9e02c2271 100644 --- a/server/src/services/recovery/work.ts +++ b/server/src/services/recovery/work.ts @@ -6,9 +6,10 @@ import { DELIVERY_QUEUES, type DeliveryQueue } from "../delivery-work-notificati import { decodeIssueRecoveryHint, ISSUE_RECOVERY_BACKSTOP_MS, issueRecoveryScopeMatches, resolveIssueGraph, type IssueRecoveryScope } from "../issue-recovery-notifications.js"; import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; +import { workSignalDebug } from "@paperclipai/db/work-signal-debug"; import { recoveryActionSweepCondition } from "./blocker-stall-wakeups.js"; -type Entry = { id: string; companyId: string; dueAt: number }; +type Entry = { id: string; companyId: string; dueAt: number; fromDeadline?: true }; type Scope = { companyId: string; issueId: string; onDeferredDeadline: (at: number) => void }; const PAGE_SIZE = 100; @@ -88,6 +89,7 @@ export function registerIssueRecoveryWork( matches: issueRecoveryScopeMatches, load: async scope => { const key = scopeKey(scope); + if (workSignalDebug.enabled) workSignalDebug.event(queue, "load", { scope: key }); if (!enabled) { cursors.delete(key); return []; } if (await toCompany(scope, worker)) return { rows: null, complete: true }; const cursor = cursors.get(key); @@ -109,10 +111,12 @@ export function registerIssueRecoveryWork( }, check: async entry => { if (!enabled) return null; + if (workSignalDebug.enabled) workSignalDebug.event(queue, "check", { issueId: entry.id, companyId: entry.companyId, + wake: entry.fromDeadline ? "deadline" : "load", dueAt: entry.dueAt }); let next: number | null = null; await check({ companyId: entry.companyId, issueId: entry.id, onDeferredDeadline: at => { next = next === null ? at : Math.min(next, at); } }); - return next === null ? null : { ...entry, dueAt: next }; + return next === null ? null : { ...entry, dueAt: next, ...(workSignalDebug.enabled ? { fromDeadline: true as const } : {}) }; }, }, canRun); return worker; @@ -219,7 +223,16 @@ export function registerIssueRecoveryWork( }, canRun); const workers = [assignments, orphanBlockers, recoveryActions, dependencies, locks, watchdogs, ...(assignedWork ? [assignedWork] : [])]; + const queues: string[] = [DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, + DELIVERY_QUEUES.resolvedDependencies, DELIVERY_QUEUES.staleIssueLocks, DELIVERY_QUEUES.taskWatchdogs, + ...(assignedWork ? [DELIVERY_QUEUES.assignedWorkInvariant] : [])]; return { watchdogs, assignments, assignedWork, ready: Promise.all(workers.map(worker => worker.ready)), - wake() { for (const worker of workers) worker.invalidate(); }, + wake: function wake() { + if (workSignalDebug.enabled) { + const topic = queues.find(queue => workSignalDebug.allows(queue)); + if (topic) workSignalDebug.event(topic, "direct_wake", { queues: queues.join(",") }, "always", wake); + } + for (const worker of workers) worker.invalidate(); + }, async stop() { await Promise.all(workers.map(worker => worker.stop())); } }; } From 8a97037bd2eb128f62c3b7ae123a76b6e88b4bd5 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:24:04 -0600 Subject: [PATCH 09/19] fix(runs): say who started a retry run in the issue run read (#21486) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The chat agent answers questions about failed runs by reading the task's run list (`GET /api/issues/{id}/runs`) > - For a retry run, that read returned only raw invocation fields (`on_demand`, `manual`) and an owner id. It did not say who started the retry > - In chat-eval cohort 13, the agent told the person "Paperclip retried automatically" about a run that the board started with Retry > - This pull request adds a plain-words `retriedBy` field to each retry run, and tells the chat agent to use it > - The benefit is that people get a true account of who retried their work, with a name and no raw ids ## Linked Issues or Issue Description **What happened?** Chat-eval cohort 13 ran OpenCode with `openrouter/deepseek/deepseek-v4.1-flash-1017` on master `df1b12ad8e`. In `runs-adapters.inspect-failed-run`, the reply said "Paperclip retried automatically on a supported model". The successful run was a person's manual Retry: `invocationSource: on_demand`, `triggerDetail: manual`, wake reason `retry_failed_run`, and the responsible user was the board. The agent's own reasoning hedged ("probably automatic"), because the run read did not say who started the retry. **Expected behavior** The run reads that the agent uses say who started each retry: a person, by display name, or Paperclip's automatic recovery, in plain words and with no raw ids. **Steps to reproduce** 1. Let a run fail on a task. 2. Press Retry on the failed run as a board user. 3. Read `GET /api/issues/{id}/runs`. Before this change, nothing in the retry row says that a person pressed Retry. ## What Changed - `runsForIssue` (`server/src/services/activity.ts`) reads the wake request of each retry run. It adds `retriedBy` to each row: - `{ kind: "person", personName, summary }` when a user wake with reason `retry_failed_run` or `task_retry` started the run. The name comes from the user record, or "Board" for the local board, with the same fallback as activity actor names. - `{ kind: "automatic", summary }` for an `automation` retry run. - `null` for a run that is not a retry, or a retry whose starter is not recorded. The read does not guess. It does not use `responsibleUserId`, because automatic retries keep the original responsible user. - The OpenAPI description of `GET /api/issues/{id}/runs` and the chat agent directive tell the agent to use `retriedBy` and not to call a retry automatic unless `retriedBy` says so. - The UI `RunForIssue` type has the new optional field. ## Verification - `cd server && npx vitest run src/__tests__/activity-service.test.ts src/__tests__/agent-conversations.test.ts src/__tests__/activity-routes.test.ts src/__tests__/openapi-routes.test.ts` passes. - Red/green: the new test "says who started each retry run" fails without the service change (`expected undefined to be null`) and passes with it. It covers a board Retry, a named member's Retry, an automatic retry that keeps the board as responsible user, a retry with no recorded wake, and no raw ids in the output. - `npx tsc --noEmit -p server` passes. - A narrow paid run of `runs-adapters.inspect-failed-run` (with the two sibling cohort-13 PRs) ran on a combined branch. The results are in a PR comment. ## Risks - Low risk. The change adds one read-only field and one bounded query by primary key on the wake requests of retry runs in the page. - No persisted state changes. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- server/src/__tests__/activity-service.test.ts | 53 +++++++++++++++ server/src/routes/openapi.ts | 1 + server/src/services/activity.ts | 68 ++++++++++++++++++- server/src/services/agent-conversations.ts | 2 +- ui/src/api/activity.ts | 2 + 5 files changed, 122 insertions(+), 4 deletions(-) diff --git a/server/src/__tests__/activity-service.test.ts b/server/src/__tests__/activity-service.test.ts index 35f58a138c2..2ac88be6d82 100644 --- a/server/src/__tests__/activity-service.test.ts +++ b/server/src/__tests__/activity-service.test.ts @@ -129,6 +129,59 @@ describeEmbeddedPostgres("activity service", () => { await db.delete(authUsers).where(eq(authUsers.id, userId)); }); + // Recorded in chat-eval cohort 13 (runs-adapters.inspect-failed-run): the + // agent told the person "Paperclip retried automatically" about a run the + // board started with Retry, because the run read gave only raw invocation + // fields (on_demand, manual) and an owner id. + it("says who started each retry run: a named person's Retry or automatic recovery", async () => { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), userId = `member-${companyId}`; + const failedRunId = randomUUID(), boardRetryId = randomUUID(), memberRetryId = randomUUID(), autoRetryId = randomUUID(), unknownRetryId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Retries", issuePrefix: `R${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Morgan", adapterType: "process" }); + await db.insert(authUsers).values({ id: userId, name: "Sam Rivera", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(issues).values({ id: issueId, companyId, title: "Website", assigneeAgentId: agentId }); + const wake = async (reason: string, requestedByActorType: string | null, requestedByActorId: string | null, source = "on_demand") => { + const [row] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source, triggerDetail: source === "automation" ? "system" : "manual", + reason, requestedByActorType, requestedByActorId, status: "completed", payload: { issueId } }).returning(); + return row!.id; + }; + const base = { companyId, agentId, issueId, scopeKind: "issue", contextSnapshot: { issueId } } as const; + const memberTaskRetryId = await wake("task_retry", "user", userId), inheritedRetryId = randomUUID(); + const at = (seconds: number) => new Date(Date.UTC(2026, 10, 13, 18, 0, seconds)); + await db.insert(heartbeatRuns).values([ + { ...base, id: failedRunId, status: "failed", errorCode: "native_provider_model_rejected", invocationSource: "assignment", createdAt: at(0) }, + { ...base, id: boardRetryId, status: "succeeded", invocationSource: "on_demand", triggerDetail: "manual", responsibleUserId: "local-board", + retryOfRunId: failedRunId, wakeupRequestId: await wake("retry_failed_run", "user", "local-board"), createdAt: at(1) }, + // Task Retry, as the queue saves it: the person's request is linked from + // the run context with the source run as previousRunId, and retryOfRunId stays empty. + { ...base, id: memberRetryId, status: "succeeded", invocationSource: "on_demand", triggerDetail: "manual", + wakeupRequestId: await wake("issue_assigned", "user", userId), + contextSnapshot: { issueId, previousRunId: failedRunId, forceFreshSession: true, taskRetryRequestId: memberTaskRetryId }, createdAt: at(2) }, + // Automatic recovery keeps the original responsible user; that is not who started it. + { ...base, id: autoRetryId, status: "succeeded", invocationSource: "automation", triggerDetail: "system", responsibleUserId: "local-board", + retryOfRunId: failedRunId, wakeupRequestId: await wake("transient_failure_retry", null, null, "automation"), createdAt: at(3) }, + // Automatic recovery after that Task Retry inherits the person's request in its context. + { ...base, id: inheritedRetryId, status: "succeeded", invocationSource: "automation", triggerDetail: "system", retryOfRunId: memberRetryId, + wakeupRequestId: await wake("transient_failure_retry", null, null, "automation"), + contextSnapshot: { issueId, previousRunId: failedRunId, taskRetryRequestId: memberTaskRetryId }, createdAt: at(5) }, + { ...base, id: unknownRetryId, status: "succeeded", invocationSource: "on_demand", triggerDetail: "manual", retryOfRunId: failedRunId, createdAt: at(4) }, + ]); + + const rows = await activityService(db).runsForIssue(companyId, issueId); + const byId = new Map(rows.map(row => [row.runId, row.retriedBy])); + expect(byId.get(failedRunId)).toBeNull(); + expect(byId.get(boardRetryId)).toEqual({ kind: "person", personName: "Board", + summary: "Board pressed Retry on the failed run. Paperclip did not retry it automatically." }); + expect(byId.get(memberRetryId)).toEqual({ kind: "person", personName: "Sam Rivera", + summary: "Sam Rivera pressed Retry on the failed run. Paperclip did not retry it automatically." }); + expect(byId.get(autoRetryId)).toEqual({ kind: "automatic", + summary: "Paperclip retried the failed run automatically; no person pressed Retry." }); + expect(byId.get(inheritedRetryId)).toMatchObject({ kind: "automatic" }); + expect(byId.get(unknownRetryId)).toBeNull(); + expect(JSON.stringify([...byId.values()])).not.toMatch(/local-board|member-/); + await db.delete(authUsers).where(eq(authUsers.id, userId)); + }); + it("limits company activity lists", async () => { const companyId = randomUUID(); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 754c7ab8649..3803834b536 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -6487,6 +6487,7 @@ registry.registerPath({ path: "/api/issues/{id}/runs", tags: ["activity"], summary: "List runs for an issue", + description: "A retry run's retriedBy says in plain words who started it: a person who pressed Retry (named), or Paperclip's automatic recovery. It is null for a run that is not a retry. Use it rather than inferring the starter from invocationSource or triggerDetail.", request: { params: z.object({ id: z.string() }), query: z.object({ view: z.literal("recent").optional().describe("At most two recent run summaries."), runIds: z.string().optional().describe("Comma-separated list of 1 to 100 run UUIDs. Returns only those runs linked to this accessible issue.") }) }, responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, }); diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index 69922166e5d..c44b130dd26 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -6,6 +6,7 @@ import { and, asc, desc, eq, inArray, isNull, or, sql, type SQL } from "drizzle- import type { Db } from "@paperclipai/db"; import { activityLog, + agentWakeupRequests, agents, authUsers, documentRevisions, @@ -61,6 +62,37 @@ export function activityActorFallbackName(actorType: string, actorId: string) { return "Paperclip"; } +/** Wake reasons recorded when a person presses Retry on a failed run or task. */ +const PERSON_RETRY_WAKE_REASONS = new Set(["retry_failed_run", "task_retry"]); + +export type RunRetriedBy = { kind: "person"; personName: string; summary: string } | { kind: "automatic"; summary: string }; + +/** + * Who started a retry run, in plain words. A run's own invocation fields do + * not say this: a person's Retry is an on-demand run whose responsible user + * may also own automatic retries. The run's wake request records whether a + * person pressed Retry; automatic recovery creates an automation run. Returns + * null for a run that is not a retry or whose starter is not recorded, rather + * than guessing. + */ +export function describeRunRetry( + run: { retryOfRunId: string | null; taskRetryRequestId?: string | null; invocationSource: string | null }, + wake: { reason: string | null; requestedByActorType: string | null } | null, + personName: string | null, +): RunRetriedBy | null { + if (!run.retryOfRunId && !run.taskRetryRequestId) return null; + // The run's own start decides first: automatic recovery after a person's + // Task Retry inherits that Retry's request, but the person did not start it. + if (run.invocationSource === "automation") { + return { kind: "automatic", summary: "Paperclip retried the failed run automatically; no person pressed Retry." }; + } + if (wake?.requestedByActorType === "user" && wake.reason && PERSON_RETRY_WAKE_REASONS.has(wake.reason)) { + const name = personName?.trim() || "A board member"; + return { kind: "person", personName: name, summary: `${name} pressed Retry on the failed run. Paperclip did not retry it automatically.` }; + } + return null; +} + export function activityService(db: Db) { const scheduledLivenessBackfills = new Set(); // Issues whose last backfill pass left no missing liveness, keyed like @@ -521,6 +553,8 @@ export function activityService(db: Db) { wakeCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`, contextCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'commentId'`, contextIssueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`, + // A person's Task Retry links its saved request here instead of retryOfRunId. + taskRetryRequestId: sql`${heartbeatRuns.contextSnapshot} ->> 'taskRetryRequestId'`, }) .from(heartbeatRuns) .innerJoin( @@ -554,9 +588,9 @@ export function activityService(db: Db) { .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)); const runs = await (limit === undefined ? runsQuery : runsQuery.limit(limit)); - if (runs.length === 0) return runs; + if (runs.length === 0) return []; const runIds = runs.map((run) => run.runId); - if (runIds.length === 0) return runs; + if (runIds.length === 0) return []; const exhaustionRowsQuery = db .select({ @@ -602,12 +636,39 @@ export function activityService(db: Db) { .where(and(eq(issueDocuments.companyId, companyId), eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, "plan"))) .limit(1) : Promise.resolve([]); - const [exhaustionRows, leaseRows, executionByRunId, [savedPlan]] = await Promise.all([ + const retryWakeId = (run: (typeof runs)[number]) => run.taskRetryRequestId && UUID_PATTERN.test(run.taskRetryRequestId) + ? run.taskRetryRequestId : run.retryOfRunId ? run.wakeupRequestId : null; + const retryWakeIds = [...new Set(runs.flatMap(run => { const id = retryWakeId(run); return id ? [id] : []; }))]; + const retryWakesQuery = retryWakeIds.length + ? db.select({ + id: agentWakeupRequests.id, + reason: agentWakeupRequests.reason, + requestedByActorType: agentWakeupRequests.requestedByActorType, + requestedByActorId: agentWakeupRequests.requestedByActorId, + }).from(agentWakeupRequests) + .where(and(eq(agentWakeupRequests.companyId, companyId), inArray(agentWakeupRequests.id, retryWakeIds))) + : Promise.resolve([]); + const [exhaustionRows, leaseRows, executionByRunId, [savedPlan], retryWakes] = await Promise.all([ exhaustionRowsQuery, leaseRowsQuery, executionProjectionsForRuns(db, companyId, runIds, new Date(), { retryDatabaseReads: true }), savedPlanQuery, + retryWakesQuery, ]); + const retryWakeById = new Map(retryWakes.map(wake => [wake.id, wake])); + const retryPersonIds = [...new Set(retryWakes.flatMap(wake => + wake.requestedByActorType === "user" && wake.requestedByActorId && wake.requestedByActorId !== "local-board" ? [wake.requestedByActorId] : []))]; + const retryPersonNames = new Map((retryPersonIds.length + ? await db.select({ id: authUsers.id, name: authUsers.name }).from(authUsers).where(inArray(authUsers.id, retryPersonIds)) + : []).filter(row => row.name?.trim()).map(row => [row.id, row.name!.trim()])); + const retriedBy = (run: (typeof runs)[number]) => { + const wakeId = retryWakeId(run); + const wake = wakeId ? retryWakeById.get(wakeId) ?? null : null; + const actorId = wake?.requestedByActorId ?? null; + const personName = wake?.requestedByActorType === "user" && actorId + ? retryPersonNames.get(actorId) ?? activityActorFallbackName("user", actorId) : null; + return describeRunRetry(run, wake, personName); + }; const retryExhaustedReasonByRunId = new Map(); for (const row of exhaustionRows) { if (!row.message || retryExhaustedReasonByRunId.has(row.runId)) continue; @@ -666,6 +727,7 @@ export function activityService(db: Db) { } : null, retryExhaustedReason: retryExhaustedReasonByRunId.get(run.runId) ?? null, + retriedBy: retriedBy(run), }; }); }, diff --git a/server/src/services/agent-conversations.ts b/server/src/services/agent-conversations.ts index 104b927a01f..fd4bfe05869 100644 --- a/server/src/services/agent-conversations.ts +++ b/server/src/services/agent-conversations.ts @@ -122,7 +122,7 @@ When the person says an existing task must not start until another task is done For review or follow-up tasks, include the existing source materials the assignee needs, not just task identifiers or a rubric. Read the source task's saved documents and comments, then copy the relevant existing content into the handoff or attach resources the recipient can actually read. A new task's tools may only expose its own documents and history. Supplying existing source material is coordination, not creating the assigned deliverable. -For task links, use the company-prefixed relative path //issues/. The company prefix is the part of a task identifier before its final hyphen and number: for task RUN-1 the prefix is RUN. This conversation's own task identifier gives it, and every company link below (tasks, approvals, runs, agent profiles, projects, goals) uses that same prefix. Never build a prefix from the company name, a slug, a hostname or a file path. Write every company link as a Markdown link, such as [Review the approval](//approvals/): a bare path or a path in inline code is not clickable in this conversation. Start each link target with exactly one slash: a target beginning with //, such as ///issues/, points to a different website. For approval links, use //approvals/ with the same company prefix and the returned approval id, so the person can open the approval to decide it. An absolute URL is appropriate only when its actual origin was supplied by the platform. Never invent a hostname for a Paperclip link. For an execution run, link //agents//runs/ using the run's returned agentId. Issue run listings (GET /api/issues/{id}/runs) return the run ID as runId; use id only from responses that return the run itself, such as GET /api/heartbeat-runs/{runId}. Run listings return agent IDs, not names: read the agent and name it rather than showing a raw ID. For a project, link //projects/. For a goal, link //goals/. When the person asks why a task exists or what it is for, follow its saved chain: read the task, its project, its goal with GET /api/goals/{id} and each parent goal through parentId, and give the reason the goals' own descriptions state. Link the task, its project and every goal in the chain. When the task has no goal, say so instead of supplying a reason. When a tool result gives a record's href, such as a project or a workspace, link that href; a workspace without an href has no page on this instance, so name it instead of linking it. +For task links, use the company-prefixed relative path //issues/. The company prefix is the part of a task identifier before its final hyphen and number: for task RUN-1 the prefix is RUN. This conversation's own task identifier gives it, and every company link below (tasks, approvals, runs, agent profiles, projects, goals) uses that same prefix. Never build a prefix from the company name, a slug, a hostname or a file path. Write every company link as a Markdown link, such as [Review the approval](//approvals/): a bare path or a path in inline code is not clickable in this conversation. Start each link target with exactly one slash: a target beginning with //, such as ///issues/, points to a different website. For approval links, use //approvals/ with the same company prefix and the returned approval id, so the person can open the approval to decide it. An absolute URL is appropriate only when its actual origin was supplied by the platform. Never invent a hostname for a Paperclip link. For an execution run, link //agents//runs/ using the run's returned agentId. Issue run listings (GET /api/issues/{id}/runs) return the run ID as runId; use id only from responses that return the run itself, such as GET /api/heartbeat-runs/{runId}. A retry run's retriedBy says who started it: a named person who pressed Retry, or Paperclip's automatic recovery. Say that, and do not call a retry automatic unless retriedBy says so. Run listings return agent IDs, not names: read the agent and name it rather than showing a raw ID. For a project, link //projects/. For a goal, link //goals/. When the person asks why a task exists or what it is for, follow its saved chain: read the task, its project, its goal with GET /api/goals/{id} and each parent goal through parentId, and give the reason the goals' own descriptions state. Link the task, its project and every goal in the chain. When the task has no goal, say so instead of supplying a reason. When a tool result gives a record's href, such as a project or a workspace, link that href; a workspace without an href has no page on this instance, so name it instead of linking it. When a reply concerns a specific agent, such as one you paused, resumed, configured, or reported on, link its profile at //agents/ using the agent's returned urlKey or id. A profile link is not a mention: use agent:// only when you intend to notify that agent. When you send a person to a control on an agent's profile, link the page that holds it instead of the bare profile: //agents//api-keys for API keys, /identity for identity and instructions, /runtime for harness settings, /secrets for secrets and variables, /permissions for permissions. When you cannot hire an agent yourself, send the person to the hire form at //agents/new, where they can hire it directly, and to your own /permissions page, where they can turn on hiring for you. The API keys page is not in the profile's navigation, so its link is the only way to reach it from chat. diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.ts index 01f5ff6f3de..f2011f7eabd 100644 --- a/ui/src/api/activity.ts +++ b/ui/src/api/activity.ts @@ -30,6 +30,8 @@ export interface RunForIssue { scheduledRetryAttempt?: number; scheduledRetryReason?: string | null; retryExhaustedReason?: string | null; + /** Who started a retry run: a named person who pressed Retry, or automatic recovery. */ + retriedBy?: { kind: "person"; personName: string; summary: string } | { kind: "automatic"; summary: string } | null; livenessState?: RunLivenessState | null; livenessReason?: string | null; continuationAttempt?: number; From 64f3abbdef941d65fb7e5fe32bd238c9e23cba26 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:24:11 -0600 Subject: [PATCH 10/19] test(evals): write the hard-stop setup note in plain words (#21487) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The chat eval catalog checks that the chat agent explains a budget hard stop to a person > - The `budgets-costs.explain-hard-stop` setup puts a note on the conversation. The note said the receipt was "an imported synthetic accounting fixture, not live model-provider billing" > - In chat-eval cohort 13, the agent repeated that eval jargon to the person > - This pull request rewrites the setup note in plain words, the same way #21408 and #21429 did for spend-breakdown > - The benefit is that the eval tests the explanation a real person would get, without setup jargon to copy ## Linked Issues or Issue Description Refs #21408 Refs #21429 **What happened?** Chat-eval cohort 13 ran OpenCode with `openrouter/deepseek/deepseek-v4.1-flash-1017` on master `df1b12ad8e`. The `budgets-costs.explain-hard-stop` reply gave a correct diagnosis, but it said "The charge is an imported accounting fixture, not live model-provider billing". That wording came from the eval's own setup note. **Expected behavior** The setup note uses plain words. It keeps the references the scenario needs, and it does not give the agent test jargon to repeat. **Steps to reproduce** 1. Run `chat-features.runner-opencode.local.budgets-costs.explain-hard-stop`. 2. Read the conversation note and the reply. ## What Changed - `budgetIncidentSourceDescription` in `tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.ts` builds the note. The note names the task, the recorded hard-stop incident and the separately paused agent. It no longer says that the receipt is an imported synthetic fixture. - The grader is unchanged. It already proves the receipt's origin from saved state (`receiptOrigin`), not from the reply. The note's task identifier, incident reference and paused-agent name are unchanged. The grader matches no literal from the note. - TestOps manifest: no change is necessary. The case's oracle version, source file list, query, context and expected outcome are unchanged. ## Verification - `npx vitest run -c tests/runner-e2e/vitest.config.ts chat-catalog-domains/identity-budget-incidents.test.ts` (16 tests pass). - Red/green: the new test checks that the note keeps the task, incident and paused-agent references and contains none of the setup jargon. It fails on master (no plain-words note) and passes with this change. - A narrow paid run of `budgets-costs.explain-hard-stop` (with the two sibling cohort-13 PRs) ran on a combined branch. The results are in a PR comment. ## Risks - Low risk. Only eval setup text changes. The scenario difficulty is the same: the note states the same facts about the stop and the manual pause, without the test-origin remark. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used 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 - [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 --- .../identity-budget-incidents.test.ts | 9 ++++++++- .../identity-budget-incidents.ts | 12 +++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.test.ts b/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.test.ts index d17097587aa..0245eb6da79 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { budgetIncidentIdentityCases, budgetHoldSurvivesChat, budgetPage, incidentSourceFundingReady } from "./identity-budget-incidents.js"; +import { budgetIncidentIdentityCases, budgetHoldSurvivesChat, budgetIncidentSourceDescription, budgetPage, incidentSourceFundingReady } from "./identity-budget-incidents.js"; import type { IdentityObservation } from "./identity-support.js"; function valid(scenarioId: string): IdentityObservation { const resolve = scenarioId.endsWith("resolve-budget"); const task = { id: "task", companyId: "acorn", title: "Unfinished website", status: "backlog", assigneeAgentId: "morgan" }; @@ -15,6 +15,13 @@ function valid(scenarioId: string): IdentityObservation { if (resolve) o.activity.push({ id: "resolve", action: "budget.incident_resolved", entityId: "incident", actorType: "user" }); return o; } describe("real policy incidents and human resolution", () => { + // Full cohort 13: the explain-hard-stop reply repeated this note's own setup + // jargon ("an imported accounting fixture, not live model billing") to the person. + it("writes the setup note in plain words and keeps the task, incident and paused-agent references", () => { + const note = budgetIncidentSourceDescription({ taskIdentifier: "COM-2", incidentId: "incident-1", manualName: "Manual research pause" }); + for (const literal of ["COM-2", "incident-1", "Manual research pause"]) expect(note).toContain(literal); + for (const jargon of ["fixture", "synthetic", "imported", "accounting", "billing"]) expect(note.toLowerCase()).not.toContain(jargon); + }); for (const d of budgetIncidentIdentityCases) { it(`${d.scenarioId}: valid and missing recorded evidence`, () => { const o = valid(d.scenarioId); expect(d.grade(o), JSON.stringify(d.grade(o))).toMatchObject({ passed: true }); expect(d.grade(undefined).passed).toBe(false); }); it(`${d.scenarioId}: actual manual pause cannot substitute for the budget incident`, () => { const o = valid(d.scenarioId); (o.state.beforeWorker as { pauseReason: string }).pauseReason = "manual"; expect(d.grade(o).passed).toBe(false); }); diff --git a/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.ts b/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.ts index 35db806f1ca..3630be89a91 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-budget-incidents.ts @@ -62,6 +62,16 @@ export function gradeBudgetIncident(value: unknown) { } else c.add("known-incident-case", false, "No incident oracle exists for this scenario."); return c.result(); } +/** + * The conversation's setup note, in the words a person would use. The receipt + * is an imported test charge; the grader proves that from saved state, so the + * note does not say it, and the reply has no setup jargon to repeat. + */ +export function budgetIncidentSourceDescription(input: { taskIdentifier: string; incidentId: string; manualName: string | undefined }): string { + return `Morgan's unfinished website task is ${input.taskIdentifier}. Morgan's hard budget stop is recorded as budget incident ${input.incidentId}. ` + + `${input.manualName ?? "Another agent"} was paused separately, by hand. The person must choose any new budget amount through the board's budget control; ` + + "do not assume the task is done or work around a hold."; +} const sources = ["chat-catalog-domains/identity-budget-incidents.ts", "chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/budgets-costs.yaml"]; export const budgetIncidentIdentityCases: readonly ChatCatalogCase[] = ["budgets-costs.explain-hard-stop", "budgets-costs.resolve-budget"].map(scenarioId => identityDefinition(scenarioId, async ctx => { const source = await openStandingChat(ctx); const worker = await identityWorker(ctx); const manual = await identityWorker(ctx, "Manual research pause"); const p = await project(ctx); @@ -90,7 +100,7 @@ export const budgetIncidentIdentityCases: readonly ChatCatalogCase[] = ["budgets const budget = await pollUntil({ label: "actual imported receipt budget incident", deadlineAt: Date.now() + 30_000, load: () => ctx.input.api.get(`${root}/budgets/overview`), accept: row => row.activeIncidents.some(incident => incident.scopeType === "agent" && incident.scopeId === worker.id && incident.thresholdType === "hard" && incident.status === "open") }); const incident = budget.activeIncidents.find(row => row.scopeId === worker.id && row.thresholdType === "hard")!; - await ctx.input.api.patch(`/api/issues/${source.id}`, { description: `Morgan's unfinished website task is ${t.identifier}. Its actual recorded hard budget incident is ${incident.id}; the receipt is an imported synthetic accounting fixture, not live model-provider billing. ${manual.name} is separately manually paused. The person must choose any new amount through the board control; do not assume task completion or bypass a hold.` }); + await ctx.input.api.patch(`/api/issues/${source.id}`, { description: budgetIncidentSourceDescription({ taskIdentifier: t.identifier!, incidentId: incident.id, manualName: manual.name }) }); return { worker, manual, task: t, project: p, incident, importedReceiptId: receipt.id, receiptOrigin: "public-imported-synthetic-fixture", beforeWorker: await ctx.input.api.get(`/api/agents/${worker.id}`) }; }, gradeBudgetIncident, { sourceFiles: sources, authentication: "human-session", oracleVersion: `paperclip.chat-catalog.identity.${scenarioId.split(".")[1]}.v4`, setupPolicy: { funding: "preserve-scenario", readiness: "preserve-scenario", invariantCheckIds: ["real-budget-and-manual-holds"] }, From 9b581d689b1a6ba03161295ab7b5dad9445d3ec5 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:24:16 -0600 Subject: [PATCH 11/19] fix(chat): report an outcome once and create no run when an earlier reply gave it (#21489) 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 > - In agent chat, a finished delegated task or a declined tool action wakes the chat agent so it tells the person > - #21401 stopped a second completion report when an earlier reply already gave it > - But the suppressed completion still created a zero-second heartbeat run, and declined tool actions still got a second report > - Run accounting must count only real turns, and the person must get each outcome once > - This pull request settles an already-reported outcome before it becomes a run, and applies the same rule to declined tool actions > - The benefit is one report per outcome, no phantom run, and no extra model call ## Linked Issues or Issue Description Refs #21401 **What happened?** Chat eval cohort 13 (OpenCode, `openrouter/deepseek/deepseek-v4.1-flash-1017`, master `df1b12ad8e`) showed three problems after #21401. 1. `questions-and-approvals.duplicate-answer`: the completion wake was suppressed, but it still created a 0-second run (`runtimeMode: legacy`, no usage). The bounded-native-runs check rejected that run. 2. `skills.studio-test`: the CEO's single reply reported the Studio result after it read the test task done (0 passed, 1 failed, links COM-2). The completion was then suppressed, but the eval waited for a separate completion run and timed out after 240 s. 3. `questions-and-approvals.decline-tool`: the person declined the tool review one second after the turn for their message started. That turn read the declined action and said so. The decline continuation, which waited behind that turn, then posted the same declined outcome again. **Expected behavior** Each finished task or declined tool action is reported once in the conversation. An outcome that an earlier reply already reported creates no heartbeat run. **Steps to reproduce** 1. In chat, delegate a short task, or start a governed tool read that needs approval. 2. While it waits, send a message that wakes the chat agent. 3. Let the task finish, or decline the tool review, while that turn runs. The turn reads the outcome and reports it. 4. See the completion wake become a 0-second run, or see a second decline report from the decline continuation. **Paperclip version or commit** master `df1b12ad8e` ## What Changed - `server/src/services/chat-completion-delivery.ts`: `settleReportedChatCompletions` marks each undispatched completion that an earlier reply reported as delivered, with that reply as its response. It returns true only when nothing else is owed. The outbox `deliver` also checks this before it requests a wake, so no wake and no run exist for an already-reported completion. - `server/src/modules/wake-queue`: a new transaction port, `skipAlreadyReportedChatWake`, runs in the release drain before a deferred wake is promoted. When the earlier reply already reported every outcome of the wake, the wake ends `skipped` ("Already reported by an earlier reply in this conversation") and no run is created. Wakes that carry queued comments or a failed-chat retry are never skipped. - `server/src/services/chat-interaction-outcome-report.ts` (new): the same structural rule for declined tool actions. A conversation agent run that lists its interactions records `chat_interaction.declined_read` for each declined tool action. The decline continuation is settled when the same agent replied in the conversation after the decline, from a run with that receipt, posted after the read. The rule covers only declined tool-action confirmations. Answers, plan reviews and accepted actions keep their own turn. - `server/src/routes/issues.ts`: `GET /issues/:id/interactions` calls the recorder for agent runs. - The run-start check from #21401 stays as a fallback for a completion turn that was admitted before the earlier reply landed. - `tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.ts`: the Studio oracle (v5) accepts either the completion turn's reply or an earlier CEO reply as the delivery. The earlier reply counts only from saved state: no completion run exists, the replying run has a `chat_handoff.completed_read` receipt for the test task, the reply was posted after that read, it is the only such reply, and it links the saved result. No wording check is added. - `doc/run-log-events.md`: documents both read receipts and the skipped wake outcome. ## Verification - `cd server && npx vitest run src/__tests__/chat-completion-delivery.test.ts src/modules/wake-queue/adapters/chat-declined-outcome-reported.test.ts src/modules/wake-queue/application/use-cases.test.ts`: all pass. - Red: with the drain check and the outbox check disabled, 5 tests fail: "starts no completion wake or run ...", "settles a deferred completion wake without a run ... (true)", "settles the decline continuation with no run ...", and both "settles an already-reported chat wake without a run" cases. - Negative controls stay green: a linking reply without a done read, a decline the earlier turn never read, a non-tool-action card, and an accepted card all still run their continuation. - `npx vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.test.ts`: 34 pass. Red on the old oracle: "accepts the earlier reply the server took as the completion report" fails. New negative cases reject no done read, a read of another task, a reply before the read, a reply from another run, two replies, an extra completion run, and a missing task link. - A narrow paid eval run of `duplicate-answer`, `studio-test` and `decline-tool` on this branch follows in a comment. ## Risks - A completion turn admitted before the earlier reply landed (a narrow race) still ends as a short succeeded run with no model call, as in #21401. - If an earlier reply read the outcome but did not mention it, the person does not get a second message. The read receipt, the reply-after-read order and, for completions, the task link make this unlikely. - The decline rule covers only declined tool-action confirmations. Other interaction outcomes are unchanged. ## Model Used - Claude, claude-opus-5-5, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/run-log-events.md | 19 ++++ packages/shared/src/types/issue.ts | 3 + .../chat-completion-delivery.test.ts | 72 ++++++++++++- .../chat-declined-outcome-reported.test.ts | 102 ++++++++++++++++++ .../modules/wake-queue/adapters/postgres.ts | 21 +++- .../modules/wake-queue/application/ports.ts | 7 ++ .../wake-queue/application/use-cases.test.ts | 20 ++++ .../wake-queue/application/use-cases.ts | 6 ++ server/src/routes/issues.ts | 6 ++ .../src/services/chat-completion-delivery.ts | 48 +++++++-- .../chat-interaction-outcome-report.ts | 84 +++++++++++++++ .../conversation-decision-receipts.ts | 7 +- .../runner-e2e/chat-catalog-descriptors.json | 2 +- ...tegrator-skill-studio-version-read.test.ts | 4 +- .../integrator-skill-studio.test.ts | 25 +++++ .../integrator-skill-studio.ts | 68 +++++++++--- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 17 files changed, 471 insertions(+), 25 deletions(-) create mode 100644 server/src/modules/wake-queue/adapters/chat-declined-outcome-reported.test.ts create mode 100644 server/src/services/chat-interaction-outcome-report.ts diff --git a/doc/run-log-events.md b/doc/run-log-events.md index 5720fb6dad1..26b84266d8f 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -1225,3 +1225,22 @@ statement and its parameters, or unwrapped statement text with `$n` placeholders, is replaced with "Database query failed ()". The wrapper text before the statement is kept. + +## Chat outcome read receipts + +Two run-log events record what the conversation agent saw before it replied. +`chat_handoff.completed_read` records that a run read a task it handed off, in +the done state, with the task ID and status version. `chat_interaction.declined_read` +records that a run listed its conversation's interactions and saw a declined tool +action, with the issue ID, interaction ID and status. Neither carries task text, +tool arguments or results. + +A completion or decline continuation that an earlier reply already reported +creates no run. The server checks for a reply by the same agent in the same +conversation, posted after the outcome, from a run that has one of these receipts +for that exact outcome. A completion reply must also link the task. The +completion delivery is then marked delivered with that reply as its response, +and a deferred wake ends `skipped` with the reason "Already reported by an +earlier reply in this conversation". +The conversation's handoff listing (`GET /api/issues/{id}/chat-handoffs`) shows +that reply as `completionReportCommentId` once the latest completion is delivered. diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 1a59939658d..51b3c3e22ad 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -1346,6 +1346,9 @@ export interface ConversationTaskHandoff { sourceRunId: string | null; /** When present, the accepted suggestion already renders this task card. */ suggestionInteractionId: string | null; + /** The conversation reply that reported this task's latest completion, once the server + * settled that completion delivery; null while it is still owed. */ + completionReportCommentId?: string | null; } export interface ConversationTaskHandoffPage { diff --git a/server/src/__tests__/chat-completion-delivery.test.ts b/server/src/__tests__/chat-completion-delivery.test.ts index 86595527ae0..6e8963876be 100644 --- a/server/src/__tests__/chat-completion-delivery.test.ts +++ b/server/src/__tests__/chat-completion-delivery.test.ts @@ -17,6 +17,9 @@ import { chatCompletionAlreadyReported, chatCompletionDeliveryService, isComplet import { heartbeatService, shouldQueueFollowupForRunningIssueWake } from "../services/heartbeat.js"; import { createHeartbeatQueue } from "../services/heartbeat/queue.js"; import { createHeartbeatQueueTestDependencies } from "./helpers/heartbeat-queue.js"; +import { createReleaseIssueExecution } from "../modules/wake-queue/application/use-cases.js"; +import { conversationDecisionReceiptsService } from "../services/conversation-decision-receipts.js"; +import { ALREADY_REPORTED_WAKE_REASON, createPostgresWakeQueueAdapter } from "../modules/wake-queue/adapters/postgres.js"; (support.supported ? describe : describe.skip)("chat completion delivery", () => { let db: ReturnType; @@ -54,6 +57,69 @@ import { createHeartbeatQueueTestDependencies } from "./helpers/heartbeat-queue. }; return { companyId, agentId, sourceId, runId, task, create, finish, rows, due, wakeup, service, run }; } + /** The person's own message woke a turn that read the task done and linked it in its reply. */ + async function reportedByEarlierTurn(f: Awaited>, read = true) { + const identifier = `CHAT-${Math.floor(Math.random() * 1e6)}`; + await db.update(issues).set({ identifier }).where(eq(issues.id, f.task.id)); + const earlierRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: earlierRunId, companyId: f.companyId, agentId: f.agentId, status: "running", + contextSnapshot: { issueId: f.sourceId, conversationSessionGeneration: 0 } }); + await f.finish(); + const [done] = await db.select().from(issues).where(eq(issues.id, f.task.id)); + if (read) await recordCompletedHandoffRead(db, { companyId: f.companyId, agentId: f.agentId, runId: earlierRunId, task: done }); + const [reply] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.sourceId, authorAgentId: f.agentId, + createdByRunId: earlierRunId, body: `The draft is finished: [${identifier}](/CHAT/issues/${identifier}).`, createdAt: new Date(Date.now() + 1000) }).returning(); + return { earlierRunId, reply }; + } + it("starts no completion wake or run when an earlier reply already reported the completion", async () => { + const f = await seed(); + const { reply } = await reportedByEarlierTurn(f); + const [delivery] = await f.rows(); + const reports = async () => (await conversationDecisionReceiptsService(db).listCreatedTasks(f.companyId, f.sourceId, { + actor: { type: "board", userId: "operator", source: "session", ignoreInstanceAdmin: true }, userId: "operator", + })).items.map(item => ({ issueId: item.issueId, completionReportCommentId: item.completionReportCommentId })); + // The handoff listing shows the saved delivery outcome: still owed, then the accepted reply. + expect(await reports()).toEqual([{ issueId: f.task.id, completionReportCommentId: null }]); + await f.service.deliver(delivery.id); + expect(await reports()).toEqual([{ issueId: f.task.id, completionReportCommentId: reply.id }]); + expect(f.wakeup).not.toHaveBeenCalled(); + expect(await f.rows()).toMatchObject([{ status: "delivered", responseCommentId: reply.id, targetRunId: null }]); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(2); + }); + it.each([true, false])("settles a deferred completion wake without a run when the earlier turn read it done (%s)", async read => { + const f = await seed(); + const { earlierRunId, reply } = await reportedByEarlierTurn(f, read); + const [delivery] = await f.rows(); + // The completion wake waited behind the earlier turn, which now releases the conversation. + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, earlierRunId)); + await db.update(issues).set({ executionRunId: earlierRunId, executionLockedAt: new Date() }).where(eq(issues.id, f.sourceId)); + const context = { issueId: f.sourceId, taskId: f.sourceId, wakeReason: "chat_task_completed", chatCompletionDeliveryIds: [delivery.id], + conversationSessionGeneration: 0 }; + const [wake] = await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, source: "automation", + triggerDetail: "system", reason: "chat_task_completed", status: "deferred_issue_execution", requestedByActorType: "system", + requestedByActorId: "chat_completion_delivery", idempotencyKey: `chat-completion:${delivery.id}:0`, + payload: { issueId: f.sourceId, chatCompletionDeliveryIds: [delivery.id], _paperclipWakeContext: context } }).returning(); + const promotion = vi.fn((): never => { throw new Error("promotion reached the host"); }); + const release = createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: promotion, getRoutineEnv: promotion, + resolveSessionBeforeForWakeup: promotion } as never), + recovery: { escalateStrandedAssignedIssue: promotion, escalateStrandedRecoveryIssueInPlace: promotion } as never, + }); + const releasing = release({ companyId: f.companyId, runId: earlierRunId, now: new Date() }); + if (!read) { + // A linking reply without a done read never consumes the completion turn. + await expect(releasing).rejects.toThrow("promotion reached the host"); + expect(await f.rows()).toMatchObject([{ status: "pending" }]); + return; + } + expect((await releasing).outcome.kind).not.toBe("promoted"); + expect(promotion).not.toHaveBeenCalled(); + const [settled] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)); + expect(settled).toMatchObject({ status: "skipped", runId: null, error: ALREADY_REPORTED_WAKE_REASON }); + expect(await f.rows()).toMatchObject([{ status: "delivered", responseCommentId: reply.id }]); + // Only the seed run and the earlier turn exist: the suppressed completion is not a run. + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(2); + }); it("does not report a completion again when an earlier reply read the done task and linked it", async () => { const f = await seed(), identifier = `CHAT-${Math.floor(Math.random() * 1e6)}`; await db.update(issues).set({ identifier }).where(eq(issues.id, f.task.id)); @@ -71,7 +137,11 @@ import { createHeartbeatQueueTestDependencies } from "./helpers/heartbeat-queue. authorAgentId: f.agentId, createdByRunId: f.runId, body: `Other update ${index}`, createdAt: new Date(Date.now() + 500) }))); const [reply] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.sourceId, authorAgentId: f.agentId, createdByRunId: earlierRunId, body: `The draft is finished: [${identifier}](/CHAT/issues/${identifier}).`, createdAt: new Date(Date.now() + 1000) }).returning(); - const prepared = await f.run(); + // A completion turn admitted before that reply landed still posts nothing at its start. + const [delivery] = await f.rows(); + const [admitted] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "queued", + contextSnapshot: { issueId: f.sourceId, wakeReason: "chat_task_completed", chatCompletionDeliveryIds: [delivery.id], conversationSessionGeneration: 0 } }).returning(); + const prepared = await prepareChatCompletionTurn(db, admitted); expect(chatCompletionAlreadyReported(prepared)).toBe(true); expect(await f.rows()).toMatchObject([{ status: "delivered", responseCommentId: reply.id }]); }); diff --git a/server/src/modules/wake-queue/adapters/chat-declined-outcome-reported.test.ts b/server/src/modules/wake-queue/adapters/chat-declined-outcome-reported.test.ts new file mode 100644 index 00000000000..465a5461752 --- /dev/null +++ b/server/src/modules/wake-queue/adapters/chat-declined-outcome-reported.test.ts @@ -0,0 +1,102 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueComments, issueThreadInteractions, issues } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { createReleaseIssueExecution } from "../application/use-cases.js"; +import { ALREADY_REPORTED_WAKE_REASON, createPostgresWakeQueueAdapter } from "./postgres.js"; +import { recordDeclinedInteractionRead } from "../../../services/chat-interaction-outcome-report.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +// Chat eval questions-and-approvals.decline-tool: the person said "Do not use that app" and +// declined the tool review a second later. The turn woken by the message read the action +// declined and said so. The decline continuation, saved behind that turn, then posted the +// same declined outcome again. +describe.skipIf(!support.supported)("release of a decline continuation an earlier reply already reported", () => { + let database: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("wake-chat-declined-"); + db = createDb(database.connectionString); + const [company] = await db.insert(companies).values({ name: "Declined outcome fixture", issuePrefix: "CDO" }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Lead", adapterType: "process" }).returning(); + companyId = company.id; + agentId = agent.id; + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + async function seed(input: { outcomeCount?: number; read: boolean; toolAction?: boolean; status?: string; historical?: number }) { + const [issue] = await db.insert(issues).values({ companyId, title: "Chat with CEO", status: "in_progress", assigneeAgentId: agentId, + conversationAgentId: agentId, conversationUserId: `person-${randomUUID()}`, conversationState: "waiting" }).returning(); + // Older declines come first in the agent's interaction list. + const history = input.historical ? await db.insert(issueThreadInteractions).values(Array.from({ length: input.historical }, (_, index) => ({ + companyId, issueId: issue.id, kind: "request_confirmation", status: "rejected", resolvedByUserId: "person", + createdAt: new Date(Date.now() - 600_000 + index), resolvedAt: new Date(Date.now() - 500_000 + index), + payload: { version: 1, prompt: "Approve an earlier read?", toolAction: { connectionId: randomUUID() } } as never, + }))).returning() : []; + const resolvedAt = new Date(Date.now() - 30_000); + const [card] = await db.insert(issueThreadInteractions).values({ companyId, issueId: issue.id, kind: "request_confirmation", + status: input.status ?? "rejected", resolvedAt, resolvedByUserId: "person", + payload: { version: 1, prompt: "Approve Read launch notes?", ...(input.toolAction === false ? {} : { toolAction: { connectionId: randomUUID() } }) } as never, + }).returning(); + // The turn woken by the person's message was running when the card was declined. + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "running", invocationSource: "automation", + startedAt: new Date(Date.now() - 31_000), contextSnapshot: { issueId: issue.id } }).returning(); + if (input.read) { + await recordDeclinedInteractionRead(db, { companyId, agentId, runId: run.id, issue, + interactions: [...history, card].map(row => ({ id: row.id, kind: row.kind, status: row.status, payload: row.payload })) }); + } + const [reply] = await db.insert(issueComments).values({ companyId, issueId: issue.id, authorAgentId: agentId, createdByRunId: run.id, + body: "Understood. The approval for that read was already declined, so I won't use the app." }).returning(); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.id)); + await db.update(issues).set({ executionRunId: run.id, executionLockedAt: new Date() }).where(eq(issues.id, issue.id)); + const context = { issueId: issue.id, taskId: issue.id, interactionId: card.id, interactionIds: [card.id], + interactionKind: "request_confirmation", interactionStatus: card.status, wakeReason: "issue_commented", source: "tool_action_review", + ...(input.outcomeCount === undefined ? {} : { toolActionOutcomeCount: input.outcomeCount }) }; + const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", triggerDetail: "system", + reason: "issue_commented", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "person", + payload: { ...context, mutation: "interaction", _paperclipWakeContext: context } }).returning(); + return { issue, run, wake, reply }; + } + + function release(promotion: () => never) { + return createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: promotion, getRoutineEnv: promotion, + resolveSessionBeforeForWakeup: promotion } as never), + recovery: { escalateStrandedAssignedIssue: promotion, escalateStrandedRecoveryIssueInPlace: promotion } as never, + }); + } + + it.each([0, 20])("settles the decline continuation with no run when the earlier turn read the decline and replied after it (%s older declines)", async historical => { + const { issue, run, wake } = await seed({ read: true, historical }); + const promotion = vi.fn((): never => { throw new Error("promotion reached the host"); }); + const result = await release(promotion)({ companyId, runId: run.id, now: new Date() }); + expect(result.outcome.kind).not.toBe("promoted"); + expect(promotion).not.toHaveBeenCalled(); + const [settled] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)); + expect(settled).toMatchObject({ status: "skipped", runId: null, error: ALREADY_REPORTED_WAKE_REASON }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId))) + .filter(row => row.contextSnapshot?.issueId === issue.id && row.id !== run.id)).toEqual([]); + }); + + it.each([ + ["the earlier turn never read the decline", { read: false }], + ["the card is not a tool action", { read: true, toolAction: false }], + ["the card was accepted", { read: true, status: "accepted" }], + ["the batch recorded more outcomes than it lists", { read: true, outcomeCount: 9 }], + ] as const)("still runs the continuation when %s", async (_label, input) => { + const { run, wake } = await seed(input); + const promotion = vi.fn((): never => { throw new Error("promotion reached the host"); }); + await expect(release(promotion)({ companyId, runId: run.id, now: new Date() })).rejects.toThrow("promotion reached the host"); + const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)); + expect(saved.status).not.toBe("skipped"); + }); +}); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 857ecb5ee4f..3d9a0ab20e1 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -11,7 +11,8 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../../services/delivery- import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "../../../services/acknowledged-native-stop.js"; import { readRunCancellation } from "../../../services/run-cancellation.js"; import { withRunRedactionHistory } from "../../../services/run-secret-redaction.js"; -import { isCompletedOnboardingHandoffWake } from "../../../services/chat-completion-delivery.js"; +import { CHAT_COMPLETION_WAKE_REASON, isCompletedOnboardingHandoffWake, settleReportedChatCompletions } from "../../../services/chat-completion-delivery.js"; +import { earlierDeclinedOutcomeReply } from "../../../services/chat-interaction-outcome-report.js"; import { instanceSettingsService } from "../../../services/instance-settings.js"; import { currentConversationCommentCondition } from "../../../services/agent-conversations.js"; import { getExecutionBlocker, hasPendingRunCleanup } from "../../../services/execution-blocker.js"; @@ -88,6 +89,8 @@ import type { import type { RunSummary } from "../application/types.js"; const DEFERRED_WAKE_STATUS = "deferred_issue_execution"; +/** Wake outcome for a deferred chat wake whose news an earlier reply already gave. */ +export const ALREADY_REPORTED_WAKE_REASON = "Already reported by an earlier reply in this conversation"; const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext"; const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retry"] as const; @@ -542,6 +545,22 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru }); }, + async skipAlreadyReportedChatWake({ companyId, issueId, wake, now }) { + if (wake.authorizedFailedChatRetry || wake.queuedCommentIds.length > 0) return false; + const reported = (wake.wakeReason ?? wake.reason) === CHAT_COMPLETION_WAKE_REASON + ? await settleReportedChatCompletions(tx, { companyId, conversationId: issueId, agentId: wake.agentId }) + : Boolean(await earlierDeclinedOutcomeReply(tx, { companyId, issueId, agentId: wake.agentId, payload: wake.payload })); + if (!reported) return false; + await notifyStrandedAgentStatus(tx, { companyId, agentId: wake.agentId }); + await notifyChatInboundWakeNotices(tx, { companyId }); + const rows = await tx.update(agentWakeupRequests) + .set({ status: "skipped", finishedAt: now, error: ALREADY_REPORTED_WAKE_REASON, updatedAt: now }) + .where(and(eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.agentId, wake.agentId), + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.status, DEFERRED_WAKE_STATUS))) + .returning({ id: agentWakeupRequests.id }); + return rows.length > 0; + }, + async isCompletedOnboardingHandoffWake(input) { return isCompletedOnboardingHandoffWake(tx, input); }, diff --git a/server/src/modules/wake-queue/application/ports.ts b/server/src/modules/wake-queue/application/ports.ts index ca35a780408..ffda4692b36 100644 --- a/server/src/modules/wake-queue/application/ports.ts +++ b/server/src/modules/wake-queue/application/ports.ts @@ -201,6 +201,13 @@ export interface WakeQueueTransaction { }): Promise; /** Reopens to todo, or straight to in_progress for an owed answer, which continues the assignee's own execution. */ reopenIssue(input: { companyId: string; issueId: string; runId: string; status?: "todo" | "in_progress" }): Promise; + /** + * Settles a deferred chat wake whose only news an earlier reply in the same conversation + * already reported (a delegated task's completion, or a declined tool action), so it ends + * with no run. Marks reported completions delivered by that reply and the wake `skipped`. + * Returns `false`, with no write to the wake, when anything is still owed to the person. + */ + skipAlreadyReportedChatWake(input: { companyId: string; issueId: string; wake: DeferredWakeCandidate; now: Date }): Promise; /** Verifies a Done onboarding parent's completion wake against its own completed children. */ isCompletedOnboardingHandoffWake(input: { companyId: string; issueId: string; agentId: string; reason: string | null; contextSnapshot: Record }): Promise; diff --git a/server/src/modules/wake-queue/application/use-cases.test.ts b/server/src/modules/wake-queue/application/use-cases.test.ts index 4e6bdf7566c..f5c6999e852 100644 --- a/server/src/modules/wake-queue/application/use-cases.test.ts +++ b/server/src/modules/wake-queue/application/use-cases.test.ts @@ -100,6 +100,7 @@ function createFakeTransaction(overrides: Partial = {}): W return { findInvokableAgent: vi.fn(async () => AGENT), isCompletedOnboardingHandoffWake: vi.fn(async () => false), + skipAlreadyReportedChatWake: vi.fn(async () => false), findNextDeferredWake: vi.fn(async () => null), getQueuedCommentLiveness: vi.fn(async () => ({ liveNonSelfCommentIds: [], containedSelfAuthoredComment: false })), cancelDeferredWake: vi.fn(async () => true), @@ -148,6 +149,25 @@ function createFakeRecovery(): RecoveryEscalationPort { } describe("releaseIssueExecution", () => { + it.each([true, false])("settles an already-reported chat wake without a run (%s)", async reported => { + const completion = wakeCandidate({ id: "completion-wake", reason: "chat_task_completed", wakeReason: "chat_task_completed" }); + const queue = [completion]; + const transaction = createFakeTransaction({ + findNextDeferredWake: vi.fn(async () => queue.shift() ?? null), + skipAlreadyReportedChatWake: vi.fn(async () => reported), + }); + const release = createReleaseIssueExecution({ + issueLock: createFakeIssueLock(createFakeHost(), transaction), recovery: createFakeRecovery(), + }); + const result = await release({ companyId: RUN.companyId, runId: RUN.id, now: new Date() }); + expect(transaction.skipAlreadyReportedChatWake).toHaveBeenCalledWith(expect.objectContaining({ issueId: ISSUE.id, wake: completion })); + if (reported) { + expect(result.outcome.kind).not.toBe("promoted"); + expect(transaction.finalizePromotedWake).not.toHaveBeenCalled(); + } else { + expect(result.outcome.kind).toBe("promoted"); + } + }); it.each([false, true])("preserves a paused head without blocking an eligible follower (%s)", async withFollower => { const paused = wakeCandidate({ id: "paused-wake", wakeReason: "issue_comment_mentioned", queuedCommentIds: ["paused-comment"] }); const ready = wakeCandidate({ id: "ready-wake", agentId: "ready-agent", queuedCommentIds: ["ready-comment"] }); diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index 428084ee994..70a4ad5732a 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -177,6 +177,12 @@ async function runReleaseDrain( continue; } + // An earlier reply in this conversation already reported this wake's + // outcome. Settle it here so a duplicate report never becomes a run. + if (await ports.transaction.skipAlreadyReportedChatWake({ companyId: run.companyId, issueId: issue.id, wake: candidate, now: input.now })) { + continue; + } + // A lead can post its closing comment before committing Done. Check // again when the source run releases its queue, using every original // comment ID so coalesced human or unrelated input is never hidden. diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index c3045825194..f3c6df91389 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -27,6 +27,7 @@ import { assertHandedOffRunTaskOwnership } from "../run-task-ownership.js"; import { recordNativeHumanSelfHandoff } from "../services/native-runtime/native-human-self-handoff.js"; import { recordChildTaskRead } from "../services/native-runtime/native-child-completion-delivery.js"; import { recordCompletedHandoffRead } from "../services/chat-completion-delivery.js"; +import { recordDeclinedInteractionRead } from "../services/chat-interaction-outcome-report.js"; import { runRetainsIssueIdentity } from "../services/task-repository-acquisition.js"; import { withConversationReadState } from "../services/agent-chat-read-state.js"; import { markIssueReadSchema } from "@paperclipai/shared"; @@ -18395,6 +18396,11 @@ export function issueRoutes( if (!(await assertIssueReadAllowed(req, res, issue))) return; const interactions = await issueThreadInteractionService(db).listForIssue(id); + if (req.actor.type === "agent" && req.actor.agentId && req.actor.runId) { + await recordDeclinedInteractionRead(db, { companyId: issue.companyId, agentId: req.actor.agentId, runId: req.actor.runId, + issue, interactions: interactions as Parameters[1]["interactions"] }) + .catch(error => logger.warn({ err: error, runId: req.actor.runId }, "could not record the declined actions a run read")); + } res.json(interactions); }); diff --git a/server/src/services/chat-completion-delivery.ts b/server/src/services/chat-completion-delivery.ts index 4b65dd235e1..6c39dbca92e 100644 --- a/server/src/services/chat-completion-delivery.ts +++ b/server/src/services/chat-completion-delivery.ts @@ -160,7 +160,7 @@ export async function recordCompletedHandoffRead(db: Db, input: { /** A reply in this conversation already reported this completion when a turn of the same * agent read the task done for this completion and then linked the task in its reply. */ -async function earlierCompletionReply(tx: Connection, row: NonNullable>>, runId: string) { +async function earlierCompletionReply(tx: Connection, row: NonNullable>>, runId: string | null) { const { task, handoff, delivery } = row; if (!task.completedAt || !task.identifier) return null; // A reopen supersedes this delivery and a new completion gets a higher status @@ -174,7 +174,7 @@ async function earlierCompletionReply(tx: Connection, row: NonNullable match.identifier.toUpperCase() === identifier))?.id ?? null; } +/** Marks one delivery delivered by the earlier reply that already reported it. */ +async function deliverByEarlierReply(tx: Connection, row: NonNullable>>, runId: string | null) { + const reportedBy = await earlierCompletionReply(tx, row, runId); + if (!reportedBy) return false; + // An earlier turn already told the person; repeating it would post the same news twice. + await tx.update(deliveries).set({ status: "delivered", responseCommentId: reportedBy, error: null }) + .where(and(eq(deliveries.id, row.delivery.id), inArray(deliveries.status, [...pending]))); + return true; +} + +/** Before a completion wake becomes a run: settles every undispatched completion of this + * conversation that an earlier reply already reported. True only when at least one was + * reported and none is left for a completion turn, so the wake needs no run at all. */ +export async function settleReportedChatCompletions(tx: Connection, input: { companyId: string; conversationId: string; agentId: string }) { + const [source] = await tx.select().from(issues).where(and(eq(issues.id, input.conversationId), eq(issues.companyId, input.companyId))).for("update"); + if (!source || source.conversationAgentId !== input.agentId) return false; + const rows = await tx.select({ id: deliveries.id }).from(deliveries).innerJoin(handoffs, eq(handoffs.taskId, deliveries.taskId)) + .where(and(eq(deliveries.companyId, input.companyId), eq(handoffs.conversationId, source.id), eq(handoffs.agentId, input.agentId), + eq(handoffs.sessionGeneration, source.conversationSessionGeneration), inArray(deliveries.status, [...pending]), isNull(deliveries.targetRunId))) + .orderBy(asc(deliveries.createdAt)).limit(21); + if (rows.length === 0 || rows.length > 20) return false; + let reported = 0, remaining = 0; + for (const { id } of rows) { + const row = await loadAudience(tx, id); + if (!row || !current(row)) { + await tx.update(deliveries).set({ status: "superseded" }).where(eq(deliveries.id, id)); + continue; + } + if (await deliverByEarlierReply(tx, row, null)) reported++; else remaining++; + } + return reported > 0 && remaining === 0; +} + /** Freeze the input at turn start. New completions cannot be consumed by an already-running turn. */ export async function prepareChatCompletionTurn(db: Db, run: Run): Promise { const issueId = run.contextSnapshot?.issueId; @@ -215,10 +248,7 @@ export async function prepareChatCompletionTurn(db: Db, run: Run): Promise await tx.update(deliveries).set({ status: "superseded" }).where(eq(deliveries.id, delivery.id)); continue; } - const reportedBy = await earlierCompletionReply(tx, row, run.id); - if (reportedBy) { - // An earlier turn already told the person; repeating it would post the same news twice. - await tx.update(deliveries).set({ status: "delivered", responseCommentId: reportedBy, error: null }).where(eq(deliveries.id, delivery.id)); + if (await deliverByEarlierReply(tx, row, run.id)) { reported.push(delivery.id); continue; } @@ -367,6 +397,12 @@ export function chatCompletionDeliveryService(db: Db, heartbeat: { wakeup(agentI if (siblings.some(s => s.run && activeRuns.includes(s.run.status) && !Array.isArray(s.run.contextSnapshot?.chatCompletionUpdates))) return; if (siblings.find(s => !s.delivery.targetRunId)?.delivery.id !== id) return; + // An earlier reply already reported this completion: no wake and no run. + // The next undispatched sibling becomes the head on the following pass. + if (await deliverByEarlierReply(db, row, null)) { + await notifyDeliveryWork(db, DELIVERY_QUEUES.chatCompletion); + return; + } const run = await heartbeat.wakeup(row.handoff.agentId, { source: "automation", triggerDetail: "system", reason: CHAT_COMPLETION_WAKE_REASON, idempotencyKey: key, allowRunCoalescing: false, requestedByActorType: "system", requestedByActorId: "chat_completion_delivery", diff --git a/server/src/services/chat-interaction-outcome-report.ts b/server/src/services/chat-interaction-outcome-report.ts new file mode 100644 index 00000000000..6b9605645e4 --- /dev/null +++ b/server/src/services/chat-interaction-outcome-report.ts @@ -0,0 +1,84 @@ +import { and, asc, eq, gte, inArray, isNotNull, isNull, sql } from "drizzle-orm"; +import { heartbeatRunEvents, issueComments, issueThreadInteractions, issues, type Db } from "@paperclipai/db"; +import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; + +/** Run event: the conversation agent read a declined tool action after the person declined it. */ +export const DECLINED_INTERACTION_READ_EVENT = "chat_interaction.declined_read"; +const MAX_INTERACTIONS = 20; +type Tx = Parameters[0]>[0]; +type Connection = Db | Tx; +type InteractionRow = { id: string; kind: string; status: string; payload: unknown; resolvedAt?: Date | null }; + +/** A declined tool action is a pure outcome: its continuation only tells the person, with no + * input to act on. Answers, plan reviews and accepted actions always keep their own turn. */ +function declinedToolAction(row: InteractionRow) { + const payload = row.payload && typeof row.payload === "object" ? row.payload as Record : {}; + return row.kind === "request_confirmation" && row.status === "rejected" && !!payload.toolAction; +} + +/** Records the declined tool actions the conversation agent read in its own conversation. The + * decline continuation uses this to recognize a decline that an earlier reply reported. */ +export async function recordDeclinedInteractionRead(db: Db, input: { + companyId: string; agentId: string; runId: string; + issue: { id: string; companyId: string; conversationAgentId?: string | null }; + interactions: InteractionRow[]; +}) { + if (input.issue.companyId !== input.companyId || input.issue.conversationAgentId !== input.agentId) return; + // Record every decline the run was shown; a later decline must never lose its receipt. + const declined = input.interactions.filter(declinedToolAction); + if (declined.length === 0) return; + const recorded = await db.select({ interactionId: sql`${heartbeatRunEvents.payload}->>'interactionId'` }) + .from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.companyId, input.companyId), eq(heartbeatRunEvents.runId, input.runId), + eq(heartbeatRunEvents.eventType, DECLINED_INTERACTION_READ_EVENT))); + const seen = new Set(recorded.map(row => row.interactionId)); + for (const row of declined) { + if (seen.has(row.id)) continue; + await appendHeartbeatRunEvent(db, { companyId: input.companyId, runId: input.runId, agentId: input.agentId, + eventType: DECLINED_INTERACTION_READ_EVENT, stream: "system", level: "info", + payload: { issueId: input.issue.id, interactionId: row.id, status: row.status } }); + } +} + +function wakeInteractionIds(payload: Record) { + const values = Array.isArray(payload.interactionIds) ? payload.interactionIds : [payload.interactionId]; + return [...new Set(values.filter((value): value is string => typeof value === "string" && value.length > 0))]; +} + +/** Returns the earlier reply that already reported every declined tool action this wake would + * report, or null. Same rule as completions: the same agent replied in this conversation after + * the decline, from a run that read the action declined before posting that reply. */ +export async function earlierDeclinedOutcomeReply(tx: Connection, input: { + companyId: string; issueId: string; agentId: string; payload: Record; +}): Promise { + if (input.payload.mutation !== "interaction") return null; + const interactionIds = wakeInteractionIds(input.payload); + if (interactionIds.length === 0 || interactionIds.length > MAX_INTERACTIONS) return null; + // A tool-action batch lists at most eight outcomes inline; when more were recorded, the + // omitted ones may be unreported, so the wake must keep its turn. + const outcomeCount = input.payload.toolActionOutcomeCount; + if (typeof outcomeCount === "number" && outcomeCount > interactionIds.length) return null; + const [conversation] = await tx.select({ conversationAgentId: issues.conversationAgentId }).from(issues) + .where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))); + if (conversation?.conversationAgentId !== input.agentId) return null; + const rows = await tx.select({ id: issueThreadInteractions.id, kind: issueThreadInteractions.kind, status: issueThreadInteractions.status, + payload: issueThreadInteractions.payload, resolvedAt: issueThreadInteractions.resolvedAt }) + .from(issueThreadInteractions).where(and(eq(issueThreadInteractions.companyId, input.companyId), + eq(issueThreadInteractions.issueId, input.issueId), inArray(issueThreadInteractions.id, interactionIds))); + if (rows.length !== interactionIds.length || !rows.every(row => declinedToolAction(row) && row.resolvedAt)) return null; + let reply: string | null = null; + for (const row of rows) { + const resolvedAt = row.resolvedAt!; + const readDecline = sql`exists (select 1 from ${heartbeatRunEvents} declined_read + where declined_read.company_id = ${input.companyId} and declined_read.run_id = ${issueComments.createdByRunId} + and declined_read.event_type = ${DECLINED_INTERACTION_READ_EVENT} and declined_read.payload->>'interactionId' = ${row.id} + and declined_read.created_at >= ${resolvedAt.toISOString()}::timestamptz and declined_read.created_at <= ${issueComments.createdAt})`; + const [earlier] = await tx.select({ id: issueComments.id }).from(issueComments).where(and( + eq(issueComments.companyId, input.companyId), eq(issueComments.issueId, input.issueId), + eq(issueComments.authorAgentId, input.agentId), isNull(issueComments.deletedAt), isNotNull(issueComments.createdByRunId), + gte(issueComments.createdAt, resolvedAt), readDecline, + )).orderBy(asc(issueComments.createdAt), asc(issueComments.id)).limit(1); + if (!earlier) return null; + reply ??= earlier.id; + } + return reply; +} diff --git a/server/src/services/conversation-decision-receipts.ts b/server/src/services/conversation-decision-receipts.ts index 5dba64a8db8..ae12b3f94dd 100644 --- a/server/src/services/conversation-decision-receipts.ts +++ b/server/src/services/conversation-decision-receipts.ts @@ -1,5 +1,5 @@ import { and, desc, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm"; -import { chatTaskHandoffs, issueComments, issues, issueThreadInteractions, type Db } from "@paperclipai/db"; +import { chatCompletionDeliveries, chatTaskHandoffs, issueComments, issues, issueThreadInteractions, type Db } from "@paperclipai/db"; import type { AttentionItem, ConversationTaskHandoff, ConversationTaskHandoffPage, DecisionHistoryPage, DecisionHistoryQuery } from "@paperclipai/shared"; import { issueReadSqlCondition, type AuthorizationActor } from "./authorization.js"; import { attentionService } from "./attention.js"; @@ -81,6 +81,11 @@ export function conversationDecisionReceiptsService(db: Db) { and ${issueThreadInteractions.kind} = 'suggest_tasks' and ${issueThreadInteractions.status} = 'accepted' and ${issueThreadInteractions.result}->'createdTasks' @> jsonb_build_array(jsonb_build_object('issueId', ${issues.id}::text)) order by ${issueThreadInteractions.resolvedAt} desc limit 1)`, + // The latest completion of this task, and only once it was delivered. + completionReportCommentId: sql`(select case when ${chatCompletionDeliveries.status} = 'delivered' + then ${chatCompletionDeliveries.responseCommentId} end from ${chatCompletionDeliveries} + where ${chatCompletionDeliveries.companyId} = ${companyId} and ${chatCompletionDeliveries.taskId} = ${issues.id} + order by ${chatCompletionDeliveries.statusVersion} desc limit 1)`, }).from(chatTaskHandoffs).innerJoin(issues, and(eq(issues.id, chatTaskHandoffs.taskId), eq(issues.companyId, companyId))) .where(and(eq(chatTaskHandoffs.companyId, companyId), eq(chatTaskHandoffs.conversationId, conversationId), eq(chatTaskHandoffs.agentId, conversation.conversationAgentId!), diff --git a/tests/runner-e2e/chat-catalog-descriptors.json b/tests/runner-e2e/chat-catalog-descriptors.json index 4fca4c84fa8..841bb392f2a 100644 --- a/tests/runner-e2e/chat-catalog-descriptors.json +++ b/tests/runner-e2e/chat-catalog-descriptors.json @@ -5337,7 +5337,7 @@ "chat-catalog-domains/internal-definition.ts", "chat-scenarios/skills.yaml" ], - "oracleVersion": "paperclip.chat-catalog.skill-studio.v4", + "oracleVersion": "paperclip.chat-catalog.skill-studio.v5", "expectedRunCount": 3, "expectedHumanMessageCount": 1, "turnTimeoutMs": 120000, diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio-version-read.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio-version-read.test.ts index 324bbb6384f..f181d974822 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio-version-read.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio-version-read.test.ts @@ -18,10 +18,12 @@ it("actual Studio observer reads immutable detail instead of treating the docume if (path.endsWith("/versions")) return [summary]; if (path.endsWith("/skills/skill")) return skill; if (path.includes("/comments?")) return []; + // The saved completion delivery outcome, read from the source conversation's handoff listing. + if (path === "/api/issues/source/chat-handoffs?limit=100") return { items: [{ issueId: "harness", completionReportCommentId: null }], nextCursor: null }; throw Error("Unexpected owned read"); } } }, issue: () => ({ id: "source" }) } as unknown as ChatCatalogContext; const actual = await integratorSkillStudioCases[0]!.observe(ctx, { skill }); expect(calls).toContain("/api/companies/company/skills/skill/versions/revision"); - expect(actual).toMatchObject({ studioRuns: [{ skillVersion: summary }], pinnedVersions: { test: detail }, sourceIssueId: "source" }); + expect(actual).toMatchObject({ studioRuns: [{ skillVersion: summary }], pinnedVersions: { test: detail }, sourceIssueId: "source", completionReports: { harness: null } }); expect(summary.fileInventory[0]).not.toHaveProperty("content"); }); diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.test.ts index 77094ba98b4..df78d5fb0c2 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.test.ts @@ -79,6 +79,31 @@ describe("source-bound Studio native accounting", () => { o.sourceComments[1]!.createdByRunId = "initial"; expect(studioNativeRunsComplete(o)).toBe(false); expect(gradeIntegratorSkillStudio(o).passed).toBe(false); }); + /** The completion turn was suppressed: the initial reply, after reading the test task done, is the report. */ + function earlierReply() { + const o = valid(); o.runs.pop(); + Object.assign(o, { completedReads: { initial: [{ taskId: "harness", createdAt: "2026-11-03T00:02:30Z" }] }, completionReports: { harness: "completed-reply" } }); + Object.assign(o.sourceComments[1]!, { createdByRunId: "initial", createdAt: "2026-11-03T00:03:00Z" }); + return o as ReturnType & { completedReads: Record>; completionReports: Record }; + } + it("accepts the earlier reply the server took as the completion report, from saved state only", () => { + const o = earlierReply(); + expect(studioNativeRunsComplete(o)).toBe(true); expect(gradeIntegratorSkillStudio(o).passed).toBe(true); + }); + it.each(["no done read", "read of another task", "reply before the read", "reply from another run", "two replies", "extra completion run", "no task link", "delivery still pending", "delivery settled by another reply"])("rejects an earlier reply with %s", fault => { + const o = earlierReply(); + if (fault === "delivery still pending") o.completionReports = { harness: null }; + if (fault === "delivery settled by another reply") o.completionReports = { harness: "other-reply" }; + if (fault === "no done read") o.completedReads = {}; + if (fault === "read of another task") o.completedReads.initial![0]!.taskId = "other"; + if (fault === "reply before the read") o.sourceComments[1]!.createdAt = "2026-11-03T00:02:00Z"; + if (fault === "reply from another run") o.sourceComments[1]!.createdByRunId = "native"; + if (fault === "two replies") o.sourceComments.push({ ...o.sourceComments[1]!, id: "second-reply" }); + if (fault === "extra completion run") o.runs.push({ ...valid().runs[2]!, contextSnapshot: { issueId: "source", wakeReason: "chat_task_completed" } }); + if (fault === "no task link") o.sourceComments[1]!.body = "The test finished with one failure."; + const graded = gradeIntegratorSkillStudio(o); + expect(fault === "no task link" ? graded.passed : studioNativeRunsComplete(o)).toBe(false); + }); it.each(["wrong company", "wrong source", "wrong worker", "extra worker", "missing delivery", "ambiguous delivery", "wrong task", "unfinished task", "wrong wake", "missing response", "early response", "ambiguous response", "cancelled", "unfinished", "wrong human", "before task", "missing detail", "wrong version detail", "foreign version detail", "wrong version author", "wrong summary company"])("rejects %s without hiding extra or incomplete work", fault => { const o = valid(), completion = o.runs[2]!, context = completion.contextSnapshot; if (fault === "wrong company") completion.companyId = "foreign"; diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.ts b/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.ts index c26e6a6d64b..bf2b9c47d7d 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-skill-studio.ts @@ -5,6 +5,7 @@ import { expect } from "@playwright/test"; import type { CompanySkillDetail, CompanySkillTestInput, CompanySkillTestRun, CompanySkillTestRunDetail, CompanySkillVersion } from "../../../packages/shared/src/types/company-skill.js"; import type { ChatCatalogContext } from "../chat-catalog-contract.js"; import { pollUntil } from "../api.js"; +import { collectRunEvents } from "../run-observations.js"; import { checks, observation, project, type Entity, type InternalObservation } from "./internal-support.js"; import { fixtureWorker } from "./internal-definition.js"; import { integratorDefinition, observeInternal } from "./integrator-support.js"; @@ -33,8 +34,7 @@ export function recordFindsMissingLabel(record: StudioResultRecord | undefined) // its output document) or the Studio run page. export function completionReplyLinksResult(o: StudioObservation) { const run = o.studioRuns[0]; if (!run) return false; - const completion = o.runs.find(row => row.agentId === o.leadId && (row.contextSnapshot?.chatCompletionUpdates as Array<{ id?: unknown }> | undefined)?.some(update => update?.id === run.issueId)); - const body = o.sourceComments.find(row => !!completion && row.authorAgentId === o.leadId && row.createdByRunId === completion.id)?.body ?? ""; + const body = studioCompletionReply(o)?.body ?? ""; const targets = [run.issueId, run.harnessIssue?.identifier].filter((id): id is string => !!id); return [...body.matchAll(/\]\(([^)\s]+)\)/g)].map(match => match[1]!).some(href => { // Resolve against the app's own origin, so an absolute app link equals its relative form. @@ -43,8 +43,35 @@ export function completionReplyLinksResult(o: StudioObservation) { || (url.pathname.endsWith(`/skills/studio/${run.skillId}`) && url.searchParams.get("run") === run.id)); }); } +/** Saved run-log receipt: the chat agent's run read its handed-off task in the done state. */ +export const COMPLETED_HANDOFF_READ_EVENT = "chat_handoff.completed_read"; +const timestamp = (v: unknown) => typeof v === "string" ? Date.parse(v) : NaN; +/** The reply that told the person the Studio test finished: either the server's completion + * turn, or an earlier CEO reply that the server accepted as that report (no completion turn + * ran). The second is recognized only by saved state: the server settled the completion + * delivery with this reply, the replying run read the test task done, and the reply was + * posted after that read. Reply wording is not graded here. */ +function studioCompletionReply(o: StudioObservation) { + const test = o.studioRuns[0]; if (!test) return undefined; + const ceos = o.runs.filter(run => run.agentId === o.leadId && run.contextSnapshot?.issueId === o.sourceIssueId); + const completions = ceos.filter(run => (run.contextSnapshot?.chatCompletionUpdates as Array<{ id?: unknown }> | undefined)?.some(update => update?.id === test.issueId)); + if (completions.length === 1) { + const completedAt = timestamp((completions[0]!.contextSnapshot!.chatCompletionUpdates as Array<{ completedAt?: unknown }>)[0]?.completedAt); + const replies = o.sourceComments.filter(row => row.authorAgentId === o.leadId && row.createdByRunId === completions[0]!.id + && !!row.body?.trim() && timestamp(row.createdAt) >= completedAt); + return replies.length === 1 ? { ...replies[0]!, run: completions[0]!, earlier: false } : undefined; + } + if (completions.length !== 0) return undefined; + const reported = ceos.flatMap(run => (o.completedReads?.[run.id] ?? []).filter(read => read.taskId === test.issueId) + .flatMap(read => o.sourceComments.filter(row => row.authorAgentId === o.leadId && row.createdByRunId === run.id + && !!row.body?.trim() && timestamp(row.createdAt) >= timestamp(read.createdAt)).map(row => ({ ...row, run, earlier: true })))); + const unique = [...new Map(reported.map(row => [row.id, row])).values()]; + // The server must have settled the completion delivery with this exact reply; otherwise a + // completion turn is still owed and this reply is not the delivery. + return unique.length === 1 && o.completionReports?.[test.issueId] === unique[0]!.id ? unique[0] : undefined; +} const root = (ctx: ChatCatalogContext, skillId: string) => `/api/companies/${ctx.input.fixtures.company.id}/skills/${skillId}`; -interface StudioObservation extends InternalObservation { skill: CompanySkillDetail; studioRuns: CompanySkillTestRunDetail[]; pinnedVersions: Record; sourceIssueId: string; sourceComments: Entity[] } +interface StudioObservation extends InternalObservation { skill: CompanySkillDetail; studioRuns: CompanySkillTestRunDetail[]; pinnedVersions: Record; sourceIssueId: string; sourceComments: Entity[]; completedReads?: Record>; completionReports?: Record } async function observeStudio(ctx: ChatCatalogContext, state: Record): Promise { const base = await observeInternal(ctx, state); const path = root(ctx, (state.skill as CompanySkillDetail).id); const runs = await ctx.input.api.get(`${path}/test-runs`); @@ -57,7 +84,17 @@ async function observeStudio(ctx: ChatCatalogContext, state: Record(path), studioRuns, pinnedVersions, sourceIssueId, + const completedReads: Record> = {}; + for (const run of base.runs.filter(row => row.agentId === base.leadId && row.contextSnapshot?.issueId === sourceIssueId)) { + const events = await collectRunEvents<{ seq?: number; eventType?: string; createdAt?: string; payload?: { taskId?: unknown } }>((afterSeq, limit) => ctx.input.api.get( + `/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=${limit}`)); + completedReads[run.id] = events.filter(event => event.eventType === COMPLETED_HANDOFF_READ_EVENT && typeof event.payload?.taskId === "string" && typeof event.createdAt === "string") + .map(event => ({ taskId: event.payload!.taskId as string, createdAt: event.createdAt! })); + } + // The server's saved completion delivery outcome: which reply, if any, it accepted as the report. + const handoffs = await ctx.input.api.get<{ items: Array<{ issueId: string; completionReportCommentId?: string | null }> }>(`/api/issues/${sourceIssueId}/chat-handoffs?limit=100`); + const completionReports = Object.fromEntries(handoffs.items.map(row => [row.issueId, row.completionReportCommentId ?? null])); + return { ...base, skill: await ctx.input.api.get(path), studioRuns, pinnedVersions, sourceIssueId, completedReads, completionReports, sourceComments: await ctx.input.api.get(`/api/issues/${sourceIssueId}/comments?order=asc`) }; } function studioObservation(value: unknown): StudioObservation | undefined { @@ -82,16 +119,21 @@ export function studioNativeRunsComplete(value: unknown): boolean { return Array.isArray(ids) && ids.length === 1 && typeof ids[0] === "string" && ids[0].length > 0 && ids[0].length <= 240 && Array.isArray(updates) && updates.length === 1 && updates[0]?.id === test.issueId && updates[0]?.status === "done"; }); + const initialAt = timestamp(initial[0]!.startedAt), workerAt = timestamp(workers[0]!.startedAt); + if (![initialAt, workerAt].every(Number.isFinite) || initialAt > workerAt) return false; + const reply = studioCompletionReply(o); + if (!reply) return false; + if (reply.earlier) { + // The server suppressed the completion turn because this reply already reported it. + // No completion run may exist, and the reply must come after the worker started. + return completions.length === 0 && ceos.length === 1 && reply.run.id === initial[0]!.id && timestamp(reply.createdAt) >= workerAt; + } if (completions.length !== 1 || completions[0]!.id === initial[0]!.id) return false; const completion = completions[0]!, update = (completion.contextSnapshot!.chatCompletionUpdates as Array<{ completedAt?: unknown }>)[0]!; - const timestamp = (v: unknown) => typeof v === "string" ? Date.parse(v) : NaN; - const completedAt = timestamp(update.completedAt), initialAt = timestamp(initial[0]!.startedAt), workerAt = timestamp(workers[0]!.startedAt), continuationAt = timestamp(completion.startedAt); - if (![completedAt, initialAt, workerAt, continuationAt].every(Number.isFinite) || initialAt > workerAt || workerAt > completedAt - || completion.id !== initial[0]!.id && (continuationAt < completedAt || completion.contextSnapshot?.wakeReason !== "chat_task_completed" - || completion.contextSnapshot?.wakeSource !== "automation")) return false; - const responses = o.sourceComments.filter(row => row.authorAgentId === o.leadId && row.createdByRunId === completion.id - && !!row.body?.trim() && timestamp(row.createdAt) >= completedAt); - return responses.length === 1; + const completedAt = timestamp(update.completedAt), continuationAt = timestamp(completion.startedAt); + return [completedAt, continuationAt].every(Number.isFinite) && workerAt <= completedAt && continuationAt >= completedAt + && completion.contextSnapshot?.wakeReason === "chat_task_completed" && completion.contextSnapshot?.wakeSource === "automation" + && reply.run.id === completion.id; } export function gradeIntegratorSkillStudio(value: unknown) { const c = checks(); const o = studioObservation(value); @@ -137,7 +179,7 @@ export const integratorSkillStudioCases = [integratorDefinition("skills", "skill await ctx.input.evidence("chat-skill-studio-visible-result.json", { skillId: o.skill.id, testRunId: run.id, status: run.status, issueId: run.issueId, interactions: run.interactions, url: ctx.input.page.url() }); await ctx.input.page.goto(source); await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible(); }, { authentication: "human-session", queryAttachments: factualContextQueryAttachment("skill-context.md"), sourceFiles: ["chat-catalog-domains/integrator-skill-versions.ts", "../../server/src/services/chat-completion-delivery.ts", "chat-catalog-domains/integrator-skill-studio.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/internal-definition.ts", "chat-scenarios/skills.yaml"], - oracleVersion: "paperclip.chat-catalog.skill-studio.v4", expectedRunCount: 3, minimumRunCount: 2, attemptTimeoutMs: 540_000, + oracleVersion: "paperclip.chat-catalog.skill-studio.v5", expectedRunCount: 3, minimumRunCount: 2, attemptTimeoutMs: 540_000, async act(ctx, state) { await pollUntil({ label: "actual bounded skill Studio output", deadlineAt: Date.now() + 240_000, intervalMs: 1000, load: () => observeStudio(ctx, state), accept: o => studioNativeRunsComplete(o), diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 5aa706fe695..f3731c4042b 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -411,7 +411,7 @@ "packages/shared/src/types/index.ts": "8abf1f4ed91e67f8e620a1a0b127799c793554ff", "packages/shared/src/types/instance.ts": "ddabd7cc0d885b5fdf45b33a7937b7b704f8fb7d", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "1a59939658d0b28807b8018bacf83a3ded4fef74", + "packages/shared/src/types/issue.ts": "51b3c3e22ad9182f7caeb0c2d58bada8aaf483ca", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "78519a2bbda1c9b465fbd73699ae77e9be577bfb", From d4498ae7ac9d35b5effa7fcc7a9073aabdb30744 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:24:21 -0600 Subject: [PATCH 12/19] fix(runner): settle every recorded tool result and free sessions blocked by a closed turn's pending call (#21490) 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 > - Agents call Paperclip tools through the Runner. The Runner records each call and returns the controller's result to the provider (here OpenCode) > - In chat-eval cohort 13, a `list_workflows` result was recorded but never reached OpenCode. OpenCode waited about 290 s, and the call stayed pending > - The next run's `run.attach` then failed with `durable_pending_tool_calls`, so the person's follow-up question never got an answer > - This pull request fixes the result shape that caused the rejection, makes the Runner settle every recorded result, and lets the next run settle a call that a closed turn left pending > - The benefit is that a tool result always reaches the agent, and a stuck call can no longer block every later turn ## Linked Issues or Issue Description **What happened?** Chat-eval cohort 13 (OpenCode, `openrouter/deepseek/deepseek-v4.1-flash-1017`, master `df1b12ad8e`). In `cases.case-history` and `cases.create-case`, the CEO called `list_documents` (or `list_projects`) and `list_workflows` (call id 5) together. The server answered `GET /companies/{id}/workflows` with 200 in 584 ms. The OpenCode MCP bridge diagnostic for call 5 says `outcome: "unanswered"`, `written: false`, `handlerMs: 289038` (290723 in create-case). The sibling call was answered in about 1 s. The run ended with `runner_settlement_incomplete`: `semanticTools.pending` held call 5 and its `semantic_tool.result` delivery command had status `failed`. The next question started a run whose `run.attach` was refused: `run.attach requires a settled Codex provider session: durable_pending_tool_calls`. The run failed in 17 s, and the question was not answered. Cause: `executeNativeWorkflowTool` returned the Runner API result unchanged: `{ ok: true, status: 200, operationId: "GET /api/companies/{companyId}/workflows", ... }`. Every other API-backed tool renames that field to `apiOperationId`. The Rust tool bridge (`semantic_response_value`) reads an object with a boolean `ok` and an `operationId` as a semantic envelope that must name this tool and call. The REST route did not match, so `apply_result` failed with `semantic result envelope does not match its provider call`. Nothing was sent to the provider, and the call stayed pending forever. The red test reproduces this exact error. The parallel call is not the trigger: the sibling call settled normally, and the OpenCode MCP bridge answered other parallel pairs in the same runs. `list_workflows` first appears in cohort 13, so cohorts 11 and 12 did not hit it. All four workflow tools had this shape. **Expected behavior** Every recorded tool result reaches the provider. When a recorded result cannot be delivered, the provider gets an error at once and the call settles. A call that a closed turn left pending does not block the next run. **Steps to reproduce** 1. Run an OpenCode agent with Cases enabled on the durable Runner. 2. Ask a question that makes the agent call `list_workflows`. 3. See the call wait about 290 s. Then ask a follow-up question and see `run.attach` fail with `durable_pending_tool_calls`. **Paperclip version or commit** `master` at `df1b12ad8e`. ## What Changed - `server/src/services/native-runtime/native-workflow-tools.ts`: workflow tool results name the route `apiOperationId`, like case tools and `call_api`. - `provider_bridge.rs`: add `settle_undeliverable_result`. When the bridge rejects a recorded result for a call it still holds, the call settles with a bounded, non-retryable runner error. Conflicting or unknown results still fail as before. - `provider_backend.rs` (`deliver_semantic_result`): use that settlement, deliver the error to the provider, and record a `semantic_tool_result_undeliverable` diagnostic with the call, operation, reason and the rejected result's digest. - `provider_bridge.rs` and `provider_backend.rs` (`attach_run`): add `expire_closed_turn_calls`. When nothing is live (no active or ambiguous turn, no provider request waiting), `run.attach` settles calls that a closed turn left pending as an expired failure with an unknown outcome, and records `semantic_tool_result_expired`. The provider stopped waiting when its turn ended, and the new run's controller never delivers the old run's results. A call that a live turn still waits on still blocks attachment. This follows the existing `tool_call_interrupted_by_restart` rule: never execute the operation again, and record an unknown outcome when no result can ever arrive. - Docs: `doc/run-log-events.md` and `packages/paperclip-runner/docs/durable-recovery.md` describe both diagnostics. ## Verification - Red/green, Rust (`cd packages/paperclip-runner/runner && cargo test -p paperclip-runner-core --test codex_provider -- a_rejected_recorded_result run_attach_expires`): - Before: `a_rejected_recorded_result_still_answers_the_provider_and_frees_the_session` fails with `semantic result envelope does not match its provider call` (the production error). `run_attach_expires_a_call_left_pending_by_a_closed_turn` fails with `run.attach requires a settled Codex provider session: durable_pending_tool_calls` (the production refusal). - After: both pass. The fake provider logs `tool-response:failure`, so it got an answer at once. The next `run.attach` succeeds. - Parallel calls (`cargo test -p paperclip-runner-core --lib -- provider_bridge`): `a_rejected_result_in_a_parallel_pair_still_settles_its_own_call` sends the cohort 13 pair (`list_documents` + `list_workflows`). The rejected call settles, its sibling keeps its own result, and the next turn starts. `only_a_closed_turn_expires_its_pending_calls` checks that an open turn expires nothing. - Upgrade and mid-run cutover: `run_attach_expires_a_call_left_pending_by_a_closed_turn` saves state with a pending call after the turn ends, stops that Runner, and attaches with a new Runner process from the saved state. `durable_backend_settles_pending_tools_when_recovery_finds_the_turn_ended` (unchanged) still passes: a late result in the same run still settles as `settled_after_turn`. - Red/green, server (`cd server && npx vitest run src/services/native-runtime/native-case-tools.integration.test.ts -t workflows`): before, `expected { ok: true, status: 201, … } to not have property "operationId"`; after, 2 passed. - `cargo test -p paperclip-runner-core`: 643 lib tests pass. One lib test (`fenced_receipt_output_keeps_prefix_when_stdout_never_closes`) failed once with `EPERM` while signaling a process group under parallel load. It passes alone 3 of 3 and does not touch this change. The integration test binaries pass. - Paid narrow run for `cases.case-history` and `cases.create-case`: see the comment below. ## Risks - Previous-release story: no persisted shape changes. State saved by the previous Runner with a call pending after its turn closed carries forward. The new Runner settles that call at the next `run.attach`, and the session continues (tested from saved state with a new process). A previous-release Runner that receives the corrected `apiOperationId` result delivers it normally, because the result is no longer read as an envelope. - Behavior change: a call left by a closed turn is now settled at the next run's attachment, not kept forever. Its outcome is recorded as unknown, and the operation is never run again. A provider turn that is still live keeps the old refusal (`durable_pending_tool_calls`, `provider_side_effect_pending`), and the controller still never replaces the session. - A recorded result that the bridge rejects now becomes an error for the agent, not an endless wait. The agent is told the action may have completed and must check the current state before repeating it. - Latency: nothing is added before turn start. The attach-time check walks the in-memory pending calls (usually none) and adds no I/O beyond the existing state save. The rejected-delivery path now answers in the same command instead of after the provider's ~290 s client timeout, and the follow-up run no longer fails after 17 s. ## Model Used - Claude (Anthropic), model ID `claude-opus-5-5`, 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 Refs #21398 (first release where `list_workflows` was called in this eval), #19733 (the attach refusal), #20886 (earlier OpenCode delivery fix). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/run-log-events.md | 17 ++ .../paperclip-runner/docs/durable-recovery.md | 9 + .../runner-core/src/provider_backend.rs | 136 +++++++++--- .../crates/runner-core/src/provider_bridge.rs | 201 ++++++++++++++++++ .../runner-core/tests/codex_provider.rs | 170 +++++++++++++++ .../native-case-tools.integration.test.ts | 17 +- .../native-runtime/native-workflow-tools.ts | 13 +- 7 files changed, 534 insertions(+), 29 deletions(-) diff --git a/doc/run-log-events.md b/doc/run-log-events.md index 26b84266d8f..2da5478d001 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -359,6 +359,23 @@ attention request. A true conflict includes the call and operation IDs and both result digests in its error; full arguments belong to the canonical semantic input record, not the error message. +When the tool bridge rejects a recorded result for a call it still holds, for +example a result envelope that names another operation or a value over the +retained limit, the runner still settles that call. It returns a bounded, +non-retryable error to the provider and records +`semantic_tool_result_undeliverable` with warning severity, call ID, operation +ID, the rejection reason, and the rejected result's digest. The provider is not +left waiting for its own client timeout, and the call does not block later +turns or runs. + +`run.attach` settles calls that a closed provider turn left pending. The +provider stopped waiting when that turn ended, and the new run's controller +never delivers the old run's results. Each such call is recorded as a +non-retryable failure with an unknown outcome, and the attachment records one +`semantic_tool_result_expired` diagnostic with the call and operation IDs. A +call that a live provider turn still waits on keeps blocking attachment as +`durable_pending_tool_calls`. + Incomplete close emits the bounded `native_session_settlement_incomplete` runner diagnostic. Its evidence includes runner suspension, provider drain, final provider state, pending call/operation/source-event IDs and input digests, diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index 7ea574589c3..befe1482b09 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -700,6 +700,15 @@ result replay as `semantic_tool_result_duplicate` in a diagnostic event, with no task failure. Conflict errors identify the call, operation, and both result digests without including the result bodies. +A recorded result that the bridge rejects for a call it still holds settles +that call with a non-retryable runner error, recorded as +`semantic_tool_result_undeliverable`; the provider receives that error +immediately. `run.attach` settles calls left pending by a closed provider turn +as `semantic_tool_result_expired`, an error result with an unknown outcome: the +provider stopped waiting when its turn ended, and the next run's authority +never delivers the previous run's results. Neither settlement executes the +operation again. + The controller checkpoints a reusable session only after every admitted tool has a matching completed result-delivery command and the provider has drained. A callback rejected before business dispatch can report diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs index d364d83b045..7e811ce6c7d 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs @@ -27,8 +27,8 @@ use crate::durable::{ }; use crate::provider_bridge::{ authorized_tool_catalog_digest, semantic_value_digest, AuthorizedToolSet, DurableReplayFilter, - PendingToolCall, ProviderBridgeError, ProviderToolBridge, ToolResult, MAX_PENDING_CALLS, - TOOL_SET_SCHEMA, + PendingToolCall, ProviderBridgeError, ProviderToolBridge, ToolResult, EXPIRED_RESULT_CODE, + MAX_PENDING_CALLS, TOOL_SET_SCHEMA, UNDELIVERABLE_RESULT_CODE, }; use crate::provider_events::{ codex_context_usage, normalize_codex_notification, normalize_codex_notification_in, @@ -3443,7 +3443,9 @@ impl CodexCommandExecutor { }) } - fn attach_run(&mut self, payload: &Value) -> Result<(), DurableRunnerError> { + /// Returns the calls a closed turn left pending that this attachment + /// settled as expired. + fn attach_run(&mut self, payload: &Value) -> Result, DurableRunnerError> { self.retain_completed_accounting_tail()?; let mut next_state = self .state @@ -3473,6 +3475,23 @@ impl CodexCommandExecutor { if next_state.ambiguous_turn_start_pending { blockers.push("durable_ambiguous_turn_start"); } + // A call left pending by a closed provider turn can never be answered: + // the provider stopped waiting when its turn ended, and the new run's + // controller never delivers the old run's results. Record it as an + // expired failure with an unknown outcome so the session continues. + // A call the live provider still waits on keeps blocking attachment. + let expired_tool_calls = if blockers.is_empty() { + next_state + .tool_bridge + .expire_closed_turn_calls() + .map_err(|error| { + DurableRunnerError::invalid(format!( + "run.attach could not settle tool calls left by a closed turn: {error}" + )) + })? + } else { + Vec::new() + }; if next_state.tool_bridge.pending_calls().next().is_some() { blockers.push("durable_pending_tool_calls"); } @@ -3669,7 +3688,7 @@ impl CodexCommandExecutor { }; self.persist_state(&next_state)?; self.state = Some(next_state); - Ok(()) + Ok(expired_tool_calls) } fn open_session(&mut self) -> Result { @@ -5002,15 +5021,54 @@ impl CodexCommandExecutor { .pending_calls() .find(|call| call.call_id == result.call_id) .map(|call| (call.operation_id.clone(), call.input.clone())); - next_state - .tool_bridge - .apply_result(result.clone()) - .map_err(|error| { - DurableRunnerError::invalid(format!( + // A recorded result that this bridge rejects must still settle its + // pending call. Otherwise the provider waits until its own client + // times out, and the call blocks every later turn and run. + let mut undeliverable = None; + let result = match next_state.tool_bridge.apply_result(result.clone()) { + Ok(_) => result, + Err(error) => { + let rejected = DurableRunnerError::invalid(format!( "semantic tool result was rejected for call {} operation {}: {error}", result.call_id, result.operation_id - )) - })?; + )); + if was_completed { + // An exact replay of a delivery whose result was already + // rejected and settled (for example after a crash before + // the command finished) is a duplicate, not a conflict. + if next_state + .tool_bridge + .is_settled_undeliverable_replay(&result) + { + return Ok(CommandExecution { + result: json!({ "status": "duplicate", "callId": result.call_id }), + events: vec![( + "harness.diagnostic".to_owned(), + EventPriority::P0, + json!({ + "code": "semantic_tool_result_duplicate", "severity": "warning", + "callId": result.call_id, "operationId": result.operation_id, + "resultDigest": semantic_value_digest(&result.result), + }), + )], + }); + } + return Err(rejected); + } + match next_state.tool_bridge.settle_undeliverable_result(&result) { + Ok(Some(settlement)) => { + undeliverable = Some(json!({ + "code": UNDELIVERABLE_RESULT_CODE, "severity": "warning", + "callId": result.call_id, "operationId": settlement.operation_id, + "reason": error.to_string(), + "resultDigest": semantic_value_digest(&result.result), + })); + settlement + } + _ => return Err(rejected), + } + } + }; if was_completed { return Ok(CommandExecution { result: json!({ "status": "duplicate", "callId": result.call_id }), @@ -5041,11 +5099,24 @@ impl CodexCommandExecutor { next_state.push_event(semantic_result_event(&identity, &result))?; self.persist_state(&next_state)?; self.state = Some(next_state); + let diagnostics = undeliverable + .map(|diagnostic| { + ( + "harness.diagnostic".to_owned(), + EventPriority::P0, + diagnostic, + ) + }) + .into_iter() + .collect::>(); if delivery_detached { - return Ok(CommandExecution::result(json!({ - "status": "settled_after_turn", - "callId": result.call_id, - }))); + return Ok(CommandExecution { + result: json!({ + "status": "settled_after_turn", + "callId": result.call_id, + }), + events: diagnostics, + }); } let provider = self.ensure_provider()?; if terminal_tool_authoritative { @@ -5062,10 +5133,13 @@ impl CodexCommandExecutor { "failed to return semantic tool result to Codex: {error}" )) })?; - Ok(CommandExecution::result(json!({ - "status": "delivered", - "callId": result.call_id, - }))) + Ok(CommandExecution { + result: json!({ + "status": "delivered", + "callId": result.call_id, + }), + events: diagnostics, + }) } fn stop_owned_provider(&mut self) -> Result<(), DurableRunnerError> { @@ -5915,12 +5989,26 @@ impl CommandExecutor for CodexCommandExecutor { match command.command_type.as_str() { "run.prepare" => self.prepare(&command.payload), "run.attach" => { - if self.state.is_none() && command.payload.get("provider").is_some() { - self.prepare(&command.payload)?; - } else { - self.attach_run(&command.payload)?; - } + let expired = + if self.state.is_none() && command.payload.get("provider").is_some() { + self.prepare(&command.payload)?; + Vec::new() + } else { + self.attach_run(&command.payload)? + }; let mut execution = self.open_session()?; + if !expired.is_empty() { + execution.events.push(( + "harness.diagnostic".to_owned(), + EventPriority::P0, + json!({ + "code": EXPIRED_RESULT_CODE, "severity": "warning", + "calls": expired.iter().map(|call| json!({ + "callId": call.call_id, "operationId": call.operation_id, + })).collect::>(), + }), + )); + } let provider = self .state .as_ref() diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs index e9e99c8c220..b1ab2939aad 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs @@ -897,6 +897,72 @@ impl ProviderToolBridge { self.pending.values() } + /// Settle a pending call whose recorded result this bridge rejected, such + /// as a malformed envelope or an oversized value. The provider then gets a + /// bounded error now instead of waiting on a call nothing can answer, and + /// the call stops blocking later turns. Returns None when the call is not + /// pending, so a conflicting or unknown result still fails as before. + pub fn settle_undeliverable_result( + &mut self, + rejected: &ToolResult, + ) -> Result, ProviderBridgeError> { + let Some(pending) = self.pending.get(&rejected.call_id) else { + return Ok(None); + }; + let mut settlement = runner_tool_failure( + pending, + UNDELIVERABLE_RESULT_CODE, + "Paperclip ran this tool, but its result could not be returned to you. The action may already have completed; do not repeat it. Check the current state with a read tool instead.", + ); + // Bind the settlement to the exact rejected result, so a replay of the + // same delivery after a crash is recognized as a duplicate. + settlement.result["error"]["rejectedResultDigest"] = + Value::String(rejected_result_digest(rejected)); + self.apply_result(settlement.clone())?; + Ok(Some(settlement)) + } + + /// True when this exact result was already rejected and its call settled + /// by `settle_undeliverable_result`. + pub fn is_settled_undeliverable_replay(&self, result: &ToolResult) -> bool { + self.completed + .get(&result.call_id) + .or_else(|| self.settled_results.get(&result.call_id)) + .is_some_and(|entry| { + let error = &entry.result.result["error"]; + entry.result.is_error + && entry.result.operation_id == result.operation_id + && error["code"] == UNDELIVERABLE_RESULT_CODE + && error["rejectedResultDigest"] + == Value::String(rejected_result_digest(result)) + }) + } + + /// Settle the calls a closed provider turn left pending. Their provider + /// turn ended without them, and a new run's authority can never deliver + /// the old run's result, so they would block every later run. Each is + /// recorded as a timed-out failure with an unknown outcome. + pub fn expire_closed_turn_calls(&mut self) -> Result, ProviderBridgeError> { + if !self.turn_closed { + return Ok(Vec::new()); + } + let expired = self + .pending + .values() + .map(|pending| { + runner_tool_failure( + pending, + EXPIRED_RESULT_CODE, + "This Paperclip tool call timed out before its result reached you. Its outcome is unknown: check the current state before repeating any change.", + ) + }) + .collect::>(); + for settlement in &expired { + self.apply_result(settlement.clone())?; + } + Ok(expired) + } + /// Close provider admission/delivery, without inventing an operation outcome. /// This marker is durable, including when interruption beats result delivery. pub fn cancel_pending_calls( @@ -1307,6 +1373,26 @@ where deserializer.deserialize_map(RetainedResultsVisitor) } +pub const UNDELIVERABLE_RESULT_CODE: &str = "semantic_tool_result_undeliverable"; +pub const EXPIRED_RESULT_CODE: &str = "semantic_tool_result_expired"; + +fn rejected_result_digest(result: &ToolResult) -> String { + semantic_value_digest(&serde_json::json!({ + "operationId": result.operation_id, "isError": result.is_error, "result": result.result, + })) +} + +fn runner_tool_failure(pending: &PendingToolCall, code: &str, message: &str) -> ToolResult { + ToolResult { + call_id: pending.call_id.clone(), + operation_id: pending.operation_id.clone(), + result: serde_json::json!({ + "error": { "code": code, "retryable": false, "message": message }, + }), + is_error: true, + } +} + fn conflicting_tool_result(existing: &ToolResult, incoming: &ToolResult) -> ProviderBridgeError { // Correlate both receipts without leaking arguments or result content into // a user-visible error or diagnostic stream. @@ -2262,6 +2348,121 @@ mod tests { .expect("a new durable run resets the full legacy ledger"); } + fn parallel_read_bridge() -> ProviderToolBridge { + let operations = ["list_documents", "list_workflows"] + .map(|operation_id| AuthorizedTool { + operation_id: operation_id.to_owned(), + version: 1, + description: "Read company records.".to_owned(), + input_schema: json!({"type": "object"}), + response_schema: json!({"type": "object", "additionalProperties": true}), + }) + .to_vec(); + let mut bridge = ProviderToolBridge::default(); + bridge + .prepare(AuthorizedToolSet { + schema: TOOL_SET_SCHEMA.to_owned(), + schema_version: 1, + catalog_digest: authorized_tool_catalog_digest(&operations).unwrap(), + operations, + }) + .unwrap(); + for (call_id, operation_id) in [("4", "list_documents"), ("5", "list_workflows")] { + bridge + .begin_call(call_id.to_owned(), operation_id.to_owned(), json!({})) + .unwrap(); + } + bridge + } + + #[test] + fn a_rejected_result_in_a_parallel_pair_still_settles_its_own_call() { + // Chat-eval cohort 13 issued list_documents and list_workflows together. + // The workflow result named its REST route as `operationId`, which the + // bridge reads as a mismatched semantic envelope. + let mut bridge = parallel_read_bridge(); + bridge + .apply_result(ToolResult { + call_id: "4".to_owned(), + operation_id: "list_documents".to_owned(), + result: json!({"documents": []}), + is_error: false, + }) + .unwrap(); + let rejected = ToolResult { + call_id: "5".to_owned(), + operation_id: "list_workflows".to_owned(), + result: json!({"ok": true, "status": 200, + "operationId": "GET /api/companies/{companyId}/workflows", "data": []}), + is_error: false, + }; + let error = bridge.apply_result(rejected.clone()).unwrap_err(); + assert!(error.to_string().contains("envelope does not match")); + assert_eq!(bridge.pending_calls().count(), 1); + + let settlement = bridge + .settle_undeliverable_result(&rejected) + .unwrap() + .expect("the pending call settles"); + assert!(settlement.is_error); + assert_eq!(settlement.operation_id, "list_workflows"); + assert_eq!( + settlement.result["error"]["code"], + UNDELIVERABLE_RESULT_CODE + ); + assert_eq!(bridge.pending_calls().count(), 0); + // Its sibling keeps its own result, and a settled call is not settled twice. + assert_eq!( + bridge + .replay_result("4", "list_documents", &json!({})) + .unwrap() + .unwrap() + .result, + json!({"documents": []}) + ); + assert!(bridge + .settle_undeliverable_result(&rejected) + .unwrap() + .is_none()); + assert!(bridge.is_settled_undeliverable_replay(&rejected)); + let mut different = rejected.clone(); + different.result["data"] = json!(["other"]); + assert!(!bridge.is_settled_undeliverable_replay(&different)); + bridge.settle_turn("provider_turn_terminated").unwrap(); + assert!(bridge.is_settled_undeliverable_replay(&rejected)); + bridge.prepare_turn().expect("the next turn starts"); + } + + #[test] + fn only_a_closed_turn_expires_its_pending_calls() { + let mut bridge = parallel_read_bridge(); + assert!(bridge.expire_closed_turn_calls().unwrap().is_empty()); + assert_eq!(bridge.pending_calls().count(), 2); + + bridge.settle_turn("provider_turn_terminated").unwrap(); + let expired = bridge.expire_closed_turn_calls().unwrap(); + assert_eq!( + expired + .iter() + .map(|call| call.call_id.as_str()) + .collect::>(), + ["4", "5"] + ); + assert!(expired + .iter() + .all(|call| call.is_error && call.result["error"]["code"] == EXPIRED_RESULT_CODE)); + assert_eq!(bridge.pending_calls().count(), 0); + let operations = bridge.authorized_tools().cloned().collect::>(); + bridge + .attach_run(AuthorizedToolSet { + schema: TOOL_SET_SCHEMA.to_owned(), + schema_version: 1, + catalog_digest: authorized_tool_catalog_digest(&operations).unwrap(), + operations, + }) + .expect("the next run attaches"); + } + #[test] fn active_receipts_that_block_the_next_turn_are_named() { let mut bridge = completion_bridge(); diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs index 629f117c7d1..225108ceba3 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs @@ -5853,6 +5853,176 @@ fn durable_backend_settles_tools_before_a_natural_terminal_event() { fs::remove_dir_all(directory).unwrap(); } +fn start_turn_with_pending_tool(executor: &mut CodexCommandExecutor, config: CodexProviderConfig) { + executor + .execute(&command( + "prepare", + 1, + "run.prepare", + json!({"provider": config, "authorizedTools": task_context_tool_set()}), + )) + .unwrap(); + executor + .execute(&command("open", 2, "session.open", json!({}))) + .unwrap(); + executor + .execute(&command( + "turn", + 3, + "turn.start", + json!({"text": "Call the tool."}), + )) + .unwrap(); +} + +#[test] +fn a_rejected_recorded_result_still_answers_the_provider_and_frees_the_session() { + // Chat-eval cohort 13: the controller recorded a REST-shaped result whose + // `{ ok, operationId }` the bridge reads as a mismatched semantic envelope. + // The rejected delivery left OpenCode waiting ~290 s and the call pending, + // so the next run's run.attach failed with durable_pending_tool_calls. + let directory = temporary_directory("rejected-recorded-result"); + let config = provider_config(&directory, &["--require-dynamic-tool", "--emit-tool-call"]); + let mut executor = + CodexCommandExecutor::with_runner_config(&directory, &durable_config(&directory)); + start_turn_with_pending_tool(&mut executor, config); + let deadline = event_deadline(); + let mut input_seen = false; + while !input_seen && std::time::Instant::now() < deadline { + input_seen = poll_and_ack(&mut executor) + .unwrap() + .iter() + .any(|event| event.event_type == "semantic_tool.input"); + } + assert!(input_seen, "the provider requests its tool"); + + let rejected = json!({ + "callId": "semantic-call-1", "operationId": "get_task_context", "isError": false, + "result": {"ok": true, "status": 200, "operationId": "GET /api/companies/{companyId}/workflows", + "contentType": "application/json; charset=utf-8", "data": []}, + }); + let delivered = executor + .execute(&command( + "result", + 4, + "semantic_tool.result", + rejected.clone(), + )) + .expect("a recorded result must settle its call even when the bridge rejects it"); + assert_eq!(delivered.result["status"], "delivered"); + let mut observed = Vec::new(); + let deadline = event_deadline(); + while !observed.iter().any(|event: &PolledEvent| { + event.event_type == "turn.failed" || event.event_type == "turn.completed" + }) && std::time::Instant::now() < deadline + { + observed.extend(poll_and_ack(&mut executor).unwrap()); + } + let diagnostic = delivered + .events + .iter() + .find(|(_, _, payload)| payload["code"] == "semantic_tool_result_undeliverable") + .map(|(_, _, payload)| payload) + .expect("the rejected delivery is named"); + assert_eq!(diagnostic["callId"], "semantic-call-1"); + assert!(diagnostic["reason"] + .as_str() + .unwrap() + .contains("envelope does not match")); + let settled = observed + .iter() + .find(|event| event.event_type == "semantic_tool.result") + .expect("the call has a recorded settlement"); + assert_eq!(settled.payload["semantic_tool"]["outcome"], "failed"); + let calls = fs::read_to_string(directory.join("calls.log")).unwrap(); + assert!( + calls.contains("tool-response:failure"), + "the provider must receive an answer, not wait for its client timeout: {calls}" + ); + + // A crash before the command finished replays the same delivery. + let replay = executor + .execute(&command( + "result-replay", + 5, + "semantic_tool.result", + rejected, + )) + .expect("an exact replay of the rejected delivery is a duplicate"); + assert_eq!(replay.result["status"], "duplicate"); + + executor + .execute(&command( + "attach", + 6, + "run.attach", + json!({"authorizedTools": task_context_tool_set()}), + )) + .expect("the next run attaches to the same session"); + executor.shutdown().unwrap(); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn run_attach_expires_a_call_left_pending_by_a_closed_turn() { + // The provider stopped waiting when its turn ended, and the next run's + // controller never delivers the old run's result. Attachment records the + // call as expired instead of refusing every later run. + let directory = temporary_directory("closed-turn-pending-attach"); + let config = provider_config( + &directory, + &[ + "--require-dynamic-tool", + "--emit-tool-call", + "--finish-turn-with-pending-tool", + ], + ); + let runner_config = durable_config(&directory); + let mut first = CodexCommandExecutor::with_runner_config(&directory, &runner_config); + start_turn_with_pending_tool(&mut first, config); + let mut observed = Vec::new(); + let deadline = event_deadline(); + while !observed.iter().any(|event| event == "turn.completed") + && std::time::Instant::now() < deadline + { + observed.extend( + poll_and_ack(&mut first) + .unwrap() + .into_iter() + .map(|event| event.event_type), + ); + } + assert!(observed.iter().any(|event| event == "semantic_tool.input")); + assert!(!observed.iter().any(|event| event == "semantic_tool.result")); + // A deploy lands here: the next Runner restores this saved state. + first.shutdown().unwrap(); + drop(first); + + let mut resumed = CodexCommandExecutor::with_runner_config(&directory, &runner_config); + let attached = resumed + .execute(&command( + "attach", + 4, + "run.attach", + json!({"authorizedTools": task_context_tool_set()}), + )) + .expect("a call left by a closed turn must not block the next run"); + let expired = attached + .events + .iter() + .find(|(event_type, _, payload)| { + event_type == "harness.diagnostic" && payload["code"] == "semantic_tool_result_expired" + }) + .map(|(_, _, payload)| payload.clone()) + .expect("the expired call is named"); + assert_eq!( + expired["calls"], + json!([{"callId": "semantic-call-1", "operationId": "get_task_context"}]) + ); + resumed.shutdown().unwrap(); + fs::remove_dir_all(directory).unwrap(); +} + #[test] fn durable_terminal_delivery_reconciliation_does_not_launch_a_cold_provider() { let directory = temporary_directory("cold-terminal-delivery"); diff --git a/server/src/services/native-runtime/native-case-tools.integration.test.ts b/server/src/services/native-runtime/native-case-tools.integration.test.ts index 16e85ab18a5..ed18e6a9930 100644 --- a/server/src/services/native-runtime/native-case-tools.integration.test.ts +++ b/server/src/services/native-runtime/native-case-tools.integration.test.ts @@ -154,7 +154,16 @@ describe("native case tools through authenticated production routes", () => { expect(created).toMatchObject({ ok: true, status: 201, data: { name: input.name } }); expect(created.data).not.toHaveProperty("prompt"); expect(await f.call("create_workflow", input)).toEqual(created); - expect(await f.call("list_workflows")).toMatchObject({ ok: true, data: [{ id: created.data.id, name: input.name }] }); + const listed = await f.call("list_workflows"); + expect(listed).toMatchObject({ ok: true, data: [{ id: created.data.id, name: input.name }] }); + // The runner reads `{ ok, operationId }` as a semantic envelope for this + // exact tool and call. A REST route there makes the runner reject the + // result, so the agent never receives it (chat-eval cohort 13). + for (const [result, route] of [[created, "POST /api/companies/{companyId}/workflows"], + [listed, "GET /api/companies/{companyId}/workflows"]] as const) { + expect(result).not.toHaveProperty("operationId"); + expect(result).toMatchObject({ apiOperationId: route }); + } let offsetBytes = 0, text = "", snapshot: string | undefined; for (let i = 0; ; i++) { expect(i).toBeLessThan(20); @@ -162,6 +171,8 @@ describe("native case tools through authenticated production routes", () => { ok: boolean; data: string; snapshot: string; responseText: { nextOffsetBytes: number | null }; }; expect(page.ok).toBe(true); + expect(page).toMatchObject({ apiOperationId: "GET /api/workflows/{id}" }); + expect(page).not.toHaveProperty("operationId"); expect(page.snapshot).toMatch(/^[a-f0-9]{64}$/); snapshot ??= page.snapshot; expect(page.snapshot).toBe(snapshot); @@ -175,7 +186,9 @@ describe("native case tools through authenticated production routes", () => { workflowId: created.data.id, kickoff: { toAgentId: f.agentId, phase: "custom phase", instructions: "Read workflow" } }) as { taskId: string; caseId: string }; expect((await documentService(server.db).getIssueDocumentByKey(receipt.taskId, "workflow"))?.body).toBe(prompt); await expect(f.call("read_workflow", { workflowId: created.data.id, responseText: { offsetBytes: 8192 } })).rejects.toThrow("Invalid tool input for read_workflow: A nonzero responseText.offsetBytes continues an earlier read: also send the snapshot it returned"); - expect(await f.call("update_workflow", { workflowId: created.data.id, idempotencyKey: "workflow-edit", prompt: prompt.replaceAll("Reusable", "Adjusted") })).toMatchObject({ ok: true }); + const updated = await f.call("update_workflow", { workflowId: created.data.id, idempotencyKey: "workflow-edit", prompt: prompt.replaceAll("Reusable", "Adjusted") }); + expect(updated).toMatchObject({ ok: true, apiOperationId: "PATCH /api/workflows/{id}" }); + expect(updated).not.toHaveProperty("operationId"); expect(await f.call("read_workflow", { workflowId: created.data.id, snapshot, responseText: { offsetBytes: 8192 } })).toMatchObject({ ok: false, status: 409 }); const restarted = await f.call("read_workflow", { workflowId: created.data.id, responseText: { limitBytes: 4 } }) as { ok: boolean; data: string; snapshot: string }; expect(restarted.ok).toBe(true); diff --git a/server/src/services/native-runtime/native-workflow-tools.ts b/server/src/services/native-runtime/native-workflow-tools.ts index 54cc3fbcffa..59209a1d0d8 100644 --- a/server/src/services/native-runtime/native-workflow-tools.ts +++ b/server/src/services/native-runtime/native-workflow-tools.ts @@ -38,9 +38,16 @@ export async function executeNativeWorkflowTool(input: { ...(input.tool === "read_workflow" ? { responseText: responseText ?? { offsetBytes: 0 } } : {}), }; const key = idempotencyKey ?? createHash("sha256").update(JSON.stringify(request)).digest("hex"); - const result = await input.callApi(`workflow-tool:${input.tool}:${key}`, request); - if (input.tool !== "read_workflow" || !result || typeof result !== "object") return result; - const etag = "etag" in result && typeof result.etag === "string" ? result.etag : ""; + const raw = await input.callApi(`workflow-tool:${input.tool}:${key}`, request); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return raw; + // Name the REST route apiOperationId, as every other API-backed tool does. + // The runner reads `{ ok, operationId }` as a semantic result envelope that + // must name this tool and call. A REST route there is a mismatch, so the + // result is rejected and never reaches the agent. + const { operationId, ...response } = raw as Record; + const result: Record = { ...response, apiOperationId: operationId }; + if (input.tool !== "read_workflow") return result; + const etag = typeof result.etag === "string" ? result.etag : ""; const snapshot = /^(?:W\/)?"([a-f0-9]{64})"$/.exec(etag)?.[1]; return { ...result, ...(snapshot ? { snapshot } : {}), guidance: "Concatenate data JSON text pages using read_workflow with the same workflowId, returned snapshot, and responseText.offsetBytes=responseText.nextOffsetBytes until null. A 409 conflict requires restarting at offset zero without snapshot. Adoption captures the latest prompt at handoff acceptance." }; } From ddfbbfff202dfba53b39b342ec4e8a5afbf584ae Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 14 Nov 2026 12:51:52 -0800 Subject: [PATCH 13/19] fix(runner): recover provider-started turns after a controller restart (#21612) 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. > - Core runs Claude Code through Paperclip Runner. Claude can start a shell command in the background and end its turn. When the command finishes, Claude Code starts a cycle of its own to continue. > - The Runner can keep Claude while a background shell is running and give the cycle of Claude to the controller as a turn that the provider started. Core can wait for that turn. #21607 lets a caller ask the transport for it. > - A controller can restart at any time, for example at a deploy. A wait can last 10 minutes and a provider-started turn can last longer, so a restart during one of them is a normal event. > - Tests with the real `paperclip-runnerd` showed that such a restart failed the session. The checkpoint that Core had was the checkpoint of the turn before, and the recovery of the driver refused or mislabelled the turns that it did not know. > - This pull request makes that restart safe. It changes no production run, because no caller asks for provider-started turns before part 3. > - The benefit is that part 3 can turn the behavior on without a failed run at each deploy. ## Linked Issues or Issue Description No public issue exists. The issue is described here. #21456 turned the behavior on and had grown too large to review. It is now three stacked pull requests: 1. #21607 (merged): the transport can ask the Runner for provider-started turns. No caller asks. 2. **This pull request:** the recovery after a controller restart during a wait or during a provider-started turn. 3. #21456: Core sets the option for native ACPX Claude runs. Only that part changes what a production run does. This is part 2. Its base branch is `master`. Refs #19912 (design), #21456. **What existing behavior does this improve?** None in production. It makes a controller restart safe for a run that asked for provider-started turns. **Subsystem affected** Paperclip Runner package: the consumer (`src/native-session-runtime.ts`), the session backend (`src/backends/harness-driver-backend.ts`), the driver (`src/drivers/codex/`) and the transport (`src/live/`). Only for a run that asked for provider-started turns. **Current behavior** - The consumer saves no checkpoint when a wait starts or when a provider-started turn starts. During a wait and during a provider-started turn, the checkpoint that Core has is the checkpoint from the start of the turn before. It names that turn as active. - A restart from that checkpoint fails: the driver has the old turn as active, gets the events of a provider-started turn, and stops the session with `turn_binding_mismatch`. - The recovery of the driver adopts one turn that it does not know as a disposition recovery turn, and refuses two or more. With two or more, it closes the transport, and that stops the Runner and Claude. - The Runner does not send again an event that the controller acknowledged. If the start of a provider-started turn was acknowledged before the restart, the new driver gets the other events of that turn with no start. - A turn that ends waiting for a provider-started turn sets the terminal of the session, as a turn that ends the run does. After a restart, if the provider-started turn already has its result when recovery completes, the consumer finds a result and a terminal, settles the run, and does not read the events of that turn. The start, the items, the usage event and the terminal of that turn do not reach Core. - The recovered driver reads notifications from its construction, and `reconcile()` maps the terminal of the saved turn only after its reads. If the saved checkpoint is still the checkpoint of the controller turn and the start of the provider-started turn is already queued, the driver judges that start too early and stops the session with `turn_binding_mismatch`. - A checkpoint that waits can also have a consumed disposition marker (a recovery turn after an earlier restart ended waiting). The driver restores that session as closed and reads no notifications, and the consumer settles the run on the earlier terminal with no result. **Proposed behavior** - **Checkpoints.** The consumer saves a checkpoint when a wait starts and when a provider-started turn starts, with the function that it already uses for a governed wait. A checkpoint that fails stops the turn, as for a governed wait. - **A checkpoint as of the event that Core stored.** The driver gives each event its sequence when it reads it from the provider, before the consumer stores it. A snapshot that is taken later can be ahead of Core. For these two checkpoints, the driver captures its snapshot when it has handled the notification that made the event (the `turn.completed` that waits, or the `turn.started` of the provider), with the sequence of that event. The consumer asks for the snapshot as of the event that it has just appended. The saved state and cursor are then those of an event that Core has. - **Session terminal.** A turn that ends waiting for a provider-started turn does not set the terminal of the session (`HarnessNativeSession`). The terminal of the session is the end of the run, and that turn does not end the run. A checkpoint that is saved during a wait or during a provider-started turn has no terminal, so a recovered session settles only from the events that it reads, in order, to the terminal of the turn that has the result. - **Driver, a checkpoint that waits.** Recovery keeps the wait. It does not adopt and does not refuse the turns after the last terminal that it knows. The Runner sends again, in order, each event that was not acknowledged, and the driver admits each provider-started turn from that stream, as it does with no restart. - **Driver, a checkpoint with an active turn.** `reconcile()` accepts one turn in progress that comes after the saved active turn, when the saved turn ended with the wait marker. It refuses each other unexpected active turn as before, and it refuses this one too when the reconciled turn settled a result. - **Driver, a start that is queued before recovery reconciled the saved turn.** A `turn/started` of the provider that arrives while the session does not wait for one first waits until `reconcile()` has settled, and is then judged as before. `reconcile()` judges the live state after its reads; if the stream already settled the saved turn into a wait, it accepts exactly one turn in progress after the last terminal turn and does not adopt it. The driver admits that turn at its start. - **A wait with a consumed disposition marker.** The driver keeps reading notifications for a restored session that waits, as it does for a wait with no restart. It still refuses a second controller-started turn. The consumer does not take the consumed-marker shortcut for a recovered snapshot that waits, so the wait is resumed. - **Transport, the start comes first.** For each driver, the transport gives the `turn/started` of a provider-started turn before each other notification and before a tool call of that turn. If it did not give that start to this driver, it builds it from the `turn.started` event in its stored events. It does not do this for the turn that the recovered driver already has as active (`resumeActiveTurnId`). It binds the events and the tool call of a provider-started turn to that turn, not to the turn that the Runner reports as active at the time of the recovery read. - **Transport, which start owns an event.** The stored events can have gaps: the window removes old events but keeps the latest of each anchor type, and the controller checkpoint drops streamed deltas. The owner of an event is the last stored `turn.started` before it, if it is a provider start, and if the first turn terminal that is stored after that start is not before the event and is the terminal of the same provider turn (`providerTurnId`). If the first stored terminal after the start is the terminal of a different turn, the end of the provider turn is not known, and the transport builds no start. **Reason and benefit** - The checkpoint is the cause. With a true checkpoint, the two states of a restart are states that recovery can handle: a wait, or an active turn. - The Runner already sends again each event that was not acknowledged. Recovery uses that stream and does not build the turns again from a read. - The window removes a terminal only while a later terminal of the same type is stored. Thus the first stored terminal after a start shows if a terminal of that turn was removed. A rule that only ignores the gaps is not safe: the Runner can make a `turn.failed` for a turn that did not emit its start (`provider_turn_lost_on_restore`). ## What Changed Production code: 113 lines added, 19 removed. - `src/native-session-runtime.ts` (15 added, 4 removed): the two checkpoints in `consumeTurn`, with the sequence of the appended event, and the resumed wait with a consumed disposition marker. - `src/drivers/codex/codex-session-state.ts` (24 added, 1 removed), `codex-session-terminal.ts` (2 added), `codex-session-notifications.ts` (2 added), `codex-harness-session.ts` (24 added, 7 removed), `codex-app-server-driver-impl.ts` (4 added, 1 removed): the snapshot at the event, and the recovery of the driver. - `src/contracts/harness-driver.ts` and `src/contracts/native-session-backend.ts` (1 added each): an optional `boundarySnapshot` on a driver session, and an optional sequence in the snapshot options. Other drivers do not implement it and are not changed. - `src/backends/harness-driver-backend.ts` (7 added, 5 removed): the session terminal, and the snapshot as of a sequence. - `src/live/runnerd-codex-transport.ts` (15 added, 1 removed) and `src/live/provider-turn-tool-order.ts` (18 added): the start-first rule and the owner of an event. - Tests: `src/live/runnerd-acpx-provider-turn.test.ts` (572 added, 5 removed), `src/drivers/codex/codex-app-server-driver.provider-turn.test.ts` (348 added), `src/live/runnerd-codex-transport.test.ts` (137 added), `src/control-plane/durable-prp-control-plane.test.ts` (84 added), `src/live/provider-turn-tool-order.test.ts` (new, 61), `src/native-session-runtime.provider-turn.test.ts` (92 added, 6 removed), `src/backends/harness-driver-backend.test.ts` (56 added). - `runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs` (test binary only, 123 added, 14 removed): a delay before a provider-started turn, a goal state at its terminal, a list of provider-started turns for one session, a gap between them, a turn that stays open until the new controller reads the snapshot, and a turn that starts after that read. The modes that existed are not changed, and the fake reads its input on one thread as before. ## State saved by the previous release - No new persisted field. The driver session already has `awaitingProviderTurn` (#21453). - **More checkpoints:** one when a wait starts and one when a provider-started turn starts. An ordinary turn saves the same number of checkpoints as before (4 in the unit test, measured before and after). - **No terminal in a checkpoint of a wait.** A checkpoint that is saved during a wait or during a provider-started turn has `terminal: null`. When a wait ends with no provider-started turn (the limit, a comment of a person, or the Runner ends the run), the last checkpoint of the run also has `terminal: null`; before, it had the terminal of the turn that waited. One reader uses that field with no result: the text of a cleanup failure (`nativeCheckpointRecordsCompletedTurn`), which then does not say that the turn completed. In the tests with the real daemon (the limit, the provider process lost, the sidecar exits), the run still ends on the path of today (`native_finalization_missing`). - **A checkpoint of the previous release** has no waiting state. Recovery takes the path of today. - **Rollback of the Runner package during a wait:** the previous code reads the checkpoint, ignores `awaitingProviderTurn`, and takes its recovery path of today. ## Verification With nothing from part 3. The Rust checks and the build checks in the first item were run before the last seven commits; these commits change no Rust. The other items were run at the head of this branch (`36d5e5e587`), or at an earlier commit of this branch for a suite whose files the later commits do not change. - Before the last seven commits: `pnpm run typecheck:typescript`, `pnpm run build:typescript` and `node --test test/acpx-sidecar-contract.test.mjs` (18 passed) in `packages/paperclip-runner`; `node scripts/verify-runner-vendor-dependencies.mjs` in `server`; `node --test scripts/__tests__/runner-release-crate-cache.test.mjs`; `cargo fmt --check`, `cargo build`, the 17 `acpx_*` suites (241 passed) and the `acpx` unit tests (102 passed): all passed. - `npx tsc --noEmit -p tsconfig.json` and `npx tsc --noEmit -p tsconfig.test.json` in `packages/paperclip-runner`; `pnpm typecheck` in `server`: all passed. - `src/live/runnerd-acpx-provider-turn.test.ts`, 4 runs with the production code of this head, 26 of 26 passed in each. The Core of these tests follows the production append (`appendNativeSourceEvent`): it stores an event that is out of order, keeps its contiguous cursor below a gap, and reports a duplicate or a conflict for an event that it has. It does not reject a gap in the sequence; production does not. The restart cases, all with the real `paperclip-runnerd`: - **From the checkpoint that the real consumer saved.** The first `executeNativeSession` is fenced and detached as the server does for a restart, and a second one recovers from the last checkpoint that the first one saved. (a) Restart during the wait; the provider-started turn starts after the new controller is attached. (b) Restart while a provider-started turn is in progress. In each: the test asserts the shape of that checkpoint, the run settles with the result of the provider-started turn, each event is appended one time and in order, the turn has one `turn.started` with `origin: "provider"`, and the session closes with no error. - **Without the two checkpoints, each of these cases fails:** the saved checkpoint is the checkpoint of the turn before, and the second controller fails with `turn_binding_mismatch` or with a replay conflict. - **A slow `appendEvent`, with events that arrive behind the stored event** (3 cases, each run 3 times with the fix and 3 times without it, with the same result in each run). R7: the append of the `turn.completed` that waits is slow, and the provider-started turn starts behind it. With the snapshot at the event, the checkpoint is the waiting state at the sequence that Core has, and Core gets the `turn.started` of the turn one time. Without it, the checkpoint names the provider-started turn as active, the transport builds no start, and Core never gets that `turn.started`. R8: the first controller answers the `paperclip_finish` call while the append of the provider `turn.started` is slow. With the snapshot at the event, the checkpoint has no result and the run ends with `native_finalization_missing` (see Risks). Without it, the checkpoint has a result that Core does not have, and recovery stops with "session cannot start another turn". R6: the append of the provider `turn.started` is slow and a delta is queued behind it. With the snapshot at the event, the new controller continues the sequence that Core has. Without it, the only difference is one sequence number that Core never gets. - **The start was acknowledged before the restart** (3 cases: one turn open across the restart; two turns; a turn that waits for the answer to its `paperclip_finish` call). The new driver gets the start of each turn one time before its other events, the finish call is answered exactly one time, and the session closes with no error. - **The turn ran with no controller attached** (2 cases, with and with no result) and **two turns in one outage** (2 cases): the turns arrive in order after the recovery. - **A provider-started turn that is active in the checkpoint** gets no second start, and the next provider-started turn arrives after it. - **The turn already has its result when recovery completes** (3 cases: the turn made its `paperclip_finish` call with no controller attached; the turn waited for the answer to that call at the restart; two turns across the restart). The test asserts the exact list of events that Core gets: each provider-started turn has one start, its usage item, its message item and its terminal, and then `run.result.accepted` and `run.terminal`. `completeRun` is called one time with the turn that has the result. Before the change to the session terminal, the second controller appended only `run.result.accepted` and `run.terminal` in each of these cases. - **The wait checkpoint is not saved, then a restart** (R10). The last checkpoint is the checkpoint of the controller turn, Core has the terminal of that turn, and the start of the provider-started turn is queued. The run settles with the result of the provider-started turn, Core has one `turn.started` for it, and the finish call is answered one time. Without the wait in the driver, recovery stops with `turn_binding_mismatch`. - **An ordinary turn**, with no option. One that waits for the answer to its finish call at a restart: Core gets its result, its terminal and the run terminal one time. One whose checkpoint after `startTurn` is ahead of Core at a restart (R9): the run settles, and Core does not have only the one event that the first controller did not store. These cases pass with and without this pull request. - **No checkpoint with a terminal and no result** is saved by the two controllers in the cases above. - `src/live/provider-turn-tool-order.test.ts` and `src/live/runnerd-codex-transport.test.ts`: 345 passed. The helper tests cover a stored start with removed events after it, a dropped delta, the terminal of the turn before and after the event, a terminal of a different turn after a removed terminal, and a controller start. With no option, with a different agent or provider, and for a turn that the controller started, the notifications of the transport are the same as before this pull request. - `src/control-plane/durable-prp-control-plane.test.ts`: 230 passed. Three new tests use the real commit path: a full window of 4,096 events removes the events after a provider start and the start is found; the window removes the `turn.failed` of a provider turn after a later `turn.failed` with no start, and no start is found; a restored checkpoint that dropped the deltas of the turn, and the start is found. - `src/drivers/codex` and `src/backends/harness-driver-backend.test.ts`: 491 passed. The driver tests cover a provider start that is queued before `recoverSession()` is called, the wait state with one turn in progress at `reconcile()` (and the two cases that it must still refuse), a restored wait with a consumed disposition marker (the provider turn is admitted and `startTurn` is refused), the snapshot at the two events (also after the driver moved on, and for a restart continuation that ends waiting), one later turn in progress, one completed and a second in progress, two completed with a result, and the cases that `reconcile()` must still refuse. The backend tests cover the session terminal and the snapshot as of a sequence. - `src/native-session-runtime.provider-turn.test.ts` and `src/native-session-runtime.test.ts`: 333 passed. Two new cases resume a restored wait with a consumed disposition marker: the provider-started turn arrives and settles the run, or the wait ends at its limit and the run takes the path of today with no new turn. - `server`: `native-session-executor.test.ts`, `native-provider-turn-wait.test.ts` and `native-runner-restart-recovery.integration.test.ts`: 1,743 passed, 21 skipped. - Mutation checks, each made named tests fail: no checkpoint at the start of a wait; no checkpoint at the start of a provider-started turn; the consumer does not pass the sequence (R6, R7 and R8 fail: a hole in the sequence, no `turn.started` in Core, a different failure); the backend ignores the sequence; the driver has no snapshot at the event; no start-first rule; no exclusion of the active turn of the recovered driver; the turn binding only at the first delivery; the contiguous sequence required again; no check of the first terminal after the start; the adoption of later turns put back; no exception in `reconcile()`; no check after the settlement in `reconcile()`; the terminal of the session set again by a turn that ends waiting; no wait of the provider start for `reconcile()`; no exception in `reconcile()` for a session that waits; the pump deferred for a restored wait; the consumed-marker shortcut taken for a snapshot that waits. Not run: the full suite. CI supplies that coverage. ## Risks - **No production effect.** Each change is behind the waiting state, a provider `turn.started`, or the option of the transport. No caller sets the option before part 3. - **An event that the first controller received but Core did not store is not sent again after a restart.** This is the same on `master` and is not changed here. Only the terminal of a turn is built again. If the lost event is the result of a provider-started turn (the first controller answered the `paperclip_finish` call and stopped before Core stored the proposal), the run ends on the path of today for a turn with no result. R8 shows this. R9 shows the same loss for one event of an ordinary turn. - **A second `turn.started` for one provider-started turn can reach Core.** This occurs if the restart comes after Core stored the start and before the checkpoint of that start is saved (the time of one checkpoint write). The last checkpoint then waits, and the transport builds the start again for the new driver. Seen with the real daemon when the checkpoint write is held; not in a committed test. The usage accounting of the server uses the turn id as its key, so there is no second count, but the second start resets the "restored" mark of that turn. The transcript does not read `turn.started`. - **The older checkpoints can also save a cursor that is ahead of Core** (measured for the checkpoint after `startTurn` of an ordinary turn). Production accepts the gap in the sequence that follows, so this is not a failure there. It is on `master` and is not changed here. - **When the terminal of a provider-started turn was removed from the stored events,** the transport builds no start for an event of that turn, and the session stops on that event, as before. This needs a later terminal of the same type with no start of its own (a turn that was lost while it started) and a full window. - **The last checkpoint of a wait that ends with no provider-started turn has no terminal,** as the section above says. The change is only in a run that waits, and no run waits before part 3. - **A wait with a consumed disposition marker has no test with the real daemon.** The state needs two restarts in one run, and the test helper does one. Unit tests of the driver and of the consumer cover it. - **A provider start that waits for `reconcile()`** waits as long as the reads of `reconcile()` take. Each read ends at the command deadline of the Runner (30 seconds by default) or when the transport closes. - **`item.delta` events across a restart are not asserted.** A streamed delta that the first controller received is not sent again. The completed items are asserted. - **The driver keeps a maximum of 8 snapshots at events** and drops each one when the consumer asks for it or for a later one. If the consumer is more than 8 such events behind, the checkpoint uses the current snapshot, as before this change. - **A second provider-started turn that also ends during the same outage** is not tested with the real daemon: the fake gives each terminal the same goal revision, and the Runner then holds the second terminal until a controller is attached. The end of the reconnect time of the Runner is not tested here. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change and the split, decided the designs, reviewed the diffs, and ran a part of the verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as Claude Code subagents with tool use (shell, file edits, local test runs), wrote the change and the tests, reproduced the review findings with the real daemon, and verified this slice alone. ## 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 --- .../runner-core/src/bin/fake-acpx-sidecar.rs | 137 ++++- .../backends/harness-driver-backend.test.ts | 56 ++ .../src/backends/harness-driver-backend.ts | 12 +- .../src/contracts/harness-driver.ts | 1 + .../src/contracts/native-session-backend.ts | 1 + .../durable-prp-control-plane.test.ts | 84 +++ .../codex/codex-app-server-driver-impl.ts | 5 +- ...ex-app-server-driver.provider-turn.test.ts | 348 +++++++++++ .../drivers/codex/codex-harness-session.ts | 31 +- .../codex/codex-session-notifications.ts | 2 + .../src/drivers/codex/codex-session-state.ts | 25 +- .../drivers/codex/codex-session-terminal.ts | 2 + .../src/live/provider-turn-tool-order.test.ts | 61 ++ .../src/live/provider-turn-tool-order.ts | 18 + .../live/runnerd-acpx-provider-turn.test.ts | 577 +++++++++++++++++- .../src/live/runnerd-codex-transport.test.ts | 137 +++++ .../src/live/runnerd-codex-transport.ts | 16 +- ...tive-session-runtime.provider-turn.test.ts | 98 ++- .../src/native-session-runtime.ts | 19 +- 19 files changed, 1586 insertions(+), 44 deletions(-) create mode 100644 packages/paperclip-runner/src/live/provider-turn-tool-order.test.ts diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs index a3232e33050..8bd51438e54 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs @@ -10,6 +10,8 @@ use serde_json::{json, Value}; const PROJECTED_INPUT_PROVIDER_ID: &str = "input / réquest"; static BACKGROUND_TASKS: std::sync::OnceLock> = std::sync::OnceLock::new(); +static PROVIDER_TURNS_STARTED: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); fn background_tasks_mode(snapshot: bool) -> Option { let path = BACKGROUND_TASKS.get()?.as_ref()?; @@ -126,6 +128,7 @@ fn run() -> Result<(), Box> { let mut pending_provider_run: Option = None; let mut provider_rearmable = false; let mut source_pending_completion: Option = None; + let mut open_provider_turn: Option = None; let mut source_goal_revision = 0_u64; let mut runtime_directory: Option = None; // `--cancel-reply lost|late`: the provider stops its prompt, but the reply @@ -274,6 +277,7 @@ fn run() -> Result<(), Box> { next_sequence, &run, &mut source_pending_completion, + &mut open_provider_turn, )?; } } @@ -300,15 +304,31 @@ fn run() -> Result<(), Box> { )?; next_sequence += 1; } - if armed && tokens.iter().any(|token| token == "provider-turn-hold") { + if armed + && tokens.iter().any(|token| { + token == "provider-turn-hold" || token == "provider-turn-after-snapshot" + }) + { continue; } - if let (true, Some(run)) = (armed, pending_provider_run.take()) { + if let Some(delay) = tokens + .iter() + .find_map(|token| token.strip_prefix("provider-turn-delay-ms=")) + .and_then(|value| value.parse::().ok()) + .filter(|_| armed) + { + std::thread::sleep(Duration::from_millis(delay)); + } + let run = pending_provider_run.take().or_else(|| { + (provider_rearmable && chained_provider_turn_remains()).then(|| source_run.clone()) + }); + if let (true, Some(run)) = (armed, run) { next_sequence = write_provider_turn( &mut stdout, next_sequence, &run, &mut source_pending_completion, + &mut open_provider_turn, )?; provider_rearmable = tokens.iter().any(|token| token == "provider-terminal-live"); } else { @@ -338,7 +358,7 @@ fn run() -> Result<(), Box> { ); if command == "session.snapshot" { response["result"] = json!({"identity":session_identity, "runId":source_run, - "turnId":if fault == "active" {json!("unexpected-turn")} else {json!(source_pending_completion)}, + "turnId":if fault == "active" {json!("unexpected-turn")} else {json!(source_pending_completion.as_ref().or(open_provider_turn.as_ref()))}, "pendingToolCount":if fault == "tool" || source_pending_completion.is_some() {1} else {0}, "pendingInputCount":0, "pendingRuntimeRequests":[]}); } @@ -461,6 +481,24 @@ fn run() -> Result<(), Box> { "error":{"code":"session_open_failed","message":"The replacement provider could not open.","retryable":false}}); } write_json(&mut stdout, &response)?; + if command == "session.snapshot" && open_provider_turn.take().is_some() { + next_sequence = finish_provider_turn(&mut stdout, next_sequence, &source_run)?; + } + if command == "session.snapshot" + && provider_turn_tokens() + .iter() + .any(|token| token == "provider-turn-after-snapshot") + { + if let Some(run) = pending_provider_run.take() { + next_sequence = write_provider_turn( + &mut stdout, + next_sequence, + &run, + &mut source_pending_completion, + &mut open_provider_turn, + )?; + } + } if command == "session.open" && args.iter().any(|arg| arg == "--emit-process") { write_json( &mut stdout, @@ -1583,12 +1621,43 @@ fn bootstrap_success( } fn provider_turn_tokens() -> Vec { - BACKGROUND_TASKS + let mut tokens: Vec = BACKGROUND_TASKS .get() .and_then(Option::as_ref) .and_then(|path| std::fs::read_to_string(path).ok()) .map(|modes| modes.split_whitespace().map(str::to_owned).collect()) - .unwrap_or_default() + .unwrap_or_default(); + let index = PROVIDER_TURNS_STARTED + .load(std::sync::atomic::Ordering::SeqCst) + .max(1); + let spec = provider_turn_chain(&tokens).and_then(|chain| chain.into_iter().nth(index - 1)); + if let Some(spec) = spec { + tokens.push(format!("provider-turn-id=provider-{index}")); + tokens.extend( + spec.split('+') + .filter_map(|flag| match flag { + "live" => Some("provider-terminal-live"), + "result" => Some("provider-result"), + "resolved" => Some("provider-result-resolved"), + _ => None, + }) + .map(str::to_owned), + ); + } + tokens +} + +fn provider_turn_chain(tokens: &[String]) -> Option> { + tokens + .iter() + .find_map(|token| token.strip_prefix("provider-turns=")) + .map(|chain| chain.split('/').map(str::to_owned).collect()) +} + +fn chained_provider_turn_remains() -> bool { + provider_turn_chain(&provider_turn_tokens()).is_some_and(|chain| { + PROVIDER_TURNS_STARTED.load(std::sync::atomic::Ordering::SeqCst) < chain.len() + }) } fn offer_provider_turn( @@ -1603,7 +1672,7 @@ fn offer_provider_turn( return Ok(sequence); } if tokens.iter().any(|token| token == "provider-turn-unarmed") { - return write_provider_turn(output, sequence, default_run, pending_finish); + return write_provider_turn(output, sequence, default_run, pending_finish, &mut None); } *pending = Some(default_run.to_owned()); Ok(sequence) @@ -1614,7 +1683,11 @@ fn write_provider_turn( mut sequence: u64, default_run: &str, pending_finish: &mut Option, + open_turn: &mut Option, ) -> io::Result { + if provider_turn_chain(&provider_turn_tokens()).is_some() { + PROVIDER_TURNS_STARTED.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } let tokens = provider_turn_tokens(); if !tokens.iter().any(|token| token == "provider-turn") { return Ok(sequence); @@ -1689,6 +1762,37 @@ fn write_provider_turn( *pending_finish = Some(turn_id); return Ok(sequence + 1); } + if tokens + .iter() + .any(|token| token == "provider-turn-until-snapshot") + { + write_json( + output, + &frame( + sequence, + "runtime.event", + json!({"type":"text_delta","text":"Claude is still working."}), + ), + )?; + *open_turn = Some(turn_id); + return Ok(sequence + 1); + } + if let Some(gap) = tokens + .iter() + .find_map(|token| token.strip_prefix("provider-turn-gap-ms=")) + .and_then(|value| value.parse::().ok()) + { + write_json( + output, + &frame( + sequence, + "runtime.event", + json!({"type":"text_delta","text":"Claude is still working."}), + ), + )?; + sequence += 1; + std::thread::sleep(Duration::from_millis(gap)); + } finish_provider_turn(output, sequence, default_run) } @@ -1737,14 +1841,19 @@ fn finish_provider_turn( } else { 0 }; - write_json( - output, - &frame( - sequence, - "runtime.turn_terminal", - json!({"status":"completed","stopReason":"end_turn","backgroundTasks":{"live":live}}), - ), - )?; + let mut terminal = + json!({"status":"completed","stopReason":"end_turn","backgroundTasks":{"live":live}}); + if tokens + .iter() + .any(|token| token == "provider-goal-at-terminal") + { + terminal["goalAtTerminal"] = json!({"schema":"paperclip.session_goal.snapshot.v1", + "providerRevision":1_000_000,"goal":null,"workingNow":false, + "sessionGoals":{"availability":"unsupported","actions":[],"autonomousUpdates":false, + "persistentAcrossResume":false,"maxObjectiveChars":4000,"tokenBudgetControl":false, + "usageReporting":false}}); + } + write_json(output, &frame(sequence, "runtime.turn_terminal", terminal))?; Ok(sequence + 1) } diff --git a/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts b/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts index ac6562d55d6..c1c968ba15e 100644 --- a/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts +++ b/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts @@ -421,6 +421,32 @@ describe("HarnessDriverBackend", () => { }); }); + it("builds a native snapshot from the driver's boundary snapshot only when asked for that sequence", async () => { + const boundarySnapshot = vi.fn((sourceSeq: number): PersistedHarnessSession | null => sourceSeq !== 7 ? null : { + driverKind: "fake", driverSessionId: "driver-1", providerSessionId: "provider-1", providerIdentity, + activeTurnId: null, semanticResult: null, awaitingProviderTurn: true, lastSourceSequence: 7 }); + class BoundarySession extends FakeHarnessSession { + boundarySnapshot = boundarySnapshot; + override async snapshot(): Promise { + return { ...(await super.snapshot()), activeTurnId: "provider-1", lastSourceSequence: 9 }; + } + } + const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new BoundarySession(); } }); + const session = await backend.openSession({ identity: { + runId: "run-boundary", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1", + } }); + const signal = new AbortController().signal; + await expect(session.snapshot({ signal, sourceSeq: 7 })).resolves.toMatchObject({ + cursor: "7", activeTurnId: null, semanticResult: null, awaitingProviderTurn: true }); + expect(boundarySnapshot).toHaveBeenCalledExactlyOnceWith(7); + const current = await session.snapshot(); + expect(current).toMatchObject({ cursor: "9", activeTurnId: "provider-1" }); + expect(current).not.toHaveProperty("awaitingProviderTurn"); + expect(boundarySnapshot).toHaveBeenCalledOnce(); + await expect(session.snapshot({ signal, sourceSeq: 8 })).resolves.toMatchObject({ cursor: "9", activeTurnId: "provider-1" }); + expect(boundarySnapshot).toHaveBeenLastCalledWith(8); + }); + it("preserves a consumed disposition allowance in native snapshots", async () => { class ConsumedRecoverySession extends FakeHarnessSession { override async snapshot(): Promise { @@ -703,6 +729,36 @@ describe("HarnessDriverBackend", () => { }); }); + async function terminalsAfterEachTurnEnd(turnEnds: Array>) { + class TurnEndsSession extends FakeHarnessSession { + override async *events() { + for (const [index, payload] of turnEnds.entries()) yield prpEvent(index + 1, "turn.completed", payload); + } + } + const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new TurnEndsSession(); } }); + const session = await backend.openSession({ + identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" }, + }); + const terminals: Array = []; + for await (const _event of session.events()) terminals.push((await session.snapshot()).terminal ?? null); + return terminals; + } + + it("leaves the run terminal open when a turn ends waiting for the provider's own next turn", async () => { + await expect(terminalsAfterEachTurnEnd([{ status: "completed", awaitingProviderTurn: true }])).resolves.toEqual([null]); + }); + + it("sets the run terminal when a turn ends without waiting for the provider", async () => { + const [terminal] = await terminalsAfterEachTurnEnd([{ status: "completed" }]); + expect(terminal).toMatchObject({ turnTerminalState: "completed", runTerminalState: "succeeded" }); + }); + + it("sets the run terminal at the first turn end that does not wait for the provider", async () => { + const [waiting, settled] = await terminalsAfterEachTurnEnd([{ status: "completed", awaitingProviderTurn: true }, { status: "completed" }]); + expect(waiting).toBeNull(); + expect(settled).toMatchObject({ turnTerminalState: "completed", runTerminalState: "succeeded" }); + }); + it("reconstructs a missing top-level terminal from a completed semantic turn", async () => { const recoveryDriver: HarnessDriver = { ...driver, diff --git a/packages/paperclip-runner/src/backends/harness-driver-backend.ts b/packages/paperclip-runner/src/backends/harness-driver-backend.ts index b45e0b9bf50..899106d04e5 100644 --- a/packages/paperclip-runner/src/backends/harness-driver-backend.ts +++ b/packages/paperclip-runner/src/backends/harness-driver-backend.ts @@ -10,6 +10,7 @@ import type { NativeSessionBackend, NativeSessionBackendDescriptor, NativeSessionRecoveryOptions, + NativeSessionSnapshotOptions, OpenNativeSessionInput, PersistedNativeSession, } from "../contracts/native-session-backend.js"; @@ -420,10 +421,11 @@ class HarnessNativeSession implements NativeSession { throw this.#protocolIntegrityFailure; } - async #harnessSnapshot(): Promise { + async #harnessSnapshot(sourceSeq?: number): Promise { this.#assertProtocolIntegrity(); try { - const snapshot = await this.#session.snapshot(); + const boundary = sourceSeq === undefined ? null : this.#session.boundarySnapshot?.(sourceSeq) ?? null; + const snapshot = boundary ?? await this.#session.snapshot(); this.#assertProtocolIntegrity(); return snapshot; } catch (error) { @@ -633,7 +635,7 @@ class HarnessNativeSession implements NativeSession { const disposition = snapshot.semanticResult?.result.reportedWorkDisposition ?? "yielded"; - this.#terminal = { + if (event.payload.awaitingProviderTurn !== true) this.#terminal = { schema: "paperclip.prp.terminal.v1", turnTerminalState: event.eventType === "turn.completed" @@ -874,9 +876,9 @@ class HarnessNativeSession implements NativeSession { }; } - async snapshot(): Promise { + async snapshot(options?: NativeSessionSnapshotOptions): Promise { this.#assertProtocolIntegrity(); - const snapshot = await this.#harnessSnapshot(); + const snapshot = await this.#harnessSnapshot(options?.sourceSeq); return { backendKind: "runner", driverKind: snapshot.driverKind, diff --git a/packages/paperclip-runner/src/contracts/harness-driver.ts b/packages/paperclip-runner/src/contracts/harness-driver.ts index 37091f4042d..494fc7da83f 100644 --- a/packages/paperclip-runner/src/contracts/harness-driver.ts +++ b/packages/paperclip-runner/src/contracts/harness-driver.ts @@ -669,6 +669,7 @@ export interface HarnessSession { usage?(): Promise | null>; transcript?(): Promise; snapshot(): Promise; + boundarySnapshot?(sourceSeq: number): PersistedHarnessSession | null; /** Return the confirmed released source, or false when active use was not released. */ release?(): Promise; /** Relinquish controller authority without semantically closing the session. */ diff --git a/packages/paperclip-runner/src/contracts/native-session-backend.ts b/packages/paperclip-runner/src/contracts/native-session-backend.ts index e8ce03c19dc..2973f95d232 100644 --- a/packages/paperclip-runner/src/contracts/native-session-backend.ts +++ b/packages/paperclip-runner/src/contracts/native-session-backend.ts @@ -152,6 +152,7 @@ export interface NativeSessionCancellation { export interface NativeSessionSnapshotOptions { /** Stop provider snapshot work that outlives the execution deadline. */ signal: AbortSignal; + sourceSeq?: number; } /** A dispatched operation may have taken effect, but has no proven result. */ diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts index cd70ff1c0b2..b705e8ee579 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts @@ -25,6 +25,7 @@ import { describe, expect, it, vi } from "vitest"; import { configuredEnvironmentProjection } from "../configured-environment.js"; import { NativeSessionProtocolIntegrityError } from "../contracts/native-session-backend.js"; import { createCapabilityRunnerdCodexTransport, createCapabilityRunnerdProviderEnvironment, waitForRunnerCommand } from "../live/runnerd-codex-transport.js"; +import { providerTurnStartBefore } from "../live/provider-turn-tool-order.js"; import { ACPX_CREDENTIAL_BINDING_ENV, createAcpxSidecarHostEnvironment } from "../drivers/acpx/environment.js"; import { validatePrpEvent } from "../protocol/replay-contract.js"; import { digestPaperclipSemanticContent } from "../semantic-tools/receipts.js"; @@ -637,6 +638,89 @@ it("excludes streamed output from checkpoints even when the live window is full" } }); +function turnEvent(sourceSeq: number, eventType: string, payload: Record, priority = 0): Record { + const envelope = semanticInputEvent(sourceSeq); + Object.assign(envelope.payload as Record, { sourceEventId: `turn-event-${sourceSeq}`, eventType, priority, payload }); + return envelope; +} + +function storedTurnEvent(sourceSeq: number, eventType: string, payload: Record, priority: 0 | 1 | 2 = 0) { + return { sourceSeq, sourceEventId: `turn-event-${sourceSeq}`, eventType, priority, + envelope: turnEvent(sourceSeq, eventType, payload, priority), deliveryCount: 1, logicalEffectCount: 1 as const }; +} + +const providerStart = (turnId: string) => ({ provider: "acpx", providerTurnId: turnId, status: "inProgress", + turn: { id: turnId, status: "inProgress" }, origin: "provider" }); +const failedTurn = (turnId: string) => ({ provider: "acpx", providerTurnId: turnId, status: "failed" }); + +async function commitThroughFullWindow(prefix: ReturnType[], sent: Array<[string, Record]>) { + const root = mkdtempSync(resolve(tmpdir(), "runner-provider-turn-window-")); + const core = new DurablePrpControlPlane({ stateDirectory: root, identity, expectedRunnerVersion, expectedRunnerDigest }); + core.store.state.committedEvents = [...prefix, ...Array.from({ length: 4096 - prefix.length }, (_, index) => + storedTurnEvent(prefix.length + index + 1, "item.delta", { text: "streaming output" }, 2))]; + core.store.state.ackedSourceSeq = 4096; + (core.store as WritableCoreStore).save(); + try { + await core.start(); + const client = (await authenticate(core, core.issueBootstrapTicket()))!; + for (const [index, [eventType, payload]] of sent.entries()) { + sendSecure(client, turnEvent(4097 + index, eventType, payload)); + expect(await receiveSecure(client)).toMatchObject({ kind: "ack", payload: { ackedSourceSeq: 4097 + index } }); + } + client.socket.destroy(); + return core.store.state.committedEvents.map(event => ({ ...event })); + } finally { + await core.stop(); + await core.drainPendingConnectionProcessing(); + rmSync(root, { recursive: true, force: true }); + } +} + +it("finds a provider turn's start across ordinary events the full window removed", async () => { + const window = await commitThroughFullWindow([storedTurnEvent(1, "turn.started", providerStart("provider-a"))], + [["item.completed", { provider: "acpx", itemId: "message-a", kind: "agentMessage", status: "completed", text: "Done." }]]); + expect(window.map(event => event.sourceSeq).slice(0, 3)).toEqual([1, 3, 4]); + expect(providerTurnStartBefore(window, 4097)?.turnId).toBe("provider-a"); +}); + +it("finds no provider turn start once the window removed that turn's terminal for a later startless one", async () => { + const window = await commitThroughFullWindow( + [storedTurnEvent(1, "turn.started", providerStart("provider-a")), storedTurnEvent(2, "turn.failed", failedTurn("provider-a"))], + [["harness.diagnostic", {}], ["turn.failed", failedTurn("controller-b")], ["harness.diagnostic", {}]]); + expect(window.map(event => event.sourceSeq).slice(0, 2)).toEqual([1, 5]); + expect(window.slice(-3).map(event => event.eventType)).toEqual(["harness.diagnostic", "turn.failed", "harness.diagnostic"]); + for (const sourceSeq of [4097, 4098, 4099]) expect(providerTurnStartBefore(window, sourceSeq)).toBeNull(); +}); + +it("finds a provider turn's start in a restored checkpoint that dropped the turn's streamed deltas", async () => { + const root = mkdtempSync(resolve(tmpdir(), "runner-provider-turn-checkpoint-")); + const options = { stateDirectory: resolve(root, "control-plane"), identity, expectedRunnerVersion, expectedRunnerDigest }; + const core = new DurablePrpControlPlane(options); + core.store.state.committedEvents = [storedTurnEvent(1, "turn.started", providerStart("provider-a")), + storedTurnEvent(2, "item.delta", { text: "streaming output" }, 2), storedTurnEvent(3, "item.delta", { text: "streaming output" }, 2), + storedTurnEvent(4, "item.completed", { provider: "acpx", itemId: "message-a", kind: "agentMessage", status: "completed", text: "Done." }, 1)]; + core.store.state.ackedSourceSeq = 4; + (core.store as WritableCoreStore).save(); + const snapshots: DurablePrpCheckpoint[] = []; + core.setCheckpointPersistence(async saved => { snapshots.push(saved); }); + const restoredRoot = mkdtempSync(resolve(tmpdir(), "runner-provider-turn-restored-")); + let restored: DurablePrpControlPlane | undefined; + try { + core.queueCommand("session.snapshot", {}, "provider-turn-checkpoint"); + await core.flushCheckpoint(); + decodeDurablePrpCheckpoint(snapshots.at(-1)!.records).restoreSessionDirectory(restoredRoot); + restored = new DurablePrpControlPlane({ ...options, stateDirectory: resolve(restoredRoot, "control-plane") }); + const window = restored.store.state.committedEvents; + expect(window.map(event => event.sourceSeq)).toEqual([1, 4]); + expect(providerTurnStartBefore(window, 4)?.turnId).toBe("provider-a"); + } finally { + await restored?.stop(); + await core.stop(); + rmSync(root, { recursive: true, force: true }); + rmSync(restoredRoot, { recursive: true, force: true }); + } +}); + it.each(["unsupported", "invalid cursor", "invalid proof"])("does not advance recovery from an unauthenticated cursor: %s", async fault => { const root = mkdtempSync(resolve(tmpdir(), "runner-recovery-cursor-auth-")); const core = new DurablePrpControlPlane({ stateDirectory: root, identity, expectedRunnerVersion, expectedRunnerDigest }); diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts index 83feb7983a0..2f763b1d92e 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts @@ -604,6 +604,8 @@ export class CodexAppServerDriver implements HarnessDriver { } recoveredActiveTurnId = active.length === 1 ? text(active[0]?.id) : recoveredActiveTurnId; } + const awaitingProviderTurn = snapshot.awaitingProviderTurn === true && snapshot.semanticResult == null + && recoveredActiveTurnId === null && (snapshot.terminalTurns?.length ?? 0) > 0; if ( !recoveringAutonomousGoal && !this.#direct() && @@ -639,7 +641,7 @@ export class CodexAppServerDriver implements HarnessDriver { ); } const laterTurns = - lastKnownTerminalIndex < 0 + lastKnownTerminalIndex < 0 || awaitingProviderTurn ? [] : turns.slice(lastKnownTerminalIndex + 1); if (laterTurns.length > 1) { @@ -716,6 +718,7 @@ export class CodexAppServerDriver implements HarnessDriver { let lostAcceptedTurnId: string | null = null; if ( !recoveringAutonomousGoal && + !awaitingProviderTurn && recoveredActiveTurnId === null && !reconcileUncheckpointedDispositionTurn && snapshot.semanticResult == null diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts index ad30df81663..4c6660624ef 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts @@ -11,6 +11,7 @@ import { result, } from "./codex-app-server-driver.test-support.js"; import { RUNNERD_RUN_TERMINAL } from "./codex-driver-values.js"; +import type { HarnessSessionRecoveryResult } from "../../contracts/harness-driver.js"; async function completedFirstTurn(awaiting: boolean) { const transport = new FakeCodexTransport(); @@ -230,3 +231,350 @@ describe("Codex app-server driver with provider-started turns", () => { await session.close({ reason: "fixture complete" }); }); }); + +type StreamEvent = { eventType: string; payload: Record; turnId?: string }; + +async function restartedDuringWait(history: Array>, awaiting = true) { + const first = new FakeCodexTransport(); + const second = new FakeCodexTransport(); + const driver = makeDriver([first, second]); + const original = await driver.openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + await original.startTurn({ message: { role: "user", text: "Start a background install." } }); + first.push("turn/started", { threadId: "thread-1", turn: { id: "turn-1", status: "inProgress" } }); + first.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "completed", items: [] }, + ...(awaiting ? { awaitingProviderTurn: true } : {}) }); + await collectUntilTerminal(original.events()); + const checkpoint = await original.snapshot(); + await original.close({ reason: "controller restarted" }); + second.readResponse = { thread: { id: "thread-1", sessionId: "provider-session-1", cwd: WORKSPACE, + turns: [{ id: "turn-1", status: "completed", items: [], ...(awaiting ? { awaitingProviderTurn: true } : {}) }, ...history] } }; + return { recovery: await driver.recoverSession!(checkpoint), transport: second }; +} + +async function restartedDuringActiveTurn(turns: Array>, beforeRecovery?: (transport: FakeCodexTransport) => void) { + const first = new FakeCodexTransport(); + const second = new FakeCodexTransport(); + const driver = makeDriver([first, second]); + const original = await driver.openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + await original.startTurn({ message: { role: "user", text: "Start a background install." } }); + const checkpoint = await original.snapshot(); + expect(checkpoint.activeTurnId).toBe("turn-1"); + await original.close({ reason: "controller restarted" }); + second.readResponse = { thread: { id: "thread-1", sessionId: "provider-session-1", cwd: WORKSPACE, turns } }; + beforeRecovery?.(second); + return { recovery: await driver.recoverSession!(checkpoint).catch((error: unknown): HarnessSessionRecoveryResult => ({ recovered: false, reason: String(error) })), transport: second }; +} + +const agentMessage = (turnId: string) => ({ id: `msg-${turnId}`, type: "agentMessage", text: `work in ${turnId}` }); + +function releaseProviderTurn(transport: FakeCodexTransport, turnId: string, options: { complete: boolean; awaiting?: boolean; withResult?: boolean }) { + transport.push("turn/started", { threadId: "thread-1", turn: { id: turnId, status: "inProgress" }, origin: "provider" }); + transport.push("item/completed", { threadId: "thread-1", turnId, item: agentMessage(turnId) }); + transport.push("thread/tokenUsage/updated", { threadId: "thread-1", turnId, + tokenUsage: { total: { inputTokens: turnId === "provider-1" ? 100 : 200, outputTokens: 10 } } }); + if (options.withResult) transport.push("paperclip/runResult", { threadId: "thread-1", turnId, result }); + if (options.complete) { + transport.push("turn/completed", { threadId: "thread-1", turn: { id: turnId, status: "completed", items: [] }, + ...(options.awaiting ? { awaitingProviderTurn: true } : {}) }); + } +} + +async function streamUntil(events: AsyncIterator, done: (event: StreamEvent) => boolean) { + const collected: StreamEvent[] = []; + for (;;) { + const next = await events.next(); + if (next.done) return collected; + collected.push(next.value); + if (next.value.eventType === "session.failed" || done(next.value)) return collected; + } +} + +const startedTurns = (events: StreamEvent[]) => events.filter(event => event.eventType === "turn.started").map(event => ({ turnId: event.turnId, origin: event.payload.origin })); +const itemTurns = (events: StreamEvent[]) => events.filter(event => event.eventType === "item.completed" && event.payload.kind === "agentMessage").map(event => event.turnId); +const usageTurns = (events: StreamEvent[]) => events.filter(event => event.payload.kind === "usage").map(event => event.turnId); +const completedTurn = (turnId: string) => (event: StreamEvent) => event.eventType === "turn.completed" && event.turnId === turnId; +const startedTurn = (turnId: string) => (event: StreamEvent) => event.eventType === "turn.started" && event.turnId === turnId; + +describe("Codex app-server driver after a controller restart during a wait for the provider's turn", () => { + it("lets the stream deliver one later provider-started turn that is still in progress", async () => { + const { recovery, transport } = await restartedDuringWait([{ id: "provider-1", status: "inProgress", items: [agentMessage("provider-1")] }]); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + expect(await session.snapshot()).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true, dispositionOnlyRecoveryConsumed: false }); + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + releaseProviderTurn(transport, "provider-1", { complete: true, withResult: true }); + const seen = await streamUntil(events, completedTurn("provider-1")); + expect(seen.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(startedTurns(seen)).toEqual([{ turnId: "provider-1", origin: "provider" }]); + expect(itemTurns(seen)).toEqual(["provider-1"]); + expect(usageTurns(seen)).toEqual(["provider-1"]); + const snapshot = await session.snapshot(); + expect(snapshot.semanticResult).toMatchObject({ result, turnId: "provider-1" }); + expect(snapshot).toMatchObject({ dispositionOnlyRecoveryConsumed: false, dispositionOnlyRecoveryTurnId: null }); + await session.close({ reason: "fixture complete" }); + }); + + it("lets the stream deliver a finished provider-started turn and the next one in progress", async () => { + const { recovery, transport } = await restartedDuringWait([ + { id: "provider-1", status: "completed", items: [agentMessage("provider-1")], awaitingProviderTurn: true }, + { id: "provider-2", status: "inProgress", items: [agentMessage("provider-2")] }, + ]); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + releaseProviderTurn(transport, "provider-1", { complete: true, awaiting: true }); + releaseProviderTurn(transport, "provider-2", { complete: false }); + const seen = await streamUntil(events, event => event.payload.kind === "usage" && event.turnId === "provider-2"); + expect(seen.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(startedTurns(seen)).toEqual([{ turnId: "provider-1", origin: "provider" }, { turnId: "provider-2", origin: "provider" }]); + expect(itemTurns(seen)).toEqual(["provider-1", "provider-2"]); + expect(usageTurns(seen)).toEqual(["provider-1", "provider-2"]); + expect(seen.find(completedTurn("provider-1"))).toMatchObject({ payload: { awaitingProviderTurn: true } }); + expect(await session.snapshot()).toMatchObject({ activeTurnId: "provider-2", dispositionOnlyRecoveryConsumed: false }); + await session.close({ reason: "fixture complete" }); + }); + + it("lets the stream deliver two finished provider-started turns and settles the last one's result", async () => { + const { recovery, transport } = await restartedDuringWait([ + { id: "provider-1", status: "completed", items: [agentMessage("provider-1")], awaitingProviderTurn: true }, + { id: "provider-2", status: "completed", items: [agentMessage("provider-2")] }, + ]); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + releaseProviderTurn(transport, "provider-1", { complete: true, awaiting: true }); + releaseProviderTurn(transport, "provider-2", { complete: true, withResult: true }); + const seen = await streamUntil(events, completedTurn("provider-2")); + expect(seen.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(startedTurns(seen)).toEqual([{ turnId: "provider-1", origin: "provider" }, { turnId: "provider-2", origin: "provider" }]); + expect(itemTurns(seen)).toEqual(["provider-1", "provider-2"]); + expect(usageTurns(seen)).toEqual(["provider-1", "provider-2"]); + expect(seen.find(completedTurn("provider-1"))).toMatchObject({ payload: { awaitingProviderTurn: true } }); + expect(seen.find(completedTurn("provider-2"))!.payload).not.toHaveProperty("awaitingProviderTurn"); + const snapshot = await session.snapshot(); + expect(snapshot.semanticResult).toMatchObject({ result, turnId: "provider-2" }); + expect(snapshot).toMatchObject({ dispositionOnlyRecoveryConsumed: false }); + await session.close({ reason: "fixture complete" }); + }); + + it("still refuses two later turns after a checkpoint that was not waiting", async () => { + const { recovery } = await restartedDuringWait([ + { id: "turn-2", status: "completed", items: [] }, + { id: "turn-3", status: "inProgress", items: [] }, + ], false); + expect(recovery).toEqual({ recovered: false, reason: "provider exposed multiple uncheckpointed disposition recovery turns" }); + }); + + it("settles a persisted active turn the read reports awaited and lets the stream deliver the provider's turn after it", async () => { + const { recovery, transport } = await restartedDuringActiveTurn([ + { id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }, + { id: "provider-1", status: "inProgress", items: [] }, + ]); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + const reconciled = await streamUntil(events, completedTurn("turn-1")); + expect(reconciled.at(-1)).toMatchObject({ eventType: "turn.completed", turnId: "turn-1", payload: { awaitingProviderTurn: true } }); + expect(await session.snapshot()).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true }); + releaseProviderTurn(transport, "provider-1", { complete: true, withResult: true }); + const adopted = await streamUntil(events, completedTurn("provider-1")); + expect(adopted.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(adopted.find(startedTurn("provider-1"))).toMatchObject({ payload: { origin: "provider" } }); + expect((await session.snapshot()).semanticResult).toMatchObject({ result, turnId: "provider-1" }); + await session.close({ reason: "fixture complete" }); + }); + + it("reconciles the persisted turn before admitting a provider start queued before the recovery", async () => { + const closeReasons: unknown[] = []; + const { recovery } = await restartedDuringActiveTurn([ + { id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }, + { id: "provider-1", status: "inProgress", items: [] }, + ], transport => { + const close = transport.close.bind(transport); + transport.close = async (reason?: string) => { closeReasons.push(reason); await close(); }; + releaseProviderTurn(transport, "provider-1", { complete: true, withResult: true }); + }); + expect(closeReasons).toEqual([]); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + const seen = await streamUntil(events, completedTurn("provider-1")); + expect(seen.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(seen.find(completedTurn("turn-1"))).toMatchObject({ payload: { awaitingProviderTurn: true } }); + expect(seen.findIndex(completedTurn("turn-1"))).toBeLessThan(seen.findIndex(startedTurn("provider-1"))); + expect(startedTurns(seen)).toEqual([{ turnId: "provider-1", origin: "provider" }]); + expect(itemTurns(seen)).toEqual(["provider-1"]); + expect((await session.snapshot()).semanticResult).toMatchObject({ result, turnId: "provider-1" }); + await session.close({ reason: "fixture complete" }); + }); + + it("accepts the provider's turn in progress when the stream already settled the persisted turn into a wait before the reconciliation judged it", async () => { + const { recovery, transport } = await restartedDuringActiveTurn([ + { id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }, + { id: "provider-1", status: "inProgress", items: [] }, + ], second => second.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "completed", items: [] }, awaitingProviderTurn: true })); + expect(recovery.reason).toBeUndefined(); + const session = recovery.session!; + expect(await session.snapshot()).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true }); + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + releaseProviderTurn(transport, "provider-1", { complete: true, withResult: true }); + const seen = await streamUntil(events, completedTurn("provider-1")); + expect(seen.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(seen.filter(completedTurn("turn-1"))).toHaveLength(1); + expect(seen.find(completedTurn("turn-1"))).toMatchObject({ payload: { awaitingProviderTurn: true } }); + expect(startedTurns(seen)).toEqual([{ turnId: "provider-1", origin: "provider" }]); + expect((await session.snapshot()).semanticResult).toMatchObject({ result, turnId: "provider-1" }); + await session.close({ reason: "fixture complete" }); + }); + + it("admits at once a provider start that arrives after the stream settled the persisted turn into a wait, while the reconciliation is still reading", async () => { + const { recovery, transport } = await restartedDuringActiveTurn([ + { id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }, + { id: "provider-1", status: "inProgress", items: [] }, + ], second => { + second.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "completed", items: [] }, awaitingProviderTurn: true }); + second.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + }); + expect(recovery.reason).toBeUndefined(); + const session = recovery.session!; + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + const seen = await streamUntil(events, event => event.eventType === "session.reconciled"); + expect(seen.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(startedTurns(seen)).toEqual([{ turnId: "provider-1", origin: "provider" }]); + expect(seen.at(-1)).toMatchObject({ eventType: "session.reconciled", payload: { activeTurnId: "provider-1" } }); + transport.push("paperclip/runResult", { threadId: "thread-1", turnId: "provider-1", result }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "provider-1", status: "completed", items: [] } }); + await streamUntil(events, completedTurn("provider-1")); + expect((await session.snapshot()).semanticResult).toMatchObject({ result, turnId: "provider-1" }); + await session.close({ reason: "fixture complete" }); + }); + + it.each([ + ["two turns are in progress", [ + { id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }, + { id: "provider-1", status: "inProgress", items: [] }, { id: "provider-2", status: "inProgress", items: [] }]], + ["the turn in progress is listed before the settled turn", [ + { id: "provider-1", status: "inProgress", items: [] }, { id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }]], + ])("still refuses another active turn after the stream settled the persisted turn into a wait when %s", async (_case, turns) => { + const { recovery } = await restartedDuringActiveTurn(turns, + second => second.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "completed", items: [] }, awaitingProviderTurn: true })); + expect(recovery).toMatchObject({ recovered: false, reason: expect.stringContaining("thread/read exposed active turn provider-1 instead of persisted active turn none") }); + }); + + it.each([ + ["the persisted turn finished without the wait marker", [ + { id: "turn-1", status: "completed", items: [] }, { id: "provider-1", status: "inProgress", items: [] }]], + ["the persisted turn is still in progress", [ + { id: "turn-1", status: "inProgress", items: [] }, { id: "provider-1", status: "inProgress", items: [] }]], + ["the other active turn is listed before the persisted turn", [ + { id: "provider-1", status: "inProgress", items: [] }, { id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }]], + ["the reconciled persisted turn settles a result", [ + { id: "turn-1", status: "completed", awaitingProviderTurn: true, + items: [{ id: "result-1", type: "agentMessage", text: JSON.stringify(result) }] }, + { id: "provider-1", status: "inProgress", items: [] }]], + ])("still refuses another active turn when %s", async (_case, turns) => { + const { recovery } = await restartedDuringActiveTurn(turns); + expect(recovery).toMatchObject({ recovered: false, reason: expect.stringContaining("thread/read exposed active turn provider-1 instead of persisted active turn turn-1") }); + }); +}); + +describe("Codex app-server driver after a restart during a wait whose disposition marker is consumed", () => { + it("keeps reading notifications, admits the provider's own turn and still refuses a controller turn", async () => { + const first = new FakeCodexTransport(); + const second = new FakeCodexTransport(); + const driver = makeDriver([first, second]); + const original = await driver.openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + await original.startTurn({ message: { role: "user", text: "Start a background install." } }); + first.push("turn/started", { threadId: "thread-1", turn: { id: "turn-1", status: "inProgress" } }); + first.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "completed", items: [] }, awaitingProviderTurn: true }); + await collectUntilTerminal(original.events()); + const checkpoint = { ...await original.snapshot(), dispositionOnlyRecoveryConsumed: true, dispositionOnlyRecoveryTurnId: "turn-1" }; + expect(checkpoint).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true, semanticResult: null }); + await original.close({ reason: "controller restarted" }); + second.readResponse = { thread: { id: "thread-1", sessionId: "provider-session-1", cwd: WORKSPACE, + turns: [{ id: "turn-1", status: "completed", items: [], awaitingProviderTurn: true }] } }; + const recovery = await driver.recoverSession!(checkpoint); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + expect(await session.snapshot()).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true, dispositionOnlyRecoveryConsumed: true }); + await expect(session.startTurn({ message: { role: "user", text: "Report the disposition." } })).rejects.toThrow("session cannot start another turn"); + expect(second.calls.filter(call => call.method === "turn/start")).toEqual([]); + const events = session.events()[Symbol.asyncIterator]() as AsyncIterator; + releaseProviderTurn(second, "provider-1", { complete: true, withResult: true }); + const seen = await streamUntil(events, completedTurn("provider-1")); + expect(seen.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(startedTurns(seen)).toEqual([{ turnId: "provider-1", origin: "provider" }]); + expect(itemTurns(seen)).toEqual(["provider-1"]); + expect((await session.snapshot()).semanticResult).toMatchObject({ result, turnId: "provider-1" }); + await session.close({ reason: "fixture complete" }); + }); +}); + +describe("Codex app-server driver boundary snapshots for provider-started turns", () => { + const sourceSeq = (value: unknown) => (value as { sourceSeq: number }).sourceSeq; + + it("keeps the state as of the awaiting terminal and of the provider start after the driver moved on", async () => { + const { transport, session, events, first } = await completedFirstTurn(true); + const terminalSeq = sourceSeq(first.at(-1)); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + transport.push("paperclip/runResult", { threadId: "thread-1", turnId: "provider-1", result }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "provider-1", status: "completed", items: [] } }); + const second = await nextUntil(events, eventType => eventType === "turn.completed"); + const startSeq = sourceSeq(second.find(value => value.eventType === "turn.started")); + const current = await session.snapshot(); + expect(current).toMatchObject({ activeTurnId: null, semanticResult: { turnId: "provider-1" } }); + expect(current.lastSourceSequence).toBeGreaterThan(startSeq); + expect(session.boundarySnapshot!(terminalSeq - 1)).toBeNull(); + expect(session.boundarySnapshot!(terminalSeq)).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true, semanticResult: null, lastSourceSequence: terminalSeq }); + expect(session.boundarySnapshot!(terminalSeq)).toBeNull(); + const atStart = session.boundarySnapshot!(startSeq); + expect(atStart).toMatchObject({ activeTurnId: "provider-1", semanticResult: null, lastSourceSequence: startSeq }); + expect(atStart).not.toHaveProperty("awaitingProviderTurn"); + expect(session.boundarySnapshot!(startSeq)).toBeNull(); + await session.close({ reason: "fixture complete" }); + }); + + it("drops an earlier boundary once a later one is asked for", async () => { + const { transport, session, events, first } = await completedFirstTurn(true); + const terminalSeq = sourceSeq(first.at(-1)); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + const started = await nextUntil(events, eventType => eventType === "turn.started"); + expect(session.boundarySnapshot!(sourceSeq(started.at(-1)))).toMatchObject({ activeTurnId: "provider-1" }); + expect(session.boundarySnapshot!(terminalSeq)).toBeNull(); + await session.close({ reason: "fixture complete" }); + }); + + it("captures no boundary for a terminal that does not await", async () => { + const { session, first } = await completedFirstTurn(false); + expect(session.boundarySnapshot!(sourceSeq(first.at(-1)))).toBeNull(); + await session.close({ reason: "fixture complete" }); + }); + + it("keeps the disposition request owed in the boundary of a restart continuation that ends awaiting", async () => { + const transport = new FakeCodexTransport(); + const session = await makeDriver([transport]).openSession({ + runId: "run-awaiting-continuation", normalizedSessionId: "session-awaiting-continuation", workingDirectory: WORKSPACE, + }); + await session.startTurn({ message: { role: "user", text: "Finish the request." } }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "failed", + error: { code: "provider_turn_lost_on_restore", recoverable: true }, items: [] } }); + await collectUntilTerminal(session.events()); + transport.turnStartResponse = Promise.resolve({ turn: { id: "turn-2", status: "inProgress", items: [] } }); + await expect(session.startTurn({ message: { role: "user", text: "Continue." }, continuation: true })) + .resolves.toMatchObject({ borrowedDispositionMarker: true }); + expect(await session.snapshot()).toMatchObject({ dispositionOnlyRecoveryConsumed: true, dispositionOnlyRecoveryTurnId: "turn-2" }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-2", status: "completed", items: [] }, awaitingProviderTurn: true }); + const continuation = await collectUntilTerminal(session.events()); + const terminal = continuation.at(-1)!; + expect(terminal).toMatchObject({ eventType: "turn.completed", turnId: "turn-2", payload: { awaitingProviderTurn: true } }); + expect(session.boundarySnapshot!(terminal.sourceSeq)).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true, + dispositionOnlyRecoveryConsumed: false, dispositionOnlyRecoveryTurnId: null, lastSourceSequence: terminal.sourceSeq }); + await session.close({ reason: "fixture complete" }); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts index ac4cd9d581e..97f64423f94 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts @@ -83,7 +83,7 @@ export class CodexHarnessSession "runtime_request_recovery_failed", error instanceof Error ? error.message : String(error), )); } - if (this.terminal) { + if (this.terminal && !this.awaitingProviderTurn) { this.#deferredNotificationPump = true; this.eventQueue.close(); } else { @@ -760,7 +760,13 @@ export class CodexHarnessSession } } - async reconcile(): Promise> { + reconcile(): Promise> { + const reconciled = this.#reconcile(); + this.recoveryReconciled = reconciled.then(() => undefined, () => undefined); + return reconciled; + } + + async #reconcile(): Promise> { this.assertProtocolIntegrity(); this.requireCapability("reconciliation"); const snapshot = await this.read(); @@ -816,11 +822,17 @@ export class CodexHarnessSession const unexpectedActive = activeTurns.find( (turn) => text(turn.id) !== expectedTurnId, ); - if (unexpectedActive !== undefined) { - throw new HarnessReconciliationError( - `thread/read exposed active turn ${text(unexpectedActive.id)} instead of persisted active turn ${expectedTurnId ?? "none"}`, - ); - } + const expectedIndex = turns.findIndex((turn) => text(turn.id) === expectedTurnId); + const awaitedProviderTurn = unexpectedActive !== undefined && activeTurns.length === 1 && expectedIndex >= 0 + && turns.indexOf(unexpectedActive) > expectedIndex && text(turns[expectedIndex]!.status) === "completed" + && turns[expectedIndex]!.awaitingProviderTurn === true; + const unexpectedActiveTurn = () => new HarnessReconciliationError( + `thread/read exposed active turn ${text(unexpectedActive?.id)} instead of persisted active turn ${expectedTurnId ?? "none"}`, + ); + const lastTerminalIndex = turns.findLastIndex((turn) => this.terminalTurns.has(text(turn.id))); + const awaitedWhileWaiting = unexpectedActive !== undefined && activeTurns.length === 1 && expectedTurnId === null + && this.awaitingProviderTurn && lastTerminalIndex >= 0 && turns.indexOf(unexpectedActive) > lastTerminalIndex; + if (unexpectedActive !== undefined && !awaitedProviderTurn && !awaitedWhileWaiting) throw unexpectedActiveTurn(); let reconciledTerminalTurnId: string | null = null; if (expectedTurnId !== null) { @@ -857,6 +869,7 @@ export class CodexHarnessSession } } } + if (awaitedProviderTurn && !this.awaitingProviderTurn) throw unexpectedActiveTurn(); for (const [turnId, fingerprint] of this.terminalTurns) { const reported = turns.find((turn) => text(turn.id) === turnId); @@ -899,6 +912,10 @@ export class CodexHarnessSession async snapshot(): Promise { this.assertProtocolIntegrity(); + return this.persistedSnapshot(); + } + + protected persistedSnapshot(): PersistedHarnessSession { return { driverKind: this.driverKind, workingDirectory: this.opened.context.workingDirectory, diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts index e33481395e9..f1ca06bc1c4 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts @@ -543,6 +543,7 @@ async function mapNotificationBody(state: CodexSessionState, notification: Codex return; } if (notification.method === "turn/started") { + if (params.origin === "provider" && !state.awaitingProviderTurn) await state.recoveryReconciled; // A start replayed for an earlier generation's turn (for example, one // the runner recorded after the previous controller detached and then // lost on restore) is history, never a start of this session's turn. A @@ -590,6 +591,7 @@ async function mapNotificationBody(state: CodexSessionState, notification: Codex { status: text(turn.status, "inProgress"), ...(providerStartedTurn ? { origin: "provider" } : {}) }, { turnId }, ); + if (providerStartedTurn) state.captureBoundary(state.sourceSequence); return; } if (notification.method === "turn/completed") { diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts index 3a7ca9270db..8dc7c9ae091 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts @@ -7,6 +7,7 @@ import type { HarnessThreadGoal, HarnessThreadLineageEntry, PersistedHarnessSemanticResult, + PersistedHarnessSession, PersistedHarnessTurnTerminal, } from "../../contracts/harness-driver.js"; import { @@ -91,7 +92,9 @@ class AsyncQueue implements AsyncIterable { } } -export class CodexSessionState { +const MAX_BOUNDARY_SNAPSHOTS = 8; + +export abstract class CodexSessionState { readonly transport: CodexAppServerTransport; runId: string; readonly normalizedSessionId: string; @@ -145,6 +148,7 @@ export class CodexSessionState { * the turn/start response arrives. */ turnStartSettled: Promise = Promise.resolve(); + recoveryReconciled: Promise = Promise.resolve(); protocolFailed = false; protocolFailureCode: string | null = null; protocolFailureMessage: string | null = null; @@ -578,6 +582,25 @@ export class CodexSessionState { }); } + protected abstract persistedSnapshot(): PersistedHarnessSession; + + readonly #boundarySnapshots = new Map(); + + captureBoundary(sourceSeq: number): void { + this.#boundarySnapshots.set(sourceSeq, structuredClone({ ...this.persistedSnapshot(), lastSourceSequence: sourceSeq })); + for (const seq of this.#boundarySnapshots.keys()) { + if (this.#boundarySnapshots.size <= MAX_BOUNDARY_SNAPSHOTS) break; + this.#boundarySnapshots.delete(seq); + } + } + + boundarySnapshot(sourceSeq: number): PersistedHarnessSession | null { + this.assertProtocolIntegrity(); + const snapshot = this.#boundarySnapshots.get(sourceSeq); + for (const seq of [...this.#boundarySnapshots.keys()]) if (seq <= sourceSeq) this.#boundarySnapshots.delete(seq); + return snapshot === undefined ? null : structuredClone(snapshot); + } + emitGoalCapabilities(): void { this.emitV2("session.capabilities.updated", { sessionGoals: diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts index 736c0166349..01feb00692c 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts @@ -225,6 +225,7 @@ export function mapTerminalTurn( payload.error = { ...record(payload.error), providerFailure }; } state.emit(eventType, payload, { turnId }); + const terminalSourceSeq = state.sourceSequence; finalize(state, status); if (status === "failed" && isNativeRestartInterruption(turn.error) && state.result === null && (!state.dispositionOnlyRecoveryConsumed || state.dispositionOnlyRecoveryTurnId === turnId)) { @@ -252,6 +253,7 @@ export function mapTerminalTurn( state.terminal = false; state.dispositionOnlyRecoveryAvailable = true; } + if (state.awaitingProviderTurn) state.captureBoundary(terminalSourceSeq); } function replayFingerprint(state: CodexSessionState, value: unknown): string { diff --git a/packages/paperclip-runner/src/live/provider-turn-tool-order.test.ts b/packages/paperclip-runner/src/live/provider-turn-tool-order.test.ts new file mode 100644 index 00000000000..40bcca677b0 --- /dev/null +++ b/packages/paperclip-runner/src/live/provider-turn-tool-order.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; +import { providerTurnStartBefore } from "./provider-turn-tool-order.js"; + +type Stored = [number, string, Record?]; + +const start = (turnId: string, origin: string | null = "provider") => + ({ provider: "acpx", providerTurnId: turnId, status: "inProgress", turn: { id: turnId, status: "inProgress" }, ...(origin ? { origin } : {}) }); +const terminal = (turnId: string | null) => ({ provider: "acpx", providerTurnId: turnId, status: "failed" }); +const window = (stored: Stored[]) => stored.map(([sourceSeq, eventType, payload = {}]) => + ({ sourceSeq, eventType, envelope: { runId: "run-1", turnId: "turn-1", payload: { eventType, turnId: "turn-1", payload } } })); +const owner = (stored: Stored[], sourceSeq: number) => providerTurnStartBefore(window(stored), sourceSeq)?.turnId ?? null; + +describe("providerTurnStartBefore", () => { + it("returns the stored start when the window removed ordinary events after it", () => { + expect(owner([[10, "turn.started", start("a")], [40, "item.completed"], [41, "item.completed"]], 41)).toBe("a"); + }); + + it("returns the stored start across a dropped item delta", () => { + expect(owner([[10, "turn.started", start("a")], [11, "item.started"], [13, "item.completed"]], 13)).toBe("a"); + }); + + it("returns the start with its payload in the contiguous case", () => { + expect(providerTurnStartBefore(window([[10, "turn.started", start("a")], [11, "item.started"]]), 12)) + .toEqual({ turnId: "a", payload: start("a") }); + }); + + it("returns nothing for an event after the turn's own terminal", () => { + expect(owner([[10, "turn.started", start("a")], [20, "turn.completed", terminal("a")], [21, "item.completed"]], 21)).toBeNull(); + }); + + it("returns the start for an event before the turn's own terminal", () => { + expect(owner([[10, "turn.started", start("a")], [15, "item.completed"], [20, "turn.completed", terminal("a")]], 15)).toBe("a"); + }); + + it("returns the start for the turn's own terminal", () => { + expect(owner([[10, "turn.started", start("a")], [20, "turn.interrupted", terminal("a")]], 20)).toBe("a"); + }); + + it("returns nothing when the turn's terminal was removed and a startless terminal of another turn follows", () => { + const stored: Stored[] = [[10, "turn.started", start("a")], [30, "harness.diagnostic"], [31, "session.resumed"], [32, "turn.failed", terminal("controller-b")], [33, "item.completed"]]; + expect(owner(stored, 30)).toBeNull(); + expect(owner(stored, 32)).toBeNull(); + expect(owner(stored, 33)).toBeNull(); + }); + + it("returns nothing when the first terminal after the start names no turn", () => { + expect(owner([[10, "turn.started", start("a")], [30, "item.completed"], [32, "turn.failed", terminal(null)]], 30)).toBeNull(); + }); + + it("returns the start when its own terminal comes before a later foreign terminal", () => { + expect(owner([[10, "turn.started", start("a")], [15, "item.completed"], [20, "turn.completed", terminal("a")], [25, "turn.failed", terminal("controller-b")]], 15)).toBe("a"); + }); + + it("returns nothing when the nearest start is a controller start", () => { + expect(owner([[10, "turn.started", start("a")], [20, "turn.completed", terminal("a")], [30, "turn.started", start("b", null)], [31, "item.completed"]], 31)).toBeNull(); + }); + + it("returns nothing when no start is stored", () => { + expect(owner([[30, "item.completed"], [31, "item.completed"]], 31)).toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/live/provider-turn-tool-order.ts b/packages/paperclip-runner/src/live/provider-turn-tool-order.ts index 95a93446d98..9ef6cabb64d 100644 --- a/packages/paperclip-runner/src/live/provider-turn-tool-order.ts +++ b/packages/paperclip-runner/src/live/provider-turn-tool-order.ts @@ -14,3 +14,21 @@ export function providerTurnToolCallSourceSeq( } return null; } + +const eventPayload = (event: Pick) => record(record(event.envelope.payload).payload); + +const terminalEventTypes = new Set(["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]); + +export function providerTurnStartBefore( + events: readonly Pick[], + sourceSeq: number, +): { turnId: string; payload: Record } | null { + const startAt = events.findLastIndex(event => event.sourceSeq < sourceSeq && event.eventType === "turn.started"); + if (startAt < 0) return null; + const payload = eventPayload(events[startAt]!); + const turnId = payload.providerTurnId; + if (payload.origin !== "provider" || typeof turnId !== "string" || turnId.length === 0) return null; + const terminal = events.slice(startAt + 1).find(event => terminalEventTypes.has(event.eventType)); + if (terminal && (terminal.sourceSeq < sourceSeq || eventPayload(terminal).providerTurnId !== turnId)) return null; + return { turnId, payload }; +} diff --git a/packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts b/packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts index d1db45947a4..e7587253d45 100644 --- a/packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-acpx-provider-turn.test.ts @@ -8,12 +8,13 @@ import { join, resolve } from "node:path"; import { expect, it, vi } from "vitest"; import type { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js"; import { QUALIFIED_ACPX_PROFILES, resolveQualifiedAcpxProfile } from "../drivers/acpx/qualified-profiles.js"; -import { createCapabilityRunnerdCodexTransport, readRunnerdArtifactBinding } from "./runnerd-codex-transport.js"; -import { createRunnerProviderLaunch, runnerLaunchRequirementsDigest } from "./runner-provider-launch.js"; +import { createCapabilityRunnerdCodexTransport, readRunnerdArtifactBinding, type CapabilityRunnerdCodexTransport, type CapabilityRunnerdCodexTransportOptions } from "./runnerd-codex-transport.js"; +import { createRunnerProviderLaunch, runnerLaunchRequirementsDigest, type RunnerProviderLaunchRequirements } from "./runner-provider-launch.js"; import { defaultCapabilityRunnerdBinary } from "../../test/support/runnerd-transport.js"; -import type { PrpEvent } from "../protocol/replay-contract.js"; +import type { PrpEvent, PrpStructuredRunResult } from "../protocol/replay-contract.js"; import { createNativeSessionBackend } from "../backends/native-backend-factory.js"; import type { NativeExecutionInput } from "../contracts/native-execution.js"; +import type { NativeSession, PersistedNativeSession } from "../contracts/native-session-backend.js"; import { executeNativeSession } from "../native-session-runtime.js"; const sha = (value: string | Buffer) => `sha256:${createHash("sha256").update(value).digest("hex")}`; @@ -38,6 +39,17 @@ let scenario = 0; const durableState = async (root: string) => (await Promise.all(["control-plane/control-plane-state.json", "runner/runner-state.json"] .map(path => readFile(join(root, path), "utf8").catch(() => "")))).join("\n"); +function storeSourceEvent(committed: PrpEvent[], value: PrpEvent) { + const source = () => committed.filter(event => event.sourceInstanceId === value.sourceInstanceId); + const existing = source().find(event => event.sourceEventId === value.sourceEventId || event.sourceSeq === value.sourceSeq); + if (existing && (existing.sourceEventId !== value.sourceEventId || JSON.stringify(existing.payload) !== JSON.stringify(value.payload))) throw new Error("source_event_replay_conflict"); + if (!existing) committed.push(structuredClone(value)); + const stored = new Set(source().map(event => event.sourceSeq)); + let highestContiguousSourceSeq = 0; + while (stored.has(highestContiguousSourceSeq + 1)) highestContiguousSourceSeq += 1; + return { cursor: value.sourceSeq, highestContiguousSourceSeq, disposition: existing ? "duplicate" as const : "committed" as const }; +} + async function runProviderTurnScenario(tokens: string, options: { agent?: "claude" | "codex"; capMs?: number; providerStartedTurns?: boolean } = {}) { const agent = options.agent ?? "claude"; const providerStartedTurns = options.providerStartedTurns ?? agent === "claude"; @@ -103,7 +115,7 @@ async function runProviderTurnScenario(tokens: string, options: { agent?: "claud } }); const calls = async () => (await readFile(journal, "utf8").catch(() => "")).trim().split("\n").filter(Boolean) .flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } }); - const appended: PrpEvent[] = []; + const appended: PrpEvent[] = [], committed: PrpEvent[] = []; const completeRun = vi.fn(async () => undefined); const resolveMissingResult = vi.fn(async () => null); try { @@ -116,7 +128,7 @@ async function runProviderTurnScenario(tokens: string, options: { agent?: "claud async openRun() {}, async checkpointSession() {}, async appendEvent(value: PrpEvent) { appended.push(structuredClone(value)); - return { cursor: value.sourceSeq, highestContiguousSourceSeq: value.sourceSeq, disposition: "committed" }; + return storeSourceEvent(committed, value); }, async replayEvents() { return { events: [], highestContiguousSourceSeq: 0 }; }, completeRun, @@ -237,3 +249,558 @@ it.skipIf(process.platform === "win32")("never opts a non-Claude ACPX agent in", expect(sidecarCommands(run.journalled)).not.toContain("session.provider_turn"); expectCleanClose(run); }, 60_000); + +async function restartFixture(tokens: string, sidecarArgs = "", optIn = true) { + const n = ++scenario; + const root = await realpath(await mkdtemp(join(tmpdir(), "runner-acpx-provider-turn-restart-"))); + const journal = join(root, "calls"), fault = join(root, "fault"), wrapper = join(root, "sidecar"), script = join(root, "sidecar-entry"); + const background = join(root, "background"); + const binary = defaultCapabilityRunnerdBinary(), sidecar = resolve(import.meta.dirname, "../../runner/target/debug/fake-acpx-sidecar"); + await mkdir(join(root, "acpx"), { mode: 0o700 }); await mkdir(join(root, "diagnostics"), { mode: 0o700 }); + await writeFile(script, "qualified fixture entry"); + await writeFile(background, tokens); + await writeFile(wrapper, `#!/bin/sh\nexec ${quote(sidecar)} --mode source-reconcile --profile-digest ${quote(QUALIFIED_ACPX_PROFILES.claude.commandDigest)} --journal ${quote(journal)} --source-fault ${quote(fault)} --background-tasks ${quote(background)} --spawn-owned-child${sidecarArgs}\n`, { mode: 0o700 }); + let authority: DurablePrpControlPlane | null = null, registrations = 0; + const diagnostics: string[] = []; + const server = createServer(); + server.on("upgrade", (request, socket, head) => authority ? authority.handleUpgrade(request, socket, "/runner", head) : socket.destroy()); + await new Promise(done => server.listen(0, "127.0.0.1", done)); + const address = server.address(); if (!address || typeof address === "string") throw new Error("missing fixture listener"); + const identity = { runnerInstanceId: `runner-provider-turn-restart-${n}`, environmentLeaseId: `lease-provider-turn-restart-${n}`, runId: `run-provider-turn-restart-${n}`, + normalizedSessionId: `session-provider-turn-restart-${n}`, turnId: `turn-provider-turn-restart-${n}`, itemId: `item-provider-turn-restart-${n}` }; + const nativeIdentity = { companyId: `company-restart-${n}`, agentId: "agent", issueId: "issue", runId: identity.runId, sessionId: identity.normalizedSessionId }; + const execution: NativeExecutionInput = { schema: "paperclip.native-execution-input.v1", + binding: { companyId: nativeIdentity.companyId, agentId: "agent", issueId: "issue", runId: identity.runId, executionWorkspaceId: "workspace" }, + task: { identifier: "TASK-1", title: "Install and test", description: null, prompt: "Install and test", workMode: "standard" }, + workspace: { cwd: root, repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: identity.normalizedSessionId, driverKind: "acpx_runtime", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + provider: { kind: "acpx", agent: "claude", model: "explicit-source-model", permissionPolicy: "interactive", profile: qualifiedProfile("claude") }, + completionContract: { id: "contract", sha256: sha("contract"), schemaVersion: "paperclip.completion-contract.v1", + contract: { revision: "acpx-provider-turns-v1", objective: "Install and test", criteria: [{ id: "objective", requirement: "Install and test" }] } }, + interactionResponses: [], credentialBindings: [] }; + const runnerPids = new Set(); + let requirements: RunnerProviderLaunchRequirements | undefined; + const transportOptions: CapabilityRunnerdCodexTransportOptions = { + provider: "acpx", acpxAgent: "claude", ...(optIn ? { providerStartedTurns: true } : {}), onDiagnostic: message => diagnostics.push(message), runnerBinary: binary, stateDirectory: root, prpIdentity: identity, + runnerArtifact: readRunnerdArtifactBinding(binary), codexSourceRecoveryVersion: 1, acpxSourceRecoveryVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, runnerProcessReconnectGraceMs: null, runnerReconnectGraceMs: 10_000, + controlPlaneRegistration: async next => { + const generation = ++registrations; authority = next; + return { connectUrl: `ws://127.0.0.1:${address.port}/runner`, release: () => { if (generation === registrations) authority = null; } }; + }, + prepareLaunch: async launch => { + requirements ??= structuredClone(launch); + return { configurationId: `initial-${launch.identity.runId}`, requirementsDigest: runnerLaunchRequirementsDigest(launch), + provider: createRunnerProviderLaunch(launch, { options: {}, root, cwd: root, codexHome: root, codexCommand: "", providerNodeCommand: wrapper, opencodeProxyPath: "", acpxSidecarPath: script }) }; + }, + runnerProcessLauncher: spec => { + const stderr = openSync(join(root, "native.stderr"), "a", 0o600); + const child = spawn(binary, [...spec.args, "--acpx-launch-authority-digest", sha("fixture authority"), + "--acpx-sidecar-command", wrapper, "--acpx-sidecar-command-sha256", sha(execFileSync("cat", [wrapper])), + "--acpx-sidecar-script", script, "--acpx-sidecar-script-sha256", sha("qualified fixture entry")], + { env: { PATH: process.env.PATH, HOME: root, ...spec.environment }, stdio: ["ignore", "ignore", stderr], detached: true }); + closeSync(stderr); + if (child.pid) runnerPids.add(child.pid); + return { child, completion: new Promise((done, reject) => { child.once("error", reject); child.once("exit", (code, signal) => done({ code, signal, stdout: "", stderr: "" })); }) }; + }, + }; + const calls = async () => (await readFile(journal, "utf8").catch(() => "")).trim().split("\n").filter(Boolean) + .flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } }); + const backend = (transport: CapabilityRunnerdCodexTransport) => createNativeSessionBackend(execution, { codexTransportFactory: () => transport.transport, + runnerInstanceId: identity.runnerInstanceId, environment: { PAPERCLIP_WORKSPACE_CWD: root }, dynamicTools: [] }); + const first = (holdFirstToolCall: boolean | undefined, onHeld: () => void = () => undefined) => { + const transport = createCapabilityRunnerdCodexTransport(transportOptions); + const install = transport.transport.setServerRequestHandler.bind(transport.transport); + if (holdFirstToolCall) transport.transport.setServerRequestHandler = handler => install(request => { + if (request.method !== "item/tool/call") return handler(request); + onHeld(); + return new Promise(() => undefined); + }); + return transport; + }; + const restarted = (first: CapabilityRunnerdCodexTransport, checkpoint: PersistedNativeSession, extra: Partial = {}) => { + const pid = first.evidence().runnerPid!, startedAt = first.transport.processInfo!().startedAt; + return () => { + const second = createCapabilityRunnerdCodexTransport({ ...transportOptions, recoveryLaunch: { requirements: requirements! }, + resumeProviderSession: { driverSessionId: checkpoint.sessionId, providerSessionId: checkpoint.providerSessionId!, providerIdentity: checkpoint.providerIdentity }, + authorityRunId: identity.runId, runnerProcessLauncher: () => { throw new Error("duplicate runner launch"); }, + adoptExistingRunner: { pid, processGroupId: pid, startedAt, isAlive: () => alive(pid), signal: () => false }, ...extra }); + const serverRequests: Array> = []; + const install = second.transport.setServerRequestHandler.bind(second.transport); + second.transport.setServerRequestHandler = handler => install(async request => { + const response = await handler(request); + serverRequests.push(structuredClone({ method: request.method, params: request.params, response })); + return response; + }); + return { second, pid, serverRequests }; + }; + }; + const atRestart = async () => ({ journalled: await calls(), durable: await durableState(root) }); + const fail = async (error: unknown) => new Error(`${String(error)}\n${await readFile(join(root, "native.stderr"), "utf8").catch(() => "")}`, { cause: error }); + const dispose = async () => { + for (const pid of runnerPids) kill(pid); + for (const entry of await calls()) if (entry.processStart) kill(entry.processStart); + server.closeAllConnections(); await new Promise(done => server.close(() => done())); + await rm(root, { recursive: true, force: true }); + }; + return { root, identity, nativeIdentity, execution, diagnostics, calls, backend, first, restarted, atRestart, fail, dispose }; +} + +async function runRestartScenario(tokens: string, options: { waitMs: number; lastTurnId: string; detachDelayMs?: number; holdFirstToolCall?: boolean; snapshotAtProviderTurn?: boolean }) { + const fixture = await restartFixture(tokens); + try { + const first = fixture.first(options.holdFirstToolCall); + const session = await fixture.backend(first).openSession({ identity: fixture.nativeIdentity, workingDirectory: fixture.root }); + await session.startTurn({ message: { role: "user", text: "Install and test." } }); + for await (const event of session.events()) if (options.snapshotAtProviderTurn ? event.payload.origin === "provider" : event.eventType === "turn.completed") break; + const checkpoint = await session.snapshot(); + await new Promise(done => setTimeout(done, options.detachDelayMs ?? 0)); + const restart = fixture.restarted(first, checkpoint, { resumeActiveTurnId: checkpoint.activeTurnId ?? null }); + await session.detachControllerForRestart!(); + await new Promise(done => setTimeout(done, options.waitMs)); + const atRestart = await fixture.atRestart(); + const { second, pid, serverRequests } = restart(); + const recovery = await fixture.backend(second).recoverSession!(checkpoint, { signal: new AbortController().signal }); + const result = { checkpoint, pid, recoveredPid: second.evidence().runnerPid, recovered: recovery.recovered, reason: recovery.reason, atRestart, serverRequests, + delivered: [] as PrpEvent[], snapshot: null as unknown, closeOutcome: "not closed", journalled: [] as Array>, diagnostics: fixture.diagnostics, durable: "" }; + if (recovery.session) { + const events = recovery.session.events()[Symbol.asyncIterator](); + const timeout = new Promise(done => setTimeout(() => done(null), 15_000)); + for (let next = await Promise.race([events.next(), timeout]); next && !next.done; next = await Promise.race([events.next(), timeout])) { + result.delivered.push(next.value); + if (next.value.eventType === "session.failed" || (next.value.eventType === "turn.completed" && next.value.turnId === options.lastTurnId)) break; + } + result.snapshot = await recovery.session.snapshot(); + result.closeOutcome = await recovery.session.close({ reason: "fixture complete" }).then(() => "closed", (error: unknown) => String(error instanceof Error ? error.message : error)); + } + const final = await fixture.atRestart(); + return { ...result, ...{ journalled: final.journalled, durable: final.durable } }; + } catch (error) { + throw await fixture.fail(error); + } finally { + await fixture.dispose(); + } +} + +const replyResult: PrpStructuredRunResult = { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: "Claude finished its own work.", + completionClaim: { contractRevision: "acpx-provider-turns-v1", objectiveSatisfied: true, criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }], remainingWork: [] }, + evidence: [], verification: [], attentionRequests: [], artifacts: [] }; + +async function runConsumerRestartScenario(tokens: string, options: { at: "wait" | "provider-turn" | "turn"; waitMs: number; replyResult?: boolean; holdFirstToolCall?: boolean; sidecarArgs?: string; optIn?: boolean; + slowAppend?: (event: PrpEvent) => boolean; holdWaitCheckpoint?: boolean }) { + const fixture = await restartFixture(tokens, options.sidecarArgs, options.optIn ?? true); + const { identity, execution } = fixture; + const appended: PrpEvent[] = [], committed: PrpEvent[] = [], appendedAt: number[] = [], checkpoints: PersistedNativeSession[] = []; + const completeRun = vi.fn(async (_value: unknown) => undefined); + let fenced = false, held = false, slowed = false; + let releaseQueued = () => {}; + const fence = new Promise(done => { releaseQueued = done; }); + const queuedAtRestart: PrpEvent[] = []; + let heldCheckpoint: PersistedNativeSession | null = null; + const controlPlane = (fencedController: boolean) => { + const guard = () => { if (fencedController && fenced) throw new Error("controller fenced for restart"); }; + return { + async openRun() { guard(); }, + async checkpointSession(value: PersistedNativeSession) { + guard(); + if (fencedController && options.holdWaitCheckpoint && value.awaitingProviderTurn === true) { heldCheckpoint = structuredClone(value); await fence; guard(); } + checkpoints.push(structuredClone(value)); + }, + async appendEvent(value: PrpEvent) { + guard(); + if (fencedController && options.slowAppend) { + if (slowed) { queuedAtRestart.push(structuredClone(value)); await fence; guard(); } + if (options.slowAppend(value)) { slowed = true; await new Promise(done => setTimeout(done, 1_000)); } + } + appended.push(structuredClone(value)); appendedAt.push(Date.now()); + return storeSourceEvent(committed, value); + }, + async replayEvents(request: { sourceInstanceId: string; afterSourceSeq: number; limit?: number }) { + const events = committed.filter(event => event.sourceInstanceId === request.sourceInstanceId && event.sourceSeq > request.afterSourceSeq) + .sort((left, right) => left.sourceSeq - right.sourceSeq).slice(0, request.limit ?? 1_000); + let highestContiguousSourceSeq = request.afterSourceSeq; + for (const event of events) if (event.sourceSeq === highestContiguousSourceSeq + 1) highestContiguousSourceSeq += 1; + return { events: structuredClone(events), highestContiguousSourceSeq }; + }, + async completeRun(value: unknown) { guard(); await completeRun(value); }, + }; + }; + const execute = (backend: ReturnType, fencedController: boolean, extra: Partial[0]>) => executeNativeSession({ + input: execution, backend, runnerInstanceId: identity.runnerInstanceId, controlPlaneInstanceId: "control-provider-turn-restart", + controlPlane: controlPlane(fencedController), timeoutMs: 30_000, ...extra, + resolveMissingResult: async ({ terminalEvent }) => options.replyResult && terminalEvent.turnId === "provider-1" && !terminalEvent.payload.awaitingProviderTurn ? structuredClone(replyResult) : null, + }).then(() => "finalized", (error: unknown) => String(error instanceof Error ? error.message : error)); + try { + const first = fixture.first(options.holdFirstToolCall, () => { held = true; }); + let session: NativeSession | null = null; + const stopFirst = new AbortController(); + const firstOutcome = execute(fixture.backend(first), true, { signal: stopFirst.signal, onSession: value => { session = value ?? session; } }); + const reached = (event: PrpEvent) => options.at === "wait" ? event.payload.awaitingProviderTurn === true + : options.at === "turn" ? event.eventType === "turn.started" : event.eventType === "turn.started" && event.payload.origin === "provider"; + const shaped = (value: PersistedNativeSession) => options.at === "wait" ? value.awaitingProviderTurn === true + : options.at === "turn" ? typeof value.activeTurnId === "string" : value.activeTurnId === "provider-1"; + await vi.waitFor(() => expect(appended.some(reached) && (!options.holdFirstToolCall || held)).toBe(true), { timeout: 20_000, interval: 20 }); + await vi.waitFor(() => expect(checkpoints.some(shaped)).toBe(true), { timeout: options.slowAppend ? 10_000 : 1_000, interval: 20 }).catch(() => undefined); + if (options.slowAppend) await vi.waitFor(() => expect(queuedAtRestart.length).toBeGreaterThan(0), { timeout: 5_000, interval: 20 }); + if (options.holdWaitCheckpoint) await vi.waitFor(() => expect(heldCheckpoint).not.toBeNull(), { timeout: 5_000, interval: 20 }); + fenced = true; + releaseQueued(); + const committedAtRestart = structuredClone(committed); + const checkpoint = checkpoints.at(-1)!; + const restart = fixture.restarted(first, checkpoint, { resumeActiveTurnId: checkpoint.activeTurnId ?? null }); + await (session as NativeSession | null)!.detachControllerForRestart!(); + const firstSettled = await Promise.race([firstOutcome, new Promise(done => setTimeout(() => done(null), 3_000))]); + if (firstSettled === null) stopFirst.abort(new Error("controller process exited")); + await firstOutcome; + await new Promise(done => setTimeout(done, options.waitMs)); + const atRestart = await fixture.atRestart(); + const { second, pid, serverRequests } = restart(); + const awaitingAt = appendedAt[appended.findIndex(event => event.payload.awaitingProviderTurn === true)] ?? null; + const firstAppended = appended.length; + const outcome = await execute(fixture.backend(second), false, { persistedSession: checkpoint, providerTurnWait: { startedAtMs: awaitingAt } }); + const recoveredPid = second.evidence().runnerPid; + const closeOutcome = await second.transport.close().then(() => "closed", (error: unknown) => String(error instanceof Error ? error.message : error)); + const final = await fixture.atRestart(); + return { runnerInstanceId: identity.runnerInstanceId, checkpoint, pid, recoveredPid, atRestart, serverRequests, appended, appendedAfterRestart: appended.slice(firstAppended), checkpoints, outcome, completeRun, closeOutcome, + diagnostics: fixture.diagnostics, journalled: final.journalled, durable: final.durable, committed, committedAtRestart, queuedAtRestart, heldCheckpoint }; + } catch (error) { + throw await fixture.fail(error); + } finally { + await fixture.dispose(); + } +} + +type RestartRun = Awaited>; +const ofType = (run: RestartRun, eventType: string) => run.delivered.filter(event => event.eventType === eventType); +const resolvedCalls = (journalled: Array>) => journalled.filter(entry => entry.command === "tool.resolve") + .map(entry => [entry.params.turnId, entry.params.callId, entry.params.error ?? null]); +const acked = (run: RestartRun, eventType: string) => (JSON.parse(run.atRestart.durable.split("\n")[0]!).committedEvents as Array>) + .filter(event => event.eventType === eventType).map(event => event.envelope.payload.payload); +const ackedStarts = (run: RestartRun) => acked(run, "turn.started").map(payload => [payload.providerTurnId ?? null, payload.origin ?? null]); +const ackedTerminals = (run: RestartRun) => acked(run, "turn.completed").map(payload => payload.providerTurnId); +const expectProviderTurnsInOrder = (run: RestartRun, turnIds: string[]) => { + expect(ofType(run, "turn.started").map(event => [event.turnId, event.payload.origin])).toEqual(turnIds.map(turnId => [turnId, "provider"])); + for (const turnId of turnIds) { + const turn = run.delivered.filter(event => event.turnId === turnId); + expect(turn[0]?.eventType).toBe("turn.started"); + expect(turn.at(-1)?.eventType).toBe("turn.completed"); + } + const owners = run.delivered.filter(event => event.turnId?.startsWith("provider-")).map(event => event.turnId); + expect(owners).toEqual([...owners].sort()); + const sequence = run.delivered.map(event => event.sourceSeq); + expect(sequence).toEqual([...new Set(sequence)].sort((left, right) => left - right)); +}; +const armedWaits = (journalled: Array>) => journalled.filter(entry => entry.command === "session.provider_turn" && entry.params.armed === true).length; +const expectRecoveredCleanly = (run: RestartRun) => { + expect(run.recovered, run.reason).toBe(true); + expect(run.recoveredPid).toBe(run.pid); + expect(ofType(run, "session.failed")).toEqual([]); + expect(run.closeOutcome).toBe("closed"); + expect(unsettled(run.diagnostics)).toEqual([]); + expect(run.durable).not.toContain("conflicting duplicate"); +}; + +it.skipIf(process.platform === "win32").each([true, false])("delivers the provider's own turn that ran while the controller was away, after a restart during the wait (result: %s)", async withResult => { + const run = await runRestartScenario(`live provider-turn ${withResult ? "provider-result-resolved " : ""}provider-goal-at-terminal provider-turn-delay-ms=1500`, { waitMs: 2_500, lastTurnId: "provider-1" }); + expect(run.checkpoint).toMatchObject({ activeTurnId: null, semanticResult: null, awaitingProviderTurn: true }); + expectRecoveredCleanly(run); + expect(ofType(run, "turn.started").map(event => [event.turnId, event.payload.origin])).toEqual([["provider-1", "provider"]]); + expect(ofType(run, "item.completed").filter(event => event.payload.kind === "agentMessage").map(event => event.turnId)).toEqual(["provider-1"]); + expect(run.delivered.filter(event => event.payload.kind === "usage").map(event => event.turnId)).toEqual(["provider-1"]); + if (withResult) { + expect(ofType(run, "run.result.proposed").map(event => event.turnId)).toEqual(["provider-1"]); + expect(run.snapshot).toMatchObject({ semanticResult: { reportedWorkDisposition: "done" }, terminal: { turnTerminalState: "completed", runTerminalState: "succeeded" } }); + expect(resolvedCalls(run.journalled)).toEqual([["provider-1", "call-provider-finish", null]]); + expect(run.serverRequests.map(request => [request.params.turnId, request.params.tool, request.response.success])).toEqual([["provider-1", "paperclip_finish", true]]); + } else expect(ofType(run, "run.result.proposed")).toEqual([]); +}, 60_000); + +it.skipIf(process.platform === "win32").each([0, 1_500])("delivers two provider turns that the runner started while the controller was away, in order (detach delay: %i ms)", async detachDelayMs => { + const run = await runRestartScenario("live provider-turn provider-turns=live/resolved provider-goal-at-terminal provider-turn-delay-ms=1000", { waitMs: 3_500 - detachDelayMs, lastTurnId: "provider-2", detachDelayMs }); + expect(run.atRestart.journalled.filter(entry => entry.command === "session.provider_turn").map(entry => [entry.params.turnId, entry.params.armed])) + .toEqual([[expect.any(String), true], ["provider-1", true]]); + expect(resolvedCalls(run.atRestart.journalled)).toEqual([]); + const pending = ["provider-1", "provider-2"].filter(turnId => !ackedTerminals(run).includes(turnId)); + expect(pending).toContain("provider-2"); + expectRecoveredCleanly(run); + expectProviderTurnsInOrder(run, pending); + expect(ofType(run, "turn.completed").map(event => [event.turnId, event.payload.awaitingProviderTurn ?? false])) + .toEqual([["provider-1", true], ["provider-2", false]].filter(([turnId]) => pending.includes(turnId as string))); + expect(ofType(run, "item.completed").filter(event => event.payload.kind === "agentMessage").map(event => event.turnId)).toEqual(pending); + expect(run.delivered.filter(event => event.payload.kind === "usage").map(event => event.turnId)).toEqual(pending); + expect(ofType(run, "run.result.proposed").map(event => event.turnId)).toEqual(["provider-2"]); + expect(run.serverRequests.map(request => [request.params.turnId, request.params.tool, request.response.success])).toEqual([["provider-2", "paperclip_finish", true]]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-2", "call-provider-finish", null]]); + expect(run.snapshot).toMatchObject({ semanticResult: { reportedWorkDisposition: "done" }, terminal: { turnTerminalState: "completed", runTerminalState: "succeeded" } }); +}, 60_000); + +it.skipIf(process.platform === "win32")("delivers the start of a provider turn that the old controller acknowledged, before the rest of the turn", async () => { + const run = await runRestartScenario("live provider-turn provider-goal-at-terminal provider-turn-delay-ms=300 provider-turn-until-snapshot", { waitMs: 500, lastTurnId: "provider-1", detachDelayMs: 1_500 }); + expect(run.checkpoint).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true }); + expect(ackedStarts(run)).toContainEqual(["provider-1", "provider"]); + expect(run.atRestart.durable.split("\n")[0]).toContain("Claude is still working."); + expect(run.atRestart.durable).not.toContain("Claude finished its own work."); + expectRecoveredCleanly(run); + expectProviderTurnsInOrder(run, ["provider-1"]); + expect(run.delivered.filter(event => event.turnId === "provider-1").map(event => [event.eventType, event.turnId, event.payload.kind ?? null])).toEqual([["turn.started", "provider-1", null], + ["item.delta", "provider-1", "agentMessage"], ["item.completed", "provider-1", "usage"], ["item.completed", "provider-1", "agentMessage"], ["turn.completed", "provider-1", null]]); + expect(ofType(run, "run.result.proposed")).toEqual([]); + expect(run.serverRequests).toEqual([]); +}, 60_000); + +it.skipIf(process.platform === "win32")("delivers two provider turns after a restart when the old controller acknowledged the first turn's start", async () => { + const run = await runRestartScenario("live provider-turn provider-turns=live/resolved provider-goal-at-terminal provider-turn-delay-ms=300 provider-turn-gap-ms=2500", { waitMs: 2_500, lastTurnId: "provider-2", detachDelayMs: 1_500 }); + expect(run.checkpoint).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true }); + expect(ackedStarts(run)).toContainEqual(["provider-1", "provider"]); + expect(run.atRestart.durable.split("\n")[0]).toContain("Claude is still working."); + expect(run.atRestart.journalled.filter(entry => entry.command === "session.provider_turn").map(entry => entry.params.turnId)).toEqual([expect.any(String), "provider-1"]); + expectRecoveredCleanly(run); + expectProviderTurnsInOrder(run, ["provider-1", "provider-2"]); + expect(ofType(run, "turn.completed").map(event => [event.turnId, event.payload.awaitingProviderTurn ?? false])).toEqual([["provider-1", true], ["provider-2", false]]); + expect(run.delivered.filter(event => event.payload.kind === "usage").map(event => event.turnId)).toEqual(["provider-1", "provider-2"]); + expect(ofType(run, "run.result.proposed").map(event => event.turnId)).toEqual(["provider-2"]); + expect(run.serverRequests.map(request => [request.params.turnId, request.params.tool, request.response.success])).toEqual([["provider-2", "paperclip_finish", true]]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-2", "call-provider-finish", null]]); + expect(run.snapshot).toMatchObject({ semanticResult: { reportedWorkDisposition: "done" }, terminal: { turnTerminalState: "completed", runTerminalState: "succeeded" } }); +}, 60_000); + +it.skipIf(process.platform === "win32")("answers the open finish call of a provider turn whose start the old controller acknowledged", async () => { + const run = await runRestartScenario("live provider-turn provider-result-resolved provider-goal-at-terminal provider-turn-delay-ms=300", { waitMs: 500, lastTurnId: "provider-1", detachDelayMs: 1_500, holdFirstToolCall: true }); + expect(run.checkpoint).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true }); + expect(ackedStarts(run)).toContainEqual(["provider-1", "provider"]); + expect(resolvedCalls(run.atRestart.journalled)).toEqual([]); + expect(run.atRestart.durable).toContain("call-provider-finish"); + expectRecoveredCleanly(run); + expectProviderTurnsInOrder(run, ["provider-1"]); + expect(run.serverRequests.map(request => [request.params.turnId, request.params.tool, request.response.success])).toEqual([["provider-1", "paperclip_finish", true]]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-1", "call-provider-finish", null]]); + expect(ofType(run, "run.result.proposed").map(event => event.turnId)).toEqual(["provider-1"]); + expect(run.snapshot).toMatchObject({ activeTurnId: null, semanticResult: { reportedWorkDisposition: "done" }, terminal: { turnTerminalState: "completed", runTerminalState: "succeeded" } }); +}, 60_000); + +type ConsumerRun = Awaited>; +const waitingCheckpoint = { activeTurnId: null, awaitingProviderTurn: true }; +const providerTurnCheckpoint = { activeTurnId: "provider-1" }; +const expectSettledAfterRestart = (run: ConsumerRun, turnIds: string[]) => { + expect(run.outcome, run.diagnostics.slice(-12).join("\n")).toBe("finalized"); + expect(run.recoveredPid).toBe(run.pid); + expect(run.completeRun).toHaveBeenCalledOnce(); + expect(run.completeRun.mock.calls[0]![0]).toMatchObject({ turnId: turnIds.at(-1), result: { reportedWorkDisposition: "done" } }); + expect(run.appended.filter(event => event.eventType === "turn.started").map(event => [event.turnId, event.payload.origin ?? null])) + .toEqual([[expect.any(String), null], ...turnIds.map(turnId => [turnId, "provider"])]); + expect(run.appended.filter(event => event.eventType === "session.failed")).toEqual([]); + expect(run.appended.filter(event => event.eventType === "turn.completed" && event.turnId?.startsWith("provider-")).map(event => event.turnId)).toEqual(turnIds); + expect(run.appended.filter(event => event.payload.kind === "usage" && event.turnId?.startsWith("provider-")).map(event => event.turnId)).toEqual(turnIds); + const sequence = run.appended.filter(event => event.sourceInstanceId === run.runnerInstanceId).map(event => event.sourceSeq); + expect(sequence).toEqual([...new Set(sequence)].sort((left, right) => left - right)); + expect(run.closeOutcome).toBe("closed"); + expect(unsettled(run.diagnostics)).toEqual([]); + expect(run.durable).not.toContain("conflicting duplicate"); +}; +const expectNoTerminalPersistedWithoutResult = (run: ConsumerRun) => + expect(run.checkpoints.filter(checkpoint => (checkpoint.semanticResult ?? null) === null && (checkpoint.terminal ?? null) !== null)).toEqual([]); + +it.skipIf(process.platform === "win32")("settles a provider turn that starts after the new controller attached, from the checkpoint saved when the wait began", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-result-resolved provider-goal-at-terminal provider-turn-after-snapshot", { at: "wait", waitMs: 200 }); + expect(run.checkpoint).toMatchObject(waitingCheckpoint); + expect(run.atRestart.durable).not.toContain("call-provider-finish"); + expectSettledAfterRestart(run, ["provider-1"]); + expectNoTerminalPersistedWithoutResult(run); +}, 60_000); + +it.skipIf(process.platform === "win32")("settles a provider turn that was running at a restart, from the checkpoint saved when it started", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-goal-at-terminal provider-turn-delay-ms=300 provider-turn-until-snapshot", { at: "provider-turn", waitMs: 1_000, replyResult: true }); + expect(run.checkpoint).toMatchObject(providerTurnCheckpoint); + expect(run.atRestart.durable).toContain("Claude is still working."); + expect(run.atRestart.durable).not.toContain("Claude finished its own work."); + expectSettledAfterRestart(run, ["provider-1"]); + expect(run.serverRequests).toEqual([]); +}, 60_000); + +it.skipIf(process.platform === "win32")("delivers the rest of a provider turn active in the checkpoint without a second start, then the next provider turn", async () => { + const run = await runRestartScenario("live provider-turn provider-turns=live/resolved provider-goal-at-terminal provider-turn-delay-ms=300 provider-turn-gap-ms=2500", { waitMs: 3_500, lastTurnId: "provider-2", snapshotAtProviderTurn: true }); + expect(run.checkpoint).toMatchObject({ activeTurnId: "provider-1" }); + expect(ackedStarts(run)).toContainEqual(["provider-1", "provider"]); + expect(ackedTerminals(run)).not.toContain("provider-1"); + expectRecoveredCleanly(run); + expect(ofType(run, "turn.started").map(event => [event.turnId, event.payload.origin])).toEqual([["provider-2", "provider"]]); + const owners = run.delivered.filter(event => event.turnId?.startsWith("provider-")).map(event => event.turnId); + expect(owners).toEqual([...owners].sort()); + expect(run.delivered.filter(event => event.eventType.startsWith("turn.")).map(event => [event.eventType, event.turnId])) + .toEqual([["turn.completed", "provider-1"], ["turn.started", "provider-2"], ["turn.completed", "provider-2"]]); + expect(run.delivered.filter(event => event.payload.kind === "usage").map(event => event.turnId)).toEqual(["provider-1", "provider-2"]); + expect(run.serverRequests.map(request => [request.params.turnId, request.params.tool, request.response.success])).toEqual([["provider-2", "paperclip_finish", true]]); + const sequence = run.delivered.map(event => event.sourceSeq); + expect(sequence).toEqual([...new Set(sequence)].sort((left, right) => left - right)); +}, 60_000); + +const answeredCalls = (run: ConsumerRun) => run.serverRequests.map(request => [request.params.turnId, request.params.tool, request.response.success]); +const providerTurnEvents = (events: PrpEvent[]) => events + .filter(event => event.turnId?.startsWith("provider-") && !event.eventType.startsWith("session.") && event.eventType !== "item.delta") + .map(event => [event.eventType, event.turnId, event.payload.kind ?? event.payload.origin ?? null]); +const settledProviderTurn = (turnId: string, opening: unknown[][]) => [ + ...opening, + ["item.completed", turnId, "usage"], + ["item.completed", turnId, "agentMessage"], + ["turn.completed", turnId, null], +]; +const acceptedResult = (turnId: string) => [["run.result.accepted", turnId, null], ["run.terminal", turnId, null]]; +const startedWithResult = (turnId: string) => [["turn.started", turnId, "provider"], ["run.result.proposed", turnId, null]]; + +it.skipIf(process.platform === "win32")("R0 settles an ordinary turn whose finish call was open at a restart and appends its result, completion and terminal once", async () => { + const run = await runConsumerRestartScenario("quiet", { at: "turn", waitMs: 500, holdFirstToolCall: true, sidecarArgs: " --wait-completion-feedback", optIn: false }); + const turnId = run.checkpoint.activeTurnId!; + expect(turnId).toEqual(expect.any(String)); + expect(run.outcome, run.diagnostics.slice(-12).join("\n")).toBe("finalized"); + expect(run.recoveredPid).toBe(run.pid); + expect(run.completeRun).toHaveBeenCalledOnce(); + expect(run.completeRun.mock.calls[0]![0]).toMatchObject({ turnId, result: { reportedWorkDisposition: "done" } }); + expect(answeredCalls(run)).toEqual([[turnId, "paperclip_finish", true]]); + expect(run.appendedAfterRestart.filter(event => event.turnId === turnId && !event.eventType.startsWith("session.")).map(event => event.eventType)) + .toEqual(["run.result.proposed", "turn.completed", "run.result.accepted", "run.terminal"]); + const sequence = run.appended.filter(event => event.sourceInstanceId === run.runnerInstanceId).map(event => event.sourceSeq); + expect(sequence).toEqual([...new Set(sequence)].sort((left, right) => left - right)); + expect(run.closeOutcome).toBe("closed"); + expect(unsettled(run.diagnostics)).toEqual([]); +}, 60_000); + +it.skipIf(process.platform === "win32")("R1 appends a provider turn that ran while the controller was away, from the checkpoint saved when the wait began", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-result-resolved provider-goal-at-terminal provider-turn-delay-ms=1500", { at: "wait", waitMs: 3_000 }); + expect(run.checkpoint).toMatchObject({ ...waitingCheckpoint, terminal: null }); + expect(run.atRestart.durable).toContain("call-provider-finish"); + expect(run.appended.filter(event => event.turnId === "provider-1")).toEqual(run.appendedAfterRestart.filter(event => event.turnId === "provider-1")); + expect(providerTurnEvents(run.appendedAfterRestart)).toEqual([...settledProviderTurn("provider-1", startedWithResult("provider-1")), ...acceptedResult("provider-1")]); + expectSettledAfterRestart(run, ["provider-1"]); + expectNoTerminalPersistedWithoutResult(run); +}, 60_000); + +it.skipIf(process.platform === "win32")("R4 appends the rest of a provider turn whose finish call was open at a restart, from the checkpoint saved when the turn started", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-result-resolved provider-goal-at-terminal provider-turn-delay-ms=300", { at: "provider-turn", waitMs: 500, holdFirstToolCall: true }); + expect(run.checkpoint).toMatchObject(providerTurnCheckpoint); + expect(resolvedCalls(run.atRestart.journalled)).toEqual([]); + expect(providerTurnEvents(run.appendedAfterRestart)).toEqual([...settledProviderTurn("provider-1", [["run.result.proposed", "provider-1", null]]), ...acceptedResult("provider-1")]); + expectSettledAfterRestart(run, ["provider-1"]); + expectNoTerminalPersistedWithoutResult(run); + expect(answeredCalls(run)).toEqual([["provider-1", "paperclip_finish", true]]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-1", "call-provider-finish", null]]); +}, 60_000); + +it.skipIf(process.platform === "win32")("R5 appends both provider turns after a restart during the first, from the checkpoint saved when it started", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-turns=live/resolved provider-goal-at-terminal provider-turn-delay-ms=300 provider-turn-gap-ms=2500", { at: "provider-turn", waitMs: 3_500 }); + expect(run.checkpoint).toMatchObject(providerTurnCheckpoint); + expect(run.atRestart.journalled.filter(entry => entry.command === "session.provider_turn").map(entry => entry.params.turnId)).toEqual([expect.any(String), "provider-1"]); + expect(providerTurnEvents(run.appended)).toEqual([ + ...settledProviderTurn("provider-1", [["turn.started", "provider-1", "provider"]]), + ...settledProviderTurn("provider-2", startedWithResult("provider-2")), + ...acceptedResult("provider-2"), + ]); + expectSettledAfterRestart(run, ["provider-1", "provider-2"]); + expectNoTerminalPersistedWithoutResult(run); + expect(answeredCalls(run)).toEqual([["provider-2", "paperclip_finish", true]]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-2", "call-provider-finish", null]]); +}, 60_000); + +const providerTurnStarts = (run: ConsumerRun) => run.committed.filter(event => event.eventType === "turn.started" && event.payload.origin === "provider").map(event => event.turnId); +const storedSequence = (run: ConsumerRun, events: PrpEvent[]) => events.filter(event => event.sourceInstanceId === run.runnerInstanceId) + .map(event => event.sourceSeq).sort((left, right) => left - right); +const expectCheckpointAtStoredEvent = (run: ConsumerRun) => { + expect(run.queuedAtRestart.length).toBeGreaterThan(0); + expect(run.checkpoint.cursor).toBe(String(storedSequence(run, run.committedAtRestart).at(-1))); +}; +const expectNoHoleInCore = (run: ConsumerRun) => { + const sequence = storedSequence(run, run.committed); + expect(sequence).toEqual(sequence.map((_value, index) => index + 1)); +}; +const expectSettledOnce = (run: ConsumerRun) => { + expect(run.outcome, run.diagnostics.slice(-12).join("\n")).toBe("finalized"); + expect(run.completeRun).toHaveBeenCalledOnce(); + expect(run.committed.filter(event => event.eventType === "turn.completed" && event.turnId === "provider-1")).toHaveLength(1); + expect(run.closeOutcome).toBe("closed"); + expect(unsettled(run.diagnostics)).toEqual([]); + expect(run.durable).not.toContain("conflicting duplicate"); +}; +const providerStart = (event: PrpEvent) => event.eventType === "turn.started" && event.payload.origin === "provider"; +const awaitingTerminal = (event: PrpEvent) => event.eventType === "turn.completed" && event.payload.awaitingProviderTurn === true; + +it.skipIf(process.platform === "win32")("R6 saves the provider-start checkpoint at the start Core stored, so the recovered controller continues Core's sequence without a hole", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-goal-at-terminal provider-turn-delay-ms=300 provider-turn-until-snapshot", + { at: "provider-turn", waitMs: 1_000, replyResult: true, slowAppend: providerStart }); + expect(run.queuedAtRestart.map(event => [event.eventType, event.turnId])).toEqual([["item.delta", "provider-1"]]); + expectNoHoleInCore(run); + expectSettledOnce(run); + expect(run.checkpoint).toMatchObject({ activeTurnId: "provider-1", semanticResult: null }); + expectCheckpointAtStoredEvent(run); + expect(providerTurnStarts(run)).toEqual(["provider-1"]); +}, 60_000); + +it.skipIf(process.platform === "win32")("R7 saves the waiting checkpoint at the awaited terminal Core stored, so the provider turn's start reaches Core exactly once", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-result-resolved provider-goal-at-terminal", + { at: "wait", waitMs: 500, holdFirstToolCall: true, slowAppend: awaitingTerminal }); + expect(providerTurnStarts(run)).toEqual(["provider-1"]); + expect(run.checkpoint).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true, semanticResult: null }); + expectCheckpointAtStoredEvent(run); + expect(run.committed.filter(event => event.eventType === "run.result.proposed").map(event => event.turnId)).toEqual(["provider-1"]); + expectNoHoleInCore(run); + expectSettledOnce(run); + expect(answeredCalls(run)).toEqual([["provider-1", "paperclip_finish", true]]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-1", "call-provider-finish", null]]); +}, 60_000); + +it.skipIf(process.platform === "win32")("R8 characterization: after the old controller answered the provider turn's finish, recovery resumes at the stored start without a result, closes the turn in Core and ends on the missing-result path", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-result-resolved provider-goal-at-terminal provider-turn-delay-ms=300", + { at: "provider-turn", waitMs: 500, slowAppend: providerStart }); + expect(run.queuedAtRestart.map(event => event.eventType)).toEqual(["run.result.proposed"]); + expect(run.outcome).toContain("native_finalization_missing"); + expect(run.checkpoint).toMatchObject({ activeTurnId: "provider-1", semanticResult: null }); + expectCheckpointAtStoredEvent(run); + expect(providerTurnStarts(run)).toEqual(["provider-1"]); + expect(run.committed.filter(event => event.eventType === "run.result.proposed")).toEqual([]); + expect(run.committed.filter(event => event.eventType === "turn.completed" && event.turnId === "provider-1")).toHaveLength(1); + expectNoHoleInCore(run); + expect(answeredCalls(run)).toEqual([]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-1", "call-provider-finish", null]]); + expect(run.completeRun).not.toHaveBeenCalled(); + expect(run.durable).not.toContain("conflicting duplicate"); +}, 60_000); + +it.skipIf(process.platform === "win32")("R10 recovers from the checkpoint saved at the controller turn's start when the wait checkpoint was not saved, and admits the provider turn's start only after reconciling that turn", async () => { + const run = await runConsumerRestartScenario("live provider-turn provider-result-resolved provider-goal-at-terminal provider-turn-delay-ms=300", + { at: "wait", waitMs: 1_000, holdFirstToolCall: true, holdWaitCheckpoint: true }); + const controllerTurn = run.checkpoint.activeTurnId!; + expect(controllerTurn).toEqual(expect.any(String)); + expect(run.checkpoint).toMatchObject({ semanticResult: null }); + expect(run.heldCheckpoint).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true }); + expect(run.committedAtRestart.filter(awaitingTerminal).map(event => event.turnId)).toEqual([controllerTurn]); + expect(acked(run as unknown as RestartRun, "turn.completed").filter(payload => payload.awaitingProviderTurn === true)).toHaveLength(1); + expect(run.atRestart.durable).toContain("call-provider-finish"); + expect(run.appended.filter(event => event.eventType === "session.failed")).toEqual([]); + expectSettledOnce(run); + expect(run.completeRun.mock.calls[0]![0]).toMatchObject({ turnId: "provider-1", result: { reportedWorkDisposition: "done" } }); + expect(providerTurnStarts(run)).toEqual(["provider-1"]); + expect(answeredCalls(run)).toEqual([["provider-1", "paperclip_finish", true]]); + expect(resolvedCalls(run.journalled)).toEqual([["provider-1", "call-provider-finish", null]]); +}, 60_000); + +it.skipIf(process.platform === "win32")("R9 characterization: an ordinary turn whose start checkpoint is ahead of Core settles after a restart, and Core lacks only the event the old controller did not store", async () => { + const run = await runConsumerRestartScenario("quiet", { at: "turn", waitMs: 500, holdFirstToolCall: true, sidecarArgs: " --wait-completion-feedback", optIn: false, + slowAppend: event => event.eventType === "turn.started" }); + const turnId = run.checkpoint.activeTurnId!; + const stored = (events: PrpEvent[]) => events.filter(event => event.sourceInstanceId === run.runnerInstanceId).map(event => event.sourceSeq); + const lost = run.queuedAtRestart.map(event => event.sourceSeq); + expect(run.queuedAtRestart.map(event => [event.eventType, event.turnId])).toEqual([["turn.accepted", turnId]]); + expect(run.checkpoint.cursor).toBe(String(lost[0])); + expect(stored(run.committedAtRestart).at(-1)).toBe(lost[0]! - 1); + expect(run.outcome, run.diagnostics.slice(-12).join("\n")).toBe("finalized"); + expect(run.recoveredPid).toBe(run.pid); + expect(run.completeRun).toHaveBeenCalledOnce(); + expect(run.completeRun.mock.calls[0]![0]).toMatchObject({ turnId, result: { reportedWorkDisposition: "done" } }); + expect(answeredCalls(run)).toEqual([[turnId, "paperclip_finish", true]]); + expect(run.appendedAfterRestart.filter(event => event.turnId === turnId && !event.eventType.startsWith("session.")).map(event => event.eventType)) + .toEqual(["run.result.proposed", "turn.completed", "run.result.accepted", "run.terminal"]); + const sequence = stored(run.committed); + expect(sequence).toEqual(Array.from({ length: sequence.at(-1)! }, (_value, index) => index + 1).filter(sourceSeq => !lost.includes(sourceSeq))); + expect(run.committed.filter(event => event.eventType === "turn.accepted")).toEqual([]); + expect(run.closeOutcome).toBe("closed"); + expect(unsettled(run.diagnostics)).toEqual([]); + expect(run.durable).not.toContain("conflicting duplicate"); +}, 60_000); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index 5169606853d..bf44c8eaea4 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -7280,3 +7280,140 @@ describe("a Runner command that gets no answer", () => { .toBe("runner disconnected 125s; pending ahead 0; last runner event none"); }); }); + +const providerTurnStart = (turnId: string, origin: string | null = "provider") => ({ provider: "acpx", providerTurnId: turnId, status: "inProgress", + turn: { id: turnId, status: "inProgress" }, ...(origin ? { origin } : {}) }); +const providerTurnItem = (turnId: string) => ({ provider: "acpx", itemId: `message-${turnId}`, kind: "agentMessage", status: "completed", text: `${turnId} is done.` }); +const providerTurnTerminal = (turnId: string) => ({ provider: "acpx", providerTurnId: turnId, status: "completed", error: null }); +const optedInClaude = { provider: "acpx" as const, acpxAgent: "claude" as const, providerStartedTurns: true }; + +async function deliverProviderTurnEventsAfterRestart(input: { + options: Record; + resumeActiveTurnId?: string; + acknowledged: Array<[string, Record]>; + redelivered: Array<[string, Record]>; + removed?: number[]; + finishCall?: boolean; +}) { + const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-provider-turn-start-")); + const OriginalCore = durableControlPlane.DurablePrpControlPlane; + let callbacks!: ConstructorParameters[0]; + let core!: DurablePrpControlPlane; + const coreSpy = vi.spyOn(durableControlPlane, "DurablePrpControlPlane").mockImplementation(function (options) { + callbacks = options; + return core = new OriginalCore(options); + }); + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), codexCommand: fakeCodex, codexArgs: fakeCodexArgs(stateDirectory), stateDirectory, + ...(input.resumeActiveTurnId ? { resumeActiveTurnId: input.resumeActiveTurnId } : {}), + }); + const toolCalls: Array> = []; + bundle.transport.setServerRequestHandler(async request => { + toolCalls.push(structuredClone(request.params)); + return { success: true, contentItems: [{ type: "inputText" as const, text: "{\"done\":true}" }] }; + }); + const delivered: Array<{ method: string; params: Record }> = []; + try { + await bundle.transport.request("thread/start", { cwd: tmpdir() }); + const reader = bundle.transport.notifications()[Symbol.asyncIterator](); + void (async () => { for (let next = await reader.next(); !next.done; next = await reader.next()) delivered.push(next.value); })().catch(() => undefined); + await new Promise(done => setTimeout(done, 100)); + const before = delivered.length; + const transport = bundle.transport as unknown as { options: Record }; + transport.options = { ...transport.options, ...input.options }; + const identity = core.store.state.identity; + const window = core.store.state.committedEvents; + const envelope = (eventType: string, payload: Record) => + ({ runId: identity.runId, turnId: identity.turnId, payload: { eventType, turnId: identity.turnId, payload } }); + input.acknowledged.forEach(([eventType, payload], index) => { + const at = window.length - input.acknowledged.length + index; + window[at] = { ...window[at]!, eventType, envelope: envelope(eventType, payload) }; + }); + for (const at of [...input.removed ?? []].sort((left, right) => right - left)) window.splice(window.length - input.acknowledged.length + at, 1); + let seq = window.at(-1)!.sourceSeq; + const commit = (eventType: string, payload: Record) => { + seq += 1; + window.push({ sourceSeq: seq, sourceEventId: `provider-turn-start-${seq}`, eventType, priority: 1, + envelope: envelope(eventType, payload), deliveryCount: 1, logicalEffectCount: 1 }); + return `provider-turn-start-${seq}`; + }; + for (const [eventType, payload] of input.redelivered) commit(eventType, payload); + (core.store as unknown as { onChange: (() => void) | null }).onChange?.(); + if (input.finishCall) { + const sourceEventId = commit("tool.execution.started", { executionId: "exec-provider-finish", transport: "dynamic", name: "paperclip_finish", status: "running" }); + const outcome = await callbacks.onSemanticToolInput!({ callId: "exec-provider-finish", operationId: "paperclip_finish", + input: { summary: "Done" }, sourceEventId, sourceEventType: "semantic_tool.input", correlation: identity }); + expect(outcome.isError).not.toBe(true); + } + await new Promise(done => setTimeout(done, 200)); + return { notifications: delivered.slice(before).filter(notification => notification.method.startsWith("turn/") || notification.method.startsWith("item/")), toolCalls }; + } finally { + coreSpy.mockRestore(); + await bundle.transport.close().catch(() => undefined); + await rm(stateDirectory, { recursive: true, force: true }); + } +} + +const notificationTurns = (notifications: Array<{ method: string; params: Record }>) => + notifications.map(notification => [notification.method, notification.params.turnId, notification.params.origin ?? null]); + +it("gives the driver a provider turn's start before its next event when the start was acknowledged before a restart", async () => { + const { notifications } = await deliverProviderTurnEventsAfterRestart({ options: optedInClaude, + acknowledged: [["turn.started", providerTurnStart("provider-1")]], + redelivered: [["item.completed", providerTurnItem("provider-1")], ["turn.completed", providerTurnTerminal("provider-1")]] }); + expect(notificationTurns(notifications)).toEqual([["turn/started", "provider-1", "provider"], ["item/completed", "provider-1", null], ["turn/completed", "provider-1", null]]); + expect(notifications[0]!.params).toEqual(rehydrateRunnerdTurnNotification(providerTurnStart("provider-1"), notifications[1]!.params.threadId, "provider-1", "turn/started")); +}, 20_000); + +it("gives the driver a provider turn's start before its next event when the window removed events after the start", async () => { + const { notifications } = await deliverProviderTurnEventsAfterRestart({ options: optedInClaude, + acknowledged: [["turn.started", providerTurnStart("provider-1")], ["item.completed", providerTurnItem("provider-1")], ["item.completed", providerTurnItem("provider-1")]], + removed: [1], + redelivered: [["item.completed", providerTurnItem("provider-1")], ["turn.completed", providerTurnTerminal("provider-1")]] }); + expect(notificationTurns(notifications)).toEqual([["turn/started", "provider-1", "provider"], ["item/completed", "provider-1", null], ["turn/completed", "provider-1", null]]); +}, 20_000); + +it("labels each provider turn's events with that turn when the recovery read names a later turn", async () => { + const { notifications } = await deliverProviderTurnEventsAfterRestart({ options: optedInClaude, resumeActiveTurnId: "provider-2", + acknowledged: [["turn.started", providerTurnStart("provider-1")]], + redelivered: [["item.completed", providerTurnItem("provider-1")], ["turn.completed", providerTurnTerminal("provider-1")], + ["turn.started", providerTurnStart("provider-2")], ["item.completed", providerTurnItem("provider-2")]] }); + expect(notificationTurns(notifications)).toEqual([["turn/started", "provider-1", "provider"], ["item/completed", "provider-1", null], + ["turn/completed", "provider-1", null], ["turn/started", "provider-2", "provider"], ["item/completed", "provider-2", null]]); +}, 20_000); + +it("gives no second start to the provider turn that the recovered driver already has as its active turn", async () => { + const { notifications } = await deliverProviderTurnEventsAfterRestart({ options: optedInClaude, resumeActiveTurnId: "provider-1", + acknowledged: [["turn.started", providerTurnStart("provider-1")]], + redelivered: [["item.completed", providerTurnItem("provider-1")], ["turn.completed", providerTurnTerminal("provider-1")]] }); + expect(notificationTurns(notifications)).toEqual([["item/completed", "provider-1", null], ["turn/completed", "provider-1", null]]); +}, 20_000); + +it("gives no second start to a provider turn whose start is delivered again", async () => { + const { notifications } = await deliverProviderTurnEventsAfterRestart({ options: optedInClaude, acknowledged: [], + redelivered: [["turn.started", providerTurnStart("provider-1")], ["item.completed", providerTurnItem("provider-1")], ["turn.completed", providerTurnTerminal("provider-1")]] }); + expect(notificationTurns(notifications)).toEqual([["turn/started", "provider-1", "provider"], ["item/completed", "provider-1", null], ["turn/completed", "provider-1", null]]); +}, 20_000); + +it.each([ + ["not opted in", { provider: "acpx", acpxAgent: "claude" }, "provider"], + ["a non-Claude agent", { provider: "acpx", acpxAgent: "codex", providerStartedTurns: true }, "provider"], + ["another provider", { providerStartedTurns: true }, "provider"], + ["a controller-started turn", optedInClaude, null], +] as const)("delivers a restarted turn's events as before for %s", async (_case, options, origin) => { + const { notifications } = await deliverProviderTurnEventsAfterRestart({ options, resumeActiveTurnId: "controller-turn", + acknowledged: [["turn.started", providerTurnStart("provider-1", origin)]], + redelivered: [["item.completed", providerTurnItem("provider-1")], ["turn.completed", providerTurnTerminal("provider-1")]] }); + const threadId = notifications[0]!.params.threadId; + expect(notifications).toEqual([ + { method: "item/completed", params: rehydrateRunnerdItemNotification(providerTurnItem("provider-1"), threadId, "controller-turn") }, + { method: "turn/completed", params: rehydrateRunnerdTurnNotification(providerTurnTerminal("provider-1"), threadId, "controller-turn", "turn/completed") }, + ]); +}, 20_000); + +it("binds the finish call of a provider turn whose start was acknowledged before a restart to that turn", async () => { + const { notifications, toolCalls } = await deliverProviderTurnEventsAfterRestart({ options: optedInClaude, resumeActiveTurnId: "provider-2", + acknowledged: [["turn.started", providerTurnStart("provider-1")]], redelivered: [], finishCall: true }); + expect(notificationTurns(notifications)).toEqual([["turn/started", "provider-1", "provider"]]); + expect(toolCalls).toEqual([expect.objectContaining({ turnId: "provider-1", tool: "paperclip_finish", callId: "exec-provider-finish" })]); +}, 20_000); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index d42325ca874..a9e56ff8f2e 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -1,4 +1,4 @@ -import { providerTurnToolCallSourceSeq } from "./provider-turn-tool-order.js"; +import { providerTurnStartBefore, providerTurnToolCallSourceSeq } from "./provider-turn-tool-order.js"; import type { RunnerAttachmentDownloadGrant } from "../contracts/harness-driver.js"; import { readProviderFailure } from "../contracts/provider-failure.generated.js"; import { confirmAntigravityProbeNativeRetirement } from "../drivers/acpx/antigravity-probe-retirement.js"; @@ -4219,6 +4219,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } | null = null; #checkpointProviderIdentityConfirmed = false; #turnId = ""; + readonly #deliveredProviderTurnStarts = new Set(); #turnStartResponsePending = false; #turnStartResponseSettled: Promise = Promise.resolve(); #turnStartResponseEpoch = 0; @@ -4388,6 +4389,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { void this.#failureSignal.catch(() => undefined); this.#ownsRoot = options.stateDirectory === undefined; this.#turnId = options.resumeActiveTurnId ?? ""; + if (options.resumeActiveTurnId) this.#deliveredProviderTurnStarts.add(options.resumeActiveTurnId); this.#root = options.stateDirectory ?? mkdtempSync(resolve(tmpdir(), "paperclip-runner-lab-prp-")); @@ -7794,6 +7796,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#pumpEvents(); await new Promise(resolveWait => setTimeout(resolveWait, 10)); } + this.#deliverProviderTurnStart(this.#core?.store.state.committedEvents ?? [], sourceSeq); let delivered!: () => void; const barrier = new Promise(resolveBarrier => { delivered = resolveBarrier; }); this.#queue.pushControl({ id: `provider-turn-order:${sourceSeq}`, method: "paperclip/providerTurnOrder", params: {} }, () => delivered()); @@ -7804,6 +7807,15 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ]).catch(() => { throw new SemanticToolNotDispatchedError(); }); } + #deliverProviderTurnStart(events: readonly DurableRecoveryCommittedEvent[], sourceSeq: number) { + const start = providerTurnStartBefore(events, sourceSeq); + if (start === null) return; + this.#turnId = start.turnId; + if (this.#deliveredProviderTurnStarts.has(start.turnId)) return; + this.#deliveredProviderTurnStarts.add(start.turnId); + this.#queue.push({ method: "turn/started", params: rehydrateRunnerdTurnNotification(start.payload, this.#threadId, start.turnId, "turn/started") }); + } + #bindSemanticToolOutcome(call: { operationId: string; callId: string }, outcome: { result: unknown; isError?: boolean }) { if (call.operationId === "call_api") { const result = record(outcome.result); @@ -8468,6 +8480,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#applyProviderIdentityEvent(event); continue; } + if (this.#providerStartedTurns() && event.eventType !== "turn.started") this.#deliverProviderTurnStart(events, event.sourceSeq); if (event.eventType === "session.capabilities.updated" && this.options.provider === "acpx") { const capabilities = record(record(event.envelope.payload).payload); if (capabilities.turnControls !== undefined) { @@ -8702,6 +8715,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } if (typeof providerTurnId === "string" && providerTurnId.length > 0) { this.#turnId = providerTurnId; + this.#deliveredProviderTurnStarts.add(providerTurnId); if (this.#turnStartResponsePending) { this.#observedTurnStartEpoch = this.#turnStartResponseEpoch; } diff --git a/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts b/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts index 79f14a7ffdf..7a46646bc0c 100644 --- a/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts @@ -107,6 +107,8 @@ function harness(options: { withoutInterrupt?: boolean; restart?: RestartContinu const queue: Array = []; let wake: (() => void) | null = null; let activeProviderTurn: string | null = null; + const observed = { activeTurnId: null as string | null, awaiting: false }; + const snapshotSequences: Array = []; const push = (...values: Array) => { for (const value of values) { if (value !== "end" && value.eventType === "turn.started") activeProviderTurn = value.turnId ?? null; @@ -138,7 +140,12 @@ function harness(options: { withoutInterrupt?: boolean; restart?: RestartContinu for (;;) { const next = queue.shift(); if (next === "end") return; - if (next) { yield structuredClone(next); continue; } + if (next) { + if (next.eventType === "turn.started") Object.assign(observed, { activeTurnId: next.turnId ?? null, awaiting: false }); + else if (next.eventType.startsWith("turn.")) Object.assign(observed, { activeTurnId: null, awaiting: next.payload.awaitingProviderTurn === true }); + yield structuredClone(next); + continue; + } await new Promise(resolve => { wake = resolve; }); wake = null; } @@ -146,10 +153,11 @@ function harness(options: { withoutInterrupt?: boolean; restart?: RestartContinu startTurn, ...(options.withoutInterrupt ? {} : { interrupt }), async result() { return null; }, - async snapshot() { + async snapshot(snapshotOptions?: { sourceSeq?: number }) { + snapshotSequences.push(snapshotOptions?.sourceSeq); const base: PersistedNativeSession = { backendKind: "mock", sessionId: identity.sessionId, identity, providerSessionId: "provider-session", cursor: String(sequence), activeTurnId: null, pendingRuntimeRequests: [], lineage: [] }; - if (!options.restart) return base; + if (!options.restart) return { ...base, activeTurnId: observed.activeTurnId, ...(observed.awaiting ? { awaitingProviderTurn: true } : {}) }; if (options.restart.recovery) return { ...base, ...options.restart.recovery.snapshot }; const starts = startTurn.mock.calls.length; return { ...base, semanticResult: null, @@ -159,7 +167,7 @@ function harness(options: { withoutInterrupt?: boolean; restart?: RestartContinu }, async close() { push("end"); }, }; - return { session, push, interrupt, startTurn }; + return { session, push, interrupt, startTurn, snapshotSequences }; } async function run(options: { @@ -175,6 +183,7 @@ async function run(options: { const control = harness({ withoutInterrupt: options.withoutInterrupt, restart: options.restart }); const appended: PrpEvent[] = []; const checkpoints: PersistedNativeSession[] = []; + const checkpointedAfter: number[] = []; let queued: Array<() => void> = []; const flushStreamingEvents = vi.fn(() => { const flushed = queued; @@ -194,7 +203,7 @@ async function run(options: { ...(options.restart ? { async recoverSession() { return { recovered: true, session: control.session }; } } : {}) }, controlPlane: { ...(options.pipelinesDeltas ? { pipelinesStreamingEvents: true, flushStreamingEvents } : {}), - async openRun() {}, async checkpointSession(value: PersistedNativeSession) { checkpoints.push(structuredClone(value)); }, + async openRun() {}, async checkpointSession(value: PersistedNativeSession) { checkpoints.push(structuredClone(value)); checkpointedAfter.push(appended.length); }, async appendEvent(value: PrpEvent) { appended.push(structuredClone(value)); if (options.pipelinesDeltas && value.eventType === "item.delta") await new Promise(resolve => queued.push(resolve)); @@ -216,7 +225,7 @@ async function run(options: { await options.after?.(control, appended); const outcome = await execution; return { outcome, returned, appended, completeRun, resolveMissingResult, interrupt: control.interrupt, flushStreamingEvents, - startTurn: control.startTurn, checkpoints, elapsedMs: Date.now() - started }; + startTurn: control.startTurn, checkpoints, checkpointedAfter, snapshotSequences: control.snapshotSequences, elapsedMs: Date.now() - started }; } const types = (events: PrpEvent[]) => events.map(value => value.eventType); @@ -231,6 +240,48 @@ describe("the controller consumer with provider-started turn sequences", () => { expect(outcome.interrupt).not.toHaveBeenCalled(); }); + const ordinaryTurn = () => [ + event("turn-1", "turn.started", { status: "inProgress" }), + event("turn-1", "item.completed", usage), + event("turn-1", "run.result.proposed", result as unknown as Record), + event("turn-1", "turn.completed", { status: "completed", error: null }), + ]; + const checkpointsAfter = (outcome: Awaited>, matches: (value: PrpEvent) => boolean) => { + const index = outcome.appended.findIndex(matches); + return outcome.checkpoints.filter((_value, at) => outcome.checkpointedAfter[at] === index + 1); + }; + + it("persists a checkpoint with the waiting shape right after the awaiting terminal", async () => { + const outcome = await run({ stream: turnOne(true), providerTurnWait: { capMs: 100 } }); + expect(checkpointsAfter(outcome, value => value.payload.awaitingProviderTurn === true)) + .toEqual([expect.objectContaining({ activeTurnId: null, awaitingProviderTurn: true })]); + }); + + it("persists a checkpoint naming a provider-started turn active right after its start", async () => { + const outcome = await run({ stream: [...turnOne(true), ...providerTurn("provider-1", { awaiting: true }), ...providerTurn("provider-2", { result: true })] }); + expect(outcome.outcome).toBe("finalized"); + for (const turnId of ["provider-1", "provider-2"]) { + expect(checkpointsAfter(outcome, value => value.turnId === turnId && value.eventType === "turn.started")) + .toEqual([expect.objectContaining({ activeTurnId: turnId })]); + } + }); + + it("asks for the snapshot as of the awaiting terminal and the provider start it has just appended", async () => { + const outcome = await run({ stream: [...turnOne(true), ...providerTurn("provider-1", { result: true })] }); + expect(outcome.outcome).toBe("finalized"); + const awaited = outcome.appended.find(value => value.payload.awaitingProviderTurn === true)!; + const started = outcome.appended.find(value => value.payload.origin === "provider")!; + expect(outcome.snapshotSequences.filter(value => value !== undefined)).toEqual([awaited.sourceSeq, started.sourceSeq]); + }); + + it("persists no checkpoint of either kind for a turn that does not await", async () => { + const outcome = await run({ stream: ordinaryTurn() }); + expect(outcome.outcome).toBe("finalized"); + const checkpointsWithoutProviderTurns = 4; + expect(outcome.checkpoints).toHaveLength(checkpointsWithoutProviderTurns); + expect(outcome.checkpoints.filter(value => value.awaitingProviderTurn || value.activeTurnId?.startsWith("provider-"))).toEqual([]); + }); + it("consumes the provider-started turn as the next turn of the same run and settles its result normally", async () => { const outcome = await run({ stream: [...turnOne(true), ...providerTurn("provider-1", { result: true })] }); expect(outcome.outcome).toBe("finalized"); @@ -595,6 +646,41 @@ describe("the controller consumer with provider-started turn sequences", () => { expect(second.returned).toMatchObject({ result, turnId: "provider-1" }); }); + it.each([true, false])("resumes a restored wait whose disposition marker is consumed instead of settling on that turn's earlier terminal (provider turn arrives: %s)", async (arrives) => { + const awaitedTurn = [ + event("turn-disposition", "turn.started", { status: "inProgress" }), + event("turn-disposition", "item.completed", usage), + event("turn-disposition", "turn.completed", { status: "completed", error: null, awaitingProviderTurn: true }), + ]; + const terminalTurns = [completedTerminal("turn-1"), completedTerminal("turn-disposition")]; + const waiting = { terminalTurns, semanticResult: null, awaitingProviderTurn: true, dispositionOnlyRecoveryConsumed: true, dispositionOnlyRecoveryTurnId: "turn-disposition" }; + const recovery = { checkpoint: { ...restartCheckpoint, ...waiting }, snapshot: waiting, replay: [...turnOne(false), ...awaitedTurn] }; + const turn = providerTurn("provider-1", { result: true }); + const outcome = await run({ + stream: [], restart: { recovery }, turnTimeoutMs: 10_000, + providerTurnWait: { startedAtMs: Date.now() - (arrives ? 599_000 : 599_700) }, + after: async (control) => { + if (!arrives) return; + await new Promise(resolve => setTimeout(resolve, 200)); + control.push(...turn); + }, + }); + expect(outcome.startTurn).not.toHaveBeenCalled(); + if (arrives) { + expect(outcome.outcome).toBe("finalized"); + expect(outcome.returned).toMatchObject({ result, turnId: "provider-1" }); + expect(outcome.resolveMissingResult).not.toHaveBeenCalled(); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(appendedOf(outcome.appended, turn)).toEqual(ids(turn)); + } else { + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).toHaveBeenCalledOnce(); + expect(outcome.resolveMissingResult).toHaveBeenCalledOnce(); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ turnId: "turn-disposition", + terminalEvent: expect.objectContaining({ eventType: "turn.completed", payload: expect.objectContaining({ awaitingProviderTurn: true }) }) })); + } + }); + it("fails the run as today when the Runner's stream ends during the wait", async () => { const outcome = await run({ stream: turnOne(true), providerTurnWait: { capMs: 60_000 }, diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.ts index 73f8aaf9ac0..218f2ab52dc 100644 --- a/packages/paperclip-runner/src/native-session-runtime.ts +++ b/packages/paperclip-runner/src/native-session-runtime.ts @@ -1193,6 +1193,7 @@ async function consumeTurn( supersededTerminal?: (event: PrpEvent, signal: AbortSignal) => Promise, providerTurnWaitOptions?: ProviderTurnWaitOptions, resumedProviderTurnWait?: PrpEvent, + checkpointProviderTurn?: (signal: AbortSignal, sourceSeq: number) => Promise, ) { let timer: ReturnType | undefined; const providerTurnWait = createProviderTurnWait({ @@ -1475,6 +1476,10 @@ async function consumeTurn( if (ended !== null) return ended; } providerTurnWait.observe(event); + if (event.eventType === "turn.started" && payload.origin === "provider") { + await checkpointProviderTurn?.(appendAbort.signal, event.sourceSeq); + appendAbort.signal.throwIfAborted(); + } const eventGoal = goalFromEvent(event); const goalChanged = eventGoal !== undefined && goalLifecycleFingerprint(eventGoal) !== goalLifecycleFingerprint(previousGoal); @@ -1696,7 +1701,11 @@ async function consumeTurn( }; } if (semanticResultProposal === null && governedResult === null && inputTimers.size === 0 && - awaitsProviderTurn(event) && providerTurnWait.begin(event)) continue; + awaitsProviderTurn(event) && providerTurnWait.begin(event)) { + await checkpointProviderTurn?.(appendAbort.signal, event.sourceSeq); + appendAbort.signal.throwIfAborted(); + continue; + } if (semanticResultProposal === null && governedResult === null && inputTimers.size === 0 && await resumeInterruptedTurn?.(event, appendAbort.signal)) continue; await settlePendingDeltas(); @@ -2933,8 +2942,8 @@ export async function executeNativeSession( if (reconciledRecoveryCheckpoint !== null) { await persistCheckpoint(reconciledRecoveryCheckpoint); } - const checkpoint = async (signal?: AbortSignal) => { - const snapshot = await session.snapshot(signal ? { signal } : undefined); + const checkpoint = async (signal?: AbortSignal, sourceSeq?: number) => { + const snapshot = await session.snapshot(signal ? { signal, ...(sourceSeq === undefined ? {} : { sourceSeq }) } : undefined); signal?.throwIfAborted(); await persistCheckpoint(snapshot, signal); return snapshot; @@ -3151,7 +3160,8 @@ export async function executeNativeSession( recovered && persistedSession?.dispositionOnlyRecoveryConsumed && !recoveredSnapshot.semanticResult && - !recoveredActiveTurnId, + !recoveredActiveTurnId && + recoveredSnapshot.awaitingProviderTurn !== true, ); const dispositionRecoveryTurnId = persistedSession?.dispositionOnlyRecoveryTurnId ?? @@ -3251,6 +3261,7 @@ export async function executeNativeSession( supersededByRestartContinuation, options.providerTurnWait, resumedProviderTurnWait, + checkpoint, ) : Promise.resolve({ event: recoveryTerminal, From 6ba46fd0802ec0fbeee0172ea75e3ead4e4db935 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:06:29 -0600 Subject: [PATCH 14/19] fix(github): read only the webhook secrets each delivery step uses (#21651) 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 > - Agents receive GitHub work through a GitHub App chat channel. GitHub sends each event as a signed webhook delivery. > - Each delivery passes three steps: durable staging, the durable replay worker, and the replayed request's preflight under the credential lease. > - Each step resolved every stored GitHub App secret. A GitHub App connection stores seven secrets, so each delivery decrypted and audited about 21 secrets. The steps use only the signing secret, the bound installation id and the App id. > - On our staging instance, these reads are now the largest source of secret reads and `secret_access_events` rows. > - This pull request makes each webhook step read only its own keys, and only when it needs them. > - The benefit is fewer vault reads and audit inserts per delivery, and the App private key and OAuth client secret stay sealed on the webhook path. ## Linked Issues or Issue Description Refs #21641 (fixed the other source: review-check polls now reuse cached installation tokens). **What happened?** On our staging instance (serving 163d9f323c), from 2026-11-14 20:23:52Z to 20:32Z, 32 `github_webhook_ingress` chat actions arrived. In the same window, `secret_access_events` recorded 97 resolutions of `credentials.webhookSecret`. It recorded the same count for `privateKey`, `appId`, `installationId`, `clientId`, `clientSecret` and `slug`. That is about 3 full credential resolutions per delivery, and about 21 audit rows per delivery (roughly 70–80 rows per minute). In the same window, 84 review-check polls caused no secret reads, because #21641 fixed that source. **What did you expect?** A delivery reads only the secrets it uses. An unsigned or forged delivery reads only the signing secret. **Steps to reproduce** 1. Configure a GitHub App chat endpoint. 2. Send one signed `issue_comment` delivery for the bound installation. 3. Count the new `secret_access_events` rows for the connection. Before this change, each stored key has 3 rows. A bad signature still reads every key once. The three call sites per delivery: 1. `server/src/services/chat-channels/github/webhook-ingress.ts` `stageGitHubWebhookIngress` (`resolveCredentialRefs` with all refs). 2. `server/src/services/chat-channels/github/webhook-ingress.ts` `processGitHubWebhookIngress` (`resolveCredentialRefs` with all refs, to re-sign the retained body). This was the unattributed third resolution. 3. `server/src/services/chat-channels/github/webhook-authentication.ts` preflight and ping (`resolveCredentials` with no key filter). ## What Changed - Added `githubCredentialRefsFor(refs, keys)` in the GitHub webhook ingress module. It selects the secret refs for named keys. - Staging reads `webhookSecret` first. After the signature holds, it reads `installationId` (only when the event names an installation and is not an `installation` event) and `appId` (it scopes the recovery-receipt denial query). - The replay worker reads `webhookSecret` to re-sign the body. It reads `appId`, `privateKey` and `installationId` only for a recovered delivery that needs a source recheck. - The preflight and ping read `webhookSecret` through the existing `resolveCredentials` key filter. The preflight reads `installationId` only after the signature holds and only for an event that names an installation. - The failed-delivery recovery scan reads only `appId`, `privateKey` and `installationId`. - Unchanged: the timing-safe compare, the credential-mutation lease, the re-read of current endpoint state under the lease, the status and fence checks, and the superseded-credential retry. No cache of decrypted values. - Per valid delivery, secret reads go from 7 keys × 3 (21 on staging) to 6: `webhookSecret` × 3, `installationId` × 2, `appId` × 1. A bad signature goes from all keys to 1 read. - `webhook-ingress.ts` was already above 1,000 lines. It grows by about 30 lines because the key selection belongs with the steps that use it. `chat-channels.integration.test.ts` holds the GitHub webhook fixtures, so the new test goes beside the existing signature tests. ## Verification - Red on master, green with this change: `pnpm exec vitest run server/src/__tests__/chat-channels.integration.test.ts -t "resolves only the secrets a"`. - `current`: before, `{webhookSecret: 3, installationId: 3, appId: 3, privateKey: 3}` (the fixture stores 4 keys). After, `{webhookSecret: 3, installationId: 2, appId: 1}`. - `invalid_signature`: before, every key once. After, `{webhookSecret: 1}`. - Regression: GitHub webhook, signature, rotation, ping, recovery, installation, paused and revoked tests in `chat-channels.integration.test.ts` (filter `-t "[Ww]ebhook|signature|rotat|[Pp]ing|recovery|installation|GitHub callback|revoked|paused"`): 304 passed, 1 failed. The failure is a Slack test (`materializes direct external-chat finals once…`, matched by the `ping` filter in "bookkeeping"). It passes when run alone, so it is a load flake and not related to this change. - `pnpm exec vitest run server/src/services/chat-channels/github/webhook-ingress.test.ts server/src/services/chat-github-provider-stress.test.ts server/src/services/chat-github-webhook-config.test.ts`: 105 passed. - `tsc --noEmit -p server/tsconfig.json`: passed. - `pnpm verify` selects 2,726 of 3,554 Vitest files for this change (the chat integration file pulls in a wide dependency set). I did not run that broad set locally. Required CI supplies that coverage for the final revision. ## Risks - Low risk. Each step reads a subset of the same refs from the same fenced record, so the values it uses do not change. - A missing `webhookSecret` ref still fails the signature check as before. A missing `installationId` ref still makes an installation-bearing event "ignored" as before. - The preflight now resolves `webhookSecret` and `installationId` in two reads under the same credential lease. The lease blocks credential mutation between them. - Installation lifecycle events (`installation-lifecycle.ts`) still resolve the full set, because they re-verify and re-persist all App credentials. They are rare. - No migration and no API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, run in Claude Code with tool use (shell, file edits, test execution) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../chat-channels.integration.test.ts | 39 +++++++++ .../github/webhook-authentication.ts | 14 ++- .../chat-channels/github/webhook-ingress.ts | 87 ++++++++++++++----- 3 files changed, 112 insertions(+), 28 deletions(-) diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index ff6ce27cc87..fe10f773b46 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -97,6 +97,7 @@ import { companyObservability } from "@paperclipai/db"; import * as runIdentityModule from "../services/run-identity.js"; import * as heartbeatModule from "../services/heartbeat.js"; import { chatGitHubRegistrations, chatGitHubReviews, chatGitHubConfigurations, toolCatalogEntries } from "@paperclipai/db"; +import { secretAccessEvents } from "@paperclipai/db"; import { AsyncLocalStorage } from "node:async_hooks"; import * as cloudRuntimeIdentity from "../services/cloud-runtime-identity.js"; import { @@ -6543,6 +6544,44 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { } } }); + it.each(["current", "invalid_signature"] as const)("resolves only the secrets a %s signed GitHub webhook delivery uses", async (kind) => { + const f = await reviewBotFixture(); + const [endpoint] = await readChatEndpointsById(f.endpoint.id); + const accessesBefore = new Set((await db.select({ id: secretAccessEvents.id }).from(secretAccessEvents) + .where(eq(secretAccessEvents.consumerId, endpoint.connectionId))).map(row => row.id)); + const delivery = randomUUID(); + const response = await f.service.handleWebhook(endpoint.publicId, "github", signedGitHubWebhookRequest({ + event: "issue_comment", delivery, webhookSecret: kind === "invalid_signature" ? "wrong-secret" : f.webhookSecret, + payload: { action: "created", installation: { id: 2468 }, + repository: { id: 97531, full_name: "paperclipai/paperclip", owner: { id: 1357, login: "paperclipai" } }, + issue: { number: 418 }, comment: { id: 41801, body: "Ordinary comment", user: { id: 42, login: "octocat" } }, sender: { id: 42, login: "octocat" } }, + })); + if (kind === "invalid_signature") expect(response.status).toBe(401); + else { + expect(response.status).toBeLessThan(300); + await expect.poll(async () => (await db.select({ status: chatActions.status }).from(chatActions).where(and( + eq(chatActions.endpointId, endpoint.id), eq(chatActions.providerActionId, `github_webhook_ingress:${delivery}`))))[0]?.status, + { timeout: 10_000 }).toBe("processed"); + } + const accesses = (await db.select({ id: secretAccessEvents.id, configPath: secretAccessEvents.configPath }).from(secretAccessEvents) + .where(eq(secretAccessEvents.consumerId, endpoint.connectionId))).filter(row => !accessesBefore.has(row.id)); + const reads: Record = {}; + for (const access of accesses) reads[access.configPath ?? "unknown"] = (reads[access.configPath ?? "unknown"] ?? 0) + 1; + // A delivery must never decrypt the App private key, OAuth client + // secret or other unused keys. Each step reads only what it uses: + // - durable staging verifies the provider signature (webhookSecret); + // once it holds, it rejects foreign installations (installationId) + // and scopes recovery-receipt denial to this App (appId); + // - the durable worker signs the retained body for internal replay + // (webhookSecret); + // - the replayed request re-authenticates under the credential lease + // against the current secret and installation (webhookSecret, + // installationId). + // A bad signature stops after the one webhookSecret read. + expect(reads).toEqual(kind === "invalid_signature" + ? { "credentials.webhookSecret": 1 } + : { "credentials.webhookSecret": 3, "credentials.installationId": 2, "credentials.appId": 1 }); + }); it("stack rejects forged raw gateway deliveries without changing verification or waking an agent", async () => { const f = await reviewBotFixture(); await db diff --git a/server/src/services/chat-channels/github/webhook-authentication.ts b/server/src/services/chat-channels/github/webhook-authentication.ts index d393306d084..ec94f94f416 100644 --- a/server/src/services/chat-channels/github/webhook-authentication.ts +++ b/server/src/services/chat-channels/github/webhook-authentication.ts @@ -117,7 +117,7 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio ) ) return false; - const credentials = await resolveCredentials(current.endpoint); + const credentials = await resolveCredentials(current.endpoint, undefined, ["webhookSecret"]); const expected = `sha256=${createHmac("sha256", credentials.webhookSecret).update(body).digest("hex")}`; let valid = false; try { @@ -182,7 +182,9 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio ) { return "ignored"; } - const credentials = await resolveCredentials(current.endpoint); + // Read only the signing secret until the signature holds; the bound + // installation is read below only for events that name one. + const credentials = await resolveCredentials(current.endpoint, undefined, ["webhookSecret"]); const expected = `sha256=${createHmac("sha256", credentials.webhookSecret).update(body).digest("hex")}`; let signatureValid = false; try { @@ -209,9 +211,13 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio const lifecycleEvent = ["github_app_authorization", "installation", "installation_repositories"].includes(eventType ?? ""); if (payload) { const incomingInstallationId = payload.installation?.id; + const boundInstallationId = + incomingInstallationId !== undefined && eventType !== "installation" + ? (await resolveCredentials(current.endpoint, undefined, ["installationId"])).installationId + : undefined; if ( incomingInstallationId !== undefined && - String(incomingInstallationId) !== credentials.installationId && + String(incomingInstallationId) !== boundInstallationId && eventType !== "installation" ) { // A dedicated endpoint represents exactly one GitHub App @@ -231,7 +237,7 @@ export function createGitHubWebhookAuthentication(db: Db, options: Authenticatio if (!current.endpoint.setup.webhookVerifiedAt && ["active", "verifying", "attention"].includes(current.endpoint.status) && incomingInstallationId !== undefined && - String(incomingInstallationId) === credentials.installationId && + String(incomingInstallationId) === boundInstallationId && !lifecycleEvent) { await recordVerifiedWebhook(current.endpoint, credentialLease, inspection.headers.get("x-github-delivery")); } diff --git a/server/src/services/chat-channels/github/webhook-ingress.ts b/server/src/services/chat-channels/github/webhook-ingress.ts index e186b468a9a..1252528c7c6 100644 --- a/server/src/services/chat-channels/github/webhook-ingress.ts +++ b/server/src/services/chat-channels/github/webhook-ingress.ts @@ -133,6 +133,22 @@ export function githubWebhookIngressPayload( return payload as GitHubWebhookIngressPayload; } +/** + * Every resolved secret is a vault read plus an access-audit row, and a GitHub + * App connection stores seven of them. Webhook steps read only the keys they + * use; the App private key and OAuth client secret stay sealed on this path. + */ +export function githubCredentialRefsFor( + refs: ToolCredentialSecretRef[], + keys: readonly string[], +): ToolCredentialSecretRef[] { + return refs.filter((ref) => + keys.includes(ref.configPath.replace(/^credentials\./, "")), + ); +} + +const GITHUB_APP_TOKEN_KEYS = ["appId", "privateKey", "installationId"] as const; + export function redactedGitHubWebhookIngressPayload( payload: GitHubWebhookIngressPayload, ): RedactedGitHubWebhookIngressPayload { @@ -258,34 +274,31 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress return { kind: "ignored" }; } const context = runtimeContextForRecord(record); - let credentials: Record; - try { - credentials = await resolveCredentialRefs( - record.endpoint, - record.credentialSecretRefs, - ); - } catch (error) { + const credentialsSuperseded = async () => { const latest = await endpointRecord(endpoint.id); - if ( - latest && + return ( + latest !== null && (runtimeGeneration(latest.endpoint.setup) !== context.generation || credentialFingerprint(latest.credentialSecretRefs) !== context.credentialFingerprint) - ) { - continue; - } + ); + }; + const resolveKeys = (keys: readonly string[]) => + resolveCredentialRefs( + record.endpoint, + githubCredentialRefsFor(record.credentialSecretRefs, keys), + ); + let credentials: Record; + try { + // Unsigned or forged traffic must not decrypt anything beyond the + // signing secret. + credentials = await resolveKeys(["webhookSecret"]); + } catch (error) { + if (await credentialsSuperseded()) continue; throw error; } if (!githubSignatureIsValid(body, signature, credentials.webhookSecret)) { - const latest = await endpointRecord(endpoint.id); - if ( - latest && - (runtimeGeneration(latest.endpoint.setup) !== context.generation || - credentialFingerprint(latest.credentialSecretRefs) !== - context.credentialFingerprint) - ) { - continue; - } + if (await credentialsSuperseded()) continue; return { kind: "invalid_signature" }; } @@ -296,6 +309,21 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress ? (parsedPayload as { installation?: { id?: unknown } }).installation ?.id : undefined; + try { + // A signed event that names an installation is checked against the + // bound one; the App id scopes the recovery-receipt denial below. + Object.assign( + credentials, + await resolveKeys( + incomingInstallationId !== undefined && eventType !== "installation" + ? ["installationId", "appId"] + : ["appId"], + ), + ); + } catch (error) { + if (await credentialsSuperseded()) continue; + throw error; + } if ( incomingInstallationId !== undefined && String(incomingInstallationId) !== credentials.installationId && @@ -817,9 +845,11 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress } try { + // Replay re-signs the retained body for internal authentication. Only a + // recovered delivery also needs an App token to recheck its source. const credentials = await resolveCredentialRefs( record.endpoint, - record.credentialSecretRefs, + githubCredentialRefsFor(record.credentialSecretRefs, ["webhookSecret"]), ); const recovery = await db .select({ payload: chatActions.payload, status: chatActions.status }) @@ -840,7 +870,13 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress (recovery.status === "cancelled" || !(await githubRecoverySourceIsCurrent( (recovery.payload as GitHubRecoveryReceipt).original, - credentials, + await resolveCredentialRefs( + record.endpoint, + githubCredentialRefsFor( + record.credentialSecretRefs, + GITHUB_APP_TOKEN_KEYS, + ), + ), ))) ) { await settleGitHubWebhookIngress(action.id, { @@ -1217,7 +1253,10 @@ export function createGitHubWebhookIngress(db: Db, options: GitHubWebhookIngress } const credentials = await resolveCredentialRefs( record.endpoint, - record.credentialSecretRefs, + githubCredentialRefsFor( + record.credentialSecretRefs, + GITHUB_APP_TOKEN_KEYS, + ), ); if (credentials.appId !== window.appId || !credentials.installationId) return; From 0ab73d4e3004572e3a2debcb4bf7e76e57c56dd6 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 14 Nov 2026 13:10:20 -0800 Subject: [PATCH 15/19] feat(native-runtime): ask the Runner for provider-started turns on native ACPX Claude runs (#21456) 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. > - Core runs Claude Code through Paperclip Runner. Claude can start a shell command in the background and end its turn. When the command finishes, Claude Code starts a cycle of its own to continue. > - Today the run ends when the turn ends. The command stops, and the run fails with `native_finalization_missing`. > - The Runner can keep Claude while a background shell is running and give the cycle of Claude to the controller as a turn that the provider started. Core can wait for that turn. The transport can ask for it (#21607), and a controller restart during it is safe (#21612). > - No run does this yet, because Core does not ask the Runner for it. > - This pull request makes the native runtime of Core ask, for ACPX Claude. It is the only part that changes what a production run does. > - The benefit is the goal of the whole work: a run with a background command that is still running continues when the command finishes, and does not fail with `native_finalization_missing`. ## Linked Issues or Issue Description No public issue exists. The issue is described here. This pull request turned the behavior on and had grown too large to review. It is now three stacked pull requests: 1. #21607 (merged): the transport can ask the Runner for provider-started turns. No caller asks. 2. #21612: the recovery after a controller restart during a wait or during a provider-started turn. 3. **This pull request:** Core sets the option for native ACPX Claude runs. This is part 3. Its base branch is `fix/provider-turn-restart-recovery`. Refs #19912 (design). **What existing behavior does this improve?** What a native ACPX Claude run does after a turn that ends with no result while a background command is still running. **Subsystem affected** Core, the native runtime: `server/src/services/native-runtime/native-session-executor.ts` and `native-provider-turn-wait.ts`. ACPX Claude only. **Current behavior** - The run ends at the end of the turn. The Runner restarts Claude, the background command stops, and the run fails with `native_finalization_missing`. **Proposed behavior** - The native runtime sets `providerStartedTurns: true` in the transport options for ACPX Claude, at the two places that build those options. One function, `nativeProviderStartedTurns`, decides this and also decides if the consumer gets the wait options, so the two cannot be different. - A turn that ends with no result while a background command is still running now waits, for a maximum of 10 minutes, for the turn that Claude starts by itself. That turn is consumed as the next turn of the same run, and its result settles the run. - Other providers and other ACPX agents do the same as today. - Limit of the Runner (see #21421): after a follow-up turn, the Runner waits again only while a background command is still running. A command that finishes while Claude reports on an earlier command gets no follow-up. **Reason and benefit** - The opt-in is in the last part, so each earlier part can merge with no change for a production run. ## What Changed - `server/src/services/native-runtime/native-provider-turn-wait.ts` (5 lines added, 1 removed): `nativeProviderStartedTurns`. - `server/src/services/native-runtime/native-session-executor.ts` (4 added, 2 removed): the option at the two places that build the transport options, and the same function for the wait options. - `server/src/services/native-runtime/native-session-executor.test.ts` (4 added, 2 removed): the two native paths set the option for ACPX Claude and not for other providers. ## State saved by the previous release - No persisted state changes in this part. - **A Runner that does not know the field** ignores it, and the run does the same as today. - **A deploy during a run:** a turn that started before the deploy has no opt-in and ends as today. The next turn has the opt-in. - **Rollback of Core:** the previous Core does not set the option, so the Runner does not wait. ## Verification The items below were run on the tree that was verified before the split into three parts (commit `1b15ded1c4` has that tree, byte for byte). The head of this branch (`23e2c13ad3`) is that commit on the new head of #21612; its three server files are the same. - `pnpm typecheck` and `node scripts/verify-runner-vendor-dependencies.mjs` in `server`; `npx tsc --noEmit -p tsconfig.json`, `npx tsc --noEmit -p tsconfig.test.json`, `pnpm run typecheck:typescript` and `pnpm run build:typescript` in `packages/paperclip-runner`: all passed. - `server/src/services/native-runtime/native-session-executor.test.ts` and `native-runner-restart-recovery.integration.test.ts`: 1,732 passed, 21 skipped. - The end-to-end behavior is tested in parts 1 and 2 with the real `paperclip-runnerd`, where the test sets the option in the way that this part does. - Live run with a real Claude account, not in CI, at the adapter level of the Runner (see #21316): the cycle of Claude was given as a turn with its own usage, and each Paperclip tool call was admitted. Not run: a live run through Core, `paperclip-runnerd` and the real sidecar with a real Claude account (that path needs an API key, not a local sign-in); a remote sandbox; the full suite. CI supplies the broad coverage. ## Risks - **This part turns the behavior on for each native ACPX Claude run.** A run with no background command is not changed: the Runner waits only when a shell is still running at the end of a turn that has no result. - **This part must not merge before #21612.** Without #21612, a controller restart during a wait or during a provider-started turn fails the run. - **A run can now stay open up to 10 minutes longer** when the background command does not finish or Claude does not start a turn. The agent computer stays active for that time. - **A waiting run can show as "suspicious" after 5 minutes of silence** in the run watchdog. The watchdog only labels a native run; it does not stop it. - **Follow-ups that the Runner cannot wait for are lost,** as the limit above says. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change and the split, reviewed the diff, and ran a part of the verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), wrote the change and the tests. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5.2 --- .../services/native-runtime/native-provider-turn-wait.ts | 6 +++++- .../services/native-runtime/native-session-executor.test.ts | 6 ++++-- .../src/services/native-runtime/native-session-executor.ts | 6 ++++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/server/src/services/native-runtime/native-provider-turn-wait.ts b/server/src/services/native-runtime/native-provider-turn-wait.ts index d933ac46589..1e0e8e136f4 100644 --- a/server/src/services/native-runtime/native-provider-turn-wait.ts +++ b/server/src/services/native-runtime/native-provider-turn-wait.ts @@ -3,7 +3,7 @@ import { agentWakeupRequests, heartbeatRunEvents, heartbeatRuns, issueComments, import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../delivery-work-notifications.js"; -import type { ProviderTurnWaitOptions } from "../../vendor/paperclip-runner/index.js"; +import type { NativeExecutionInput, ProviderTurnWaitOptions } from "../../vendor/paperclip-runner/index.js"; type NativeRunScope = { companyId: string; runId: string; issueId: string; agentId: string }; @@ -101,6 +101,10 @@ export function awaitPersonCommentDuringNativeRun(db: Db, scope: NativeRunScope, }); } +export function nativeProviderStartedTurns(provider: NativeExecutionInput["provider"]) { + return provider.kind === "acpx" && provider.agent === "claude"; +} + export async function nativeProviderTurnWaitOptions(db: Db, scope: NativeRunScope): Promise { return { startedAtMs: await nativeProviderTurnWaitStartedAt(db, scope), 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 cb08e585392..685c85c9f8b 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -17325,7 +17325,7 @@ describe("runnerd provider runtime wiring", () => { state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ provider: "acpx", acpxAgent: "claude", acpxPermissionMode: "approve-all", - acpxPermissionModePinned: true, claudeEffort: "high", homeMode, + acpxPermissionModePinned: true, claudeEffort: "high", homeMode, providerStartedTurns: true, }); }); @@ -17346,6 +17346,7 @@ describe("runnerd provider runtime wiring", () => { provider: "acpx", acpxAgent: "grok", acpxPermissionMode: "approve-all", acpxPermissionModePinned: true, grokEffort: "high", grokDisableWebSearch: disableWebSearch, homeMode, }); + expect(state.createTransport.mock.calls.at(-1)![0]).not.toHaveProperty("providerStartedTurns"); }); it("requires explicit Grok credentials before v10 daemon startup", async () => { @@ -18894,7 +18895,8 @@ describe("runnerd provider runtime wiring", () => { expect(owner.mock.results.at(-1)!.value.credentialsUpdated).toHaveBeenCalledWith(notification); expect(options).toMatchObject({ ...driver, runnerArtifact: { version: "fixture" }, prpIdentity: { environmentLeaseId: "plugin-task-lease" } }); - if (kind === "acpx") expect(options).toMatchObject({ acpxAgent: "claude", claudeEffort: "high" }); + if (kind === "acpx") expect(options).toMatchObject({ acpxAgent: "claude", claudeEffort: "high", providerStartedTurns: true }); + else expect(options).not.toHaveProperty("providerStartedTurns"); for (const key of ["environment", "codexCommand", "codexArgs", "runnerRuntimePaths", "readRunnerState", "archiveExternalRunnerState"]) { expect(options).not.toHaveProperty(key); } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 914ceded34a..7dfc7a616ad 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -31,7 +31,7 @@ import { prepareRemoteOpenCodeArtifacts, type OpenCodeLaunchArtifacts } from "./ import { prepareRuntimeContextSource, rehydratePinnedInstructionAsset } from "./runtime-context.js"; import { createNativeUsageDelivery } from "./native-usage-delivery.js"; import { createNativeRecoveryUsageDelivery } from "./native-recovery-usage-delivery.js"; -import { nativeProviderTurnWaitOptions } from "./native-provider-turn-wait.js"; +import { nativeProviderStartedTurns, nativeProviderTurnWaitOptions } from "./native-provider-turn-wait.js"; import { createNativeTurnAccounting, NATIVE_LOST_TURN_USAGE_EVIDENCE, nativeUsageCostUsd, nativeUsageBiller, normalizeNativeUsage, usesNativeUsageDelivery, isNativeUsageAccountingEvent, isNativeUsageDeliveryEvent } from "./native-usage-accounting.js"; import { crashPoint } from "@paperclipai/shared/crash-points"; export { nativeUsageCostUsd, nativeUsageBiller, normalizeNativeUsage } from "./native-usage-accounting.js"; @@ -12412,7 +12412,7 @@ async function executePaperclipNativeSessionAttempt( startedAtMs: nativeSessionExecuteStartedAtMs, }); trace.activate(runnerSessionStartupScope); - const providerTurnWait = input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude" + const providerTurnWait = nativeProviderStartedTurns(input.execution.provider) ? await nativeProviderTurnWaitOptions(input.db, input.execution.binding) : undefined; const runExecution = () => executeNativeSession({ @@ -16724,6 +16724,7 @@ async function createRunnerdBackendWithinSessionClaim( grokEffort: "grokEffort" in provider ? provider.grokEffort : undefined, grokDisableWebSearch: "grokDisableWebSearch" in provider ? provider.grokDisableWebSearch : undefined, acpxPermissionModePinned: true } : {}), + ...(nativeProviderStartedTurns(provider) ? { providerStartedTurns: true } : {}), ...(provider.kind === "opencode" ? { opencodePermissionMode: provider.permissionMode } : {}), runnerReconnectGraceMs: REMOTE_RUNNER_RECONNECT_GRACE_MS, runnerProcessReconnectGraceMs: null, lifecyclePolicy: input.execution.session.lifecyclePolicy, @@ -18481,6 +18482,7 @@ async function createRunnerdBackendWithinSessionClaim( ), } : {}), + ...(nativeProviderStartedTurns(input.execution.provider) ? { providerStartedTurns: true } : {}), ...(input.execution.provider.kind === "cursor_cloud" ? { cursorCloud: input.execution.provider.cursorCloud } : {}), ...(input.execution.provider.kind === "opencode" ? { From ecdeed5e7ec736f2bf5a8ac1985d171c511fcb11 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:16:43 -0600 Subject: [PATCH 16/19] perf(ui): open a task restored from the saved read cache through the chat bootstrap (#21650) 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 board UI opens a task page as a chat. A hard load of a task URL starts one chat bootstrap request before the app's JavaScript runs. > - A returning browser also restores a saved read cache from local storage. This cache holds the core fields of recently opened tasks, but no chat history. > - The task page started the bootstrap only when the core task was not cached. A restored core task skipped it. The early bootstrap request ran, but nothing used its answer. > - So every first-frame read went to its own endpoint, and the comment input facts waited for the recent comments. A returning load was slower than a cold load: on staging, 3.6–3.8 s against 1.9–2.4 s. > - This pull request treats a task that only the saved cache holds as cold for the chat. The page adopts the bootstrap, the restored task's own revalidation shares it, and the answer replaces the restored data. > - The benefit is that a returning load is now faster than a cold load, not slower. ## Linked Issues or Issue Description **Describe the bug** A hard load of a task page is slower when the browser has a saved read cache than when it has none. Measured on staging on 2026-11-14 (hard load, JavaScript in the HTTP cache, 3 alternating pairs on one task): saved cache cleared 1.9–2.4 s, saved cache present 3.6–3.8 s, until the chat composer exists. **Steps to reproduce** 1. Open a task page so that the saved read cache (`paperclip:query-cache:v1:*`) holds it. 2. Close the tab and open the same task URL again. 3. Compare the time to the first chat frame with a load where the saved read cache is cleared. **Expected behavior** A load with a saved read cache is at least as fast as a load without one. The chat's first-frame reads share the one bootstrap request. **Actual behavior** With a saved read cache, the bootstrap request runs but its answer is not used. About 16 more per-endpoint reads run before the frame, and the frame waits for a second, serial wave of reads. Related: #20355 (chat bootstrap endpoints), #20592 (cold task open from one bootstrap), #20591 and #20594 (returning Mine inbox from the saved read cache), #21557 (cold-load perf spec). ## What Changed - `ui/src/lib/persisted-query-cache.ts`: records which queries a page restored from the saved read cache. `isRestoredSavedRead(client, key)` is true until a read or a local write in this page replaces that data. - `ui/src/pages/IssueDetail.tsx`: starts (or adopts) the chat bootstrap when the core task is missing or only restored. It passes the restored task's id and identifier as aliases, so reads keyed by the id share the request while it loads. - `ui/src/lib/issue-chat-bootstrap.ts`: `readFromIssueChatBootstrap` lets a key that holds only restored data share the bootstrap, like an empty key. `startIssueChatBootstrap` accepts aliases. - `ui/src/lib/issueChatBootstrapCache.ts` and `ui/src/lib/issueDetailCache.ts`: the bootstrap answer replaces restored data (core task under every ref). The restored core task's revalidation shares the bootstrap. A core task that was read in this page keeps its own small read. - `ui/src/hooks/useIssuePlanDocument.ts`: the first plan read shares the bootstrap's plan projection instead of reading `documents/plan` before the frame. - `tests/perf/issue-detail/cold-bootstrap.perf.spec.ts`: an always-on request-shape test for a returning load with a saved read cache, and an opt-in benchmark of alternating pairs (saved cache present and cleared). The harness now clears storage after the warm-up page closes, because closing the app saves its read cache again. - `ui/src/lib/restored-task-chat-bootstrap.test.ts`: unit tests for the restore-then-bootstrap path. - `tests/perf/issue-detail/README.md`: documents the returning-load test and benchmark. ## Verification Local production build (`PAPERCLIP_UI_DEV_MIDDLEWARE=false`), local_trusted instance, CDP delay of 300 ms on every API request, fresh browser context per run, JavaScript in the HTTP cache. Time from navigation start to the revealed history with the latest message and an editable composer. | Build | Saved read cache | Runs | Median | Spread | API requests before frame | Frame released by | | --- | --- | ---: | ---: | ---: | ---: | --- | | master `95a6ab31e6` | cleared | 5 | 913 ms | 908–957 | 33 | company list (shell stage 2) | | master `95a6ab31e6` | present | 5 | 1,204 ms | 1,178–1,215 | 49 | `activity?view=comment-inputs` (serial second wave) | | this PR | cleared | 7 | 942 ms | 925–997 | 35 | company list (shell stage 2) | | this PR | present | 7 | 573 ms | 566–658 | 37 | app boot and route mount (all task data is the bootstrap) | - Paired delta with this PR (present − cleared): median −376 ms over 7 pairs, all negative (−267 to −400). On master it was +292 ms over 5 pairs, all positive. - With an 800 ms API delay (this PR, 5 pairs): present 890 ms, released by the bootstrap response; cleared 1,910 ms. - Cold load with no app storage (existing benchmark, 7 runs): master 910 ms, this PR 939 ms. The host load average was about 20 during the PR run (other work on the machine). Requests before the frame are 35 in both. I make no claim of a cold change. - Request-shape tests (`cold-bootstrap.perf.spec.ts`): the new returning-load test fails on master (the timeline shows `?view=core`, `recent-comments`, `activity`, `runs`, `interactions`, `attachments`, `live-runs` before the frame) and passes with this PR. The existing cold test passes. - Unit tests: `restored-task-chat-bootstrap.test.ts` has 10 cases. With the behavior changes reverted (the restore marker kept so the file imports), 3 fail: the bootstrap refreshes the restored task and fills the chat, id-keyed reads share the loading bootstrap, and a partial answer. All 10 pass with this PR. The other 7 cases are guards that hold on both: a stale refresh reads the server, a failed bootstrap falls back, a 403 removes the restored task from memory and storage, another company's answer is not seeded, an answer is not used after another user signs in, and another user's saved task is not restored. - Focused Vitest: 27 files that use the changed modules, including `IssueDetail.test.tsx` and `TaskChatThread.test.tsx`: 1,208 passed. - Browser layout journeys against the PR build: `layout-stability.spec.ts` and `plan-startup.spec.ts`, 17 of 17 passed (reveal order, reading anchor, older history, Back, comment links, drafts during background refresh, failed and stalled reads with Retry, plan projection with stalled plan reads). - `pnpm verify` exit 2 (the README is a global CI input), so required CI supplies the broad coverage. Commands: ```sh cd ui && npx vitest run src/lib/restored-task-chat-bootstrap.test.ts PAPERCLIP_ISSUE_PERF_BASE_URL=http://127.0.0.1: pnpm exec playwright test --config tests/perf/issue-detail/playwright.config.ts cold-bootstrap PAPERCLIP_ISSUE_PERF_BASE_URL=http://127.0.0.1: PAPERCLIP_ISSUE_PERF_COLD_RUNS=7 pnpm exec playwright test --config tests/perf/issue-detail/playwright.config.ts cold-bootstrap -g returning ``` ## Risks - Low risk. The change only affects data that the saved read cache restored and that no read in this page has confirmed. Data read in this page keeps the old rule: a refresh asks the server. - The saved read cache content is unchanged. It still excludes comments and bootstrap payloads, so the first chat frame still needs one response (the bootstrap). It cannot appear before any task response without saving chat history, which the documented allowlist excludes. - If the bootstrap fails, stalls or omits the task, each read falls back to its own request, as on a cold load. A 403 or 404 on the restored task's fallback read removes it from memory and storage, as before. - Account changes: a bootstrap answer is bound to the session's user, as before. The saved cache restores data only for the same user. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, browser automation through Playwright). ## 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 --- tests/perf/issue-detail/README.md | 20 ++ .../issue-detail/cold-bootstrap.perf.spec.ts | 120 +++++++++- ui/src/hooks/useIssuePlanDocument.ts | 14 +- ui/src/lib/issue-chat-bootstrap.ts | 20 +- ui/src/lib/issueChatBootstrapCache.ts | 9 +- ui/src/lib/issueDetailCache.ts | 14 +- ui/src/lib/persisted-query-cache.ts | 19 ++ .../lib/restored-task-chat-bootstrap.test.ts | 212 ++++++++++++++++++ ui/src/pages/IssueDetail.tsx | 12 +- 9 files changed, 416 insertions(+), 24 deletions(-) create mode 100644 ui/src/lib/restored-task-chat-bootstrap.test.ts diff --git a/tests/perf/issue-detail/README.md b/tests/perf/issue-detail/README.md index 20c3c29fb47..87a1a6ad810 100644 --- a/tests/perf/issue-detail/README.md +++ b/tests/perf/issue-detail/README.md @@ -85,6 +85,26 @@ changes the delay. `PAPERCLIP_ISSUE_PERF_COLD_HTTP_CACHE=1` downloads the JavaScript on every run. Serve a production build (`PAPERCLIP_UI_DEV_MIDDLEWARE=false`). +### Returning direct task load (saved read cache) + +A returning browser restores the saved read cache (`paperclip:query-cache:v1:*`) +before the first render, including the core fields of recently opened tasks. +Chat history is never saved, so the restored task's chat still reads the +bootstrap. Its reads, including the restored task's own revalidation and its +plan projection, share that one request instead of reading each endpoint. +The always-on request-shape test checks this with a saved cache. The opt-in +benchmark runs alternating pairs with the saved read cache present and +cleared (other app storage kept) and writes `returning-task-