From b9cf64f5bf88f66f02e695f8f7bc326e004961ba Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:15:45 -0600 Subject: [PATCH 01/20] test(server): check the agent row lock with FOR SHARE so lock checks cannot block each other (#21775) 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 > - Each master commit must pass Cloud readiness before its canary and image publish > - `agent-file-restore-locking.test.ts`, added in #21694, failed master Cloud readiness run 43712563988 on 2026-11-15, so that commit's canary did not publish > - The test reported the agent row as locked during the download, but its own sampler measured 0 ms of product lock time > - The cause is in the test: its two lock checks used `FOR UPDATE NOWAIT` on one pool and could block each other > - This pull request checks the lock with `FOR SHARE NOWAIT`, which still detects the product's `FOR UPDATE` but never conflicts with another check > - The benefit is that the test fails only when the product really holds the lock ## Linked Issues or Issue Description **What happened?** `downloads a stale projection without holding the agent row lock` failed in master Cloud readiness run 43712563988, attempt 2: `expected [{ objectKey, agentRowLocked: true }] to deeply equal [{ objectKey, agentRowLocked: false }]`. The test's metric line showed `lockedMs: 0`. **Steps to reproduce** 1. Make each sampler check hold its `FOR UPDATE NOWAIT` lock for 50 ms (to make the overlap certain). 2. Run `pnpm exec vitest run src/__tests__/agent-file-restore-locking.test.ts -t "stale projection"` in `server/`. 3. The test fails 3 of 3 times with `agentRowLocked: true` and `lockedMs: 0`, the same as CI. **Expected behavior** Only a lock held by the product makes the check report "locked". Refs #21694 ## What Changed - `agentRowLocked()` uses `FOR SHARE NOWAIT` instead of `FOR UPDATE NOWAIT`. The product takes `FOR UPDATE` on this row (`agent-file-store.ts`, `agent-instruction-revisions.ts`), which conflicts with `FOR SHARE`. Two `FOR SHARE` checks do not conflict. - New test: three concurrent checks all report unlocked, a `FOR UPDATE` held on another connection is reported locked, and the row reads unlocked again after release. ## Verification - Red: with the forced 50 ms overlap and the old `FOR UPDATE` probe, the test failed 3 of 3 runs with the CI error. - Green: with the same forced overlap and `FOR SHARE`, 4 of 4 tests passed in 3 of 3 runs. - Final file (no forced overlap): `pnpm exec vitest run src/__tests__/agent-file-restore-locking.test.ts` in `server/`: 5 of 5 tests passed in 5 of 5 runs. ## Risks - Low risk. Test-only change. The new test makes sure the check still detects a real `FOR UPDATE` lock. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] 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 --- .../agent-file-restore-locking.test.ts | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/agent-file-restore-locking.test.ts b/server/src/__tests__/agent-file-restore-locking.test.ts index e804283d0d3..b37a54e7bf8 100644 --- a/server/src/__tests__/agent-file-restore-locking.test.ts +++ b/server/src/__tests__/agent-file-restore-locking.test.ts @@ -47,9 +47,10 @@ describe("agent file restore locking", () => { const board = () => ({ type: "board" as const, userId, source: "session" as const }); const target = () => ({ companyId, agentId }); + const lockCheckQuery = () => sql`select id from agents where id = ${agentId} for share nowait`; async function agentRowLocked(): Promise { try { - await observer.transaction(async tx => { await tx.execute(sql`select id from agents where id = ${agentId} for update nowait`); }); + await observer.transaction(async tx => { await tx.execute(lockCheckQuery()); }); return false; } catch (error) { const code = (error as { code?: string; cause?: { code?: string } }).code ?? (error as { cause?: { code?: string } }).cause?.code; @@ -106,6 +107,30 @@ describe("agent file restore locking", () => { await fs.rm(home, { recursive: true, force: true }); }); + async function whileHolding(lock: (tx: Parameters[0]>[0]) => Promise, check: () => Promise) { + let release!: () => void; + const released = new Promise(resolve => { release = resolve; }); + let holding!: () => void; + const held = new Promise(resolve => { holding = resolve; }); + const holder = db.transaction(async tx => { await lock(tx); holding(); await released; }); + await Promise.race([held, holder]); + try { await check(); } finally { release(); } + await holder; + } + + it("a lock check does not block another lock check", async () => { + await whileHolding(tx => tx.execute(lockCheckQuery()), async () => { + expect(await agentRowLocked()).toBe(false); + }); + }); + + it("a lock check detects the product's agent row lock", async () => { + await whileHolding(tx => tx.select().from(agents).where(eq(agents.id, agentId)).for("update"), async () => { + expect(await agentRowLocked()).toBe(true); + }); + expect(await agentRowLocked()).toBe(false); + }); + it("downloads a stale projection without holding the agent row lock", async () => { await loseLocalProjection(); objects.probe = agentRowLocked; From 2b23119ed25536f8f5d69d521b1cbd463fc26ad8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:19:23 -0600 Subject: [PATCH 02/20] fix(native): keep a warm follow-up that inherited its predecessor's process identity waiting on the same run (#21774) 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. A warm agent session stays with the outgoing server that ran its last turn. > - #21697 makes a follow-up wait while that outgoing server is still alive, instead of starting a second Runner over its session. > - Runtime selection copies the warm predecessor's process fields (`processPid`, `processGroupId`, `processStartedAt`) onto the follow-up and records `inheritedProcessIdentityRunId`. > - The wait records itself with `deferNativeControllerRecovery`. That function refused any run with process fields, so it refused every warm follow-up that the wait stopped. The run failed with `native_controller_recovery_wait_authority_changed`. > - This pull request lets the deferral accept an inherited identity, and clears those inherited fields in the same transaction so the usual resumption claim can pick the run up. > - The benefit is that a warm follow-up in a deploy overlap stays on the same run and does not fail. ## Linked Issues or Issue Description Refs #21697 **What happened?** In a zero-downtime release-swap test, a follow-up comment arrived 0.25 s after its predecessor finished on the outgoing server. The follow-up run started on the incoming server 1.09 s later. `waitForLiveWarmSessionOwner` found the outgoing server alive and asked to wait. `deferNativeControllerRecovery` then refused with `native_controller_recovery_wait_authority_changed`, because the run carried the process fields that runtime selection copied from its warm predecessor. The run failed after 2.7 s with `native_continuation_requires_reconciliation`. Held recovery started a fresh run. The task finished, but the run history shows one failed run. **Expected behavior** A warm follow-up whose only process identity is inherited from its predecessor waits on the same run. The resumption owner claims it at the deadline. A run whose own process has started is still refused. **Steps to reproduce** 1. Run a warm remote agent turn on server A. 2. Switch new run starts to server B while A still serves. 3. Post a follow-up within about 1 s of the turn's finish. 4. The follow-up fails with `native_controller_recovery_wait_authority_changed`. ## What Changed - `server/src/services/native-runtime/native-controller-recovery.ts` (`deferNativeControllerRecovery`): - Process fields refuse the deferral only when they are the run's own. Fields count as inherited when `runnerProfileJson.inheritedProcessIdentityRunId` is set and the run has no own `native.process_start_requested` or `native.process_identity_recorded` event. `run-cost-accounting.ts` uses the same proof. - With an inherited identity, the same transaction clears `processPid`, `processGroupId` and `processStartedAt`. It keeps `inheritedProcessIdentityRunId`. `claimNativeSessionResumptions` requires those fields to be null. - `server/src/services/native-runtime/native-controller-recovery.integration.test.ts` (real Postgres): - New: "keeps a warm follow-up that inherited its predecessor's process identity on the same run until the outgoing owner's deadline". - Two new cases in "does not publish an admission wait after authority changes": `own-process` (process fields, no marker) and `inherited-then-own-process` (marker plus an own process-start event). Both stay refused and keep their fields. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-controller-recovery.integration.test.ts -t "inherited its predecessor|does not publish an admission wait|unstarted follow-up"`: 9 passed. - Red on master: the new test fails with `Error: native_controller_recovery_wait_authority_changed`. The own-process cases pass on master and with the change. - Green: the run is `retryable_failure` with `nextAttemptAt` at the deadline, its process fields are null, no claim happens before the deadline, and one claim happens at the deadline. ## Risks - The follow-up now waits instead of failing. The wait ends when the outgoing server saves a suspended checkpoint, when it exits, or at the predecessor's finish plus its idle window plus 2 minutes. In the observed case, the outgoing server's idle close could not save its checkpoint (`native_runner_checkpoint_owner_lost`), so the wait would end only when that server exits. See the follow-up note below. - An own process is still refused. The proof uses the run's own process-start events, the same proof as run cost accounting. **Follow-up note (not in this PR):** The outgoing server's checkpoint write checks the task's current run. A native successor that is parked in this wait is not one of the accepted successor kinds, and the idle close is not retried. So the wait does not end early from a checkpoint. In the observed timeline, the wait is about 225 s (until the outgoing server exited). The worst case with the default 5-minute idle window is about 425 s. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used in Claude Code with tool use (shell, file edit) and extended thinking. ## 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 --- .../src/services/native-local-process-stop.ts | 4 +-- .../services/native-process-start-events.ts | 5 +++ ...ve-controller-recovery.integration.test.ts | 35 +++++++++++++++++-- .../native-controller-recovery.ts | 18 ++++++++-- server/src/services/run-cost-accounting.ts | 3 +- 5 files changed, 57 insertions(+), 8 deletions(-) create mode 100644 server/src/services/native-process-start-events.ts diff --git a/server/src/services/native-local-process-stop.ts b/server/src/services/native-local-process-stop.ts index 527d18063aa..d377b91632c 100644 --- a/server/src/services/native-local-process-stop.ts +++ b/server/src/services/native-local-process-stop.ts @@ -12,8 +12,8 @@ import os from "node:os"; import { currentProcessSpaceHash, UNKNOWN_PROCESS_SPACE } from "./controller-process-identity.js"; import { proveOwnerGone } from "./owner-proof.js"; -export const PROCESS_START_REQUESTED = "native.process_start_requested"; -export const PROCESS_IDENTITY_RECORDED = "native.process_identity_recorded"; +import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "./native-process-start-events.js"; +export { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED }; /** Server-authored: the runner-state fence refused this run before it asked for * a runner, because a prior run's saved state could not be proven finished. */ export const PRIOR_OWNER_FENCE_REFUSED = "native.prior_owner_fence_refused"; diff --git a/server/src/services/native-process-start-events.ts b/server/src/services/native-process-start-events.ts new file mode 100644 index 00000000000..8167671ea55 --- /dev/null +++ b/server/src/services/native-process-start-events.ts @@ -0,0 +1,5 @@ +export const PROCESS_START_REQUESTED = "native.process_start_requested"; +export const PROCESS_IDENTITY_RECORDED = "native.process_identity_recorded"; + +/** Server-authored events (no source event ID) that prove a run started its own process. */ +export const OWN_PROCESS_START_EVENT_TYPES = [PROCESS_START_REQUESTED, PROCESS_IDENTITY_RECORDED] as const; 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 6cf7f9b25b5..8e43a723ef6 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 @@ -433,6 +433,27 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "successor", runIds: [runId], now: nextDeadline })).toEqual([]); }); + it("keeps a warm follow-up that inherited its predecessor's process identity on the same run until the outgoing owner's deadline", async () => { + const fixture = await seed(), runId = randomUUID(); + const scope = { ...fixture.scope, runId }; + const deadline = new Date(Date.now() + 60_000); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: scope.issueId, + nativeSessionId: scope.normalizedSessionId, status: "running", runtimeMode: "native", + processPid: 609, processGroupId: 609, processStartedAt: new Date(Date.now() - 120_000), + runnerProfileJson: { nativeExecutionInput: { binding: scope }, inheritedProcessIdentityRunId: fixture.scope.runId } }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, scope.issueId)); + await db.insert(nativeRunFinalizations).values({ companyId, issueId: scope.issueId, runId, phase: "observed" }); + await deferNativeControllerRecovery(db, { ...scope, retryAt: deadline }); + const [finalization] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + expect(finalization).toMatchObject({ phase: "retryable_failure", attempt: 0, leaseOwner: null, + nextAttemptAt: deadline, failureCode: NATIVE_RETAINED_OWNER_WAIT }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(run).toMatchObject({ processPid: null, processGroupId: null, processStartedAt: null }); + expect(run.runnerProfileJson).toMatchObject({ inheritedProcessIdentityRunId: fixture.scope.runId }); + expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "successor", runIds: [runId] })).toEqual([]); + expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "successor", runIds: [runId], now: deadline })).toHaveLength(1); + }); + it.each(["committed", "workspace_finalizing"])("defers a remote warm continuation while its %s predecessor has a finalization lease", async phase => { const fixture = await seed(), runId = randomUUID(), environmentId = randomUUID(); const previous = parseNativeExecutionInput({ @@ -935,14 +956,21 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d } }); - it.each(["live-owner", "expired-owner", "provider-attempt", "stopped", "operator-stop"])("does not publish an admission wait after authority changes: %s", async scenario => { + it.each(["live-owner", "expired-owner", "provider-attempt", "stopped", "operator-stop", "own-process", "inherited-then-own-process", "inherited-then-own-identity"])("does not publish an admission wait after authority changes: %s", async scenario => { const fixture = await seed(), runId = randomUUID(); const scope = { ...fixture.scope, runId }; + const ownProcess = scenario.startsWith("own-process") || scenario.startsWith("inherited-then-own"); await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: scope.issueId, status: scenario === "stopped" ? "cancelled" : "running", runtimeMode: "native", resultJson: scenario === "operator-stop" ? { cancellation: { source: "operator", expected: true, initiator: { type: "user" }, reason: "Stop", recordedAt: new Date().toISOString() } } : null, - runnerProfileJson: { nativeExecutionInput: { binding: scope } } }); + ...(ownProcess ? { processPid: 4242, processGroupId: 4242, processStartedAt: new Date() } : {}), + runnerProfileJson: { nativeExecutionInput: { binding: scope }, + ...(scenario.startsWith("inherited-then-own") ? { inheritedProcessIdentityRunId: fixture.scope.runId } : {}) } }); + if (scenario.startsWith("inherited-then-own")) { + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1, + eventType: scenario === "inherited-then-own-process" ? "native.process_start_requested" : "native.process_identity_recorded" }); + } await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, scope.issueId)); await db.insert(nativeRunFinalizations).values({ companyId, issueId: scope.issueId, runId, phase: "observed", attempt: scenario === "provider-attempt" ? 1 : 0, @@ -953,6 +981,9 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d retryAt: new Date(Date.now() + 60_000) })) .rejects.toThrow("wait_authority_changed"); expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0].phase).toBe("observed"); + if (ownProcess) { + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0].processPid).toBe(4242); + } }); it("reports bounded retained-pointer coverage without loading historical payloads", async () => { diff --git a/server/src/services/native-runtime/native-controller-recovery.ts b/server/src/services/native-runtime/native-controller-recovery.ts index 859c7c837b7..a5696d40f02 100644 --- a/server/src/services/native-runtime/native-controller-recovery.ts +++ b/server/src/services/native-runtime/native-controller-recovery.ts @@ -1,10 +1,11 @@ import { posix } from "node:path"; -import { and, eq, inArray, ne, or, sql } from "drizzle-orm"; -import { environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, type Db } from "@paperclipai/db"; +import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, type Db } from "@paperclipai/db"; import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; import { captureLegacyDurablePrpCheckpoint, parseNativeExecutionInput, type DurablePrpCheckpoint, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js"; import { notifyNativeFinalizationWork } from "../native-finalization-notifications.js"; import { readRunCancellation } from "../run-cancellation.js"; +import { OWN_PROCESS_START_EVENT_TYPES } from "../native-process-start-events.js"; import { nativeSha256 } from "./canonical.js"; import { findNativeSessionResumeRun, isNativeSessionId, isUnusedNativeSessionBootstrap, nativeSessionProviderEvidence } from "./native-session-resume.js"; import { insertMigratedNativeRunnerCheckpoint, loadNativeRunnerCheckpoint } from "./native-runner-checkpoint.js"; @@ -99,16 +100,27 @@ export async function deferNativeControllerRecovery(db: Db, input: { const cancellation = record(run?.resultJson?.nativeCancellation); const stop = readRunCancellation(run?.resultJson); const [clock] = await tx.execute<{ now: Date }>(sql`select clock_timestamp() as now`); + const hasProcessIdentity = Boolean(run?.processPid || run?.processGroupId || run?.processStartedAt); + const inheritedProcessIdentity = hasProcessIdentity + && typeof record(run?.runnerProfileJson).inheritedProcessIdentityRunId === "string" + && !(await tx.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, input.companyId), eq(heartbeatRunEvents.runId, input.runId), + isNull(heartbeatRunEvents.sourceEventId), + inArray(heartbeatRunEvents.eventType, [...OWN_PROCESS_START_EVENT_TYPES]))).limit(1)).length; if (!run || run.runtimeMode !== "native" || run.status !== "running" || task?.executionRunId !== input.runId || !owner || owner.phase !== "observed" || owner.resultId || owner.attempt !== 0 || owner.controllerGeneration !== 0 || owner.leaseOwner !== (input.leaseOwner ?? null) || (input.leaseOwner && (!owner.leaseExpiresAt || owner.leaseExpiresAt <= new Date(clock.now))) - || run.processPid || run.processGroupId || run.processStartedAt || authority || progress.size + || (hasProcessIdentity && !inheritedProcessIdentity) || authority || progress.size || !record(run.runnerProfileJson).nativeExecutionInput || run.resultJson?.startupCancellation || (stop?.source === "operator" && stop.expected) || (["run", "issue"].includes(String(cancellation.scope)) && ["pending", "acknowledged"].includes(String(cancellation.dispatchState)))) { throw new Error("native_controller_recovery_wait_authority_changed"); } + if (inheritedProcessIdentity) { + await tx.update(heartbeatRuns).set({ processPid: null, processGroupId: null, processStartedAt: null, updatedAt: new Date() }) + .where(eq(heartbeatRuns.id, input.runId)); + } await notifyNativeFinalizationWork(tx, input); await tx.update(nativeRunFinalizations).set({ phase: "retryable_failure", leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null, diff --git a/server/src/services/run-cost-accounting.ts b/server/src/services/run-cost-accounting.ts index fcf5d0062cf..dc6a235d08a 100644 --- a/server/src/services/run-cost-accounting.ts +++ b/server/src/services/run-cost-accounting.ts @@ -13,6 +13,7 @@ import { settleChargedImageReceiptsInTransaction } from "./native-runtime/genera import type { BudgetServiceHooks } from "./budgets.js"; import { queueBudgetEvaluation } from "./budget-evaluation-work.js"; import { ensureRuntimeAccountingBaseline } from "./runtime-accounting-totals.js"; +import { OWN_PROCESS_START_EVENT_TYPES } from "./native-process-start-events.js"; import { logger } from "../middleware/logger.js"; import { promises as fs } from "node:fs"; import { priceAnthropicReceipt } from "./anthropic-pricing.js"; @@ -141,7 +142,7 @@ const inheritedProcessIdentityOnly = sql`${heartbeatRuns.runnerProfileJson}->>'i and not exists (select 1 from ${heartbeatRunEvents} own_process where own_process.company_id = ${heartbeatRuns.companyId} and own_process.run_id = ${heartbeatRuns.id} and own_process.source_event_id is null - and own_process.event_type in ('native.process_start_requested', 'native.process_identity_recorded'))`; + and own_process.event_type in (${sql.join(OWN_PROCESS_START_EVENT_TYPES.map(type => sql`${type}`), sql`, `)}))`; const nativeProviderWorkNeverStarted = sql`${heartbeatRuns.runtimeMode} = 'native' and ${heartbeatRuns.status} in ('failed', 'cancelled', 'timed_out', 'interrupted') From 3706f520fd34ce9070b9da388e902ef7b2cc4245 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:39:28 -0600 Subject: [PATCH 03/20] test(scaling): keep ramping through recovered runs, read spend from cost records, and wait for termination before deleting agents (#21776) 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 scaling effort uses a real-agent ramp harness (`scripts/scale-agents-ramp.ts`, #21695 and #21757) to load a hosted test instance through the product API > - Its first run with agents that really ran (10 agents, 105 tasks, 106 runs) stopped on one failed run, recorded $0 model spend, and left cleanup errors > - Read-only inspection of the instance showed three harness faults. The failed run had a same-run bootstrap retry scheduled 33 s later, but the harness stopped and cleaned up first. Run rows carry no cost, but cost records do (63.7 cents for the run's agents). Terminated agents leave the company agent list, so the harness treated them as done and sent deletes that Paperclip refused with 409 > - These faults make the ramp stop too early, make its spend cap inert, and make cleanup report the wrong cause > - This pull request keeps the ramp going through runs that Paperclip recovers by itself, reads spend from cost records, records board latency per route, and makes cleanup wait for termination and name what it left behind > - The benefit is that the next ramp grades the product, not the harness, and its spend cap works ## Linked Issues or Issue Description Refs #21695 Refs #21757 **What happened?** The ramp stopped at step 1 with `failed_runs_zero failed (observed 1)`. The run failed with `runner_ingress_bind_conflict` before its provider session opened. Its run events show `same-run resume persisted` with `recoverable: true` and `nextAttemptAt` 33 s later. The harness stopped within 9 s and paused the agents, so the retry was blocked (`native_retry_admission_ineligible`). The result showed `Recorded model spend: $0`. The harness read `costUsd` from run rows, which is always null; `GET /api/companies//costs/by-agent` holds 63.71 cents over 104 cost events for the 10 agents. Cleanup reported two `DELETE /api/agents/:id returned 409: Complete termination before deleting the agent`. Those agents were still `lifecycleState: terminating`; the harness waited on the company agent list, which hides terminated agents, so it treated them as done. A later `--cleanup-only` changed nothing because it also found agents only through that list. The board API p90 failed (765 ms), but the result had no per-route timings to say which request was slow. **Expected behavior** A failed run whose task finishes by itself is counted, not a stop. A failed run whose task does not finish within a grace stops the ramp. The share of failed runs is graded at the step end. Spend comes from Paperclip's cost records. Cleanup deletes an agent only after termination completes, and names the agents and sandbox leases still pending. **Steps to reproduce** 1. Run `node --test scripts/scale-ramp/scale-ramp.test.ts` with the new fake and tests and the `origin/master` `ramp.ts`, `cleanup.ts`, `criteria.ts` and `report.ts`. 2. 16 tests fail, among them every new test (recovered run, unrecovered run, spend from cost records, spend cap, board per route, termination wait, still-terminating agents and `--cleanup-only`, leases released during the wait). 3. With this change, all 60 pass. **Paperclip version or commit** Instance on `2026.1106.0+2564.git.3244780bd`; harness from #21757. ## What Changed - `criteria.ts`: replace `failed_runs_zero` with `failed_runs_unrecovered_zero` (immediate) and `failed_run_rate` (at the step end). Step metrics add `runsEnded`, `runsFailedRecovered`, `runsFailedUnrecovered`, `runsFailedPending` and `board.byRoute`. - `ramp.ts`: a run counts as failed once it was seen `failed` or `timed_out`. It is recovered when its task reaches `done`. It is unrecovered when the task rests not done, needs Retry, or has no live run for `--recovery-grace-minutes` after the failure. A task whose interruption has an automatic retry scheduled (`state: retry_scheduled`, `nextRetryAt` or `retryWait`) does not count as needing Retry. Spend comes from `costs/by-agent` for the run's agents on each poll, and each step reports the spend in its window. Board probes keep a distribution per route. - `config.ts`: add `--max-failed-run-percent` (default 2) and `--recovery-grace-minutes` (default 15). - `cleanup.ts`: read agents by id as well as from the list, so terminated agents in the state file are found. Wait for `lifecycleState` `terminated` or `rejected` by id before a delete. Report `agentsStillTerminating`, `activeSandboxLeaseIds` and `sandboxLeasesReleasedDuringWait`, and name each lease still active with its run and acquire time. - `report.ts`: the summary shows recovered, unrecovered and pending failed runs, board latency per route, and each cleanup error. - `fake-paperclip.ts`: run rows carry no cost; `costs/by-agent` returns cents per agent. Optional failure of the n-th run, a scheduled recovery run, a termination delay (terminated agents leave the list and a delete answers 409 until termination completes), and leases that stay active after their run. - `doc/plans/2026-11-13-thousand-concurrent-agents.md`: the runbook describes the failed-run criteria, the spend source and the cleanup behavior. ## Verification - `node --test scripts/scale-ramp/scale-ramp.test.ts`: 60 of 60 pass. - Red check: with the new fake and tests but the `origin/master` `ramp.ts`, `cleanup.ts`, `criteria.ts` and `report.ts`, 16 tests fail, including all 8 new ones. - `tsc -p scripts/scale-ramp/tsconfig.json`: no errors. - Evidence from read-only GETs on the test instance: run `f1892d43` events (bind conflict, scheduled same-run retry, blocked after the pause), run rows (`costUsd` null on all 106), `costs/by-agent` (63.71 cents for the 10 agents), agent rows by id (`terminating` while absent from the list), lease rows. - Not run: a new real ramp (needs the owner's go-ahead). ## Risks - Low risk. The change touches only the scale-ramp harness, its fake, its tests and one runbook section. No product code changes. - A failed run no longer stops the ramp at once. An unrecovered one stops it after the grace (15 min by default), so a broken step can run up to that long. The step-end failed-run rate still fails a step with more than 2% failed runs. - Spend now needs cost read access for the board token. If `costs/by-agent` cannot be read, the result reports spend as not measured and the spend cap does not trigger. - Cleanup can now take up to 5 more minutes while it waits for termination by id. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, read-only HTTP GETs to the test instance). ## 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 --- .../2026-11-13-thousand-concurrent-agents.md | 27 +- package.json | 2 +- scripts/scale-ramp/cleanup.ts | 73 +++- scripts/scale-ramp/config.ts | 6 + scripts/scale-ramp/criteria.ts | 21 +- scripts/scale-ramp/fake-paperclip.ts | 77 ++++- scripts/scale-ramp/ramp.ts | 130 +++++-- scripts/scale-ramp/report.ts | 22 +- scripts/scale-ramp/scale-ramp-spend.test.ts | 132 ++++++++ scripts/scale-ramp/scale-ramp.test.ts | 317 ++++++++++-------- scripts/scale-ramp/test-harness.ts | 86 +++++ .../runner-e2e/source-sdk-public-inputs.json | 2 +- 12 files changed, 687 insertions(+), 208 deletions(-) create mode 100644 scripts/scale-ramp/scale-ramp-spend.test.ts create mode 100644 scripts/scale-ramp/test-harness.ts diff --git a/doc/plans/2026-11-13-thousand-concurrent-agents.md b/doc/plans/2026-11-13-thousand-concurrent-agents.md index 24e850f2a4b..5816f6f4545 100644 --- a/doc/plans/2026-11-13-thousand-concurrent-agents.md +++ b/doc/plans/2026-11-13-thousand-concurrent-agents.md @@ -432,7 +432,12 @@ the one origin. above `--spend-threshold-usd` (default $5) unless `--confirm-spend ` is at least the estimate. It never creates more tasks than the printed cap, and it stops when the model spend the runs record passes the confirmed -amount. The defaults are assumptions: $0.02 model spend per task and $0.10 +amount. It reads recorded spend from Paperclip's cost records for the run's +agents (`/api/companies//costs/by-agent?period=all`); run rows carry no +cost. When some cost events have no known price, it prints a warning, grades +the run incomplete, and checks the cap against tasks created times the +per-task assumption as well. The +defaults are assumptions: $0.02 model spend per task and $0.10 per sandbox-hour (`PAPERCLIP_SCALE_MODEL_USD_PER_TASK`, `PAPERCLIP_SCALE_SANDBOX_USD_PER_HOUR`). Correct them from the recorded spend of the first run. @@ -451,7 +456,8 @@ A missing source is reported as "not measured", never as zero. | Criterion | Source | Target | Measured from | | --- | --- | --- | --- | | Runs that need Retry | finish line | 0, stops at once | task view offers Retry | -| Failed or timed-out runs | harness | 0, stops at once | run list | +| Failed runs whose task did not finish by itself | harness | 0 within `--recovery-grace-minutes` (default 15), stops then | run list and task status | +| Failed runs, recovered ones included, as a share of ended runs | harness | at most `--max-failed-run-percent` (default 2) | run list | | Tasks at rest but not done | harness | 0 | task status | | Peak running agents | harness | at least 90% of the step | run list | | Board page API requests, p90 | finish line | below 500 ms | a GET mix every 10 s: dashboard, issues, agents, live runs, sidebar badges | @@ -464,6 +470,23 @@ A missing source is reported as "not measured", never as zero. | Lease renewals that miss their deadline | finish line | 0 | metrics endpoint | | Kill one server process | finish line | runs resume, no Retry | not measured by this harness | +**Failed runs.** Paperclip retries many failed runs by itself (a same-run +bootstrap retry, a continuation run). A failed run does not stop the ramp +while its task can still finish: the harness keeps going and counts the run as +recovered when its task reaches `done`, and as unrecovered when the task comes +to rest without being done, offers Retry with no automatic retry scheduled, or +has no live run for the recovery grace after the failure. An unrecovered run +stops the ramp at once. The share of failed runs, recovered ones included, is +graded at the end of each step. + +**Cleanup.** The harness reads each agent by id (a terminated agent leaves the +company's agent list) and deletes it only after Paperclip reports its +termination complete (`lifecycleState` `terminated`). An agent Paperclip keeps +for its cost history stays terminated. The result names the agents still +terminating and the sandbox leases still active after the waits, and counts the +leases that released while it waited; `--cleanup-only ` finishes them +later from the state file. + **Server metrics.** Each server process can serve `GET /api/instance/server-metrics`, a JSON snapshot of that process over the last 50 to 60 s (`windowMs`), with its `processId` (random per process diff --git a/package.json b/package.json index 2d2a4abebb6..b6a185b015b 100644 --- a/package.json +++ b/package.json @@ -61,7 +61,7 @@ "smoke:notion-generic-live": "node scripts/smoke/notion-generic-live.mjs", "smoke:posthog-live": "node scripts/smoke/posthog-live.mjs", "smoke:terminal-bench-loop-skill": "node scripts/smoke/terminal-bench-loop-skill-smoke.mjs", - "test:release-registry": "node scripts/ci-profile/node-test.mjs scripts/ci-profile/reporters.test.mjs scripts/ci/retry-reporter.test.mjs scripts/__tests__/runner-vitest-package-lanes.test.mjs scripts/__tests__/canary-startup-playwright.test.mjs scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/public-install-closure.test.mjs scripts/__tests__/public-install-registry.test.mjs scripts/__tests__/prefetch-child.test.mjs scripts/__tests__/stage-bundled-packages.test.mjs scripts/__tests__/pack-staged-packages.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs scripts/__tests__/runner-debug-crate-cache.test.mjs scripts/__tests__/agent-build-cache.test.mjs scripts/__tests__/agent-preflight.test.mjs scripts/__tests__/vitest-worker-isolation.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/draft-stable-notes.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs scripts/typecheck-test-programs.test.mjs scripts/__tests__/local-verify.test.mjs scripts/test-sandbox-providers.test.mjs scripts/__tests__/ci-typecheck-lane.test.mjs scripts/scale-ramp/scale-ramp.test.ts", + "test:release-registry": "node scripts/ci-profile/node-test.mjs scripts/ci-profile/reporters.test.mjs scripts/ci/retry-reporter.test.mjs scripts/__tests__/runner-vitest-package-lanes.test.mjs scripts/__tests__/canary-startup-playwright.test.mjs scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/public-install-closure.test.mjs scripts/__tests__/public-install-registry.test.mjs scripts/__tests__/prefetch-child.test.mjs scripts/__tests__/stage-bundled-packages.test.mjs scripts/__tests__/pack-staged-packages.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs scripts/__tests__/runner-debug-crate-cache.test.mjs scripts/__tests__/agent-build-cache.test.mjs scripts/__tests__/agent-preflight.test.mjs scripts/__tests__/vitest-worker-isolation.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/draft-stable-notes.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs scripts/typecheck-test-programs.test.mjs scripts/__tests__/local-verify.test.mjs scripts/test-sandbox-providers.test.mjs scripts/__tests__/ci-typecheck-lane.test.mjs scripts/scale-ramp/scale-ramp.test.ts scripts/scale-ramp/scale-ramp-spend.test.ts", "storybook-visual:baseline": "node scripts/storybook-visual-baseline.mjs", "test:storybook-visual": "node scripts/storybook-visual-baseline.mjs download && node scripts/storybook-visual-baseline.mjs verify && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts", "test:storybook-visual:update": "node scripts/storybook-visual-baseline.mjs download && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts --update-snapshots && node scripts/storybook-visual-baseline.mjs pack", diff --git a/scripts/scale-ramp/cleanup.ts b/scripts/scale-ramp/cleanup.ts index f40b169ca97..bda4d807768 100644 --- a/scripts/scale-ramp/cleanup.ts +++ b/scripts/scale-ramp/cleanup.ts @@ -10,16 +10,23 @@ export interface CleanupReport { agentsTerminated: number; agentsDeleted: number; agentsKeptForCostHistory: number; + agentsStillTerminating: string[]; secretDeleted: boolean; projectArchived: boolean; companyArchived: boolean; activeSandboxLeases: number | null; + activeSandboxLeaseIds: string[]; + sandboxLeasesReleasedDuringWait: number; durationMs: number; errors: string[]; } export const LIVE_RUN_STATUSES = new Set(["queued", "running", "scheduled_retry"]); const PARALLELISM = 8; +const TERMINATED = new Set(["terminated", "rejected"]); +const TERMINATION_READS_PER_POLL = 200; +const TERMINATION_POLL_MS_PER_AGENT = 30; +const TERMINATION_POLL_MAX_MS = 30_000; export interface CleanupInput { api: PaperclipClient; @@ -53,8 +60,9 @@ export async function cleanupRun(input: CleanupInput): Promise { const started = clock.now(); const pollMs = input.pollMs ?? 3_000; const report: CleanupReport = { - agentsPaused: 0, runsCancelled: 0, tasksArchived: 0, agentsTerminated: 0, agentsDeleted: 0, agentsKeptForCostHistory: 0, - secretDeleted: false, projectArchived: false, companyArchived: false, activeSandboxLeases: null, durationMs: 0, errors: [], + agentsPaused: 0, runsCancelled: 0, tasksArchived: 0, agentsTerminated: 0, agentsDeleted: 0, agentsKeptForCostHistory: 0, agentsStillTerminating: [], + secretDeleted: false, projectArchived: false, companyArchived: false, activeSandboxLeases: null, activeSandboxLeaseIds: [], + sandboxLeasesReleasedDuringWait: 0, durationMs: 0, errors: [], }; const attempt = async (what: string, action: () => Promise): Promise => { try { @@ -79,8 +87,22 @@ export async function cleanupRun(input: CleanupInput): Promise { return report; } const prefix = agentPrefix(label); + const readAgent = async (id: string): Promise => { + try { + return await api.get(`/api/agents/${id}`); + } catch (error) { + if (error instanceof ApiError && error.status === 404) return null; + report.errors.push(`read agent ${id}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300)); + return { id, status: "unknown", lifecycleState: "unknown" }; + } + }; const listed = await read("list agents", `/api/companies/${companyId}/agents`, []); const agents = listed.filter(agent => String(agent.name ?? "").startsWith(prefix)); + const unlisted = state.agentIds.filter(id => !agents.some(agent => String(agent.id) === id)); + await mapLimit(unlisted, PARALLELISM, async id => { + const agent = await readAgent(id); + if (agent && String(agent.name ?? prefix).startsWith(prefix)) agents.push(agent); + }); const agentIds = new Set(agents.map(agent => String(agent.id))); input.log?.(`Cleanup ${label}: ${agents.length} agents, ${state.taskIds.length} recorded tasks`); @@ -121,16 +143,27 @@ export async function cleanupRun(input: CleanupInput): Promise { if (await attempt(`terminate agent ${agent.id}`, () => api.post(`/api/agents/${agent.id}/terminate`))) report.agentsTerminated += 1; }); const pending = new Set(agentIds); - for (const until = clock.now() + (input.terminateWaitMs ?? 300_000); pending.size && clock.now() < until;) { - const current = await read("list agents", `/api/companies/${companyId}/agents`, []); - for (const agent of current) { - if (!pending.has(String(agent.id))) continue; - if (agent.status === "terminated" && (agent.lifecycleState == null || agent.lifecycleState === "terminated")) pending.delete(String(agent.id)); - } - for (const id of [...pending]) if (!current.some(agent => String(agent.id) === id)) pending.delete(id); - if (pending.size) await clock.sleep(pollMs); + const waitMs = input.terminateWaitMs ?? 300_000; + const readPending = async (ids: string[]) => mapLimit(ids, PARALLELISM, async id => { + const agent = await readAgent(id); + if (!agent || TERMINATED.has(String(agent.lifecycleState))) pending.delete(id); + }); + let cursor = 0; + for (const until = clock.now() + waitMs; pending.size && clock.now() < until;) { + const ids = [...pending]; + const start = cursor % ids.length; + const batch = [...ids.slice(start), ...ids.slice(0, start)].slice(0, TERMINATION_READS_PER_POLL); + cursor = start + batch.length; + await readPending(batch); + if (!pending.size) break; + await clock.sleep(Math.min(TERMINATION_POLL_MAX_MS, Math.max(pollMs, pending.size * TERMINATION_POLL_MS_PER_AGENT))); + } + if (pending.size) await readPending([...pending]); + report.agentsStillTerminating = [...pending]; + if (pending.size) { + report.errors.push(`${pending.size} agents had not completed termination after ${Math.round(waitMs / 60_000)} min, so they were not deleted: ` + + `${[...pending].join(", ")}; run --cleanup-only ${label} again later`); } - if (pending.size) report.errors.push(`${pending.size} agents were not terminated in time; run --cleanup-only ${label} again`); await mapLimit([...agentIds].filter(id => !pending.has(id)), PARALLELISM, async agentId => { try { await api.delete(`/api/agents/${agentId}`); @@ -154,7 +187,10 @@ export async function cleanupRun(input: CleanupInput): Promise { } if (state.environmentId && taskIds.size) { - for (const until = clock.now() + (input.leaseWaitMs ?? 300_000); ;) { + const leaseWaitMs = input.leaseWaitMs ?? 300_000; + const seen = new Set(); + let active: Json[] = []; + for (const until = clock.now() + leaseWaitMs; ;) { let leases: Json[] | null = null; try { leases = await api.get(`/api/environments/${state.environmentId}/leases?status=active`); @@ -162,11 +198,18 @@ export async function cleanupRun(input: CleanupInput): Promise { leases = null; } if (leases === null) break; - report.activeSandboxLeases = leases.filter(lease => taskIds.has(String(lease.issueId))).length; - if (report.activeSandboxLeases === 0 || clock.now() >= until) break; + active = leases.filter(lease => taskIds.has(String(lease.issueId)) || agentIds.has(String(lease.metadata?.agentId ?? ""))); + for (const lease of active) seen.add(String(lease.id)); + report.activeSandboxLeases = active.length; + if (active.length === 0 || clock.now() >= until) break; await clock.sleep(pollMs); } - if (report.activeSandboxLeases) report.errors.push(`${report.activeSandboxLeases} sandbox leases of this run are still active`); + report.activeSandboxLeaseIds = active.map(lease => String(lease.id)); + report.sandboxLeasesReleasedDuringWait = [...seen].filter(id => !report.activeSandboxLeaseIds.includes(id)).length; + if (active.length) { + const detail = active.map(lease => `${lease.id} (run ${lease.heartbeatRunId ?? "unknown"}, acquired ${lease.acquiredAt ?? "unknown"})`).join(", "); + report.errors.push(`${active.length} sandbox leases of this run were still active after ${Math.round(leaseWaitMs / 60_000)} min: ${detail}`.slice(0, 600)); + } } if (state.companyCreated) { diff --git a/scripts/scale-ramp/config.ts b/scripts/scale-ramp/config.ts index 65db8760d38..9ac7bfe4940 100644 --- a/scripts/scale-ramp/config.ts +++ b/scripts/scale-ramp/config.ts @@ -21,6 +21,8 @@ export interface Thresholds { queueWaitP95Ms: number; firstActivityP95Ms: number; minConcurrencyRatio: number; + maxFailedRunRatio: number; + recoveryGraceMs: number; maxEventLoopUtilization: number; runEventLatenessP99Ms: number; agentApiPreHandlerP99Ms: number; @@ -159,6 +161,8 @@ export function parseOptions(argv: readonly string[], env: NodeJS.ProcessEnv, no "max-queue-wait-p95-seconds": { type: "string" }, "max-first-activity-p95-seconds": { type: "string" }, "min-concurrency-ratio": { type: "string" }, + "max-failed-run-percent": { type: "string" }, + "recovery-grace-minutes": { type: "string" }, }, }); if (values["dry-run"] && values["cleanup-only"]) throw new Error("--dry-run and --cleanup-only exclude each other"); @@ -198,6 +202,8 @@ export function parseOptions(argv: readonly string[], env: NodeJS.ProcessEnv, no queueWaitP95Ms: number(values["max-queue-wait-p95-seconds"], "--max-queue-wait-p95-seconds", 60, 1, 3_600) * 1_000, firstActivityP95Ms: number(values["max-first-activity-p95-seconds"], "--max-first-activity-p95-seconds", 60, 1, 3_600) * 1_000, minConcurrencyRatio: number(values["min-concurrency-ratio"], "--min-concurrency-ratio", 0.9, 0.1, 1), + maxFailedRunRatio: number(values["max-failed-run-percent"], "--max-failed-run-percent", 2, 0, 100) / 100, + recoveryGraceMs: number(values["recovery-grace-minutes"], "--recovery-grace-minutes", 15, 1, 120) * 60_000, maxEventLoopUtilization: 0.6, runEventLatenessP99Ms: 1_000, agentApiPreHandlerP99Ms: 100, diff --git a/scripts/scale-ramp/criteria.ts b/scripts/scale-ramp/criteria.ts index be596ff392e..32691fe6eb6 100644 --- a/scripts/scale-ramp/criteria.ts +++ b/scripts/scale-ramp/criteria.ts @@ -22,7 +22,11 @@ export interface StepMetrics { tasksFinished: number; tasksFailed: number; tasksNeedingRetry: number; + runsEnded: number; runsFailed: number; + runsFailedRecovered: number; + runsFailedUnrecovered: number; + runsFailedPending: number; runsInterrupted: number; runsCancelled: number; peakRunning: number; @@ -32,7 +36,7 @@ export interface StepMetrics { ttftMs: Distribution; firstActivityMs: Distribution; runDurationMs: Distribution; - board: { requests: number; failures: number; ms: Distribution }; + board: { requests: number; failures: number; ms: Distribution; byRoute: Record }; server: ServerMetrics; recordedSpendUsd: number; } @@ -69,10 +73,17 @@ export const CRITERIA: readonly Criterion[] = [ evaluate: m => ({ status: m.tasksNeedingRetry === 0 ? "pass" : "fail", observed: m.tasksNeedingRetry }), }, { - id: "failed_runs_zero", source: "harness", immediate: true, - description: "Runs that ended failed or timed out", - threshold: () => "= 0", - evaluate: m => ({ status: m.runsFailed === 0 ? "pass" : "fail", observed: m.runsFailed }), + id: "failed_runs_unrecovered_zero", source: "harness", immediate: true, + description: "Failed or timed-out runs whose task did not finish by itself within the recovery grace", + threshold: t => `= 0 (grace ${Math.round(t.recoveryGraceMs / 60_000)} min)`, + evaluate: m => ({ status: m.runsFailedUnrecovered === 0 ? "pass" : "fail", observed: m.runsFailedUnrecovered }), + }, + { + id: "failed_run_rate", source: "harness", immediate: false, + description: "Failed or timed-out runs as a share of ended runs, recovered ones included (%)", + threshold: t => `<= ${Math.round(t.maxFailedRunRatio * 1_000) / 10}%`, + evaluate: (m, t) => m.runsEnded === 0 ? { status: "not_measured", observed: null } + : { status: m.runsFailed / m.runsEnded <= t.maxFailedRunRatio ? "pass" : "fail", observed: Math.round((m.runsFailed / m.runsEnded) * 1_000) / 10 }, }, { id: "tasks_rested_not_done_zero", source: "harness", immediate: false, diff --git a/scripts/scale-ramp/fake-paperclip.ts b/scripts/scale-ramp/fake-paperclip.ts index 0dcddcac131..eb087f2e200 100644 --- a/scripts/scale-ramp/fake-paperclip.ts +++ b/scripts/scale-ramp/fake-paperclip.ts @@ -25,7 +25,14 @@ export interface FakeConfig { runDurationMs: number; capacity: number; failWhenRunningAbove: number; + failRun: (startIndex: number) => boolean; retryOnFailure: boolean; + recoverFailedRunAfterMs: number | null; + retrySameRunAfterMs: number | null; + sameRunRetryDurationMs: number | null; + unpricedEventsPerAgent: number; + terminationDelayMs: number; + leaseLingerMs: number; costPerRunUsd: number; boardLatencyMs: (running: number) => number; failRequest: (method: string, path: string, count: number) => { status: number; body: string } | null; @@ -42,6 +49,8 @@ interface FakeRun { startedAt: number | null; finishedAt: number | null; willFail: boolean; + recovery: boolean; + retryAt?: number | null; } export interface RequestLog { @@ -66,6 +75,7 @@ export class FakePaperclip { readonly environmentId = "00000000-0000-4000-8000-0000000000e1"; private seq = 0; private agentsCreated = 0; + private runsStarted = 0; private counts = new Map(); readonly clock: VirtualClock; @@ -82,7 +92,14 @@ export class FakePaperclip { runDurationMs: 60_000, capacity: Number.POSITIVE_INFINITY, failWhenRunningAbove: Number.POSITIVE_INFINITY, + failRun: () => false, retryOnFailure: false, + recoverFailedRunAfterMs: null, + retrySameRunAfterMs: null, + sameRunRetryDurationMs: null, + unpricedEventsPerAgent: 0, + terminationDelayMs: 0, + leaseLingerMs: 0, costPerRunUsd: 0.01, boardLatencyMs: () => 40, failRequest: () => null, @@ -108,7 +125,7 @@ export class FakePaperclip { for (let index = 0; index < count; index += 1) { const id = this.id(); this.runs.set(id, { id, agentId: "noise-agent", issueId: "noise-issue", status: "succeeded", createdAt: this.clock.now() + 1e10 + index, - startedAt: null, finishedAt: null, willFail: false }); + startedAt: null, finishedAt: null, willFail: false, recovery: false }); } } @@ -128,6 +145,7 @@ export class FakePaperclip { advance(): void { const now = this.clock.now(); for (const agent of this.agents.values()) { + if (agent.lifecycleState === "terminating" && now >= agent.terminatingSince + this.config.terminationDelayMs) agent.lifecycleState = "terminated"; const delay = typeof this.config.agentReadyDelayMs === "function" ? this.config.agentReadyDelayMs(agent.index) : this.config.agentReadyDelayMs; if (!["preparing", "verifying"].includes(agent.lifecycleState) || now < agent.createdAt + delay) continue; if (this.config.agentSetupError) { @@ -138,16 +156,38 @@ export class FakePaperclip { agent.status = "idle"; } } + for (const run of this.runs.values()) { + if (run.status !== "failed" || !run.retryAt || now < run.retryAt) continue; + run.status = "running"; + run.startedAt = run.retryAt; + run.finishedAt = null; + run.retryAt = null; + run.willFail = false; + run.recovery = true; + } for (const run of [...this.runs.values()].sort((a, b) => a.createdAt - b.createdAt)) { - if (run.status === "running" && run.startedAt !== null && now >= run.startedAt + this.config.runDurationMs) { - run.finishedAt = run.startedAt + this.config.runDurationMs; + const duration = run.recovery && this.config.sameRunRetryDurationMs !== null ? this.config.sameRunRetryDurationMs : this.config.runDurationMs; + if (run.status === "running" && run.startedAt !== null && now >= run.startedAt + duration) { + run.finishedAt = run.startedAt + duration; const issue = this.issues.get(run.issueId)!; if (run.willFail) { run.status = "failed"; issue.interruption = this.config.retryOnFailure ? { state: "failed", canRetry: true, retryWait: false } : null; + if (this.config.retrySameRunAfterMs !== null) { + run.retryAt = run.finishedAt + this.config.retrySameRunAfterMs; + issue.interruption = { state: "retry_scheduled", canRetry: true, nextRetryAt: new Date(run.retryAt).toISOString() }; + } + if (this.config.recoverFailedRunAfterMs !== null) { + const retryAt = run.finishedAt + this.config.recoverFailedRunAfterMs; + issue.interruption = { state: "retry_scheduled", canRetry: true, nextRetryAt: new Date(retryAt).toISOString() }; + const id = this.id(); + this.runs.set(id, { id, agentId: run.agentId, issueId: run.issueId, status: "queued", createdAt: retryAt, startedAt: null, finishedAt: null, + willFail: false, recovery: true }); + } } else { run.status = "succeeded"; issue.status = "done"; + issue.interruption = null; } } } @@ -156,7 +196,8 @@ export class FakePaperclip { if (this.running() >= this.config.capacity) break; run.status = "running"; run.startedAt = Math.max(run.createdAt + this.config.startDelayMs, now - 1_000); - run.willFail = this.running() > this.config.failWhenRunningAbove; + this.runsStarted += 1; + run.willFail = !run.recovery && (this.running() > this.config.failWhenRunningAbove || this.config.failRun(this.runsStarted)); this.issues.get(run.issueId)!.status = "in_progress"; } } @@ -165,8 +206,7 @@ export class FakePaperclip { const iso = (value: number | null) => value === null ? null : new Date(value).toISOString(); return { id: run.id, agentId: run.agentId, issueId: run.issueId, status: run.status, createdAt: iso(run.createdAt), startedAt: iso(run.startedAt), - finishedAt: iso(run.finishedAt), costUsd: run.status === "succeeded" || run.status === "failed" ? this.config.costPerRunUsd : null, - error: null, errorCode: null, + finishedAt: iso(run.finishedAt), costUsd: null, error: null, errorCode: null, }; } @@ -227,8 +267,18 @@ export class FakePaperclip { this.projects.set(id, { id, companyId, name: body.name, archivedAt: null }); return json(201, this.projects.get(id)); } + if (c === "costs" && parts[3] === "by-agent" && method === "GET") { + const cents = new Map(); + const month = new Date(now).toISOString().slice(0, 7); + for (const run of this.runs.values()) { + if (run.status !== "succeeded" && run.status !== "failed") continue; + if (query.get("period") !== "all" && new Date(run.finishedAt!).toISOString().slice(0, 7) !== month) continue; + cents.set(run.agentId, (cents.get(run.agentId) ?? 0) + this.config.costPerRunUsd * 100); + } + return json(200, [...cents].map(([agentId, costCents]) => ({ agentId, costCents, unpricedEventCount: this.config.unpricedEventsPerAgent }))); + } if (c === "agents") { - if (method === "GET") return json(200, [...this.agents.values()].filter(agent => agent.companyId === companyId)); + if (method === "GET") return json(200, [...this.agents.values()].filter(agent => agent.companyId === companyId && agent.status !== "terminated")); const id = this.id(); this.agents.set(id, { id, companyId, name: body.name, status: "paused", lifecycleState: "preparing", lifecycleHolds: [], lifecycleError: null, pauseReason: null, createdAt: now, index: this.agentsCreated++, payload: body }); @@ -242,7 +292,8 @@ export class FakePaperclip { const agent = this.agents.get(body.assigneeAgentId); if (agent && agent.status !== "terminated") { const runId = this.id(); - this.runs.set(runId, { id: runId, agentId: body.assigneeAgentId, issueId: id, status: "queued", createdAt: now, startedAt: null, finishedAt: null, willFail: false }); + this.runs.set(runId, { id: runId, agentId: body.assigneeAgentId, issueId: id, status: "queued", createdAt: now, startedAt: null, finishedAt: null, + willFail: false, recovery: false }); } return json(201, this.issues.get(id)); } @@ -267,16 +318,19 @@ export class FakePaperclip { if (a === "agents" && b) { const agent = this.agents.get(b); if (!agent) return json(404, { error: "Agent not found" }); + if (method === "GET" && !c) return json(200, agent); if (method === "PATCH") { Object.assign(agent, body); return json(200, agent); } if (method === "POST" && c === "terminate") { agent.status = "terminated"; - agent.lifecycleState = "terminated"; + agent.lifecycleState = this.config.terminationDelayMs > 0 ? "terminating" : "terminated"; + agent.terminatingSince = now; return json(200, agent); } if (method === "DELETE") { + if (agent.lifecycleState !== "terminated") return json(409, { error: "Complete termination before deleting the agent" }); this.agents.delete(b); return json(200, { ok: true }); } @@ -324,7 +378,10 @@ export class FakePaperclip { return json(200, project); } if (a === "environments" && b === this.environmentId && c === "leases") { - return json(200, this.liveRuns().map(run => ({ id: run.id, issueId: run.issueId, status: "active" }))); + const held = [...this.runs.values()].filter(run => ["queued", "running"].includes(run.status) + || (run.finishedAt !== null && now < run.finishedAt + this.config.leaseLingerMs)); + return json(200, held.map(run => ({ id: `lease-${run.id}`, issueId: run.issueId, heartbeatRunId: run.id, status: "active", + acquiredAt: new Date(run.createdAt).toISOString(), metadata: { agentId: run.agentId } }))); } return json(404, { error: `fake: no route for ${method} ${route}` }); } diff --git a/scripts/scale-ramp/ramp.ts b/scripts/scale-ramp/ramp.ts index 848ac9c267c..82206b718a8 100644 --- a/scripts/scale-ramp/ramp.ts +++ b/scripts/scale-ramp/ramp.ts @@ -1,9 +1,9 @@ -import { readMetrics, type Clock, type Fetcher, type PaperclipClient } from "./client.ts"; +import { pathClass, readMetrics, type Clock, type Fetcher, type PaperclipClient } from "./client.ts"; import type { Options, Step } from "./config.ts"; import { evaluate, firstFailure, type CriterionResult, type ServerMetrics, type StepMetrics } from "./criteria.ts"; import { LIVE_RUN_STATUSES } from "./cleanup.ts"; import { AgentsNotReady, describeAgent, ensureAgents, waitForAgentsReady } from "./setup.ts"; -import { distribution } from "./stats.ts"; +import { distribution, type Distribution } from "./stats.ts"; import { mapLimit, taskTag, type RunState, type StateStore } from "./state.ts"; import { runTiming, taskBrief, taskNonce, taskTitle, type RunEvent } from "./workload.ts"; @@ -27,6 +27,7 @@ const RETRY_RECHECK_MS = 30_000; const EVENT_FETCHES_PER_TICK = 10; const EVENT_PAGES = 4; const SINGLE_READS_PER_TICK = 50; +const SPEND_READ_FAILURES_TO_STOP = 3; const AGENT_RUN_PAGE = 20; const AGENT_RUN_READ_PARALLELISM = 8; @@ -50,7 +51,8 @@ interface RunRecord { createdAt: number | null; startedAt: number | null; finishedAt: number | null; - costUsd: number; + everFailed: boolean; + everEnded: boolean; sampled: boolean; error: string | null; errorCode: string | null; @@ -63,12 +65,14 @@ interface StepAccumulator { endedAt: number | null; runningSamples: number[]; boardMs: number[]; + boardByRoute: Record; boardRequests: number; boardFailures: number; serverSamples: Array>; ttftMs: number[]; firstActivityMs: number[]; sampled: number; + spendAtStartUsd: number; } export interface StepResult { @@ -93,7 +97,9 @@ export interface RampOutcome { openTasksAtEnd: number; tasksCreated: number; taskCapReached: boolean; - recordedSpendUsd: number; + recordedSpendUsd: number | null; + spendReadError: string | null; + unpricedCostEvents: number; runsListTruncated: boolean; metricsSource: "endpoint" | "not provided" | "unavailable"; } @@ -192,6 +198,10 @@ export class Ramp { private nextBoardAt = 0; private nextPollAt = 0; private taskCapReached = false; + private spendUsd: number | null = null; + private spendReadFailures = 0; + private spendReadError: string | null = null; + private unpricedCostEvents = 0; private fallbackCursor = 0; private runsListTruncated = false; private metricsSource: RampOutcome["metricsSource"]; @@ -220,8 +230,8 @@ export class Ramp { break; } log(`Step ${step.index + 1}/${options.steps.length}: ${step.concurrency} agents for ${Math.round(step.holdMs / 60_000)} min`); - const accumulator: StepAccumulator = { step, startedAt: clock.now(), endedAt: null, runningSamples: [], boardMs: [], boardRequests: 0, - boardFailures: 0, serverSamples: [], ttftMs: [], firstActivityMs: [], sampled: 0 }; + const accumulator: StepAccumulator = { step, startedAt: clock.now(), endedAt: null, runningSamples: [], boardMs: [], boardByRoute: {}, boardRequests: 0, + boardFailures: 0, serverSamples: [], ttftMs: [], firstActivityMs: [], sampled: 0, spendAtStartUsd: this.spendUsd ?? 0 }; this.accumulators.push(accumulator); stop = await this.prepareStep(step); if (!stop) { @@ -249,13 +259,15 @@ export class Ramp { const last = this.current(); last.endedAt = clock.now(); } + const finalSpendRead = await this.readSpend(); for (const result of results) { result.metrics = this.metrics(result.index); result.criteriaFinal = evaluate(result.metrics, options.thresholds); } return { steps: results, stop, drained, openTasksAtEnd: this.openTasks().length, tasksCreated: this.tasks.size, taskCapReached: this.taskCapReached, - recordedSpendUsd: this.recordedSpend(), runsListTruncated: this.runsListTruncated, metricsSource: this.metricsSource, + recordedSpendUsd: finalSpendRead ? this.spendUsd : null, spendReadError: finalSpendRead ? null : this.spendReadError, + unpricedCostEvents: this.unpricedCostEvents, runsListTruncated: this.runsListTruncated, metricsSource: this.metricsSource, }; } @@ -374,8 +386,17 @@ export class Ramp { } private immediateStop(stepIndex: number): StopReason | null { - if (this.recordedSpend() > this.deps.spendCapUsd) { - return { stepIndex, reason: `recorded model spend $${this.recordedSpend().toFixed(2)} passed the cap of $${this.deps.spendCapUsd}`, criterion: "spend_cap" }; + if ((this.spendUsd ?? 0) > this.deps.spendCapUsd) { + return { stepIndex, reason: `recorded model spend $${this.spendUsd!.toFixed(2)} passed the cap of $${this.deps.spendCapUsd}`, criterion: "spend_cap" }; + } + const bound = this.unpricedSpendBoundUsd(); + if (bound !== null && bound > this.deps.spendCapUsd) { + return { stepIndex, reason: `${this.unpricedCostEvents} cost events have no known price, so the spend cap uses tasks created x $${this.deps.options.pricing.modelUsdPerTask}` + + ` per task: $${bound.toFixed(2)} passed the cap of $${this.deps.spendCapUsd}`, criterion: "spend_cap" }; + } + if (this.spendReadFailures >= SPEND_READ_FAILURES_TO_STOP) { + return { stepIndex, reason: `recorded model spend could not be read ${this.spendReadFailures} times in a row, so the spend cap cannot be enforced: ${this.spendReadError}`, + criterion: "spend_unreadable" }; } for (const accumulator of this.accumulators) { const failed = firstFailure(evaluate(this.metrics(accumulator.step.index), this.deps.options.thresholds, true)); @@ -388,10 +409,39 @@ export class Ramp { return [...this.tasks.values()].filter(task => task.outcome === "open"); } - private recordedSpend(): number { - let total = 0; - for (const run of this.runs.values()) total += run.costUsd; - return Math.round(total * 100) / 100; + private unpricedSpendBoundUsd(): number | null { + if (this.unpricedCostEvents === 0) return null; + return Math.round(this.tasks.size * this.deps.options.pricing.modelUsdPerTask * 100) / 100; + } + + private async readSpend(): Promise { + const agentIds = new Set(this.deps.state.agentIds); + if (!agentIds.size) return this.spendReadFailures === 0; + let rows: unknown; + try { + rows = await this.deps.api.get(`/api/companies/${this.companyId}/costs/by-agent?period=all`); + if (!Array.isArray(rows)) throw new Error("costs by agent did not return a list"); + } catch (error) { + this.spendReadFailures += 1; + this.spendReadError = error instanceof Error ? error.message : String(error); + return false; + } + this.spendReadFailures = 0; + this.spendReadError = null; + let cents = 0; + let unpriced = 0; + for (const row of rows as Json[]) { + if (!agentIds.has(String(row.agentId))) continue; + cents += num(row.costCents) ?? 0; + unpriced += num(row.unpricedEventCount) ?? 0; + } + if (unpriced > 0 && this.unpricedCostEvents === 0) { + this.deps.log(`Warning: ${unpriced} cost events of this run have no known price. Recorded spend is a lower bound, so the spend cap now uses` + + ` tasks created x $${this.deps.options.pricing.modelUsdPerTask} per task (PAPERCLIP_SCALE_MODEL_USD_PER_TASK)`); + } + this.unpricedCostEvents = unpriced; + this.spendUsd = Math.round(cents) / 100; + return true; } private async topUp(concurrency: number, stepIndex: number, until: number): Promise { @@ -425,12 +475,18 @@ export class Ramp { const accumulator = this.current(); for (const route of BOARD_MIX) { const before = this.deps.api.records.length; - await this.deps.api.get(route(this.companyId), "board").catch(() => null); + const path = route(this.companyId); + await this.deps.api.get(path, "board").catch(() => null); const record = this.deps.api.records[before]; if (!record) continue; accumulator.boardRequests += 1; - if (record.ok) accumulator.boardMs.push(record.ms); - else accumulator.boardFailures += 1; + if (!record.ok) { + accumulator.boardFailures += 1; + continue; + } + accumulator.boardMs.push(record.ms); + const name = pathClass(path).split("/").at(-1)!; + (accumulator.boardByRoute[name] ??= []).push(record.ms); } } @@ -439,6 +495,7 @@ export class Ramp { await this.readTasks(); await this.checkRetry(); await this.sampleEvents(); + await this.readSpend(); let running = 0; for (const run of this.runs.values()) if (run.status === "running") running += 1; if (!recordSample) return; @@ -457,9 +514,11 @@ export class Ramp { if (!this.tasks.has(taskId)) return; const id = String(row.id ?? row.runId); const previous = this.runs.get(id); + const status = String(row.status); this.runs.set(id, { - id, taskId, agentId: String(row.agentId), status: String(row.status), createdAt: ms(row.createdAt), startedAt: ms(row.startedAt), - finishedAt: ms(row.finishedAt), costUsd: num(row.costUsd) ?? previous?.costUsd ?? 0, sampled: previous?.sampled ?? false, + id, taskId, agentId: String(row.agentId), status, createdAt: ms(row.createdAt), startedAt: ms(row.startedAt), + finishedAt: ms(row.finishedAt), everFailed: (previous?.everFailed ?? false) || FAILED_RUN.has(status), + everEnded: (previous?.everEnded ?? false) || ENDED_RUN.has(status), sampled: previous?.sampled ?? false, error: typeof row.error === "string" && row.error ? row.error : null, errorCode: typeof row.errorCode === "string" && row.errorCode ? row.errorCode : null, liveness: typeof row.livenessReason === "string" && row.livenessReason ? row.livenessReason : null, @@ -532,7 +591,9 @@ export class Ramp { if (task.outcome === "failed" && task.lastRetryCheckAt !== null) continue; task.lastRetryCheckAt = now; const view = await this.deps.api.get(`/api/issues/${task.id}`).catch(() => null); - if (view && view.status !== "done" && view.interruption?.canRetry === true && !view.interruption?.retryWait) { + const interruption = view?.interruption; + const systemRetrying = interruption?.state === "retry_scheduled" || Boolean(interruption?.nextRetryAt) || Boolean(interruption?.retryWait); + if (view && view.status !== "done" && interruption?.canRetry === true && !systemRetrying) { task.neededRetry = true; this.deps.log(`Task ${task.nonce} offers Retry`); } @@ -576,8 +637,10 @@ export class Ramp { if (known === undefined || run.startedAt < known) firstStart.set(run.taskId, run.startedAt); } const samples = accumulator.runningSamples; - let spend = 0; - for (const run of runs) spend += run.costUsd; + const failed = this.classifyFailedRuns(runs); + const spendAtEnd = this.accumulators[stepIndex + 1]?.spendAtStartUsd ?? this.spendUsd ?? 0; + const byRoute: Record = {}; + for (const [name, values] of Object.entries(accumulator.boardByRoute)) byRoute[name] = distribution(values); return { step: accumulator.step, startedAt: accumulator.startedAt, @@ -587,7 +650,11 @@ export class Ramp { tasksFinished: tasks.filter(task => task.outcome === "done").length, tasksFailed: tasks.filter(task => task.outcome === "failed").length, tasksNeedingRetry: tasks.filter(task => task.neededRetry).length, - runsFailed: runs.filter(run => FAILED_RUN.has(run.status)).length, + runsEnded: runs.filter(run => run.everEnded).length, + runsFailed: failed.recovered + failed.unrecovered + failed.pending, + runsFailedRecovered: failed.recovered, + runsFailedUnrecovered: failed.unrecovered, + runsFailedPending: failed.pending, runsInterrupted: runs.filter(run => run.status === "interrupted").length, runsCancelled: runs.filter(run => run.status === "cancelled").length, peakRunning: samples.length ? Math.max(...samples) : 0, @@ -597,12 +664,27 @@ export class Ramp { ttftMs: distribution(accumulator.ttftMs), firstActivityMs: distribution(accumulator.firstActivityMs), runDurationMs: distribution(runs.flatMap(run => run.startedAt !== null && run.finishedAt !== null ? [run.finishedAt - run.startedAt] : [])), - board: { requests: accumulator.boardRequests, failures: accumulator.boardFailures, ms: distribution(accumulator.boardMs) }, + board: { requests: accumulator.boardRequests, failures: accumulator.boardFailures, ms: distribution(accumulator.boardMs), byRoute }, server: serverMetrics(accumulator.serverSamples, { earlier: this.accumulators.slice(0, stepIndex).flatMap(earlier => earlier.serverSamples), runStartedAt: this.accumulators[0]?.startedAt ?? null, }), - recordedSpendUsd: Math.round(spend * 100) / 100, + recordedSpendUsd: Math.round(Math.max(0, spendAtEnd - accumulator.spendAtStartUsd) * 100) / 100, }; } + + private classifyFailedRuns(runs: readonly RunRecord[]): { recovered: number; unrecovered: number; pending: number } { + const now = this.deps.clock.now(); + const out = { recovered: 0, unrecovered: 0, pending: 0 }; + for (const run of runs) { + if (!run.everFailed) continue; + const task = this.tasks.get(run.taskId)!; + const live = this.runsOf(task.id).some(candidate => LIVE_RUN_STATUSES.has(candidate.status)); + if (task.outcome === "done") out.recovered += 1; + else if (task.outcome === "failed" || task.neededRetry) out.unrecovered += 1; + else if (!live && run.finishedAt !== null && now - run.finishedAt >= this.deps.options.thresholds.recoveryGraceMs) out.unrecovered += 1; + else out.pending += 1; + } + return out; + } } diff --git a/scripts/scale-ramp/report.ts b/scripts/scale-ramp/report.ts index 745dbc1e03a..f52679b8bf6 100644 --- a/scripts/scale-ramp/report.ts +++ b/scripts/scale-ramp/report.ts @@ -32,6 +32,7 @@ export interface RampResult { tasksCreated: number; taskCapReached: boolean; recordedSpendUsd: number | null; + unpricedCostEvents: number; sources: Record; cleanup: CleanupReport | null; requests: { total: number; failed: number }; @@ -53,6 +54,10 @@ export function incompleteReasons(outcome: RampOutcome | null): string[] { const missing = notMeasured(outcome); if (missing.length) reasons.push(`criteria not measured: ${missing.join(", ")}`); if (outcome.taskCapReached) reasons.push("the task cap was reached, so a step may have run below its concurrency"); + if (outcome.recordedSpendUsd === null) reasons.push("recorded model spend could not be read at the end of the run"); + if (outcome.unpricedCostEvents > 0) { + reasons.push(`${outcome.unpricedCostEvents} cost events have no known price, so recorded spend is a lower bound and the spend cap does not cover them`); + } if (outcome.openTasksAtEnd > 0) reasons.push(`${outcome.openTasksAtEnd} tasks were still open when the drain ended`); return reasons; } @@ -100,9 +105,13 @@ export function buildResult(input: { tasksCreated: outcome?.tasksCreated ?? 0, taskCapReached: outcome?.taskCapReached ?? false, recordedSpendUsd: outcome ? outcome.recordedSpendUsd : null, + unpricedCostEvents: outcome?.unpricedCostEvents ?? 0, sources: { runsAndTasks: outcome?.runsListTruncated ? "API (company run list was full; open tasks without a listed run were read one by one)" : "API", - boardLatency: "harness GET mix (dashboard, issues, agents, live runs, sidebar badges)", + boardLatency: "harness GET mix (dashboard, issues, agents, live runs, sidebar badges), with a distribution per route", + modelSpend: outcome?.spendReadError ? `not measured: the last read of costs by agent failed (${outcome.spendReadError})` + : `costs by agent for the run's agents over all time (Paperclip's recorded cost events)${outcome?.unpricedCostEvents + ? `; ${outcome.unpricedCostEvents} events have no known price and are not included` : ""}`, firstTokenAndActivity: `run events of up to ${options.eventSamplePerStep} succeeded runs per step`, serverMetrics: outcome?.metricsSource === "endpoint" ? "PAPERCLIP_SCALE_METRICS_URL" : outcome?.metricsSource === "unavailable" ? "PAPERCLIP_SCALE_METRICS_URL gave no readable sample: not measured" : "not provided: not measured", @@ -129,7 +138,8 @@ export function summaryLines(result: RampResult): string[] { "", `Verdict: **${result.verdict}**. Target ${result.target.baseUrl} (${result.target.kind}).`, result.stop ? `Stopped at step ${result.stop.stepIndex + 1}: ${result.stop.reason}.` : "No stop.", - `Tasks created: ${result.tasksCreated}${result.taskCapReached ? " (task cap reached)" : ""}. Recorded model spend: ${result.recordedSpendUsd === null ? "not measured" : `$${result.recordedSpendUsd}`}; estimate was $${result.plan.estimate.totalUsd}.`, + `Tasks created: ${result.tasksCreated}${result.taskCapReached ? " (task cap reached)" : ""}. Recorded model spend: ${result.recordedSpendUsd === null ? "not measured" : `$${result.recordedSpendUsd}`}` + + `${result.unpricedCostEvents ? ` (incomplete: ${result.unpricedCostEvents} cost events have no known price)` : ""}; estimate was $${result.plan.estimate.totalUsd}.`, "", ]; for (const step of result.steps) { @@ -138,13 +148,15 @@ export function summaryLines(result: RampResult): string[] { `## Step ${step.index + 1}: ${step.concurrency} agents, ${step.holdMs / 60_000} min`, "", `- Tasks created / started / finished / failed / needed Retry: ${m.tasksCreated} / ${m.tasksStarted} / ${m.tasksFinished} / ${m.tasksFailed} / ${m.tasksNeedingRetry}`, - `- Runs failed / interrupted / cancelled: ${m.runsFailed} / ${m.runsInterrupted} / ${m.runsCancelled}`, + `- Runs ended / failed / interrupted / cancelled: ${m.runsEnded} / ${m.runsFailed} / ${m.runsInterrupted} / ${m.runsCancelled}`, + `- Failed runs whose task finished by itself / did not / still pending: ${m.runsFailedRecovered} / ${m.runsFailedUnrecovered} / ${m.runsFailedPending}`, `- Running agents peak / mean: ${m.peakRunning} / ${m.meanRunning ?? "not measured"}`, `- Queue wait p50 / p95 / p99: ${dist(m.queueWaitMs, seconds)}`, `- Time to first token p50 / p95 / p99: ${dist(m.ttftMs, seconds)}`, `- First activity p50 / p95 / p99: ${dist(m.firstActivityMs, seconds)}`, `- Run duration p50 / p95 / p99: ${dist(m.runDurationMs, seconds)}`, `- Board API p50 / p95 / p99: ${dist(m.board.ms, millis)}; failed ${m.board.failures} of ${m.board.requests}`, + ...Object.entries(m.board.byRoute).map(([route, d]) => ` - ${route} p50 / p90 / p99: ${millis(d.p50)} / ${millis(d.p90)} / ${millis(d.p99)} (n=${d.n})`), `- Event-loop utilization max: ${m.server.eventLoopUtilizationMax ?? "not measured"}; delay p99 max: ${millis(m.server.eventLoopDelayP99MsMax)}; statements/s max: ${m.server.statementsPerSecondMax ?? "not measured"}; pool wait p99 max: ${millis(m.server.poolWaitP99MsMax)}`, "- Criteria (final):", ...step.criteriaFinal.map(criterionLine), @@ -157,7 +169,9 @@ export function summaryLines(result: RampResult): string[] { if (result.cleanup) { const c = result.cleanup; lines.push(`Cleanup in ${seconds(c.durationMs)}: ${c.runsCancelled} runs cancelled, ${c.tasksArchived} tasks archived, ${c.agentsDeleted} agents deleted` - + ` (${c.agentsKeptForCostHistory} kept terminated for cost history), sandbox leases still active: ${c.activeSandboxLeases ?? "not readable"}, errors: ${c.errors.length}.`); + + ` (${c.agentsKeptForCostHistory} kept terminated for cost history, ${c.agentsStillTerminating.length} still terminating),` + + ` sandbox leases still active: ${c.activeSandboxLeases ?? "not readable"} (${c.sandboxLeasesReleasedDuringWait} released while the cleanup waited), errors: ${c.errors.length}.`); + for (const error of c.errors) lines.push(`- ${error}`); } if (result.error) lines.push(`Error: ${result.error}`); return lines; diff --git a/scripts/scale-ramp/scale-ramp-spend.test.ts b/scripts/scale-ramp/scale-ramp-spend.test.ts new file mode 100644 index 00000000000..73cd1453139 --- /dev/null +++ b/scripts/scale-ramp/scale-ramp-spend.test.ts @@ -0,0 +1,132 @@ +import assert from "node:assert/strict"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { describe, it } from "node:test"; +import { PaperclipClient, Redactor } from "./client.ts"; +import { parseOptions, QUALIFIED_OPENCODE_MODEL } from "./config.ts"; +import { checkSpend, estimateSpend } from "./estimate.ts"; +import { EXIT, main } from "./main.ts"; +import { Ramp } from "./ramp.ts"; +import { prepareCompany } from "./setup.ts"; +import { emptyState, fileStateStore, type RunState } from "./state.ts"; +import { baseArgs, goodMetrics, harness, METRICS_URL, ORIGIN, PROVIDER_KEY, readResult, tempDir, TOKEN } from "./test-harness.ts"; + +describe("dry run and spend", () => { + it("prints the plan and estimate and touches nothing", async () => { + const out = await tempDir(); + const h = harness(); + const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--dry-run"], h.deps); + assert.equal(code, EXIT.pass); + assert.equal(h.fetchCalls(), 0); + assert.deepEqual(await readdir(out), []); + const text = h.out.join("\n"); + assert.match(text, /Ramp: 10 -> 50 -> 100 -> 200 -> 500 -> 1000 agents/); + assert.match(text, /Estimated spend: \$\d/); + assert.match(text, /retry_needed_zero \[finish-line\]/); + assert.match(text, /Dry run: nothing was created or contacted/); + }); + + it("estimates tasks, sandbox-hours and cost from the steps", () => { + const options = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack", "--steps", "10,50", "--hold-minutes", "10", "--task-minutes", "5", + "--drain-minutes", "10"], {}, 0); + const estimate = estimateSpend(options); + assert.equal(estimate.agents, 50); + assert.equal(estimate.tasks, 10 * 2 + 50 * 2); + assert.equal(estimate.maxTasks, 150); + assert.equal(estimate.sandboxHours, 18.3); + assert.equal(estimate.modelUsd, 3); + assert.equal(estimate.totalUsd, 4.83); + }); + + it("requires --confirm-spend of at least the estimate above the threshold", async () => { + const estimate = { totalUsd: 120 } as ReturnType; + assert.equal(checkSpend(estimate, 5, null).ok, false); + assert.equal(checkSpend(estimate, 5, 100).ok, false); + assert.equal(checkSpend(estimate, 5, 130).ok, true); + assert.equal(checkSpend(estimate, 200, null).ok, true); + const out = await tempDir(); + const h = harness(); + const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--yes"], h.deps); + assert.equal(code, EXIT.usage); + assert.equal(h.fetchCalls(), 0); + assert.match(h.err.join("\n"), /--confirm-spend/); + }); + + it("defaults to the qualified OpenCode model of the runner", async () => { + const source = await readFile(path.join(import.meta.dirname, "../../packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts"), "utf8"); + const match = /QUALIFIED_OPENCODE_MODEL\s*=\s*"([^"]+)"/.exec(source); + assert.equal(match?.[1], QUALIFIED_OPENCODE_MODEL); + }); +}); + +describe("recorded model spend", () => { + it("records model spend from Paperclip's cost records, which the run list does not carry", async () => { + const out = await tempDir(); + const h = harness({ costPerRunUsd: 0.25 }); + await main(baseArgs(out, ["--steps", "2", "--drain-minutes", "0"]), h.deps); + const result = await readResult(out); + const finished = [...h.fake.runs.values()].filter(run => run.status === "succeeded").length; + assert.ok(finished > 0); + assert.equal(result.recordedSpendUsd, Math.round(finished * 25) / 100); + assert.equal(result.steps[0]!.metrics.recordedSpendUsd, result.recordedSpendUsd); + const capped = await tempDir(); + const h2 = harness({ costPerRunUsd: 3 }); + await main(baseArgs(capped, ["--steps", "2", "--hold-minutes", "20"]), h2.deps); + assert.equal((await readResult(capped)).stop!.criterion, "spend_cap"); + }); + + it("keeps the spend of a ramp that crosses a month boundary", async () => { + const out = await tempDir(); + const h = harness({ costPerRunUsd: 0.25 }); + h.clock.t = Date.parse("2026-11-30T23:58:00.000Z"); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + const finished = [...h.fake.runs.values()].filter(run => run.status === "succeeded"); + assert.ok(finished.some(run => new Date(run.finishedAt!).getUTCMonth() === 10), "some spend is in the earlier month"); + assert.ok(finished.some(run => new Date(run.finishedAt!).getUTCMonth() === 11), "some spend is in the later month"); + assert.equal(result.recordedSpendUsd, Math.round(finished.length * 25) / 100); + }); + + it("grades a run incomplete when some cost events have no known price", async () => { + const out = await tempDir(); + const h = harness({ metricsUrl: METRICS_URL, metrics: goodMetrics, unpricedEventsPerAgent: 1 }, { PAPERCLIP_SCALE_METRICS_URL: METRICS_URL }); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + assert.equal(result.verdict, "incomplete"); + assert.ok(result.incompleteReasons.some(reason => /2 cost events have no known price/.test(reason)), result.incompleteReasons.join("; ")); + assert.match(result.sources.modelSpend!, /no known price/); + assert.equal(result.unpricedCostEvents, 2); + assert.match(await readFile(path.join(out, "scale-test-run", "SUMMARY.md"), "utf8"), /incomplete: 2 cost events have no known price/); + assert.ok(h.out.some(line => /^Warning: \d+ cost events of this run have no known price/.test(line))); + }); + + it("stops on a conservative spend bound when cost events have no known price", async () => { + const out = await tempDir(); + const h = harness({ costPerRunUsd: 0, unpricedEventsPerAgent: 1 }, { PAPERCLIP_SCALE_MODEL_USD_PER_TASK: "0.5" }); + const options = parseOptions(baseArgs(out, ["--steps", "2", "--hold-minutes", "20"]), h.deps.env, h.clock.now()); + const api = new PaperclipClient(options.target, TOKEN, h.deps.fetcher, h.clock, new Redactor([TOKEN])); + const state: RunState = emptyState(options.label, options.target.baseUrl, h.clock.now()); + const store = fileStateStore(options.outDir); + await prepareCompany({ api, options, state, store, credential: PROVIDER_KEY, log: () => {} }); + const outcome = await new Ramp({ api, clock: h.clock, fetcher: h.deps.fetcher, options, state, store, maxTasks: 100, spendCapUsd: 2, metricsToken: null, + log: () => {}, shouldStop: () => false }).run(); + assert.equal(outcome.recordedSpendUsd, 0); + assert.equal(outcome.stop!.criterion, "spend_cap"); + assert.match(outcome.stop!.reason, /no known price.*passed the cap of \$2/); + assert.ok(outcome.tasksCreated >= 5 && outcome.tasksCreated <= 6, `tasks: ${outcome.tasksCreated}`); + }); + + it("stops when recorded spend cannot be read, and reports spend as not measured", async () => { + const out = await tempDir(); + const h = harness({ failRequest: (method, route, count) => method === "GET" && route.endsWith("/costs/by-agent") && count > 2 + ? { status: 503, body: "{\"error\":\"unavailable\"}" } : null }); + const code = await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "20"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.fail); + assert.equal(result.stop!.criterion, "spend_unreadable"); + assert.match(result.stop!.reason, /could not be read 3 times in a row/); + assert.equal(result.recordedSpendUsd, null); + assert.match(result.sources.modelSpend!, /not measured/); + }); + +}); diff --git a/scripts/scale-ramp/scale-ramp.test.ts b/scripts/scale-ramp/scale-ramp.test.ts index 3eab4e9ac87..a4dae632a3f 100644 --- a/scripts/scale-ramp/scale-ramp.test.ts +++ b/scripts/scale-ramp/scale-ramp.test.ts @@ -1,100 +1,21 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; -import { mkdtemp, readdir, readFile, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; -import { after, describe, it } from "node:test"; +import { describe, it } from "node:test"; +import { cleanupRun } from "./cleanup.ts"; import { PaperclipClient, Redactor } from "./client.ts"; import { metricsCredential, parseOptions, QUALIFIED_OPENCODE_MODEL, readSecrets } from "./config.ts"; import { evaluate, type StepMetrics } from "./criteria.ts"; -import { checkSpend, estimateSpend } from "./estimate.ts"; -import { FakePaperclip, VirtualClock, type FakeConfig } from "./fake-paperclip.ts"; import { classifyHost, resolveTarget, TargetRefused } from "./guard.ts"; -import { EXIT, main, type MainDeps } from "./main.ts"; +import { EXIT, main } from "./main.ts"; import { Ramp, serverMetrics } from "./ramp.ts"; -import { verdictOf, type RampResult } from "./report.ts"; +import { verdictOf } from "./report.ts"; import { ensureAgents, prepareCompany } from "./setup.ts"; import { distribution } from "./stats.ts"; -import { emptyState, fileStateStore, mapLimit, type RunState } from "./state.ts"; +import { agentName, emptyState, fileStateStore, mapLimit, type RunState } from "./state.ts"; import { runTiming } from "./workload.ts"; - -const TOKEN = "board-token-SECRET-4f2a9c"; -const PROVIDER_KEY = "sk-or-v1-SECRET-provider-key-77"; -const METRICS_TOKEN = "metrics-token-SECRET-91"; -const HOST = "scale1.test.paperclip.app"; -const ORIGIN = `https://${HOST}`; -const METRICS_URL = "https://metrics.scale1.test/metrics"; - -const dirs: string[] = []; -after(async () => { - for (const dir of dirs) await rm(dir, { recursive: true, force: true }); -}); - -async function tempDir(): Promise { - const dir = await mkdtemp(path.join(tmpdir(), "scale-ramp-test-")); - dirs.push(dir); - return dir; -} - -interface Harness { - clock: VirtualClock; - fake: FakePaperclip; - out: string[]; - err: string[]; - deps: MainDeps; - fetchCalls: () => number; - interrupt: () => void; -} - -function harness(config: Partial = {}, env: Record = {}, answer = HOST): Harness { - const clock = new VirtualClock(); - const fake = new FakePaperclip(clock, { token: TOKEN, origin: ORIGIN, ...config }); - const out: string[] = []; - const err: string[] = []; - let calls = 0; - let handler: (() => void) | null = null; - const deps: MainDeps = { - env: { PAPERCLIP_SCALE_TOKEN: TOKEN, OPENROUTER_API_KEY: PROVIDER_KEY, ...env }, - fetcher: async (url, init) => { - calls += 1; - return fake.fetch(url, init); - }, - clock, - out: line => out.push(line), - err: line => err.push(line), - confirm: async () => answer, - onInterrupt: fn => { - handler = fn; - return () => { - handler = null; - }; - }, - random: () => 0.5, - }; - return { clock, fake, out, err, deps, fetchCalls: () => calls, interrupt: () => handler?.() }; -} - -const baseArgs = (out: string, extra: string[] = []) => [ - "--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--label", "scale-test-run", "--yes", - "--hold-minutes", "2", "--drain-minutes", "3", "--poll-seconds", "15", "--board-probe-seconds", "10", "--task-minutes", "1", ...extra, -]; - -async function readResult(out: string): Promise { - return JSON.parse(await readFile(path.join(out, "scale-test-run", "result.json"), "utf8")) as RampResult; -} - -function assertCleanedUp(fake: FakePaperclip): void { - assert.equal(fake.liveRuns().length, 0, "no queued or running run is left"); - assert.equal(fake.agents.size, 0, "every harness agent is deleted"); - assert.ok([...fake.issues.values()].every(issue => issue.hiddenAt), "every task is archived"); - assert.equal(fake.secrets.size, 0, "the stored provider secret is deleted"); - assert.ok([...fake.projects.values()].every(project => project.archivedAt), "the project is archived"); -} - -const goodMetrics = (running: number) => ({ - eventLoopUtilization: 0.2 + running / 1_000, mainThreadCpu: 0.25, eventLoopDelayP99Ms: 20, statementsPerSecond: 40 * running, - poolWaitP99Ms: 2, runEventLatenessP99Ms: 120, agentApiPreHandlerP99Ms: 15, leaseRenewalsMissed: 0, -}); +import { assertCleanedUp, baseArgs, goodMetrics, harness, HOST, METRICS_TOKEN, METRICS_URL, ORIGIN, PROVIDER_KEY, readResult, tempDir, TOKEN } from "./test-harness.ts"; describe("target guard", () => { it("classifies hosts", () => { @@ -147,61 +68,14 @@ describe("target guard", () => { }); }); -describe("dry run and spend", () => { - it("prints the plan and estimate and touches nothing", async () => { - const out = await tempDir(); - const h = harness(); - const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--dry-run"], h.deps); - assert.equal(code, EXIT.pass); - assert.equal(h.fetchCalls(), 0); - assert.deepEqual(await readdir(out), []); - const text = h.out.join("\n"); - assert.match(text, /Ramp: 10 -> 50 -> 100 -> 200 -> 500 -> 1000 agents/); - assert.match(text, /Estimated spend: \$\d/); - assert.match(text, /retry_needed_zero \[finish-line\]/); - assert.match(text, /Dry run: nothing was created or contacted/); - }); - - it("estimates tasks, sandbox-hours and cost from the steps", () => { - const options = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack", "--steps", "10,50", "--hold-minutes", "10", "--task-minutes", "5", - "--drain-minutes", "10"], {}, 0); - const estimate = estimateSpend(options); - assert.equal(estimate.agents, 50); - assert.equal(estimate.tasks, 10 * 2 + 50 * 2); - assert.equal(estimate.maxTasks, 150); - assert.equal(estimate.sandboxHours, 18.3); - assert.equal(estimate.modelUsd, 3); - assert.equal(estimate.totalUsd, 4.83); - }); - - it("requires --confirm-spend of at least the estimate above the threshold", async () => { - const estimate = { totalUsd: 120 } as ReturnType; - assert.equal(checkSpend(estimate, 5, null).ok, false); - assert.equal(checkSpend(estimate, 5, 100).ok, false); - assert.equal(checkSpend(estimate, 5, 130).ok, true); - assert.equal(checkSpend(estimate, 200, null).ok, true); - const out = await tempDir(); - const h = harness(); - const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--yes"], h.deps); - assert.equal(code, EXIT.usage); - assert.equal(h.fetchCalls(), 0); - assert.match(h.err.join("\n"), /--confirm-spend/); - }); - - it("defaults to the qualified OpenCode model of the runner", async () => { - const source = await readFile(path.join(import.meta.dirname, "../../packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts"), "utf8"); - const match = /QUALIFIED_OPENCODE_MODEL\s*=\s*"([^"]+)"/.exec(source); - assert.equal(match?.[1], QUALIFIED_OPENCODE_MODEL); - }); -}); - describe("criteria", () => { const empty = distribution([]); const metrics = (patch: Partial = {}): StepMetrics => ({ step: { index: 0, concurrency: 10, holdMs: 60_000 }, startedAt: 0, endedAt: 1, tasksCreated: 10, tasksStarted: 10, tasksFinished: 10, - tasksFailed: 0, tasksNeedingRetry: 0, runsFailed: 0, runsInterrupted: 0, runsCancelled: 0, peakRunning: 10, meanRunning: 9, + tasksFailed: 0, tasksNeedingRetry: 0, runsEnded: 10, runsFailed: 0, runsFailedRecovered: 0, runsFailedUnrecovered: 0, runsFailedPending: 0, + runsInterrupted: 0, runsCancelled: 0, peakRunning: 10, meanRunning: 9, queueWaitMs: distribution([1_000, 2_000]), taskToStartMs: empty, ttftMs: empty, firstActivityMs: distribution([4_000]), runDurationMs: empty, - board: { requests: 10, failures: 0, ms: distribution([100, 120, 130, 140]) }, + board: { requests: 10, failures: 0, ms: distribution([100, 120, 130, 140]), byRoute: {} }, server: { mainThreadCpuMax: null, eventLoopUtilizationMax: null, eventLoopDelayP99MsMax: null, statementsPerSecondMax: null, poolWaitP99MsMax: null, runEventLatenessP99MsMax: null, agentApiPreHandlerP99MsMax: null, leaseRenewalsMissed: null, samples: 0 }, recordedSpendUsd: 0, ...patch, @@ -217,22 +91,41 @@ describe("criteria", () => { assert.equal(results.lease_renewals_missed_zero, "not_measured"); assert.equal(results.run_event_lateness_p99, "not_measured"); assert.equal(results.kill_one_process_resumes, "not_measured"); - assert.equal(byId(evaluate(metrics({ board: { requests: 0, failures: 0, ms: empty } }), thresholds)).board_api_p90, "not_measured"); + assert.equal(byId(evaluate(metrics({ board: { requests: 0, failures: 0, ms: empty, byRoute: {} } }), thresholds)).board_api_p90, "not_measured"); }); it("fails each finish-line threshold it can measure", () => { const server = { mainThreadCpuMax: 0.7, eventLoopUtilizationMax: 0.5, eventLoopDelayP99MsMax: 10, statementsPerSecondMax: 1, poolWaitP99MsMax: 1, runEventLatenessP99MsMax: 1_500, agentApiPreHandlerP99MsMax: 100, leaseRenewalsMissed: 2, samples: 3 }; - const results = byId(evaluate(metrics({ tasksNeedingRetry: 1, peakRunning: 8, board: { requests: 4, failures: 1, ms: distribution([100, 600, 700]) }, server }), thresholds)); + const results = byId(evaluate(metrics({ tasksNeedingRetry: 1, peakRunning: 8, runsFailed: 1, runsFailedUnrecovered: 1, + board: { requests: 4, failures: 1, ms: distribution([100, 600, 700]), byRoute: {} }, server }), thresholds)); assert.deepEqual(results, { - retry_needed_zero: "fail", failed_runs_zero: "pass", tasks_rested_not_done_zero: "pass", concurrency_reached: "fail", board_api_p90: "fail", board_api_errors_zero: "fail", + retry_needed_zero: "fail", failed_runs_unrecovered_zero: "fail", failed_run_rate: "fail", tasks_rested_not_done_zero: "pass", concurrency_reached: "fail", + board_api_p90: "fail", board_api_errors_zero: "fail", queue_wait_p95: "pass", first_activity_p95: "pass", main_thread_cpu: "fail", run_event_lateness_p99: "fail", agent_api_pre_handler_p99: "fail", lease_renewals_missed_zero: "fail", kill_one_process_resumes: "not_measured", }); }); - it("only evaluates retry and failed runs as immediate stops", () => { - assert.deepEqual(evaluate(metrics(), thresholds, true).map(result => result.id), ["retry_needed_zero", "failed_runs_zero"]); + it("only evaluates retry and unrecovered failed runs as immediate stops", () => { + assert.deepEqual(evaluate(metrics(), thresholds, true).map(result => result.id), ["retry_needed_zero", "failed_runs_unrecovered_zero"]); + }); + + it("passes a step whose failed runs all recovered while their share of ended runs stays under the limit", () => { + const recovered = byId(evaluate(metrics({ runsEnded: 106, runsFailed: 1, runsFailedRecovered: 1 }), thresholds)); + assert.equal(recovered.failed_runs_unrecovered_zero, "pass"); + assert.equal(recovered.failed_run_rate, "pass"); + assert.equal(byId(evaluate(metrics({ runsEnded: 20, runsFailed: 1, runsFailedRecovered: 1 }), thresholds)).failed_run_rate, "fail"); + assert.equal(byId(evaluate(metrics({ runsEnded: 0 }), thresholds)).failed_run_rate, "not_measured"); + }); + + it("compares the unrounded failed-run share with the limit", () => { + const justOver = evaluate(metrics({ runsEnded: 49, runsFailed: 1, runsFailedRecovered: 1 }), thresholds).find(result => result.id === "failed_run_rate")!; + assert.equal(justOver.status, "fail"); + assert.equal(justOver.observed, 2); + const zero = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack", "--max-failed-run-percent", "0"], {}, 0).thresholds; + assert.equal(byId(evaluate(metrics({ runsEnded: 2_500, runsFailed: 1, runsFailedRecovered: 1 }), zero)).failed_run_rate, "fail"); + assert.equal(byId(evaluate(metrics({ runsEnded: 50, runsFailed: 1, runsFailedRecovered: 1 }), thresholds)).failed_run_rate, "pass"); }); it("reads first token and first activity from run spans, with an event fallback", () => { @@ -404,7 +297,7 @@ describe("ramp against the fake API", () => { mutate: (issue, run, now) => { issue.status = "cancelled"; run.status = "cancelled"; run.finishedAt = now; } }, { name: "blocked", criterion: "run_started", reason: /ended before any run started.*is blocked.*is queued/, mutate: issue => { issue.status = "blocked"; } }, - { name: "failed before it started", criterion: "failed_runs_zero", reason: /failed_runs_zero failed/, + { name: "failed before it started", criterion: "run_started", reason: /ended before any run started.*is failed/, mutate: (_issue, run, now) => { run.status = "failed"; run.finishedAt = now; } }, ]; for (const preflight of preflightCases) { @@ -450,11 +343,11 @@ describe("ramp against the fake API", () => { const out = await tempDir(); const h = harness({ failWhenRunningAbove: 0, runDurationMs: 3 * 60_000, agentReadyDelayMs: index => index === 0 ? 3_000 : 10 * 60_000 }); const started = h.clock.now(); - const code = await main(baseArgs(out, ["--steps", "1,3", "--min-concurrency-ratio", "0.5"]), h.deps); + const code = await main(baseArgs(out, ["--steps", "1,3", "--min-concurrency-ratio", "0.5", "--recovery-grace-minutes", "1"]), h.deps); const result = await readResult(out); assert.equal(code, EXIT.fail); assert.equal(result.stop!.stepIndex, 1); - assert.equal(result.stop!.criterion, "failed_runs_zero"); + assert.equal(result.stop!.criterion, "failed_runs_unrecovered_zero"); assert.equal(result.steps[0]!.metrics.runsFailed, 1); assert.ok(h.clock.now() - started < 6 * 60_000, "the failure is seen during the agent wait, not after it"); assertCleanedUp(h.fake); @@ -540,7 +433,7 @@ describe("ramp against the fake API", () => { assert.equal(code, EXIT.fail); assert.equal(result.verdict, "fail"); assert.equal(result.stop!.stepIndex, 1); - assert.equal(result.stop!.criterion, "failed_runs_zero"); + assert.equal(result.stop!.criterion, "failed_run_rate"); assert.equal(result.steps.length, 2); const agents = h.fake.requests.filter(request => request.method === "POST" && new URL(request.url).pathname.endsWith("/agents")); assert.equal(agents.length, 4, "the 8-agent step never created agents"); @@ -554,7 +447,7 @@ describe("ramp against the fake API", () => { const result = await readResult(out); assert.equal(result.verdict, "fail"); assert.equal(result.stop!.stepIndex, 0); - assert.ok(["retry_needed_zero", "failed_runs_zero"].includes(result.stop!.criterion!)); + assert.ok(["retry_needed_zero", "failed_runs_unrecovered_zero"].includes(result.stop!.criterion!)); assert.ok(result.steps[0]!.metrics.tasksNeedingRetry + result.steps[0]!.metrics.runsFailed > 0); }); @@ -625,6 +518,138 @@ describe("ramp against the fake API", () => { assert.ok(result.drained, "finished runs are not left counted as running"); }); + it("keeps ramping when Paperclip recovers a failed run by itself, counts it, and grades the failed-run rate at the step end", async () => { + const out = await tempDir(); + const h = harness({ failRun: index => index === 2, recoverFailedRunAfterMs: 30_000, runDurationMs: 20_000 }); + await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "4"]), h.deps); + const result = await readResult(out); + const metrics = result.steps[0]!.metrics; + assert.equal(metrics.runsFailed, 1); + assert.equal(metrics.runsFailedRecovered, 1); + assert.equal(metrics.runsFailedUnrecovered, 0); + assert.equal(metrics.tasksNeedingRetry, 0, "a scheduled automatic retry is not a task that needs Retry"); + assert.equal(result.stop!.criterion, "failed_run_rate"); + assert.match(result.stop!.reason, /at the end of the step/); + assert.ok(metrics.tasksFinished >= 3, "the step kept creating work after the failure"); + const tolerant = await tempDir(); + const h2 = harness({ failRun: index => index === 2, recoverFailedRunAfterMs: 30_000, runDurationMs: 20_000 }); + await main(baseArgs(tolerant, ["--steps", "2", "--hold-minutes", "4", "--max-failed-run-percent", "50", "--min-concurrency-ratio", "0.5"]), h2.deps); + const passed = await readResult(tolerant); + assert.equal(passed.stop, null); + assert.ok(passed.steps[0]!.criteriaFinal.filter(c => c.id.startsWith("failed_run")).every(c => c.status === "pass")); + }); + + it("stops when a failed run's task has not finished within the recovery grace", async () => { + const out = await tempDir(); + const h = harness({ failRun: index => index === 2 }); + const started = h.clock.now(); + const code = await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "20", "--recovery-grace-minutes", "2"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.fail); + assert.equal(result.stop!.criterion, "failed_runs_unrecovered_zero"); + assert.equal(result.steps[0]!.metrics.runsFailedUnrecovered, 1); + assert.ok(h.clock.now() - started < 10 * 60_000, "it stops once the grace runs out, not at the end of the hold"); + }); + + it("counts a run that Paperclip retries on the same run id once, as recovered, with a share of at most 100%", async () => { + const out = await tempDir(); + const h = harness({ failRun: index => index === 2, retrySameRunAfterMs: 30_000, runDurationMs: 20_000 }); + await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "4", "--max-failed-run-percent", "50", "--min-concurrency-ratio", "0.5"]), h.deps); + const result = await readResult(out); + const metrics = result.steps[0]!.metrics; + const retried = [...h.fake.runs.values()].find(run => run.recovery)!; + assert.equal(retried.status, "succeeded", "the failed run itself finished on its retry"); + assert.equal(metrics.runsFailed, 1); + assert.equal(metrics.runsFailedRecovered, 1); + assert.equal(metrics.tasksNeedingRetry, 0); + assert.ok(metrics.runsEnded >= metrics.runsFailed); + const rate = result.steps[0]!.criteriaFinal.find(criterion => criterion.id === "failed_run_rate")!; + assert.equal(rate.observed, Math.round(1_000 / metrics.runsEnded) / 10); + assert.equal(rate.status, "pass"); + }); + + it("keeps a failed run in the ended runs while Paperclip retries it on the same run id", async () => { + const out = await tempDir(); + const h = harness({ failRun: index => index === 2, retrySameRunAfterMs: 30_000, sameRunRetryDurationMs: 60 * 60_000, runDurationMs: 20_000 }); + await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "4", "--drain-minutes", "0", "--max-failed-run-percent", "50", + "--min-concurrency-ratio", "0.5"]), h.deps); + const metrics = (await readResult(out)).steps[0]!.metrics; + const succeeded = [...h.fake.runs.values()].filter(run => run.status === "succeeded").length; + assert.equal(metrics.runsFailed, 1); + assert.equal(metrics.runsFailedPending, 1, "the retry is still running"); + assert.equal(metrics.runsEnded, succeeded + 1, "the retrying run still counts as ended once"); + }); + + it("keeps the termination wait to a bounded number of reads for a large run", async () => { + const out = await tempDir(); + const h = harness({ terminationDelayMs: 60 * 60_000 }); + const options = parseOptions(baseArgs(out, ["--steps", "2"]), h.deps.env, h.clock.now()); + const api = new PaperclipClient(options.target, TOKEN, h.deps.fetcher, h.clock, new Redactor([TOKEN])); + const state: RunState = emptyState(options.label, options.target.baseUrl, h.clock.now()); + await prepareCompany({ api, options, state, store: fileStateStore(options.outDir), credential: PROVIDER_KEY, log: () => {} }); + for (let index = 0; index < 1_000; index += 1) { + const agent = await api.post<{ id: string }>(`/api/companies/${state.companyId}/agents`, { name: agentName(options.label, index) }); + state.agentIds.push(agent.id); + } + const before = h.fake.requests.length; + const report = await cleanupRun({ api, clock: h.clock, label: options.label, state }); + const reads = h.fake.requests.slice(before).filter(request => request.method === "GET" && /\/api\/agents\/[0-9a-f-]+$/.test(new URL(request.url).pathname)).length; + assert.equal(report.agentsStillTerminating.length, 1_000); + assert.ok(reads <= 5_000, `termination reads: ${reads}`); + }); + + it("reports board latency per route", async () => { + const out = await tempDir(); + const h = harness({ boardLatencyMs: () => 300 }); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const byRoute = (await readResult(out)).steps[0]!.metrics.board.byRoute; + assert.deepEqual(Object.keys(byRoute).sort(), ["agents", "dashboard", "issues", "live-runs", "sidebar-badges"]); + assert.equal(byRoute.dashboard!.p50, 300); + assert.ok(byRoute.issues!.n > 0); + const summary = await readFile(path.join(out, "scale-test-run", "SUMMARY.md"), "utf8"); + assert.match(summary, / - dashboard p50 \/ p90 \/ p99: 300 ms/); + }); + + it("deletes an agent only after Paperclip completes its termination", async () => { + const out = await tempDir(); + const h = harness({ terminationDelayMs: 2 * 60_000 }); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + assert.deepEqual(result.cleanup!.errors, []); + assert.deepEqual(result.cleanup!.agentsStillTerminating, []); + assert.equal(result.cleanup!.agentsDeleted, 2); + assertCleanedUp(h.fake); + }); + + it("names the agents still terminating and the sandbox leases still active, and finishes them with --cleanup-only later", async () => { + const out = await tempDir(); + const h = harness({ terminationDelayMs: 20 * 60_000, leaseLingerMs: 20 * 60_000 }); + const code = await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.incomplete); + assert.equal(result.cleanup!.agentsStillTerminating.length, 2); + assert.equal(result.cleanup!.agentsDeleted, 0); + assert.ok(result.cleanup!.activeSandboxLeases! > 0); + assert.equal(result.cleanup!.activeSandboxLeaseIds.length, result.cleanup!.activeSandboxLeases); + assert.ok(result.cleanup!.errors.some(error => /had not completed termination/.test(error))); + assert.ok(result.cleanup!.errors.some(error => /still active after 5 min: lease-/.test(error))); + assert.ok(!result.cleanup!.errors.some(error => /409/.test(error)), "no delete is sent before termination completes"); + await h.clock.sleep(20 * 60_000); + const later = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--cleanup-only", "scale-test-run", "--yes"], h.deps); + assert.equal(later, EXIT.pass); + assertCleanedUp(h.fake); + }); + + it("counts sandbox leases that release while the cleanup waits", async () => { + const out = await tempDir(); + const h = harness({ leaseLingerMs: 2 * 60_000 }); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const cleanup = (await readResult(out)).cleanup!; + assert.equal(cleanup.activeSandboxLeases, 0); + assert.ok(cleanup.sandboxLeasesReleasedDuringWait > 0); + assert.deepEqual(cleanup.errors, []); + }); + it("cleans up after a crash in the middle of the ramp", async () => { const out = await tempDir(); const h = harness({ failRequest: (method, route, count) => method === "POST" && route.endsWith("/issues") && count === 5 ? { status: 500, body: "boom" } : null }); diff --git a/scripts/scale-ramp/test-harness.ts b/scripts/scale-ramp/test-harness.ts new file mode 100644 index 00000000000..26229693107 --- /dev/null +++ b/scripts/scale-ramp/test-harness.ts @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after } from "node:test"; +import { FakePaperclip, VirtualClock, type FakeConfig } from "./fake-paperclip.ts"; +import type { MainDeps } from "./main.ts"; +import type { RampResult } from "./report.ts"; + +export const TOKEN = "board-token-SECRET-4f2a9c"; +export const PROVIDER_KEY = "sk-or-v1-SECRET-provider-key-77"; +export const METRICS_TOKEN = "metrics-token-SECRET-91"; +export const HOST = "scale1.test.paperclip.app"; +export const ORIGIN = `https://${HOST}`; +export const METRICS_URL = "https://metrics.scale1.test/metrics"; + +const dirs: string[] = []; +after(async () => { + for (const dir of dirs) await rm(dir, { recursive: true, force: true }); +}); + +export async function tempDir(): Promise { + const dir = await mkdtemp(path.join(tmpdir(), "scale-ramp-test-")); + dirs.push(dir); + return dir; +} + +export interface Harness { + clock: VirtualClock; + fake: FakePaperclip; + out: string[]; + err: string[]; + deps: MainDeps; + fetchCalls: () => number; + interrupt: () => void; +} + +export function harness(config: Partial = {}, env: Record = {}, answer = HOST): Harness { + const clock = new VirtualClock(); + const fake = new FakePaperclip(clock, { token: TOKEN, origin: ORIGIN, ...config }); + const out: string[] = []; + const err: string[] = []; + let calls = 0; + let handler: (() => void) | null = null; + const deps: MainDeps = { + env: { PAPERCLIP_SCALE_TOKEN: TOKEN, OPENROUTER_API_KEY: PROVIDER_KEY, ...env }, + fetcher: async (url, init) => { + calls += 1; + return fake.fetch(url, init); + }, + clock, + out: line => out.push(line), + err: line => err.push(line), + confirm: async () => answer, + onInterrupt: fn => { + handler = fn; + return () => { + handler = null; + }; + }, + random: () => 0.5, + }; + return { clock, fake, out, err, deps, fetchCalls: () => calls, interrupt: () => handler?.() }; +} + +export const baseArgs = (out: string, extra: string[] = []) => [ + "--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--label", "scale-test-run", "--yes", + "--hold-minutes", "2", "--drain-minutes", "3", "--poll-seconds", "15", "--board-probe-seconds", "10", "--task-minutes", "1", ...extra, +]; + +export async function readResult(out: string): Promise { + return JSON.parse(await readFile(path.join(out, "scale-test-run", "result.json"), "utf8")) as RampResult; +} + +export function assertCleanedUp(fake: FakePaperclip): void { + assert.equal(fake.liveRuns().length, 0, "no queued or running run is left"); + assert.equal(fake.agents.size, 0, "every harness agent is deleted"); + assert.ok([...fake.issues.values()].every(issue => issue.hiddenAt), "every task is archived"); + assert.equal(fake.secrets.size, 0, "the stored provider secret is deleted"); + assert.ok([...fake.projects.values()].every(project => project.archivedAt), "the project is archived"); +} + +export const goodMetrics = (running: number) => ({ + eventLoopUtilization: 0.2 + running / 1_000, mainThreadCpu: 0.25, eventLoopDelayP99Ms: 20, statementsPerSecond: 40 * running, + poolWaitP99Ms: 2, runEventLatenessP99Ms: 120, agentApiPreHandlerP99Ms: 15, leaseRenewalsMissed: 0, +}); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 11a49de8470..980f64e64ff 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -1,6 +1,6 @@ { "inputs": { - "package.json": "2d2a4abebb6a5931be1a8f0c8fb2615890324d21", + "package.json": "b6a185b015b2ec9ffc80564f0970916b65b7d6ba", "packages/plugins/sdk/package.json": "b7a4936e2803fd0d3b32dd7f17fc1ea86609ead0", "packages/plugins/sdk/src/bundlers.ts": "883bf3d9f2bd42877cfc0c3707cd882a6f6248d0", "packages/plugins/sdk/src/define-plugin.ts": "a99e07ce77ef72fcf1df1347346aacb8ba12e284", From 8f1d39da79d989e7b64aa3d8296153e71b196699 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:50:19 -0600 Subject: [PATCH 04/20] perf(server): cache the instance settings row per process (#21768) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process runs every agent on one Node main thread, and each database statement costs main-thread time > - The `default` instance settings row is read on hot paths: live run event delivery, run log redaction, the stranded-task recovery check, runner tool calls, adapter routes and run preparation > - A staging measurement with 7 live runs showed the full-row settings read at 10.24 statements per second, and 3.5 to 5.4 per second when idle > - The row changes only when an admin or a boot step writes it, so almost every read returns the same value > - This pull request adds a per-process read-through cache for that row, with in-process invalidation on every write and a 2 second age bound for changes made by another process > - The benefit is at most one settings read per 2 seconds per server process, whatever the load ## Linked Issues or Issue Description **Is your feature request related to a problem?** The full `instance_settings` row read (`select id, singleton_key, default_environment_id, general, experimental ...`) runs at 10.24 statements per second on staging with 7 live runs, and 3.5 to 5.4 per second at idle. It scales with run events and recovery checks, not with settings changes. **Describe the solution you would like** Cache the row per process. Drop the cached row when a settings write commits, in this process and, through the existing work-signal notification, in the other process during a deploy overlap. Bound the age of a cached row to 2 seconds, so any other change (a direct database edit, a second process outside an overlap) takes effect within 2 seconds. **Describe alternatives you have considered** A database trigger with LISTEN/NOTIFY would also catch direct edits, but it needs a migration, and work notifications cross processes only during a deploy overlap today. The existing signal plus a 2 second bound keeps the change small. ## What Changed - New `server/src/services/instance-settings-cache.ts`: a read-through cache keyed by the database client. Concurrent misses share one read. A cached row is at most `INSTANCE_SETTINGS_CACHE_TTL_MS` (2000 ms) old, measured from the start of the read. Every caller gets its own copy. Reads through a transaction handle skip the cache. - `instanceSettingsService` `get`, `getGeneral` and `getExperimental` use the cache. Write paths (`update`, `updateGeneral`, `updateExperimental`, and the feedback vote save) still read the row fresh. - Every settings write publishes an `instance-settings-changed` work signal through the existing work-signal channel (`@paperclipai/db/work-signals`). Inside a transaction it is the first signal of the write, so its `pg_notify` payload goes out before the other wakes of the same commit (for example `status-card-evaluation`). This process drops the cached row when the write commits. During a deploy overlap, when work notifications cross processes, the other process drops its cached row on receipt, before a worker woken by the same write reads the settings. A reconnect of the notification listener also drops the row. - `fillUnsetInstanceDefault` writes through `update({ db: tx })`, so its signal is sent when its transaction commits. - A read that starts before an invalidation never stores its result, so an old value can not come back after a write. - The test setup clears the cache before each test, because many tests write the row directly. Hot callers of the cached row: - Live run event delivery: `live-run-event-redaction.ts` (`censorUsernameInLogs`), once per delivery batch. - Run output and run lifecycle redaction: `heartbeat.ts` `getCurrentUserRedactionOptions`, used by `run-output.ts`, `run-lifecycle.ts`, `run-completion.ts`. - The stranded-task recovery check: `recovery/service.ts` reads `getExperimental().enableAgentChat` once per checked conversation issue. - Runner tool calls: `paperclip-runner-tool-authority.ts` (`enableIsolatedWorkspaces`, `enableExternalObjects`). - Adapter routes: `app.ts` (`enableNativeRunner`, `enableOpenAiDot`) per request. - Run preparation: `heartbeat.ts` (`instance_settings` preparation step), `queued-run-line.ts`, `queued-run-dispatch-liveness.ts`, `run-control.ts`. - Issue and comment paths in `issues.ts` (`censorUsernameInLogs`, `enableAgentChat`). ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/instance-settings-cache.test.ts` (embedded PostgreSQL): - 150 hot reads (`getGeneral`, `getExperimental`, `get` from new service objects) after one warm read: 0 statements. Without the cache the same test measures 150 statements (red run). - 20 concurrent misses: 1 statement. - `updateExperimental` and `updateGeneral` are visible at once to a new read in the same process. - `fillUnsetInstanceDefault` (transaction write of the default environment) is visible at once after it returns. - A change written by a second client (another process) becomes visible within 2000 ms plus a 500 ms test margin. - A caller that changes the returned object does not change the cached row. - A read through a transaction handle sees the transaction's uncommitted write, two such reads issue 2 statements, and the cache does not keep the write after rollback. - A read that started before an invalidation is not stored. - A received `instance-settings-changed` notification from another process drops the cached row (next read issues 1 statement). - `updateExperimental({ enableStatusCards: true })` sends `instance-settings-changed` as its first notification, before `status-card-evaluation`; `updateGeneral` sends it alone. - The server tests that use instance settings or write the row directly (230 files): see the run notes in the first comment. ## Risks - A direct database edit, or a change from a second process outside a deploy overlap, takes up to 2 seconds to apply in this process. Before this change it applied at the next read. This includes access flags such as `enableOwnerInstanceAdmin` (read per cloud-tenant request) and the default environment. - A change made through the settings service applies at once in this process, and during a deploy overlap at once in the other process. - A new code path that writes the `default` row must call `announceInstanceSettingsChange`, or its change applies within 2 seconds. - No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes (no user-facing setting or command changed) - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../agent-runtime-assignments.test.ts | 2 + .../__tests__/agent-runtime-skills.test.ts | 2 + server/src/__tests__/ai-connections.test.ts | 2 + .../__tests__/instance-settings-cache.test.ts | 168 ++++++++++++++++++ .../__tests__/project-environments.test.ts | 15 +- server/src/__tests__/setup-supertest.ts | 6 + server/src/__tests__/smoke-lab.test.ts | 2 + .../src/middleware/cloud-tenant-actor.test.ts | 4 +- .../cloud-tenant-sync-postgres.test.ts | 3 + server/src/services/feedback.ts | 2 + .../src/services/instance-settings-cache.ts | 63 +++++++ server/src/services/instance-settings.ts | 14 +- .../native-run-log-watermark.test.ts | 3 +- 13 files changed, 278 insertions(+), 8 deletions(-) create mode 100644 server/src/__tests__/instance-settings-cache.test.ts create mode 100644 server/src/services/instance-settings-cache.ts diff --git a/server/src/__tests__/agent-runtime-assignments.test.ts b/server/src/__tests__/agent-runtime-assignments.test.ts index 6c9b9bc2550..a049dd6b92f 100644 --- a/server/src/__tests__/agent-runtime-assignments.test.ts +++ b/server/src/__tests__/agent-runtime-assignments.test.ts @@ -15,6 +15,7 @@ import { toolAccessService } from "../services/tool-access.js"; import { createToolGatewayService } from "../services/tool-gateway.js"; import { connectionIntentService } from "../services/connection-intents.js"; import { aiConnectionService } from "../services/ai-connections.js"; +import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js"; vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn().mockResolvedValue(undefined) })); @@ -170,6 +171,7 @@ describeDatabase("connection assignment synchronization", () => { await pluginAgentRuntimeState(db, pluginId, companyId, agentId); const before = (await events()).length; await db.update(instanceSettings).set({ experimental: { enableChatConnectors: true } }); + invalidateInstanceSettingsCache(); expect(await events()).toHaveLength(before + 2); expect((await pluginAgentRuntimeState(db, pluginId, companyId, agentId))!.connectionAssignments.features).toEqual({ publicMcp: false, chatConnectors: true }); }); diff --git a/server/src/__tests__/agent-runtime-skills.test.ts b/server/src/__tests__/agent-runtime-skills.test.ts index 0f2f5d1f5eb..26207f985de 100644 --- a/server/src/__tests__/agent-runtime-skills.test.ts +++ b/server/src/__tests__/agent-runtime-skills.test.ts @@ -9,6 +9,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { pluginAgentRuntimeState } from "../services/plugin-agent-runtime-state.js"; import { instanceSettingsService } from "../services/instance-settings.js"; +import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js"; const support = await getEmbeddedPostgresTestSupport(); const describeDatabase = support.supported ? describe : describe.skip; @@ -143,6 +144,7 @@ describeDatabase("skill runtime invalidation", () => { it("resolves immutable pinned and latest skill sources and removes unassigned skills", async () => { await instanceSettingsService(db).getExperimental(); await db.update(instanceSettings).set({ experimental: { enableBetaSkills: true } }); + invalidateInstanceSettingsCache(); const first = await publish("first version", 1); const pinned = await agent([{ key, versionId: first.id }]); const latest = await agent(); diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index ae747a42c69..3bb34223966 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -49,6 +49,7 @@ import * as copilotProbe from "../services/copilot-connection-probe.js"; import * as settingsModule from "../services/instance-settings.js"; import { agentRoutes } from "../routes/agents.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; +import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js"; vi.mock("../services/local-ai-browser-login.js", () => ({ startLocalBrowserLogin: () => ({ authorizationUrl: "https://auth.openai.com/codex/device", code: "ABCD-EFGHJ", abort: () => {} }), })); @@ -2519,6 +2520,7 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" await db.insert(toolConnections).values(ids.map(id => ({ ...connection, id, uid: id, name: `Cost ${id}` }))); await db.insert(connectionGrants).values(ids.map(connectionId => ({ ...grant, id: randomUUID(), connectionId }))); selects.mockClear(); + invalidateInstanceSettingsCache(); const large = await request(app).get(url); largeQueries = selects.mock.calls.length; expect(large.status).toBe(200); diff --git a/server/src/__tests__/instance-settings-cache.test.ts b/server/src/__tests__/instance-settings-cache.test.ts new file mode 100644 index 00000000000..ce433d4e1fc --- /dev/null +++ b/server/src/__tests__/instance-settings-cache.test.ts @@ -0,0 +1,168 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { createDb, environments, companies, instanceSettings, type Db } from "@paperclipai/db"; +import { eq, sql } from "drizzle-orm"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { createStatementCensus } from "./helpers/statement-census.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; +import { INSTANCE_SETTINGS_CACHE_TTL_MS, INSTANCE_SETTINGS_CHANGED_TOPIC, invalidateInstanceSettingsCache, readThroughInstanceSettings } from "../services/instance-settings-cache.js"; +import { DATABASE_WORK_CHANNEL, enableDatabaseWorkNotifications, receiveDatabaseWorkNotification } from "@paperclipai/db/work-signals"; +import { fillUnsetInstanceDefault } from "../services/managed-instance-default.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +async function waitUntil(check: () => Promise, timeoutMs: number) { + const started = Date.now(); + while (Date.now() - started < timeoutMs) { + if (await check()) return Date.now() - started; + await new Promise(resolve => setTimeout(resolve, 50)); + } + throw new Error(`condition not met within ${timeoutMs} ms`); +} + +(support.supported ? describe : describe.skip)("instance settings read-through cache", () => { + let database: Awaited>; + let db: Db; + let otherProcess: Db; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("instance-settings-cache-"); + db = createDb(database.connectionString); + otherProcess = createDb(database.connectionString); + await db.insert(companies).values({ name: "Settings cache", issuePrefix: "SCC" }); + }, 90_000); + + afterAll(async () => { + await Promise.all([db?.$client.end({ timeout: 0 }), otherProcess?.$client.end({ timeout: 0 })]); + await database?.cleanup(); + }, 60_000); + + beforeEach(async () => { + await db.delete(instanceSettings); + invalidateInstanceSettingsCache(); + }); + + it("serves repeated hot reads from one statement", async () => { + const census = createStatementCensus(db); + try { + const settings = instanceSettingsService(db); + await settings.get(); + const measured = await census.measure(async () => { + for (let index = 0; index < 50; index++) { + await Promise.all([settings.getGeneral(), settings.getExperimental(), instanceSettingsService(db).get()]); + } + }); + expect(measured.statements).toBe(0); + invalidateInstanceSettingsCache(); + const concurrent = await census.measure(() => Promise.all(Array.from({ length: 20 }, () => settings.getExperimental()))); + expect(concurrent.statements).toBe(1); + } finally { + census.uninstall(); + } + }); + + it("reads its own writes in this process at once", async () => { + const settings = instanceSettingsService(db); + expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false); + await settings.updateExperimental({ enableIsolatedWorkspaces: true }); + expect((await instanceSettingsService(db).getExperimental()).enableIsolatedWorkspaces).toBe(true); + expect((await settings.getGeneral()).censorUsernameInLogs).toBe(false); + await settings.updateGeneral({ censorUsernameInLogs: true }); + expect((await settings.getGeneral()).censorUsernameInLogs).toBe(true); + }); + + it("sees a default environment committed in a caller's transaction once it commits", async () => { + const settings = instanceSettingsService(db); + expect((await settings.get()).defaultEnvironmentId).toBeNull(); + const [environment] = await db.insert(environments).values({ + name: "Managed Sandbox", driver: "sandbox", status: "active", config: {}, + }).returning({ id: environments.id }); + expect((await fillUnsetInstanceDefault(db, environment!.id)).filled).toBe(true); + expect((await settings.get()).defaultEnvironmentId).toBe(environment!.id); + }); + + it("takes a change made by another process within the cache bound", async () => { + const settings = instanceSettingsService(db); + expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false); + const changedAt = Date.now(); + await otherProcess.update(instanceSettings) + .set({ experimental: sql`coalesce(${instanceSettings.experimental}, '{}'::jsonb) || '{"enableIsolatedWorkspaces":true}'::jsonb` }) + .where(eq(instanceSettings.singletonKey, "default")); + await waitUntil(async () => (await settings.getExperimental()).enableIsolatedWorkspaces === true, + INSTANCE_SETTINGS_CACHE_TTL_MS + 1_000); + expect(Date.now() - changedAt).toBeLessThanOrEqual(INSTANCE_SETTINGS_CACHE_TTL_MS + 500); + }); + + it("never shares cached rows with callers that mutate them", async () => { + const settings = instanceSettingsService(db); + const first = await settings.get(); + (first.experimental as unknown as Record).enableIsolatedWorkspaces = true; + expect((await settings.get()).experimental.enableIsolatedWorkspaces).toBe(false); + }); + + it("reads inside a transaction bypass the cache", async () => { + const settings = instanceSettingsService(db); + expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false); + await db.transaction(async tx => { + await tx.update(instanceSettings).set({ experimental: { enableIsolatedWorkspaces: true } }) + .where(eq(instanceSettings.singletonKey, "default")); + const inside = instanceSettingsService(tx as unknown as Db); + expect((await inside.getExperimental()).enableIsolatedWorkspaces).toBe(true); + const census = createStatementCensus(db); + try { + const reads = await census.measure(async () => { await inside.getExperimental(); await inside.getGeneral(); }); + expect(reads.statements).toBe(2); + } finally { + census.uninstall(); + } + throw new Error("rollback"); + }).catch(() => undefined); + expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false); + }); + + it("never stores a read that started before an invalidation", async () => { + const owner = {}; + let resolveFirst!: (value: string) => void; + const first = readThroughInstanceSettings(owner, () => new Promise(resolve => { resolveFirst = resolve; })); + invalidateInstanceSettingsCache(); + resolveFirst("before the write"); + expect(await first).toBe("before the write"); + let loads = 0; + expect(await readThroughInstanceSettings(owner, async () => { loads += 1; return "after the write"; })).toBe("after the write"); + expect(await readThroughInstanceSettings(owner, async () => { loads += 1; return "unexpected"; })).toBe("after the write"); + expect(loads).toBe(1); + }); + + it("drops the cached row when another process announces a settings change", async () => { + const settings = instanceSettingsService(db); + await settings.getExperimental(); + const census = createStatementCensus(db); + try { + const cached = await census.measure(() => settings.getExperimental()); + expect(cached.statements).toBe(0); + receiveDatabaseWorkNotification(db, JSON.stringify({ version: 1, origin: "another-process", topic: INSTANCE_SETTINGS_CHANGED_TOPIC })); + const refreshed = await census.measure(() => settings.getExperimental()); + expect(refreshed.statements).toBe(1); + } finally { + census.uninstall(); + } + }); + + it("announces a settings change before the other wakes of the same write", async () => { + const payloads: string[] = []; + const listener = await otherProcess.$client.listen(DATABASE_WORK_CHANNEL, payload => { payloads.push(payload); }); + enableDatabaseWorkNotifications(db); + try { + await instanceSettingsService(db).updateExperimental({ enableStatusCards: true }); + await waitUntil(async () => payloads.length > 1, 5_000); + const topics = payloads.map(payload => (JSON.parse(payload) as { topic: string }).topic); + expect(topics[0]).toBe(INSTANCE_SETTINGS_CHANGED_TOPIC); + expect(topics).toContain("status-card-evaluation"); + payloads.length = 0; + await instanceSettingsService(db).updateGeneral({ censorUsernameInLogs: true }); + await waitUntil(async () => payloads.length > 0, 5_000); + expect(payloads.map(payload => (JSON.parse(payload) as { topic: string }).topic)).toEqual([INSTANCE_SETTINGS_CHANGED_TOPIC]); + } finally { + await listener.unlisten(); + } + }); +}); diff --git a/server/src/__tests__/project-environments.test.ts b/server/src/__tests__/project-environments.test.ts index db951894ed6..9521ef45baa 100644 --- a/server/src/__tests__/project-environments.test.ts +++ b/server/src/__tests__/project-environments.test.ts @@ -15,6 +15,7 @@ import { projectRoutes } from "../routes/projects.js"; import { errorHandler } from "../middleware/index.js"; import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js"; const support = await getEmbeddedPostgresTestSupport(); describe.skipIf(!support.supported)("project environment compatibility", () => { @@ -43,6 +44,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { { name: "Build host", driver: "ssh", config: { host: "build.example.com" } }, ]).returning(); await db.insert(instanceSettings).values({ defaultEnvironmentId: sandbox.id }); + invalidateInstanceSettingsCache(); return { ...f, plugin, computer, local, sandbox, ssh }; } @@ -85,6 +87,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, f.input.agentId)); expect((await projectEnvironmentOptions(db, f.companyId, { userId: "person" })).defaultEnvironmentId).toBe(f.sandbox.id); await db.update(instanceSettings).set({ defaultEnvironmentId: null }); + invalidateInstanceSettingsCache(); expect((await projectEnvironmentOptions(db, f.companyId)).defaultEnvironmentId).toBe(f.local.id); }); @@ -101,6 +104,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { expect(await withDefaultProjectStorage(db, f.companyId, explicit)).toEqual(explicit); await expect(withDefaultProjectStorage(db, f.companyId, explicit, { environmentId: f.computer.id })).rejects.toMatchObject({ status: 409 }); await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id }); + invalidateInstanceSettingsCache(); expect((await svc.getById(sandboxProject.id))?.workspaceProvider?.pluginId).toBeNull(); }); @@ -175,6 +179,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { it("keeps a cold worker's storage identity, and uses the only storage left after its default is archived", async () => { const f = await fixture(); await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id }); + invalidateInstanceSettingsCache(); await db.update(plugins).set({ status: "error" }).where(eq(plugins.id, f.pluginId)); expect(await withDefaultProjectStorage(db, f.companyId, null)).toMatchObject({ storageProviderPluginId: f.pluginId }); await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.computer.id)); @@ -186,6 +191,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { const f = await fixture(); const [fake] = await db.insert(environments).values({ name: "Fake", driver: "sandbox", config: { provider: "fake" } }).returning(); await db.update(instanceSettings).set({ defaultEnvironmentId: fake.id }); + invalidateInstanceSettingsCache(); const options = await projectEnvironmentOptions(db, f.companyId); expect(options.groups).toHaveLength(2); expect(options.defaultEnvironmentId).toBeNull(); @@ -197,6 +203,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { const f = await fixture(); await db.update(environments).set({ status: "archived" }).where(inArray(environments.id, [f.sandbox.id, f.ssh.id])); await db.update(instanceSettings).set({ experimental: { enableManagedSandboxOnly: true } }); + invalidateInstanceSettingsCache(); const options = await projectEnvironmentOptions(db, f.companyId); expect(options).toEqual({ groups: [{ storageProviderPluginId: f.pluginId, environments: [{ id: f.computer.id, name: f.computer.name }] }], @@ -214,8 +221,10 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "operator" }); await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.computer.id)); - if (source === "instance") await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id }); - else { + if (source === "instance") { + await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id }); + invalidateInstanceSettingsCache(); + } else { await db.update(agents).set({ defaultEnvironmentId: f.computer.id }).where(eq(agents.id, f.input.agentId)); await db.insert(userCompanyPreferences).values({ companyId: f.companyId, userId, primaryAgentId: f.input.agentId }); } @@ -231,10 +240,12 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { const f = await fixture(); await db.update(environments).set({ metadata: { managedByPaperclip: true, managedKubernetesSandbox: true } }).where(eq(environments.id, f.sandbox.id)); await db.update(instanceSettings).set({ defaultEnvironmentId: f.local.id, experimental: { enableManagedSandboxOnly: true } }); + invalidateInstanceSettingsCache(); const managed = await projectEnvironmentOptions(db, f.companyId); expect(managed.defaultEnvironmentId).toBe(f.sandbox.id); expect(managed.groups.flatMap(group => group.environments).map(value => value.id)).not.toContain(f.local.id); await db.update(instanceSettings).set({ general: { executionMode: "kubernetes" } }); + invalidateInstanceSettingsCache(); const forced = await projectEnvironmentOptions(db, f.companyId); expect(forced.groups).toEqual([{ storageProviderPluginId: null, environments: [{ id: f.sandbox.id, name: f.sandbox.name }] }]); await expect(withDefaultProjectStorage(db, f.companyId, null, { environmentId: f.computer.id })).rejects.toMatchObject({ status: 409 }); diff --git a/server/src/__tests__/setup-supertest.ts b/server/src/__tests__/setup-supertest.ts index be189a6abe0..adab4b32f77 100644 --- a/server/src/__tests__/setup-supertest.ts +++ b/server/src/__tests__/setup-supertest.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import { createIsolatedTestHome } from "./helpers/isolated-test-home.js"; +import { beforeEach } from "vitest"; import { createRequire } from "node:module"; import type { AddressInfo, Server as NetServer } from "node:net"; import os from "node:os"; @@ -76,3 +77,8 @@ if (!SupertestTest.prototype.__paperclipLoopbackPatched) { SupertestTest.prototype.__paperclipLoopbackPatched = true; } + +beforeEach(async () => { + const { invalidateInstanceSettingsCache } = await import("../services/instance-settings-cache.js"); + invalidateInstanceSettingsCache(); +}); diff --git a/server/src/__tests__/smoke-lab.test.ts b/server/src/__tests__/smoke-lab.test.ts index 165ca21fc51..2fe45a6f942 100644 --- a/server/src/__tests__/smoke-lab.test.ts +++ b/server/src/__tests__/smoke-lab.test.ts @@ -28,6 +28,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { smokeLabRoutes } from "../routes/smoke-lab.js"; import { SMOKE_LAB_OAUTH_SCOPE } from "../services/smoke-lab.js"; import { errorHandler } from "../middleware/index.js"; +import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js"; const externalTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_SMOKE_LAB_TEST_DATABASE_URL"); const embeddedPostgresSupport = externalTestDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); @@ -50,6 +51,7 @@ async function enableSmokeLab(db: TestDb) { target: [instanceSettings.singletonKey], set: { experimental: { enableSmokeLab: true }, updatedAt: new Date() }, }); + invalidateInstanceSettingsCache(); } async function createAgent(db: TestDb, companyId: string) { diff --git a/server/src/middleware/cloud-tenant-actor.test.ts b/server/src/middleware/cloud-tenant-actor.test.ts index 61929549d0d..f13be1579d1 100644 --- a/server/src/middleware/cloud-tenant-actor.test.ts +++ b/server/src/middleware/cloud-tenant-actor.test.ts @@ -279,7 +279,7 @@ describe("resolveCloudTenantActor (shared-pool hardening)", () => { expect(insertedTables.filter((table) => table === companyMemberships)).toHaveLength(3); }); - it("coalesces concurrent identical syncs while keeping authority reads and stale-admin purges per request", async () => { + it("coalesces concurrent identical syncs and settings reads while keeping membership reads and stale-admin purges per request", async () => { let release!: () => void; let entered!: () => void; const blocked = new Promise(resolve => { release = resolve; }); @@ -294,7 +294,7 @@ describe("resolveCloudTenantActor (shared-pool hardening)", () => { const actors = await Promise.all(requests); expect(insertedTables.filter(table => table === companyMemberships)).toHaveLength(1); expect(deletedTables.filter(table => table === instanceUserRoles)).toHaveLength(20); - expect(selectWheres.filter(entry => entry.table === instanceSettings)).toHaveLength(20); + expect(selectWheres.filter(entry => entry.table === instanceSettings)).toHaveLength(1); expect(selectWheres.filter(entry => entry.table === companyMemberships && !entry.locked)).toHaveLength(20); expect(selectWheres.filter(entry => entry.table === companyMemberships && entry.locked)).toHaveLength(1); expect(actors.every(actor => actor?.memberships?.[0]?.membershipRole === "owner")).toBe(true); diff --git a/server/src/middleware/cloud-tenant-sync-postgres.test.ts b/server/src/middleware/cloud-tenant-sync-postgres.test.ts index 46fbf351f41..ce7ce28f464 100644 --- a/server/src/middleware/cloud-tenant-sync-postgres.test.ts +++ b/server/src/middleware/cloud-tenant-sync-postgres.test.ts @@ -11,6 +11,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { cloudActorHeaderSourceFromHeaders, resolveCloudTenantActor } from "./auth.js"; import { errorHandler } from "./error-handler.js"; import { userProfileRoutes } from "../routes/user-profiles.js"; +import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js"; const support = await getEmbeddedPostgresTestSupport(); const aliasFields = ["name", "email-local", "email", "principal"] as const; @@ -172,11 +173,13 @@ const aliasFields = ["name", "email-local", "email", "principal"] as const; await db.update(companyMemberships).set({ status: "inactive" }).where(and(eq(companyMemberships.companyId, importedCompanyId), eq(companyMemberships.principalId, userId))); await db.insert(instanceSettings).values({ singletonKey: "default", experimental: { enableOwnerInstanceAdmin: true } }) .onConflictDoUpdate({ target: instanceSettings.singletonKey, set: { experimental: { enableOwnerInstanceAdmin: true } } }); + invalidateInstanceSettingsCache(); const elevated = await resolve(db, value); expect(elevated?.isInstanceAdmin).toBe(true); expect(elevated?.companyIds).toEqual(actor!.companyIds); expect(await db.select().from(instanceUserRoles).where(eq(instanceUserRoles.userId, userId))).toEqual([]); await db.update(instanceSettings).set({ experimental: { enableOwnerInstanceAdmin: false } }); + invalidateInstanceSettingsCache(); expect((await resolve(db, value))?.isInstanceAdmin).toBe(false); }); diff --git a/server/src/services/feedback.ts b/server/src/services/feedback.ts index 5a202a84860..aa4e13af3c0 100644 --- a/server/src/services/feedback.ts +++ b/server/src/services/feedback.ts @@ -51,6 +51,7 @@ import { getRunLogStore, isRunLogStoreType } from "./run-log-store.js"; import { isObjectJournalBusyError } from "./object-byte-journal.js"; import { recoverSettledNativeRunLog } from "./native-runtime/native-run-log-recovery.js"; import { getOperatorSettingDefaults } from "./setting-defaults.js"; +import { announceInstanceSettingsChange } from "./instance-settings-cache.js"; const FEEDBACK_SCHEMA_VERSION = "paperclip-feedback-envelope-v2"; const FEEDBACK_BUNDLE_VERSION = "paperclip-feedback-bundle-v2"; @@ -2027,6 +2028,7 @@ export function feedbackService(db: Db, options: FeedbackServiceOptions = {}) { getOperatorSettingDefaults(), ); if (currentInstanceSettings && currentGeneral.feedbackDataSharingPreference === "prompt") { + await announceInstanceSettingsChange(tx); const nextSharingPreference = sharedWithLabs ? "allowed" : "not_allowed"; const currentGeneralRaw = asRecord(currentInstanceSettings.general) ?? {}; await tx diff --git a/server/src/services/instance-settings-cache.ts b/server/src/services/instance-settings-cache.ts new file mode 100644 index 00000000000..08ad61e73e3 --- /dev/null +++ b/server/src/services/instance-settings-cache.ts @@ -0,0 +1,63 @@ +import { is } from "drizzle-orm"; +import { PgTransaction } from "drizzle-orm/pg-core"; +import { publishDatabaseWorkHint, publishDatabaseWorkSettled, subscribeDatabaseWork } from "@paperclipai/db/work-signals"; + +export const INSTANCE_SETTINGS_CACHE_TTL_MS = 2_000; +export const INSTANCE_SETTINGS_CHANGED_TOPIC = "instance-settings-changed"; + +type Entry = { generation: number; at: number; value?: unknown; pending?: Promise }; + +let generation = 0; +const entries = new WeakMap(); +const subscribed = new WeakSet(); + +export function invalidateInstanceSettingsCache() { + generation += 1; +} + +export async function announceInstanceSettingsChange(connection: object) { + invalidateInstanceSettingsCache(); + publishDatabaseWorkSettled(connection, INSTANCE_SETTINGS_CHANGED_TOPIC); + if (!is(connection, PgTransaction)) { + await publishDatabaseWorkHint(connection, INSTANCE_SETTINGS_CHANGED_TOPIC).catch(() => undefined); + } +} + +function subscribeToChanges(db: object) { + if (subscribed.has(db)) return; + subscribed.add(db); + try { + subscribeDatabaseWork(db, INSTANCE_SETTINGS_CHANGED_TOPIC, invalidateInstanceSettingsCache); + } catch { + return; + } +} + +export async function readThroughInstanceSettings(db: object, load: () => Promise): Promise { + if (is(db, PgTransaction)) return load(); + subscribeToChanges(db); + const current = entries.get(db); + if (current && current.generation === generation) { + if ("value" in current && Date.now() - current.at < INSTANCE_SETTINGS_CACHE_TTL_MS) { + return structuredClone(current.value as T); + } + if (current.pending) return structuredClone(await (current.pending as Promise)); + } + const startedAt = Date.now(); + const startedGeneration = generation; + const entry: Entry = { generation: startedGeneration, at: startedAt }; + const pending = load(); + entry.pending = pending; + entries.set(db, entry); + try { + const value = await pending; + if (entries.get(db) === entry) { + if (generation === startedGeneration) entries.set(db, { generation: startedGeneration, at: startedAt, value }); + else entries.delete(db); + } + return structuredClone(value); + } catch (error) { + if (entries.get(db) === entry) entries.delete(db); + throw error; + } +} diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts index d440ce2ae25..ece871a0cf1 100644 --- a/server/src/services/instance-settings.ts +++ b/server/src/services/instance-settings.ts @@ -59,6 +59,7 @@ import { getManagedInstanceConfig, type ManagedInstanceConfig } from "./managed- import { getOperatorSettingDefaults } from "./setting-defaults.js"; import { isCloudStagingExperimentalSetting, isCloudStagingInstance } from "./cloud-instance.js"; import { forbidden } from "../errors.js"; +import { announceInstanceSettingsChange, readThroughInstanceSettings } from "./instance-settings-cache.js"; const DEFAULT_SINGLETON_KEY = "default"; const instanceGeneralSettingsStorageSchema = instanceGeneralSettingsSchema.strip(); @@ -552,8 +553,12 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService throw new Error("Failed to initialize instance settings row"); } + function getCachedRow(runner: InstanceSettingsWriteDb = db) { + return readThroughInstanceSettings(runner, () => getOrCreateRow(runner)); + } + return { - get: async (): Promise => toInstanceSettings(await getOrCreateRow()), + get: async (): Promise => toInstanceSettings(await getCachedRow()), update: async ( patch: PatchInstanceSettings, @@ -576,13 +581,14 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService }) .where(eq(instanceSettings.id, current.id)) .returning(); + await announceInstanceSettingsChange(runner); return toInstanceSettings(updated ?? current); }, getGeneral: async ( readOptions?: { db?: InstanceSettingsWriteDb }, ): Promise => { - const row = await getOrCreateRow(readOptions?.db); + const row = await getCachedRow(readOptions?.db); return toGeneralView(row.general); }, @@ -593,7 +599,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService }, getExperimental: async (): Promise => { - const row = await getOrCreateRow(); + const row = await getCachedRow(); return toExperimentalView(row.experimental); }, @@ -617,6 +623,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService }) .where(eq(instanceSettings.id, current.id)) .returning(); + await announceInstanceSettingsChange(db); return toInstanceSettings(updated ?? current); }, @@ -651,6 +658,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService && toExperimentalView(nextExperimental).enableAgentChat; const now = new Date(); const [updated] = await db.transaction(async tx => { + await announceInstanceSettingsChange(tx); if (patch.enableStatusCards !== undefined) await notifyStatusCardEvaluation(tx); if (chatBecameEnabled) await notifyDeferredExecutionEligibility(tx); if(toExperimentalView(current.experimental).enablePublicMcp!==toExperimentalView(nextExperimental).enablePublicMcp)await prepareMcpClientMirrorPolicy(tx as unknown as Db,toExperimentalView(nextExperimental).enablePublicMcp); diff --git a/server/src/services/native-runtime/native-run-log-watermark.test.ts b/server/src/services/native-runtime/native-run-log-watermark.test.ts index e0896fd7e79..77c24f1d8af 100644 --- a/server/src/services/native-runtime/native-run-log-watermark.test.ts +++ b/server/src/services/native-runtime/native-run-log-watermark.test.ts @@ -18,6 +18,7 @@ import { createObjectRunLogStore } from "../object-run-log-store.js"; import { nativeSha256 } from "./canonical.js"; import { createNativeRunLogCoverageVerifier, formatNativeRunLogEvent } from "./native-run-log-export.js"; import { readRecoverableRunLog, recoverSettledNativeRunLog } from "./native-run-log-recovery.js"; +import { invalidateInstanceSettingsCache } from "../instance-settings-cache.js"; // Use an explicit guarded test database or a new owned embedded fixture. const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_NATIVE_LOG_WATERMARK_DATABASE_URL"); @@ -348,7 +349,7 @@ describe.skipIf(!support.supported)("native run log source watermarks", () => { const f = await fixture(); const setMasking = async (value: boolean) => db.execute(sql`insert into instance_settings(general) values(${JSON.stringify({ censorUsernameInLogs: value })}::jsonb) - on conflict(singleton_key) do update set general=excluded.general`); + on conflict(singleton_key) do update set general=excluded.general`).finally(invalidateInstanceSettingsCache); const redaction = async () => ({ enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs, userNames: ["fixture-operator"], homeDirs: ["/home/fixture-operator"] }); await setMasking(enabled); From 531db3c10b09167a124e4bb00e66fe5ca3d3847f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:51:55 -0600 Subject: [PATCH 05/20] perf(db): keep dedicated connections for the next burst (#21769) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process runs every agent on one Node main thread, and each new database connection costs a TLS handshake, about 0.36 ms of SCRAM key derivation on that thread, and a type-fetch query > - `withDedicatedDbConnection` gives lock holders a private session; since #21693 it keeps at most 4 released sessions and closes the rest > - When the same burst of more than 4 dedicated holders comes back, every holder above 4 opens a new connection again > - A harness on embedded PostgreSQL measured 504 new connections per 1,000 uses for bursts of 8 and 760 for bursts of 16 > - This pull request keeps released dedicated clients for reuse while idle plus in-use clients stay within `DATABASE_DEDICATED_CONNECTION_MAX`; the driver idle timeout still closes their sessions when they are not used > - The benefit is 8 and 16 new connections per 1,000 uses for the same bursts, with no change to any pool maximum or to `databaseConnectionBudget()` ## Linked Issues or Issue Description **What is the problem?** A staging measurement showed `SET application_name='paperclip-runner-checkpoint'` at 3.17/s and `SET application_name='paperclip'` at 3.86/s with 7 live runs. This looked like connection churn. The investigation found two separate facts: 1. The `SET` statements are not new client connections. postgres.js sends `application_name` in the startup packet, never as a `SET` statement (`StartupMessage` in postgres.js `src/connection.js`). PgBouncer in transaction mode sends `SET application_name` itself when it gives a client transaction a server connection that a client with another `application_name` used last. With one shared server pool, every checkpoint transaction that lands after a main-pool transaction costs one `SET`, and the reverse. The rate follows checkpoint transactions, not connects. The checkpoint pool opens at most 3 connections per 1,000 saves (measured below). 2. Dedicated connections did churn by construction for recurring bursts of more than 4 holders (measured below). This pull request fixes that. **Steps to reproduce** Run `packages/db/src/connection-reuse-census.test.ts`. It counts `pg_stat_database.sessions` around 1,000 operations. **Expected behavior** A recurring burst reuses the sessions that the previous burst opened. ## What Changed - `withDedicatedDbConnection` keeps a released client idle when fewer than `DEDICATED_CONNECTION_IDLE_MAX` (4) are idle, as before, or when idle plus in-use clients stay within the dedicated limit (`DATABASE_DEDICATED_CONNECTION_MAX`, default 24). A client whose action failed, an ended client and clients after shutdown are still closed. - Each retained client keeps the main pool's `idle_timeout` (default 60 s), so its session closes after that idle time, as the main pool's do. The next use reconnects. - The worst case stays at `2 x DATABASE_DEDICATED_CONNECTION_MAX + 4`: a new client opens only when no client is idle, and a client is kept above 4 only while idle plus in-use is within the limit. `databaseConnectionBudget()` and every pool maximum are unchanged. - New `connection-reuse-census.test.ts` measures connections opened per 1,000 checkpoint saves and per 1,000 dedicated uses. - `dedicated-connection-pool.test.ts`: the burst test now checks that the next burst reuses all sessions and that they close after the idle timeout (1 s in the test). Before, it checked that at most 4 stayed open. - `doc/DATABASE.md` describes the new retention rule. ## Verification Connections opened per 1,000 operations, embedded PostgreSQL, `pg_stat_database.sessions` (load average about 10.5 on a shared machine): | Operation | Before | After | | --- | --- | --- | | Checkpoint saves, concurrency 1 / 7 / 24 | 1 / 3 / 3 | 1 / 3 / 3 | | Dedicated uses, steady concurrency 1 / 4 / 8 / 16 | 1 / 4 / 8 / 16 | 1 / 4 / 8 / 16 | | Dedicated uses, recurring bursts of 8 | 504 | 8 | | Dedicated uses, recurring bursts of 16 | 760 | 16 | - `pnpm --filter @paperclipai/db exec vitest run src/connection-reuse-census.test.ts src/dedicated-connection-pool.test.ts src/dedicated-connection-admission.test.ts src/client-options.test.ts`: 38 passed. The burst cases fail on `master` (504 and 760 against a bound of 8 and 16). ## Risks - After a burst, up to `DATABASE_DEDICATED_CONNECTION_MAX` dedicated sessions stay open for up to `DATABASE_IDLE_TIMEOUT_SECONDS` (60 s) instead of closing at once above 4. This stays inside the connection budget. With `DATABASE_IDLE_TIMEOUT_SECONDS=0` they stay open until shutdown, like the main pool. - Retained sessions keep the existing rule: actions keep session state transaction-scoped. - The PgBouncer `SET application_name` statements stay. Removing them needs one shared `application_name` for all pools, which removes the per-pool names that operators and tests use. That is a separate decision. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- doc/DATABASE.md | 9 ++- packages/db/src/client.ts | 3 +- .../db/src/connection-reuse-census.test.ts | 69 +++++++++++++++++++ .../db/src/dedicated-connection-pool.test.ts | 19 +++-- 4 files changed, 89 insertions(+), 11 deletions(-) create mode 100644 packages/db/src/connection-reuse-census.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 15ecde9114a..7a2458af677 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -139,9 +139,12 @@ DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; def `withDedicatedDbConnection` gives an action exclusive use of one session outside the main pool (application name `paperclip-workspace-finalization-lock`). Each -`createDb` owner keeps at most `DEDICATED_CONNECTION_IDLE_MAX` (4) of these -single-connection clients idle for reuse; they follow the same idle timeout and -max lifetime as the main pool. At most `DATABASE_DEDICATED_CONNECTION_MAX` +`createDb` owner keeps released single-connection clients idle for reuse: always +up to `DEDICATED_CONNECTION_IDLE_MAX` (4), and more while idle plus in-use +clients stay within `DATABASE_DEDICATED_CONNECTION_MAX`, so a recurring burst +reuses the sessions the previous burst opened instead of reconnecting. They +follow the same idle timeout and max lifetime as the main pool, so a retained +client closes its session after `DATABASE_IDLE_TIMEOUT_SECONDS` without use. At most `DATABASE_DEDICATED_CONNECTION_MAX` (default 24) dedicated clients are in use at once per owner. A caller that finds the limit reached waits in a first-in, first-out queue. A caller that already holds a dedicated client, or runs inside an open transaction of the diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 61d2e52b9d4..c4ea948081a 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -446,7 +446,8 @@ export async function withDedicatedDbConnection(db: Db, action: (dedicated: D } finally { hold.active = false; try { - if (dedicated && completed && !set.closed && !set.ended.has(dedicated) && set.idle.length < DEDICATED_CONNECTION_IDLE_MAX) { + if (dedicated && completed && !set.closed && !set.ended.has(dedicated) + && (set.idle.length < DEDICATED_CONNECTION_IDLE_MAX || set.idle.length + set.inUse <= set.limit)) { set.idle.push(dedicated); } else if (dedicated && !set.ended.has(dedicated)) { await dedicated.$client.end({ timeout: 1 }); diff --git a/packages/db/src/connection-reuse-census.test.ts b/packages/db/src/connection-reuse-census.test.ts new file mode 100644 index 00000000000..094eade4998 --- /dev/null +++ b/packages/db/src/connection-reuse-census.test.ts @@ -0,0 +1,69 @@ +import { sql } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { checkpointDb, closeCheckpointDb, closeDedicatedDbConnections, createDb, withDedicatedDbConnection, type Db } from "./client.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +async function sessionsOpened(observer: Db) { + const [row] = await observer.execute<{ sessions: string }>(sql`select sessions::text as sessions from pg_stat_database where datname = current_database()`); + return Number(row!.sessions); +} + +async function runConcurrently(total: number, concurrency: number, work: () => Promise) { + let next = 0; + await Promise.all(Array.from({ length: concurrency }, async () => { + while (next < total) { next++; await work(); } + })); +} + +describe.skipIf(!support.supported)("connections opened per 1,000 operations", () => { + let temporary: Awaited>; + let observer: Db; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("connection-reuse-"); + observer = createDb(temporary.connectionString, { maxConnections: 1, applicationName: "connection-reuse-observer" }); + await sessionsOpened(observer); + }, 90_000); + afterAll(async () => { + await observer?.$client.end({ timeout: 1 }); + await temporary?.cleanup(); + }); + + async function measure(open: (db: Db) => Promise) { + const db = createDb(temporary.connectionString, { maxConnections: 10 }); + await db.execute(sql`select 1`); + const before = await sessionsOpened(observer); + try { + await open(db); + return await sessionsOpened(observer) - before; + } finally { + await closeCheckpointDb(db, 1); + await closeDedicatedDbConnections(db, 1); + await db.$client.end({ timeout: 1 }); + } + } + + it.each([1, 7, 24])("checkpoint saves at concurrency %i reuse the checkpoint pool", async concurrency => { + const opened = await measure(db => runConcurrently(1_000, concurrency, () => + checkpointDb(db).transaction(async tx => { await tx.execute(sql`select 1`); }))); + expect(opened).toBeLessThanOrEqual(3); + }); + + it.each([1, 4, 8, 16])("dedicated connection uses at concurrency %i", async concurrency => { + const opened = await measure(db => runConcurrently(1_000, concurrency, () => + withDedicatedDbConnection(db, connection => connection.transaction(async tx => { await tx.execute(sql`select 1`); })))); + expect(opened).toBeLessThanOrEqual(concurrency); + }); + + it.each([8, 16])("bursts of %i dedicated connection uses reuse the connections the last burst opened", async width => { + const opened = await measure(async db => { + for (let burst = 0; burst < 1_000 / width; burst++) { + await Promise.all(Array.from({ length: width }, () => + withDedicatedDbConnection(db, connection => connection.transaction(async tx => { await tx.execute(sql`select 1`); })))); + } + }); + expect(opened).toBeLessThanOrEqual(width); + }); +}); diff --git a/packages/db/src/dedicated-connection-pool.test.ts b/packages/db/src/dedicated-connection-pool.test.ts index 74933f3ec31..835883fbeb8 100644 --- a/packages/db/src/dedicated-connection-pool.test.ts +++ b/packages/db/src/dedicated-connection-pool.test.ts @@ -73,8 +73,9 @@ describe.skipIf(!support.supported)("withDedicatedDbConnection connection reuse" expect(seen.size).toBeLessThanOrEqual(DEDICATED_CONNECTION_IDLE_MAX); }); - it("gives concurrent callers exclusive sessions and keeps at most the cap open afterwards", async () => { - const db = owner(); + it("gives concurrent callers exclusive sessions, reuses them for the next burst and closes them once idle", async () => { + const db = createDb(temporary.connectionString, { maxConnections: 2, idleTimeoutSeconds: 1 }); + owners.push(db); const concurrency = DEDICATED_CONNECTION_IDLE_MAX + 3; let release!: () => void; const gate = new Promise(resolve => { release = resolve; }); @@ -94,12 +95,16 @@ describe.skipIf(!support.supported)("withDedicatedDbConnection connection reuse" release(); const sessions = await Promise.all(held); expect(new Set(sessions.map(key)).size).toBe(concurrency); - expect((await eventually(openDedicatedSessions, open => open.length <= DEDICATED_CONNECTION_IDLE_MAX)).length) - .toBeLessThanOrEqual(DEDICATED_CONNECTION_IDLE_MAX); const retained = new Set(sessions.map(key)); - for (let i = 0; i < 20; i++) { - expect(retained.has(key(await withDedicatedDbConnection(db, session)))).toBe(true); - } + const nextBurst = await Promise.all(Array.from({ length: concurrency }, () => + withDedicatedDbConnection(db, dedicated => dedicated.transaction(async tx => { + const mine = await session(tx); + await tx.execute(sql`select pg_sleep(0.05)`); + return mine; + })))); + expect(nextBurst.every(value => retained.has(key(value)))).toBe(true); + expect(await eventually(openDedicatedSessions, open => open.length === 0)).toEqual([]); + expect(retained.has(key(await withDedicatedDbConnection(db, session)))).toBe(false); }); it("discards a connection whose action failed mid-transaction", async () => { From 171e70c11de96387c7161d660e7f6890148d3e3e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:06:05 -0600 Subject: [PATCH 06/20] refactor: drop span and run-log event catalogs from the observability docs (#21779) 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 > - `doc/observability.md` and `doc/run-log-events.md` described every OpenTelemetry span and every run-log event > - `rules/data-paths.mdc` told authors to update `doc/run-log-events.md` for each event, so both files only grew: 2,313 and 1,263 lines > - Each span and event is already defined next to the code that writes it, and its name is a literal string that a search finds in one step > - This pull request removes the per-span and per-event catalogs and keeps only what code does not say > - The benefit is two short docs that do not drift from the code, and no rule that makes them grow again ## Linked Issues or Issue Description Refs #21670, #21700, and #21743 (the same cleanup for other docs). **Issue type** Outdated or confusing documentation. **Where is the issue?** `doc/observability.md`, `doc/run-log-events.md`, and `rules/data-paths.mdc` **What's wrong?** The two docs repeated span names, span attributes, and event payloads that the code defines. Operator setup started at line 138 of `doc/observability.md`. The rule required a doc edit for every new run-log event. **Suggested fix** Keep operator setup and the Sentry privacy contract. Point to the code for span and event definitions. Remove the rule line that requires a doc entry per event. ## What Changed - `doc/observability.md` is now 619 lines. It keeps: how to enable tracing, `service.version` resolution, scope, how to enable Sentry, DSN delivery, environment attribution, privacy settings, server request data, the core of "Run failure context", browser data, fail-open behavior, the default capture set, and operator responsibilities. Kept text is unchanged except the intro and two sentences noted below. - Deleted from `doc/observability.md`: budget, Slack receipt, task detail, and browser tracing notes; controller preparation phases; native Runner spans; sandbox startup spans; sandbox duplex transport; shared skill preparation; invocation attribution; and about 500 lines of per-failure detail in "Run failure context". - Replaced that per-failure detail with one paragraph. It names the failures that `unexpected` mode keeps out of Sentry, and says the remaining diagnostic contexts are defined in `server/src/sentry.ts`. "Default capture set" now says the same. - `doc/run-log-events.md` is now 23 lines. It says what the run log is, where events are defined and appended, and keeps the payload storage note. - `rules/data-paths.mdc`: the run-log line now says to define an event where it is written, not in a doc. The span-allowlist line now says the allowlist is in the code that opens the span. The review levels and globs do not change. - Repointed links in two feature maps, two agent-access map files, `tests/runner-e2e/SUITES.md`, `doc/runner-api-tools.md`, and the Telemetry README. Updated the `honeycomb-tracing` skill and one code comment in `packages/adapter-utils/src/http2-bridge-server.ts`. ## Verification - A script built the new `doc/observability.md` from line ranges of the old file and asserts the first line of each range. - A link check on all changed Markdown files found 0 missing files and 0 missing anchors. The remaining inbound anchors (`#enabling-tracing`, `#sentry-error-monitoring`) still exist. - No test reads either doc. - `node scripts/check-maps.mjs` passes. - `node --test .github/scripts/tests/*.test.mjs`: 808 pass, 0 fail. - `pnpm verify` was not run. This worktree has no installed dependencies. The only code change is a comment. ## Risks - The privacy contract no longer lists each run-failure diagnostic context field. `server/src/sentry.ts` is now the list. A reviewer of a Sentry change must read that file. - No browsable list of span names or run-log event names remains. A search for the quoted name finds the producer. - `.greptile/files.json` still scopes `rules/data-paths.mdc` to both docs. Both files still exist, so it does not change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code desktop, with tool use. Earlier analysis in this session used Claude Fable 5.2. ## 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 - [ ] 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 --- .agents/skills/honeycomb-tracing/SKILL.md | 11 +- .../references/trace-design.md | 6 +- CONTRIBUTING.md | 2 +- doc/observability.md | 1752 +---------------- doc/run-log-events.md | 1273 +----------- doc/runner-api-tools.md | 2 +- maps/agent-access-map/README.md | 2 +- maps/agent-access-map/runs-adapters.md | 3 +- maps/feature-map/chat-channels.md | 3 +- maps/feature-map/runs-adapters.md | 3 +- .../adapter-utils/src/http2-bridge-server.ts | 5 +- packages/shared/src/telemetry/README.md | 5 +- rules/data-paths.mdc | 6 +- tests/runner-e2e/SUITES.md | 2 +- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 15 files changed, 80 insertions(+), 2997 deletions(-) diff --git a/.agents/skills/honeycomb-tracing/SKILL.md b/.agents/skills/honeycomb-tracing/SKILL.md index 587bfa5dbe4..35494334f46 100644 --- a/.agents/skills/honeycomb-tracing/SKILL.md +++ b/.agents/skills/honeycomb-tracing/SKILL.md @@ -22,11 +22,12 @@ replaying tasks, changing credentials, or deploying instrumentation. | What is a page's real-user load time or SLO on a hosted instance? | Browser `page.load` spans in [browser performance tracing](../../../doc/browser-performance-tracing.md) | | Which CI jobs or test files delay the whole suite? | [CI profiling](references/ci.md) | | How should a trace be organized so a person can understand it? | Human-readable waterfall guidance below and [trace design](references/trace-design.md) | -| Where should a new span go? | Instrumentation guidance below and [Observability contract](../../../doc/observability.md) | +| Where should a new span go? | Instrumentation guidance below and the code that opens the nearest existing span | -Repository-relative paths and commands assume the checkout root. The maintained -contracts are `doc/observability.md` and `doc/ci-profiling.md`; recheck them and -the owning code when a deployed version differs. +Repository-relative paths and commands assume the checkout root. Span names and +attributes are defined in the code that opens each span; `doc/observability.md` +covers only operator setup and Sentry. `doc/ci-profiling.md` covers CI traces. +Recheck the owning code when a deployed version differs. Keep the repository's three paths distinct: @@ -178,7 +179,7 @@ explain one slow scan. Observability must not retry the operation, replace its return/error, change authorization/locks, or break execution when the tracer fails. Preserve root sampling and the explicit endpoint gate even if another library registers an -OTel provider. Update `doc/observability.md` when the trace contract changes. +OTel provider. Update `doc/observability.md` only when operator setup changes. Run focused tests for endpoint-off behavior, parentage/concurrent-run isolation, failure handling, and the changed seam. Use real exported evidence to claim that new spans appear in Honeycomb; a unit-test tracer alone does not prove ingestion. diff --git a/.agents/skills/honeycomb-tracing/references/trace-design.md b/.agents/skills/honeycomb-tracing/references/trace-design.md index cfcde0bb07b..ecd0028d79b 100644 --- a/.agents/skills/honeycomb-tracing/references/trace-design.md +++ b/.agents/skills/honeycomb-tracing/references/trace-design.md @@ -2,9 +2,9 @@ Read this when adding, reorganizing, or reviewing a waterfall's hierarchy. The goal is to understand the work at a glance, then expand the slow phase to -find its cause. Follow the current -[Observability contract](../../../../doc/observability.md) for exact names, -roots, lifecycle boundaries, sampling, and allowed attributes. +find its cause. Follow the code that +opens the nearest existing span for exact names, roots, lifecycle boundaries, +sampling, and allowed attributes. ## Organize by the work being done diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e5c52b54c5d..62130263397 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -122,7 +122,7 @@ and coverage requirements. This repo has three separate data paths: Telemetry, Observability, and the run log. See [`rules/data-paths.mdc`](rules/data-paths.mdc) for the full definitions and the review level each path needs. -If your change adds, removes, or modifies emitted telemetry events, update the [Telemetry Data Contract](packages/shared/src/telemetry/README.md) in the same PR. Keep clients emitting raw dimension values and avoid documenting or relying on private delivery details. If your change adds, removes, or modifies an OpenTelemetry span or span attribute, keep the change inside the closed span-attribute allowlist in `packages/adapter-utils/src/acpx-engine/startup-timing.ts`. If your change adds or modifies a run-log event, update `doc/run-log-events.md` in the same PR. +If your change adds, removes, or modifies emitted telemetry events, update the [Telemetry Data Contract](packages/shared/src/telemetry/README.md) in the same PR. Keep clients emitting raw dimension values and avoid documenting or relying on private delivery details. If your change adds, removes, or modifies an OpenTelemetry span or span attribute, keep the change inside the closed span-attribute allowlist in `packages/adapter-utils/src/acpx-engine/startup-timing.ts`. Define a new or changed run-log event where it is written; do not list it in a doc. ### Paperclip Gates Must Pass diff --git a/doc/observability.md b/doc/observability.md index e2a8d6f8746..77a0b1d8e66 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -1,10 +1,16 @@ # Observability -This document is the Observability contract. It covers the OpenTelemetry -trace path, the opt-in Sentry error-monitoring path, and two local -instrumentation contracts; see the +This document covers how an operator turns on the two opt-in observability +paths, OpenTelemetry traces and Sentry error monitoring, and what Sentry events +may contain. See the [Telemetry Data Contract](../packages/shared/src/telemetry/README.md) for the -separate first-party event system. +separate first-party event system, and `rules/data-paths.mdc` for how the paths +differ. + +It does not list span names or attributes. Those are defined next to the code +that opens each span; search for the span name, or for `getTracer(` and +`startActiveSpan(` under `server/src` and `packages`. Add a new span in code +without adding it here. Paperclip ships with **opt-in** OpenTelemetry auto-instrumentation for the server process. When activated it produces **traces only** — no metrics and no @@ -42,99 +48,6 @@ the application healthy. For Honeycomb, configure the ingest key in the [Honeycomb authentication](https://docs.honeycomb.io/api/query-annotations/authorization). Keep credential values out of logs and diagnostic reports. -## Budget admission, accounting, and enforcement - -The operator-gated `paperclip.budgets` tracer records -`budget.admission.inspect`, `budget.admission.reconcile`, -`budget.admission.evaluate`, `budget.admission.reserve`, -`budget.accounting.transaction`, `budget.accounting.settlement`, `budget.accounting.lock_wait`, -`budget.exposure.evaluate`, `budget.enforcement.deliver`, -`budget.enforcement.scope`, `budget.cancellation.deliver`, and `budget.accounting.recover`. -Inspection and admission spans cover read-only eligibility. Paid reservations, -receipts and all five settlement owners avoid the company accounting mutex. -`budget.admission.reconcile` remains a historical span name; eligibility no longer -publishes budget transitions. `budget.accounting.lock_wait` still describes the -legacy low-frequency configuration/control wrapper, not paid settlement. -Transaction spans include commit time. Settlement spans cover the atomic ledger, -reservation and owner acknowledgement. Acquisition duration is not a pure -PostgreSQL lock-wait measurement: it can include network and Node scheduling. -Enforcement spans cover asynchronous evaluation/delivery; cancellation delivery -covers the external Stop attempt, separate from provider inference. - -The closed attribute list is `budget.policy_count` (applicable policy count), -`budget.enforcement.queue_delay_ms` (time since pending intent/retry), and -`budget.accounting.owner` (`run`, `decision`, `classifier`, `fast_response`, -`browser`). The owner tag identifies the shared settlement span's emitter. -These spans contain no prompts, usage receipt bodies, credentials or provider -error bodies. They remain gated by the operator OTLP endpoint and do not change -Paperclip's separate first-party Telemetry contract. - -## Slack receipt reactions - -Slack stages its eyes reaction in the same transaction as the authorized task, -comment, message link and wakeup intent. Transport starts after that commit, -independently of attachment preparation, thread subscription and scheduler -acceptance. Eyes acknowledge durable receipt; they do not certify agent startup. -The existing action worker retains retries, credential fencing and exact-source -cleanup when the final response is published. - -The Slack adapter also skips the SDK's two-second polling wait for optional link -unfurls before message dispatch. Text, formatted content, link URLs and file -download handles remain available. Paperclip does not consume that optional -preview metadata for task admission. - -With an operator OTLP endpoint, the `paperclip.chat` tracer records -`chat.slack.receipt` around each Slack reaction API attempt. Its closed attributes -are `paperclip.chat.receipt.operation` (`add` or `remove`), -`paperclip.chat.receipt.outcome` (`confirmed` or `failed`), -`paperclip.chat.receipt.queue_ms` (action creation to transport), and -`paperclip.chat.receipt.delivery_age_ms` (durable inbound receipt to provider -confirmation or failure). `already_reacted` confirms an idempotent add. -Delivery age excludes Slack-to-webhook transit and SDK parsing; the span duration -measures provider I/O. A failed attempt is not an acknowledgement latency sample. -No content, identifiers, credentials, URLs or exception text are added. -Without the endpoint this instrumentation does no tracer lookup. Tracer errors -cannot change reaction transport or settlement. - -## Task detail loading - -`GET /api/issues/:id` returns `Server-Timing` with `paperclip_issue` for the -whole handler and `issue_` for its reads. The total includes the final -execution-blocker read after recovery revalidation. Concurrent phases overlap; -do not sum them to obtain request duration. - -With the existing operator-configured OTLP endpoint, the same reads produce -`issue.read.` child spans through the `paperclip.issue-read` tracer. -There are no custom attributes, identifiers, content, or exception messages. -The closed phase names in `server/src/services/issue-read-timing.ts` are: -`lookup`, `authorization`, `project_goal`, `ancestors`, `mentions`, `documents`, -`relations`, `blockers`, `review`, `references`, `handoff`, `retry`, `recovery`, -`cases`, `inbox`, `channel`, `workspace`, `work_products`, `created_from`, -`execution_blocker`, `relation_recovery`, `revalidate_recovery`, and -`mentioned_projects`. -Without an OTLP endpoint, spans remain no-ops. This adds no first-party -Telemetry events or run-log events. - -The browser's `issue-detail:navigate→content-paint` User Timing measure ends -after the redesigned conversation is revealed and painted, rather than when -the comments request completes while the conversation is still hidden. Durable -messages can paint before run history and plan enrichment. Runtime-only threads -wait for initial output; late history retains the existing scroll-anchor behavior. -Use Chrome's request waterfall and this mark together to distinguish API wait, -request dependencies, and rendering time. A hard-load trace also includes auth, -company selection, and JavaScript startup before the task navigation mark. - -## Browser performance tracing - -Hosted Paperclip Cloud instances can also trace the board UI in the browser: -a `page.load` span for every hard load and client-side navigation (named by -route pattern), Core Web Vitals, and same-origin API request spans whose W3C -trace context joins the server spans above. It is off unless the instance is -cloud managed and `PAPERCLIP_BROWSER_TRACES_ENDPOINT` is set; self-hosted -installs never download the browser SDK. Configuration, the closed attribute -allowlist, the page-load definitions, and example queries are in -[browser-performance-tracing.md](browser-performance-tracing.md). - ## Enabling tracing ### 1. Install the OTel peer dependencies @@ -230,615 +143,17 @@ for `fs`, `dns`, and `net` are disabled by default because they are too chatty for this workload; everything else from `@opentelemetry/auto-instrumentations-node` is on (HTTP, Express, PG, etc.). -This document also holds three local instrumentation contracts: native runner -traces, sandbox startup traces, and sandbox duplex transport instrumentation. -Those sections follow below. - -## Controller preparation phases - -With an operator OTLP endpoint, `paperclip.heartbeat-preparation` emits active -`heartbeat.prepare.` spans around environment selection, execution -configuration, session preparation, workspace preparation, GitHub environment -and launcher preparation, run output initialization, workspace validation, -runtime services, instruction files, and runtime selection. Database and HTTP -instrumentation can attach child spans during each awaited operation. - -Early context preparation also records `agent_read`, `chat_completion`, -`conversation`, `runtime_state`, `issue_context`, `run_identity`, `trust_preset`, -and `task_context` beneath `heartbeat.prepare`. These time the existing awaited -operations before environment selection; they do not add reads or record content. -The work between those phases is named too: `chat_retry_admission`, -`workspace_selection`, `dependency_readiness`, `issue_checkout`, -`instance_settings`, `workspace_context`, `project_context`, -`plan_wake_routing`, `routine_environment` and `responsible_user`. -`execution_start` times the run and agent status writes and the "run started" -event before run output starts. A repeated read or write has its own span. - -Execution configuration also records separate phases for mentioned skills, -GitHub identity selection, secret resolution, managed AI runtime preparation, -skill inventory, connector assignments, connector skill preparation and delivery, -connection instructions, and agent identity. Their names are -`heartbeat.prepare.configuration_`, using the closed names in -`server/src/services/execution-preparation-timing.ts`. These intervals are inside -`execution_configuration`; do not add them to its duration. They remain available -when a later setup step fails before the provider lifecycle trace starts. - -`task.execution_attempt` owns one invocation of the server executor, from its -admission reads through preparation, provider dispatch, and inline settlement. -Deferred native workspace finalization and reply persistence can finish after -this root ends. It starts a new root trace with a link to the active trigger. It -therefore follows the operator's root sampler even when the HTTP trigger was not -sampled. Async-local ownership parents same-run preparation and nested phases to -the current attempt. Concurrent runs have separate contexts. A phase invoked -without a live matching attempt still starts an independent linked root. - -`task.workspace_finalization` owns each deferred native workspace finalization -check. It starts when the background worker checks the run, including its -admission and ownership checks, and ends when that check returns or fails. -Workspace restore phases nest under this root using the same hashed run ID. -It does not extend an earlier execution attempt or include time waiting for -the background worker to run. Retries have separate roots. A check that finds -no eligible work can end without a restore child. - -`task.response_presentation` owns recovery of an already committed native reply. -It starts a separate linked root because deferred presentation can run after the -execution attempt and workspace finalization have ended. Worker discovery for -a specific run and worker checks include candidate reads under -`response.resolve`. Each discovery or check owns its root; direct recovery and -its worker check share one root when nested. `response.transaction` -includes the recovery transaction; `response.transaction.entry` measures entry -into its callback, including connection acquisition. These spans retain only the -same hashed run ID and never capture reply content. A successful task status is -separate from the time the reply is saved. - -These spans exist before provider dispatch, including setup failures. Preparation phases have -only the existing `paperclip.task.run.run_id` attribute: the first 12 hexadecimal -characters of the run UUID's SHA-256 hash. Failed operations set error status -without recording exception messages, paths, inputs, or returned content. -Search by that hash without a root-name filter to include these preparation -traces; the provider lifecycle trace is created later and can have a different -trace ID. Without an endpoint, tracing remains a no-op. These spans add no -first-party Telemetry events or database run-log writes. - -Workspace preparation also records `heartbeat.prepare.workspace_` spans -for source resolution, provisioning policy, base validation, source access, -provisioning, retained source access, workspace record creation and updates, -task binding, operation binding, configuration records, repository admission, -project repositories, and recovery-root reservation. These intervals are inside -`heartbeat.prepare.workspace`. Repeated bindings or updates have separate spans. -Do not add these intervals to the containing workspace duration. They use the -same run hash and contain no workspace paths, commands, or returned records. - -The `paperclip.native-controller` tracer records -`native.controller.` spans around GitHub access setup, wake binding, -backend construction, connector assignments, assigned MCP discovery, tool -authority, companion selection and Runner binary resolution. It also records -GitHub shutdown, coordinator release, instruction checkpoints and collection, -and warm-session release. Before the coordinator claim it also records -attachment staging, warm controller restore, persistence of the preparation -spans to the run log, and Runner state migration. These intervals can occur between the existing native -preparation, execution and settlement spans. They are controller work, not model -turn time, and carry only the existing run hash. Nested phases overlap their -containing backend or lifecycle intervals; do not add both durations. - -Before provider dispatch, `execution.usage_startup` measures durable usage-recorder -initialization. `execution.mcp_handoff` measures native MCP server resolution or -legacy managed MCP configuration. `execution.dispatch_admission` measures the -final admission gate, including its nested `execution.budget_reservation` span. -The admission span ends after the provider promise is handed off, not after the -provider turn finishes. These spans use only the existing run hash. They close -gaps between preparation and execution; their nested intervals are not additive. - -All preparation timing uses the endpoint gate, even when another library has -registered a tracer provider. Tracer lookup, callback, status or ending failures -cannot repeat work or replace its result or error. Automatic database children -are not guaranteed: an aggregate workspace trace can contain just one span. -If a process exits before an operation settles, its open span may not be exported. - -With an endpoint, `paperclip.controller-startup` records independent -`controller.startup.` root spans for tool reviews, gateway sessions, -delivery-worker readiness, accounting, plugin-worker readiness, native recovery, -hot-restart adoption, orphan reaping, scheduled retries, queued runs, and goal -recovery. These spans have no custom attributes. Each ends when its awaited -phase settles, including failures. They separate controller readiness from -provider startup; they are not agent-run durations. A disabled endpoint takes -the direct work path without a tracer lookup or additional log messages. -Tracing failures cannot repeat recovery or replace its result or error. - -Native recovery and orphan reaping each run a native finalization -reconciliation pass; the periodic recovery loop runs it on every scheduler tick. -With an endpoint, a pass that takes at least one second records, after it ends, -a `controller.native_reconciliation` root span from `paperclip.native-reconciliation` -with one child span per phase: `legacy_workspace_exports`, -`obsolete_policy_reviews`, `automatic_completion_reviews`, `candidate_scan` and -`candidates`. The pass span carries `paperclip.native_reconciliation.scoped` and, -once known, `paperclip.native_reconciliation.candidates` (a count). A failed -pass marks the pass span and the phase that was running with an error status. -Faster passes record nothing. - -Heartbeat configuration preparation overlaps independent reads. Skill preparation -runs alongside connector assignments; standing connection instructions wait for -assignment catalog repairs, but can overlap the skill branch. These spans can -finish out of order. Do not add their durations as serial elapsed time. The -historical `skills.prepare` span ends when the skill branch settles, rather than -when its concurrent branches finish. Each preparation attempt settles its started -branches before it returns an error or releases acquired credentials. - -### Detailed execution phases - -The `paperclip.execution` tracer adds these content-free spans beneath the current -attempt or owning phase: - -| Span family | Measured work | -| --- | --- | -| `workspace.transaction`, `.entry`, `.commit`, `.rollback` | Transaction lifetime, connection acquisition plus BEGIN, and settlement after the callback returns. Entry cannot distinguish pool wait from BEGIN. | -| `workspace.row_lock` | Current workspace row read with its row lock. | -| `workspace.sources.inventory`, `workspace.access.*` | Current selected-record reads, task/run identity, current task and selected-project authorization, and selected-source trust. The execution check is separate from full workspace-record disclosure. | -| `workspace.repository.*` | Repository admission binding and policy revalidation, receipt reads/writes, catalog access, filesystem preparation, directory publication lock boundaries, ownership verification, and Git inspection. See the nested admission hierarchy below. | -| `authorization.base`, `.responsible_user`, `.authorizing_user`, `.task_privacy`, `.project_privacy` | The existing base decision, responsible/authorizing-user intersections, and applicable app-record privacy decisions beneath `workspace.access.task_authorization` or `workspace.access.authorization`. These details are scoped to workspace authorization. | -| `workspace.notification`, `workspace.write` | Notification statements and record writes. | -| `workspace.materialize.*`, `workspace.checkout.*` | Private source-directory setup and identity verification, existing checkout lookup, Git credential resolution, clone, optional pristine-object cache lookup/publication (`cache_lookup`, `cache_publish`), requested-ref checkout, and atomic publication. The enclosing `heartbeat.prepare.workspace_source_materialize` includes the complete source-materialization path. | -| `runtime_selection.*` | Completion contracts, session/recovery reads, profiles, interaction materialization, backend discovery, dynamic skill package staging (`skill_assets`), bootstrap, run/coordinator writes, transaction entry/settlement, and workspace synchronization. | -| `runtime_context.instructions`, `.skills`, `.mcp` | The three concurrent runtime-context branches. Their durations overlap. | -| `runtime_context.asset_*` | Source reads, manifest hashing, cache lookup, cold materialization, and exact file verification on cold and warm paths. | -| `skills.inventory`, `.wait`, `.bundled`, `.releases`, `.folders`, `.local_sources` | Company skill reconciliation, waiting for an existing company refresh, and its bundled imports, release verification, folder, and local-source work beneath runtime skill preparation. Inventory children overlap their parent. | -| `skills.cache.acquire`, `skills.rows`, `skills.version.read`, `skills.repository.read`, `skills.version.materialize`, `skills.version.verify` | Dedicated connection/transaction startup plus advisory-lock acquisition, authorized skill rows, frozen version and repository reads, and exact runtime materialization/validation. Lock acquisition ends before the protected work; version verification is inside materialization. Only bounded file counts are added. | -| `skills.consume` | The caller's delivery and durable version-pinning callback while the cache lock remains held. | -| `workspace_sync.prepare_host_current`, `.prepare_durable_seed`, `.prepare_adopt_remote` | Runtime preparation under the selected inbound mode, including snapshot and staging work. A warm mismatch may produce a second preparation; it is real repeated work. | -| `workspace_sync.source_root`, `.repositories`, `.ignore_rules`, `.snapshot_git`, `.snapshot_baseline` | Physical source capture, managed repositories, ignore rules, Git metadata and baseline content snapshot. | -| `workspace_sync.pack`, `.git_clone`, `.git_archive`, `.overlay_copy`, `.overlay_archive`, `.deleted_manifest` | Temporary shallow Git clone, its archive callback, selected working-tree overlay copy/archive, and the deleted-file manifest. The archive is inside the clone's lifetime; do not sum parent and child. | -| `workspace_sync.seed_generation`, `.seed_lookup`, `.seed_replay`, `.seed_persist`, `.seed_publish`, `.seed_verify`, `.seed_extract`, `.seed_snapshot`, `.seed_cleanup` | Seed identity, cache lookup, replay, durable copies, publication, extraction/re-snapshot verification and temporary cleanup. Cache hits omit cold clone and verification work. | -| `workspace_sync.seed_cache_copy`, `.seed_cache_sync`, `.seed_cache_hash` | Archive linking/copying, disk flush, and checksum work inside cache publication. Recovery-backed archives retain their existing flush, including when a cache link shares the recovery inode. Only a separate cache-only Git seed omits the flush; its bytes are rebuilt on a cache miss. Every reader verifies checksums. These are children of seed publication, not additional elapsed time to add to that parent. | -| `workspace_sync.seed_cache_capacity`, `.seed_cache_evict`, `.seed_cache_locked_publish` | Quota inventory, eviction planning/application, and the publication body after the company lock is acquired. Capacity may run before and inside the lock. A gap after seed verification and before locked publication can include lock acquisition; locked publication itself excludes that wait. Copy/sync/hash and the locked quota/eviction work are nested children. | -| `workspace_sync.seed_read_copy`, `.seed_read_hash`, `.seed_read_touch` | Private cache materialization, verification of the exact reused bytes, and last-used bookkeeping including company-lock acquisition. All are nested in seed lookup. A long lookup alone does not identify copy, hashing, or lock contention as its cause. | -| `workspace_sync.git_index_refresh` | Fully awaited stat-metadata refresh after restoring a fresh OpenCode sandbox checkout. It shares the inbound barrier and command timeout; dirty working-tree content stays unstaged. Recovery and retained sandboxes skip it. | -| `workspace_sync.inbound_barrier`, `.stage_workspace`, `.transfer` | The inbound scheduler barrier, whole workspace task, and provider `syncIn` call (including provider guards, upload and post-upload extraction). Parallel tasks overlap; provider transfer/exec children give the finer transport split when available. | -| `workspace_sync.progress` | Awaited progress/status reporting, including the existing lifecycle run-log writes. These are not file transfer work. | -| `workspace_sync.run_read`, `.descriptor_directory`, `.descriptor_read`, `.archive_hash`, `.warm_stamp`, `.durable_seed_verify`, `.manifests_persist`, `.descriptor_write`, `.reference_write` | Saved run state, recovery descriptors, archive hashing, remote warm-stamp check, manifests and final descriptor/reference persistence. | -| `connectors.browser_use.resolve`, `connectors.speko.resolve`, `connectors.slack.resolve`, `connectors.agentmail.resolve` | Each sequential connector resource resolver beneath configuration or native-controller assignment resolution. Empty/denied assignments still have measurable work. | -| `connectors.browser_use.connection`, `.catalog`, `.grant` | Browser Use candidate reads, the full authorized catalog listing currently used to discover Browser Use resources, and grant checks. The catalog can contain work for other connectors. | -| `connectors.discovery.scheduled`, `.queue`, `.build`, `.agent`, `.connections`, `.github`, `.slack`, `.speko`, `.policy`, `.on_demand_policy` | Discovery scheduler lifetime and wait, catalog construction, agent validation, descriptor sources, and policy decisions. Queued work retains the initiating run's trace context even when another run releases the scheduler slot. | -| `connectors.github.catalog`, `.connections`, `.grants`, `.grant_members`, `.membership`, `.refresh`, `.credentials`, `.repositories`, `.grant_lock`, `.grant_write`, `.webhooks` | Authorized GitHub catalog construction, current connection/grant reads, credential and metadata refresh, repository pagination, grant transaction row lock/write, and parallel webhook binding calls. | -| `connectors.github.refresh.transaction`, `.entry`, `.commit`, `.rollback` | The existing managed-grant refresh transaction and settlement. Entry combines connection acquisition and BEGIN. | -| `connectors.slack.candidates`, `.authority`, `.profile`, `.settings`, `.identity`, `.credentials`, `.revision` | Slack endpoint enumeration, authority revalidation, enabled profile, settings, accepted requester provenance, credential reads and authorization revision. | -| `connectors.slack.authority.transaction*`, `connectors.slack.catalog.transaction*`, `connectors.slack.catalog.lock`, `.entries`, `.write`, `.profile` | Slack authority and catalog transaction entry/settlement, advisory lock, catalog reads/updates and existing-profile lookup. Entry combines pool acquisition and BEGIN; it does not isolate pool wait. | -| `execution.runtime` | Runtime dispatch, usage, workspace finalization and runtime cleanup; this includes work after provider execution. | -| `execution.workspace_finalize` | Best-effort native workspace finalization, including restore recovery, copyback and commit. Its nested restore and commit spans measure distinct steps. | -| `execution.workspace_ownership`, `.workspace_ownership_wait`, `.workspace_restore`, `.workspace_commit`, `.native_finalize` | Ownership coordination including its action, acquisition before the action, copyback, final snapshot/stamp/descriptor persistence, and native settlement. | -| `completion.*` | Completion handler, run-log finalization, terminal persistence, accounting, liveness, and continuation summaries. | -| `response.resolve`, `.authorize`, `.add_comment`, `.transaction*`, `.row_lock`, `.write`, `.publish` | Response selection, existing authorization, comment transaction including commit or rollback, row wait, insert, and external publication enqueue. | -| `execution.realtime` | Synchronous live-event and plugin publication dispatch. It does not measure browser receipt or paint. | - -For bounded native OpenCode diagnosis, set -`PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS=1` as an agent/environment variable. -The existing configured-environment projection carries it into the native Runner. -It defaults off. The Runner creates an authenticated loopback OTLP sink and enables -the pinned OpenCode runtime's internal tracing. The sink discards logs, resource -attributes, span attributes, events, and unknown span names. It retains only closed -phase names, wall timestamps, and success/failure, with a 1 MiB request limit, -128 retained measurements, and 16 measurements per phase. No operator OTLP endpoint -or ingestion credential is passed to OpenCode. - -For fresh remote diagnostic runs, the selected pack must contain the current -build's OpenCode proxy. An otherwise compatible image pack can predate the -collector. Such a pack cannot satisfy the diagnostic request. The existing -verified pack preparation path selects or stages the current proxy; it can add -startup time or fail admission when matching runtime assets are unavailable. -Ordinary runs retain compatible image-pack reuse. Recovery retains the pack -identity already admitted for that session. - -Available phases cover context/instruction loading, skill discovery, tool and model -resolution, model streaming (`ai.streamText`, including stream consumption), Git -discovery/default branch, snapshots, dependency installation, and plugin startup. -These intervals overlap; do not sum them as elapsed time. At each terminal turn, -already-received measurements travel in one `harness.diagnostic` event through the -existing durable PRP channel. Late exports may be absent; collection never waits -for a provider flush or delays terminal publication to complete the diagnostic. -Late spans from a prior completed turn are discarded at the next boundary. - -The server validates the closed fields again and records them under a foldable -`provider.runtime` group inside `native.session.execute`. The normal operator -endpoint gate controls Honeycomb export. The single diagnostic batch stays in the instance run log. Its OTel projection -does not write duplicate phase rows or await additional database work before -terminal consumption. Without an endpoint, no provider child spans are exported. Raw OpenCode OTLP must -never be sent directly to the operator endpoint: it can contain prompts and -authorization attributes before the loopback sink removes them. - -Detail phases emit at most 16 spans of each name per attempt. Larger receipt and -asset inventories continue under the containing group without unbounded per-row -or per-file spans. Adding detail spans does not itself change work, query order, -authorization, or locks. -Manual transaction and dispatch boundaries retain their actual lifetime. -Asset writes and verification may add only non-negative integer -`paperclip.execution.fileCount` and `paperclip.execution.bytes` attributes. -The closed keys are declared in `EXECUTION_PREPARATION_SPAN_ATTRS` in -`packages/adapter-utils/src/acpx-engine/startup-timing.ts`. -Repository checkout cache phases also carry the closed -`paperclip.execution.repositoryCache.outcome` value: `disabled`, `hit`, `miss`, -`published`, `already_present`, `contended`, `capacity`, `budget`, `invalid`, or `error`. -The clone span carries the boolean -`paperclip.execution.repositoryCache.reference_supplied`, including `false` for -a fallback clone. A lookup hit means a validated cache was found, and supplying -a reference does not prove Git avoided a download. These attributes carry no -cache keys, remote URLs, paths, refs, credentials, or error text. - -Pristine repository-object cache version 2 mirrors the fresh checkout's refs, -including remote-tracking refs. Version 1 copied their objects into a bare -repository but omitted the remote-tracking tips. Git could then download those -objects again during negotiation. The version is part of the cache key, so the -first checkout creates a new generation and later checkouts can reuse its tips. -Existing generations remain under the same storage limits. Cached refs stay -private to the company and credential scope. Task checkouts still authenticate -online, use the current remote refs, and dissociate their objects from the cache. - -Other execution phases, including manual boundaries, carry only the existing -hashed run ID. Exceptions set status without exporting their messages. - -#### Repository admission - -Repository preparation keeps repeated current-identity and permission checks -visible. An existing ready checkout still validates its receipt, origin, pin, -current binding and acquisition authority. A ready checkout can omit clone work -while retaining catalog, database, filesystem and Git inspection work. - -The hierarchy folds those operations beneath the admission that initiated them: - -```text -heartbeat.prepare.workspace_repository_admission - workspace.repository.binding (repeated at publication boundaries) - workspace.repository.db.issue / db.workspace / db.run - workspace.repository.paths (when the destination must be checked) - workspace.repository.current_policy - workspace.repository.db.agent / db.project / db.run - workspace.access.execution - workspace.access.task_read / agent_read / run_read - workspace.access.task_authorization - authorization.base / responsible_user / authorizing_user / task_privacy - workspace.access.workspace_read / source_read / projects_read - workspace.access.authorization (selected project) - authorization.base / responsible_user / authorizing_user / project_privacy - workspace.access.trust - workspace.access.trust.project_read - workspace.repository.receipts - workspace.repository.paths - workspace.repository.catalog - connectors.github.catalog (when GitHub catalog access is needed) - connectors.github.connections / grants / grant_members / membership - connectors.github.refresh (managed grant, including existing retry) - connectors.github.credentials - connectors.github.repositories (metadata and repository pagination) - connectors.github.refresh.transaction - connectors.github.refresh.transaction.entry - connectors.github.grant_lock / grant_write - connectors.github.refresh.transaction.commit / rollback - connectors.github.webhooks (existing parallel binding calls) - connectors.github.credentials / repositories (legacy or unmanaged connection) - workspace.repository.fs_prepare - workspace.repository.ignore_rules - workspace.repository.publication (one per concrete receipt) - workspace.repository.lock_wait - workspace.repository.critical_section - workspace.repository.checkout_identity - workspace.repository.state_write - workspace.repository.ownership_read / ownership_verify - workspace.repository.acquisition (repeated current acquisition check) - workspace.repository.db.issue / db.workspace - workspace.repository.current_policy - workspace.repository.materialize - workspace.checkout.lookup - workspace.checkout.git_auth / git_clone / git_ref / publish (cold path only) - workspace.repository.git_origin / git_branch / git_commit - workspace.repository.binding (same current checks as above) - workspace.repository.ownership_write / state_write - workspace.repository.lock_release -``` - -Optional branches appear only when the corresponding existing operation runs. -The first binding check precedes the receipt lookup; an empty receipt list returns -without catalog, path, staging or publication work. Later binding and acquisition -checks revalidate current authority rather than authorizing historical readers. -The retired filesystem-history inventory, root-policy reservations and reader -authorization phases are no longer part of admission. - -Catalog groups retain the existing sequential connection processing and any -credential refresh or pagination it requires. The initial four catalog reads -can overlap, as can webhook-binding requests. Automatic HTTP spans, when enabled, -sit beneath the owning credential, repository-metadata or webhook group. They -do not require a separate execution-attempt root. `credentials` includes its -existing secret/credential lookup and any OAuth refresh; `repositories` includes -the whole metadata or token-repository listing, rather than one invented span -per repository. No repository list or credential value is attached to a custom -span. - -Database read/write spans measure the complete awaited client operation. Their -duration can include pool acquisition, driver and network time, database work, -and database lock waits. They do not by themselves identify a slow SQL plan or -prove a pool wait. `lock_wait` instead measures the directory publication helper -up to entry into its callback, including canonicalization and lock acquisition. -`critical_section` measures the callback after acquisition. `lock_release` starts -after that callback settles and ends when the helper finishes releasing its -lock. A callback failure marks the critical section and publication as failed; -a successful release remains successful. These directory boundaries are not -PostgreSQL pool or row-lock measurements. - -Parents include their children, so do not add binding, catalog or publication -durations to their descendants. Repeated guards and concurrent HTTP requests -must be read in timeline order. Detail names remain capped at 16 occurrences per -attempt; later operations still execute under their enclosing group. A missing -leaf after that cap, or absent automatic driver instrumentation, does not prove -that no work occurred. - -The `authorization.*` details appear only inside a workspace task/project -authorization group. Unrelated startup decisions do not emit those details or -consume their per-attempt budget before repository admission reaches its current -task checks. - -These additions use the existing opt-in OpenTelemetry path. With -`OTEL_EXPORTER_OTLP_ENDPOINT` unset or blank they perform the original work -without consulting a tracer, even if a provider is globally registered. They add -no Telemetry events, run-log writes or span-attribute keys. The closed attribute -allowlist above remains unchanged: no raw SQL, paths, company/task/workspace or -receipt IDs, repository URLs, refs, credentials, request bodies or error text. -Tracer failures must preserve the original result or error and must not replay -authorization, writes, Git commands or lock callbacks. - -A committed comment transaction establishes durable server storage. A publication -enqueue establishes pending delivery, and realtime dispatch establishes a server -notification call. None establishes browser paint or external delivery. The attempt -can continue through later bookkeeping and resource cleanup. A later recovery -invocation has its own attempt; this does not manufacture one continuous trace -across queueing, process restarts, or an unavailable controller. - -### Connector preparation work - -Run configuration resolves the four connector families concurrently and preserves -registration order. Browser Use assignment reads only active Browser Use -connections and their eligible catalog entries. It applies the same tool policy, -grant, company, and restricted GitHub guest checks without joining the full tool -discovery queue or resolving unrelated Slack, GitHub, and Speko tools. - -Native startup registers direct connector tool definitions from the run's pinned -skills. It does not repeat assignment discovery. These definitions do not grant -access: each invocation still resolves current assignments and enters the existing -permission and approval gateway. A retained session may advertise a tool whose -access was revoked; the call fails under the current authorization state. - -Slack assignment checks stored catalog hashes against the bundled definitions. -A current catalog and existing profile need no catalog transaction or advisory -lock. Current profile bindings and entries still determine availability, followed -by one live task authority check. Missing or changed catalog definitions use the -existing locked reconciliation path, with authority checks before and after the -update. Disabled catalog entries and operator-removed bindings remain disabled. -No authorization result is cached across calls. - -### Reading a slow startup in Honeycomb - -Filter `paperclip.task.run.run_id` to the first 12 hex characters of -`SHA256(run UUID)`, then inspect the attempt's waterfall with its -`service.version`. An agent/model setting or the repository's checked-out commit -does not establish the server revision. The detailed spans are available only -after this instrumentation is deployed; an earlier aggregate cannot establish -which child was slow. - -Start beneath `heartbeat.prepare.workspace` with source materialization versus -provisioning, repository admission, and environment acquisition/realization. -Source materialization now separates filesystem setup, credential resolution, -Git cloning and source identity checks. Under -`runtime_selection.workspace_sync`, compare snapshot work, the seed-cache path, -archive construction/verification, provider transfer and descriptor persistence. -Use span start/end times to identify serial work and uncovered gaps; summing -nested or concurrent durations overstates elapsed time. - -For connector delay, compare the four `connectors.*.resolve` spans beneath each -assignment-resolution parent. A long Browser Use `.catalog` can be discovery -queueing, connection descriptors, another connector's authority checks, or policy -evaluation. A long Slack transaction entry, lock or credential span calls for a -different investigation. Configuration and native backend setup currently resolve -assignments separately; the trace records both without caching authorization or -changing access decisions. - -New workspace detail callbacks have fixed names and remain trace-only. They do -not create additional lifecycle events or awaited run-log writes. Existing coarse -progress writes remain intact and appear under `workspace_sync.progress`, so -reporting overhead is visible alongside useful work. No per-file spans, paths, -repository URLs, connector resource IDs, tool schemas, credentials or exception -messages are added to the export. The endpoint gate and per-phase span limit -above still apply. - - -## Native Runner Trace Spans - -Provider-pack fallback staging separates `provider_pack.archive.verify` -(controller archive identity), `provider_pack.archive.probe` (remote helper support), -`provider_pack.archive.reuse` (copy and hash image files), -`provider_pack.archive.verify_missing` (verify only layers needing upload), -`provider_pack.archive.transfer` (compressed file -transfer), and `provider_pack.archive.extract` (received hash check and extraction). -They are children of the existing pack selection/upload path and also appear in -the local run timing log. Their fixed names add no paths, credentials, or content -attributes. The operator endpoint gate remains unchanged. Source installs without -prebuilt archives retain the existing directory upload span. -`provider_pack.directory.verify` measures expanded source verification when -directory staging is required. - -Archive installation verifies the archive bytes and then the installed pack -against the selected manifest. It does not hash the unused expanded controller -tree. Directory installation still verifies that tree before upload, including -when the remote cannot extract an available archive. The final installed-pack -verification applies to both paths. A slow controller tree scan can block the -server event loop and inflate overlapping asynchronous span durations; a copy -span alone does not establish that the disk spent all that time copying. - -The native provider lifecycle emits one foldable OpenTelemetry trace, linked to -the server attempt described above. This is -the native-run trace schema version `3`. `task.provider_session` is the native -provider lifecycle root; it includes preparation and provider execution, but -ends before outer workspace persistence. The heartbeat-owned local run-log -`task.run.measured` records terminal elapsed time including durable copyback; -every other native span carries a real OpenTelemetry parent context rather than -only a descriptive `parentName` field. - -The native lifecycle root uses the operator's root sampling policy. It links -to the matching live server attempt (or a valid active trigger) without inheriting -its sampling decision. This is a link because historical ingress and queue spans -can predate this invocation. It does not reparent earlier work beneath a later span. -An unsampled HTTP request therefore cannot suppress an otherwise sampled -background run. An operator who disables root sampling still gets no spans. -Without an OTLP endpoint, tracing remains silent and does not export data. - -The run link in Honeycomb matches `task.provider_session` for native runs, `task.run` for legacy adapters, -`task.execution_attempt` for server preparation and settlement, and -`task.workspace_finalization` for deferred native copyback and `task.response_presentation` -for committed native reply recovery. It retains the exact hashed run-ID and service filters and groups by trace ID. The URL builder uses Honeycomb’s supported `in` operator for the five root names; see the [query specification](https://github.com/honeycombio/honeycomb-mcp#query-specification-for-run_query). This changes only the query link. The operator endpoint gate and span attribute allowlist remain unchanged. - -The canonical lifecycle is: - -```text -task.provider_session -├── heartbeat.queue -├── task.prepare -│ ├── environment.startup -│ │ ├── environment.acquire -│ │ └── environment.workspace.realize -│ ├── skills.prepare -│ ├── heartbeat.prepare_before_environment -│ ├── heartbeat.prepare_after_environment -│ └── native.coordinator.claim -├── native.session.execute -│ ├── runner.session.startup -│ │ ├── runner.transport.connect -│ │ │ └── runner.artifact.prepare -│ │ ├── runner.transport.activation -│ │ ├── runner.transport.ready -│ │ ├── runner.runtime.stage -│ │ │ └── stage.sync -│ │ │ ├── stage.asset.home -│ │ │ │ └── session.checkpoint.restore -│ │ │ ├── stage.asset.runtime_context -│ │ │ └── stage.asset.ca_bundle -│ │ ├── runner.session.bootstrap | runner.session.resume -│ │ └── runner.turn.submit -│ └── agent.turn -│ ├── runner.turn.submitted_to_started -│ ├── provider.time_to_first_agent_event -│ ├── tool.request.input_stream -│ └── tool.execute -└── task.settle - ├── native.result.finalize - └── session.checkpoint.persist -``` - -The tree shows stable semantic groups, not an exhaustive leaf list. Existing -artifact discovery and verification, process launch, PRP/websocket, ingress, -sandbox lease, harness-state, provider, duplex, and `sandbox.exec` spans remain -under the closest group. This keeps detailed diagnosis available while letting -a trace UI collapse the run into preparation, runner startup, agent work, and -settlement. A repeated operation creates another span with the same semantic -name; attempts are not encoded into span names. - -`runner.session.startup` ends at the first durable `turn.submitted` event. A -fresh provider session records `runner.session.bootstrap`; an exact recovered -session records `runner.session.resume`. `agent.turn` begins at -`turn.submitted` and ends at the provider terminal event. `task.settle` begins -at that terminal event and remains open through finalization and checkpoint -persistence, so settlement work does not appear to outlive its parent. - -`provider.time_to_first_agent_event` ends at the first meaningful provider -activity: a nonempty assistant/reasoning delta, a tool announcement with an -execution identity, or an existing assistant/reasoning/tool item start or -completion. Usage updates and empty deltas do not count. This is a first -activity metric, not time to a finished answer. - -`task.time_to_first_token` measures the wait until text is deliverable to the -task transcript for each native dispatch. The first qualifying event is a -nonempty assistant or reasoning text delta, a completed assistant or reasoning -item with text, or an accepted run result with a nonempty summary. Text released -by redaction at item/turn/session completion also qualifies. Item identities and -text fields follow the task transcript projection; item starts, tools, usage, -empty text, result proposals, and duplicate PRP replay do not end the wait. - -The first-text milestone occurs after `task.prepare` and Runner startup. The -timing span is a cumulative interval, not a separate preparation step: - -```text -accepted ingress → queue → task.prepare → Runner startup → provider work → first text -└────────────────────── task.time_to_first_token ──────────────────────────────────┘ -``` - -The span starts at the earliest accepted input. The accepted comment or attested -question response is the start only when its span is the earliest preparation span. -A comment coalesced into an already-queued run starts after run creation, so that -run starts at run creation from the queue span and reports `run_created`. The -durable wake request's acceptance time replaces the start when it is earlier -(deferred, coalesced and retried wakes). The `anchor` attribute (`comment`, `question_response`, -`wake_request`, `run_created`) names which one. The wake request time is read -after the first text in detached diagnostic work bounded to 2 s (PostgreSQL -cancels a stalled read through a transaction-local `statement_timeout`), so it never adds a -wait before `turn.start` and never delays event delivery. Callers without -preparation history start at native dispatch and report `run_created`. The interval includes queueing, Core preparation, workspace preparation, -Runner startup, provider latency, transport, and durable event ingestion. It ends -in Core's commit callback, when the text is readable through the run-events API, -using the Core clock rather than the provider event timestamp. Browser delivery -and rendering are excluded. The name is retained for existing trace queries; -this measures the first deliverable text, not an exact model token boundary. -Only the first qualifying event in a dispatch emits a span. Its `eventKind` is -`reasoning` for thinking text and `agentMessage` for assistant text or a result. -A dispatch without deliverable text emits no sample, including an early failure. -Same-run recovery retains the original historical start and can emit a new sample -only for newly committed output; it does not reconstruct prior first-token timing. -`task.time_to_first_token` is a child of `task.provider_session` that overlaps -queueing, preparation and execution; do not add its duration to those phases. -No text or provider event identifiers are exported. The existing duration attribute -is `paperclip.native.span.duration_ms`. - -`task.time_to_first_agent_activity` uses the same start and `anchor` as -`task.time_to_first_token`, and ends when Core commits the first event that -`provider.time_to_first_agent_event` counts: a text delta, a tool-call start, or -a reasoning item, whichever comes first. That is when the user sees the agent -respond, so the native speed budgets judge this span (metric -`time_to_first_activity`, measured from run creation). Its `eventKind` is -`agentMessage`, `reasoning`, `toolCall` or `dynamicToolCall`. Time to first text -stays a reported metric without a budget: tool-first adapters (for example -Claude) often call tools before they write any text, so first text includes -model tool work rather than control-plane latency. Like TTFT, it is a cumulative -child of `task.provider_session`; do not add it to the phases it overlaps. - -`tool.request.input_stream` measures the observed request-input window: from -an ACP tool announcement to its last input update before the provider reports -the tool complete. It can include provider buffering and transport. It is not -a claim about the exact end of model generation or the start of API execution. -The span is omitted when no subsequent input update is observed. - -For native control-plane tools, `tool.execute` measures authorization and -execution inside the server authority, including time spent in HTTP requests. -Provider tool IDs and MCP request IDs are separate namespaces; the trace does -not guess a pairing by tool name or arrival order. Both spans belong to the -current run's `agent.turn`, including when a warm provider session is reused. -Their `operation` attribute is a known semantic tool name or `other`. Only a -boolean input-update marker crosses the provider-event boundary; no arguments, -argument hashes, or raw call IDs are exported by these spans. Concurrent tools -have separate durations; overlapping spans must not be summed as wall time. - -The active native scope is also published through the existing asynchronous -runtime-parent seam. Provider execution, plugin, websocket/duplex, daemon, and -sandbox spans therefore inherit the correct branch even when their callbacks -run in another service layer. With no active native scope, those existing seams -retain their documented fallback behavior. - -The root carries only a hashed run id, runtime label, schema version, wall time, -and outcome. Native child attributes use the bounded -`paperclip.native.span.` prefix and a closed key allowlist; values are limited -to finite numbers, booleans, or short strings. Commands, arguments, environment -values, paths, output, credentials, and raw identifiers are discarded by the -trace helper. `task.provider_session.measured` records that same interval in the -local run log, without a duplicate full-width OTel span. The separate heartbeat -`task.run.measured` event is the authoritative end-to-end duration. -Persisted `run.performance.span` events retain the v1 run-log schema and include -`traceSchemaVersion: 3` so local tooling can distinguish the hierarchy. - -Like every span in this document, native-run spans are opt-in. When -`OTEL_EXPORTER_OTLP_ENDPOINT` is unset, the tracer remains a no-op; the local -run-log copy is unaffected. +## Other diagnostic switches + +- **OpenCode performance diagnostics.** Set + `PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS=1` as an agent or environment + variable. It defaults off, and setting the OTLP endpoint alone does not turn it + on. The Runner then records closed OpenCode phase timings through a local, + authenticated sink. No operator OTLP endpoint or ingestion credential is + passed to OpenCode. +- **Browser page-load tracing** on hosted instances needs + `PAPERCLIP_BROWSER_TRACES_ENDPOINT`. See + [browser performance tracing](browser-performance-tracing.md). ## Sentry Error Monitoring @@ -1016,7 +331,7 @@ backend Sentry DSN and the audited SDK. Set `PAPERCLIP_SENTRY_RUN_FAILURES` to: | Value | Reports | | --- | --- | | `off` (default) | No run failure events. Ordinary server exception reporting still uses the backend DSN. | -| `unexpected` | Failed and timed-out runs, plus unexpected started cancellations, with the existing configuration, quota, and external connection filters described below. | +| `unexpected` | Failed and timed-out runs, plus unexpected started cancellations, with the configuration, quota, and external connection filters described below. | | `all` | Every failed or timed-out run, including the known configuration, quota, and external connection failures. Unexpected started cancellations also report. | Missing, blank, or unrecognized values keep run reporting off. Expected operator @@ -1116,509 +431,17 @@ Sentry, so a crash or network outage can lose events. `all` selects failures; it does not promise delivery or export complete transcripts. Detailed output stays in the instance behind the existing authenticated APIs, with its normal retention. -Known missing-secret configuration blockers are kept in the task's run log, -blocked state, and owner recovery action, without a Sentry run-failure event. -The exclusions in this section apply to `unexpected` mode only. -This requires a failed `configuration_incomplete` run in the preparing stage, -a setup-phase report, explicit proof that provider work did not start, and a -nonempty list of recognized missing or inactive secret bindings. Process exit -evidence, unknown binding reasons, secret-provider failures, ambiguous missing -secret-definition lookups remain reportable. This filter does not change task -recovery, credentials, or execution policy. - -Native `native_provider_usage_limit` failures also stay on the task when their -typed provider failure is `quota_exhausted` or `rate_limit`. The task keeps its -blocked state and quota cooldown. Setup failures, interrupted processes, missing -or malformed provider evidence, and other failure categories still report. -`all` mode also reports typed native usage limits. - -AI account selection also stays local when the selection service proves a -missing responsible user, personal default, or selected connection; an -incompatible selection; an account that needs reconnection; or an active -responsible user who lacks the selected credential's human sharing permission. -The sharing rejection keeps its existing HTTP 403 and does not grant access. -Other permission denials, including absent identity and inactive membership, -remain outside this sharing classification. The service marks the original error, -and setup preserves its closed `selectionFailure` reason. -The same failed/preparing/setup/bootstrap checks apply, and resumed native runs -with persisted provider input remain reportable. The generic -`ai_connection_unavailable` wrapper alone is insufficient: database, credential -provider, controller, and unclassified errors still report. Failed runs, blocked -tasks, and account-repair actions remain unchanged. - -A workspace policy conflict also stays local when the resolver proves that an -explicit `local_path` or `non_git_path` project workspace has no repository URL, -Git confirms the selected directory is not a repository, and the task requests -a Git worktree. The run must fail during setup before provider work starts. -Its existing validation error, blocked task and board recovery action remain. -Local Git command failures, permissions, corrupt repositories, fallback paths, -and generic missing or unrestorable workspaces remain reportable. The error text -or `workspace_validation_failed` code alone never suppresses them. - -Recognized external connection failures also stay in the local run result instead -of producing application-error events in Sentry. Their producer records a closed -`connectionFailure` descriptor: schema version, provider, operation, and reason. -It contains no URL, host, path, credential, or remote response. This classification -does not change the run's failed state, task recovery action, retry policy, or -whether remote work may have been accepted. - -- Managed remote Git clones classify known authentication, repository access, - invalid URL, DNS (including machine-specific SSH aliases), connection, TLS, - rate-limit, and upstream failures from the actual clone subprocess. Setup must - fail before provider work starts. Every failed workspace candidate must have - proven connection evidence; a mixed or unknown failure remains reportable. - Local/file clones, credential-provider exceptions, local checkout or copy - failures, process signals, and repository corruption remain reportable. Remote - fetch failures already return workspace warnings; their classification is not - transferred to a later failure resolving a local base ref. -- Hermes gateway configuration validation and the initial create-run request use - exact config, HTTP, or structured transport evidence. Missing configuration, - rejected credentials, unavailable endpoints, rate limits, and upstream outages - remain visible to the run owner. Unknown protocol/parser errors, missing run - identifiers, untyped terminal failures, and timeouts after accepted work remain - reportable. Stream/poll errors retain their existing retry and logging behavior. - -A Codex ACP model capacity failure also stays local. The Codex ACP classifier -must match a typed `service` terminal failure that reports the model at capacity -or the server overloaded. It records `codex_transient_upstream` with the -`transient_upstream` family, and the bounded transient retry owns recovery. The -report must come after setup and carry no signal. Other `service` failures, -untyped capacity text, and Codex CLI transient upstream failures remain reportable. -The run keeps its failed state and its terminal diagnostic. - -A native Codex model capacity failure stays local only while its automatic -retry owns recovery. The run must carry `native_provider_overloaded`. The proof -of the retry is the `native_provider_overloaded` successor run for the same -task, which only the committed capacity status decision creates, and only for -the typed `codex`/`server_overloaded` diagnostic. The run's own `resultJson` is -not required: the live heartbeat's failed-status write replaces it with the -adapter's copy, which lacks the finalizer's diagnostic and finalization fields. -Exhausted or held capacity failures, other retry lanes, setup failures, signals, -and unreadable retry evidence remain reportable. A failed retry reports its own -outcome. - -Expected pre-provider waits for a shared project workspace, a credential rotation -lock, or an exhausted AI connection pool carry a server-owned expected -cancellation receipt. They retain existing retry and lock behavior without a -Sentry cancellation event. A later failed retry still reports its actual error; -the wait code alone is not sufficient to suppress an event. - -MCP tool discovery records recognized outbound HTTP/transport failures through -server-only provenance. These failures preserve the response status, stored -connection health, audit record, local context, and first-party telemetry while -skipping only Sentry. A proven missing OAuth scope returns an actionable 422 -response with its reconnect guidance. Unknown responses, parsing errors, local -callbacks, database errors, and unproven network-looking messages still report. - -The `run_failure` context also includes the recorded process `exitCode` and -`signal`, so a generic adapter error can still distinguish a nonzero exit from -a signal termination. Exit codes must fit the database's signed 32-bit integer; -missing or malformed values become `null`. Signals must match the reporting -host's Node signal constants; missing values become `null` and unrecognized -values become `unknown`. A signal such as `SIGKILL` does not establish who sent -it or prove an out-of-memory kill. These fields do not change error grouping -or run outcomes, and do not include process output or adapter result payloads. - -For a native Codex turn that ends with a structured HTTP 400 model/ChatGPT -compatibility rejection, the run records `native_provider_model_rejected` -and a fixed message that asks the user to select a supported model or connection. -This requires a committed runner terminal for the selected model and the exact -failed turn. Agent text, tool output, unrelated turns, and unknown provider -errors do not create this classification. The provider diagnostic contains only -`provider=codex`, `category=model_auth_incompatible`, `status=400`, and -`authMode=chatgpt`. It excludes the model name and provider response. This does -not change credentials, select a fallback model, replay a turn, or alter the -accepted semantic result or cleanup. The existing configuration-blocker recovery -path requires a configuration change instead of automatically retrying the same -model and connection. Native finalization also derives this evidence from the -committed event and the run's pinned provider configuration before it can queue -a failed-result retry. This survives a controller restart before the adapter -diagnostic is saved. Invalid bindings, missing evidence, or a mismatched event -hash do not grant this classification. A current worker's task is blocked for a -configuration change. A pending review instead keeps its original decision and -status version, releases execution, and creates no automatic recovery action. -After repairing the configuration, explicitly retry the reviewer to resolve the -same pending review. The Board's exact failed-run Retry accepts this classified -native failure only while its saved review is still current and pending; caller -payloads cannot select a different review. Dispatch checks that assignment again. -Superseded or completed reviews retain their authority. - -Cloud portfolio proxy failures have an event-local `cloud_portfolio` context. -It contains only the phase (`fetch`, `http_response`, `response_body`, or -`response_write`), upstream HTTP status when available, elapsed milliseconds, -and an allowlisted network error code. Unknown values become `unknown` or -`null`; elapsed time outside 0–60,000 ms becomes `null`. Codes come from at -most four error/cause objects' own data properties, never error messages. -`DEADLINE_EXCEEDED` means the request's own ten-second signal was aborted. -The route's warning uses the same safe fields. Neither record includes URLs, -headers, cookies, bodies, user/stack IDs, or the original exception. Sentry -receives a plain error with the existing generic message and default grouping. -The context does not change the HTTP response, authentication, cookies, cache, -deadline, or single-fetch behavior, and does not carry into unrelated events. - -A file storage provider failure has an event-local `storage_failure` context -and `storage_operation` and `storage_error_code` tags. The S3 provider records -the failed call (`put_object`, `get_object`, `head_object`, `delete_object`, -`create_multipart_upload`, `upload_part`, or `complete_multipart_upload`), -the provider's error code, the HTTP status, the provider-issued request ID, -and the SDK attempt count. Values come from the SDK error's own data -properties. A value that does not match its bounded format becomes `unknown` -or `null`. The record never includes the bucket, object key, endpoint, -credentials, error message, or provider response body (such as an S3 -`StringToSign`). Sentry receives the original error with default grouping, -so existing issues keep collecting events. The record does not change -storage behavior, not-found handling, or HTTP responses. It is attached only -to the error that the failed call threw. - -An unconfirmed adapter Stop timeout has an event-local `adapter_stop` context: -the run UUID, built-in adapter type, native/legacy runtime mode, configured -wait duration, and whether abort was requested. Invalid identities become -`null`, and unknown adapter/runtime values become `unknown`. The report does -not include stop reasons, prompts, process output, provider responses, or -credentials. It preserves default error grouping and does not acknowledge -termination, remove the live execution control, or change the timeout. The -context is sent only through the existing opt-in Sentry gate and never leaks -into unrelated captures. - -The context also samples the pending execution `phase` and `phaseElapsedMs` -when the Stop timer expires. An in-memory tracker belongs to the exact live -execution control; a replaced or missing owner reports `unknown` with a null -elapsed time. Labels come from a closed list and elapsed time uses a monotonic -clock, capped at one day. Nested scopes remain visible while their awaits are -pending, including ACP session close, transport stop, instruction collection, -workspace restore, and host instruction or lease cleanup. `phase_reporting` -means a step is waiting to write timing or teardown error diagnostics. `adapter_execution` and -`host_execution` are coarse labels for work outside those narrower scopes. -The tracker clears when its executor finishes. A phase is diagnostic context, -not evidence that a provider stopped or that files were recovered. No new -run-log or Telemetry event is emitted by this tracker. - -The shared reporter also attaches bounded diagnostic contexts for both legacy -and native runs: - -- `run_execution`: runtime mode, execution stage/native phase, driver and version, - duration, ACP activity, failure phase, stop reason, error family, - and timeout settings when available. -- `adapter_failure`: selected adapter error fields such as phase, category, - protocol code, retryability, cause message, stack preview, HTTP status, and request ID. -- `provider_failure`: the saved provider failure category, title, and details. -- `run_exception_0` through `run_exception_3`: exception names, codes, HTTP - statuses, and request IDs for a caught exception and up to three causes. - -When a Daytona acquisition fails with pending allocation cleanup, the immediate -setup-failure report can include `environmentAcquisitionPhase`, -`environmentAcquisitionElapsedMs`, and `environmentAcquisitionBudgetMs` in -`run_execution`. The phase is one of `create`, `workspace`, `shell`, `expiry`, -or `sentinel`. It records the first acquisition failure observation, before -inline cleanup, not the cause of the failure. Elapsed time measures acquisition -start to that observation; if cleanup later consumes the deadline, this time -still describes the earlier failure. The overall error message is unchanged. -Elapsed time is bounded to seven days, and the budget to one day. Unknown or -malformed optional values are omitted without invalidating cleanup ownership. - -When the deadline expires while Daytona creation is still pending, the plugin -makes one read-only lookup (bounded to five seconds, inside the host's 30-second -RPC margin) of its provisional creation name and reports -`environmentAcquisitionProviderState`. The value is one of `absent`, `creating`, -`pending_build`, `building_snapshot`, `pulling_snapshot`, `starting`, `started`, -`error`, `build_failed`, `other`, or `unavailable` (lookup failed, timed out, or -ownership labels did not match). It records where the provider left the -allocation, not why. The lookup does not delete, retry, or change the cleanup -envelope. - -These fields cross the existing creation-cleanup RPC envelope only for lease -acquisition. The host accepts them only from an actual RPC error with matching -company, environment, and run ownership. A private receipt binds the report to -that run; arbitrary error fields and saved result JSON do not supply evidence. -Raw provider causes, output, paths, URLs, and cleanup ownership identifiers are -not copied into these diagnostic fields. This does not change timeout budgets, -commands, cleanup, retries, task status, or Sentry filtering. The receipt is -process-local: post-restart reports without the original error cannot recover -these observations. Existing saved runs and leases are not backfilled. - -The orphan reaper records a bounded `processLossDiagnostic` before status writes -or cleanup. For `process_lost` failures, `run_execution` includes -`processLossPidRecorded`, `processLossGroupRecorded`, and `processLossLocalCheck` -(`not_observed_alive`, `not_checked`, or `no_identifiers`). It also includes -`processLossRunPredatesObserver`, `processLossObserverUptimeMs`, and -`processLossLastOutputAgeMs` when the timestamps are available and valid. Ages -above seven days are omitted. These are observations, not proof of an OOM, -provider failure, or deployment. The last-output age can include system output. -`processLossRetryEligible` records eligibility for the existing process-loss retry -at detection; it does not claim that a retry was queued or succeeded. This data -contains no process IDs, task text, paths, or credentials and changes no recovery -or ownership decisions. - -When a native session fails because close could not prove durable runner -suspension (`provider_transport_failed: runner did not durably suspend before -checkpoint`), `run_execution` records which barrier was unproven: -`closeRunnerSuspended`, `closeProviderDrained`, `closeSuspendCommandStatus` -(a runner command status, or `not_queued`), `closeRunnerLifecycle` (`ready`, -`suspended`, `closed`, `recoverable_failure`, or `unobserved`), -`closeRunnerIdentityMatches`, `closeProviderState` (`settled`, `unsettled`, -`unreadable`, or `not_local`), `closeProviderPendingEventCount`, -`closeProviderTurnActive`, `closeSemanticResultPersistenceFailed`, and the counts -`closeSemanticToolsPending`, `closeSemanticToolDeliveriesOpen`, and -`closeSemanticResultFailures`. Fields absent from the runner's settlement are -omitted. Tool call, operation, command and event identities, input digests and -provider turn IDs stay in the instance run log. The report reads the caught error -only for these labels; its text and stack are not copied, because they bypass the -executor's identity redaction. These observations do not change close, quarantine -or recovery behavior. - -Remote runner reattachment failures also record `remoteRunnerRecoveryStage` -and `remoteRunnerRecoveryReason` from the saved run. A confirmed missing process -also records the closed `remoteRunnerLifecycle` and boolean `remoteRunnerSettled` -from the exited runner's saved state. When reattachment fails -before the coordinator saves its result, the report reads the same labels from -the caught recovery error instead. These fields contain -closed labels for marker reads and process verification. They distinguish -missing or unsafe markers, invalid or missing fingerprints, changed or -unavailable process identity, and failed or timed-out probes. Paths, PIDs, -nonces, command lines and transport output are excluded. The existing -`runner_remote_process_identity_unavailable` error message and native failure -classification remain unchanged. The coordinator also saves these labels in -its failure detail and recovery evidence. A later failure clears stale labels. - -ACP turns record `acpLastEventAgeMs`, `acpObservedEventCount`, -`acpPendingToolCount`, and `acpToolInventoryComplete` at finalization, before -usage reads, error logging, and cleanup. The age measures time since the last -runtime event and is omitted if no event was observed or the clock is invalid. -Timeout and cleanup log messages do not reset this age. The pending count uses -known tool statuses; an incomplete inventory cannot establish that no work is -pending. Recent events do not prove useful progress. These fields contain only -numbers and a boolean, never tool names, IDs, arguments, or event content, and -do not change the execution timeout, cancellation, or recovery policy. - -A stopped turn (wall-clock timeout or operator stop) also records -`acpLastEventAgeAtStopMs` and `acpOldestPendingToolAgeAtStopMs`, measured at the -moment the stop fired. A cancel can make the agent emit closing events, so the -finalization age alone cannot separate a turn that went silent long before its -deadline from one that was still working. For a stopped turn, pending tools -means the tools pending when the stop fired, so a tool the cancel closes still -counts; `acpPendingToolCount` keeps its finalization-time meaning. When tools are -pending, `acpPendingToolKinds` lists their ACP tool kinds as a sorted, comma-separated -string drawn only from the closed ACP `ToolKind` enum plus `unknown`; the -server drops the field if any other value appears. - -Claude ACP turns also run a stalled-tool watchdog. A pending tool call that gets -no ACP update for 30 minutes (`stalledToolTimeoutSec`; kept at least 15 minutes -above `MCP_TOOL_TIMEOUT` and `BASH_MAX_TIMEOUT_MS`) ends the turn through the -same cancel and fail-fast deadline as a duplex channel loss. The run fails with -`acpx_tool_stalled` instead of waiting for the wall-clock timeout, and records -`acpStalledToolKind` (one closed `ToolKind` label or `unknown`) and -`acpStalledToolSilentMs`. The stop-time fields above are measured when the -watchdog fired. A live subagent's Task call keeps receiving heartbeats, so only -a call that itself went silent trips the watchdog. A background subagent's Task -call completes when the subagent starts, so the watchdog watches that subagent's -own tool calls instead. Other ACP agents are watched only when -`stalledToolTimeoutSec` is set. - -The engine also observes ACP permission requests without deciding them; ACPX's -permission mode still decides each one. A stalled run records -`acpStalledToolPermissionRequested` (whether the stalled call's permission -request reached Paperclip) and `acpPendingToolPermissionRequestedCount` (how many -pending calls had one). These fields record only that a request arrived, not -that the reply reached the agent. A call whose request never arrived stalled -before the request reached Paperclip. A call whose request arrived stalled -later: on the reply's return trip, or after the agent received the decision. -Both fields hold only a boolean and a count. - -A missing request is informative only if calls like it normally send one. So a -stalled run also records `acpSettledSameKindToolCount` (how many finished calls -of the stalled call's kind the run saw) and -`acpSettledSameKindToolPermissionRequestedCount` (how many of those sent a -permission request). These counts are supporting evidence, not proof of where -the call stalled. The ACP kind is coarse, so peers of the same kind can be -different tools with different permission rules. Read them this way: - -- All or nearly all finished peers sent a request, and the stalled call did not: - this supports a stall before the request reached Paperclip. -- No finished peer sent a request: calls of that kind may skip the request, so - its absence on the stalled call says nothing about where it stalled. -- Some finished peers sent a request and others did not: the counts do not show - whether the stalled call should have sent one. Compare the specific tools in - the run log before drawing a conclusion. -- No finished peers (a count of zero): there is no comparison. - -Both fields hold only counts. - -A sandbox ACP run also records how its agent process session ended, when the -host bridge saw it end before finalization. Startup failures (`create_runtime`, -`ensure_session`, `configure_session`) carry the same fields, so an agent process -that dies during the handshake is reported too. `acpProcessTerminalSource` is one of -`remote_event`, `input_delivery`, `output_poll`, `output_stream`, or -`proxy_close`, and `acpProcessTerminalOutcome` is `exit` or `error`. -`acpProcessTerminalExitCode` (0–255) and `acpProcessTerminalSignal` (a closed -POSIX signal name) are present only when known. These are the same values as the -run log's `ACP process session terminal:` line. They separate a killed or exited -agent process from a host proxy close after a generic ACP connection failure. The -server drops all of them if the source is not a closed label. - -ACP and legacy OpenCode results retain the adapter's resolved wall-clock timeout as -`adapterExecutionTimeout` in the instance run result. Finalization uses it for -`effectiveTimeoutSec`, `timeoutSource`, and `timeoutConfigured`. Sources are -`configured`, `sandbox_default`, or `unlimited`; `timeoutConfigured` identifies an -explicit override, including a negative value that disables the timer. An untouched -sandbox value of zero reports the four-hour default, while a local zero reports -unlimited. Older adapters without a valid resolution retain the config-based -metadata fallback. This does not change timers, Stop acknowledgement, or recovery. -Legacy OpenCode reports a generic timeout message because a provider or output -observation timeout can occur before the configured execution deadline. The -resolved policy describes the configured limit, not proof that its timer fired; -`timeoutFired` retains the existing terminal timeout classification. Provider -stderr remains in the instance run log and is not used as the timeout exception -message. An earlier provider timeout does not establish its upstream cause. - -Legacy OpenCode requests Daytona's persistent process session for -its main CLI command. Daytona targets with the effective persistent-session capability -use asynchronous dispatch and log observation instead of holding one synchronous -command HTTP request open for the whole run. The command's resolved timeout is -forwarded separately from individual status/log observation timeouts. One timer -bounds dispatch and observation, fences late log callbacks, and clears at settlement. -A timeout does not prove command termination; the existing stop/lease cleanup -path still owns that evidence. Existing session callers without this deadline -keep their previous lifetime. Probes, preparation and other providers -keep their existing paths. Local and SSH execution do not use this option. -The resolved execution budget and lease cleanup remain unchanged; the session -request does not prove that a previously observed gateway timeout had this cause. - -When settlement records a workspace restore failure, `run_execution` also -includes `workspaceRestoreFailure` with one of the shared, path-free codes: -`restore_permission_denied`, `restore_lock_timeout`, `restore_unsafe_archive`, -or `restore_failed`. Unknown values are omitted. Workspace paths and arbitrary -pre-restore result data are not included. A later successful run does not, by -itself, establish that an earlier failed restore recovered the workspace files. - -For `configuration_incomplete` with `workspace_base_ref_unresolved`, -`run_execution` includes `workspaceBaseRefRemoteLookup`, `workspaceBaseRefAuthLookup`, -`workspaceBaseRefFetch`, and `workspaceBaseRefRefResolution` when producer evidence -is available. These closed outcomes distinguish skipped operations, auth lookup -failure, and failed or completed Git commands. Optional `workspaceBaseRefFetchExitCode` -and `workspaceBaseRefRefExitCode` are integers from 0 through 255. -`workspaceBaseRefFetchFailureKind` is a coarse, bounded Git diagnostic category; -unknown, mixed, truncated, or oversized command output remains `unknown`. -A failed fetch that prints “remote ref not found” is an observation, not -authoritative proof of user error. These failures remain reportable. The fields -add no Git calls and do not change authentication, retries, task blocking, -recovery actions, or Sentry filtering. They never contain repository URLs, -configured refs, command output, paths, or credentials. - -For `workspace_validation_failed` with `git_worktree_not_reusable`, `run_execution` -includes `workspaceValidationReason` and an allowlisted `workspaceValidationReasonCode`: -`missing_worktree`, `not_a_git_checkout`, `not_registered`, `wrong_repository_root`, -`branch_mismatch`, or `git_inspection_failed`. The last code distinguishes an -unsuccessful or truncated Git registration inspection from confirmed absence in -a complete list. Its optional `workspaceValidationInspection*` fields identify -the fixed command `worktree_list`, failure (`spawn_failed`, `nonzero_exit`, or -`output_truncated`), an allowlisted OS error code (or `unknown`), and an exit code -from 1 through 255. No paths, repository or branch names, IDs, command output, or -arbitrary messages enter these fields. Validation still blocks reuse; it does -not repair Git metadata, change the selected repository, or retry the task. - -For explicit reuse of a retained Git workspace, `persisted_workspace_source_conflict` -uses the same two fields with the fixed reason codes `source_scope_mismatch`, -`explicit_project_workspace_conflict`, `source_path_unproven`, -`source_registration_unproven`, `source_repository_mismatch`, or -`source_repository_unavailable`. These distinguish an unverified original source -from a missing Git registration. Paths, repository URLs, and workspace IDs stay -out of the diagnostic fields. The task remains blocked until its original source -is available or the owner intentionally selects a different workspace. A failed -Git registration probe retains `git_inspection_failed` and the same bounded -inspection fields, including when it occurs during original-source selection. - -When available, the saved `workspaceRestoreDiagnostic` adds the bounded fields -`workspaceRestorePhase`, `workspaceRestoreStep`, `workspaceRestoreErrorCode`, -`workspaceRestoreHttpStatus`, and `workspaceRestoreExitCode` to `run_execution`. -The phase is `workspace` or `asset`. The failing step is one of `git_export`, -`git_import`, `workspace_transfer`, `workspace_extract`, `directory_merge`, -`git_integration`, `index_reset`, `git_ref_cleanup`, or `asset_restore`. -Nested steps retain the most specific failing operation. Error codes come from -the restore diagnostic allowlist, with unrecognized codes reported as `unknown`; -HTTP statuses are integers from 400 through 599 and process exit codes are -integers from 1 through 255. These fields accompany a known restore failure code -only. They omit error messages, raw command lines, paths, process output, and arbitrary -cause data. Git error wrappers preserve only these safe codes and numbers for -diagnostics, without adding the original error as a cause. -Native sandbox `environmentSyncOut` failures carry the same allowlisted codes -and bounded HTTP/exit statuses across the plugin worker RPC boundary. The host -revalidates that optional envelope and retains it only for restore diagnostics. -The envelope excludes provider messages, response bodies, names, paths, and -credentials. The existing RPC error message and code remain unchanged, as do -restore classification, retries, and source retention. Older workers without the -envelope still report `unknown` when no structured cause is available. -For native transfers, optional `workspaceRestoreTransferStep` identifies -`sandbox_access`, `sandbox_guard`, `file_download`, `file_finalize`, -`archive_create`, `archive_download`, `archive_validate`, or `archive_extract`. -`workspaceRestoreTransferFailureKind` distinguishes a producer-confirmed -`command_failed`, `download_failed`, `download_missing`, `unsafe_archive`, -`listing_timeout`, `listing_entry_limit`, `listing_byte_limit`, -`listing_line_limit`, or `listing_stderr_limit`. These labels are fixed values, -not classifications inferred from provider message text. Missing labels remain -absent. A listing deadline records `ETIMEDOUT`; sandbox and listing commands -retain bounded nonzero exit codes even when their error text is wrapped. -`workspaceRestoreRpcCode` retains only known numeric plugin RPC error codes from -a typed error at the host's sync-out boundary. In particular, RPC `TIMEOUT` -(`-32003`) is separate from the model execution's `timedOut` value; successful -model execution does not exclude a later transfer timeout. Transfer evidence is -isolated per outbound request and per restore settlement, then independently -revalidated before persistence and Sentry projection. These fields only accompany -`workspace_transfer` or `asset_restore` diagnostics and do not authorize cleanup -or retries. Older workers remain compatible. -For `git_integration`, optional `workspaceRestoreGitCommand` identifies the fixed -command family: `rev_parse`, `symbolic_ref`, `merge_base`, `merge_tree`, -`commit_tree`, `update_ref`, or `log`. `workspaceRestoreGitFailureKind` is -`merge_conflict`, `invalid_object`, `ref_conflict`, `permission_denied`, or -`unknown`. A merge conflict requires an uninterrupted `merge-tree --write-tree` -exit of 1 with a completed tree ID in stdout; exit 1 alone is ambiguous. -Object and ref classifications require recognized Git diagnostics; -permission denial requires an OS `EACCES` or `EPERM` code. Unrecognized or -localized messages remain `unknown`. Up to 16 KiB of stderr is inspected only -in memory; no arguments, stderr, paths, repository URLs, filenames, or ref names -enter these fields. Handled probes and successful retries emit no diagnostic. -This does not change -restore behavior, retries, timeouts, or recovery policy. - -A caught directory-merge lock timeout also records `restoreLockOwnerState` -(`alive`, `dead`, `unknown`, `missing`, or `invalid`), `restoreLockKnownLocalHolder`, -and, when available, `restoreLockOwnerSameProcess`, `restoreLockOwnerPredatesProcess`, -`restoreLockOwnerAgeMs`, and `restoreLockWaitMs` in `run_execution`. Ages are capped -at seven days. These fields omit paths, PIDs, owner records, and absolute timestamps. -The local-holder flag covers this module's active acquisitions only. Process-age -comparison uses the wall clock and a one-second margin; it is a clue to PID reuse, -not proof of ownership or permission to remove a lock. Diagnostic reads can race -with release. The extra diagnostic owner read has a 100 ms budget; a stalled or -unreadable read leaves the owner state `unknown`, while malformed JSON is `invalid`. -These fields do not change lock acquisition, reclamation, or retries. -Agent-directory callers also supply `restoreLockOperation`: `agent_directory_release`, -`agent_directory_collect`, `agent_directory_checkpoint`, or `agent_directory_handoff`. -This identifies the operation waiting for the lock, including cleanup after a -completed adapter turn when the recorded execution stage has not advanced. - -The execution and setup catch paths pass the original exception to the reporter. -It snapshots and rebuilds only these selected fields and the original message and -stack. Sentry receives the sanitized cause chain rather than a stack created at -the reporting call. Saved adapter results use an available adapter stack preview; -without one, the report has no synthetic reporting stack. - -Credential patterns, the current user's home path, registered run-secret values, -and known host/runtime environment credentials are removed before truncation. -Environment values stay private unless their names and values identify an ordinary -process setting. Flags and counts require both a setting-name match and a boolean -or numeric value. Mode labels use a closed value list. Paths, regions, and key -selectors such as `SORT_KEY` use explicit ordinary-setting names. Unknown opaque -values remain private, including credentials under arbitrary names. Declared -secret bindings and recognizable credential contents override ordinary-setting -exemptions, including short values. Runtime values are used only for redaction -and are never copied into an event. Stack fields are limited to 8,192 characters, -exception messages to 2,048, provider titles to 4,096, and provider details to -12,288. Other diagnostic strings are limited to 200 characters (adapter cause -messages: 2,048). Truncation is marked in the text and in -`run_execution.truncatedFields`; cyclic and deeper cause chains are marked too. -Request/response objects, headers, environment/configuration, prompts, stdout, -stderr, and arbitrary adapter result fields are not copied. The existing DSN -opt-in gate and error-code/adapter fingerprint remain unchanged. These reports -cannot recover diagnostic data that a provider or adapter discarded upstream. +In `unexpected` mode, some failures that the task already shows to its owner +stay in the run log and the task's blocked state instead of reporting. Examples +include known missing-secret configuration blockers, some provider quota and +rate-limit failures, recognized external connection failures, and a scheduled +Codex capacity retry. Most exclusions have conditions, so read +`server/src/services/run-failure-report.ts` for the full policy. `all` mode +reports these failures. +Other run failures attach bounded diagnostic contexts. Their fields are defined +in `server/src/sentry.ts` and pass through the existing secret redaction and size +limits. They can include selected provider error titles and details, but not raw +request or response objects, prompts, message bodies, or credentials. ### Browser data @@ -1661,7 +484,9 @@ log line and keep running with no error monitoring. ### Default capture set The lists below name every event and every context field this feature -sends, so an operator can read what the feature does before turning it on. +sends, so an operator can read what the feature does before turning it on. The +diagnostic contexts on run failure events are the exception: they are defined in +`server/src/sentry.ts`, as described under "Run failure context". Each Sentry integration name below is verified against the default integration list of `@sentry/node@10.71.0` and `@sentry/browser@10.71.0`. @@ -1806,508 +631,3 @@ Two controls belong to the operator. This feature ships neither one. events from the operator's network, not from the server's network, so an internal-only host name fails silently for the browser even when it works for the server. - -## Sandbox Startup Trace Spans - -Paperclip opens OpenTelemetry spans on the sandbox start path. These spans are -an Observability surface. They are not Paperclip Telemetry events. The -generated telemetry contract does not cover them, so this section is their -canonical contract. - -The spans are opt-in. Paperclip exports them only when an OTLP endpoint is -configured. With no endpoint the whole span path is a no-op. Paperclip opens the -spans only for a run that targets a remote sandbox. A local run and an SSH run -stay out of these spans. - -Every span attribute uses the closed `paperclip.sandbox.startup.` prefix and -rides a fixed allowlist. A command line, an argument, an environment value, a -file path, program output, or a raw identifier never rides a span. It rides -neither as an attribute nor as an event. The producer bounds each free-form -value: - -- A command basename maps to a small known set. Any other value maps to `other`. -- A region maps to a small known set. Any other value maps to `unknown`. -- An image id, a sandbox id, and a lease id ride only as a non-reversible short - hash. - -Each numeric attribute is finite. Paperclip omits an attribute when its value is -absent, never a misleading `0`. - -### Spans - -| Span | Scope | Parent | -| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -| `sandbox.startup` | The one root span for a sandbox bring-up. | none (root) | -| `workspace.resolve` | Workspace resolution step. | `sandbox.startup` | -| `codex-home.seed` | Managed-home seed step. | `sandbox.startup` | -| `skills.reconcile` | Skills reconcile step. | `sandbox.startup` | -| `stage.sync` | Workspace stage-sync step. | `sandbox.startup` | -| `snapshot.git` | Host-side git workspace enumeration inside `stage.sync` (`git status --ignored`, the HEAD diffs, `ls-files`). | `stage.sync` | -| `snapshot.baseline` | Host-side baseline workspace content-hash walk inside `stage.sync`, kept for restore. | `stage.sync` | -| `stage.workspace` | One inbound workspace stage task inside `stage.sync`. It packs and uploads the workspace. | `stage.sync` | -| `stage.asset.` | One inbound asset stage task inside `stage.sync`. It packs and uploads one managed-home asset. The `` segment is the asset key. | `stage.sync` | -| `stage.project.` | One inbound referenced-project stage task inside `stage.sync`. It uploads one referenced project. The `` segment is the project id. | `stage.sync` | -| `pack` | Host-side workspace tarball build inside the `stage.workspace` task. | `stage.workspace` | -| `bridge.paperclip` | Paperclip bridge start step. | `sandbox.startup` | -| `bridge.process-session` | Process-session bridge start step. | `sandbox.startup` | -| `acp.handshake` | ACP session handshake step. | `sandbox.startup` | -| `sandbox.syncBack` | The settlement sync-back that restores the managed home at teardown. | the active run span | -| `restore.workspace` | One outbound workspace restore task at teardown. It reads the sandbox workspace back and merges it into the host workspace. | `sandbox.syncBack` | -| `restore.asset.` | One outbound asset restore task at teardown. It reads one asset back to its host store. The `` segment is the asset key. | `sandbox.syncBack` | -| `sandbox.agentSession.sendInput` | One outbound ACP message to the agent — the socket handler's one `writeTextFile` exec. | the active run span | -| `sandbox.agentSession.pollOutput` | One 100 ms poll tick — `list`, then `read`+`remove` per file found (`1 + 2n` execs). | the active run span | -| `sandbox.callbackBridge.relayRequest` | One Paperclip-API callback request — read the request, write the response, remove it. | the active run span | -| `sandbox.agentProcess` | The persistent streamed agent process the process-session bridge launches; open until the process settles or the bridge tears down, whichever comes first. | the active run span | -| `sandbox.exec` | One host-to-sandbox execution. | the active step or wrapper span | - -A step span name is the step name. The `sandbox.exec` span parents to the step -span that runs the execution, so each execution nests under its step. Within -`stage.sync`, the host-side sub-steps `snapshot.git` and `snapshot.baseline` open -as child spans of the step, so the host work at the head of the step is -attributed rather than showing as a gap. Each inbound sync operation also opens -its own task span under `stage.sync`: `stage.workspace`, one `stage.asset.` -per asset, and one `stage.project.` per referenced project. The `pack` span -nests under `stage.workspace`, because the host builds the tarball inside that -task. Two concurrent tasks produce overlapping spans. - -The settlement `sandbox.syncBack` span runs at teardown and parents to the run -span. It wraps the managed-home restore. Each outbound restore operation opens -its own task span under `sandbox.syncBack`: `restore.workspace` and one -`restore.asset.` per asset. Two concurrent restore tasks produce overlapping -spans. A run-time -`sandbox.exec` span parents instead to the run-time wrapper span that runs it -(`sandbox.agentSession.sendInput`, `sandbox.agentSession.pollOutput`, -`sandbox.callbackBridge.relayRequest`, or `sandbox.agentProcess`). Each run-time -wrapper span parents to the live run span (`agent.turn` during the turn, -`task.provider_session` otherwise). With no active trace context the exec span opens -unparented. - -`sandbox.agentProcess` wraps the persistent streamed agent process. The -process-session bridge launches it during `bridge.process-session`, so it opens -under `task.provider_session` — no turn has started yet. It therefore overlaps the sibling -`agent.turn` rather than nesting under it or dangling off the short-lived bring-up -step. The span ends when the process settles or when the bridge tears down, -whichever comes first. The bridge tears down before the run root span ends, so -the span never outlives `task.provider_session` even when the process lingers past teardown -(the sandbox `execute` has no cancel, so a lingering process cannot be forced to -resolve). - -The root span sets the error status when the bring-up fails. Each step span sets -the error status when its step fails. The `sandbox.exec` span sets the error -status when the exit code is non-zero or the execution throws. - -### Outcome values - -The `paperclip.sandbox.startup.outcome` attribute uses a closed value set: - -- `ok` — the step or the execution settled with a success result. -- `skipped` — a warm cache skipped the step; the step ran no work. -- `failed` — the step or the execution threw, or the exit code was non-zero. - -### Root span attributes - -The `sandbox.startup` root span uses this closed attribute allowlist. - -| Attribute | Type | Optional | Meaning | -| ---------------------------------------- | ------- | -------- | ---------------------------------------------------------- | -| `paperclip.sandbox.startup.root.wall_ms` | number | no | The root-span wall time of the whole bring-up. | -| `paperclip.sandbox.startup.root.work_ms` | number | no | The sum of the step wall times. | -| `paperclip.sandbox.startup.root.diff_ms` | number | no | `work_ms − wall_ms`; the overlap the parallel steps saved. | -| `paperclip.sandbox.startup.provider` | string | yes | The normalized provider family. | -| `paperclip.sandbox.startup.cold_start` | boolean | yes | Legacy value, set only when receipts establish cold or warm startup. | -| `paperclip.sandbox.startup.warmth` | string | yes | Receipt-derived `cold`, `warm`, `partial_reuse`, or `unknown`. | -| `paperclip.sandbox.startup.region` | string | yes | The clamped region label. | -| `paperclip.sandbox.startup.image_id` | string | yes | The hashed image id. | -| `paperclip.sandbox.startup.sandbox_id` | string | yes | The hashed sandbox id. | -| `paperclip.sandbox.startup.lease_id` | string | yes | The hashed lease id. | - -### Step span attributes - -The root's warmth uses the per-layer receipts documented in -[run-log-events.md](./run-log-events.md#startup-reuse-evidence). Partial and -unknown evidence omit the legacy `cold_start` boolean. A reused session ID or -runtime object alone cannot establish warmth. These attributes retain the -operator OTLP endpoint gate and are no-operations without that endpoint. - -Each bring-up step span uses this closed attribute allowlist. The step name -rides the span name, so no `step` attribute repeats it. - -| Attribute | Type | Optional | Meaning | -| ------------------------------------------------------------ | ------ | -------- | -------------------------------------------------------- | -| `paperclip.sandbox.startup.step.wall_ms` | number | no | The wall time of the step. | -| `paperclip.sandbox.startup.outcome` | string | no | The step outcome (`ok`, `skipped`, or `failed`). | -| `paperclip.sandbox.startup.provider` | string | yes | The normalized provider family. | -| `paperclip.sandbox.startup.batch` | string | yes | A shared tag that marks two parallel steps as one batch. | -| `paperclip.sandbox.startup.handshake.create_runtime.wall_ms` | number | yes | The create-runtime sub-time of the `acp.handshake` step. | -| `paperclip.sandbox.startup.handshake.ensure_session.wall_ms` | number | yes | The ensure-session sub-time of the `acp.handshake` step. | - -The round-trip count and the provider durations no longer ride a step span. The -per-execution `sandbox.exec` child spans carry that detail. - -### `sandbox.exec` span attributes - -The `sandbox.exec` span uses this closed attribute allowlist. Paperclip omits a -numeric attribute when the provider does not report the value. - -| Attribute | Type | Optional | Meaning | -| ----------------------------------------------- | ------- | -------- | -------------------------------------------------------------------------- | -| `paperclip.sandbox.startup.provider` | string | no | The normalized provider family. | -| `paperclip.sandbox.startup.exec.command` | string | no | The clamped `argv[0]` command label. | -| `paperclip.sandbox.startup.exec.exit_code` | number | yes | The numeric process exit code. | -| `paperclip.sandbox.startup.exec.wall_ms` | number | no | The host-measured wall time of the execution. | -| `paperclip.sandbox.startup.exec.wait_before_ms` | number | yes | The provider handle-fetch wait before the execution ran. | -| `paperclip.sandbox.startup.exec.sandbox_ms` | number | yes | The in-sandbox run time of the execution. | -| `paperclip.sandbox.startup.exec.network_ms` | number | yes | The transport time the host adds; `wall_ms − wait_before_ms − sandbox_ms`. | -| `paperclip.sandbox.startup.exec.critical_path` | boolean | no | Whether the execution sits on the startup critical path. | -| `paperclip.sandbox.startup.exec.cache_hit` | boolean | yes | Whether the provider served the sandbox handle from its warm cache. | -| `paperclip.sandbox.startup.outcome` | string | no | The execution outcome (`ok` or `failed`). | - -The plugin decides the cache hit at the sandbox-handle lookup. The span no -longer infers a cache hit from `wait_before_ms == 0`. Paperclip omits the -`cache_hit` attribute when the provider does not report the value. - -To add a span attribute, extend the `SANDBOX_STARTUP_SPAN_ATTRS` allowlist in -the code first. Keep the attribute low-cardinality and free of user content. - -### Provider spans - -A sandbox provider plugin also opens spans for its own sync steps. These spans -use the `sandbox.daytona.` name prefix. They share the -`paperclip.sandbox.startup.` attribute prefix and obey the same opt-in and -no-user-content rules as the startup spans above. - -The plugin worker runs in a separate process from the host. So the host treats -every field of a worker-sent span as untrusted input. The host re-clamps the -span name and every attribute at one boundary, the `span.record` host handler, -before it records the span. - -| Span | Scope | Parent | -| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- | -| `sandbox.daytona.pack` | The host-local pack step that builds the upload tarball. It makes no sandbox round trip. | the active startup step span | -| `sandbox.daytona.transfer` | The transfer step: an upload to the sandbox (inbound) or a download from the sandbox (outbound). The `paperclip.sandbox.startup.transfer.direction` attribute records the direction. | the active sync task span (`stage.*` inbound, `restore.*` under `sandbox.syncBack` outbound) | -| `sandbox.daytona.ensureDirectory` | The `mkdir -p` step that ensures a directory exists before a write. | the active startup step span | -| `sandbox.daytona.checkSymlinkEscape` | The re-check step that a path resolves inside the workspace root before use. | the active startup step span | -| `sandbox.daytona.promote` | The atomic move of a staged temp onto its target via a pinned dir handle. | the active startup step span | -| `sandbox.daytona.extractTarball` | The one round trip that re-checks the path, runs `tar -xf`, and removes the scratch tarball. | the active startup step span | -| `sandbox.daytona.postUploadCommand` | One caller-supplied post-upload command. | the active startup step span | -| `sandbox.daytona.session.open` | The create of the one persistent session for a lease, on the first in-run command. | the active run span | -| `sandbox.daytona.session.close` | The delete of that persistent session on lease release. | the active run span | -| `sandbox.daytona.other` | Any span name outside the known set. | the active startup step span | - -The host clamps the span name to the closed set of leaf names above (`pack`, -`transfer`, `ensureDirectory`, `checkSymlinkEscape`, `promote`, `extractTarball`, -`postUploadCommand`, `session.open`, and `session.close`). The host maps a known -name to `sandbox.daytona.`. The host maps any other value to -`sandbox.daytona.other`, so a span name never carries free-form data. Only the -daytona provider emits these spans today, so the segment is the literal -`daytona`. - -### Daytona lease acquisition and resume - -The worker invocation carries nested, monotonic timing receipts for lease work. -The host also admits the following fixed `lease.*` names and prefixes them with -`sandbox.daytona.`. These use the existing opt-in endpoint and host-owned parent -context; they do not create an exporter or first-party Telemetry events. - -```text -execution.plugin_dispatch -└── plugin.worker - ├── sandbox.daytona.lease.wait_for_teardown (only when teardown blocks resume) - ├── sandbox.daytona.lease.lookup - ├── sandbox.daytona.lease.refresh (missing-container confirmation) - ├── sandbox.daytona.lease.channel_cleanup (before restart) - ├── sandbox.daytona.lease.wait_transition (only while the sandbox is changing state) - │ └── sandbox.daytona.lease.force_stop (only when `stopping` outlasts 30 s) - ├── sandbox.daytona.lease.start (or lease.recover) - └── sandbox.daytona.lease.verify - ├── sandbox.daytona.lease.workspace - ├── sandbox.daytona.lease.sentinel - └── sandbox.daytona.lease.shell -``` - -`lease.lookup` includes cached-handle lookup and any required provider refresh. -`lease.start` and `lease.recover` measure the actual SDK operation, including its -internal readiness wait. They also cover starts triggered by execution or sync. -They do not separate SDK-internal requests or provider-side queue time. -Their `paperclip.sandbox.startup.state` attribute records the state before the -call: `started`, `stopped`, `archived`, `error`, a transition (`starting`, -`stopping`, `restoring`, `archiving`, `resizing`), or `other`. Both the plugin and -host restrict this value; no provider error text or resource identity is sent. -`lease.wait_transition` covers polling a sandbox that is changing state before a -start; its state attribute is the state it found. A start that finds the sandbox -`stopping` for more than 30 s forces the stop (`lease.force_stop`) and keeps -waiting within the same start deadline if Daytona refuses. The forced stop belongs -to the sandbox: parallel callers send one, and none of them starts the sandbox -until that request settles. A confirmed start ends that stuck stop, so a later -one is forced again. - -Fresh acquisition emits `lease.create`, `lease.workspace`, `lease.shell`, -`lease.expiry`, and `lease.sentinel`. `lease.create` covers the existing creation -helper, including qualification-only snapshot resolution and creation-failure -cleanup. Setup-failure deletion is a separate `lease.cleanup` sibling, so it -does not inherit a failed workspace or verification phase. Existing deadlines, -ownership, cleanup and retry behavior are unchanged. Failed awaited steps close -with error status; the receipt contains no exception message. - -Children nest beneath the current `plugin.worker` receipt and verification -children nest beneath `lease.verify`. Never add parent and child durations. -Receipt budgets and clock validation still apply. Older workers without -`tracer.withSpan` keep the original behavior without these detail spans. Tracing -failures preserve the operation's result or error and never repeat it. - -The `sandbox.daytona.*` spans use this closed attribute allowlist. The host -drops every other key, so a command, an argument, a path, an id, a standard -output, or a standard error never rides a provider span. The host records only -the attributes that the producer sends for one span. - -| Attribute | Type | Optional | Meaning | -| ------------------------------------------------ | ------ | -------- | --------------------------------------------------------------------------------------------------------- | -| `paperclip.sandbox.startup.provider` | string | no | The normalized provider family. | -| `paperclip.sandbox.startup.state` | string | yes | State before start/recovery: `started`, `stopped`, `archived`, `error`, or `other`. | -| `paperclip.sandbox.startup.outcome` | string | yes | The step outcome (`ok`, `skipped`, or `failed`). | -| `paperclip.sandbox.startup.pack.wall_ms` | number | yes | The host-local wall time of the pack step. It rides the `sandbox.daytona.pack` span. | -| `paperclip.sandbox.startup.transfer.wall_ms` | number | yes | The wall time of the transfer step. It rides the `sandbox.daytona.transfer` span. | -| `paperclip.sandbox.startup.transfer.guard.count` | number | yes | The number of serial guard round trips before one transfer. It rides the `sandbox.daytona.transfer` span. | -| `paperclip.sandbox.startup.transfer.direction` | string | yes | The transfer direction (`inbound` or `outbound`). It rides the `sandbox.daytona.transfer` span. | - -The `span.record` host handler enforces the allowlist. It re-maps `provider` -through the provider-family normalizer. It keeps `outcome` only when the value -is `ok`, `skipped`, or `failed`. It keeps `transfer.direction` only when the -value is `inbound` or `outbound`. It keeps a numeric attribute only when the -value is a finite number. It drops a status message and keeps only the numeric -status code. The handler never throws, because observability must not change the -sync control flow. - -The `span.record` host method needs the `environment.drivers.register` -capability. So only a plugin that registers an environment driver may emit a -provider span. The capability gate rejects a provider span from any other -plugin. - -The host parents each provider span to the active sync task span. An inbound -transfer runs inside a `stage.*` task span, so its provider spans parent there. -An outbound transfer runs inside a `restore.*` task span under `sandbox.syncBack` -at teardown, so its provider spans parent there. The host mints a W3C -`traceparent` from the active task span and passes it to the plugin worker on the -per-call invocation channel. The teardown restore runs inside the run-parented -`sandbox.syncBack` span, so the host mints a `traceparent` for an outbound -provider span the same way it does for an inbound one. The worker tags its span with the -`traceparent` and treats the value as opaque. The worker never derives the -parent from it. The host recovers the `traceparent` from its own invocation -record, so a worker can never forge a parent. The host validates the -`traceparent` and rejects a missing or malformed value. With no active host -trace context the worker sends no span, so the whole provider-span path is a -no-op. - -## Sandbox Duplex Transport Instrumentation - -This section documents one duplex transport with three sinks: an -OpenTelemetry span, a counter in the `tool_runtime_metric_counters` table, and -one run-log event. - -Paperclip opens a fixed observability surface for the sandbox duplex transport. -This instrumentation is separate from Paperclip Telemetry events and from the -sandbox startup trace spans above. The generated telemetry contract does not -cover it, so this section is its canonical contract. The code owner is -`packages/adapter-utils/src/duplex-observability.ts`. That module holds each name and -each enum value as a literal constant, so the surface never drifts. - -The surface is opt-in. The host injects a recorder that binds the span to the -OTel tracer, the counter to the guarded counter store in -`server/src/services/tool-runtime-metrics.ts`, and the event to the run-events -bridge. The default recorder is a no-op, so the whole surface stays inert until -the host binds a real recorder. Every recorder call sits inside an error swallow, -so a telemetry failure never breaks the request path. - -The surface carries no user content. No route, no query, no request body, no -token, and no raw identifier rides a span, a counter, or an event. Each record -carries only the closed dimension keys below and, for the request span, a -latency. The `provider` dimension carries only the allowlisted public value -`daytona`. Any other plugin key maps to `other` before the record reaches a sink, -so a raw plugin key never reaches a span attribute, a counter label, or an event -field. - -### Spans - -| Span | Scope | Latency | -| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------ | -| `sandbox.duplex.channel_open` | One duplex channel-open attempt. The `outcome` dimension is `ok` when the channel opened and readiness passed, or `error` when the open or readiness failed. | none | -| `sandbox.duplex.request` | One duplex request the broker forwarded to the host. | The request latency in milliseconds. | - -### Event - -| Event | Scope | -| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `sandbox.duplex.transport` | The host emits it at each transport boundary: a ready duplex channel, a fallback to the file bridge, and a terminal channel loss. Its dimensions record the boundary. | - -### Counters - -| Counter | Scope | -| ----------------------------------- | ----------------------------------------------------------------------------------- | -| `sandbox_duplex_channel_open_total` | One successful duplex channel open. | -| `sandbox_duplex_fallback_total` | One fallback to the file bridge. The `fallback_reason` dimension records the cause. | -| `sandbox_duplex_loss_total` | One terminal duplex channel loss. The `loss_class` dimension records the phase. | -| `sandbox_duplex_session_leak_total` | One leaked provider session at teardown. | - -### Dimension keys - -Counters carry no dimension labels. The guarded counter store keys each counter -on `(companyId, metric)` with no label column, so the `fallback_reason` and -`loss_class` values fold into the counter metric name instead. The full closed -dimension set below rides only the spans and the `sandbox.duplex.transport` -event, which use only these closed keys. A test asserts the exact set, so a new -key never reaches a sink by accident. - -| Key | Type | Optional | Value set | -| --- | --- | --- | --- | -| `provider` | string | no | `daytona`, or `other` for any other plugin key. | -| `transport` | string | no | `duplex`, `http2`, or `file`. `duplex` names the retired bespoke frame protocol; `http2` names the Node HTTP/2 session over the sandbox channel; a fallback record uses `file`. | -| `outcome` | string | yes | `ok` or `error`. | -| `fallback_reason` | string | yes | `gate_off`, `capability_absent`, `route_busy`, `entrypoint_sync_failed`, `broker_construction_failed`, `channel_open_failed`, `ready_invalid`, `ready_nonce_mismatch`, `ready_timeout`, `contaminated`, or `preface_missing`. It rides only a fallback record. `route_busy` marks the process-scoped route ceiling full. `entrypoint_sync_failed` and `broker_construction_failed` mark the named build step. `channel_open_failed` marks a failed channel open. `preface_missing` marks a missing or an invalid HTTP/2 client connection preface inside the bounded readiness buffer: the host found no valid preface after the accepted READY line, aborted the `http2` open, and moved the run to the file bridge (`queue_v1`) one time. | -| `loss_class` | string | yes | `pre_dispatch` or `post_dispatch`, relative to the first request dispatch. It rides only a loss record. | -| `loss_reason` | string | yes | `stdin_eof`, `provider_exit`, `heartbeat_timeout`, `rpc_failure`, `write_error`, `transport_closed`, or `other`. The host maps every loss cause to one of these values, so no raw provider text reaches a sink. `write_error` marks a rejected host-to-sandbox write. `transport_closed` marks a reason-less provider transport close with no exit data. It rides only a loss record. | - -To add a name or an enum value, extend the literal constant in -`duplex-observability.ts` first, then update the test that asserts the closed set. - -### Known behavior: aggregate retained body bytes - -Each HTTP/2 bridge route holds up to 168,820,736 bytes (161 MiB) at its own -peak (see `HTTP2_BRIDGE_MAX_CONCURRENT_STREAMS` in `http2-bridge-server.ts`). -The host process admits up to 128 concurrent routes (see -`DEFAULT_MAX_CONCURRENT_DUPLEX_ROUTES` in `plugin-worker-manager.ts`). Those -two figures alone would let the process retain up to 21,609,054,208 bytes -(about 20.1 GiB) of body data across every route at the same time. - -The process does not reach that figure, on two levels. -`HTTP2_BRIDGE_MAX_PROCESS_BODY_BYTES` (`http2-bridge-server.ts`) enforces a -real, live ledger: 1,073,741,824 bytes (1 GiB) across every route, not merely -an accepted paper ceiling. Every HTTP/2 stream creates one `BridgeBodyReservation` owner over -its lifetime, and every source-level full-body buffer that stream retains — -its request-body chunk array, the concatenated request body, the -response-body chunk array, and the concatenated response body — reserves -against that one owner before it allocates. A reservation that would pass the -process total is denied before it copies anything, and the host answers 503 -instead of accepting the body. The reservation stays live for the response -body until the HTTP/2 write actually finishes flowing to the peer or the -stream closes, not merely until the write call returns, so a slow or -backpressured peer cannot hold response bytes in memory the ledger no longer -counts. - -`HTTP2_BRIDGE_MAX_ROUTE_BODY_BYTES` adds a second, per-route ledger on top of -that process-wide one: each route's own reservations also check a ceiling -scoped to that one route (its own 168,820,736-byte peak from above), so one -busy or malicious route can pass its own ceiling and get denied with a 503, -but it can never spend the whole process-wide total and deny every sibling -route admission. This accounting covers source-level full-body buffers only: -internal Node.js and Undici copies (socket buffers, HTTP/2 frame buffers, -decompression buffers) stay outside it. - -The generated gateway process inside the sandbox (`getSandboxCallbackBridgeServerSource` -in `sandbox-callback-bridge.ts`) enforces its own separate ledger, independent -of the two host-side ledgers above: each side bounds only the memory in its -own process. `readBodyBytes` reserves a request body's chunk bytes as they -arrive, then reserves the concatenated buffer's own byte count before -`Buffer.concat` allocates it, against a ceiling of `maxBodyBytes * 8` (4 -concurrent bodies, each counted twice for its two live copies). A denied -reservation answers 503 with no forward call. Each request handler releases -its own reservation once the whole request settles: a completed response, a -thrown error, a client abort, or a deadline timeout all reach the same -release call. - -Keep every dimension low-cardinality and free of user content. - -### Shared skill preparation - -`skills.prepare` measures the shared inventory listing and runtime materialization -inside `task.prepare`. It is also contained in the broader -`heartbeat.prepare_before_environment` interval; do not add those two durations. -Preparation failures emit a failed span even when no native session starts. -It carries no skill contents, identifiers, locations, or credentials. It uses the -existing run performance events and operator-configured OpenTelemetry endpoint; -no first-party Telemetry event is added. - -The `skills.*` detail spans above distinguish inventory reconciliation and lock -acquisition from repository transfer and file validation. A repository-backed -skill's authored `SKILL.md` is not its complete runtime payload: the generated -discovery entrypoint includes the pinned repository under `.paperclip-repository`. -Measure the delivered bundle's file count and bytes when reproducing its cost. - -Runtime preparation refreshes the company inventory once per listing. Local and -catalog directories remain direct sources, so edits are visible on the next -preparation. Explicit version selections still use their stored snapshots. - -Reconstructed skills use `__runtime_cache_v1__///files` -beneath company skill storage, with a sibling manifest of paths, sizes, and SHA-256 -content digests. Every warm hit validates the manifest and exact file contents; -it does not fetch upstream, rewrite files, or remove directories. The fingerprint -includes installed source identity, revision, file inventory, and stored Markdown, -and excludes display names, stars, and general update timestamps. Manifests stay -outside the directory delivered to agents. - -GitHub and skills.sh imports are cached only when pinned to a full commit SHA. -Remote freshness is explicit: update or reimport selects a new revision, including -supporting-file-only changes. A branch advancing upstream does not change an -installed revision. Legacy mutable refs retain uncached behavior until updated. -URL-only skills use stored Markdown. An unavailable new revision reports missing; -it never silently reuses an older revision. Stored `SKILL.md` remains a fallback, -but missing supporting files prevent publication of a reusable partial cache. - -Builds publish read-only files and directories from unique staging directories. -A skill-scoped lock serializes builds and cleanup across processes. Cold builders -recheck that the skill still exists under its original key before reading files -and before atomic publication. Existing valid -revisions stay readable during updates. Invalid entries are quarantined in the -same skill cache root for inspection; rename/removal cleans up that skill's cache. -Read-only listings validate caches without downloading or repairing them. A -publication lock left by an abruptly terminated process is reported for operator -cleanup; remove it only after confirming its recorded PID is no longer running. - -Run `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-skill-preparation.ts` for an isolated embedded -PostgreSQL benchmark with 114 mixed skills and at least 400 remote files. It -reports one cold sample and ten warm samples (one in a new process), refresh and -fetch counts, rebuilds, missing entries, and content checks. Upstream responses are -deterministic fixtures; use real deployed run spans for user-facing latency. - -## Invocation and native turn attribution (v1) - -The existing opt-in OTLP endpoint gate also controls invocation timing. No new -exporter is installed. Generic plugin timing uses `span.record`, still gated by -`environment.drivers.register` or `workspaces.manage`, and the host-owned invocation ID. The host clamps -names, attributes, status and timestamps again. A worker cannot choose a trace -parent. Existing provider `startSpan` calls are retained as children of the -worker receipt. `ctx.tracer.withSpan` supplies async-local nesting; it is optional -for compatibility with older SDK fixtures. The host generates each child span's -identity. Receipts share one invocation-wide budget of 256 nodes and 12 levels. The worker root supports up to 24 hours; short children keep their widths on long execute calls. Nested timestamps share one monotonic origin. Missing, invalid, -expired and cross-invocation context cannot select another call's parent. - -| Boundary | Coverage | Owner and clock | Meaning / limit | -| --- | --- | --- | --- | -| Dispatch / receipt / return | `execution.plugin_dispatch` → `plugin.worker` | Host invocation; worker monotonic durations anchored to its epoch start | Outer minus worker time is an unattributed dispatch/scheduling remainder. It is not network latency. | -| Repeated host reads | `plugin.host.identity.read`, `config.read`, `progress.read`, `progress.write` | Worker invocation, one span per awaited call, bounded by receipt budget | Round trip and host service together. Span count is call count; overlapping reads are not additive. | -| Plugin coordination | `plugin.storage.queue`, `storage.execute`, `runtime.queue`, `runtime.prepare`, `runtime.reconcile`, `runtime.verify`, `workspace.prepare`, `workspace.failure` | Invoking plugin, monotonic durations | The plugin keeps its locking and authorization owners. `plugin.reused` is boolean. `plugin.failure_reason` on `workspace.failure` is a closed workspace operation failure reason or `unknown`. | -| Completed remote lifecycle | `plugin.remote.lifecycle`, linked to the host-owned observer | Bounded prior monotonic durations, up to ten minutes old | Independent lifecycle trace; never a child of a later polling request. The worker cannot supply link IDs. | -| Remote operation receipt | `plugin.remote.request` → `plugin.remote.operation` | Remote monotonic offsets, checked against local round trip and parent bounds | Closed operation classes cover mount refresh, guest setup, process execution, scripts and cleanup. No remote wall-clock subtraction. | -| Retained/cold transport | `runner.transport.attach`, `resume`, `cold_start`, `prepare`, `registration`, `provider_identity` | Controller process, current active context on every operation | A retained transport must not capture the preceding run's trace. These parents overlap their children. | -| Command and provider admission | `runner.transport.turn_start`, `command_ack`, `started_event`; optional ACPX `runner.remote.turn_start` → `runner.sidecar.turn_start` → `status_read`, `prompt_started` | Local monotonic spans; remote numeric durations anchored at receipt | Command ACK proves durable command completion. ACPX `promptStarted` proves the runtime prompt-start barrier, not a model token or provider queue exit. SDK-internal work stays opaque. | -| Durable events | `runner.event.persist` with bounded event kind | Host-local monotonic interval | Receipt through event transaction commit, before live publication. Duplicate receipts are not new provider starts. | -| First event / first text | Existing `provider.time_to_first_agent_event`, `task.time_to_first_token`; `response.first_nonempty_text` | Durable event observations | First event can be a tool; text must be nonempty and pass the existing deliverable-text observer. | -| Completion | `completion.request.first`, existing `tool.request.input_stream`, `completion.tool_accepted`, `completion.result_committed` | Same turn; provider tool identity retained only in memory | Input-stream end is the last observed argument update. `run.result.proposed` is the validated tool receipt; `completion.result_committed` follows the successful result transaction; the earlier `run.result.accepted` event alone does not prove persistence. Neither certifies response publication. | -| Reply commit / publication | Existing response transaction/write/publish phases | Response owner, transaction and local publication | Keep separate from tool acceptance and first text. | -| Input/context | `inputBytes`, `toolSchemaBytes`, `toolCount`, `contextReused`, `tokenDataAvailable` | Controller numeric/boolean metadata | Counts only. No prompts, instructions, tool arguments or credentials. Token/cache counters remain unavailable unless supplied by a provider with known semantics. Model/effort stay in existing effective run settings. | - -Remote receipt spans use their measured duration and causal bounds. Their absolute -placement inside a round trip remains uncertain by transport/scheduling time. -Never add parent and child widths, sum concurrent host reads, or label this -remainder inference or network delay. Failure receipts carry status codes without -exception text. Incomplete or malformed receipts are discarded without affecting -execution. A receipt cap can omit further detail; it does not truncate work. - -The linked private implementation owns its remote stage names and protocol. -Core contains generic operation semantics only. Before using this coverage to -rank optimizations, deploy a compatible source set and inspect actual collector -exports for parentage, concurrent ownership, widths and closed failure spans. -Unit tests do not establish ingestion or a latency improvement. - -The shared ACPX instrumentation does not change any provider profile identity: -Copilot, Grok and Pi digests attest their upstream releases, not Runner source. -Provider packages, models and permission defaults are unchanged. diff --git a/doc/run-log-events.md b/doc/run-log-events.md index b1d45b17acd..76b3f84ff11 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -1,1263 +1,24 @@ # Run-Log Events -Run-log events write to the `heartbeat_run_events` table -(`packages/db/src/schema/heartbeat_run_events.ts:6-20`). They are not -Paperclip Telemetry events, and they are not OpenTelemetry exports. A run-log -event needs no operator endpoint. - -## ACPX sidecar shutdown - -The ACPX sidecar emits `runtime.diagnostic` with code -`sidecar_shutdown_requested` once at the first local shutdown request, before -waiters are removed. Its JSON message records the local reason, pending tool, -input and permission counts, completion-normalization count, and at most 16 -oldest pending tools. Each tool sample contains elapsed milliseconds and a -SHA-256 call ID. Hash the corresponding `runtime.tool_called` call ID to match -it. Arguments, results, operation names and raw call IDs are excluded. -The existing diagnostic path also writes this message to sidecar stderr. -A controller that has already stopped may not ingest the frame. Stdin EOF -identifies a closed controller pipe, not the upstream reason for that closure. -This is local run evidence; no first-party Telemetry event or OpenTelemetry -span is added. Retry, cancellation and authorization behavior stay unchanged. - -## Startup reuse evidence - -`run.startup.reuse` uses schema `paperclip.startup-reuse.v1`. Each receipt names -one layer: `environment` (the lease), `workspace`, `runner`, `provider_process`, -or `provider_session`. Its state is `reused`, `fresh`, `unknown`, or -`not_applicable`. Reasons use a closed set: `verified_reuse`, `created`, -`replacement`, `not_found`, `expired`, `identity_mismatch`, `resume_failed`, -`configuration_changed`, `tools_changed`, `workspace_changed`, `cache_miss`, -`not_applicable`, and `evidence_missing`. No paths, identifiers, configuration -values, or exception messages enter these fields. - -A restart's reattachment to a remote Runner resumes the run's own retained -sandbox lease and never acquires another one. Its `environment` receipt is -`reused` / `verified_reuse`. Earlier releases reported the lease's original -acquisition there, so a reattachment to a sandbox the run created showed -`fresh` / `created` although no sandbox was created. - -Provider-process receipts carry a cumulative `providerLaunchCount` for the run. -`null` means unobserved; zero requires a physical launch observer. Direct ACPX -processes count initial launches and respawns, including launches during retries. -On the remote process-session bridge, ACPX observes the host relay rather than -the sandbox provider. Provider-process reuse and launch counts stay unknown on -that transport. Native Runner session events establish session continuity, but -do not establish provider-process reuse or its launch count. Those values stay -unknown without physical evidence. The final ACPX receipt does not wait for -persistence, so a stalled diagnostic sink cannot hold the staging lease. -The existing successful `runner.process.launch` performance receipt establishes -a fresh Runner process, independently of provider-session continuity. - -The Product E2E result stores `startupReuse` by run, and its dashboard displays -each layer, its reason, and the launch count. `warm` requires all applicable -layers to be reused and zero observed provider launches. `cold` requires all -applicable layers to be fresh. Some reuse with other fresh or missing evidence -is `partial_reuse`; otherwise the label is `unknown`. Fresh decisions dominate -later reuse receipts within a run. Legacy runs without receipts retain unknown -layers and a null launch count. Session IDs and follow-up turns never establish -warmth. These events stay in the local run log; they add no first-party Telemetry. - -## Ordinary event persistence - -Events without a native source identity or retry-exhaustion receipt use one -atomic PostgreSQL statement. The statement checks the stored run's company and -agent, allocates its next sequence, and inserts the event. An insertion failure -also rolls back the sequence allocation. The returned row uses the existing -column decoders, including the lossless payload codec. Callers still wait for -the durable write before they publish or acknowledge the event. Native-source -replay and retry-exhaustion deduplication retain their existing transaction path. - -## Legacy case handoff cleanup - -`legacy.case_handoff_cleanup_intent` records local cleanup ownership before -dispatch, then binds it atomically to the observed process identity on spawn. -It includes the host, controller/run generation, PID/group/start identity, and -owned scratch descriptor or explicit `null`. It does not prove termination. -`legacy.case_handoff_cleanup_verified` records the later stop proof before -scratch removal. Restart recovery rechecks process, controller, workspace and -ownership gates before completing cleanup and releasing the handoff. -These controller receipts are cleanup bookkeeping, not evidence of agent task -progress, and are excluded from run-liveness action counts. -The controller authors both events on the system stream. Adapter ingestion -rejects the reserved `legacy.case_handoff_` namespace. These events stay in the -instance run log and add no first-party Telemetry or OpenTelemetry export. - -## Provider-pack preparation timing - -Every `run.performance.span` payload also carries `wallStartedAtMs`, the span's own -start time in epoch milliseconds (since 2026-11-09). Span rows can be written late -through deferred diagnostics, so readers take a span's start from this field (or -from the trace start plus `startOffsetMs`), never from the row's write time. -The preparation spans of a native run (`heartbeat.queue`, `heartbeat.prepare_*`, -`environment.*`) are always written this way: in the order they ended, while the -provider starts, and before the run's trace finishes. They can appear after the -first Runner events of the run. - -`run.performance.span` also records `task.time_to_first_token` once per native -dispatch at the first newly committed deliverable text: assistant or reasoning -`item.delta`/`item.completed`, a redaction tail released at completion, or an -accepted run-result summary. Its -`durationMs` starts at the earliest accepted input. The accepted comment or -answered question is the start only when its span is the earliest preparation span. -A comment coalesced into an already-queued run starts after run creation, so that -run uses queued run creation. The durable wake request's `requested_at` replaces -the start when it is earlier (deferred, coalesced and retried wakes). Without -preparation history, the start is dispatch and the anchor is `run_created`. It ends at Core commit callback. `anchor` names the start: -`comment`, `question_response`, `wake_request` or `run_created`. `startOffsetMs` is -zero, or negative when a wake request precedes the run trace. `eventKind` is -`agentMessage` or `reasoning`. The wake request time is read after the first text, -in detached diagnostic work bounded to 2 s (a -transaction-local `statement_timeout`, so PostgreSQL cancels a stalled read), so the measurement adds no wait before -`turn.start` and never delays event delivery. The span can appear after later -run-log rows; the trace settles it before `task.provider_session.measured`. It includes preparation and startup, but excludes browser -delivery/rendering. This measures text availability, not an exact model token. -Empty text, item starts, tools, usage, result proposals, and duplicate replay do -not qualify. No deliverable text means no timing sample. A recovered dispatch can -record newly committed output from the original start; it does not reproduce -earlier output timing. The event contains no text or provider identifiers. - -## Speed budget breaches - -`run.performance.budget_exceeded` (schema `paperclip.run-performance-budget.v1`, -level `warn`) records one native run that exceeded its p95 speed budget. The -budgets come from the Phase 0 local baseline and are listed in -`doc/plans/2026-11-07-durable-ownership-and-reconciliation.md` ("Speed budgets"). -`metric` is `time_to_first_activity` (`task.time_to_first_agent_activity`: -the first text delta, tool-call start or reasoning item; named `ttft` and -judged on `task.time_to_first_token` before 2026-11-08), `agent_boot` (end of -`heartbeat.queue` to the end of `runner.turn.submit` or `runner.session.resume`) -or `restart_recovery_control_plane` (startup recovery `ready` to the start of the -provider's saved-session load, `provider.session.load`, or to the recovered run's -first provider event when nothing reloads). That is Paperclip's own share of a -recovery: claim, prepare, runtime stage and runner launch. The full recovery -(`ready` to the first provider event) and the provider's session load grow with -session size and with how many sessions resume at once, so they are reported in -the payload as `restartTotalMs` and `providerLoadMs` and are not judged; events -written before 2026-11-09 judged the full latency as `restart_recovery`. -The payload names `adapter` (`codex`, `claude` or `opencode`), -`environment` (`local`), `startKind` (`cold`, `warm` or `unknown`; an unknown -start uses the looser budget), `measuredMs`, `budgetP50Ms`, `budgetP95Ms`, -`percentile` (`p95`), `baseline`, and, for restart recovery, `disposition`. -For `time_to_first_activity`, `measuredMs` counts from run creation: when the input waited for its -run to exist (for example a comment posted while the previous turn was still -running), that wait is excluded from the judgment and reported as `inputWaitMs`. -Each metric is checked at most once per dispatch. A restart-recovery dispatch is -judged only on `restart_recovery_control_plane`, because its first activity and boot span the outage. Time to first text (`task.time_to_first_token`) is reported without a budget. Remote runs and other adapters have -no budget yet. The event is written in detached diagnostic work after the -measurement, so it adds no wait before `turn.start`. It is a run-log row only -and never goes to Telemetry. - -The existing `run.performance.span` event also records `provider_pack.select`, -`provider_pack.discover`, `provider_pack.verify`, `provider_pack.verify_preinstalled`, -`provider_pack.link_preinstalled`, `provider_pack.clear_stale`, `provider_pack.upload`, -and `provider_pack.verify_uploaded`. Selection records `stateSource` as `staged`, -`preinstalled`, or `uploaded`. Its closed reason is `verified_pack_reused` or -`cached_packs_unverified`. A verification failure describes an unusable candidate; -it does not identify a particular compatibility mismatch or a failed run. -Harness startup also records `harness_state.inspect`, `harness_state.path_check`, -and `harness_state.launch_material` for remote state inspection and fresh launch -material. These events retain the existing schema and carry no paths or exception strings. -They also become native Observability spans only with an operator OTLP endpoint. - -## Local runner startup sub-steps - -`run.performance.span` splits a local Runner startup (`runner.session.bootstrap` or -`runner.session.resume`) into three sequential children of `runner.session.startup`: - -- `runner.runtime.stage`: controller-side launch preparation before the Runner - process exists (runtime context, provider home, launch profiles; on resume, the - durable-state checks and authority rotation as well). -- `runner.process.launch`: from spawning `paperclip-runnerd` until its first - authenticated connection to the PRP control plane. An exact adoption of a live - Runner records no launch, so this span keeps meaning a fresh Runner process - (see startup reuse above). -- `provider.session.load`: from that authentication until the provider session - identity is confirmed. It covers `run.prepare` and `session.open`, or on resume - the `run.attach` that restores the provider and the recovery probe. - -Each carries `mode` (`bootstrap` or `resume`), `target: "local"`, and `outcome` -(`failed` when startup fails inside the step). The Runner transport reports each -milestone synchronously; the controller writes the row as deferred diagnostic -work, so the run-log write never delays `turn.start`. Remote launchers keep their -own `runner.runtime.stage` and `runner.process.launch` spans. These rows stay in -the instance run log; with an operator OTLP endpoint they are also Observability -spans. They are not Telemetry. - -## Native PRP Run-Log Events - -Provider startup command failures and failed provider turns can carry a -`providerFailure` cause with schema `paperclip.provider-failure.v1`. The cause -retains a normalized category, a bounded and redacted provider explanation, the -startup/turn phase, and available status, code, request ID, or retry time. Provider -adapters extract these fields; arbitrary exception objects, request bodies, -headers, environment variables, and stacks are excluded. Unknown categories retain -their explanation. The cause stays in company-scoped run records and the run log; -it is not added to first-party Telemetry, Observability attributes, or Sentry -failure reports. The reportable run error keeps its existing generic text, except -that an ACPX startup rejection keeps Runner's closed rejection text and its -classification. Startup receipts retain the cause across controller restart before -any provider turn exists. - -When a failed ACPX control closes the session before polling, the resulting -`turn.failed` event retains that control's closed-code error. A later closed-session -check does not replace it, and a closed code does not infer a provider explanation. -The terminal still reports `recoverable: false` and no observed provider terminal; -it does not prove termination or authorize replay. - -Every ACPX session ensure rejection carries a startup cause. When the provider -returned no ACP error, the cause keeps the rejection's own redacted message with -category `unknown`. A provider can type the failure with ACP's -authentication-required code, or with a known error type or `errorKind` in the ACP -error data. The cause then uses that category, and the rejection classification is -`provider_`, such as `provider_quota_exhausted`, instead of -`session_ensure_failed`. - -Completed OpenCode builtin `bash` parts preserve the numeric process exit from -`state.metadata.exit` in `tool.execution.completed.payload.exitCode`. The tool -status stays `completed` even when the command exits with a nonzero code. This -status describes completion of the tool call, not success of the command or the -native run. Metadata adds an exit only when it is an integer. Conflicting supplied -legacy exits stay unknown. Existing numeric `state.exit` values remain supported; -metadata on other tools cannot add process-exit proof. - -An edit tool call can carry `fileChanges` on its `tool.execution.*` payload. -Each entry names one workspace-relative `path`, its `operation` (`create`, -`modify`, `delete` or `rename`), `previousPath`, `additions`, `deletions`, a -unified `diff` and `diffTruncated`. The runner drops paths outside the working -directory, redacts secrets in each patch, and bounds a patch to 32 KiB and one -call to 32 files. Counts cover the whole patch even when the patch is shortened. -Codex `fileChange` items produce these rows. Claude Edit and Write calls produce -them from the ACP `diff` content. Codex `turn/diff/updated` also records the -whole-turn diff as `workspace.change.updated` (`paperclip.workspace.diff.v1`). -The task chat shows each patch under its edit row. It ends the turn with the -change set, or with one built from the edit rows when the harness reports no -whole-turn diff. - -`auth.credentials.updated` is a runner-produced PRP event for a change to a -supported credential store, including account identity changes and later token -refreshes on the new account. The bundled transport awaits a host commit callback -before acknowledging delivery, including during warm idle and provider cleanup. -The callback writes directly to the bound run through the shared run-log writer. -Its separate credential source namespace avoids collisions with driver-normalized -source sequences and deduplicates retries using the original PRP event identity. -The original envelope is retained in `prpEvent`. Its payload contains only a -provider, an opaque binding ID, a revision, and a detection method. It contains -no credentials, account identity, file path, or credential fingerprint. The -consumer can use the event to read the updated credentials through its existing -private credential channel. This run-log event stays in the instance database. - - -`native.recovery.execution_reclaimed` records an atomic same-run recovery claim -that restores a released task execution binding. The claim locks the task, -coordinator, and original run in that order. It preserves the assignee and checks -current execution/checkout owners, other live work, dependencies, pause holds, -and stop/successor records before restoring the binding. Attachment authorization -keeps its existing requirement for that exact binding. Remote retry claims also -require the exact saved controller authority and reject a newer task run. The -event does not prove that a remote provider survived or permit provider replay. -Skipped local retry candidates wait 30 seconds before recheck. Remote admission -holds use the existing bounded system-recovery backoff independently of provider -attempts. Permanent ineligibility or policy exhaustion records the terminal -automatic recovery disposition and board action without releasing the retained -execution binding, provider, or checkpoint. These settled holds schedule no -further retry. Repeated blocked visits record only a changed hold reason. -The same durable hold prevents background stale-lock cleanup and queue release -from clearing either task binding until the remote termination receipt contract -is satisfied. A terminal heartbeat status is not a provider-stop receipt. -Undated retries sort first. A failed candidate cannot discard earlier committed -claims. Queued waiters do not block the original execution owner from recovery; -they still wait for that owner to settle before normal queue promotion. -This is local run-log data. - -Fresh remote Codex model substitution emits `runner.model_fallback` on the -system stream with `warn` severity. Its payload contains `requestedModel`, -`effectiveModel`, and `codexCliVersion`. It records a preparation choice before -provider launch, not a failed turn or a retry. The same substitution appears as -a system warning in the task conversation. It remains local run-log data. - -The hidden native coordinator writes each validated PRP event to the bound -run's existing event stream before it acknowledges the runner. The row keeps -the PRP `eventType`, source instance, source event ID, source sequence, protocol -schema version, and a SHA-256 digest of the canonical stored envelope. Its -payload is `{ "prpEvent": }`. - -Native API tool events omit HTTP request and response bodies from durable history. -This includes serialized provider `contentItems`, legacy HTTP receipts and -`call_api` arguments. Saved receipts retain the operation and call IDs, success -flag, HTTP status and content type when present. The body becomes -`***REDACTED***`, with `apiPayloadRedacted: true` and `apiPayloadSha256`, a SHA-256 -digest of the original payload. These digests distinguish duplicate events from -changed payloads; they cannot recover omitted bodies for debugging or replay. -The model receives the original authorized response. Credential-bearing mutation -receipts use encrypted storage separately from this run log. - -Checkpoints and completion records apply the same redaction. Completion retries -compare stored and expected payloads through the control-plane port's idempotent -`normalizeReplayPayload` projection, so a saved redacted result can be confirmed -without restoring API bodies. Ports without a projection compare their original -payloads. Repeated redaction preserves the original digest and detects changed -private payloads. - -The native runtime passes this projection through backend recovery to the Codex -driver. Recovery compares saved semantic results and turn fingerprints with -provider history through the same representation. A private body change retains -its distinct digest and fails recovery; an unchanged body does not require -restoring its plaintext into the checkpoint. - -PostgreSQL JSONB cannot represent NUL (U+0000), which can occur in command -output such as Vite virtual-module paths. The run-event payload column uses a -lossless storage codec for these events: the JSONB projection renders NUL as -the literal `\u0000`, and the reserved `$paperclipRunEventJsonV1` field contains -the original serialized JSON as a doubly escaped string. Ordinary payloads -retain their existing representation. Drizzle reads restore the exact stored -payload before replay, hash validation, redaction, or API presentation. SQL -queries can still inspect ordinary routing fields in the projection; raw SQL -readers of the whole payload must apply `decodeRunEventPayload`. The column -remains JSONB and requires no schema migration. - -The writer locks the native `heartbeat_runs` row and allocates the existing -per-run `seq` cursor. A byte-equivalent retry reuses the first row; a changed -retry or source-sequence gap is rejected. Company, issue, agent, run, session, -and runner-source bindings must match the persisted native run. Bootstrap -tickets, reconnect leases, authentication proofs, encryption keys, and raw -credential material are never written to the run log. - -These records remain run-log events. They do not create an OpenTelemetry or -Paperclip Telemetry export, and legacy adapters do not use this writer. - -## Semantic Settlement Diagnostics and Retry Logs - -When native tool arguments fail their authorized JSON Schema, the runner records -`harness.diagnostic` with code `semantic_tool_denied` and `paperclipExecuted: false`. -Its optional `inputSchemaGuidance` retains the same safe repair guidance sent to -the provider: at most three authorized schema locations within 512 bytes. -It includes no rejected arguments, submitted values, or unknown input keys. -The rejected call does not create a semantic input event or execution receipt. -Validated runner diagnostics retain this scalar metadata even when the operation -is an API or case tool. API request and response bodies keep their existing redaction. - -If a declared native completion tool is rejected and the turn ends without an -accepted replacement report, the runner emits `session.failed` with code -`semantic_completion_rejected` and `recoverable: false` before the provider's -original turn terminal. It emits no successful result proposal or human review -request. Core uses its existing permanent native failure path and does not start -a missing-result recovery turn. This failure also precedes terminal goal updates; -Core records the original turn terminal before rejecting goal success or further -goal continuation. Recoverable goal failures retain their existing behavior. -The rejection survives same-turn restoration; -a new turn or run binding clears it. A later accepted completion report keeps -its normal authority, and ordinary turns with no completion-tool attempt keep -their existing fallback. - -Before interrupting a Codex turn, the runner durably records a -`harness.diagnostic` event with code `provider_interrupt_requested`, the stop -reason, provider turn ID, and pending tool call IDs. A harmless identical result -replay records `semantic_tool_result_duplicate` with warning severity, call ID, -operation ID, and result digest. It does not fail the task or create a user -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, -and incomplete result-delivery command IDs and statuses. If execution and -cleanup both fail, execution retains its original error identity and cleanup is -attached as `cleanupError`. `runnerRetained: true` means a remote Runner that -could not prove its suspension was left running for the same-run -reattachment instead of being force-stopped; the diagnostic -`remote runner left alive unsettled for same-run reattachment` records it. - -Semantic settlement also includes up to 20 content-free failure records, with -the call ID, operation ID, stage (`dispatch` or `persist_result`), and cause. -Causes distinguish an oversized command, a full command journal, known storage -errors, dispatcher rejection, and other persistence failures. Exception messages -and tool results are excluded. These diagnostics do not authorize replay of an -operation whose outcome is unknown. - -Instruction writes also commit an `agent.instruction_write_attempted` activity -row and a run-scoped `instructionToolAttempts` entry before permitting the -filesystem effect. They retain the call ID, operation ID, and input digest, not -instruction text. A later transaction rollback cannot erase this attempt proof. -A missing success or definite pre-write failure receipt means the outcome is -unknown, even if the current file contains the requested text. Known validation -and stale-base failures are saved under the attempt's `failure` entry and replay -their original status, message, and details without a new write. Unknown -outcomes remain blocked until reconciled; a -committed receipt with a lost acknowledgement can replay its exact result. - -The NDJSON output log appends across repeated `begin` calls for one run. Each -new handle adds an `attemptId` to its lines. If the local file is absent and a -durable S3 mirror exists, `begin` restores that prefix before appending. A -failed restore must not replace the mirror with an empty or partial attempt. -Publishing a restored prefix uses an atomic create-if-absent operation, so a -concurrent restore cannot overwrite lines another attempt has already appended. -Earlier attempts therefore remain available for incident diagnosis. Existing -records without `attemptId` remain readable. - -These records use the instance run log and its configured storage. They add no -Paperclip Telemetry or OpenTelemetry export. - -## Omitted Unsafe Workspace Export - -`workspace_export_omitted` is an informational system event in the local run log. -Its payload is `{ "reason": "restore_unsafe_archive" }`, with `"legacy": true` -when recovering an unsafe failure from an older controller. It records that native -finalization discarded an unsafe export and continued with the accepted result. -It contains no archive names, link targets, or raw error details. It does not -create a task warning, recovery action, Telemetry event, or OpenTelemetry export. - -## Native Restart Recovery Run-Log Event - -Paperclip writes a `native.recovery.transition` event for native restart -classifications and for graceful restart suspension. A blocked remote retry -records a changed hold reason once; repeated visits with the same hold reason, -an existing future deadline, or a live lease do not append another transition. -Exhausting the automatic admission policy records its terminal disposition even -when the underlying hold reason remains the same. -This immutable run-log -record lets operators reconstruct recovery decisions without exporting data to -Paperclip Telemetry or OpenTelemetry. - -The payload contains the restart kind, recovery request id when one exists, -runner disposition, and the controller generation and provider attempt for a -claimed recovery. Live-runner adoption also records the runner PID, process -group, and process-start fingerprint. A non-claim disposition records a bounded -reason instead. Graceful suspension records the signal and confirms that it did -not create a retry run. - -The event never includes bootstrap tickets, reconnect leases, authentication -proofs, encryption keys, environment variables, provider credentials, command -arguments, or an unsanitized stderr stream. Detailed failed-attempt diagnostics -remain in the bounded `native_run_finalizations.recovery_history` ledger. - -`native.remote_runner_recovery_failed` records the closed `stage` and `reason` -when remote identity verification fails, including admission failures before the -execution coordinator opens. Unavailable probes are retried within a shared -30-second deadline; identity conflicts are not retried. The event distinguishes -an unreadable identity from a confirmed missing process and contains no command -output or credentials. Saved-state read failures use `state_read_failed`; malformed -saved JSON uses `state_invalid`. It does not itself authorize replacement or cleanup. -For `process_not_running`, the event also records `runnerLifecycle` and -`runnerSettled` from the exited runner's saved state. `runnerLifecycle` is a known -runner lifecycle, `other` for an unknown value, or `unavailable` when the state has -none. `runnerSettled` is true only when the outbox is empty and no terminal delivery, -provider cleanup or warm transition is pending. These fields explain how the runner -stopped. The event is not recorded when a scheduled retry resumes a runner that -exited after a settled suspension. - -`native.interrupted_turn_outcome_unknown` (level `warn`) is recorded once on a -failed run whose reattachment proved the Runner process gone -(`process_verification` / `process_not_running`) while its last provider turn -had no observed settlement, just before the server requests the automatic -Retry. The payload holds the provider `turnId` (or `null`), the last turn event -type, `replayed: false`, and the closed `runnerExit` fields `stage`, `reason` -and `runnerLifecycle`. It names a turn whose outcome is unknown; the Retry's -fresh session never replays it. - -For a prepared remote workspace interrupted before its first executor claim, -that ledger records `remote_execution_never_claimed` with a -`bootstrap_incomplete` disposition. The provider attempt remains zero during -classification; the executor increments it before starting provider work. -A claimed remote bootstrap (the sandbox runner was launched and may have -connected) records `remote_bootstrap_proven_incomplete` with the same -disposition. Recovery admits it only after the previous controller lease has -expired and the Postgres controller checkpoint holds just `run.prepare` and an -unfinished `session.open`, with no committed or acknowledged event. The -executor restores that checkpoint and checks the same proof before it -bootstraps again. After three provider attempts it records -`execution_recovery_budget_exhausted` instead. -A claimed remote run whose previous controller is gone, with no -`native.process_start_requested`, process identity, adapter invocation, -runner-sourced event or controller checkpoint, records -`remote_runner_never_launched` with the same disposition and budget. The -executor records `native.process_start_requested` before a backend may spawn a -runner, so its absence (with no checkpoint) proves nothing reached a runner. -A remote run that a graceful drain suspended just after its runner opened the -provider session records `remote_session_opened_without_turn` with the same -disposition. Its Postgres controller record must hold only `run.prepare` and -`session.open`, with every committed event a session-open event and no event -missing. Before that same-run bootstrap relaunches in the reused sandbox, the -executor stops the interrupted runner it can verify there, so the new runner -does not fail with `runner_ingress_bind_conflict`. -The same rule covers a remote run that its executor already settled as a -same-run `bootstrap_retry` (for example when a shutdown closed the local -runtime listener during startup) and that is due when the server restarts. - -For a local Codex, OpenCode, or ACPX turn lost while runnerd was stopped, the canonical `turn.failed` -event retains `error.code: "provider_turn_lost_on_restore"` and -`error.recoverable: true`. It records the interrupted turn, not a final task -outcome. There is no synthesized result for that interruption. An admitted -same-session continuation emits its own `turn.submitted`, accepted turn ID, and -terminal events; only the final outcome closes the run. Reconstructed thread -history retains the original error so reconciliation and live delivery agree. -An ACPX session records this only after the original provider lifetime loses -its fence quorum and the same conversation is restored. Otherwise its -`turn.failed` carries `error.code: "acpx_active_turn_recovery_closed"` with -`error.recoverable: false`, and the run closes with an honest restart message. -After an ACPX restore, the controller can still deliver results for semantic -calls of the lost turn. Runnerd acknowledges each one as `retired` without -sending it to the restored provider, so the calls settle and live semantic -dispatch resumes for the continuation. A restored ACPX provider is a new process -whose MCP request ids restart, so its semantic `callId` values carry a -per-process prefix (`r:`). They never reuse an earlier call's id in -the same run. - -## Native Local Process Stop Evidence - -The server writes `native.local_process_stopped` in the same transaction that -clears a local run's process identity, after it verifies that its PID and process -group are absent. The payload contains only those process IDs. Remote process -IDs are never checked against the control-plane host. - -A crash can land after `native.process_start_requested` and before the runner's -process identity is recorded. Continuation admission then writes -`native.local_process_stopped` with null process IDs and -`basis: "unidentified_runner_absent"`. It does this only on the host named in -the launch event's `hostname` payload, after it checks two things. First, no -process carries the run's `--run-id` runner argument. Second, no -saved runner control-plane state (canonical or quarantined) belongs to the run; -a provider starts only after its runner connects and writes that state. - -The server writes `native.process_start_requested` before a backend can spawn, -and `native.process_identity_recorded` when it stores a new native process -identity. Either invalidates an earlier local stop receipt, including a crash -before the new PID callback. Continuation admission accepts only the latest -server-authored event among these three types; provider -source events cannot supply stop authority. These records stay in the local run -log and do not add Telemetry or OpenTelemetry data. - -The server writes `native.prior_owner_fence_refused` when its runner-state -check refuses a run before any launch, because the conversation's saved runner -state belongs to an earlier run that cannot be proven finished. The payload -holds only the closed refusal `reason` (for example -`prior_owner_terminal_state_indeterminate`). Continuation admission reads it, -with no launch, identity, `adapter.invoke` or runner-sourced event, as proof -that the failed run never had a runner, so Retry and new input need no stop -record for it. - -Explicit continuation writes `native.stopped_conversation_verified` after it -verifies the retained worker and provider processes stopped. Its payload binds -the requesting `runId`, retained `ownerRunId`, native session, runner instance, -process IDs, retained-state fingerprint, successor run, Retry receipt, and local -workspace identity. The owner can be a preceding terminal -run when the requesting attempt failed before launch with the same process -identity. The server checks host-bound process birth and independent provider -receipts before retiring cleanup ownership. The event does not settle uncertain -actions or authorize replay of the old session. - -## Verified Local Codex Replacement Evidence - -The server writes `native.stopped_text_turn_verified` in the same transaction -that schedules a fresh successor for a stopped local Codex run. It records the -runner and provider process identities, retained-state digests, provider thread -and turn IDs, and IDs of exactly receipted task-completion calls. The server first -checks the complete turn inventory, process-stop receipt, and execution binding. -Unknown actions or changed retained state prevent this event and replacement. - -The record documents why the old execution can be retired. It does not make the -old session resumable, rewrite provider files, or authorize replay on its own. -It remains in the local run log and adds no Telemetry or OpenTelemetry export. - -## Sandbox Startup Run-Log Event - -Paperclip writes one `run.startup.step` event to the run log for each bring-up -step. This event is a run-log record, not a first-party telemetry event. The -generated telemetry contract does not cover it, so this section is its canonical -contract. - -The event payload carries only three fields. - -| Field | Type | Meaning | -| --- | --- | --- | -| `step` | string | The bring-up step name, for example `stage.sync`. | -| `durationMs` | number | The wall time of the step. A skipped step reports `0`. | -| `outcome` | string | The step outcome (`ok`, `skipped`, or `failed`). | - -The event no longer carries the per-step round-trip count or the provider -duration fields. It dropped `roundTrips`, `providerExecMs`, `providerGetMs`, -`createRuntimeMs`, and `ensureSessionMs`. The startup spans in -[`doc/observability.md`](observability.md) carry that detail now. The -`sandbox.exec` child spans hold the round-trip and provider durations. The -`acp.handshake` step span holds the create-runtime and ensure-session -sub-times. - -To read the detailed timing, use the startup spans. The spans need an OTLP -endpoint. A run with no endpoint keeps only the three run-log fields above. - -## Run Phase Timing Run-Log Event - -Paperclip writes one `run.phase.timing` event to the run log for each -run-lifecycle phase. This event is a run-log record, not a first-party telemetry -event. The generated telemetry contract does not cover it, so this section is its -canonical contract. The producer is `emitRunPhaseTiming` in -`packages/adapter-utils/src/acpx-engine/startup-timing.ts`. - -The event payload carries only three fields. - -| Field | Type | Meaning | -| --- | --- | --- | -| `phase` | string | The run-lifecycle phase name from the closed allowlist below. | -| `durationMs` | number | The wall time of the phase. A negative or a non-finite value clamps to `0`. | -| `outcome` | string | The phase outcome (`ok` or `failed`). | - -The `phase` field is one member of a closed, low-cardinality allowlist. The -producer drops any event whose phase name is outside this allowlist, so a -free-form label never reaches the run log. The allowlist has twelve phase names. - -| Phase | Meaning | -| --- | --- | -| `place_workspace` | Place the run workspace. | -| `start_transport` | Start the agent transport. | -| `create_runtime` | Create the agent runtime. | -| `ensure_session` | Ensure the agent session exists. | -| `configure_session` | Configure the agent session. | -| `prepare_turn` | Prepare the turn. | -| `turn` | Run the turn. | -| `end_session` | End the agent session. | -| `settle_reuse` | Settle the session for reuse. | -| `stop_transport` | Stop the agent transport. | -| `sync_back` | Sync the workspace back. | -| `release_staging_lease` | Release the staging lease. | - -The payload never carries a command, an argument, a path, an environment value, -or a raw identifier. The event rides the `ctx.onEvent` run-event bridge and is -run-log-only. It needs no OTLP endpoint. - -## Workspace Restore and Settled Run Measurements - -The heartbeat controller writes these records with `eventType: "lifecycle"`, -`stream: "system"`, and `level: "info"`. The event name below is its `message` -and its payload's `phase`. They remain in the instance run log and add no -Paperclip Telemetry or OpenTelemetry export. - -| Event | Payload fields besides `phase` | Meaning | -| --- | --- | --- | -| `workspace_checkpoint` | `mode`, `scannedEntries`, `changedFiles`, `payloadBytes` | Metrics for a validated sparse checkpoint, or a full restore fallback. | -| `workspace.restore` | `durationMs` | Wall time around native workspace restoration. | -| `task.run.measured` | `durationMs`, `outcome`, `durableSettlement` | Wall time through terminal owner cleanup, with the persisted terminal run status and `durableSettlement: true`. | - -For `workspace_checkpoint`, `mode` is `"sparse"` or `"full"`. Sparse metrics -count snapshot entries in `scannedEntries`, regular files in the validated -downloaded payload in `changedFiles`, and their total bytes in `payloadBytes`. -Deleted entries and symlinks do not add to the regular-file count or byte total. -Full fallback reports all three counts as `null`: unavailable, not zero. A run -can emit multiple checkpoint records while restoring its repositories. These -payloads contain no paths, filenames, file contents, or credentials. - -`workspace.restore` is emitted when the timed restoration exits, including an -exception. It has no outcome field and does not by itself prove restore success. -Its producer is the native workspace sync `onPhase` callback. - -`task.run.measured` is emitted only after the controller observes a terminal run -with no remaining native runner ownership. Its duration starts at `startedAt`, -or `createdAt` if the run never started, and includes preparation, execution, -finalization, and cleanup. It is not model-only time; the creation-time fallback -also includes time spent queued. `outcome` is the actual terminal status, such as -`succeeded`, `failed`, or `cancelled`. Provider turn completion can precede this -settlement record. The record does not imply exactly-once emission across -controller recovery, and failure to write it is logged without changing the -already-settled outcome. - -## Storage outage waits - -A run waits out a file-storage outage on its critical path: when it starts its -run log, restores its saved workspace, or saves it. While it waits, the run's live -status says so, with phase `waiting_for_storage`, for example "Waiting for file -storage before starting the run log (45s so far)". That status lives in server -memory and on the live-event stream only. It writes nothing to the run row or -the run log during the wait. - -When the wait ends, the controller writes one record with `eventType: -"lifecycle"`, `stream: "system"`, and `level: "warn"`. Its message is "Waited Ns -for file storage before ." or, when storage stayed unavailable, "Waited Ns -for file storage before ; it was still unavailable." Its payload holds -`reason: "storage_outage_wait"`, `purpose` (the step), `waitedMs`, and -`recovered`. The record stays in the instance run log. - -When the outage outlasts that wait, the run fails. Only a run recorded with -`errorCode: "storage_unavailable"` gets a storage wait: a bounded retry -(`retryReason: "storage_unavailable_wait"`) that starts again after storage is -back. Its error says "Paperclip will retry automatically when storage is back" -only while that retry is scheduled. When the retry budget is spent, the error -says so and asks for Retry. When no storage wait follows, the error says -"Paperclip is not retrying it automatically. Retry or send a message to -continue." That happens when a native recovery already holds the run under -another code (for example `native_continuation_requires_reconciliation`, where -its files are kept and its unfinished turn is not replayed), or when the retry -is refused or cannot be written. A run saved by an earlier release with the -retry promise under another code reads with the same Retry text, with no -migration. - -## Durable storage timing - -A saved remote workspace is one encrypted archive in durable object storage. -Restoring it before a turn, and saving it after one, runs these steps as named -run phases: - -| Phase | Step | -| --- | --- | -| `storage.snapshot.download` | Get the encrypted archive from storage. | -| `storage.snapshot.decrypt` | Hash the downloaded archive and decrypt it to private scratch, at the same time on worker threads. | -| `storage.snapshot.verify_plaintext` | Hash the decrypted archive against its sealed digest while copying it beside its destination, on a worker thread. | -| `storage.snapshot.publish` | Link the verified copy to its destination. | -| `workspace.snapshot.sandbox_restore` | Upload and unpack the archive in the sandbox. | -| `workspace.snapshot.sandbox_upload` | Inside `sandbox_restore`: copy the archive into the sandbox. | -| `workspace.snapshot.sandbox_extract` | Inside `sandbox_restore`: verify and unpack the archive, then publish the restored folder. | -| `storage.snapshot.prior_attempts` | Check whether an earlier upload attempt already landed. | -| `storage.snapshot.encrypt` | Hash the archive, encrypt it and hash the encrypted file, in one pass on a worker thread. This is the only full read of a downloaded archive: one whose digest or size differs from the sandbox's receipt fails here, before any upload is recorded. | -| `storage.snapshot.digest` | Record the digest of the encrypted file. The `encrypt` pass computes it, so this step takes no time. | -| `storage.snapshot.put` | Upload the encrypted archive (multipart above 16 MiB). | -| `storage.snapshot.verify` | Confirm the stored object (its size when the backend checked every part, otherwise a full read-back). | - -A restore runs inside run preparation, so each of its steps of 50 ms or more is -a `run.performance.span` row of the run. A save runs after the turn. Its step -durations are recorded on its `remote_workspace_snapshot` workspace operation, -in `metadata.saveTiming.storage`: -- `priorAttemptCheckMs`, `encryptMs`, `digestMs`, `putMs` and `verifyMs`; -- `bytes`; -- `requests`, the storage requests the save sent. These are `requests`, - `attempts` (SDK attempts across them), `failedRequests`, `retryDelayMs` (SDK - waits between its own retries), `parts`, `throttled` (part sends the backend - rate-limited with 503, 429 or SlowDown) and `backoffMs` (the uploader's waits - before resending a part). - -A restore also records its step durations, `bytes` and `requests` on its -`remote_workspace_restore` workspace operation, in `metadata.restoreTiming` -(schema `paperclip.remote-workspace-restore-timing.v1`). A save that reuses an -earlier upload still reads it back; that read-back is counted in `verifyMs`. -A throttled part send counts in `throttled` even when it ends the retries, -and a multipart abort sent during cleanup counts in `requests`. - -These are counts and durations only: no object keys, paths or provider text. - -## System notices and final replies - -Automatic comments with a stored `system_notice` presentation, including -workspace-ready notices, remain available as progress information. They do not -occupy the run's final reply slot. Final response selection still preserves -ordinary explicit agent comments and excludes receipt-bound generated progress. - -## ACP terminal failure diagnostics - -The shared ACP adapter engine preserves typed terminal session failures in the -run error, the `acpx.error` transcript record, and -`heartbeat_runs.result_json.terminalSessionFailure`. The structured diagnostic -contains the provider category, title, and details. It works when raw provider -tracing is disabled. The existing UI and CLI render the diagnostic as an error, -not as assistant output or an automatic task response. -Issue continuation summaries and session-compaction handoffs retain only the -generic failure category; provider diagnostic prose is not copied into prompts. - -Both pinned ACPX patches pass complete title and detail strings to the in-memory -callback. The engine redacts configured environment values (including resolved -secrets with arbitrary variable names), launch environment values outside a -closed allowlist of public process settings, known boolean flags, and run identifiers, -connection URL passwords, the run API key, and common credential forms before -truncation. It removes control characters, -retains line breaks for JSON and stack traces, and preserves up to 4,096 title -characters and 24,576 detail characters. These bounds also keep the escaped -transcript JSON below the server's 64 KiB chunk limit. Longer fields end with an explicit -omission count and appear in `truncatedFields`. The error message includes the -same sanitized text. Ordinary run retrieval preserves the bounded structured -diagnostic even when multibyte text or other result fields exceed the result -byte budget. In that reduced response, title and details have 1 KiB and 8 KiB -byte budgets, including truncation markers. `retrievalTruncated` directs callers -to the full adapter-bounded text in the run error or transcript. Other provider -metadata and action payloads are not copied. - -When an ACP request fails with a JSON-RPC error, the engine also keeps the -provider explanation. It reads a string `data`, or the string `data.details`, or -the string `data.message`, in that order. It adds the explanation on a new line -after the error message unless the message already contains it. The combined -text passes through the same redaction and the 4,096-character title bound -before it becomes the run error, the summary, and the `acpx.error` `message`. -A numeric JSON-RPC error code appears as the optional integer `rpcCode` in -`errorMeta` and in the `acpx.error` record. Errors without these fields keep -their existing message and omit `rpcCode`. - -Recovery still uses the typed failure category and the adapter's existing -classifier. Provider warnings do not become failures, and timeouts or lost -control channels keep their authoritative failure messages. These diagnostics -stay in the instance's run records and configured run-log storage. They add no -Paperclip Telemetry or OpenTelemetry export. - -## Related instrumentation - -The sandbox duplex transport also writes one run-log event as one of its three -sinks. See the -[Sandbox Duplex Transport Instrumentation](observability.md#sandbox-duplex-transport-instrumentation) -section in the Observability contract. - -## Execution recovery - -Cancelled runs retain `resultJson.cancellation`: a closed `source` label -(`operator`, `queued_message`, `shutdown`, `provider`, `transport`, -`control_plane`, `controller_lease`, or `unknown`), whether the stop was expected, -the initiator, reason, and recording time. Recorded stop intent survives adapter -completion. `controller_lease` means the host stopped its own legacy adapter -after it lost the durable controller lease; the reason names a closed cause -(`renewal_rejected`, `renewal_deadline`, or `renewal_error`). The watchdog -retries a failed renewal until the lease deadline, so `renewal_error` means the -attempts still failed with an error when the deadline passed. -All legacy controllers in one server process renew through a single queue on -the private lease connection pool. Renewals that arrive while one is in flight -share the next statement, so a burst of runs costs one renewal statement per -round instead of one transaction per run, and a renewal waits behind at most -one other. A run whose row another transaction holds is skipped and retried -shortly, without delaying the other runs. A renewal only moves the lease -deadline later, so it does not wake live-run recovery; recovery rereads the -moved deadline when the earlier one comes due. -A lease lost during run setup (for example a rejected renewal while preparing -the workspace) settles the run `failed` with error code `controller_lease_lost`, -the same `controller_lease` cancellation evidence, and -`executionRecovery.providerWorkStarted: false`. Recovery retries it as transient -infrastructure instead of blocking on `setup_failed`. A setup-phase error after -provider dispatch began keeps `setup_failed`, so started work is never retried. -The local lifecycle event includes this evidence. Started cancellations without -an expected stop are also reported to Sentry; its cancellation diagnostics contain -only source, expectedness, initiator type, and the closed lease-loss cause, never -initiator IDs or reason text. -A lease loss also records `resultJson.controllerLeaseLoss`, including a loss -during setup that fails the run before adapter dispatch. It holds the closed -cause and the watchdog timings in milliseconds: `sinceRenewalMs` (since the -last successful renewal), `renewalPendingMs` (age of a renewal operation still -in progress, including its retries and retry waits, or `null`), `deadlineLateMs` -(how late the deadline callback ran, when the lease deadline ended the run, -otherwise `null`), and `renewalCount`. A long `renewalPendingMs` can mean a -stalled database query or repeated failed attempts with retry waits; the cause -label tells them apart (`renewal_deadline` or `renewal_error`). A long -`deadlineLateMs` points at a blocked event loop. Failure reports carry these -bounded numbers and the cause label only. -Historical ambiguous cancellations stay `unknown` and do not authorize replay. - -Provider tool-definition validation failures use -`provider_tool_definition_invalid` / `configuration`. Automatic retry and -continuation recovery stop until the configuration is repaired. Classification -uses raw provider diagnostics in memory before redaction; stored diagnostics -remain redacted and bounded. - -Provider identity diagnostics remain in the local run log. They record the notification method, expected and received thread/turn identifiers, and the classification (root, verified descendant, stale, unrelated informational, or invalid authoritative). They omit the original provider payload and credentials. Repeated informational notices are bounded. - -Ignored unrelated Codex notifications use `harness.diagnostic` with code -`codex_unrelated_information`. The payload retains only the bounded provider -method and expected/received thread and turn identifiers. Account updates, skill -changes, and unrelated thread information do not create a provider notice in -chat. Chat also omits the matching notice stored by older runners. Real provider -warnings and errors remain visible. - -Provider rate-limit windows use `provider.notice.recorded` with category -`provider.rate_limits` and scope `account`. Codex sends them as -`account/rateLimits/updated`. Claude sends them as `usage_update` metadata -(`_claude/rateLimit`) when it uses a subscription sign-in. The runner merges -sparse Codex updates and records a notice only when the windows change. The -notice has one `rateLimits` detail: a JSON snapshot with schema -`paperclip.provider.rate_limits.v1` (windows with used percent and reset time, -credits, and the reached window). Chat does not show the notice. The server -keeps the latest snapshot in the agent's runtime state under -`providerRateLimits`, and the task properties pane shows it as the assignee's -**Usage limit**. The snapshot is display data. It does not hold or start work; -the provider-limit wait reads typed run failures. - -Harness status notices use `provider.notice.recorded` with a status category. -Codex `error` notifications read `error.message`. A notification with -`willRetry: true` becomes a recoverable `provider_retry` notice. A final error -keeps category `error`. The `CodexErrorInfo` kind, the HTTP status, and the -reconnect attempt count become notice details. Claude compaction, model -fallback, and SDK informational banners arrive as ACP message text without a -message identity. The ACPX layer records them as `context_compaction`, -`model_fallback`, or `provider_informational` notices instead of answer text. -Compaction start and end share one notice identity and carry a `Phase` detail. -The task chat shows these notices as inline status chips. A retry chip fades -after later provider work. A final provider error shows the real provider -message. Generic warnings stay out of chat as before. - -Recovery lifecycle events retain the original structured failure code, retry attempt, next retry time, and predecessor/successor identifiers. Durable status delivery uses an idempotency marker; delivery grants no provider authority. Failed publication is retried without repeating provider work. These records are not first-party Telemetry. - -An unstarted legacy conversation retry waiting for execution cleanup retains -`resultJson.executionWait` with the issue, blocking run, and -`execution_owner_active` cause. A local lifecycle event records the wait and the -unchanged scheduled retry attempt once per blocking run. Repeated scheduler -checks update the same retry row without repeating that event. Promotion removes -this ownership-wait marker after cleanup; other execution holds retain their -existing dispatch gates. - -If execution-continuation setup finds that a task no longer exists, is closed, -or its owner changed, the existing cancellation settlement records -`continuation_task_ownership_changed`. The run and wake request become cancelled -before adapter dispatch, with the run-log message -`stale execution continuation cancelled before dispatch`. Immediate recovery is -suppressed. A comment the cancelled run carried that no run read is saved -first when an agent run closed the task: a person's comment, or another agent's -comment posted with `resume: true`. The release then reopens the task and -delivers that comment once. Another agent's comment without `resume: true` -stays communicative and does not reopen the task. Missing source context, authorization failures, and other setup -errors retain their failure classification. An untyped error with the same -message is also still a failure; cancellation requires the typed ownership guard. - -Bounded retry exhaustion writes one lifecycle receipt per run, retry reason, -scheduled attempt, and retry limit. Repeated or concurrent recovery checks reuse -that receipt, including receipts from earlier builds, without advancing the event -sequence or publishing another live event. Attention reads select the latest -matching receipt in PostgreSQL and project only the run's issue/task identifiers -from its context, so historical duplicate receipts cannot multiply run contexts -in server memory. Existing duplicate events do not require deletion or migration. - -### Workspace restore failures - -Legacy adapter results can carry `workspaceRestoreFailure` with the code -`restore_permission_denied`, `restore_lock_timeout`, `restore_unsafe_archive`, -or `restore_failed`. The heartbeat records `workspace_restore_failed` and keeps -the run failed and the workspace-finalization barrier closed. Available output, -usage, session metadata, and the previous execution outcome survive settlement. -`executionBeforeRestore` retains the earlier error code, exit code, signal, and -timeout flag. The ordinary redacted error field retains an earlier error message. - -The chat reports the restore phase separately from a missing final response. -A saved-plan link requires a stored document and its run-bound revision or a -matching run-bound review record. Older unclassified failures use neutral wording. Diagnostics show only -a validated relative member path, never an archive link target or host path. - -An unsafe archive or an outbound confinement refusal keeps the existing execution recovery hold, including across -conversation resets. It cannot start another model turn until an operator uses -the existing recovery action to record `executionReconciliation` with -`workspaceRepairEvidence` (20–12000 characters). This evidence must describe -verified safe staging or repair for the referenced failed run. It does not grant -plan approval. Saved comments, document revisions, and confirmation IDs and -states stay unchanged. Recovery uses the existing delivery identity and links -the successor to the original failed run. Repair does not reset the automatic -retry budget. Transient failures retain the existing -bounded retry policy. Archive confinement remains required. - -Sandbox restore tasks also write a `Workspace restore diagnostic` line to the -run log on failure. `phase` is `workspace` or `asset`, so a failed staged-asset -copy-back (such as credentials) can be distinguished from workspace restoration. The line -contains only an allowlisted OS/transport `errorCode` (otherwise `unknown`), an -optional numeric HTTP error status, and an optional bounded process exit code. -Up to four nested causes are inspected. Messages, URLs, filesystem paths, asset -names, credentials, and response bodies are excluded. Every failed outbound -task emits its own diagnostic; nested repository failures are logged once by -the enclosing workspace task. The original error and restore safety policy are -unchanged. These lines stay in the instance run log and its configured durable -storage, and are not new first-party telemetry events. - -Native sandbox `environmentSyncOut` errors preserve allowlisted error codes and -bounded HTTP/exit statuses across worker RPC for this diagnostic line. The host -revalidates the envelope and keeps the original failure and recovery policy. -Provider messages, paths, response bodies, credentials, and arbitrary error data -are not copied into the new envelope. Older workers can still report `unknown`. - -The optional `step` identifies the failed restore operation. For -`phase=workspace` and `step=git_integration`, `gitCommand` identifies one fixed -command family (`rev_parse`, `symbolic_ref`, `merge_base`, `merge_tree`, -`commit_tree`, `update_ref`, or `log`). `gitFailureKind` is `merge_conflict`, -`invalid_object`, `ref_conflict`, `permission_denied`, or `unknown`; it is a -bounded diagnostic clue, not a new recovery or retry decision. Only supported -exit/OS codes and recognized Git messages produce a specific classification. -No command arguments, stderr, filenames, repository URLs, or ref names are saved. -The same closed fields persist in `workspaceRestoreDiagnostic` and are -revalidated before projection into an enabled Sentry failure report. - -## Codex resume usage snapshot - -The native runner retains a bounded local `harness.diagnostic` event with code -`codex_resume_usage_snapshot`. It identifies `thread/tokenUsage/updated` as -`resume_usage_snapshot`, retains the reported thread and completed-turn IDs, -and records cumulative usage counters. It does not include provider credentials -or message content. The event establishes the accounting baseline; it is not a -new billable usage receipt or a user-facing provider warning. Other provider -identity checks remain in force. - -## OpenRouter serving host - -OpenRouter can route one model across many hosts, which may serve different -quantizations. OpenCode runs routed through OpenRouter record which host served -each model call. The runner's provider proxy reads the top-level `provider` and -`id` fields from the first streamed chunk, or from the whole JSON body when the -response is not streamed. It forwards every byte to OpenCode unchanged and -before it inspects them, so the first token is not delayed. It scans at most -the first 64 KiB of a stream and 1 MiB of a JSON body. It skips encoded bodies, -non-2xx responses, and any malformed or missing field. A recording failure -never affects the response or the turn. - -Each `item.completed` usage event (`payload.kind: "usage"`) carries two fields -in `payload.usage`: - -- `upstreamProvider`: the host that served the most recently finished model - call when the usage was reported, such as `Novita` or `DeepInfra`. -- `providerRequestId`: that call's OpenRouter generation ID, such as - `gen-1762981234-AbCdEfGh`. - -The proxy records a call's host when that call's response ends, not when the -request starts. OpenCode reports a step's usage only a few milliseconds before -it sends the next model request, so a step's usage still names its own call's -host while the next call is in flight. A call whose host the proxy could not -read records no host when it ends, and a session clears the recorded host when -it attaches another run. Such a call therefore carries neither field. It never -inherits an earlier call's or an earlier run's values. - -The runner's internal `usage.reported` event carries the same values, using its -existing `providerRequestId` field and an optional `upstreamProvider` field. -The run's `usageJson.providerRequestId` and its cost event name the first -generation ID the run reported. That value stays the same as later turns -report, so a late usage receipt still matches the charge. Remote Runner runs carry -the same ID in each saved usage receipt's producer event and in the receipt -itself. A receipt saved before this field existed still replays when the -Runner now names an ID. Per-call IDs and -hosts remain in the run log. Runs whose provider reports no host carry neither -field, and `usageJson.providerRequestId` stays `null` as before. - -These are run-log fields. They stay in the instance database and are not sent -to Paperclip Telemetry or OpenTelemetry. - -## AI subscription contention - -A fresh task execution cannot enter this wait. A run that already entered this -wait writes an informational `lifecycle` event to the local run log. Its -payload contains only `retryScheduled`, a boolean that reports -whether the scheduler created a retry. -The message distinguishes an automatic retry from work that is no longer eligible. -This pre-provider wait records `ai_connection_busy` on the cancelled run and does -not consume the provider-failure retry allowance. The event contains no credentials -and creates no Telemetry or OpenTelemetry export. - -## Agent directory waits - -A run whose instruction preparation finds another run of the same agent using -its files writes one informational `lifecycle` event to the local run log, with -`stream: "system"`. It records no file contents, paths or credentials, and -creates no Telemetry or OpenTelemetry export. - -- A resumed native run that stays on its own run writes the message "Another - run of this agent is still using its files; this run continues when it - finishes". Its payload has exactly two fields: `retryReasonCode`, always - `agent_directory_operation_busy`, and `nextAttemptAt`, the ISO time when the - same run is scheduled to try again. -- A run that has not yet started native execution is cancelled with error code - `agent_directory_busy` and writes "Another run of this agent is still using - its files. This task will continue automatically." when an - `agent_directory_busy` retry was scheduled, or "Another run of this agent is - still using its files, and this task could not be rescheduled." when it was - not. Its payload contains only `retryScheduled`, a boolean. - -Neither wait consumes the provider-failure retry allowance. Each stops after 30 -deferrals, after which the run follows the normal failure path. - -## Task history reads - -When a native run reads its task's comments through `get_task_history`, the -server writes one `task_history.read` event (`stream: "system"`, level `info`) -to that run's log. Its payload has one field, `comments`, which maps each -returned comment ID to that comment's `updatedAt` timestamp. It contains no comment bodies or -author identifiers. The event creates no Telemetry or OpenTelemetry export. - -Per-comment delivery (`deliveredQueuedCommentIds`) reads this event together -with the run's `run.result.accepted` event. A read alone is not delivery: the -run may have read the comment and set it aside. A comment counts as received -only when a run of the task's assignee succeeded after reading the comment's -current revision, and that run's accepted result cites the comment as a -`comment:` evidence reference (top-level `evidence[].ref` or a criterion's -`evidenceRefs`). The comment's queued wake then neither reopens the finished -task nor starts another turn. An edit after the read, a read by a run that did -not succeed, or a read the result does not cite leaves the comment owed, so it -is delivered once in a new turn. That turn's wake marks the comment -`readByEarlierTurn` when an earlier finished run read its current revision, and -the prompt asks the agent to check the current task state before acting so -already-applied work is not repeated. `get_task_history` returns -`arrivedDuringThisTurn` (the `comment:` refs of comments that other authors -posted or edited after the run started) with instructions to cite each applied -comment. The check reads only the assignee's succeeded runs of that task that -finished at or after the comment's current revision, through the existing -run-binding and `(company_id, run_id)` event indexes. A saved follow-up -resumed after a remote Stop uses the same rule. `taskHistoryReadsForRun` lists -the comments one run read, with each read's time and the comment revision it -saw, whatever the run's outcome. A failure to write the event leaves the -comment owed in the same way. - -When a run reads a finished child task, the server writes one -`child_task.read` event (`stream: "system"`, level `info`) to that run's log. -The reads that count are `get_task_context` on the parent task, and a -successful agent request with a run token for `GET /api/issues/:id`, -`GET /api/issues/:id/documents` or `GET /api/issues/:id/documents/:key` of a -child in `done`. The route writes the event only after the requested content -has loaded, so a 400 or 404 records nothing. The payload has `parentIssueId` -and `children`, which maps each finished child ID to the revision the run -received: its `status`, `updatedAt` and `statusDecisionId`. It contains no -titles, summaries or document bodies. The event creates no Telemetry or -OpenTelemetry export. - -`hasPendingNativeChildCompletion` reads this event. A child-completion wake no -longer keeps the parent's done claim open when the finishing run received that -child in `done` at the completion the wake reports: the received -`statusDecisionId` is the wake's completion decision, or the received -`updatedAt` is at or after that decision was saved. The event's own write time -does not count, so a delayed write of an older revision cannot deliver a newer -completion. The wake is then cancelled at release instead of starting another -parent turn. A read while the child was still open, a read of an older -revision, a read by another run, or a failure to write the event leaves the -child result owed. - -## Managed Agent File Save Receipts - -The server writes `instruction_save` after managed file collection or a warm -turn checkpoint. The payload includes the save state, instruction entry path, -storage warning, and error code/message. Agent-directory receipts identify -`contract: "agent_files"` and the applied candidate hash. Legacy instruction -receipts instead identify the saved revision. - -A validated warm checkpoint reports `saved` or `unchanged`, even though its -working directory remains owned by the live session. An unstable checkpoint -reports `pending_collection` until stopped collection produces a final receipt. -Successful checkpoints can include `checkpointStats`: `scannedEntries`, -`hashedBytes`, `copiedFiles`, and `copiedBytes`. These counts describe that -capture, not cumulative traffic or an atomic snapshot of background writers. -They contain no file contents. The receipt remains in the instance run log; -it adds no Paperclip Telemetry or OpenTelemetry export. - -If instruction-copy release throws, `instruction_cleanup` records a warning -with payload `{ "state": "deferred" }`. The existing working-copy recovery sweep -retries cleanup. This event preserves the run outcome and does not claim a file -save; `instruction_save` remains authoritative for collection. The event contains -no raw exception, host path, file contents, or lock-owner metadata. Failure to -write the warning must not replace the provider outcome or stop lease release. - -## Agent observability availability - -`agent_observability.unavailable` is one warning for a preparation snapshot that -cannot apply company export settings. Its payload contains only a closed reason -and the settings revision. It carries no endpoint, credential, secret reference -or resolver error. Recording the diagnostic never contacts a destination. - -## Runtime activity - -`runtime.activity.recorded` is a P1 Runner PRP event with a closed -`{ namespace, activityKey }` payload. `namespace` groups a producer's activity -types under a stable name. `activityKey` identifies an activity within that group. -Consumers use the pair to select a response to activity in the current run. - -For example, `{ namespace: "example.computer", activityKey: "desktop.used" }` -records successful desktop use. Core can map that activity to a Desktop viewer -for the task's running agent. The authenticated event envelope supplies the run, -session, source sequence and emission time. Core resolves the company, task and -agent through the run's existing authorization checks. - -Both activity identifiers contain 1–160 Unicode code points and exclude C0 -controls and DEL. Callers cannot supply run, task or agent identity in this payload. - -The ordinary authenticated Runner event is the durable record. Normal source-event -acknowledgement and replay deduplicate delivery. Existing run-read authorization -and secret redaction apply to saved and live events. Recording reported activity -is not independent proof that it happened and grants no resource permission. - -The native transport forwards runtime activity as a run-scoped fact. It retains -the authenticated run identity across warm session attachment. Provider messages -cannot impersonate this transport-owned notification. -New-run activity waits for warm attachment to finish. A failed attachment does -not retarget queued activity to the previous run. - -Runner accepts local activity records only with an opaque context -captured before the operation. Warm run attachment and process recovery rotate -that authority. Runner supplies the run identity from its active authenticated -binding. Optional hint failure does not fail the underlying operation. No output -text is scanned and no synthetic receipt is written. - -`GET /api/heartbeat-runs/:runId/events?view=plugin-panels` reads these events and -returns only installed agent task-panel contributions under normal run-read and -telemetry-read authorization. Ordinary PRP reads/live delivery retain run-secret -and current-user redaction. The task page uses one history read on mount/reconnect -and the existing live transcript stream, then makes a bounded plugin readiness -check. No panel discovery timer scans runs or provider state while connected. - -## Post-result failure diagnostics - -`native.post_result_failure` records `stage: post_result_execution`, a closed -`category` (`io_not_found`, `io_permission_denied`, `io_failure`, or -`execution_failure`), and `resultAlreadyAccepted: true`. It requires an accepted -selected result and exact current, unexpired controller authority. A busy diagnostic -row lock is skipped. Reporting is best effort under the existing 60-second control -bound; the sink can finish later and emit a late event. The `native_session_lease_lost` -control classification stays unchanged. The labels grant no recovery, result, -Stop, provider-work or payment authority and do not establish a hosted failure cause. +Run-log events are rows in the `heartbeat_run_events` table +(`packages/db/src/schema/heartbeat_run_events.ts`). They stay in the instance +database. They are not Paperclip Telemetry events and not OpenTelemetry +exports, and they need no operator endpoint. See `rules/data-paths.mdc` for how +the three data paths differ. + +This file does not list events or their payloads. Each event is defined where +it is written: search for the event name as a quoted string under `server/src` +and `packages` to find its producer and payload. Payload limits are defined in +`server/src/services/heartbeat/run-log.ts`; the storage codec lives in +`packages/db/src/run-event-payload.ts`. The server appends events through +`appendRunEvent` in `server/src/services/heartbeat.ts`. ## Payload storage -Structured events in this guide remain in `heartbeat_run_events`. When the -instance's existing file storage uses S3, new stdout/stderr NDJSON logs use the -same stack bucket and configured prefix under `run-logs/`, with existing run -references in Postgres. Local-disk instances remain local. Raw provider -traces have their own restricted, encrypted object path. See +Structured events remain in `heartbeat_run_events`. When the instance's existing +file storage uses S3, new stdout/stderr NDJSON logs use the same stack bucket +and configured prefix under `run-logs/`, with existing run references in +Postgres. Local-disk instances remain local. Raw provider traces have their own +restricted, encrypted object path. See [run evidence storage](run-evidence-storage.md) for batching, durability, configuration, migration, retention, and qualification boundaries. - -### Event commit stall diagnostics - -A Runner event commit stall records the first safe error code in the error and -up to three nested `cause` objects. This retains database and transport codes -when an adapter wraps the original error. Each code has the existing 80-character -identifier limit. If no safe code exists, the diagnostic uses the outer error's -safe name. It never copies exception messages, SQL, or query arguments. Cyclic or -long cause chains stop at the same four-object limit. - -This only improves the recorded cause. Event acknowledgement, replay integrity, -the bounded stall policy, and operator recovery requirements stay unchanged. - -A later successful continuation does not establish the cause of an earlier -failure that recorded only `Error`. - -### Failure cause of generic run failures - -A run that fails with a generic code (`adapter_failed`, `setup_failed`) keeps -that code, because callers compare against it, and records -`resultJson.failureCause`: one identifier of at most 80 characters -(`[A-Za-z0-9_.:-]`). For a thrown error it is the provider's HTTP status -(`provider_http_429`) or category, else the first safe code in the error and up -to three nested `cause` objects (`40001`, `ECONNRESET`, the same extraction as -the Runner's event commit stall diagnostics), else the error's class name. For -an adapter result without a code it is the error family, `signal_`, -`process_cancellation_failed`, `exit_code_` or `adapter_reported_error`. It -never copies message text. The server's failure log line carries the same -cause, and the board's run list shows it, for example "adapter failed (40001)". -Older rows have no cause and read as before. - -Run error text keeps SQL statements off the board: a Drizzle `Failed query:` -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/doc/runner-api-tools.md b/doc/runner-api-tools.md index a4dc4081fc2..9ee52c8683f 100644 --- a/doc/runner-api-tools.md +++ b/doc/runner-api-tools.md @@ -343,7 +343,7 @@ idempotent redaction projection. Repeated projection preserves the original payload digest. Provider recovery uses the same projection to compare saved completion results with provider history. Changed private bodies still conflict. Restart preparation preserves the run's admitted REST credential scope, even -when the task mode changes. See [the run-log guide](run-log-events.md) for stored fields. +when the task mode changes. The stored fields are defined where the run-log event is written. The server-issued REST credential for the bound run is never returned to the model. Streaming, WebSocket, MCP and authentication diff --git a/maps/agent-access-map/README.md b/maps/agent-access-map/README.md index e5d633077ff..2fc8f2e87f3 100644 --- a/maps/agent-access-map/README.md +++ b/maps/agent-access-map/README.md @@ -79,7 +79,7 @@ receipt and inline response policy as newly created webhook secrets. Task image access requires the company boundary and the task permission; skill-test and low-trust agents do not need company-wide browsing authority. Completion replay applies the same idempotent projection to stored and expected -payloads; [the run-log guide](../../doc/run-log-events.md) describes its fields. +payloads; its fields are defined where the [run-log event](../../doc/run-log-events.md) is written. Sources: [API client](../../server/src/services/native-runtime/runner-api-client.ts), [catalog](../../server/src/services/native-runtime/runner-api-catalog.ts), diff --git a/maps/agent-access-map/runs-adapters.md b/maps/agent-access-map/runs-adapters.md index 8fc0e9e281c..6a7023064bd 100644 --- a/maps/agent-access-map/runs-adapters.md +++ b/maps/agent-access-map/runs-adapters.md @@ -287,7 +287,8 @@ The native first-text span ends after text is committed for the existing run-eve reader, including reasoning and completed responses. It exports only the bounded text kind and timing, with no text content or new agent access. This adds no agent API, credential access, run-log write, or recovery authority. -See [the tracing contract](../../doc/observability.md#controller-preparation-phases). +See the spans in +[`execution-preparation-timing.ts`](../../server/src/services/execution-preparation-timing.ts). Live latency verification remains separate from the existing access baseline. API: `present` — representative operation IDs: diff --git a/maps/feature-map/chat-channels.md b/maps/feature-map/chat-channels.md index 679eb9265e7..dfb8e215947 100644 --- a/maps/feature-map/chat-channels.md +++ b/maps/feature-map/chat-channels.md @@ -110,7 +110,8 @@ Eyes should appear after authorized task/comment persistence, independently of file preparation, subscription and agent startup. Duplicate delivery must keep one receipt; the final reply must remove only its source message's eyes. Record live mention-to-reaction timing separately from the PostgreSQL fixture tests and -the `chat.slack.receipt` transport span described in [Observability](../../doc/observability.md). +the `chat.slack.receipt` transport span in +[`receipt-timing.ts`](../../server/src/services/chat-channels/slack/receipt-timing.ts). During a top-level DM run, verify that the bot adds eyes to the source message and removes them when the final reply arrives. The pinned Slack SDK encodes a diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.md index 014a56832a1..a03ce83c1d8 100644 --- a/maps/feature-map/runs-adapters.md +++ b/maps/feature-map/runs-adapters.md @@ -44,7 +44,8 @@ For latency diagnosis with an operator OTLP endpoint, search the hashed run ID without restricting the root span name. Compare workspace preparation with its `workspace_` intervals. Measure controller readiness separately through `controller.startup.`. A recovery pause or deployment drain is not model -execution time. See the [tracing contract](../../doc/observability.md#controller-preparation-phases). +execution time. See the spans in +[`execution-preparation-timing.ts`](../../server/src/services/execution-preparation-timing.ts). These source-level diagnostics do not establish a live response-time budget. `task.time_to_first_token` measures accepted ingress through the first committed text that the task transcript can show, including thinking and completed diff --git a/packages/adapter-utils/src/http2-bridge-server.ts b/packages/adapter-utils/src/http2-bridge-server.ts index 3d96787ff25..4094292f0aa 100644 --- a/packages/adapter-utils/src/http2-bridge-server.ts +++ b/packages/adapter-utils/src/http2-bridge-server.ts @@ -132,9 +132,8 @@ export const HTTP2_BRIDGE_SERVER_OPTIONS: http2.ServerOptions = { * total, so no combination of concurrent streams, across every route, can * retain more than this many bytes at once. This value keeps the accepted * process ceiling at 1,073,741,824 bytes (1 GiB) — the same ceiling - * `doc/observability.md` already accepted before the per-body limit rose to - * 10 MiB — now enforced by this reservation instead of left as an unenforced - * document note. See the per-route budget comment above for the full + * the project already accepted before the per-body limit rose to 10 MiB — + * now enforced by this reservation instead of left as an unenforced note. See the per-route budget comment above for the full * accounting. */ export const HTTP2_BRIDGE_MAX_PROCESS_BODY_BYTES = 1024 * 1024 * 1024; diff --git a/packages/shared/src/telemetry/README.md b/packages/shared/src/telemetry/README.md index e792827b9f1..28125b5ab54 100644 --- a/packages/shared/src/telemetry/README.md +++ b/packages/shared/src/telemetry/README.md @@ -126,9 +126,8 @@ This document covers Paperclip Telemetry only. The generated Telemetry contract covers neither the Observability path nor the run-log path. Two other data paths document their own contract in their own file: -- [Observability](../../../../doc/observability.md) — the OpenTelemetry trace - path, the sandbox startup trace spans, and the sandbox duplex transport - instrumentation. +- [Observability](../../../../doc/observability.md) — the operator-enabled + OpenTelemetry trace path and Sentry error monitoring. - [Run-Log Events](../../../../doc/run-log-events.md) — events written to the local `heartbeat_run_events` table. diff --git a/rules/data-paths.mdc b/rules/data-paths.mdc index 0d3f28ca3c6..202c3732a51 100644 --- a/rules/data-paths.mdc +++ b/rules/data-paths.mdc @@ -49,10 +49,10 @@ Apply a review level that matches the path: - **Observability change (lighter review).** The operator endpoint gate stays in place. The no-operation behaviour stays when no endpoint is set. A privacy review is not necessary while the change stays inside the closed - span-attribute allowlist. + span-attribute allowlist defined in the code that opens the span. - **Run-log change (no extra review).** A run-log change needs neither review - level above, because the data stays in the instance database. Update - `doc/run-log-events.md` when an event is added or changed. + level above, because the data stays in the instance database. Define the + event and its payload where it is written; do not list it in a doc. ## Exclusion diff --git a/tests/runner-e2e/SUITES.md b/tests/runner-e2e/SUITES.md index f0b94e468f4..e1ec469dd01 100644 --- a/tests/runner-e2e/SUITES.md +++ b/tests/runner-e2e/SUITES.md @@ -1861,7 +1861,7 @@ Results can include a `startupReuse` entry for each run. The dashboard shows receipt-derived warmth, the environment/lease, workspace, Runner, provider process and session decisions, and observed provider launches. Private attempt evidence includes `snapshots/startup-reuse.json`. See the -[run-log contract](../../doc/run-log-events.md#startup-reuse-evidence) for the +[startup reuse receipt](../../packages/adapter-utils/src/startup-reuse.ts) for the closed states and reasons. Historical runs without receipts show unknown values. Provider-session continuity does not establish physical process reuse. diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 980f64e64ff..a34d5f70074 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -351,7 +351,7 @@ "packages/shared/src/slack-tools.ts": "c53a75cd3099c6d8dcd1475e755aae589d4c88f6", "packages/shared/src/subscriptions.ts": "ef70e63395ca967bbc30776b71560e96eb354a75", "packages/shared/src/summary-slot.test.ts": "5f8e222dea425f0d5bff0adb5c683087bd7cf7fb", - "packages/shared/src/telemetry/README.md": "e792827b9f1e629ccdb66eecaad014cd02e532e8", + "packages/shared/src/telemetry/README.md": "28125b5ab542abc46c4bb6c044636a093f13584f", "packages/shared/src/telemetry/client-types.test.ts": "3b630edda4972b929ba4decd7457f226eb9cfc5b", "packages/shared/src/telemetry/client.test.ts": "3ba900cdab5a1ac1dcc1dcea382bb790af32d895", "packages/shared/src/telemetry/client.ts": "03a10a5550b542487543fbfd4a417e6eb316e11e", From d14a3b88b188cf5eee0e44c826facead8221062b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:09:32 -0600 Subject: [PATCH 07/20] fix(native): release an idle warm session whose Runner is proven gone, and retry a failed idle close (#21782) 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 warm agent session keeps its Runner alive in a sandbox between turns. The server closes idle sessions, and closes them again before it exits. > - When an idle close failed, the idle-timer path kept the session registered and never tried again, unless the sandbox lease was already inactive. > - The controller-restart path tried once more, but it accepted no proof that the session was already gone. It checked a destroyed sandbox only for a forced environment delete. > - In a release-swap test, one idle close failed with `runner_remote_process_identity_unavailable`. The session stayed registered until shutdown, the shutdown close failed again, and the sandbox was held until the host stopped it. > - This pull request treats a failed close as complete when the Runner is proven gone or the sandbox is stopped or destroyed, retries a failed idle close a bounded number of times, and logs which Runner check failed. > - The benefit is that a dead warm session is released, and the next failure names its cause. ## Linked Issues or Issue Description Refs #21627 **What happened?** In a zero-downtime release-swap test, a warm session's idle close failed 4 s after the server left new run starts. The failure was `runner_remote_process_identity_unavailable`. The idle-timer path kept the session registered with no retry. At SIGTERM, `closeIdleWarmNativeSessionsForRestart` tried again and failed the same way. The log showed "idle warm native sessions did not close" and the restart-chaos harness counted a warm-shutdown failure. The log did not say which Runner check failed, so the cause of the unreadable identity is not known. **Expected behavior** A close whose Runner is proven gone, or whose sandbox is stopped or destroyed, releases the session. A failed idle close is tried again a bounded number of times. The failure text names the Runner check stage and reason. **Steps to reproduce** 1. Keep a warm remote session idle. 2. Make its close fail with a `RemoteRunnerRecoveryError` (for example, `process_verification/process_not_running`). 3. Call `closeIdleWarmNativeSessionsForRestart()`. On master the result is `failed: 1`. ## What Changed - `server/src/services/native-runtime/native-session-executor.ts`: - New `warmCloseFailureProvesOwnerGone`. It uses existing proofs only: the close error's Runner diagnostic is `process_verification/process_not_running`, or a lease row for the sandbox has a termination receipt (`hasRemoteTerminationReceipt`) with state `destroyed`, or the warm run's own lease row has a receipt with state `stopped`. `pending_cleanup` and a lease without a receipt prove nothing. A lease read error counts as no proof. - `closeIdleWarmNativeSessions` (controller restart, environment delete, idle sleep) uses this proof for every failed close, not only for a forced environment delete. A released Runner detach failure is unchanged. - The idle-timer path uses the same proof. Its earlier status-only rule from #21504 (any lease status other than `active` or `retained`) is removed, because `pending_cleanup` is written before the provider stop. Without proof, it re-arms the timer and tries again, every 5 s, at most 3 times (`WARM_IDLE_CLOSE_RETRY_MS`, `WARM_IDLE_CLOSE_MAX_RETRIES`). The log line records the attempt number. - `describeWarmCloseFailure` appends the Runner check as `[stage/reason/lifecycle]` when the error carries one. - `server/src/services/native-runtime/native-session-executor.test.ts`: three tests. - "an idle warm session whose close fails with runner_remote_process_identity_unavailable and whose Runner is proven gone is released at controller restart" - "names the Runner check in a warm close failure and keeps an unproven owner registered at controller restart" - "retries a failed idle warm close a bounded number of times" - The #21504 idle-path test is now "forgets a warm owner whose idle close failed only once its sandbox has a stop or destroy receipt". A stop or destroy receipt releases the owner. `pending_cleanup`, `released` without a receipt, and `retained` keep it. - "reads the warm owner's own lease rows at controller restart" (a stop receipt for this run releases the owner; `pending_cleanup`, no receipt, or another run's receipt do not) ## Verification - `cd server && npx vitest run src/services/native-runtime/native-session-executor.test.ts`: 1519 passed, 7 skipped. - Red on master (with only the two exported constants added so the file compiles): all three new tests fail. The first fails with `"failed": 1`. - `npx tsc --noEmit -p server`: no errors. ## Risks - A session is released without a checkpoint only when its Runner is proven gone or its sandbox is stopped or destroyed. The last saved checkpoint stays the recovery source, which is the same as the forced environment delete path today. - Environment delete and idle sleep now also accept the proof. Before, they accepted only a destroyed receipt during a forced delete. `pending_cleanup` is written before the provider stop, so it never counts as proof here. - The idle retry adds at most 3 more close attempts per failed session, 5 s apart. - A failed idle close whose sandbox stop is still pending now keeps its owner until a receipt lands or a successor retires it. Before, the status alone released it. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used in Claude Code with tool use (shell, file edit) and extended thinking. ## 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 --- .../native-session-executor.test.ts | 136 +++++++++++++++++- .../native-runtime/native-session-executor.ts | 70 +++++---- 2 files changed, 170 insertions(+), 36 deletions(-) diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 8e463045596..c0011b7afc0 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -434,6 +434,8 @@ import { nativeSessionWorkspaceScope, reserveWarmNativeInstructionDirectory, closeIdleWarmNativeSessionsForRestart, + WARM_IDLE_CLOSE_MAX_RETRIES, + WARM_IDLE_CLOSE_RETRY_MS, readNativeSessionIdleWork, createGovernedWaitEventObservation, createRemoteRunnerProcessLauncher, @@ -11614,10 +11616,12 @@ describe("native warm session supervision", () => { }); it.each([ - { lease: "pending_cleanup", forgotten: true }, - { lease: "released", forgotten: true }, + { lease: "stopped-receipt", forgotten: true }, + { lease: "destroyed-receipt", forgotten: true }, + { lease: "pending_cleanup", forgotten: false }, + { lease: "released", forgotten: false }, { lease: "retained", forgotten: false }, - ])("forgets a warm owner whose idle close failed only once the host gave up its sandbox: $lease", async ({ lease, forgotten }) => { + ])("forgets a warm owner whose idle close failed only once its sandbox has a stop or destroy receipt: $lease", async ({ lease, forgotten }) => { const identity = `warm-idle-close-sandbox-${lease}`; const warmExecution = { ...execution, binding: { ...execution.binding, runId: identity, executionWorkspaceId: `${identity}-workspace` }, session: { ...execution.session, normalizedSessionId: identity, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 50 } }, @@ -11632,7 +11636,7 @@ describe("native warm session supervision", () => { }); const copy = (runId: string) => ({ runId, root: `/tmp/${identity}`, preparationKey: "same", hasChanges: async () => false, collectStopped: async () => undefined, retirementFailed: async () => undefined }); - let leaseRows: Array<{ status: string }> = []; + let leaseRows: Array> = []; const base = leaseDb(warmExecution); const db = { ...base, select: (fields?: unknown) => ({ from: (table: unknown) => table === environmentLeases ? { where: async () => leaseRows } : base.select(fields as never).from(table as never) }) } as unknown as Db; @@ -11641,7 +11645,14 @@ describe("native warm session supervision", () => { runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId: identity, remoteCwd: `/tmp/${identity}`, sandboxLeaseAcquisition: { providerLeaseId: `${identity}-sandbox` } } as never, instructionWorkingCopy: copy(identity) }); - leaseRows = [{ status: lease }]; + const receipt = lease.endsWith("-receipt") ? lease.slice(0, -"-receipt".length) : null; + leaseRows = [{ id: `${identity}-lease`, companyId: warmExecution.binding.companyId, environmentId: identity, + heartbeatRunId: identity, provider: "daytona", providerLeaseId: `${identity}-sandbox`, + status: receipt ? "released" : lease, releasedAt: lease === "retained" ? null : new Date(), + cleanupStatus: receipt || lease === "released" ? "success" : "failed", leasePolicy: "reuse_by_environment", + metadata: receipt ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", + companyId: warmExecution.binding.companyId, runId: identity, leaseId: `${identity}-lease`, provider: "daytona", + providerLeaseId: `${identity}-sandbox`, state: receipt, confirmedAt: new Date().toISOString() } } : {} }]; await vi.waitFor(() => expect(session.close).toHaveBeenCalledTimes(1)); const followUpRunId = `${identity}-follow-up`; const adopt = vi.fn(async () => null); @@ -12197,6 +12208,79 @@ describe("native warm session supervision", () => { expect(collectStopped).toHaveBeenCalledOnce(); }); + it("an idle warm session whose close fails with runner_remote_process_identity_unavailable and whose Runner is proven gone is released at controller restart", async () => { + const name = "warm-close-runner-gone"; + const current = { ...execution, + binding: { ...execution.binding, runId: name, executionWorkspaceId: name }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } }, + } as NativeExecutionInputV1; + const close = vi.fn<() => Promise>(async () => { + throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "process_not_running" }); + }); + state.execute.mockReset().mockImplementationOnce(async options => { + await options.onSession?.({ close }); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, + turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", + nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + await expect(executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name })) + .resolves.toMatchObject({ exitCode: 0 }); + expect(close).not.toHaveBeenCalled(); + expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] }); + expect(close).toHaveBeenCalledOnce(); + expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] }); + }); + + it("names the Runner check in a warm close failure and keeps an unproven owner registered at controller restart", async () => { + const name = "warm-close-marker-missing"; + const current = { ...execution, + binding: { ...execution.binding, runId: name, executionWorkspaceId: name }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } }, + } as NativeExecutionInputV1; + const close = vi.fn<() => Promise>(async () => { + throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "marker_missing" }); + }); + state.execute.mockReset().mockImplementationOnce(async options => { + await options.onSession?.({ close }); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, + turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", + nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name }); + expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, failed: 1, failures: [{ runId: name, + reason: "close failed: runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/marker_missing]" }] }); + close.mockResolvedValue(undefined); + expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1, failed: 0 }); + }); + + it("retries a failed idle warm close a bounded number of times", async () => { + const name = "warm-idle-close-retry"; + const current = { ...execution, + binding: { ...execution.binding, runId: name, executionWorkspaceId: name }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 20 } }, + } as NativeExecutionInputV1; + const close = vi.fn<() => Promise>(async () => { throw new Error("native_runner_checkpoint_owner_lost"); }); + state.execute.mockReset().mockImplementationOnce(async options => { + await options.onSession?.({ close }); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, + turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", + nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name }); + await vi.advanceTimersByTimeAsync(20); + expect(close).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(WARM_IDLE_CLOSE_RETRY_MS); + expect(close).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(WARM_IDLE_CLOSE_RETRY_MS * 10); + expect(close).toHaveBeenCalledTimes(1 + WARM_IDLE_CLOSE_MAX_RETRIES); + expect(readNativeSessionIdleWork()).toBe("present"); + } finally { vi.useRealTimers(); } + close.mockResolvedValue(undefined); + expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1, failed: 0 }); + }); + it.each(["failed", "cancelled"] as const)("retires a %s session even if its warm checkpoint rejects", async (runTerminalState) => { const name = `warm-checkpoint-rejects-${runTerminalState}`; const current = { ...execution, @@ -13245,6 +13329,48 @@ describe("native warm session supervision", () => { }, ); + it.each([ + { lease: "released-stop-receipt", closed: 1 }, + { lease: "pending_cleanup", closed: 0 }, + { lease: "released-without-receipt", closed: 0 }, + { lease: "stop-receipt-for-another-run", closed: 0 }, + ] as const)("reads the warm owner's own lease rows at controller restart: $lease", async ({ lease: kind, closed }) => { + const { base } = fixture(`restart-lease-${kind}`); + const environmentId = `restart-lease-env-${kind}`, providerLeaseId = `restart-lease-sandbox-${kind}`; + const close = vi.fn(async (): Promise => { throw new Error("owned close not yet confirmed"); }); + state.execute.mockReset().mockImplementationOnce(async options => { + await options.onSession?.({ close }); return result; + }); + const leaseRunId = kind === "stop-receipt-for-another-run" ? "earlier-run" : base.binding.runId; + const terminal = kind !== "pending_cleanup"; + const row = { id: `lease-${kind}`, companyId: base.binding.companyId, environmentId, heartbeatRunId: leaseRunId, + provider: "daytona", providerLeaseId, status: terminal ? "released" : "pending_cleanup", releasedAt: new Date(), + cleanupStatus: terminal ? "success" : "failed", leasePolicy: "reuse_by_environment", + metadata: kind === "released-stop-receipt" || kind === "stop-receipt-for-another-run" + ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId: base.binding.companyId, + runId: leaseRunId, leaseId: `lease-${kind}`, provider: "daytona", providerLeaseId, state: "stopped", + confirmedAt: new Date().toISOString() } } + : { failureReason: "sandbox_stop_pending" } }; + let leaseRows: unknown[] = []; + const ownerDb = leaseDb(base), select = ownerDb.select.bind(ownerDb); + ownerDb.select = ((fields?: Record) => ({ from: (table: unknown) => { + if (table !== environmentLeases) return select(fields as never).from(table as never); + const query = { then: (...args: Parameters["then"]>) => Promise.resolve(leaseRows).then(...args), + where: () => query, limit: () => query }; + return query; + } })) as unknown as Db["select"]; + try { + await executePaperclipNativeSession({ db: ownerDb, execution: base, runnerInstanceId: "runner", + runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId, remoteCwd: `/tmp/${environmentId}`, + sandboxLeaseAcquisition: { outcome: "created", providerLeaseId } } }); + leaseRows = [row]; + expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed, failed: 1 - closed }); + } finally { + close.mockResolvedValue(undefined); + await closeIdleWarmNativeSessionsForRestart(); + } + }); + it("retains failed retirement for retry and never launches over an uncontained owner", async () => { const { base, next, run } = fixture("identity-close-failure"); const close = vi.fn().mockRejectedValueOnce(new Error("containment unavailable")).mockResolvedValue(undefined); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index cffe9cd56c0..26badf5ba56 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -743,12 +743,15 @@ type WarmNativeSession = { controllerDetachedForRestart?: boolean; finishRelease?: () => Promise; closeOnReleaseReason?: string; + idleCloseRetries?: number; idleTimer: ReturnType | null; lastActivityAt: string; }; const WARM_CLOSE_FAILURE_DETAIL_MAX = 2_000; const WARM_NATIVE_SESSION_CLOSE_CONCURRENCY = 4; +export const WARM_IDLE_CLOSE_RETRY_MS = 5_000; +export const WARM_IDLE_CLOSE_MAX_RETRIES = 3; export function describeWarmCloseFailure(error: unknown): string { const describe = (value: unknown): string => { @@ -757,8 +760,10 @@ export function describeWarmCloseFailure(error: unknown): string { const code = "code" in value && typeof value.code === "string" ? `${value.code}: ` : ""; const settlement = value instanceof NativeSessionCloseUnrecoverableError && value.settlement ? ` ${JSON.stringify(value.settlement)}` : ""; + const remote = readRemoteRunnerRecoveryError(value); + const recovery = remote ? ` [${remote.stage}/${remote.reason}${remote.runnerLifecycle ? `/${remote.runnerLifecycle}` : ""}]` : ""; const cause = value.cause === undefined ? "" : ` (cause: ${describe(value.cause)})`; - return `${code}${value.message}${settlement}${cause}`; + return `${code}${value.message}${recovery}${settlement}${cause}`; }; const text = describe(error).replaceAll(/[\r\n]+/g, " "); return text.length > WARM_CLOSE_FAILURE_DETAIL_MAX ? `${text.slice(0, WARM_CLOSE_FAILURE_DETAIL_MAX)}…` : text; @@ -1107,17 +1112,7 @@ export async function closeWarmNativeSessionsForEnvironment(input: { return closeIdleWarmNativeSessions(input); } -async function warmSandboxGivenUpByHost(entry: WarmNativeSession): Promise { - if (!entry.sandboxLeaseDb || !entry.providerLeaseId || !entry.environmentId) return false; - const leases = await entry.sandboxLeaseDb.select({ status: environmentLeases.status }).from(environmentLeases).where(and( - eq(environmentLeases.companyId, entry.companyId), - eq(environmentLeases.environmentId, entry.environmentId), - eq(environmentLeases.providerLeaseId, entry.providerLeaseId), - )); - return leases.length > 0 && leases.every(lease => lease.status !== "active" && lease.status !== "retained"); -} - -async function warmSandboxDestroyed(db: Db, entry: WarmNativeSession): Promise { +async function warmSandboxTerminated(db: Db, entry: WarmNativeSession): Promise { if (!entry.providerLeaseId || !entry.environmentId) return false; const leases = await db.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, entry.companyId), @@ -1125,8 +1120,23 @@ async function warmSandboxDestroyed(db: Db, entry: WarmNativeSession): Promise resolveRemoteTerminationLease(db, lease))); - return resolved.some(lease => hasRemoteTerminationReceipt(lease) - && (lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined)?.state === "destroyed"); + return resolved.some(lease => { + if (!hasRemoteTerminationReceipt(lease)) return false; + const state = (lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined)?.state; + return state === "destroyed" || (state === "stopped" && lease.heartbeatRunId === entry.runId); + }); +} + +/** A failed close is complete when its Runner is proven gone, its sandbox is destroyed, or the run's own sandbox lease has a stop receipt. */ +async function warmCloseFailureProvesOwnerGone(entry: WarmNativeSession, error: unknown, db = entry.sandboxLeaseDb): Promise { + const diagnostic = readRemoteRunnerRecoveryError(error); + if (diagnostic?.stage === "process_verification" && diagnostic.reason === "process_not_running") return true; + try { + return db ? await warmSandboxTerminated(db, entry) : false; + } catch (proofError) { + logger.warn({ err: proofError, runId: entry.runId }, "could not read the warm session's sandbox lease"); + return false; + } } /** Detach released owners and checkpoint unreleased owners before a controller @@ -1195,16 +1205,10 @@ async function closeIdleWarmNativeSessions(input: { busy += 1; return; } - const destroyed = !detach && input.forceStopUnsettled && input.db - ? await warmSandboxDestroyed(input.db, entry).catch(proofError => { - logger.warn({ err: proofError, runId: entry.runId }, "could not read the warm session's sandbox lease"); - return false; - }) - : false; - if (destroyed) { + if (!detach && await warmCloseFailureProvesOwnerGone(entry, error, input.db ?? entry.sandboxLeaseDb)) { logger.warn({ runId: entry.runId, issueId: entry.issueId, environmentId: entry.environmentId, providerLeaseId: entry.providerLeaseId ?? null, reason: input.reason, closeFailure: describeWarmCloseFailure(error) }, - "warm native session's sandbox was already destroyed; released its owner"); + "warm native session's Runner or sandbox is gone; released its owner"); forgetWarmNativeSession(sessionId, entry); closed += 1; return; @@ -8860,17 +8864,21 @@ function armWarmNativeSessionIdleTimer( return; } logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId, - providerLeaseId: current.providerLeaseId ?? null, closeFailure: describeWarmCloseFailure(error) }, + providerLeaseId: current.providerLeaseId ?? null, closeFailure: describeWarmCloseFailure(error), + closeAttempt: (current.idleCloseRetries ?? 0) + 1 }, released ? "idle warm native session detach failed" : "idle warm native session close failed"); if (released) return; - return warmSandboxGivenUpByHost(current).then(givenUp => { - if (!givenUp) return; - logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId, - providerLeaseId: current.providerLeaseId ?? null }, - "warm native session's sandbox was stopped by the host; released its owner"); - forgetWarmNativeSession(sessionId, current); - }, proofError => { - logger.warn({ err: proofError, runId: current.runId }, "could not read the warm session's sandbox lease"); + return warmCloseFailureProvesOwnerGone(current, error).then(gone => { + if (gone) { + logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId, + providerLeaseId: current.providerLeaseId ?? null }, + "warm native session's Runner or sandbox is gone; released its owner"); + forgetWarmNativeSession(sessionId, current); + return; + } + if ((current.idleCloseRetries ?? 0) >= WARM_IDLE_CLOSE_MAX_RETRIES) return; + current.idleCloseRetries = (current.idleCloseRetries ?? 0) + 1; + armWarmNativeSessionIdleTimer(sessionId, current, WARM_IDLE_CLOSE_RETRY_MS); }); }) .finally(() => { From 7a9177af0f5aa9cf925e9d40723944e39723cd7b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:13:19 -0600 Subject: [PATCH 08/20] test(runner): remove coreutils and pid-file timing assumptions from static checks (#21787) 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 Paperclip Runner package has a "static checks" CI job that runs `node --test` script tests > - Two of these tests failed on unrelated pull requests on 2026-11-15 and passed on re-run > - Each failure costs a re-run of the failed jobs and delays merges, and it teaches people to re-run instead of read > - One test assumed that a copied `/bin/sleep` acts as `sleep` under any name. The other read a pid file before the child finished writing it > - This pull request removes both assumptions, and one more instance of the second pattern in the same test family > - The benefit is that these tests no longer depend on the runner image or on process scheduling ## Linked Issues or Issue Description **What happened?** 1. `scripts/stage-runner-binary.test.mjs` failed in "ci / Verify Paperclip Runner (static checks)" on PR #21765, head `98197c87e9`, job 132850068174: - `atomically publishes while the previous executable is running`: `AssertionError: 1 !== null` at line 124 (`old.child.exitCode`), after 77 ms. - `a source rebuild selects fresh dev bytes ...`: `Expected "actual" not to be strictly deep-equal` (line 192). - That job ran on a GitHub-hosted `ubuntu-26.04` image (20261111.82.6). The same tests pass on the RunsOn `ubuntu24` image, for example job 132822472729. 2. `scripts/materialize-kimi-distribution.test.mjs` › `setup cancellation physically stops an in-flight owned child` failed in the same job on PR #21758, head `40e38fc28a`, job 132822472729: `AssertionError: The real child did not start` after 149 ms. **Expected behavior** The tests pass on every supported runner image and on a loaded runner. **Steps to reproduce** 1. stage-runner-binary: in a Linux container, replace `/bin/sleep` and `/bin/echo` with one multicall binary that picks the utility from `argv[0]` and exits 1 for an unknown name (this is how uutils coreutils works on Ubuntu 26.04). Run `node --test scripts/stage-runner-binary.test.mjs`. On `master` both tests fail with the CI messages, 20 of 20 runs. 2. kimi: make the child create the pid file, wait 300 ms, then write the pid. On `master` the test fails with `The real child did not start` in about 125 ms, the same as CI. **Root cause** 1. On Ubuntu 26.04, `/bin/sleep` and `/bin/echo` are the same uutils multicall binary. The test copies it to `paperclip-runnerd` and runs it. The binary sees `argv[0] = paperclip-runnerd`, finds no utility of that name, and exits 1. The fresh-build fixture (a copy of `echo`) also has the same bytes as the old artifact (a copy of `sleep`), so the "fresh bytes" assertion fails too. 2. The child wrote the pid with `writeFileSync`, which creates the file and then writes it. The test loop broke on the first successful read. An empty read gave `Number("") === 0`, so the loop stopped and the assertion failed. The loop also had a fixed budget of 100 polls of 10 ms for a Node child to start. **Production impact** None. Only tests change. The staging code works with any executable. The Kimi setup cancellation code is correct: the deterministic repro shows that the child is stopped once the test reads a real pid. ## What Changed - `stage-runner-binary.test.mjs`: the test helper passes `argv0` to `spawn`. The copied `sleep` runs with `argv0: "sleep"`, so a multicall binary still acts as `sleep`. The fresh-build fixture is now a copy of `/bin/sh` and runs `-c "exit 0"`, so its bytes always differ from the old `sleep` artifact. - `materialize-kimi-distribution.test.mjs`: the child writes `pid.tmp` and renames it to `pid`, so a read never sees a partial file. The test waits until the pid is valid or the command settles. The 3 s command timeout and 5 s test timeout are unchanged. - `provision-kimi-package.test.mjs`: the wait for the `download-ready` marker continues until the child exits, instead of a fixed 1 s budget. The existing 5 s kill timer still bounds it. - No retries, skips or timeout changes. ## Verification - stage-runner-binary, Linux container (`node:24-bookworm-slim`) with a multicall `sleep`/`echo` built from a 15-line Go program that dispatches on `argv[0]`: - `master`: 0/20 pass, same two assertions as CI. - this branch: 50/50 pass. - this branch with stock coreutils, and on macOS: all 9 tests pass. - kimi setup cancellation: - delayed-write repro: `master` fails, this branch passes. - loop on macOS, `master` test without extra load: 59/60 (one natural failure). This branch: 60/60. - loop with 4 extra busy-loop processes (load average about 13 before them): `master` 100/100, this branch 100/100. - `node --test scripts/stage-runner-binary.test.mjs scripts/materialize-kimi-distribution.test.mjs scripts/provision-kimi-package.test.mjs`: 19 pass, 1 skipped (public download test, opt-in). - The other CI flake from the same day, `runnerd-codex-transport-orphaned-tool-at-attach.test.ts`, is a Runner defect. It is fixed in a separate pull request. ## Risks - Low risk. Only tests change. - The rebuild test now uses `/bin/sh` as the fixture for the fresh build. This file exists on every supported Linux and macOS runner. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, GitHub CLI, Docker). ## 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 --- .../scripts/materialize-kimi-distribution.test.mjs | 12 +++++++----- .../scripts/provision-kimi-package.test.mjs | 2 +- .../scripts/stage-runner-binary.test.mjs | 14 +++++++------- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/packages/paperclip-runner/scripts/materialize-kimi-distribution.test.mjs b/packages/paperclip-runner/scripts/materialize-kimi-distribution.test.mjs index a3adb002918..0bd816430a9 100644 --- a/packages/paperclip-runner/scripts/materialize-kimi-distribution.test.mjs +++ b/packages/paperclip-runner/scripts/materialize-kimi-distribution.test.mjs @@ -39,12 +39,14 @@ test("distribution build admits network settings without provider keys or Node i test("setup cancellation physically stops an in-flight owned child", { timeout: 5_000 }, async t => { const { root } = await fixture(t), pidFile = join(root, "pid"); const controller = new AbortController(); - const result = runKimiBuildCommand(process.execPath, ["-e", "require('node:fs').writeFileSync(process.argv[1],String(process.pid));setInterval(()=>{},1000)", pidFile], { env: {}, timeout: 3_000 }, undefined, controller.signal).then(() => null, error => error); - let pid; + const result = runKimiBuildCommand(process.execPath, ["-e", "const f=require('node:fs');f.writeFileSync(process.argv[1]+'.tmp',String(process.pid));f.renameSync(process.argv[1]+'.tmp',process.argv[1]);setInterval(()=>{},1000)", pidFile], { env: {}, timeout: 3_000 }, undefined, controller.signal).then(() => null, error => error); + let pid, settled = false; + void result.then(() => { settled = true; }); try { - for (let attempt = 0; attempt < 100; attempt++) { - try { pid = Number(await readFile(pidFile, "utf8")); break; } - catch (error) { if (error.code !== "ENOENT") throw error; await delay(10); } + while (!settled && !(Number.isSafeInteger(pid) && pid > 0)) { + try { pid = Number(await readFile(pidFile, "utf8")); } + catch (error) { if (error.code !== "ENOENT") throw error; } + await delay(10); } assert.ok(Number.isSafeInteger(pid) && pid > 0, "The real child did not start"); controller.abort(); diff --git a/packages/paperclip-runner/scripts/provision-kimi-package.test.mjs b/packages/paperclip-runner/scripts/provision-kimi-package.test.mjs index acd9f190df9..e9ae78dfa81 100644 --- a/packages/paperclip-runner/scripts/provision-kimi-package.test.mjs +++ b/packages/paperclip-runner/scripts/provision-kimi-package.test.mjs @@ -54,7 +54,7 @@ test("installed Kimi setup is self-contained, rejects corrupt assets and cancels let stderr = ""; cancelled.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-4096); }); const kill = setTimeout(() => cancelled.kill("SIGKILL"), 5_000); try { - for (let attempt = 0; attempt < 100; attempt++) { + while (cancelled.exitCode === null && cancelled.signalCode === null) { try { if (await readFile(ready, "utf8") === "ready") break; } catch (error) { if (error.code !== "ENOENT") throw error; } await delay(10); diff --git a/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs b/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs index e262d64a213..2127a9d1842 100644 --- a/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs +++ b/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs @@ -86,8 +86,8 @@ test("release metadata rejects incompatible native, harness and protocol contrac async function withOwnedChildren(root, action) { const owned = []; - const start = (command, args) => { - const child = spawn(command, args, { env: { PATH: "/usr/bin:/bin" }, stdio: "ignore" }); + const start = (command, args, argv0) => { + const child = spawn(command, args, { argv0, env: { PATH: "/usr/bin:/bin" }, stdio: "ignore" }); // close follows both exit and spawn error. A failed second spawn must not // interrupt retirement of the first still-running executable. const closed = new Promise(resolve => child.once("close", resolve)); @@ -115,7 +115,7 @@ test("atomically publishes while the previous executable is running", { skip: pr await withOwnedChildren(root, async start => { await stageRunnerBinary("/bin/sleep", destination); const previous = await stat(destination); - const old = start(destination, ["30"]); + const old = start(destination, ["30"], "sleep"); await old.spawned; await stageRunnerBinary("/bin/sleep", destination); const published = await stat(destination); @@ -124,7 +124,7 @@ test("atomically publishes while the previous executable is running", { skip: pr assert.equal(old.child.exitCode, null); assert.equal(old.child.signalCode, null); assert.deepEqual(await readdir(root), ["paperclip-runnerd"]); - const next = start(destination, ["0"]); + const next = start(destination, ["0"], "sleep"); await next.spawned; await next.closed; assert.equal(next.child.exitCode, 0); }); @@ -150,7 +150,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries await mkdir(path.dirname(source), { recursive: true }); await writeFile(source, "fn main() {}\n"); await mkdir(path.dirname(built), { recursive: true }); - await copyHostFixture("/bin/echo", built); + await copyHostFixture("/bin/sh", built); const previousBuild = path.join(root, "previous-build"); await copyHostFixture("/bin/sleep", previousBuild); await stageRunnerBinary(previousBuild, hostTarget); @@ -178,7 +178,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries const manifestPath = path.join(binaryRoot, "release-manifest.json"); const manifest = JSON.stringify({ schema: "paperclip.runner.release-binaries.v1", sourceRevision: "a".repeat(40), platforms }); await writeFile(manifestPath, manifest); - const old = start(hostTarget, ["30"]); + const old = start(hostTarget, ["30"], "sleep"); await old.spawned; const requirement = { repoRoot: root, nativeRunnerRequired: true }; assert.equal(paperclipRunnerBinaryNeedsBuild(requirement), true); @@ -198,7 +198,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries assert.equal(paperclipRunnerBinaryNeedsBuild(requirement), false); assert.equal(old.child.exitCode, null); assert.equal(old.child.signalCode, null); - const next = start(selected.binary, ["rebuilt"]); + const next = start(selected.binary, ["-c", "exit 0"]); await next.spawned; await next.closed; assert.equal(next.child.exitCode, 0); }); From 46e5e4450ffada4826775a8336ef6f33ae8ef345 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:27:04 -0600 Subject: [PATCH 09/20] fix(runner): leave an undispatched tool call to the next controller on restart detach (#21786) 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 Paperclip Runner keeps an agent session alive while its controller restarts, for example during a deploy, and the next controller adopts it > - A Paperclip tool call can be between its committed input and its handler when the controller detaches > - In that window the old controller journaled "The turn stopped before this operation was dispatched" as the final, non-retryable result, but the turn did not stop > - The agent then got a false failure for a call that never ran, and the next controller could not recover the call. A restart must never fail work > - This pull request leaves that call unsettled for the next controller, the same as a call that was already in its handler > - The benefit is that a controller restart no longer turns an agent's pending tool call into a permanent error, and a CI test that failed on four pull requests now passes deterministically ## Linked Issues or Issue Description **What happened?** `src/live/runnerd-codex-transport-orphaned-tool-at-attach.test.ts` › `settles an earlier generation's in-flight tool call at attach even when that attach never finishes startup` failed in "ci / Verify Paperclip Runner (vitest package (3/3))" on 2026-11-15. In each job the first try and the CI retry both failed: - PR #21757, head `d04825d812`, job 132824209377 - PR #21713, head `7758d56719`, job 132681892394 - PR #21729, head `c63a05a013`, job 132732839971 Every failure is the same, at line 74, right after `detachControllerForRestart()`: ``` AssertionError: expected [ { …(8) } ] to deeply equal [] + "type": "semantic_tool.result", "status": "pending", + "result": { "error": { "code": "semantic_tool_not_dispatched", + "message": "The turn stopped before this operation was dispatched.", "retryable": false } } ``` **Expected behavior** When a controller detaches for restart, a tool call that it has not dispatched stays unsettled. The next controller recovers it at attach, the same as a call that is in its handler. **Steps to reproduce** 1. Hold the semantic tool dispatch at a gate after the Runner commits the tool input. 2. Call `detachControllerForRestart()`, then release the gate. 3. On `master`, the control-plane state has the `semantic_tool_not_dispatched` result above. It is byte-identical to CI (same command id and payload). The new test case `(still before dispatch at detach)` does this. **Root cause** This is a Runner defect, not a test timing problem. `#detachControllerOnce` sets `#closed`, resolves the closed signal and resolves the turn-start admission with `false`. A call in `#handleSemanticToolInput` that has not reached the handler then throws `SemanticToolNotDispatchedError`. The durable control plane turns that error into a journaled `semantic_tool_not_dispatched` result. That result is correct when the turn stops. It is false when the controller only detaches for restart, because the Runner and the turn continue. The old test waited only for the committed input, so on a loaded CI runner the detach sometimes came before the handler call. **Production impact** Yes. During a controller restart or deploy, an agent tool call in this window got a non-retryable "turn stopped" error after the Runner was adopted, and the next controller did not recover the call. ## What Changed - `durable-prp-control-plane.ts`: new `SemanticToolHandedOffError`. When the dispatcher rejects with it, the control plane journals no result. The input stays unsettled for the next controller. - `runnerd-codex-transport.ts`: the semantic tool callback goes through `#dispatchSemanticToolInput`. If the call ends as not dispatched after the transport detached for restart, it throws `SemanticToolHandedOffError`. A normal close still journals `semantic_tool_not_dispatched`. - `runnerd-codex-transport-orphaned-tool-at-attach.test.ts`: the test waits for the exact stage instead of the committed input. It runs two cases: the call is in its handler at detach, and the call is held before dispatch across the detach. Both then check the existing attach recovery and the final `completed` result. ## Verification - Red on `master`: the `(still before dispatch at detach)` case fails every run with the CI assertion and payload. - Green on this branch: `npx vitest run src/live/runnerd-codex-transport-orphaned-tool-at-attach.test.ts` passes 2/2. - Loop on macOS with 4 extra busy-loop processes (load average about 13 before them), 50 runs each: this branch 50/50 (100 test cases). The old `master` test was 50/50 locally too, so the local loop does not show the CI interleaving. The gate does. - All 36 runner test files that use `detachControllerForRestart` or `SemanticToolNotDispatchedError`: 1180/1182 pass with 3 workers under load. The 2 failures (`runnerd-codex-transport-settlement.test.ts` and `runnerd-acpx-source-reconciliation.test.ts`, `kill EPERM`) pass 36/36 when run alone. - `npx tsc -p tsconfig.json --noEmit` and `npx tsc -p tsconfig.test.json --noEmit` pass in `packages/paperclip-runner`. - The other two static-check flakes from the same day are test-only and are fixed in a separate pull request. ## Risks - Medium-low risk. This changes Runner restart behavior for one window. A call that was not dispatched now goes to the next controller's recovery (`recoverSemanticToolInput`) instead of getting a final error. That is the same path that already handles a call in its handler, so no new recovery code is involved. - If no successor ever attaches, the input stays unsettled. That is the same state as for a call that was in its handler at detach. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../durable-prp-control-plane.ts | 7 ++ ...-transport-orphaned-tool-at-attach.test.ts | 89 +++++++++++++++++-- .../src/live/runnerd-codex-transport.ts | 14 ++- 3 files changed, 101 insertions(+), 9 deletions(-) diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index 492e7534800..2ddf31f66b5 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -293,6 +293,12 @@ export class SemanticToolNotDispatchedError extends Error { } } +export class SemanticToolHandedOffError extends Error { + constructor() { + super("semantic_tool_handed_off"); + } +} + export interface DurablePrpControlPlaneOptions { stateDirectory: string; identity: DurableRecoveryIdentity; @@ -4798,6 +4804,7 @@ export class DurablePrpControlPlane { queueResult(outcome.result, outcome.isError === true), ) .catch((error: unknown) => { + if (error instanceof SemanticToolHandedOffError) return; if (error instanceof SemanticToolNotDispatchedError) { queueResult({ error: { code: "semantic_tool_not_dispatched", diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-orphaned-tool-at-attach.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-orphaned-tool-at-attach.test.ts index c946377453d..080305097ad 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport-orphaned-tool-at-attach.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-orphaned-tool-at-attach.test.ts @@ -3,7 +3,8 @@ import { createServer } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; -import { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js"; +import * as durableControlPlane from "../control-plane/durable-prp-control-plane.js"; +import type { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js"; import { recoverToolCallback, TOOL_CALLBACK_INTERRUPTED_CODE } from "../control-plane/orphaned-tool-callback.js"; import { createCapabilityRunnerdCodexTransport } from "./runnerd-codex-transport.js"; import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js"; @@ -12,7 +13,7 @@ const taskTool = { name: "get_task_context", description: "Read current task", i type SavedCommand = { commandId: string; type: string; status: string; payload: Record }; -it("settles an earlier generation's in-flight tool call at attach even when that attach never finishes startup", async () => { +it.each(["dispatched to its handler", "still before dispatch"] as const)("settles an earlier generation's in-flight tool call at attach even when that attach never finishes startup (%s at detach)", async stage => { const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-orphaned-tool-at-attach-")); const controlPlaneStatePath = join(stateDirectory, "control-plane", "control-plane-state.json"); const server = createServer(); @@ -55,8 +56,28 @@ it("settles an earlier generation's in-flight tool call at attach even when that const recovered = vi.fn(async (call: { operationId: string; callId: string; input: unknown; admission?: "this_controller" | "earlier_controller" }) => recoverToolCallback({ runId: identity.runId, call: { tool: call.operationId, callId: call.callId, arguments: call.input }, admission: call.admission, recover: async () => null })); + let reached!: () => void; + const callReached = new Promise(resolveReached => { reached = resolveReached; }); + let releaseDispatch!: () => void; + const dispatchGate = new Promise(resolveGate => { releaseDispatch = resolveGate; }); + let gatedOutcome: Promise | null = null; + const OriginalCore = durableControlPlane.DurablePrpControlPlane; + const coreSpy = vi.spyOn(durableControlPlane, "DurablePrpControlPlane").mockImplementation(function (coreOptions) { + const dispatch = coreOptions.onSemanticToolInput; + if (stage === "still before dispatch" && dispatch && !gatedOutcome) { + coreOptions = { ...coreOptions, onSemanticToolInput: call => { + reached(); + gatedOutcome = dispatchGate.then(() => dispatch(call)); + return gatedOutcome as ReturnType; + } }; + } + return new OriginalCore(coreOptions); + }); const first = createCapabilityRunnerdCodexTransport(options); - first.transport.setServerRequestHandler(() => new Promise>(() => undefined)); + first.transport.setServerRequestHandler(() => { + reached(); + return new Promise>(() => undefined); + }); const generations: Array> = []; let runnerPid: number | null = null; const savedToolResults = async () => (JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { commands: SavedCommand[] }) @@ -66,11 +87,11 @@ it("settles an earlier generation's in-flight tool call at attach even when that runnerPid = first.evidence().runnerPid; const runnerStartedAt = first.transport.processInfo!().startedAt; await first.transport.request("turn/start", { input: [{ type: "text", text: "Read current task" }] }); - await vi.waitFor(async () => { - const saved = JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { committedEvents: Array<{ eventType: string }> }; - expect(saved.committedEvents.some(event => event.eventType === "semantic_tool.input")).toBe(true); - }, { timeout: 10_000 }); + await callReached; await first.detachControllerForRestart(); + releaseDispatch(); + await (gatedOutcome as Promise | null)?.catch(() => undefined); + await new Promise(resolveTurn => setImmediate(resolveTurn)); expect(await savedToolResults()).toEqual([]); const adopt = (graceMs?: number) => { @@ -110,6 +131,8 @@ it("settles an earlier generation's in-flight tool call at attach even when that }, { timeout: 10_000 }); expect(recovered).toHaveBeenCalledTimes(1); } finally { + releaseDispatch(); + coreSpy.mockRestore(); for (const generation of generations.reverse()) await generation.transport.close().catch(() => undefined); await first.transport.close().catch(() => undefined); if (runnerPid) { @@ -120,3 +143,55 @@ it("settles an earlier generation's in-flight tool call at attach even when that await rm(stateDirectory, { recursive: true, force: true }); } }, 120_000); + +it("still settles a call stopped before dispatch as not dispatched when the controller closes without a restart", async () => { + const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-not-dispatched-at-close-")); + const controlPlaneStatePath = join(stateDirectory, "control-plane", "control-plane-state.json"); + let reached!: () => void; + const callReached = new Promise(resolveReached => { reached = resolveReached; }); + let releaseDispatch!: () => void; + const dispatchGate = new Promise(resolveGate => { releaseDispatch = resolveGate; }); + let gatedOutcome: Promise | null = null; + const OriginalCore = durableControlPlane.DurablePrpControlPlane; + const coreSpy = vi.spyOn(durableControlPlane, "DurablePrpControlPlane").mockImplementation(function (coreOptions) { + const dispatch = coreOptions.onSemanticToolInput; + if (dispatch && !gatedOutcome) { + coreOptions = { ...coreOptions, onSemanticToolInput: call => { + reached(); + gatedOutcome = dispatchGate.then(() => dispatch(call)); + return gatedOutcome as ReturnType; + } }; + } + return new OriginalCore(coreOptions); + }); + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: fakeCodex, + codexArgs: fakeCodexArgs(stateDirectory, "--emit-tool-call"), + stateDirectory, + }); + bundle.transport.setServerRequestHandler(() => new Promise>(() => undefined)); + let runnerPid: number | null = null; + try { + await bundle.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [taskTool] }); + runnerPid = bundle.evidence().runnerPid; + await bundle.transport.request("turn/start", { input: [{ type: "text", text: "Read current task" }] }); + await callReached; + const closing = bundle.transport.close().catch(() => undefined); + releaseDispatch(); + await (gatedOutcome as Promise | null)?.catch(() => undefined); + await closing; + const results = (JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { commands: SavedCommand[] }) + .commands.filter(command => command.type === "semantic_tool.result"); + expect(results).toHaveLength(1); + expect(JSON.stringify(results[0]!.payload)).toContain("semantic_tool_not_dispatched"); + } finally { + releaseDispatch(); + coreSpy.mockRestore(); + await bundle.transport.close().catch(() => undefined); + if (runnerPid) { + try { process.kill(-runnerPid, "SIGKILL"); } catch { runnerPid = null; } + } + await rm(stateDirectory, { recursive: true, force: true }); + } +}, 120_000); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index a9e56ff8f2e..338eedbcd6f 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -76,6 +76,7 @@ import { NativeRunnerResumeStateUnavailableError, NativeRunnerSourceReconciliati import { DurablePrpControlPlane, inspectStagedRunAttachment, + SemanticToolHandedOffError, SemanticToolNotDispatchedError, durableRecoveryInternals, inspectWarmRunTransition, @@ -6518,7 +6519,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { onAuthenticatedConnection: () => this.#startupSteps?.advance("runner.process.launch", "provider.session.load"), get authorityRunId() { return authorityRunId(); }, semanticInputMode: this.#retainsSourceInputs() || this.options.recoveryPurpose === "stop_cleanup" ? "retain_only" : "dispatch", - onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#handleSemanticToolInput(call), + onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#dispatchSemanticToolInput(call), recoverSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : call => this.#recoverSemanticToolInput(call), onCommittedEvent: async (event) => { const source = this.#sourceAccountingIdentity(); @@ -7079,7 +7080,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { onAuthenticatedConnection: () => this.#startupSteps?.advance("runner.process.launch", "provider.session.load"), get authorityRunId() { return authorityRunId(); }, semanticInputMode: this.#retainsSourceInputs() || this.options.recoveryPurpose === "stop_cleanup" ? "retain_only" : "dispatch", - onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#handleSemanticToolInput(call), + onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#dispatchSemanticToolInput(call), recoverSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : call => this.#recoverSemanticToolInput(call), onCommittedEvent: async (event) => { const source = this.#sourceAccountingIdentity(); @@ -7680,6 +7681,15 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { return outcome ? this.#bindSemanticToolOutcome(call, outcome) : null; } + async #dispatchSemanticToolInput(call: Parameters>[0]) { + try { + return await this.#handleSemanticToolInput(call); + } catch (error) { + if (error instanceof SemanticToolNotDispatchedError && this.#controllerDetachedForRestart) throw new SemanticToolHandedOffError(); + throw error; + } + } + async #handleSemanticToolInput( call: Parameters< NonNullable From 3ee6049f7147ea5fa1eb03f192c1cc3a23750bcd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:46:33 -0600 Subject: [PATCH 10/20] perf(native-runtime): name why a preinstalled provider pack was not reused (#21781) 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 remote agent run needs the provider pack (Node, OpenCode and the Runner bridge) inside its sandbox before the provider can start > - The server reuses a pack that is already installed in the sandbox image, or it uploads its own pack > - In a recent load test every task uploaded the pack, and this step was about 43% of the time to first token > - The compatibility check and the preinstalled-pack verification failed, but the run records did not say which check failed > - This pull request records the failed check on the run's performance spans > - The benefit is that the next run names the reason, so the image or the check can be fixed without guesswork ## Linked Issues or Issue Description **What existing behavior does this improve?** The run performance spans for provider pack selection. Today a failed `provider_pack.compatibility` or `provider_pack.verify_preinstalled` span only says `outcome: failed`. The code catches the error and drops it. **Subsystem affected** Server: native runtime, remote provider pack selection (`server/src/services/native-runtime`). **Current behavior** `provider_pack.select` records `reason: cached_packs_unverified` when it uploads. The compatibility check throws one generic message for about ten different conditions, and the caller swallows it. The remote verification script throws a generic `manifest mismatch` without the fields that differ. **Proposed behavior** Each failed check has a short, fixed name (for example `installation_unprotected`, `contract_digest`, `artifact:nodeCommand`, `manifest_mismatch:runnerSourceRevision`). The trace records this name as the `check` attribute on the failed span. `provider_pack.select` records the last preinstalled rejection as `check` when it uploads. The compatibility span records `target: image` or `target: workspace`. **Reason and benefit** Upload of the provider pack costs about 15 s per task on the test instance. To remove it, we must know which check rejects the image pack. The attribute holds only fixed check names and manifest field names, never paths or values. **Breaking changes** None. Error messages keep their existing text. The upload decision does not change. ## What Changed - `remote-provider-pack-verification.ts`: the compatibility check names the failed condition (`failureCheck`). The remote verification script prints a fixed `paperclip-pack-check=` line, and for a manifest mismatch it names the differing manifest fields. Missing files now give a named check instead of a raw stack trace. - `native-run-trace.ts`: a failed `measure` records the error's `failureCheck` as the safe `check` attribute. - `remote-provider-pack.ts`: `provider_pack.select` records the last preinstalled rejection (or `no_preinstalled_pack`) when it uploads. - `native-session-executor.ts`: the `provider_pack.compatibility` span records `target`, the preinstalled-pack selection passes its rejection callback, and a failed link has the `link_failed` check. No other lines change. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-run-trace.test.ts src/services/native-runtime/remote-provider-pack.test.ts src/services/native-runtime/remote-provider-pack-verification.test.ts src/__tests__/redaction.test.ts` passes (131 tests). - Red/green: with the source changes reverted and the new tests kept, 12 tests fail. With the changes, all pass. - The verification test runs the real remote script in a Node process: a provenance-only difference gives `manifest_mismatch:runnerSourceRevision`, a wrong artifact gives `artifact_digest:nodeCommand`, and a missing manifest gives `manifest_unreadable`. - `npx tsc --noEmit -p server/tsconfig.json` passes. ## Risks - Low risk. The change adds diagnostics only. The selection order, the checks themselves and the upload path do not change. - The `check` attribute is filtered by the existing safe-attribute list and a strict character pattern, so it cannot carry paths or secrets. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] 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 --- .../native-runtime/native-run-trace.test.ts | 12 +++ .../native-runtime/native-run-trace.ts | 8 ++ .../native-runtime/native-session-executor.ts | 11 ++- .../remote-provider-pack-verification.test.ts | 39 ++++++++- .../remote-provider-pack-verification.ts | 86 ++++++++++++------- .../remote-provider-pack.test.ts | 25 ++++++ .../native-runtime/remote-provider-pack.ts | 15 ++-- 7 files changed, 152 insertions(+), 44 deletions(-) diff --git a/server/src/services/native-runtime/native-run-trace.test.ts b/server/src/services/native-runtime/native-run-trace.test.ts index 8954fe10442..47e2e44875a 100644 --- a/server/src/services/native-runtime/native-run-trace.test.ts +++ b/server/src/services/native-runtime/native-run-trace.test.ts @@ -69,6 +69,18 @@ function createRecordingTraceContext(): { } describe("native runner performance trace", () => { + it("records the named check of a failed measurement on its run event", async () => { + const {traceContext}=createRecordingTraceContext(); + const events: Array> = []; + const trace=createNativeRunTrace({runId:"provider-pack-check",startedAtMs:1000,traceContext, + onEvent:async event=>{events.push(event.payload as Record);}}); + const rejected=Object.assign(new Error("runner_remote_provider_artifact_incompatible: incompatible"),{failureCheck:"contract_digest"}); + await expect(trace.measure("provider_pack.compatibility",async()=>{throw rejected;},{attributes:{target:"image"}})).rejects.toBe(rejected); + await expect(trace.measure("provider_pack.verify",async()=>{throw Object.assign(new Error("x"),{failureCheck:"has space"});})).rejects.toThrow("x"); + await trace.finish("ok"); + expect(events.find(event=>event.span==="provider_pack.compatibility")).toMatchObject({outcome:"failed",target:"image",check:"contract_digest"}); + expect(events.find(event=>event.span==="provider_pack.verify")).not.toHaveProperty("check"); + }); it("projects a full durable diagnostic batch without waiting on duplicate run-log writes", async () => { const {traceContext, spans}=createRecordingTraceContext(); let release!: () => void; diff --git a/server/src/services/native-runtime/native-run-trace.ts b/server/src/services/native-runtime/native-run-trace.ts index 9911b158cd0..2e8f5c54676 100644 --- a/server/src/services/native-runtime/native-run-trace.ts +++ b/server/src/services/native-runtime/native-run-trace.ts @@ -210,6 +210,7 @@ const SAFE_NATIVE_RUN_SPAN_ATTRIBUTE_KEYS = new Set([ "adapter", "anchor", "bytesTransferred", + "check", "inputBytes", "toolSchemaBytes", "toolCount", "contextReused", "tokenDataAvailable", "connectionOwner", "driver", @@ -229,6 +230,11 @@ const SAFE_NATIVE_RUN_SPAN_ATTRIBUTE_KEYS = new Set([ "target", ]); +export function nativeRunFailureCheck(error: unknown): string | undefined { + const check = (error as { failureCheck?: unknown } | null)?.failureCheck; + return typeof check === "string" && /^[A-Za-z0-9_.:,@/-]{1,120}$/.test(check) ? check : undefined; +} + function finiteMs(value: number): number { return Number.isFinite(value) ? Math.max(0, value) : 0; } @@ -630,6 +636,8 @@ export function createNativeRunTrace(input: { return await run(scope, fn); } catch (error) { outcome = "failed"; + const check = nativeRunFailureCheck(error); + if (check) annotate(scope, { check }); throw error; } finally { await end(scope, { outcome }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 26badf5ba56..0fa234824a3 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -50,7 +50,7 @@ import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-pre import { notifyInstructionCollection } from "../instruction-collection-notifications.js"; import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js"; import { nativeProviderPackAdmissionFailureCode, prepareNativeProviderPackAdmission, rememberAdmittedNativeProviderPack, rememberRecoveredNativeProviderPack, recordNativeProviderPackAdmission, type NativeProviderPackAdmissionSource } from "./native-provider-pack-admission.js"; -import { type ProviderPackInstallation, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js"; +import { type ProviderPackInstallation, providerPackIncompatible, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js"; import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js"; import { NATIVE_SESSION_EXECUTION_LEASE_TTL_MS, lockNativeExecutionLeaseForReacquire, nativeExecutionLeaseHeldCondition, releaseUnstartedNativeExecutionClaim, startNativeSessionExecutionLeaseRenewal, type NativeExecutionLeaseRenewal } from "./native-execution-lease.js"; export { renewNativeSessionExecutionLease } from "./native-execution-lease.js"; @@ -14706,7 +14706,8 @@ export async function prepareRemoteProviderPackOnTarget(input: { "provider_pack.verify", () => verifyRemoteProviderPack(stagedRemoteProviderPackRoot), ), - usePreinstalled: async () => useVerifiedPreinstalledRemoteProviderPack({ + usePreinstalled: async (onRejected) => useVerifiedPreinstalledRemoteProviderPack({ + onRejected, candidates: preinstalledProviderPackRoots = await measureNativeRunnerSpan(input.trace, "provider_pack.discover", discoverPreinstalledProviderPack), verifyAndLink: async (preinstalledProviderPack) => { await measureNativeRunnerSpan( @@ -14736,9 +14737,7 @@ export async function prepareRemoteProviderPackOnTarget(input: { timeoutMs: 10_000, })); if (linked.exitCode !== 0 || linked.timedOut) { - throw new Error( - "runner_remote_provider_artifact_incompatible: preinstalled provider pack could not be linked", - ); + throw providerPackIncompatible("link_failed", "preinstalled provider pack could not be linked"); } activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; await input.onLog?.( @@ -17151,7 +17150,7 @@ async function createRunnerdBackendWithinSessionClaim( requireExactIdentity: retainProviderPack || explicitProviderPackSelection, requireCurrentOpenCodeProxy: !retainProviderPack && runnerEnvironment?.PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS === "1", - })); + }), { attributes: { target: installation.root === stagedRemoteProviderPackRoot ? "workspace" : "image" } }); if (!retainProviderPack) providerPackAuthority!.select(manifest); expectedProviderPackManifest = manifest; activeRemoteProviderPackRoot = installation.root; diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts index 3c4255a4dc5..308d142b9cc 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts @@ -51,8 +51,20 @@ describe("installed provider pack compatibility", () => { try { // Exercise the old complete-manifest comparison in a real Node process. // Only provenance changed; provider bytes and interface are identical. - await expect(verifyRemoteProviderPack(input)).rejects.toThrow("manifest mismatch"); + await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({ + message: expect.stringContaining("manifest mismatch"), failureCheck: "manifest_mismatch:runnerSourceRevision" }); expect(execute).toHaveBeenCalledOnce(); + await expect(verifyRemoteProviderPack({ ...input, manifest: installed })).rejects.toMatchObject({ + message: expect.stringContaining("nodeCommand digest mismatch"), failureCheck: "artifact_digest:nodeCommand" }); + await rm(join(root, "provider-pack.json")); + await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({ failureCheck: "manifest_unreadable" }); + const combined = vi.fn(async (request: Parameters[0]) => { + const result = await execute(request); + return { ...result, stdout: `${result.stdout}${result.stderr}`, stderr: "" }; + }); + await expect(verifyRemoteProviderPack({ ...input, runner: { execute: combined } })) + .rejects.toMatchObject({ failureCheck: "manifest_unreadable" }); + await writeFile(join(root, "provider-pack.json"), JSON.stringify(installed)); execute.mockClear(); const selected = await verifyRemoteProviderPack({ ...input, installation: { root, manifest: installed, immutable: true }, provider: { kind: "opencode" } }); @@ -70,6 +82,31 @@ describe("installed provider pack compatibility", () => { provider: { kind: "opencode" }, requireExactIdentity: options.requireExactIdentity, requireCurrentOpenCodeProxy: options.requireCurrentOpenCodeProxy }); }; + it.each([ + ["interface", "compatibility_revision"], ["contracts", "contract_digest"], ["platform", "target"], ["schema", "schema"], + ["artifact_path", "artifact:nodeCommand"], ["digest", "manifest_digest"], ["legacy", "compatibility_revision"], + ["legacy_contracts", "contract_digest_missing"], + ])("names the failed check for an incompatible %s", async (field, failureCheck) => { + let pack = manifest("a"); + if (field === "interface") pack.payload.compatibility!.opencode += 1; + if (field === "contracts") pack.payload.contractDigest = sha("other-contracts"); + if (field === "legacy") delete pack.payload.compatibility; + if (field === "legacy_contracts") delete pack.payload.contractDigest; + if (field === "platform") pack.payload.target.architecture = "arm64"; + if (field === "schema") pack.schema = "unknown"; + if (field === "artifact_path") pack.payload.artifacts.nodeCommand.path = "../node"; + pack = reseal(pack); + if (field === "digest") pack.digest = sha("corrupt"); + await expect(check(pack)).rejects.toMatchObject({ failureCheck }); + }); + it("names unprotected, exact-identity and proxy rejections", async () => { + await expect(check(manifest("b"), { immutable: false })).rejects.toMatchObject({ failureCheck: "installation_unprotected" }); + await expect(check(manifest("a"), { requireExactIdentity: true })).rejects.toMatchObject({ failureCheck: "exact_identity" }); + await expect(check(manifest("a"), { requireCurrentOpenCodeProxy: true })).rejects.toMatchObject({ failureCheck: "opencode_proxy" }); + const unpinned = manifest("b"); + (unpinned.payload.pins as Record).opencode = null; + await expect(check(reseal(unpinned))).rejects.toMatchObject({ failureCheck: "opencode_pin_missing" }); + }); it.each(["interface", "contracts", "platform", "schema", "artifact_path", "digest", "legacy", "legacy_contracts"])("rejects an incompatible %s", async field => { let pack = manifest("a"); if (field === "interface") pack.payload.compatibility!.opencode += 1; diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts index 5d48ea89146..5e7c424f20b 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -28,6 +28,22 @@ export type ProviderPackIdentity = { }; }; +export function providerPackIncompatible(check: string, detail: string): Error & { failureCheck: string } { + return Object.assign(new Error(`runner_remote_provider_artifact_incompatible: ${detail}`), { failureCheck: check }); +} + +async function withProviderPackCheck(step: "pack" | "opencode", verify: () => Promise): Promise { + try { + return await verify(); + } catch (error) { + if (!(error instanceof Error) || error.name === "AbortError") throw error; + const reported = /paperclip-pack-check=([A-Za-z0-9_.:,@/-]{1,100})/.exec(error.message)?.[1]; + const check = reported ?? (error.message.startsWith("runner_remote_provider_verification_unavailable") + ? `${step}_verifier_unavailable` : `${step}_verifier_failed`); + throw Object.assign(error, { failureCheck: check }); + } +} + export type ProviderPackInstallation = { root: string; manifest: unknown; immutable: boolean }; export type PackProvider = { kind: "opencode" } | { kind: "acpx"; agent: string }; @@ -45,28 +61,33 @@ function compatibleInstallation( const actual = installation.manifest as T | null; const payload = actual?.payload; const contract = expected.payload.compatibility?.[provider.kind]; - if (!installation.immutable || installation.root !== packRoot || !payload - || actual.schema !== expected.schema - || actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` - || canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) - || (requireExactIdentity ? actual.digest !== expected.digest - : !Number.isSafeInteger(contract) || contract! < 1 || payload.compatibility?.[provider.kind] !== contract - || !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "") - || payload.contractDigest !== expected.payload.contractDigest) - || typeof payload.pins?.opencode !== "string") { - throw new Error("runner_remote_provider_artifact_incompatible: installed provider pack interface or installation is incompatible"); + const failed = !installation.immutable ? "installation_unprotected" + : installation.root !== packRoot ? "installation_root" + : !payload ? "manifest_missing" + : actual.schema !== expected.schema ? "schema" + : actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` ? "manifest_digest" + : canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) ? "target" + : requireExactIdentity ? (actual.digest !== expected.digest ? "exact_identity" : null) + : !Number.isSafeInteger(contract) || contract! < 1 ? "expected_compatibility_missing" + : payload.compatibility?.[provider.kind] !== contract ? "compatibility_revision" + : !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "") ? "expected_contract_digest_missing" + : payload.contractDigest === undefined ? "contract_digest_missing" + : payload.contractDigest !== expected.payload.contractDigest ? "contract_digest" + : null; + if (failed || !actual || !payload || typeof payload.pins?.opencode !== "string") { + throw providerPackIncompatible(failed ?? "opencode_pin_missing", "installed provider pack interface or installation is incompatible"); } // Launch profiles and recovery receipts bind the selected installation's own // bytes, never the current controller's artifact hashes. for (const [name, expectedArtifact] of Object.entries(expected.payload.artifacts)) { const artifact = payload.artifacts?.[name]; if (artifact?.path !== expectedArtifact.path || !/^sha256:[a-f0-9]{64}$/.test(artifact.sha256)) { - throw new Error("runner_remote_provider_artifact_incompatible: installed provider pack artifact identity is invalid"); + throw providerPackIncompatible(`artifact:${name}`, "installed provider pack artifact identity is invalid"); } } if (provider.kind === "opencode" && requireCurrentOpenCodeProxy && payload.artifacts.opencodeProxy?.sha256 !== expected.payload.artifacts.opencodeProxy?.sha256) { - throw new Error("runner_remote_provider_artifact_incompatible: installed proxy does not match the requested OpenCode diagnostics"); + throw providerPackIncompatible("opencode_proxy", "installed proxy does not match the requested OpenCode diagnostics"); } if (provider.kind === "acpx") { const agent = provider.agent; @@ -78,7 +99,7 @@ function compatibleInstallation( if (currentProfile ? payload.acpxProfileDigests?.[agent] !== currentProfile : !selected || !installed || ["version", "profileDigest", "closureDigest", "qualification", "path"].some(key => (installed as Record)[key] !== (selected as Record)[key])) { - throw new Error("runner_remote_provider_artifact_incompatible: selected ACPX provider profile is incompatible"); + throw providerPackIncompatible("acpx_profile", "selected ACPX provider profile is incompatible"); } } return structuredClone(actual); @@ -112,47 +133,48 @@ export async function verifyRemoteProviderPack({ "const path=require('node:path')", "const root=process.argv[1]", "const expected=Buffer.from(process.argv[2],'base64').toString('utf8')", - "const actual=fs.readFileSync(path.join(root,'provider-pack.json'),'utf8').trim()", + "const fail=(check,detail)=>{fs.writeSync(2,detail+'\\n');fs.writeSync(1,'\\npaperclip-pack-check='+check+'\\n');process.exit(3)}", + "let actual;try{actual=fs.readFileSync(path.join(root,'provider-pack.json'),'utf8').trim()}catch{fail('manifest_unreadable','provider pack manifest unreadable')}", "const canonical=(v)=>Array.isArray(v)?'['+v.map(canonical).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}':JSON.stringify(v)", - "const manifest=JSON.parse(actual)", - "if(canonical(manifest)!==expected)throw new Error('manifest mismatch')", - "const hash=(p)=>'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')", - "const tree=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}", - "for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)throw new Error(name+' digest mismatch')}", - "if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)throw new Error('dist tree digest mismatch')", - "for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)throw new Error('candidate asset tree digest mismatch')}", + "let manifest;try{manifest=JSON.parse(actual)}catch{fail('manifest_invalid','provider pack manifest invalid')}", + "const differing=(a,b)=>[...new Set([...Object.keys(a||{}),...Object.keys(b||{})])].sort().filter(k=>canonical((a||{})[k])!==canonical((b||{})[k]))", + "if(canonical(manifest)!==expected){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}", + "const hash=(p)=>{try{return 'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')}catch{return 'unreadable'}}", + "const walk=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}", + "const tree=(treeRoot)=>{try{return walk(treeRoot)}catch{return 'unreadable'}}", + "for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)fail('artifact_digest:'+name,name+' digest mismatch')}", + "if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)fail('dist_digest','dist tree digest mismatch')", + "for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)fail('candidate_digest','candidate asset tree digest mismatch')}", "const version=process.versions.node.split('.').map(Number)", "const minimum=manifest.payload.pins.nodeMinimum.split('.').map(Number)", - "if(version[0]JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version", + "if(version[0]{try{return JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version}catch{return null}}", "const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}", - "for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)throw new Error(pkg+' version mismatch')", + "for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version:'+pkg,pkg+' version mismatch')", ].join(";"); - await runRemoteProviderVerification(() => runner.execute({ + await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({ command: providerNodeCommand, args: ["-e", verifyScript, packRoot, expected], cwd: cwd, bypassSession: true, timeoutMs: 30_000, - }), "provider pack verification"); + }), "provider pack verification")); const opencodeCommand = posix.join( packRoot, manifest.payload.artifacts.opencodeCommand.path, ); - const opencodeVersion = await runRemoteProviderVerification(() => runner.execute({ + const opencodeVersion = await withProviderPackCheck("opencode", () => runRemoteProviderVerification(() => runner.execute({ command: opencodeCommand, args: ["--version"], cwd: cwd, bypassSession: true, timeoutMs: 30_000, - }), "OpenCode version verification"); + }), "OpenCode version verification")); if ( opencodeVersion.stdout.trim() !== manifest.payload.pins.opencode ) { - throw new Error( - "runner_remote_provider_artifact_incompatible: OpenCode version mismatch", - ); + throw providerPackIncompatible("opencode_version", "OpenCode version mismatch"); } return structuredClone(manifest); } diff --git a/server/src/services/native-runtime/remote-provider-pack.test.ts b/server/src/services/native-runtime/remote-provider-pack.test.ts index 5d5991abca4..0ae23290c7f 100644 --- a/server/src/services/native-runtime/remote-provider-pack.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; +import { createNativeRunTrace } from "./native-run-trace.js"; import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; describe("remote provider verification", () => { @@ -96,6 +97,30 @@ describe("remote provider pack reuse", () => { stageAndVerify.mockResolvedValue(undefined); await expect(prepareVerifiedRemoteProviderPack(input)).resolves.toBe("uploaded"); }); + + it("records on the selection span why the image pack was not reused", async () => { + const trace = createNativeRunTrace({ runId: "provider-pack-select-run", startedAtMs: Date.now() }); + const annotate = vi.spyOn(trace, "annotate"); + const rejected = Object.assign(new Error("runner_remote_provider_artifact_incompatible: provider pack verification failed"), + { failureCheck: "manifest_mismatch:runnerSourceRevision" }); + await expect(prepareVerifiedRemoteProviderPack({ + trace, + verifyStaged: async () => { throw new Error("missing"); }, + usePreinstalled: onRejected => useVerifiedPreinstalledRemoteProviderPack({ + candidates: ["/opt/paperclip-runner/provider-pack", "/home/operator/.local/share/paperclip-runner/provider-pack"], onRejected, + verifyAndLink: async root => { + throw root.startsWith("/opt/") ? rejected : Object.assign(new Error("missing"), { failureCheck: "manifest_unreadable" }); + }, + }), + stageAndVerify: async () => {}, + })).resolves.toBe("uploaded"); + expect(annotate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + stateSource: "uploaded", reason: "cached_packs_unverified", check: "manifest_mismatch:runnerSourceRevision" })); + annotate.mockClear(); + await prepareVerifiedRemoteProviderPack({ trace, verifyStaged: async () => { throw new Error("missing"); }, + usePreinstalled: async () => false, stageAndVerify: async () => {} }); + expect(annotate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ check: "no_preinstalled_pack" })); + }); }); diff --git a/server/src/services/native-runtime/remote-provider-pack.ts b/server/src/services/native-runtime/remote-provider-pack.ts index 15eb74ff0b5..b803d6d6d2c 100644 --- a/server/src/services/native-runtime/remote-provider-pack.ts +++ b/server/src/services/native-runtime/remote-provider-pack.ts @@ -1,5 +1,5 @@ import { redactSensitiveText } from "../../redaction.js"; -import type { NativeRunTrace } from "./native-run-trace.js"; +import { nativeRunFailureCheck, type NativeRunTrace } from "./native-run-trace.js"; import type { NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; /** Qualified ACPX releases carry their Linux image manifest and daemon. */ @@ -55,24 +55,27 @@ export async function runRemoteProviderVerification( export async function prepareVerifiedRemoteProviderPack(input: { trace?: NativeRunTrace; verifyStaged: () => Promise; - usePreinstalled: () => Promise; + usePreinstalled: (onRejected: (check: string) => void) => Promise; stageAndVerify: () => Promise; }): Promise<"staged" | "preinstalled" | "uploaded"> { const scope = input.trace?.start("provider_pack.select"); let failed = false; + let preinstalledCheck = "no_preinstalled_pack"; const select = async () => { try { await input.verifyStaged(); return "staged" as const; } catch {} - if (await input.usePreinstalled()) return "preinstalled" as const; + let rejected = false; + if (await input.usePreinstalled(check => { if (!rejected) preinstalledCheck = check; rejected = true; })) return "preinstalled" as const; await input.stageAndVerify(); return "uploaded" as const; }; try { const source = scope ? await input.trace!.run(scope, select) : await select(); if (scope) input.trace!.annotate(scope, { stateSource: source, - reason: source === "uploaded" ? "cached_packs_unverified" : "verified_pack_reused" }); + reason: source === "uploaded" ? "cached_packs_unverified" : "verified_pack_reused", + ...(source === "uploaded" ? { check: preinstalledCheck } : {}) }); return source; } catch (error) { failed = true; @@ -85,12 +88,14 @@ export async function prepareVerifiedRemoteProviderPack(input: { export async function useVerifiedPreinstalledRemoteProviderPack(input: { candidates: readonly string[]; verifyAndLink: (root: string) => Promise; + onRejected?: (check: string) => void; }): Promise { for (const candidate of input.candidates) { try { await input.verifyAndLink(candidate); return true; - } catch { + } catch (error) { + input.onRejected?.(nativeRunFailureCheck(error) ?? "verification_failed"); } } return false; From 10ddb26dbb5ce5426f48b652eb706b425ec1fe66 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:47:19 -0600 Subject: [PATCH 11/20] test(server): accept dash's exit code for a sandbox-denied shell write (#21792) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Runner workspace bridge runs agent commands in a `bwrap` sandbox that binds only `/usr`, `/bin`, `/lib` and the task workspace > - A server test checks that a sandboxed command cannot read or write a file outside the workspace > - The test only runs where `/usr/bin/bwrap` exists. CI jobs that the gate sends to GitHub's `ubuntu-latest` now get the `ubuntu-26.04` image, which has `bwrap`, so the test runs on CI for the first time > - There it fails on every run, because it expects the write attempt to exit with 1, but Ubuntu's `/bin/sh` (dash) exits with 2 when a redirection fails > - This pull request checks that the write fails and that the file is unchanged, without depending on the shell's exit code > - The benefit is that the "General tests (server (7/12))" job passes again on the new image, and the test still proves the sandbox denial ## Linked Issues or Issue Description **What happened?** `server/src/services/native-runtime/runner-bridge-tools.test.ts` › `Runner workspace bridge > runs useful commands but denies files outside the workspace and injected credentials` fails in "ci / General tests (server (7/12))" on unrelated branches, on the first run and the retry: - PR #21765, head `98197c87e9` - branch `feat/run-loop-detector`, run 43732047843, head `b8c6e27429`, job 132866487949, image `ubuntu-26.04` version 20261111.196.1 ``` AssertionError: expected { exitCode: 2, signal: null, …(3) } to match object { exitCode: 1 } ❯ src/services/native-runtime/runner-bridge-tools.test.ts:180:19 ``` On jobs that ran on the RunsOn `ubuntu24` image there is no `/usr/bin/bwrap`, so the test is skipped (7 skipped instead of 6). **Expected behavior** The test passes wherever the command sandbox is available, and it fails if the sandboxed command can read or change the outside file. **Steps to reproduce** 1. In a Debian or Ubuntu container, run `/bin/sh -c 'printf stolen > "$1"' sh /nonexistent/dir/private.txt`. 2. dash prints `cannot create /nonexistent/dir/private.txt: Directory nonexistent` and exits with 2. bash exits with 1. `cat` of the same path exits with 1. 3. In the sandbox, the outside temporary directory is not bound, so the path does not exist. This is the same case. **Root cause** A stale test expectation, exposed by a CI image change. No commit on `master` changed the bridge, the sandbox or this test today (the last change to the test is from 2026-11-08). The test expected the shell write to exit with 1. That is bash behavior. On Ubuntu, `/bin/sh` is dash, which exits with 2 for a failed redirection. Until today no CI image had `bwrap`, so the test never ran on CI. **Production impact** None. The sandbox denies the access as intended: the `cat` step on the same run exits with 1 and its output does not contain the secret, and the write fails with `Directory nonexistent` because the outside directory is not visible in the sandbox. This is not a sandbox regression. ## What Changed - The write step now checks that the outside file still contains `PRIVATE` first, then that the command was not stopped and exited with a non-zero code. It no longer requires exit code 1 from the shell. - The read step and the success step are unchanged. ## Verification - Linux container (`node:24-bookworm-slim`, `/bin/sh -> dash`): the write command exits with 2 under dash and 1 under bash, and both are failures, as the test now accepts. - `npx vitest run src/services/native-runtime/runner-bridge-tools.test.ts` in `server/` on macOS: 11 passed, 6 skipped (the sandbox tests need Linux with `bwrap`). - I cannot run the sandbox test on this Mac. It runs in this pull request's CI only when the job lands on an `ubuntu-26.04` runner. ## Risks - Low risk. Only one test assertion changes. The test still fails if the write succeeds, because the file content check runs first and the exit code must be non-zero. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, GitHub CLI, Docker). ## 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 --- server/src/services/native-runtime/runner-bridge-tools.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/src/services/native-runtime/runner-bridge-tools.test.ts b/server/src/services/native-runtime/runner-bridge-tools.test.ts index b46cf65e215..8a1e22fa73f 100644 --- a/server/src/services/native-runtime/runner-bridge-tools.test.ts +++ b/server/src/services/native-runtime/runner-bridge-tools.test.ts @@ -177,7 +177,8 @@ if sys.argv[1] != "completion": const read = await executeWorkspaceTool(directory, "workspace_run", { program: "/bin/cat", args: [secret] }, authorize); expect(read).toMatchObject({ exitCode: 1 }); expect(String((read as any).output)).not.toContain("PRIVATE"); const write = await executeWorkspaceTool(directory, "workspace_run", { program: "/bin/sh", args: ["-c", 'printf stolen > "$1"', "sh", secret] }, authorize); - expect(write).toMatchObject({ exitCode: 1 }); expect(await readFile(secret, "utf8")).toBe("PRIVATE"); + expect(await readFile(secret, "utf8")).toBe("PRIVATE"); + expect(write).toMatchObject({ stopped: null, exitCode: expect.any(Number) }); expect((write as { exitCode: number }).exitCode).not.toBe(0); }); it.skipIf(!workspaceCommandSandboxAvailable())("stops its owned process on authority loss and bounds output", async () => { const directory = await root(); let calls = 0; From cec8c2b3f46b9b62da6614e50ac3454abdb7e8b9 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:47:34 -0600 Subject: [PATCH 12/20] perf(recovery): name the run or task in run writers' recovery hints instead of the company (#21765) 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 server runs issue recovery queues on one Node main thread. The `stranded-assignments` and `assigned-work-invariant` queues check assigned tasks that have no live run. One stranded check costs about 19 database statements. > - #21552 scoped run hints to the run's task graph. #21729 made the 5-minute backstop re-check only changed tasks. A hint with only a company id still makes the queue re-check every open task of the company, 25 per pass. > - Under load on staging (7 native runs), the stranded check ran about 6.7 times per second, and its statement bundle was more than a third of all statements. An activity fixture shows the cause: ordinary run writers send a company-only hint once per run, and one company hint costs about 850 checks. At 1,000 agents this work never stops. > - This pull request makes those writers name the run (or the task) they already know. A run that has no task now resolves to no tasks instead of the whole company. The changed-tasks backstop no longer counts an agent's own run heartbeat as a change to every task of that agent. > - The benefit: with 7 runs a minute plus one taskless run, stranded checks drop from 18.4 to 1.0 per second and stranded-check statements from 344 to 7 per second. Real company-wide changes (pause lifted, budget, company status, tree holds) keep the full company pass. ## Linked Issues or Issue Description Refs #21729, #21552, #21676, #21724 **What existing behavior does this improve?** The issue recovery task queues (`stranded-assignments`, `assigned-work-invariant`, `resolved-dependencies`, `stale-issue-locks`) and the writers that wake them. **Subsystem affected** Server: issue recovery background work and the run lifecycle writers that publish recovery hints. **Current behavior** Many run lifecycle writers know the run but publish a company-only hint, for example `notifyExecutionRunWork(tx, { companyId })` in the native finalizer and projection, `settleNativeTerminalWake`, the claimed-wake settlement, and an environment lease release of a run without a task. A queued run without a task publishes a company hint. A graph hint for a run without a task resolves to "whole company". A comment sends a company hint to `assigned-work-invariant` and `resolved-dependencies`. Each of these re-checks all open tasks of the company. Also, the changed-tasks backstop treats any change to the assignee agent's row as a change to all of that agent's tasks, and every run start and finish writes that row. **Proposed behavior** A writer that knows the run sends the run's graph hint. A writer that knows the task sends the task hint. A run without a task affects no task queue entry. An agent row change that is only the agent's own run heartbeat does not mark its other tasks changed. Company-wide facts keep the company hint. **Reason and benefit** The work is now proportional to activity, not to (activity x history). See Verification. ## What Changed - `server/src/services/issue-recovery-notifications.ts`: - `notifyIssueRecovery` with a task sends the task hint to all four task queues (before: only to `stranded-assignments` and `stale-issue-locks`; `assigned-work-invariant` and `resolved-dependencies` got the company hint). Only comments (`issue-comment-writes.ts`) call it with a task. - `resolveIssueGraph` returns `[]` when a run-only graph has no task. A missing task seed still returns `null` (whole company). - `server/src/services/recovery/work.ts`: a load for an empty graph returns no rows. The `assigned-work-invariant` queue emits the same `check` debug event as `stranded-assignments` (with `PAPERCLIP_DEBUG_WORK_SIGNALS=assigned-work-invariant`), with the load reason. - `server/src/services/recovery/changed-tasks.ts`: the assignee-agent part of the changed-tasks condition skips an agent whose last write was its run heartbeat (`last_heartbeat_at = updated_at`). A resume, pause or configuration write (no heartbeat stamp) still counts. - `server/src/services/heartbeat/queue.ts`: a queued run without a task gets its id before the insert and publishes a run hint, not a company hint. The daily-cap comment release publishes the run's graph hint. - `server/src/services/environments.ts`, `work-intent-outbox.ts`, `chat-inbound-wake-notice-notifications.ts`: a lease release passes its run id. `promoteDeferredWorkIntents` scopes `lock_released` with only a run to that run's graph. `notifyChatInboundWakeNotices` accepts an optional `runId` for its settlement hint. - Native and recovery run writers now pass the run id they already have to `notifyExecutionRunWork`, `writeExecutionControl` or `notifyExternalConversationSettlement`: `native-run-finalizer.ts` (3), `native-run-projection.ts` (2), `native-session-executor.ts` (3), `wake-request-claimed-settlement.ts`, `native-superseded-retry.ts`, `native-safe-replacement.ts`, `native-restart-recovery.ts` (2), `native-failed-workspace-recovery.ts`, `native-recovery-preparation-failure.ts`, `execution-control-reconciliation.ts`, `execution-recovery-resolution.ts` (2). These are the native equivalents of the legacy run paths in `heartbeat/queue.ts`, which already pass the run id. - Tests: - `server/src/__tests__/issue-recovery-activity-hints.test.ts` (new): staging-shaped company (780 in-review tasks with succeeded native runs, 40 in progress, 30 to-do, 50 agents) on embedded PostgreSQL, the real recovery, dispatch and retry-cancellation workers, a fake clock, and real process-adapter runs. Each run is woken by a user comment through `heartbeat.wakeup`, starts, calls back to post an agent comment and move the task to `in_review`, and finishes. One (or five) taskless runs a minute run beside them. It counts checks by queue and reason, task-queue signals by caller, and statements by owner. It asserts the workload (runs started and succeeded, agent comments, run events, zero agent write failures, at most 10% failed runs), then no company check and no company-only task-queue signal. In CI it runs the 7-runs-a-minute workload for 4 minutes (about 1 minute of real time). With `RECOVERY_ACTIVITY_REPORT=` it runs both workloads at full length, attributes statements by stack, and writes the numbers below to that file. - `server/src/__tests__/issue-recovery-deadlines.test.ts`: pickup tests for each narrowed writer (see Verification). ### Publishers of company-only (or `*`) hints to the recovery task queues "Per" is how often the writer fires on a busy instance. "Known" says whether the run or task is known at the call site. Narrowed in this pull request: | Call site | Event | Per | Known | Now | | --- | --- | --- | --- | --- | | `heartbeat/queue.ts:5396` `enqueueWakeup` | queue a run without a task (timer, manual, chat without a task) | each taskless run | run (id generated) | run graph (no tasks) | | `environments.ts:1780` `releaseLease` -> `notifyChatInboundWakeNotices` | environment lease released | each run without a task | run | run graph | | `environments.ts:1792` `releaseLease` -> `promoteDeferredWorkIntents(lock_released)` | lease released | each run without a task | run | run graph | | `environments.ts:1934` `releaseLeasesForRun` | leases of a run released | each run without a task | run | run graph | | `issue-comment-writes.ts:12` (`assigned-work-invariant`, `resolved-dependencies` only) | comment | each comment | task | task | | `native-runtime/native-run-projection.ts:54` `settleNativeTerminalWake` | native run's wake claim settled | each native run finish | run | run graph | | `native-runtime/native-run-projection.ts:177` | native run status projected | each native run finish | run | run graph | | `native-runtime/native-run-finalizer.ts:408`, `:629`, `:2080` | native finalization terminal / failure / projection | each native run finish | run | run graph | | `native-runtime/native-session-executor.ts:13018`, `:13085`, `:13284` | native execution control deadline, cancelled retry, pre-result settlement | each native run end | run | run graph | | `recovery/wake-request-claimed-settlement.ts:67` | claimed wake settled after the run | each run whose claim is reconciled | run | run graph | | `heartbeat/queue.ts:590` | daily-cap comment key release | each run cancelled at the daily cap | run | run graph | | `native-runtime/native-superseded-retry.ts:42`, `native-safe-replacement.ts:613`, `native-restart-recovery.ts:1033`, `:1935`, `native-failed-workspace-recovery.ts:164`, `native-recovery-preparation-failure.ts:30`, `execution-control-reconciliation.ts:270`, `execution-recovery-resolution.ts:830`, `:965` | native recovery terminal writes | each recovered run | run | run graph | | `resolveIssueGraph` for any run-only hint of a run without a task (for example `setWakeupStatus`, `run-lifecycle.ts:1570`) | run lifecycle | each taskless run event | run | no tasks | Left with the company hint (company-wide fact, or the graph is not known): | Call site | Event | Per | Why kept | | --- | --- | --- | --- | | `budgets.ts:371`, `:386`, `:429`, `:437`, `:454` | budget policy changed, scope paused or resumed | operator or budget event | eligibility of every task can change | | `work-intent-outbox.ts:79` with `pause_lifted`, `tree_hold_released`, `scheduling_resumed`, `reconciler_backstop`, and `accounting_settled` with an active hard stop | hold release | operator event; `accounting_settled` once per run only with a hard-stop policy | can admit any task; guarded by "keeps the company pass for hold releases that can admit any task" | | `companies.ts:77`, `:350`, `:353`, `:361`, `:512`, `:522` | company created, paused, resumed, archived | operator | company-wide | | `agent-lifecycle.ts:65`, `:72`, `agent-lifecycle-driver.ts:29`, `agent-configuration.ts:130`, `:159`, `agent-deletion.ts:61` | agent paused, resumed, configured, deleted | operator | can change many tasks, and other agents' review paths | | `access.ts:570`, `:752`, `:912`, `:926`, `:960`, `:975`, `:1175`, `board-claim.ts:129`, `:142`, `middleware/auth.ts:706` | membership and authority changes | operator, first sign-in | company authority | | `chat-channels/endpoints.ts:461`, `identity-links.ts:323`, `resource-reconciliation.ts:290`, `slack/setup-services.ts:50`, `chat-github-management.ts:182`, `:352`, `chat-work-notifications.ts:50` | chat authority changes | operator | company authority | | `instance-settings.ts:666`, `:669`, `:680` (`*`) | instance setting changed | operator | instance-wide | | `issue-tree-control.ts:809`, `:889`, `:1236`, `:1339` | tree hold created or released | operator | many tasks | | `company-deletion.ts:83`, `company-portability.ts:6560` | company delete, import | rare | many tasks | | `issues.ts:8015` (blockers replaced), `:11165` (task created), `:12685`, `:12699` (task deleted), `:12991`, `:14618` | task graph changes | per task create or blocker edit | graph moves; #21552 kept these | | `documents.ts:615`, `:673`, `:757`, `:808`, `:860` | document delete and restore | rare | #21552 kept these | | `task-watchdogs.ts:854`, `:1841` | watchdog changes | rare | #21552 kept these | | `system-recovery.ts:17`, `:70`, `task-retry.ts:294`, `workspace-recovery-capture-policy.ts:59`, `workspace-recovery-stop-proof.ts:122` | system and workspace recovery | per recovery | not shown to stay in one graph | | `agent-conversations.ts:607`, `chat-channels/telegram/attachment-failure.ts:83`, `native-runtime/chat-attachment-reuse.ts:1754`, `native-runner-file-handoff.ts:1317` | conversation and attachment paths | per failure | not shown to stay in one graph | | `wake-queue/adapters/postgres.ts:376`, `:410`, `:555`, `:1169`, `routes/issues.ts:14552`, `issues.ts:12070`, `:12171`, `heartbeat/run-control.ts:1128`, `:1770`, `projects.ts:100`, `:1051`, `environments.ts:1617` (`notifyChatInboundWakeNotices` without a task) | saved notice and wake changes | per manual wake or project change | company admission state; not reached by run activity in the fixture | | `heartbeat/run-state.ts:1746`, `native-harness-backup-expiration.ts:356`, `:526`, `explicit-native-continuation.ts:705` | session goal clear, backup expiry, explicit continuation | rare | no run id at the call site | | `fast-responses.ts:201`, `:559`, `:672`, `:1053`, `chat-github-response-comments.ts:62`, `:229`, `:440`, `chat-github-reviews.ts:1063` (`notifyChatResponseAvailability` with a delivery only) | chat response availability | per chat response | no task at the call site; not measured here (chat paths are not in the fixture) | Per-run-event path: appending run events, saving native checkpoints, renewing leases and streaming deltas publish no recovery task-queue hint. `heartbeat-run-events.ts` reaches only live-run recovery queues (`native.process_*`, `turn.*` events), chat progress, response presentation, and `notifyNativeStatusReassessment` for control-plane evidence events only. Checkpoints and lease renewals reach `notifyLiveRunRecovery`, which does not include the task queues. A run's start and finish publish its graph hint from several writers (about 20 task-queue signals per legacy run in the fixture, for example `notifyChatRunMilestones` in `run-identity.ts` activation, `claimQueuedRun`, `run-completion.ts`, `setWakeupStatus`). They coalesce into about 3 checks of the run's own task per run. That is not one hint, but it is bounded by the run's graph. This pull request does not change it. ## Verification - Activity fixture (`issue-recovery-activity-hints.test.ts`), checks per second by queue and reason, and statements per second. Each workload minute is exactly 60 s of fake-clock time, and the rates use the elapsed fake-clock time. "Before" is this branch's test against the `origin/master` service files. Both versions did the same work (7 runs/min: 150 runs started, 143 to 145 succeeded, 133 to 135 agent comments, about 1,280 run events; 50 runs/min: 629 to 630 started, 620 to 622 succeeded, about 590 agent comments, about 5,550 run events). The test now asserts this workload and zero agent write failures before it accepts the counts. | | master | this branch | | --- | --- | --- | | 7 runs/min + 1 taskless run/min (600 s), stranded checks/s | 18.30 company + 0.07 hint | 0.91 hint + 0.06 backstop, 0 company | | 7 runs/min, statements/s in stranded checks | 343.9 | 7.2 | | 7 runs/min, all statements/s | 577.5 | 220.4 | | 7 runs/min, company-only task-queue signals | 710 | 0 | | 50 runs/min + 5 taskless runs/min (360 s), stranded checks/s | 16.86 company + 0.31 hint | 1.05 hint, 0 company | | 50 runs/min, statements/s in stranded checks | 314.0 | 7.4 | | 50 runs/min, all statements/s | 1,717.6 | 1,387.5 | | 50 runs/min, company-only task-queue signals | 2,864 | 0 | "Statements in stranded checks" counts statements whose stack includes `reconcileStrandedAssignedIssues`. The other statements are the runs themselves. Recovery load queries (graph lookups and hint loads) are 12.5 to 17.2/s at 7 runs and 69 to 72/s at 50 runs in both versions. `stale-issue-locks` saved deadlines check about 1 to 1.6 tasks/s in both versions. - Without the taskless runs, master already showed the backstop degrade under activity: with 7 runs a minute, 2.46 backstop checks/s, because every run writes its agent's row and marks all of that agent's tasks changed. With this branch: 0.27/s. - New tests in `issue-recovery-deadlines.test.ts`, red on `origin/master` service files and green here: - "re-checks a run's own tasks for its settlement, lease and dispatch writers, and nothing for a run without a task": for `notifyRunDispatch`, `notifyExecutionRunWork`, `notifyExternalConversationSettlement`, `notifyChatInboundWakeNotices` and `promoteDeferredWorkIntents(lock_released)` with a run id, the run's graph (task, parent, dependent) is checked within one pass and none of 300 backlog tasks is. For a run without a task, no task is checked. A comment checks only its task in `stranded-assignments` and `assigned-work-invariant`. - "counts an agent's own run heartbeat as no change to its other tasks, and a resume as a change". - "resolves a run without a task to no tasks and a missing task to the whole company". - Unchanged and passing: the #21729 pickup tests in `issue-recovery-idle-backstop.test.ts` (finished run, user comment, raised budget, resumed agent within a minute; missed hint within the backstop bound; outside change within the hourly pass), the #21552 tests in `issue-recovery-deadlines.test.ts` (including "keeps the company pass for hold releases that can admit any task" and "falls back to the company pass when a run affects more tasks than a hint names"). - Regression, embedded PostgreSQL: `issue-recovery-deadlines`, `issue-recovery-work-debug-attribution`, `issue-recovery-signal-fanout`, `issue-recovery-work-lifecycle` (42 tests); `native-run-projection-work`, `native-recovery-notice-work`, `muse-terminal-settlement`, `heartbeat-held-comment-wake`, `superseded-workspace-export-recovery`, `native-recovery-preparation-failure`, `upgrade-readiness-post-result`, `chat-wake-conversation-batch`, `environment-service`, `retained-native-session-cleanup-work`, `slack-conversation-lifecycle`, `workspace-recovery-dependency-finalize`, `native-failed-run-owner-release`, `chat-run-milestone-work` (462 tests). - `tsc --noEmit -p server/tsconfig.json` passes. ## Risks - **Recovery time bounds. The owner must see this.** No hint-driven pickup becomes slower for a task in the run's graph. Two missed-hint bounds change: - An agent change that sends no hint and is followed by a run heartbeat of the same agent inside the 5-minute window (for example a resume whose hint was lost, after which the agent ran another task) is now found by the hourly full pass, not the 5-minute changed-tasks pass. A normal resume sends `pause_lifted` and is checked at once (tested). - A task outside the run's graph whose recovery depended on the end of a taskless run, or on the native finish writers above, is now found by its own hint, the 5-minute changed-tasks pass (its own rows), or the hourly full pass. Before, any run finish re-checked the whole company. I found no recovery decision that waits on another run of the agent: concurrency waits are queued runs that dispatch resumes. - A run-only hint for a run row that does not exist resolves to no tasks (it was the whole company). A run row is not deleted while its tasks are open, except by company deletion, which sends the company hint. - Native finish writers now send run-scoped hints to the live-run recovery queues too (`notifyLiveRunRecovery`, `notifyLiveResourceRecovery`, attention retention). The legacy run paths already send these with the run id. - The fixture uses process-adapter runs, not native runs. The native writers are narrowed by code reading. Their effect on the hosted staging instance is not verified. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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 --- .../issue-recovery-activity-hints.test.ts | 215 ++++++++++++++++++ .../issue-recovery-deadlines.test.ts | 65 ++++++ .../chat-inbound-wake-notice-notifications.ts | 3 +- server/src/services/environments.ts | 7 +- .../execution-control-reconciliation.ts | 2 +- .../services/execution-recovery-resolution.ts | 4 +- server/src/services/heartbeat/queue.ts | 9 +- .../services/issue-recovery-notifications.ts | 10 +- .../native-failed-workspace-recovery.ts | 2 +- .../native-recovery-preparation-failure.ts | 2 +- .../native-runtime/native-restart-recovery.ts | 4 +- .../native-runtime/native-run-finalizer.ts | 6 +- .../native-runtime/native-run-projection.ts | 4 +- .../native-runtime/native-safe-replacement.ts | 2 +- .../native-runtime/native-session-executor.ts | 6 +- .../native-runtime/native-superseded-retry.ts | 2 +- server/src/services/recovery/changed-tasks.ts | 3 +- .../wake-request-claimed-settlement.ts | 2 +- server/src/services/recovery/work.ts | 16 +- server/src/services/work-intent-outbox.ts | 1 + 20 files changed, 329 insertions(+), 36 deletions(-) create mode 100644 server/src/__tests__/issue-recovery-activity-hints.test.ts diff --git a/server/src/__tests__/issue-recovery-activity-hints.test.ts b/server/src/__tests__/issue-recovery-activity-hints.test.ts new file mode 100644 index 00000000000..68accc0236e --- /dev/null +++ b/server/src/__tests__/issue-recovery-activity-hints.test.ts @@ -0,0 +1,215 @@ +import { appendFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { setImmediate as immediate } from "node:timers/promises"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { expect, it, vi } from "vitest"; +import { agents, heartbeatRunEvents, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import { trimWorkSignalStack, workSignalDebug } from "@paperclipai/db/work-signal-debug"; +import { issueService } from "../services/issues.js"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; +import { seedRecoveryPopulation } from "./helpers/recovery-population.js"; + +vi.hoisted(() => { process.env.PAPERCLIP_DEBUG_WORK_SIGNALS = "stranded-assignments:1,assigned-work-invariant:1"; }); + +const MINUTE = 60_000; +const measuring = Boolean(process.env.RECOVERY_ACTIVITY_REPORT); +const report = (label: string, summary: unknown) => { + if (process.env.RECOVERY_ACTIVITY_REPORT) appendFileSync(process.env.RECOVERY_ACTIVITY_REPORT, `${label} ${JSON.stringify(summary, null, 1)}\n`); +}; +const TASK_QUEUES = new Set(["stranded-assignments", "assigned-work-invariant", "resolved-dependencies", "stale-issue-locks"]); +type Recorded = { at: number; topic: string; name: string; fields: Record }; + +describeIssueRecovery("recovery checks while runs are active in a staging-shaped company", () => { + const state = issueRecoveryFixture({ meter: true }); + + async function advance(ms: number) { + const until = Date.now() + ms; + while (Date.now() < until) { + await vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now())); + await Promise.allSettled([...state.passes]); await immediate(); + } + } + + function record() { + const events: Recorded[] = []; + vi.spyOn(workSignalDebug, "event").mockImplementation((topic, name, fields = {}) => { + if (name === "check") events.push({ at: Date.now(), topic, name, fields }); + }); + vi.spyOn(workSignalDebug, "signal").mockImplementation((topic, hint) => { + if (!TASK_QUEUES.has(topic)) return; + const holder: { stack?: string } = {}; + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 40; + Error.captureStackTrace(holder); + Error.stackTraceLimit = limit; + const frames = trimWorkSignalStack(holder.stack, 30).filter(line => !/issue-recovery-notifications|run-dispatch-notifications|external-conversation-settlement-notifications|native-status-reassessment-notifications|execution-control-notifications|issue-review-state-notifications|mockImplementation|spy|vitest/.test(line)); + const short = (line: string) => line.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")"); + const app = frames.filter(line => /services|modules|routes/.test(line)); + const caller = app.length ? app.slice(0, process.env.RECOVERY_ACTIVITY_FRAMES ? Number(process.env.RECOVERY_ACTIVITY_FRAMES) : 1).map(short).join(" < ") + : short(frames[0] ?? "unknown"); + const kind = hint === undefined || hint === "*" ? "all" : (() => { + const scope = JSON.parse(hint) as Record; + return scope.issueId ? "task" : scope.graphRunId || scope.graphIssueId ? "graph" : scope.backstop ? "backstop" : "company"; + })(); + events.push({ at: Date.now(), topic, name: "signal", fields: { kind, caller } }); + }); + return events; + } + + function summarize(events: Recorded[], seconds: number) { + const checks: Record> = {}, signals: Record = {}, scoped: Record = {}; + for (const event of events) { + if (event.name === "check") { + const byQueue = checks[event.topic] ??= {}; + byQueue[String(event.fields.wake)] = (byQueue[String(event.fields.wake)] ?? 0) + 1; + } else if (event.topic === "stranded-assignments" && (event.fields.kind === "task" || event.fields.kind === "graph")) { + const key = `${event.fields.kind} ${event.fields.caller}`; + scoped[key] = (scoped[key] ?? 0) + 1; + } else if (event.fields.kind !== "task" && event.fields.kind !== "graph") { + const key = `${event.topic} ${event.fields.kind} ${event.fields.caller}`; + signals[key] = (signals[key] ?? 0) + 1; + } + } + const perSecond = Object.fromEntries(Object.entries(checks).map(([queue, byReason]) => [queue, Object.fromEntries( + Object.entries(byReason).map(([reason, count]) => [reason, Number((count / seconds).toFixed(2))]))])); + const total = (queue: string) => Object.values(checks[queue] ?? {}).reduce((sum, count) => sum + count, 0); + return { checks, perSecond, signals, scoped, stranded: total("stranded-assignments"), assigned: total("assigned-work-invariant") }; + } + + async function provider(companyId: string, workerIds: string[]) { + const failures: unknown[] = []; + const listener = createServer(async (request, response) => { + try { + let body = ""; + for await (const chunk of request) body += chunk; + const { runId } = JSON.parse(body) as { runId: string }; + const [run] = await state.db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))); + if (!run!.contextSnapshot?.issueId) { response.end("ok"); return; } + const issueId = String(run!.contextSnapshot?.issueId); + const deadlocked = (error: unknown): boolean => typeof error === "object" && error !== null + && ((error as { code?: string }).code === "40P01" || deadlocked((error as { cause?: unknown }).cause)); + const retryDeadlock = async (write: () => Promise) => { + for (let attempt = 1; ; attempt++) { + try { return await write(); } catch (error) { if (attempt >= 3 || !deadlocked(error)) throw error; } + } + }; + await retryDeadlock(() => issueService(state.db).addComment(issueId, "Progress: done with this step", { agentId: run!.agentId, runId })); + await retryDeadlock(() => issueService(state.db).update(issueId, { status: "in_review" })); + response.end("ok"); + } catch (error) { failures.push(error); response.statusCode = 500; response.end("failed"); } + }); + await new Promise(resolve => listener.listen(0, "127.0.0.1", resolve)); + const port = (listener.address() as { port: number }).port; + const script = `fetch("http://127.0.0.1:${port}/progress",{method:"POST",body:JSON.stringify({runId:process.env.PAPERCLIP_RUN_ID})}).then(r=>{if(!r.ok)process.exitCode=1;console.log("ok")})`; + await state.db.update(agents).set({ adapterConfig: { command: process.execPath, args: ["-e", script], cwd: process.cwd() } }) + .where(inArray(agents.id, workerIds)); + return { failures, close: async () => { listener.closeAllConnections(); await new Promise(resolve => listener.close(() => resolve())); } }; + } + + async function measure(runsPerMinute: number, minutes: number, timerRunsPerMinute = 0) { + const f = await state.fixture(); + const population = await seedRecoveryPopulation(state.db, f.companyId, { agents: 50, inReview: 780, inProgress: 40, todo: 30, + recoveryActions: 12, terminated: 3 }); + const workers = population.agentIds.slice(7, 7 + 41); + const fake = await provider(f.companyId, workers); + const events = record(); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + await state.start({}); + await advance(10 * MINUTE); + events.length = 0; + const counts = async () => { + const [runs] = await state.db.select({ finished: sql`count(*) filter (where ${heartbeatRuns.status} = 'succeeded')::int`, + failed: sql`count(*) filter (where ${heartbeatRuns.status} = 'failed')::int`, all: sql`count(*)::int` }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.runtimeMode, "legacy"))); + const [events] = await state.db.select({ n: sql`count(*)::int` }).from(heartbeatRunEvents) + .where(eq(heartbeatRunEvents.companyId, f.companyId)); + const [comments] = await state.db.select({ n: sql`count(*)::int` }).from(issueComments) + .where(and(eq(issueComments.companyId, f.companyId), sql`${issueComments.authorAgentId} is not null`)); + return { ...runs!, events: events!.n, agentComments: comments!.n }; + }; + const workBefore = await counts(); + const before = state.meter.read(); + const startedAt = Date.now(); + const byCheck: Record = {}, settingsCallers: Record = {}; + const tally = (log: ReturnType) => { + for (const entry of log) { + const stack = entry.stack ?? ""; + const owner = stack.includes("reconcileStrandedAssignedIssues") ? "stranded-assignments" + : /assigned-work-sweep|checkIssue/.test(stack) ? "assigned-work-invariant" + : stack.includes("sweepStaleIssueLocks") ? "stale-issue-locks" : stack.includes("recovery/work.ts") ? "recovery-loads" : "other"; + byCheck[owner] = (byCheck[owner] ?? 0) + 1; + if (/from "instance_settings"/.test(entry.sql)) { + const frame = stack.split("\n").map(line => line.trim()).find(line => /server\/src\/services\//.test(line) && !/instance-settings/.test(line)) ?? "unknown"; + const key = `${owner} ${frame.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")")}`; + settingsCallers[key] = (settingsCallers[key] ?? 0) + 1; + } + } + }; + if (measuring) state.meter.startLog({ stacks: true }); + let next = 12; + for (let minute = 0; minute < minutes; minute++) { + const minuteEnds = startedAt + (minute + 1) * MINUTE; + for (let started = 0; started < runsPerMinute; started++) { + const issueId = population.inReview[next++ % population.inReview.length]!; + const comment = await issueService(state.db).addComment(issueId, "Please take another pass", { userId: "recovery-user" }); + const [task] = await state.db.select({ assigneeAgentId: issues.assigneeAgentId }).from(issues).where(eq(issues.id, issueId)); + await state.heartbeat.wakeup(task!.assigneeAgentId!, { source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: comment.id, mutation: "comment" }, requestedByActorType: "user", requestedByActorId: "recovery-user", + contextSnapshot: { issueId, taskId: issueId, commentId: comment.id, wakeCommentId: comment.id, source: "issue.comment", + wakeReason: "issue_commented" } }); + await vi.advanceTimersByTimeAsync(Math.floor(MINUTE / runsPerMinute / 4)); + } + for (let timer = 0; timer < timerRunsPerMinute; timer++) { + await state.heartbeat.wakeup(workers[(minute * timerRunsPerMinute + timer) % workers.length]!, { source: "on_demand", triggerDetail: "manual", + reason: "manual", requestedByActorType: "user", requestedByActorId: "recovery-user", + contextSnapshot: { source: "scheduler", reason: "interval_elapsed", now: new Date().toISOString() } }); + } + await advance(minuteEnds - Date.now()); + await state.heartbeat.drainActiveRunExecutions(); + if (measuring) tally(state.meter.stopLog()); + if (measuring) state.meter.startLog({ stacks: true }); + } + const seconds = (Date.now() - startedAt) / 1000; + const after = state.meter.read(); + if (measuring) tally(state.meter.stopLog()); + const workAfter = await counts(); + const work = { started: workAfter.all - workBefore.all, finished: workAfter.finished - workBefore.finished, + failed: workAfter.failed - workBefore.failed, events: workAfter.events - workBefore.events, + agentComments: workAfter.agentComments - workBefore.agentComments }; + const summary = { ...summarize(events, seconds), seconds, work, + statementsPerSecond: Number(((after.statements - before.statements) / seconds).toFixed(1)), + agentWriteFailures: fake.failures.length, + statementsPerSecondBy: Object.fromEntries(Object.entries(byCheck).map(([owner, count]) => [owner, Number((count / seconds).toFixed(1))])), + instanceSettingsReads: settingsCallers }; + await fake.close(); + return summary; + } + + function expectWorkload(summary: Awaited>, taskRuns: number, tasklessRuns: number) { + expect(summary.agentWriteFailures).toBe(0); + expect(summary.work.started).toBeGreaterThanOrEqual(taskRuns + tasklessRuns); + expect(summary.work.finished).toBeGreaterThanOrEqual(taskRuns + tasklessRuns); + expect(summary.work.failed).toBeLessThanOrEqual(Math.ceil(0.1 * summary.work.started)); + expect(summary.work.agentComments).toBeGreaterThanOrEqual(taskRuns); + expect(summary.work.events).toBeGreaterThan(summary.work.finished); + } + + it("re-checks only the tasks seven runs a minute touch, among 850 open tasks", async () => { + const minutes = measuring ? 10 : 4; + const summary = await measure(7, minutes, 1); + report("7 runs/min", summary); + expectWorkload(summary, 7 * minutes, minutes); + expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0); + expect(summary.signals).toEqual({}); + expect(summary.stranded / summary.seconds).toBeLessThan(2); + }, 1_800_000); + + it.runIf(measuring)("re-checks only the tasks fifty runs a minute touch, among 850 open tasks", async () => { + const summary = await measure(50, 6, 5); + report("50 runs/min", summary); + expectWorkload(summary, 300, 30); + expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0); + expect(summary.signals).toEqual({}); + expect(summary.stranded / summary.seconds).toBeLessThan(3); + }, 1_800_000); +}); diff --git a/server/src/__tests__/issue-recovery-deadlines.test.ts b/server/src/__tests__/issue-recovery-deadlines.test.ts index a63b1e3a983..b2344c7c4fc 100644 --- a/server/src/__tests__/issue-recovery-deadlines.test.ts +++ b/server/src/__tests__/issue-recovery-deadlines.test.ts @@ -8,12 +8,15 @@ import { heartbeatService } from "../services/heartbeat.js"; import { issueService } from "../services/issues.js"; import { issueRecoveryActionService } from "../services/issue-recovery-actions.js"; import { registerIssueRecoveryWork } from "../services/recovery/work.js"; +import { changedTaskCondition } from "../services/recovery/changed-tasks.js"; import { recoveryService } from "../services/recovery/service.js"; import { ISSUE_RECOVERY_BACKSTOP_MS, ISSUE_RECOVERY_MAX_ISSUE_IDS, notifyIssueRecovery, resolveIssueGraph } from "../services/issue-recovery-notifications.js"; import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js"; import { notifyExecutionRunWork } from "../services/execution-control-notifications.js"; import { notifyRunDispatch } from "../services/run-dispatch-notifications.js"; +import { notifyExternalConversationSettlement } from "../services/external-conversation-settlement-notifications.js"; +import { notifyChatInboundWakeNotices } from "../services/chat-inbound-wake-notice-notifications.js"; import { promoteDeferredWorkIntents } from "../services/work-intent-outbox.js"; import { taskWatchdogService } from "../services/task-watchdogs.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; @@ -183,6 +186,68 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => await graph.backlog(4000); expect(await lifecycleEvent(finished())).toBe(first); }); + it("re-checks a run's own tasks for its settlement, lease and dispatch writers, and nothing for a run without a task", async () => { + const f = await fixture(); + const graph = await runGraph(f.companyId, f.agentId); + await graph.backlog(300); + const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "succeeded", + finishedAt: new Date(), contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id }); + const checked: string[] = []; + const assigned: string[] = []; + await recordedRecovery({ + stranded: async scope => { checked.push(scope.issueId); }, + assignedWork: { + listSuspects: (scope, cursor, limit) => recoveryService(state.db, { enqueueWakeup: async () => null }) + .assignedWork.listSuspects(scope, cursor, limit), + checkIssue: async scope => { assigned.push(scope.issueId); }, + }, + }, { backstopMs: 60 * 60_000 }); + await settleWork({ backstopPending: true }); + const writers = (runId: string): Array<(tx: object) => Promise> => [ + tx => notifyRunDispatch(tx, { companyId: f.companyId, runId }), + tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId }), + tx => notifyExternalConversationSettlement(tx, { companyId: f.companyId, runId }), + tx => notifyChatInboundWakeNotices(tx, { companyId: f.companyId, runId }), + tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "lock_released", issueId: null, runId }), + ]; + for (const [runId, expected] of [[graph.runId, graph.affected], [taskless.id, []]] as Array<[string, string[]]>) { + for (const writer of writers(runId)) { + checked.length = 0; assigned.length = 0; + await state.db.transaction(tx => writer(tx)); + await settleWork({ backstopPending: true }); + expect([...new Set(checked)].sort()).toEqual(expected); + expect(assigned.every(id => expected.includes(id))).toBe(true); + await vi.advanceTimersByTimeAsync(31_000); + } + } + checked.length = 0; assigned.length = 0; + await issueService(state.db).addComment(graph.siblingId, "A note on the next task", { userId: "recovery-user" }); + await settleWork({ backstopPending: true }); + expect(checked).toEqual([graph.siblingId]); + expect(assigned.every(id => id === graph.siblingId)).toBe(true); + }); + it("counts an agent's own run heartbeat as no change to its other tasks, and a resume as a change", async () => { + const f = await fixture(); + const old = new Date(Date.now() - 60 * 60_000); + const tasks = await state.db.insert(issues).values(Array.from({ length: 5 }, (_, index) => ({ companyId: f.companyId, + title: `Waiting ${index}`, status: "todo", assigneeAgentId: f.agentId, createdAt: old, updatedAt: old }))).returning({ id: issues.id }); + const since = new Date(Date.now() - 5 * 60_000); + const changed = async () => (await state.db.select({ id: issues.id }).from(issues) + .where(and(eq(issues.companyId, f.companyId), changedTaskCondition(since)))).map(row => row.id).sort(); + const heartbeatAt = new Date(); + await state.db.update(agents).set({ status: "idle", lastHeartbeatAt: heartbeatAt, updatedAt: heartbeatAt }).where(eq(agents.id, f.agentId)); + expect(await changed()).toEqual([]); + await state.db.update(agents).set({ status: "idle", updatedAt: new Date(heartbeatAt.getTime() + 1000) }).where(eq(agents.id, f.agentId)); + expect(await changed()).toEqual(tasks.map(row => row.id).sort()); + }); + it("resolves a run without a task to no tasks and a missing task to the whole company", async () => { + const f = await fixture(); + const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", + contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id }); + expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: taskless.id })).toEqual([]); + expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: randomUUID() })).toEqual([]); + expect(await resolveIssueGraph(state.db, { companyId: f.companyId, issueId: randomUUID() })).toBeNull(); + }); it("resolves a run's task graph through index lookups, not the backlog", async () => { const f = await fixture(); const graph = await runGraph(f.companyId, f.agentId); diff --git a/server/src/services/chat-inbound-wake-notice-notifications.ts b/server/src/services/chat-inbound-wake-notice-notifications.ts index 9137e51b72f..7f38fd8b9a9 100644 --- a/server/src/services/chat-inbound-wake-notice-notifications.ts +++ b/server/src/services/chat-inbound-wake-notice-notifications.ts @@ -2,7 +2,8 @@ import { notifyExternalConversationSettlement } from "./external-conversation-se import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import type { InboundWakeNoticeScope } from "./chat-channels/inbound/wakeup-notices.js"; -export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope, options: { notifySettlement?: boolean } = {}) { +export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope & { runId?: string }, + options: { notifySettlement?: boolean } = {}) { if (options.notifySettlement !== false) await notifyExternalConversationSettlement(tx, scope); const hint = JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatInboundWakeNotices, hint); diff --git a/server/src/services/environments.ts b/server/src/services/environments.ts index b0d57b588f5..84eda427ec3 100644 --- a/server/src/services/environments.ts +++ b/server/src/services/environments.ts @@ -1778,7 +1778,7 @@ export function environmentService(db: Db) { (options?.cleanupStatus !== undefined && previous.cleanupStatus !== options.cleanupStatus) || (status !== "retained" && !previous.releasedAt))) { await notifyChatInboundWakeNotices(tx, { - companyId: previous.companyId, issueId: previous.issueId ?? undefined, + companyId: previous.companyId, issueId: previous.issueId ?? undefined, runId: previous.heartbeatRunId, }); } if (previous.heartbeatRunId && ["active", "pending_cleanup"].includes(previous.status) @@ -1789,7 +1789,8 @@ export function environmentService(db: Db) { // Messages saved behind a finished run wait for its cleanup to // settle. Reconsider them through normal deferred admission. await notifyDeferredExecutionWork(tx, { companyId: previous.companyId }); - await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId }); + await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId, + runId: previous.heartbeatRunId }); } if (previous.creationOperationId && previous.status === "pending_cleanup" && options?.cleanupStatus === "success" && status !== "pending_cleanup") { await tx.update(sandboxCreationOperations).set({ state: "resolved", updatedAt: now }) @@ -1932,7 +1933,7 @@ export function environmentService(db: Db) { await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId: heartbeatRunId }); await notifyDeferredExecutionWork(tx, { companyId: run.companyId }); await promoteDeferredWorkIntents(tx, { companyId: run.companyId, trigger: "lock_released", - issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null }); + issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null, runId: heartbeatRunId }); } return tx.update(environmentLeases) .set({ diff --git a/server/src/services/execution-control-reconciliation.ts b/server/src/services/execution-control-reconciliation.ts index 8b8e6d41617..3bfc73d77c9 100644 --- a/server/src/services/execution-control-reconciliation.ts +++ b/server/src/services/execution-control-reconciliation.ts @@ -267,7 +267,7 @@ export async function reconcileAbandonedExecutionControl( await notifyNativeEnvironmentSettlement(tx, { companyId: run.companyId, runId: run.id }); await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id }); await notifyUnsafeWorkspaceExportRunChange(tx, run); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); const [updatedRun] = await tx .update(heartbeatRuns) .set({ diff --git a/server/src/services/execution-recovery-resolution.ts b/server/src/services/execution-recovery-resolution.ts index 7b0cb23dd52..b1161d584f8 100644 --- a/server/src/services/execution-recovery-resolution.ts +++ b/server/src/services/execution-recovery-resolution.ts @@ -827,7 +827,7 @@ export async function settleUnrecoverableExecutions( companyId: run.companyId, issueId: task.id, runId: run.id, }).limit(1).for("update") : []; if (!hold) return void await continueNativeInterruption(tx as unknown as Db, { action, run, coordinator, now }); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); const note = "Exact session recovery stopped. The recorded workspace recovery holds this execution without replaying its actions."; await tx.update(issueRecoveryActions).set({ status: "cancelled", outcome: "cancelled", resolvedAt: now, updatedAt: now, wakePolicy: null, monitorPolicy: null, @@ -962,7 +962,7 @@ export async function settleUnrecoverableExecutions( replay: "not_authorized", }, }); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); await tx .update(heartbeatRuns) .set({ executionStatusDeliveryId: randomUUID() }) diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 221a9284839..74b219eb610 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -10,7 +10,7 @@ import { refreshRunStartYieldIfStale } from "../run-start-handover.js"; import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js"; import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, recheckQueuedRunInteractions, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js"; import { deferredWorkIntentWait } from "../work-intent-outbox.js"; -import { notifyIssueRecovery } from "../issue-recovery-notifications.js"; +import { notifyIssueGraphRecovery } from "../issue-recovery-notifications.js"; import { createHeartbeatTimerPolicy } from "./timer-policy.js"; import { QUEUED_RUN_AGING_MS, RECOVERY_WAKE_REASONS, createQueuedRunDispatcher, hasQueuedRunAged, queuedRunDispatchClass } from "./queued-run-dispatch-order.js"; import { reserveAutomaticRunStart } from "../recovery/automatic-run-brake.js"; @@ -587,7 +587,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const receipts = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(owned).for("update"); if (!receipts.length) return; // Register the recovery signal before the write it announces. - await notifyIssueRecovery(tx, { companyId: run.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: run.companyId, runId: run.id }); await tx.update(agentWakeupRequests).set({ idempotencyKey: null, payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) @@ -5392,8 +5392,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende return mergedRun; } + const queuedRunId = randomUUID(); const queueOutcome = await db.transaction(async (tx) => { - await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId) }); + await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId), + runId: readNonEmptyString(enrichedContextSnapshot.issueId) ? undefined : queuedRunId }); await tx.execute( sql`select id from agents where id = ${agentId} and company_id = ${agent.companyId} for update`, ); @@ -5463,6 +5465,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const newRun = await tx .insert(heartbeatRuns) .values({ + id: queuedRunId, companyId: agent.companyId, agentId, scopeKind: readNonEmptyString(enrichedContextSnapshot.issueId) ? "issue" : "company", diff --git a/server/src/services/issue-recovery-notifications.ts b/server/src/services/issue-recovery-notifications.ts index 5c5038d5425..37034c76bef 100644 --- a/server/src/services/issue-recovery-notifications.ts +++ b/server/src/services/issue-recovery-notifications.ts @@ -20,11 +20,8 @@ const TASK_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.strandedAssignments, DELIV export async function notifyIssueRecovery(transaction: object, scope?: IssueRecoveryScope) { const companyHint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*"; const issueHint = scope ? JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }) : "*"; - for (const queue of [DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.assignedWorkInvariant, DELIVERY_QUEUES.resolvedDependencies, - DELIVERY_QUEUES.taskWatchdogs, DELIVERY_QUEUES.staleIssueLocks]) { - await notifyDeliveryWork(transaction, queue, - queue === DELIVERY_QUEUES.strandedAssignments || queue === DELIVERY_QUEUES.staleIssueLocks ? issueHint : companyHint); - } + for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint); + for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, issueHint); } export function issueRecoveryBackstopHint(companyId: string) { @@ -71,5 +68,6 @@ export async function resolveIssueGraph(db: Db, scope: { companyId: string; runI and issue_id in (select id from seed) limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1}) ) select id::text as id from affected limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1}`); const issueIds = rows.map(row => row.id).sort(); - return issueIds.length && issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null; + if (issueIds.length === 0) return scope.issueId ? null : []; + return issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null; } diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.ts index bc37846ba7f..f693698265d 100644 --- a/server/src/services/native-runtime/native-failed-workspace-recovery.ts +++ b/server/src/services/native-runtime/native-failed-workspace-recovery.ts @@ -161,7 +161,7 @@ export async function preserveNativeFailedWorkspace(db: Db, selected: Pick, recoveryRequestId: string | null) { - await notifyExecutionRunWork(tx, { companyId: row.run.companyId }); + await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id }); await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null, nextAttemptAt: null, failureCode: "native_restart_recovery_blocked", failureDetail: { ...row.coordinator.failureDetail, reason, executorStopEvidence: "unverified" }, @@ -1932,7 +1932,7 @@ export async function claimNativeRestartRecoveries(input: { recycledProviderPids: providerProcesses.recycledPids, stderrTail: row.run.stderrExcerpt, }); - await notifyExecutionRunWork(tx, { companyId: row.run.companyId }); + await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id }); await tx .update(nativeRunFinalizations) .set({ diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index d9c07e2ab65..df6232eb978 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -405,7 +405,7 @@ export async function endSupersededNativeFinalizationRuns(db: Db, runIds?: reado : accepted === "succeeded" ? "succeeded" as const : accepted === "cancelled" ? "cancelled" as const : "failed" as const; await notifyNativeFinalizationWork(tx, { companyId: run.companyId, runId: run.id }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId }); await notifyInstructionCollection(tx, { companyId: run.companyId, runId: run.id }); await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id }); @@ -626,7 +626,7 @@ async function recordRetryableFailure(input: { if (phase === "terminal_failure" && failureCode === "native_workspace_sync_out_unsafe_archive") { await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId }); } - await notifyExecutionRunWork(tx, { companyId: input.run.companyId }); + await notifyExecutionRunWork(tx, { companyId: input.run.companyId, runId: input.run.id }); await notifyChatRunMilestones(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId }); await tx .update(nativeRunFinalizations) @@ -2077,7 +2077,7 @@ export async function finalizeNativeRun(input: { if (input.projectRunStatus) await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id }); if (input.projectRunStatus) await notifyUnsafeWorkspaceExportRunChange(tx, run); if (input.projectRunStatus) await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId }); const [after] = await projectRun(tx); if (after && input.projectRunStatus) await settleNativeTerminalWake(tx, after); diff --git a/server/src/services/native-runtime/native-run-projection.ts b/server/src/services/native-runtime/native-run-projection.ts index c36e9b251dd..b480977eb23 100644 --- a/server/src/services/native-runtime/native-run-projection.ts +++ b/server/src/services/native-runtime/native-run-projection.ts @@ -51,7 +51,7 @@ export async function settleNativeTerminalWake(tx: Db, run: Pick= ${at}) or exists (select 1 from issue_comments c where c.company_id = ${issues.companyId} and c.issue_id = ${issues.id} and c.created_at >= ${at}) - or exists (select 1 from agents ag where ag.id = ${issues.assigneeAgentId} and ag.updated_at >= ${at}))`; + or exists (select 1 from agents ag where ag.id = ${issues.assigneeAgentId} and ag.updated_at >= ${at} + and (ag.last_heartbeat_at is null or ag.last_heartbeat_at < ag.updated_at)))`; } diff --git a/server/src/services/recovery/wake-request-claimed-settlement.ts b/server/src/services/recovery/wake-request-claimed-settlement.ts index 68ac1146803..d676ed543d5 100644 --- a/server/src/services/recovery/wake-request-claimed-settlement.ts +++ b/server/src/services/recovery/wake-request-claimed-settlement.ts @@ -64,7 +64,7 @@ export async function settleClaimedWakeRequest(db: Db, record: InProgressRecord, .where(claim).for("update"); if (!current) return { settled: false, reason: "claim_no_longer_held" }; // Work intents before the write they announce (sleep-aware background work). - await notifyExternalConversationSettlement(tx, { companyId: run.companyId }); + await notifyExternalConversationSettlement(tx, { companyId: run.companyId, runId: run.id }); await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: current.agentId }); const updated = await tx.update(agentWakeupRequests).set({ status: wakeStatusFor(run.status), diff --git a/server/src/services/recovery/work.ts b/server/src/services/recovery/work.ts index 9926f1c9fb8..53511dde244 100644 --- a/server/src/services/recovery/work.ts +++ b/server/src/services/recovery/work.ts @@ -76,6 +76,8 @@ export function registerIssueRecoveryWork( const scopeKey = (scope: IssueRecoveryScope | undefined) => scope ? JSON.stringify([scope.companyId, scope.issueId, scope.graphRunId, scope.graphIssueId, scope.backstop]) : "*"; const isGraph = (scope: IssueRecoveryScope | undefined) => Boolean(scope?.graphRunId || scope?.graphIssueId); + const loadOrigin = (scope: IssueRecoveryScope | undefined) => !workSignalDebug.enabled ? undefined : !scope ? "reload" as const + : scope.backstop ? "backstop" as const : scope.issueId || isGraph(scope) ? "hint" as const : "company" as const; const graphs = new Map }>(); async function resolveGraph(scope: IssueRecoveryScope | undefined) { if (!scope || !isGraph(scope)) return; @@ -115,6 +117,7 @@ export function registerIssueRecoveryWork( 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 }; + if (scope?.issueIds?.length === 0) return { rows: [], complete: true }; const cursor = cursors.get(key); const changedSince = passes.changedSince(scope, key, !cursor); const rows = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(and( @@ -133,8 +136,7 @@ export function registerIssueRecoveryWork( if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); passes.loaded(scope, key, complete); const keepUnseen = changedSince ? { keepUnseen: true as const } : {}; - const origin = !workSignalDebug.enabled ? undefined : !scope ? "reload" as const : scope.backstop ? "backstop" as const - : scope.issueId || isGraph(scope) ? "hint" as const : "company" as const; + const origin = loadOrigin(scope); return { rows: rows.map(row => ({ ...row, dueAt: Date.now(), ...(origin ? { origin } : {}) })), complete, ...keepUnseen }; }, check: async entry => { @@ -172,22 +174,28 @@ export function registerIssueRecoveryWork( const key = scopeKey(scope); if (!enabled) { cursors.delete(key); return []; } if (await toCompany(scope, worker)) return { rows: null, complete: true }; + if (scope?.issueIds?.length === 0) return { rows: [], complete: true }; const changedSince = passes.changedSince(scope, key, !cursors.has(key)); const rows = await sweep.listSuspects(scope ? { companyId: scope.companyId, issueId: scope.issueId, issueIds: scope.issueIds, ...(changedSince ? { changedSince } : {}) } : {}, cursors.get(key) ?? null, PAGE_SIZE); const complete = rows.length < PAGE_SIZE; if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); passes.loaded(scope, key, complete); + const origin = loadOrigin(scope); return { rows: rows.map(row => ({ id: row.id, companyId: row.companyId, updatedAt: row.updatedAt.getTime(), dueAt: Date.now(), - ...(scope?.backstop ? { fromBackstop: true as const } : {}) })), complete, ...(changedSince ? { keepUnseen: true as const } : {}) }; + ...(scope?.backstop ? { fromBackstop: true as const } : {}), ...(origin ? { origin } : {}) })), complete, + ...(changedSince ? { keepUnseen: true as const } : {}) }; }, check: async entry => { if (!enabled) return null; + if (workSignalDebug.enabled) workSignalDebug.event(DELIVERY_QUEUES.assignedWorkInvariant, "check", { issueId: entry.id, + companyId: entry.companyId, wake: entry.fromDeadline ? "deadline" : entry.origin ?? "load", dueAt: entry.dueAt }); let next: number | null = null, unchanged = false; await sweep.checkIssue({ companyId: entry.companyId, issueId: entry.id, onDeferredDeadline: (at, detail) => { next = next === null ? at : Math.min(next, at); unchanged ||= detail?.unchanged === true; } }); const { unchanged: _previous, fromBackstop: _source, ...rest } = entry; - return next === null ? null : { ...rest, dueAt: next, ...(unchanged ? { unchanged: true as const } : {}) }; + return next === null ? null : { ...rest, dueAt: next, ...(unchanged ? { unchanged: true as const } : {}), + ...(workSignalDebug.enabled ? { fromDeadline: true as const } : {}) }; }, }, canRun); return worker; diff --git a/server/src/services/work-intent-outbox.ts b/server/src/services/work-intent-outbox.ts index 39da2efca12..7ec9e6dee10 100644 --- a/server/src/services/work-intent-outbox.ts +++ b/server/src/services/work-intent-outbox.ts @@ -71,6 +71,7 @@ export async function promoteDeferredWorkIntents(tx: object, input: { .select({ id: budgetPolicies.id }).from(budgetPolicies).where(and(eq(budgetPolicies.companyId, input.companyId), eq(budgetPolicies.isActive, true), eq(budgetPolicies.hardStopEnabled, true))).limit(1)).length > 0 : true; const scope = input.trigger === "lock_released" && input.issueId ? { companyId: input.companyId, issueId: input.issueId } + : input.trigger === "lock_released" && input.runId ? { companyId: input.companyId, runId: input.runId } : input.trigger === "accounting_settled" && input.runId && !hardStop ? { companyId: input.companyId, runId: input.runId } : null; // Register the work signals before the write they announce. await notifyRunDispatch(tx, scope ?? { companyId: input.companyId }); From df9914dbd98ce4b188526f8c11ac1310149c0d2c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:02:31 -0600 Subject: [PATCH 13/20] fix(native): let the outgoing server checkpoint its idle warm session while the incoming follow-up waits for it (#21791) 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. A warm agent session stays with the outgoing server that ran its last turn. > - Since #21774, a follow-up that the incoming server claims during the overlap waits (`native_controller_recovery_waiting_for_owner`) and checks again every 5 s. > - About 1 s after the traffic switch (#21627), the outgoing server tries to save and close its idle warm session. The checkpoint fence refuses that save with `native_runner_checkpoint_owner_lost`. The task's current run is the parked follow-up. That run has its own finalization row under another controller boot, and the fence does not accept that kind of successor. > - The close retry from #21782 fails the same way each time. So the follow-up waits until the outgoing server exits, or until the predecessor's finish time plus the idle window plus 2 min. In the CHA-5 case that was about 225 s, and the worst case is about 425 s. Speed is a requirement. > - This pull request records which owner a parked follow-up waits on, and lets the fence accept the outgoing owner's final save when the follow-up is parked on exactly that owner and has not started. > - The benefit is that the outgoing server saves and closes the session on its first attempt, and the follow-up continues at its next 5 s check. ## Linked Issues or Issue Description Refs #21774, #21782, #21697, #21627, #21279 **What happened?** During a release-swap overlap, a warm follow-up was claimed by the incoming server while the outgoing server still owned the idle warm session. The follow-up waited correctly. The outgoing server's idle close failed with `native_runner_checkpoint_owner_lost` on every attempt. The wait ended only when the outgoing server exited, about 225 s after the follow-up was created. **Expected behavior** The outgoing server saves and closes the session while the follow-up waits. The follow-up sees the saved session and continues within one 5 s check. **Steps to reproduce** 1. Run a warm native session on a remote sandbox and let a run finish on server A. 2. Start server B with an overlap and switch traffic to it. 3. Post a follow-up comment so that B claims the follow-up while A is still alive. 4. A's idle close fails with `native_runner_checkpoint_owner_lost`, and the follow-up waits until A exits. **Paperclip version or commit** master `d14a3b88b1`. ## What Changed - `NativeControllerRecoveryWaitingError` carries the owner that the follow-up waits on: the predecessor run and its controller boot. `waitForLiveWarmSessionOwner` and the live-owner wait in `inspectRemoteWarmSessionRecovery` set it. - `deferNativeControllerRecovery` stores that owner in the finalization `failureDetail.waitingForOwner`. The executor passes it through. - `validateNativeRunnerCheckpointOwner` accepts one more successor kind: a parked follow-up waiting on this exact owner. All of these must be true, or the fence still refuses: - The checkpoint holds an accepted result and has no new work (unchanged rule). - The follow-up finalization is `retryable_failure` with `native_controller_recovery_waiting_for_owner`, `attempt = 0`, no result, and no lease owner (no claim is running it). - `waitingForOwner` names this owner's run and controller boot. - The follow-up run is a running native run for the same company and task, on the same native session as the owner's run. - The follow-up has no process fields, no own process-start events, and no checkpoint rows. - The fence locks the follow-up's finalization row (`for share`), so a resumption claim and the save cannot interleave. - Tests in `native-controller-recovery.integration.test.ts` (real Postgres): - The outgoing server saves and closes its idle warm session while the incoming follow-up waits, and the follow-up resumes within one recheck. - Negative cases: the save is still refused when the follow-up has its own process, its own process-start event, its own checkpoint, or a live resumption claim, or when it waits on a different owner boot or run. ## Verification - Red on master: with the `native-runner-checkpoint.ts` change removed, the scenario test fails with `native_runner_checkpoint_owner_lost` at the outgoing server's first close attempt. The follow-up keeps waiting. Green with the change. - The negative cases pass with and without the change. - Measured in the test scenario (warm idle window 600 s): - Before: the follow-up waits until the outgoing server exits, or about 720 s (finish + 600 s idle window + 120 s margin). - After: the outgoing save and close succeed on the first attempt. The follow-up is claimable and its wait resolves at `retryAt`, 4998 ms after it parked. - `vitest run` of `native-controller-recovery.integration.test.ts`, `native-runner-restart-recovery.integration.test.ts` and `native-harness-backup-storage.integration.test.ts`: 349 passed, 14 skipped. - `vitest run` of `native-session-executor.test.ts`, `remote-warm-session-recovery.test.ts`, `native-runner-checkpoint-save.test.ts`, `native-runner-checkpoint-retirement.test.ts` and `native-runner-checkpoint-authority.integration.test.ts`: 1566 passed, 7 skipped. - `tsc --noEmit` for `server` passes. - `pnpm verify` exits 2 (opaque setup dependency). Required CI supplies the broad coverage. - Not run: a release-swap wave. The fix is not yet measured on a live overlap. ## Risks - The fence is wider. It accepts only a final save with an accepted result and no new work, and only while the current run is parked on this exact owner and has not started. A follow-up that has a claim, a process, process-start events or checkpoint rows still causes a refusal. - A follow-up that a server parked before this change has no `waitingForOwner`. The fence refuses its owner's save as before. At its next recheck, the follow-up parks again with the owner recorded. - While a resumption claim runs the follow-up's recheck (a short window every 5 s), the save is refused. The close retry from #21782 then tries again. ## Model Used - Anthropic Claude Opus 5.5 (`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 - [ ] 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 --- ...ve-controller-recovery.integration.test.ts | 140 +++++++++++++++++- .../native-controller-recovery.ts | 10 +- .../native-runner-checkpoint.ts | 30 +++- .../native-runtime/native-session-executor.ts | 2 +- .../remote-warm-session-recovery.ts | 8 +- 5 files changed, 175 insertions(+), 15 deletions(-) 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 8e43a723ef6..71024185b23 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 @@ -8,14 +8,15 @@ import { createHash, randomUUID } from "node:crypto"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; 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"; import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; -import { nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js"; +import { assertNativeRunnerCheckpointOwner, loadNativeRunnerCheckpoint, nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js"; +import { assertNativeHarnessBackupOwner, nativeHarnessBackupOwner } from "./native-harness-backup-storage.js"; import { assertNativeRetainedSandboxBinding, createNativeControllerRecovery, deferNativeControllerRecovery, deferNativeRunForBusyAgentDirectory, NATIVE_AGENT_DIRECTORY_BUSY_WAIT, importNativeControllerRecovery, NativeControllerRecoveryWaitingError, NATIVE_RETAINED_OWNER_WAIT, resolveNativeControllerRecovery } from "./native-controller-recovery.js"; import { claimNativeSessionResumptions } from "./native-finalization-reconciler.js"; import { claimNativeRestartRecoveries, currentNativeControllerIdentity } from "./native-restart-recovery.js"; @@ -27,6 +28,7 @@ import { inspectRemoteWarmSessionRecovery, waitForLiveWarmSessionOwner } from ". import { currentProcessSpaceHash } from "../controller-process-identity.js"; import { registerControllerInstanceDb, resetControllerInstanceLeaseForTests } from "../controller-instance-lease.js"; import { readProcessStartedAt } from "../hot-restart.js"; +import { PROCESS_START_REQUESTED } from "../native-process-start-events.js"; describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable discovery and import", () => { let database: Awaited>; @@ -610,17 +612,20 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d 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(), + const { inspect, recordOwner, runId, current, fixture } = await seedWarmFollowUpOnOldServer(); + const outgoingBoot = randomUUID(); + await recordOwner({ controllerBootId: outgoingBoot, 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.owner).toEqual({ runId: fixture.scope.runId, controllerBootId: outgoingBoot }); expect(waiting.retryAt.getTime()).toBeGreaterThan(before); expect(waiting.retryAt.getTime()).toBeLessThanOrEqual(Date.now() + 10_000); - await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt }); + await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt, waitingForOwner: waiting.owner }); 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 }); + .toMatchObject({ phase: "retryable_failure", attempt: 0, failureCode: NATIVE_RETAINED_OWNER_WAIT, resultId: null, + failureDetail: expect.objectContaining({ waitingForOwner: { runId: fixture.scope.runId, controllerBootId: outgoingBoot } }) }); const [task] = await db.select().from(issues).where(eq(issues.executionRunId, runId)); expect(task?.status).toBe("in_progress"); @@ -685,6 +690,129 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d } finally { resetControllerInstanceLeaseForTests(); } }); + async function parkFollowUpBehindOutgoingServer(waitingFor?: (owner: { runId: string; controllerBootId: string }) => { runId: string; controllerBootId: string }) { + const seeded = await seedWarmFollowUpOnOldServer(); + const { fixture, current, identity, recordOwner, runId } = seeded; + const outgoingBoot = fixture.owner.bootId; + await recordOwner({ controllerBootId: outgoingBoot, controllerPid: 7, controllerHostHash: "outgoing-container", + controllerProcessStartedAt: new Date(Date.now() - 600_000), leaseOwner: null, leaseExpiresAt: null }); + await db.insert(controllerInstances).values({ bootId: outgoingBoot, processSpace: "outgoing-container", pid: 7, + leaseExpiresAt: new Date(Date.now() + 90_000) }); + await db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID() }).where(eq(nativeRunFinalizations.runId, runId)); + const wait = (checkpointedAt: Date | null) => waitForLiveWarmSessionOwner({ db, execution: current, + priorRunId: fixture.scope.runId, checkpointedAt: async () => checkpointedAt }); + const waiting = await wait(null).catch(error => error); + expect(waiting).toBeInstanceOf(NativeControllerRecoveryWaitingError); + expect(waiting.owner).toEqual({ runId: fixture.scope.runId, controllerBootId: outgoingBoot }); + const parkedAt = Date.now(); + await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt, + waitingForOwner: waitingFor ? waitingFor(waiting.owner) : waiting.owner }); + const outgoingRoot = join(root, `${fixture.scope.runId}-outgoing`); + (await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }))! + .restoreSessionDirectory(outgoingRoot); + const outgoing = new DurablePrpControlPlane({ stateDirectory: join(outgoingRoot, "control-plane"), identity, + expectedRunnerVersion: "discovery-fixture", expectedRunnerDigest: `sha256:${"a".repeat(64)}` }); + outgoing.setCheckpointPersistence(nativeRunnerCheckpointWriter(db, fixture.owner)); + const fenceHarnessBackup = async () => assertNativeHarnessBackupOwner(db, await nativeHarnessBackupOwner(db, { + companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId, bootId: outgoingBoot })); + const saveSuspend = async () => { + outgoing.queueCommand("runner.suspend", {}, `idle-close-${randomUUID()}`); + await outgoing.flushCheckpoint(); + }; + const closeIdleSession = async () => { + await fenceHarnessBackup(); + await saveSuspend(); + return new Date(); + }; + return { ...seeded, wait, waiting: waiting as NativeControllerRecoveryWaitingError, parkedAt, outgoing, + fenceHarnessBackup, saveSuspend, closeIdleSession }; + } + + it("the outgoing server checkpoints and closes its idle warm session while the incoming server's follow-up waits for it, and the follow-up resumes within one recheck", async () => { + registerControllerInstanceDb(db); + const parked = await parkFollowUpBehindOutgoingServer(); + try { + const { fixture, runId, wait, waiting, parkedAt, outgoing, closeIdleSession } = parked; + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0]) + .toMatchObject({ phase: "retryable_failure", attempt: 0, leaseOwner: null, failureCode: NATIVE_RETAINED_OWNER_WAIT, + failureDetail: expect.objectContaining({ waitingForOwner: waiting.owner }) }); + const [prior] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.scope.runId)); + const ownerExitDeadline = prior!.finishedAt!.getTime() + 600_000 + 120_000; + + const checkpointedAt = await closeIdleSession(); + const saved = await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }); + const restoredRoot = join(root, `${runId}-idle-close`); + saved!.restoreSessionDirectory(restoredRoot); + const restored = JSON.parse(await readFile(join(restoredRoot, "control-plane", "control-plane-state.json"), "utf8")); + expect(restored.commands).toContainEqual(expect.objectContaining({ type: "runner.suspend" })); + await outgoing.stop(); + + expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId] })).toEqual([]); + const claims = await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt }); + expect(claims).toHaveLength(1); + await expect(wait(checkpointedAt)).resolves.toBeUndefined(); + const waitedMs = Math.max(waiting.retryAt.getTime(), checkpointedAt.getTime()) - parkedAt; + expect(waitedMs).toBeLessThanOrEqual(5_000); + expect(ownerExitDeadline - parkedAt).toBeGreaterThan(600_000); + } finally { + await parked.outgoing.stop(); + resetControllerInstanceLeaseForTests(); + } + }); + + it("holds a resumption claim of the parked follow-up until the outgoing server's save commits", async () => { + registerControllerInstanceDb(db); + const parked = await parkFollowUpBehindOutgoingServer(); + try { + const { fixture, runId, waiting } = parked; + let claim!: Promise>>; + let claimSettled = false; + await db.transaction(async tx => { + await assertNativeRunnerCheckpointOwner(tx, fixture.owner, false); + claim = claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt }); + void claim.finally(() => { claimSettled = true; }); + await vi.waitFor(async () => { + const [blocked] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity + where datname = current_database() and wait_event_type = 'Lock' and query ilike '%native_run_finalizations%'`); + expect(blocked.count).toBeGreaterThan(0); + }, { timeout: 1_500, interval: 20 }); + expect(claimSettled).toBe(false); + }); + expect(await claim).toHaveLength(1); + await expect(parked.saveSuspend()).rejects.toThrow("native_runner_checkpoint_owner_lost"); + } finally { + await parked.outgoing.stop(); + resetControllerInstanceLeaseForTests(); + } + }); + + it.each(["own-process", "own-process-event", "own-checkpoint", "claimed", "other-owner-boot", "other-owner-run"] as const)( + "refuses the outgoing server's idle checkpoint when the parked follow-up is no longer waiting on it: %s", async scenario => { + registerControllerInstanceDb(db); + const parked = await parkFollowUpBehindOutgoingServer(owner => scenario === "other-owner-boot" + ? { ...owner, controllerBootId: randomUUID() } : scenario === "other-owner-run" ? { ...owner, runId: randomUUID() } : owner); + try { + const { fixture, runId, waiting, fenceHarnessBackup, saveSuspend } = parked; + if (scenario === "own-process") { + await db.update(heartbeatRuns).set({ processPid: 4242, processGroupId: 4242, processStartedAt: new Date() }).where(eq(heartbeatRuns.id, runId)); + } else if (scenario === "own-process-event") { + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1, eventType: PROCESS_START_REQUESTED }); + } else if (scenario === "own-checkpoint") { + await db.insert(nativeRunnerCheckpoints).values({ companyId, issueId: fixture.scope.issueId, runId, part: "header", material: {} }); + } else if (scenario === "claimed") { + expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt })).toHaveLength(1); + } + const before = await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }); + await expect(fenceHarnessBackup()).rejects.toThrow("native_runner_checkpoint_owner_lost"); + await expect(saveSuspend()).rejects.toThrow("native_runner_checkpoint_owner_lost"); + expect((await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }))?.records) + .toEqual(before?.records); + } finally { + await parked.outgoing.stop(); + resetControllerInstanceLeaseForTests(); + } + }); + 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-controller-recovery.ts b/server/src/services/native-runtime/native-controller-recovery.ts index a5696d40f02..c7523d642f0 100644 --- a/server/src/services/native-runtime/native-controller-recovery.ts +++ b/server/src/services/native-runtime/native-controller-recovery.ts @@ -70,8 +70,10 @@ export type NativeControllerRecoveryOutcome = export const NATIVE_RETAINED_OWNER_WAIT = "native_controller_recovery_waiting_for_owner"; +export type NativeRetainedOwnerWait = { runId: string; controllerBootId: string }; + export class NativeControllerRecoveryWaitingError extends Error { - constructor(readonly retryAt: Date) { + constructor(readonly retryAt: Date, readonly owner?: NativeRetainedOwnerWait) { super(NATIVE_RETAINED_OWNER_WAIT); this.name = "NativeControllerRecoveryWaitingError"; } @@ -83,7 +85,7 @@ export class NativeControllerRecoveryWaitingError extends Error { * permissions and task ownership when this deadline arrives. */ export async function deferNativeControllerRecovery(db: Db, input: { companyId: string; agentId: string; issueId: string; runId: string; - leaseOwner?: string; retryAt: Date; + leaseOwner?: string; retryAt: Date; waitingForOwner?: NativeRetainedOwnerWait; }): Promise { await db.transaction(async tx => { const [task] = await tx.select({ executionRunId: issues.executionRunId }).from(issues) @@ -128,7 +130,9 @@ export async function deferNativeControllerRecovery(db: Db, input: { failureDetail: { originalFailureCode: NATIVE_RETAINED_OWNER_WAIT, message: "Waiting for the retained native controller owner to release its lease.", recoveryMode: record(run.runnerProfileJson).sessionCheckpoint ? "same_session_resume" : "bootstrap_retry", - providerSessionEstablished: false, providerEventsExist: false }, + providerSessionEstablished: false, providerEventsExist: false, + ...(input.waitingForOwner ? { waitingForOwner: { runId: input.waitingForOwner.runId, + controllerBootId: input.waitingForOwner.controllerBootId } } : {}) }, updatedAt: new Date(), }).where(eq(nativeRunFinalizations.runId, input.runId)); }); diff --git a/server/src/services/native-runtime/native-runner-checkpoint.ts b/server/src/services/native-runtime/native-runner-checkpoint.ts index 055168d68e5..3a76c84ac17 100644 --- a/server/src/services/native-runtime/native-runner-checkpoint.ts +++ b/server/src/services/native-runtime/native-runner-checkpoint.ts @@ -3,12 +3,14 @@ import { NATIVE_PREPARATION_FENCING_VERSION } from "./native-active-runs.js"; import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js"; import { createHash } from "node:crypto"; import { and, eq, exists, gt, isNull, lte, inArray, notExists, or, sql, type SQL } from "drizzle-orm"; -import { checkpointDb, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, primeDatabaseWorkTransactionId, type Db } from "@paperclipai/db"; +import { checkpointDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, primeDatabaseWorkTransactionId, type Db } from "@paperclipai/db"; import { inspectDurablePrpCheckpointHeader, inspectUnauthenticatedBootstrapCheckpoint, inspectUnclaimedBootstrapCheckpoint, decodeDurablePrpCheckpoint, type DurablePrpCheckpoint, type DurablePrpControlPlane, type DurableRecoveryIdentity } from "../../vendor/paperclip-runner/index.js"; import { createLocalEncryptedCipher, deriveLocalEncryptedInstanceSecret } from "../../secrets/local-encrypted-provider.js"; import { legacyControllerBootId } from "../legacy-controller-lease.js"; import { assertNativeSourceCheckpointConsumer, lockSourceRecoveryCoordinators } from "./native-source-recovery-ownership.js"; import { runnerdStateHasNoProviderTurn, runnerdStateIsIncompleteBootstrap } from "./native-bootstrap-proof.js"; +import { NATIVE_RETAINED_OWNER_WAIT } from "./native-controller-recovery.js"; +import { OWN_PROCESS_START_EVENT_TYPES } from "../native-process-start-events.js"; type Binding = { companyId: string; issueId: string; runId: string }; export const NATIVE_CHECKPOINT_HEADER_INSPECTION_MAX_BYTES = 1024 * 1024; @@ -116,13 +118,37 @@ export async function validateNativeRunnerCheckpointOwner( eq(heartbeatRuns.issueId, owner.issueId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"]), notExists(tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations) .where(eq(nativeRunFinalizations.runId, heartbeatRuns.id))))) : []; + const [parkedSuccessor] = !successor && !preparingSuccessor && !waitingSuccessor && task?.executionRunId && task.executionRunId !== owner.runId + ? await parkedSuccessorWaitingForOwner(tx, owner, task.executionRunId) : []; if (!current.resultId || newWork || !task - || (task.executionRunId && task.executionRunId !== owner.runId && !successor && !preparingSuccessor && !waitingSuccessor)) { + || (task.executionRunId && task.executionRunId !== owner.runId && !successor && !preparingSuccessor && !waitingSuccessor && !parkedSuccessor)) { throw new Error("native_runner_checkpoint_owner_lost"); } } } +function parkedSuccessorWaitingForOwner(tx: CheckpointTransaction, owner: NativeRunnerCheckpointFenceOwner, successorRunId: string) { + return tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations) + .innerJoin(heartbeatRuns, eq(heartbeatRuns.id, nativeRunFinalizations.runId)).where(and( + eq(nativeRunFinalizations.runId, successorRunId), eq(nativeRunFinalizations.companyId, owner.companyId), + eq(nativeRunFinalizations.issueId, owner.issueId), eq(nativeRunFinalizations.phase, "retryable_failure"), + eq(nativeRunFinalizations.failureCode, NATIVE_RETAINED_OWNER_WAIT), eq(nativeRunFinalizations.attempt, 0), + isNull(nativeRunFinalizations.resultId), isNull(nativeRunFinalizations.leaseOwner), + sql`${nativeRunFinalizations.failureDetail}->'waitingForOwner'->>'runId' = ${owner.runId}`, + sql`${nativeRunFinalizations.failureDetail}->'waitingForOwner'->>'controllerBootId' = ${owner.bootId}`, + eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.nativeIssueId, owner.issueId), + eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "running"), + isNull(heartbeatRuns.processPid), isNull(heartbeatRuns.processGroupId), isNull(heartbeatRuns.processStartedAt), + sql`${heartbeatRuns.nativeSessionId} = (select source.native_session_id from heartbeat_runs source + where source.id = ${owner.runId} and source.company_id = ${owner.companyId})`, + notExists(tx.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints).where(and( + eq(nativeRunnerCheckpoints.companyId, owner.companyId), eq(nativeRunnerCheckpoints.runId, successorRunId)))), + notExists(tx.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, owner.companyId), eq(heartbeatRunEvents.runId, successorRunId), + isNull(heartbeatRunEvents.sourceEventId), inArray(heartbeatRunEvents.eventType, [...OWN_PROCESS_START_EVENT_TYPES])))), + )).for("share", { of: nativeRunFinalizations }); +} + export async function assertNativeRunnerCheckpointOwner(tx: CheckpointTransaction, owner: NativeRunnerCheckpointOwner, newWork: boolean) { const locked = await lockNativeRunnerCheckpointOwner(tx, owner); await validateNativeRunnerCheckpointOwner(tx, owner, locked, newWork); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index c78ad91a900..a225db8c5a7 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -10735,7 +10735,7 @@ export async function executePaperclipNativeSession(input: { executionFailure = error; if (error instanceof NativeControllerRecoveryWaitingError) { await deferNativeControllerRecovery(input.db, { ...input.execution.binding, - leaseOwner: input.leaseOwner, retryAt: error.retryAt }); + leaseOwner: input.leaseOwner, retryAt: error.retryAt, waitingForOwner: error.owner }); } if (!(error instanceof NativeRunnerOwnershipUnverifiedError) && !(error instanceof NativeStartupCleanupPendingError) && startup.stopRequested && startup.executionContext?.signal.reason instanceof Error && startup.executionContext.signal.reason.message === "native_session_cancelled") { 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 113cb8b5be9..3397917819e 100644 --- a/server/src/services/native-runtime/remote-warm-session-recovery.ts +++ b/server/src/services/native-runtime/remote-warm-session-recovery.ts @@ -53,10 +53,10 @@ export async function waitForLiveWarmSessionOwner(input: { const finishedAt = prior?.finishedAt ?? null; const retryAt = await liveWarmSessionOwnerRetryAt({ owner, finishedAt, idleTimeoutMs: input.execution.session.lifecyclePolicy.idleTimeoutMs ?? null }); - if (!retryAt) return; + if (!retryAt || !owner.controllerBootId) return; const checkpointedAt = await input.checkpointedAt(); if (checkpointedAt && finishedAt && checkpointedAt >= finishedAt) return; - throw new NativeControllerRecoveryWaitingError(retryAt); + throw new NativeControllerRecoveryWaitingError(retryAt, { runId: input.priorRunId, controllerBootId: owner.controllerBootId }); } export type RemoteWarmSessionRecovery = { @@ -228,7 +228,9 @@ export async function inspectRemoteWarmSessionRecovery(input: { 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 (liveOwnerRetryAt) { + throw new NativeControllerRecoveryWaitingError(liveOwnerRetryAt, { runId: identity.runId, controllerBootId: prior.owner.controllerBootId }); + } if (sourceProviderLeaseId === providerLeaseId) settledPredecessor = { runId: identity.runId, providerLeaseId }; const checkpoint = input.loadCheckpoint(previous); if (!checkpoint || checkpoint.identity.runId !== identity.runId || From b5447432bd0de18398aab67b5294702f87b3b9e8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:15:17 -0600 Subject: [PATCH 14/20] fix(ui): keep the active company on Cases and Status navigation links (#21794) 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 builds company-prefixed links, such as `/PAP/cases`, from short paths in the sidebar > - The Cases and Status links use `/cases` and `/status`, but these roots were not in the board route list > - The router read `cases` as a company prefix and left the link unprefixed, so the link only worked through the unprefixed redirect > - When a person clicked Cases before the company list loaded, the redirect picked an arbitrary company and showed its empty case list > - The same race made `tests/e2e/cases-read-only.spec.ts` fail in "ci / e2e shard (2/8)" on unrelated PRs (#21683, #21715, #21765) > - This pull request adds both roots to the board route list and makes the e2e test force the race > - The benefit is that Cases and Status always open in the company the person is in, and the flaky e2e test becomes deterministic ## Linked Issues or Issue Description Refs #21683 Refs #21715 Refs #21765 **What happened?** The read-only Cases e2e test failed about once per day with `Expected: 3, Received: 0` links in the case list (job 132875164249 on #21765, job 132680942843 on #21715). The failure screenshot shows the sidebar of a different company ("Passive artifacts …", created by the previous spec) and "No cases yet". The server log shows that the page asked for the cases of the other company and never for the test company. **Expected behavior** A click on the Cases or Status link opens that page for the company in the URL, also when the click happens before the company list has loaded. **Steps to reproduce** 1. Have two or more companies. 2. Open `//issues` on a slow connection (the e2e test holds `GET /api/companies`). 3. Before the company list loads, open More and click Cases. 4. The URL becomes `/cases`. When the list loads, the app redirects to `//cases` and shows another company's empty case list. **Paperclip version or commit** `master` at 46e5e4450f. ## What Changed - `ui/src/lib/company-routes.ts`: add `cases` and `status` to `BOARD_ROUTE_ROOTS`, so `applyCompanyPrefix("/cases", "PAP")` returns `/PAP/cases`. Remove the part of the `caseHref` doc comment that described the old behavior. - `ui/src/lib/company-routes.test.ts`: unit test for both roots (red before the fix, green after). - `tests/e2e/cases-read-only.spec.ts`: hold `GET /api/companies` until the Cases link is clicked, then require the URL `//cases`. Without the fix the URL is `/cases`, so the test fails every time instead of sometimes. ## Verification - `cd ui && npx vitest run src/lib/company-routes.test.ts src/App.cases-routing.test.tsx src/lib/router.company-task-link.test.tsx`: 23 passed. The new test failed on `master` (2 failed). - E2E, before the fix (spec change only): `npx playwright test --config tests/e2e/playwright.config.ts tests/e2e/cases-read-only.spec.ts --repeat-each=5`: 5 of 5 failed with `Received string: "http://127.0.0.1:3199/cases"`. - E2E, after the fix: same command with `--repeat-each=50` on a loaded machine (load average 6 to 12): 50 of 50 passed. - The e2e config starts its own server on port 3199 (`reuseExistingServer: false`) with a fresh `mkdtemp` home and its own embedded PostgreSQL data directory, so these runs did not touch any other instance. ## Risks - Low risk. A company whose issue prefix is exactly `CASES` or `STATUS` now gets the same treatment as a company named after any other board route (for example `TASKS`): a bare `/CASES` path is read as the Cases page. The existing `//issues` exception still applies. - No API, schema, or migration change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, local Playwright 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 --- tests/e2e/cases-read-only.spec.ts | 8 ++++++++ ui/src/lib/company-routes.test.ts | 8 ++++++++ ui/src/lib/company-routes.ts | 7 ++----- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/tests/e2e/cases-read-only.spec.ts b/tests/e2e/cases-read-only.spec.ts index 22183302f14..b40226ea49e 100644 --- a/tests/e2e/cases-read-only.spec.ts +++ b/tests/e2e/cases-read-only.spec.ts @@ -76,9 +76,17 @@ test("browses passive cases and rolled-up task documents without starting work o await page.setViewportSize({ width: 1440, height: 1000 }); // The agentless dashboard offers onboarding. Start on the ordinary task // list so this zero-agent fixture can use Cases navigation without setup. + let releaseCompanies!: () => void; + const companiesHeld = new Promise(resolve => { releaseCompanies = resolve; }); + await page.route(url => url.pathname === "/api/companies", async route => { + await companiesHeld; + await route.continue(); + }); await page.goto(`/${company.issuePrefix}/issues`); await page.getByRole("button", { name: "More workspace pages", exact: true }).click(); await page.getByRole("link", { name: /^Cases\b/ }).first().click(); + await expect(page).toHaveURL(new RegExp(`/${company.issuePrefix}/cases$`)); + releaseCompanies(); const casePage = page.getByTestId("case-pages"); const list = page.getByRole("region", { name: "Case list", exact: true }); const choose = async (filter: string, option: string) => { diff --git a/ui/src/lib/company-routes.test.ts b/ui/src/lib/company-routes.test.ts index 0b2631debe6..713b55ff4d7 100644 --- a/ui/src/lib/company-routes.test.ts +++ b/ui/src/lib/company-routes.test.ts @@ -139,6 +139,14 @@ describe("company routes", () => { expect(toCompanyRelativePath("/PAP/timeline")).toBe("/timeline"); }); + it.each(["cases", "status"])("keeps the active company on /%s navigation links", (root) => { + expect(isBoardPathWithoutPrefix(`/${root}`)).toBe(true); + expect(extractCompanyPrefixFromPath(`/${root}`)).toBeNull(); + expect(applyCompanyPrefix(`/${root}`, "PAP")).toBe(`/PAP/${root}`); + expect(applyCompanyPrefix(`/PAP/${root}`, "REA")).toBe(`/PAP/${root}`); + expect(toCompanyRelativePath(`/PAP/${root}`)).toBe(`/${root}`); + }); + it("treats Skill Studio create mode as an unprefixed board route", () => { expect(isBoardPathWithoutPrefix("/skills/studio/new")).toBe(true); expect(extractCompanyPrefixFromPath("/skills/studio/new")).toBeNull(); diff --git a/ui/src/lib/company-routes.ts b/ui/src/lib/company-routes.ts index 34012edc128..5b0b2c6c818 100644 --- a/ui/src/lib/company-routes.ts +++ b/ui/src/lib/company-routes.ts @@ -31,6 +31,8 @@ const BOARD_ROUTE_ROOTS = new Set([ "search", "settings", "timeline", + "cases", + "status", ]); const GLOBAL_ROUTE_ROOTS = new Set(["auth", "invite", "board-claim", "cli-auth", "mcp-connect", "dot-connect", "assistant-connections", "docs", "instance"]); @@ -93,11 +95,6 @@ export function applyCompanyPrefix(path: string, companyPrefix: string | null | * Build a company-prefixed href for an experimental Cases route, e.g. * `caseHref("PAP", "PAP-C5")` → `/PAP/cases/PAP-C5`. * - * Case paths carry identifiers like `PAP-C5` in the first segment, which the - * generic {@link applyCompanyPrefix} mistakes for a company prefix ("CASES") and - * therefore leaves `/cases/...` unprefixed — every case link then only resolves - * via the PAP-13002 unprefixed→prefixed redirect. This builder emits the - * prefixed href directly so case-to-case navigation matches the rest of the app. * Falls back to the unprefixed path (still valid via the redirect) when no * company is active. */ From c6cdd57f7abac954158347b99957a8e858a50334 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:07:56 -0600 Subject: [PATCH 15/20] perf(native-runtime): reuse a same-content image provider pack across builds (#21784) 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 remote agent run needs the provider pack (Node, OpenCode and the Runner bridge) inside its sandbox before the provider can start > - The server reuses a pack that is installed in the sandbox image only when its full manifest equals the server's own manifest > - The manifest includes `runnerSourceRevision`, which is the commit that built the server, so an image pack fails this check on every later server build, also when every file in the pack is the same > - The run then uploads the whole pack again, which cost about 15 s per task in a recent load test > - This pull request accepts an image pack whose sealed content equals the expected pack and that differs only in build provenance, and caches verified archive hashes in the server process > - The benefit is that a sandbox image stays usable across server releases that do not change the pack, and the server does less hashing on its main thread ## Linked Issues or Issue Description Refs #21781 (merged), which names the failed check on the run spans. **What existing behavior does this improve?** Selection of the remote provider pack for a new sandbox (`provider_pack.select`). **Subsystem affected** Server: native runtime, remote provider pack verification and upload. **Current behavior** `provider_pack.verify_preinstalled` compares the complete manifest of the image pack with the server's manifest. Any difference fails, including `runnerSourceRevision` and `runnerInputsDigest`, which only record where the pack was built. The run then uploads the full pack. The server also hashes the same archive or pack directory again for every task. **Proposed behavior** When the run is not bound to a saved pack and the operator did not select a custom pack, the remote verification accepts an image pack when (1) its own digest seals its payload, and (2) its schema and payload equal the expected pack after the two provenance fields are removed. Every artifact, the `dist` tree, the candidate trees, the package versions, the Node version, the target platform and the OpenCode version are still checked in the sandbox, against the same values. The server checks the reported manifest again and selects it through the pack authority, as the compatibility path already does. An upload still happens for different content, a corrupted or partial pack, or no pack. The server also remembers a verified transport archive (by path, inode, size and times), so it does not hash it again for the next task. **Reason and benefit** In the harness (fake sandbox, 150 ms per command, 300 ms + 10 MiB/s per transfer, 24 MiB pack), the cross-build case goes from 4.1 s and 24 MiB uploaded to 1.1 s and 0 bytes. Other cases do not change. **Breaking changes** None. A saved or reattached session, and an operator-selected custom pack, still require the exact pack identity. ## What Changed - `remote-provider-pack-verification.ts`: new `acceptProvenance` option. The remote script accepts a sealed pack with the same content and prints its manifest. The server checks that manifest (`sameContentManifest`) and returns it. A forged or different report fails with `installed_manifest_invalid`. - `native-session-executor.ts` (`prepareRemoteProviderPackOnTarget`): staged and preinstalled verification use the option when `acceptProvenanceDifferences` is set. The function returns the selected manifest. The run caller sets the option only through `providerPackProvenanceReuseAllowed` (not retained, no explicit custom pack, selectable authority), and selects a different manifest through the pack authority. - `provider-pack-layers.ts`: `verifyArchive` skips the hash for an archive it already verified with the same file identity. - `remote-provider-pack.ts`: `providerPackProvenanceReuseAllowed` gate, with tests for each case. - `provider-pack-selection-harness.test.ts`: new harness. Uploads go through the workspace confinement check of the Daytona sync guard. It runs the real remote verification in local processes, with modelled sandbox latency and transfer speed, for five cases, before and after. ## Verification - `cd server && npx vitest run src/services/native-runtime/provider-pack-selection-harness.test.ts src/services/native-runtime/provider-pack-archive.test.ts src/services/native-runtime/remote-provider-pack-verification.test.ts src/services/native-runtime/remote-provider-pack.test.ts src/services/native-runtime/retained-provider-pack-source.test.ts src/__tests__/kimi-connection-probe.test.ts` passes. - `npx vitest run src/services/native-runtime/native-session-executor.test.ts src/services/native-runtime/native-artifact-preparation.test.ts src/services/native-runtime/remote-provider-pack-authority.test.ts` passes (1541 passed, 7 skipped). - Red/green: with the source changes reverted, the harness case `same_content_other_build` and the archive cache test fail. With the changes, they pass. - Harness output (load average about 9 on a shared machine; modelled time = wall time + modelled sandbox latency): | Case | Before | After | | --- | --- | --- | | Exact image pack | preinstalled, 1.1 s, 0 MiB | preinstalled, 1.0 s, 0 MiB | | Same content, other build | uploaded, 4.1 s, 24 MiB | preinstalled, 1.1 s, 0 MiB | | Different content | uploaded, 4.1 s, 24 MiB | uploaded, 4.0 s, 24 MiB | | Corrupted image pack | uploaded, 4.0 s, 24 MiB | uploaded, 4.1 s, 24 MiB | | No image pack | uploaded, 3.7 s, 24 MiB | uploaded, 3.8 s, 24 MiB | - The pack step runs no database statements. - `npx tsc --noEmit -p server/tsconfig.json` passes. ## Risks - This changes which provider pack the server accepts. It accepts a different manifest digest only when all content fields are equal and every file is hashed in the sandbox, and only for a run that is not bound to a saved pack. The selected manifest goes through the existing pack authority, so launch profiles and receipts bind the installed pack's own identity. - The archive hash cache trusts each archive file's identity (inode, size, times) on the server. The sandbox still checks the uploaded bundle digest and verifies every uploaded file, so a changed local file still fails closed. - This does not help when the image pack has other content (for example a different contract digest). See the hand-off notes for the image build. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] 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 --- .../native-runtime/native-session-executor.ts | 29 ++- .../provider-pack-archive.test.ts | 20 ++ .../native-runtime/provider-pack-layers.ts | 8 + .../provider-pack-selection-harness.test.ts | 188 ++++++++++++++++++ .../remote-provider-pack-verification.test.ts | 18 ++ .../remote-provider-pack-verification.ts | 38 +++- .../remote-provider-pack.test.ts | 13 +- .../native-runtime/remote-provider-pack.ts | 9 + 8 files changed, 307 insertions(+), 16 deletions(-) create mode 100644 server/src/services/native-runtime/provider-pack-selection-harness.test.ts diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index a225db8c5a7..c16a79bc208 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -130,7 +130,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js"; -import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; import { uploadVerifiedProviderPack } from "./provider-pack-upload.js"; import { selectRemotePiCompanion } from "./remote-pi-companion.js"; import { scheduledResumeContinuationAllowed } from "./scheduled-resume-continuation.js"; @@ -14672,6 +14672,7 @@ export async function prepareRemoteProviderPackOnTarget(input: { signal?: AbortSignal; trace?: NativeRunTrace; onLog?: (stream: "stdout" | "stderr", chunk: string) => void | Promise; + acceptProvenanceDifferences?: boolean; }): Promise<{ root: string; manifest: RemoteProviderPackManifest; source: "staged" | "preinstalled" | "uploaded" }> { const remoteTarget = input.target, remoteCommandRunner = input.runner; const configuredProviderPackRoot = input.configuredProviderPackRoot; @@ -14679,10 +14680,10 @@ export async function prepareRemoteProviderPackOnTarget(input: { const stagedRemoteProviderPackRoot = posix.join(remoteTarget.remoteCwd, ".paperclip-runtime", "paperclip-runner", "provider-pack"); let activeRemoteProviderPackRoot: string | null = null; let preinstalledProviderPackRoots: string[] = []; - const verifyRemoteProviderPack = async (packRoot: string) => { - await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, - cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest }); - }; + let selectedProviderPackManifest = expectedProviderPackManifest; + const verifyRemoteProviderPack = (packRoot: string, acceptProvenance = false) => + verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, cwd: remoteTarget.remoteCwd, packRoot, + manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true }); const discoverPreinstalledProviderPack = async () => { if (!remoteTarget || !remoteCommandRunner) return []; const result = await remoteCommandRunner.execute({ @@ -14704,16 +14705,16 @@ export async function prepareRemoteProviderPackOnTarget(input: { verifyStaged: () => measureNativeRunnerSpan( input.trace, "provider_pack.verify", - () => verifyRemoteProviderPack(stagedRemoteProviderPackRoot), + async () => { selectedProviderPackManifest = await verifyRemoteProviderPack(stagedRemoteProviderPackRoot, true); }, ), usePreinstalled: async (onRejected) => useVerifiedPreinstalledRemoteProviderPack({ onRejected, candidates: preinstalledProviderPackRoots = await measureNativeRunnerSpan(input.trace, "provider_pack.discover", discoverPreinstalledProviderPack), verifyAndLink: async (preinstalledProviderPack) => { - await measureNativeRunnerSpan( + const preinstalledManifest = await measureNativeRunnerSpan( input.trace, "provider_pack.verify_preinstalled", - () => verifyRemoteProviderPack(preinstalledProviderPack), + () => verifyRemoteProviderPack(preinstalledProviderPack, true), ); const escapedSource = preinstalledProviderPack.replaceAll( "'", @@ -14740,6 +14741,7 @@ export async function prepareRemoteProviderPackOnTarget(input: { throw providerPackIncompatible("link_failed", "preinstalled provider pack could not be linked"); } activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; + selectedProviderPackManifest = preinstalledManifest; await input.onLog?.( "stderr", "[paperclip-runner] using manifest-matched preinstalled provider pack\n", @@ -14774,9 +14776,10 @@ export async function prepareRemoteProviderPackOnTarget(input: { targetPath: stagedRemoteProviderPackRoot, mode: 0o700, }), - verifyUploaded: () => verifyRemoteProviderPack(stagedRemoteProviderPackRoot), + verifyUploaded: async () => { await verifyRemoteProviderPack(stagedRemoteProviderPackRoot); }, }); activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; + selectedProviderPackManifest = expectedProviderPackManifest; }, }); activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; @@ -14786,7 +14789,7 @@ export async function prepareRemoteProviderPackOnTarget(input: { "[paperclip-runner] reusing manifest-matched provider pack from the workspace\n", ); } - return { root: activeRemoteProviderPackRoot!, manifest: expectedProviderPackManifest, source: packSource }; + return { root: activeRemoteProviderPackRoot!, manifest: selectedProviderPackManifest, source: packSource }; } /** Read selection identity only; verify controller contents only if upload is needed. */ @@ -17214,7 +17217,13 @@ async function createRunnerdBackendWithinSessionClaim( target: remoteTarget, runner: remoteCommandRunner, configuredProviderPackRoot, manifest: expectedProviderPackManifest, trace: input.trace, onLog: input.onLog, signal: sourceSignals.length ? AbortSignal.any(sourceSignals) : undefined, + acceptProvenanceDifferences: providerPackProvenanceReuseAllowed({ retainProviderPack, explicitProviderPackSelection, + authoritySelectable: providerPackAuthority !== null }), }); + if (prepared.manifest.digest !== expectedProviderPackManifest.digest) { + providerPackAuthority!.select(prepared.manifest); + expectedProviderPackManifest = prepared.manifest; + } activeRemoteProviderPackRoot = prepared.root; providerPackVerified = true; } diff --git a/server/src/services/native-runtime/provider-pack-archive.test.ts b/server/src/services/native-runtime/provider-pack-archive.test.ts index ee891ed4925..70462a6d46a 100644 --- a/server/src/services/native-runtime/provider-pack-archive.test.ts +++ b/server/src/services/native-runtime/provider-pack-archive.test.ts @@ -69,6 +69,7 @@ it("keeps historical/source packs without an archive on the existing path", asyn it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk", async version => { const { pack } = version === "v2" ? await layeredFixture() : await fixture(); const archivePath = version === "v2" ? `${pack}.archives/overlay.tar.zst` : `${pack}.tar.zst`; + await fs.utimes(archivePath, new Date(), new Date(Date.now() + 60_000)); const controller = new AbortController(); const handle = await fs.open(archivePath, "r"); const prototype = Object.getPrototypeOf(handle) as typeof handle; @@ -85,6 +86,25 @@ it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk } finally { streaming.mockRestore(); } }); +it("hashes an unchanged verified archive once per server process and again after it changes", async () => { + const { pack } = await fixture(); + const archivePath = `${pack}.tar.zst`; + const handle = await fs.open(archivePath, "r"); + const prototype = Object.getPrototypeOf(handle) as typeof handle; + await handle.close(); + const streaming = vi.spyOn(prototype, "createReadStream"); + try { + await expect(readProviderPackArchive(pack, digest)).resolves.toMatchObject({ sourcePath: archivePath }); + expect(streaming).not.toHaveBeenCalled(); + const original = await fs.readFile(archivePath); + const corrupted = Buffer.from(original); + corrupted[corrupted.length - 1] ^= 0xff; + await fs.writeFile(archivePath, corrupted); + await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("sha256_mismatch"); + expect(streaming).toHaveBeenCalledOnce(); + } finally { streaming.mockRestore(); } +}); + async function layeredFixture() { const { root, pack } = await fixture(); await fs.writeFile(path.join(pack, "bin", "large"), Buffer.alloc(1024 * 1024, 42), { mode: 0o755 }); diff --git a/server/src/services/native-runtime/provider-pack-layers.ts b/server/src/services/native-runtime/provider-pack-layers.ts index c2b8382e15b..090181fdab2 100644 --- a/server/src/services/native-runtime/provider-pack-layers.ts +++ b/server/src/services/native-runtime/provider-pack-layers.ts @@ -28,6 +28,10 @@ const validArchive = (value: unknown): value is Archive => { export const invalidArchive = (reason: string, cause?: unknown) => new Error(`runner_remote_provider_archive_invalid: ${reason}`, cause === undefined ? undefined : { cause }); +const verifiedArchives = new Set(); +const archiveIdentity = (path: string, expected: Archive, metadata: { dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }) => + [path, expected.sha256, metadata.dev, metadata.ino, metadata.size, metadata.mtimeMs, metadata.ctimeMs].join("\0"); + export async function verifyArchive(path: string, expected: Archive, signal?: AbortSignal) { signal?.throwIfAborted(); let file; @@ -37,10 +41,14 @@ export async function verifyArchive(path: string, expected: Archive, signal?: Ab const metadata = await file.stat(); if (!metadata.isFile()) throw invalidArchive("archive_not_file"); if (metadata.size !== expected.bytes) throw invalidArchive("size_mismatch"); + const identity = archiveIdentity(path, expected, metadata); + if (verifiedArchives.has(identity)) return; const hash = createHash("sha256"); for await (const chunk of file.createReadStream({ autoClose: false, signal })) hash.update(chunk); signal?.throwIfAborted(); if (hash.digest("hex") !== expected.sha256) throw invalidArchive("sha256_mismatch"); + if (verifiedArchives.size >= 1_024) verifiedArchives.clear(); + verifiedArchives.add(identity); } finally { await file.close(); } } diff --git a/server/src/services/native-runtime/provider-pack-selection-harness.test.ts b/server/src/services/native-runtime/provider-pack-selection-harness.test.ts new file mode 100644 index 00000000000..8ff7be13870 --- /dev/null +++ b/server/src/services/native-runtime/provider-pack-selection-harness.test.ts @@ -0,0 +1,188 @@ +import { execFile } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import { chmod, cp, mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join, posix } from "node:path"; +import { promisify } from "node:util"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; +import { QUALIFIED_ACPX_PROFILES, QUALIFIED_ACPX_VERSION } from "../../vendor/paperclip-runner/index.js"; +import { prepareRemoteProviderPackOnTarget, resolveRemoteProviderPackSource, sha256DirectoryTree } from "./native-session-executor.js"; +import { canonicalProviderPackJson } from "./remote-provider-pack-verification.js"; + +const exec = promisify(execFile); +const EXECUTE_LATENCY_MS = 150; +const TRANSFER_LATENCY_MS = 300; +const TRANSFER_BYTES_PER_SECOND = 10 * 1024 * 1024; +const LARGE_ARTIFACT_BYTES = 24 * 1024 * 1024; +const sha = (value: string | Buffer) => `sha256:${createHash("sha256").update(value).digest("hex")}`; + +async function writePack(root: string, revision: string, large: Buffer, distSuffix = "") { + const files: Record = { + "node_modules/node/bin/node": `#!/bin/sh\nexec '${process.execPath}' "$@"\n`, + "node_modules/.bin/opencode": "#!/bin/sh\necho 1.18.34\n", + "node_modules/opencode-ai/bin/opencode.exe": large, + "node_modules/opencode-ai/package.json": JSON.stringify({ version: "1.18.34" }), + "node_modules/acpx/package.json": JSON.stringify({ version: QUALIFIED_ACPX_VERSION }), + "node_modules/@agentclientprotocol/claude-agent-acp/package.json": JSON.stringify({ version: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion }), + "node_modules/@agentclientprotocol/codex-acp/package.json": JSON.stringify({ version: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion }), + "pnpm-lock.yaml": "lockfileVersion: '9.0'\n", + "dist/cli/opencode-app-server-proxy.cjs": `module.exports = "proxy${distSuffix}";\n`, + "dist/cli/acpx-runtime-sidecar.cjs": "module.exports = 'sidecar';\n", + "dist/providers/grok/launcher.cjs": "module.exports = 'grok';\n", + }; + for (const [path, content] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content); + } + await chmod(join(root, "node_modules/node/bin/node"), 0o755); + await chmod(join(root, "node_modules/.bin/opencode"), 0o755); + const artifact = (path: string) => ({ path, sha256: sha(files[path]!) }); + const proxy = artifact("dist/cli/opencode-app-server-proxy.cjs"), sidecar = artifact("dist/cli/acpx-runtime-sidecar.cjs"); + const distDigest = sha256DirectoryTree(join(root, "dist")); + const payload = { + pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, opencode: "1.18.34", acpx: QUALIFIED_ACPX_VERSION, + claudeAcp: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion, codexAcp: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion, + grok: QUALIFIED_ACPX_PROFILES.grok.agentRuntimeVersion }, + target: { platform: process.platform, architecture: process.arch }, + runnerSourceRevision: revision.repeat(40), + distDigest, + bridgeDigest: `sha256:${createHash("sha256").update(proxy.sha256).update("\n").update(sidecar.sha256).update("\n").update(distDigest).digest("hex")}`, + acpxProfileDigests: { grok: QUALIFIED_ACPX_PROFILES.grok.commandDigest, claude: QUALIFIED_ACPX_PROFILES.claude.commandDigest, + codex: QUALIFIED_ACPX_PROFILES.codex.commandDigest }, + artifacts: { + grokLauncher: artifact("dist/providers/grok/launcher.cjs"), nodeCommand: artifact("node_modules/node/bin/node"), + productionLock: artifact("pnpm-lock.yaml"), opencodeCommand: artifact("node_modules/.bin/opencode"), + opencodeExecutable: artifact("node_modules/opencode-ai/bin/opencode.exe"), opencodeProxy: proxy, acpxSidecar: sidecar, + }, + }; + await writeFile(join(root, "provider-pack.json"), JSON.stringify({ schema: "paperclip-runner/remote-provider-pack/v1", + digest: sha(canonicalProviderPackJson(payload)), payload })); +} + +async function directoryBytes(root: string): Promise { + let total = 0; + for (const entry of await readdir(root, { withFileTypes: true, recursive: true })) { + if (entry.isFile()) total += (await stat(join(entry.parentPath, entry.name))).size; + } + return total; +} + +function assertConfinedSandboxPath(remoteDir: string, candidate: string) { + const root = posix.normalize(remoteDir); + const normalized = posix.normalize(candidate); + if (normalized !== root && !normalized.startsWith(`${root}/`)) { + throw new Error(`sync target path escapes the workspace remote dir: ${candidate}`); + } +} + +function simulatedSandbox(home: string, workspace: string) { + const usage = { simulatedMs: 0, executes: 0, bytesUploaded: 0 }; + const runner: CommandManagedRuntimeRunner = { + execute: async request => { + usage.executes += 1; + usage.simulatedMs += EXECUTE_LATENCY_MS; + try { + const result = await exec(request.command, request.args ?? [], { cwd: request.cwd, env: { ...process.env, HOME: home }, maxBuffer: 1 << 24 }); + return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stdout: result.stdout, stderr: result.stderr }; + } catch (error) { + const failed = error as Error & { code?: number; stdout?: string; stderr?: string }; + return { exitCode: typeof failed.code === "number" ? failed.code : 127, signal: null, pid: null, startedAt: null, timedOut: false, + stdout: failed.stdout ?? "", stderr: failed.stderr ?? String(error) }; + } + }, + syncIn: async operations => { + const results = []; + for (const operation of operations) { + let bytes = 0; + for (const file of operation.files) { + if (file.kind !== "directory" || !file.sourcePath) throw new Error("unexpected transfer"); + assertConfinedSandboxPath(workspace, file.targetPath); + bytes += await directoryBytes(file.sourcePath); + await mkdir(dirname(file.targetPath), { recursive: true }); + await cp(file.sourcePath, file.targetPath, { recursive: true }); + } + usage.bytesUploaded += bytes; + usage.simulatedMs += TRANSFER_LATENCY_MS + (bytes / TRANSFER_BYTES_PER_SECOND) * 1000; + results.push({ operationId: operation.operationId, filesTransferred: operation.files.length, bytesTransferred: bytes }); + } + return { operations: results }; + }, + }; + return { runner, usage }; +} + +type Scenario = "exact" | "same_content_other_build" | "different_content" | "corrupted" | "none"; + +describe("provider pack selection harness", () => { + let root: string; + let large: Buffer; + let server: ReturnType; + const rows: string[] = []; + beforeAll(async () => { + root = await mkdtemp(join(tmpdir(), "provider-pack-harness-")); + large = randomBytes(LARGE_ARTIFACT_BYTES); + await writePack(join(root, "server-pack"), "b", large); + server = resolveRemoteProviderPackSource(join(root, "server-pack")); + }); + afterAll(async () => { + if (rows.length) process.stdout.write(`\nprovider pack harness (execute ${EXECUTE_LATENCY_MS} ms, transfer ${TRANSFER_LATENCY_MS} ms + ${TRANSFER_BYTES_PER_SECOND / 1024 / 1024} MiB/s)\n${rows.join("\n")}\n`); + await rm(root, { recursive: true, force: true }); + }); + + const run = async (scenario: Scenario, acceptProvenanceDifferences: boolean) => { + const sandbox = await mkdtemp(join(root, `${scenario}-`)); + const home = join(sandbox, "home"), workspace = join(sandbox, "workspace"); + await mkdir(workspace, { recursive: true }); + const image = join(home, ".local/share/paperclip-runner/provider-pack"); + if (scenario === "exact") await writePack(image, "b", large); + if (scenario === "same_content_other_build") await writePack(image, "a", large); + if (scenario === "different_content") await writePack(image, "a", large, "-older"); + if (scenario === "corrupted") { + await writePack(image, "a", large); + await writeFile(join(image, "dist/cli/acpx-runtime-sidecar.cjs"), "tampered\n"); + } + const { runner, usage } = simulatedSandbox(home, workspace); + const cpuBefore = process.cpuUsage(); + const startedAt = performance.now(); + const prepared = await prepareRemoteProviderPackOnTarget({ + target: { kind: "remote", transport: "sandbox", remoteCwd: workspace, runner } as never, + runner, configuredProviderPackRoot: server.configuredRoot, manifest: server.manifest, acceptProvenanceDifferences, + }); + const wallMs = performance.now() - startedAt; + const cpu = process.cpuUsage(cpuBefore); + rows.push(`${scenario.padEnd(26)} ${acceptProvenanceDifferences ? "after " : "before"} source=${prepared.source.padEnd(12)} ` + + `modelled=${((wallMs + usage.simulatedMs) / 1000).toFixed(2)}s uploaded=${(usage.bytesUploaded / 1024 / 1024).toFixed(1)}MiB ` + + `executes=${usage.executes} serverCpu=${((cpu.user + cpu.system) / 1000).toFixed(0)}ms dbStatements=0`); + return { prepared, usage }; + }; + + it("confines simulated uploads to the workspace", async () => { + const { runner } = simulatedSandbox(root, join(root, "workspace")); + await expect(runner.syncIn!([{ operationId: "escape", files: [{ kind: "directory", sourcePath: join(root, "server-pack"), + targetPath: join(root, "workspace", "..", "outside"), mode: 0o700 }] }])).rejects.toThrow("escapes the workspace"); + }); + + it.each<[Scenario, "preinstalled" | "uploaded", "preinstalled" | "uploaded"]>([ + ["exact", "preinstalled", "preinstalled"], + ["same_content_other_build", "uploaded", "preinstalled"], + ["different_content", "uploaded", "uploaded"], + ["corrupted", "uploaded", "uploaded"], + ["none", "uploaded", "uploaded"], + ])("selects the pack for %s (before: %s, after: %s)", async (scenario, before, after) => { + const previous = await run(scenario, false); + expect(previous.prepared.source).toBe(before); + expect(previous.prepared.manifest).toEqual(server.manifest); + const current = await run(scenario, true); + expect(current.prepared.source).toBe(after); + expect(current.usage.bytesUploaded).toBe(after === "uploaded" ? previous.usage.bytesUploaded : 0); + if (scenario === "same_content_other_build") { + expect(current.prepared.manifest.digest).not.toBe(server.manifest.digest); + expect(current.prepared.manifest.payload.runnerSourceRevision).toBe("a".repeat(40)); + expect({ ...current.prepared.manifest.payload, runnerSourceRevision: null }) + .toEqual({ ...server.manifest.payload, runnerSourceRevision: null }); + } else { + expect(current.prepared.manifest).toEqual(server.manifest); + } + }, 120_000); +}); diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts index 308d142b9cc..0f47eece296 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts @@ -120,6 +120,24 @@ describe("installed provider pack compatibility", () => { if (field === "digest") pack.digest = sha("corrupt"); await expect(check(pack)).rejects.toThrow("runner_remote_provider_artifact_incompatible"); }); + it("accepts a reported installed manifest only when its sealed content equals the expected pack", async () => { + const expected = manifest("b"); + const report = (installed: unknown) => vi.fn(async (request: Parameters[0]) => ({ + exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "", + stdout: request.args?.[0] === "--version" ? "1.18.34\n" + : `\npaperclip-pack-manifest=${Buffer.from(JSON.stringify(installed)).toString("base64")}\n` })); + const input = { cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack", manifest: expected, acceptProvenance: true }; + const otherBuild = manifest("b"); + otherBuild.payload.runnerSourceRevision = "a".repeat(40); + await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(reseal(otherBuild)) } })).resolves.toEqual(reseal(otherBuild)); + const otherContent = reseal({ ...otherBuild, payload: { ...otherBuild.payload, contractDigest: sha("other") } }); + await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(otherContent) } })) + .rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" }); + await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report({ ...reseal(otherBuild), digest: sha("unsealed") }) } })) + .rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" }); + await expect(verifyRemoteProviderPack({ ...input, acceptProvenance: false, runner: { execute: report(reseal(otherBuild)) } })) + .resolves.toEqual(expected); + }); it("does not reuse image packs when the controller's bundled pack records no contract digest", async () => { const current = manifest("b"); delete current.payload.contractDigest; diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts index 5e7c424f20b..dff334bc7dd 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -105,7 +105,7 @@ function compatibleInstallation( return structuredClone(actual); } -export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false }: { +export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false }: { runner: CommandManagedRuntimeRunner; cwd: string; packRoot: string; @@ -114,6 +114,7 @@ export async function verifyRemoteProviderPack({ provider?: PackProvider; requireExactIdentity?: boolean; requireCurrentOpenCodeProxy?: boolean; + acceptProvenance?: boolean; }): Promise { if (installation) { if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required"); @@ -138,7 +139,10 @@ export async function verifyRemoteProviderPack({ "const canonical=(v)=>Array.isArray(v)?'['+v.map(canonical).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}':JSON.stringify(v)", "let manifest;try{manifest=JSON.parse(actual)}catch{fail('manifest_invalid','provider pack manifest invalid')}", "const differing=(a,b)=>[...new Set([...Object.keys(a||{}),...Object.keys(b||{})])].sort().filter(k=>canonical((a||{})[k])!==canonical((b||{})[k]))", - "if(canonical(manifest)!==expected){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}", + "const provenance=process.argv[3]==='provenance'", + "const content=(m)=>{const c=JSON.parse(JSON.stringify(m??null))??{};delete c.digest;if(c.payload&&typeof c.payload==='object'){delete c.payload.runnerSourceRevision;delete c.payload.runnerInputsDigest}return canonical(c)}", + "const sealed=manifest?.digest==='sha256:'+crypto.createHash('sha256').update(canonical(manifest?.payload)).digest('hex')", + "if(canonical(manifest)!==expected&&!(provenance&&sealed&&content(manifest)===content(JSON.parse(expected)))){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}", "const hash=(p)=>{try{return 'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')}catch{return 'unreadable'}}", "const walk=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}", "const tree=(treeRoot)=>{try{return walk(treeRoot)}catch{return 'unreadable'}}", @@ -152,14 +156,16 @@ export async function verifyRemoteProviderPack({ "const packageVersion=(pkg)=>{try{return JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version}catch{return null}}", "const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}", "for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version:'+pkg,pkg+' version mismatch')", + "if(provenance)process.stdout.write('\\npaperclip-pack-manifest='+Buffer.from(canonical(manifest)).toString('base64')+'\\n')", ].join(";"); - await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({ + const verified = await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({ command: providerNodeCommand, - args: ["-e", verifyScript, packRoot, expected], + args: ["-e", verifyScript, packRoot, expected, ...(acceptProvenance ? ["provenance"] : [])], cwd: cwd, bypassSession: true, timeoutMs: 30_000, }), "provider pack verification")); + const selected = acceptProvenance ? sameContentManifest(manifest, verified.stdout) : manifest; const opencodeCommand = posix.join( packRoot, manifest.payload.artifacts.opencodeCommand.path, @@ -176,5 +182,27 @@ export async function verifyRemoteProviderPack({ ) { throw providerPackIncompatible("opencode_version", "OpenCode version mismatch"); } - return structuredClone(manifest); + return structuredClone(selected); +} + +const PROVENANCE_FIELDS = ["runnerSourceRevision", "runnerInputsDigest"] as const; + +export function providerPackContent(manifest: ProviderPackIdentity): string { + const payload: Record = { ...manifest.payload }; + for (const field of PROVENANCE_FIELDS) delete payload[field]; + return canonicalProviderPackJson({ schema: manifest.schema, payload }); +} + +function sameContentManifest(expected: T, stdout: string): T { + const encoded = /paperclip-pack-manifest=([A-Za-z0-9+/=]{1,200000})/.exec(stdout)?.[1]; + let installed: T | null = null; + try { installed = encoded ? JSON.parse(Buffer.from(encoded, "base64").toString("utf8")) as T : null; } catch {} + if (!installed?.payload || installed.schema !== expected.schema + || installed.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(installed.payload)).digest("hex")}` + || providerPackContent(installed) !== providerPackContent(expected) + || !/^[0-9a-f]{40}(?:-dirty)?$/.test(installed.payload.runnerSourceRevision) + || (installed.payload.runnerInputsDigest !== undefined && !/^[0-9a-f]{64}$/.test(installed.payload.runnerInputsDigest))) { + throw providerPackIncompatible("installed_manifest_invalid", "installed provider pack identity is invalid"); + } + return installed; } diff --git a/server/src/services/native-runtime/remote-provider-pack.test.ts b/server/src/services/native-runtime/remote-provider-pack.test.ts index 0ae23290c7f..8d4928683d8 100644 --- a/server/src/services/native-runtime/remote-provider-pack.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { createNativeRunTrace } from "./native-run-trace.js"; -import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; describe("remote provider verification", () => { const ok = { exitCode: 0, timedOut: false, stdout: "verified", stderr: "", signal: null }; @@ -124,6 +124,17 @@ describe("remote provider pack reuse", () => { }); +describe("same-content pack reuse across builds", () => { + it.each([ + [{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: true }, true], + [{ retainProviderPack: true, explicitProviderPackSelection: false, authoritySelectable: true }, false], + [{ retainProviderPack: false, explicitProviderPackSelection: true, authoritySelectable: true }, false], + [{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: false }, false], + ])("allows provenance-only differences only for an unbound run: %j", (input, allowed) => { + expect(providerPackProvenanceReuseAllowed(input)).toBe(allowed); + }); +}); + describe("ordinary ACPX image artifacts", () => { const provider = (agent: string) => ({ kind: "acpx", agent, model: "selected-model" } as Parameters[0]["provider"]); it.each(["cursor", "copilot"])("selects bundled artifacts for remote %s without an operator override", agent => { diff --git a/server/src/services/native-runtime/remote-provider-pack.ts b/server/src/services/native-runtime/remote-provider-pack.ts index b803d6d6d2c..0003cd13661 100644 --- a/server/src/services/native-runtime/remote-provider-pack.ts +++ b/server/src/services/native-runtime/remote-provider-pack.ts @@ -13,6 +13,15 @@ export function shouldUseBundledAcpxImageAssets(input: { ["cursor", "copilot", "kimi"].includes(input.provider.agent); } +/** A run may adopt a same-content pack from another build only when no saved or operator-selected identity binds it. */ +export function providerPackProvenanceReuseAllowed(input: { + retainProviderPack: boolean; + explicitProviderPackSelection: boolean; + authoritySelectable: boolean; +}): boolean { + return !input.retainProviderPack && !input.explicitProviderPackSelection && input.authoritySelectable; +} + type VerificationCommandResult = { exitCode: number | null; timedOut: boolean; From c2e7df2dcc34fd989c4d20faed8f315f22bd056b Mon Sep 17 00:00:00 2001 From: marshall Date: Sun, 15 Nov 2026 10:10:25 -0800 Subject: [PATCH 16/20] fix(workspaces): use project storage for a fresh retry after unowned task storage (#20756) 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 project can use a storage provider plugin. That plugin prepares each task's git worktree > - A board Retry after a failed run can start a fresh attempt. The fresh attempt starts from the project source > - `preparePluginWorkspace` returns `null` when the task is still bound to a workspace that no storage provider owns. It does this also for a fresh attempt > - On a plugin task environment, the host then reserves an empty adapter-managed "Fresh task workspace" with no repository. The runner fails in it. The next Retry finds that empty workspace bound to the task, returns `null` again and reserves another empty workspace. The task can never start again > - This pull request lets a fresh attempt use the project storage provider even when the previous workspace is not provider-owned > - The benefit is that one Retry gives the task a normal provider worktree again ## Linked Issues or Issue Description **What happened?** Tasks moved off an older execution environment kept a binding to a workspace that no storage provider owned. A board Retry selected `fresh_isolated_workspace`. `preparePluginWorkspace` returned `null` because the bound workspace was not plugin-owned. The host fell back to `reserveFreshPluginTaskWorkspace`, which made an empty `adapter_managed` workspace (strategy `project_primary`, no repository, no recovery snapshots). The run failed in about one second with "Plugin-provided Runner execution operation unavailable; reconcile the same task before retrying". Each later Retry made another empty workspace, chained to the last one. **Steps to reproduce** 1. Use a project with a storage provider plugin that supports fresh workspaces. 2. Bind a task to a workspace that the provider does not own (for example an adapter-managed workspace). 3. Call `preparePluginWorkspace` for a fresh attempt with that workspace as the previous workspace. **Expected behavior** The storage provider prepares a new worktree for the fresh attempt. **Actual behavior** `preparePluginWorkspace` returns `null` and never calls the provider. ## What Changed - `server/src/services/plugin-workspaces.ts`: the early `return null` for a previous workspace that no provider owns no longer applies to a fresh attempt. The fresh attempt then uses the project's storage provider, as for a task with no bound workspace. - `server/src/__tests__/plugin-fresh-workspaces.integration.test.ts`: new test "prepares provider storage for a fresh retry that follows a workspace the provider does not own". ## Verification - The first commit adds only the test. CI on that commit (`d09ad235`, [failed job](https://github.com/paperclipai/paperclip/actions/runs/42976154239/job/130393285731)) shows only this test fail on the current code (`preparePluginWorkspace` returns `null`). - The second commit adds the fix. CI shows the test pass. - The other tests in the file keep the fresh-attempt guarantees: an older provider still fails closed, a changed binding revision still stops the call, and a lost reply still reconciles to the same operation. - I did not run the suite locally. The test needs embedded Postgres, and this environment does not install packages. CI runs it. ## Risks - Low to medium risk. A fresh attempt in a project with a storage provider now uses that provider even when the previous workspace was local or adapter-managed. Before, such an attempt used the fallback path. This matches the project's storage policy, and a fresh attempt does not reuse the previous workspace's files. - Projects without a storage provider are not affected: the function still returns `null` for them. - Non-fresh preparation is not affected. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use (shell, file edits). Standard reasoning mode. ## 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 - [ ] 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: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- ...plugin-fresh-workspaces.integration.test.ts | 18 ++++++++++++++++++ server/src/services/plugin-workspaces.ts | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts b/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts index 28854abedfe..5490aaee97a 100644 --- a/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts +++ b/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts @@ -98,6 +98,24 @@ describe.skipIf(!support.supported)("provider-owned fresh retry reservations", ( expect(settled.metadata?.workspaceProviderRemoved).toBe(true); expect(cache.release).toHaveBeenCalledTimes(2); }); + it("prepares provider storage for a fresh retry that follows a workspace the provider does not own", async () => { + const f = await createPluginWorkspaceFixture(db); await enable(f.pluginId); + const [previous] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: f.input.projectId, + projectWorkspaceId: f.input.projectWorkspaceId, sourceIssueId: f.issueId, mode: "isolated_workspace", + strategyType: "project_primary", name: "Fresh task workspace", status: "active", providerType: "adapter_managed" }).returning(); + await db.update(issues).set({ executionWorkspaceId: previous.id, workspaceBindingRevision: 1 }).where(eq(issues.id, f.issueId)); + await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.runId)); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.input.agentId, + issueId: f.issueId, status: "running" }).returning(); + const fresh = { attemptId: randomUUID(), sourceRunId: f.runId, previousWorkspaceId: previous.id, recoverySnapshots: [] }; + const workspace = await preparePluginWorkspace(db, f.workers, { ...f.input, runId: run.id, + existingWorkspaceId: previous.id, fresh, expectedBindingRevision: 1 }); + expect(workspace).not.toBeNull(); + expect(workspace!.id).not.toBe(previous.id); + expect(workspace!.providerType).toBe("plugin"); + expect(f.calls).toHaveLength(1); + expect(f.calls[0].operation).toMatchObject({ kind: "prepare", fresh, branchName: null }); + }); it("rejects a changed task revision before calling the provider", async () => { const f = await fixture(); await enable(f.pluginId); await db.update(issues).set({ workspaceBindingRevision: 2 }).where(eq(issues.id, f.issueId)); diff --git a/server/src/services/plugin-workspaces.ts b/server/src/services/plugin-workspaces.ts index feeac4c55a3..d91fac253bd 100644 --- a/server/src/services/plugin-workspaces.ts +++ b/server/src/services/plugin-workspaces.ts @@ -133,7 +133,8 @@ export async function preparePluginWorkspace( ), ) : []; - if (prior && prior.providerType !== "plugin" && !priorBinding && !prior.metadata?.workspaceProviderOwner) return null; + // A fresh attempt starts from the project source, so storage the provider does not own does not decide it. + if (!input.fresh && prior && prior.providerType !== "plugin" && !priorBinding && !prior.metadata?.workspaceProviderOwner) return null; const owner = priorBinding?.pluginId ?? prior?.metadata?.workspaceProviderOwner ?? (!existing && input.selectedProviderPluginId !== undefined ? input.selectedProviderPluginId : !existing && project ? (await effectiveProjectWorkspacePolicy(db, input.companyId, project.executionWorkspacePolicy, false))?.storageProviderPluginId : null); From b4f71fc2766160ac2a1cb8bb621f0e5931e06d49 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:13:18 -0600 Subject: [PATCH 17/20] perf(recovery): stop re-checking settled workspace flags and snapshot ledger rows every pass (#21795) 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 server runs all background recovery on one Node main thread, and each database statement costs time on it > - The ownership reconciliation pass settles in-progress records every 30 s while it has records to watch > - Two of its kinds listed records that can never change again: dirty remote workspaces whose writer reached runtime, and snapshot ledger rows that are uploaded or still held by a stale writer's epoch > - Each such record cost a transaction, a row lock and up to four reads on every pass, forever, and kept the 30 s watch armed on an idle instance > - This pull request lists only the records that the settle step can still act on, locks the writer run only when the settle will write, and skips one stranded-task read that can never match a native run > - The benefit is that recovery work follows activity, not history ## Linked Issues or Issue Description **Describe the problem** On a hosted instance with 7 native runs, the ownership pass ran about 7.6 + 3.2 + 3.5 + 2.8 statements per second over records that cannot change, and took a row lock on `heartbeat_runs` for each stale dirty workspace on every pass. At 1,000 agents this becomes thousands of statements per second. **Steps to reproduce** Seed about 100 dirty remote workspaces whose writer run reached runtime and ended, 50 pending ledger rows still held by those writers, and 100 uploaded ledger rows. Run the ownership reconciliation worker. The new census test `server/src/__tests__/recovery-settled-records-census.test.ts` does this on the embedded database. **Expected behavior** A settled record costs zero statements on later passes. An idle instance runs no SQL from this pass. **Actual behavior** On master, one pass costs 714 statements and 150 row locks. An idle half hour costs 40,800 statements and 9,000 row locks (the settle watch re-checks every 30 s). Refs #21765 (the stranded-assignment hint scoping that this rebases on) ## What Changed - `remote_workspace_unsaved_files` lists a dirty workspace only when its writer run can still be a preparation-only writer: stage `preparing`, no `runtime_mode_resolved_at`, no process, session or runner id, no finalization row and no work-started event (or no writer at all). The SQL lives with the settle step in `remote-workspace-unsaved-files-settlement.ts`. - The unsaved-files settle reads the writer run without a lock. It takes `for update` only after every check passes, just before it writes, and checks the locked row again. - `remote_snapshot_ledger` lists only `pending` rows with no object key, whose operation is a workspace save, and whose workspace epoch has moved past the row's writer. Uploaded rows belong to snapshot retention, as before. - `terminalRunSettlingUntil` in `recovery/service.ts` skips its `heartbeat_runs` read when the latest run already in memory is not a legacy run of another server boot. `getLatestIssueRun` now also selects `runtime_mode` and `controller_boot_id`. The live-execution check still runs first. - New census test with a staging-shaped fixture, a statement counter grouped by statement shape and caller, and prompt-pickup checks. New red/green test for the stranded-task lease read. Census (embedded PostgreSQL, same fixture, base 531db3c10b vs this branch): | Window | Master statements | Master row locks | Branch statements | Branch row locks | | --- | --- | --- | --- | --- | | One full ownership pass | 714 | 150 | 62 | 0 | | One settle-watch re-check | 681 | 150 | 29 | 0 | | Idle 30 min (real worker) | 40,800 | 9,000 | 0 | 0 | | Active, 7 live runs hinting every 10 s | 47,257 per 30 min | 9,000 | 2,763 per 10 min (about 8,300 per 30 min, of which about 4,200 are the test's own hint writers) | 0 | Confirmed callers on master (per full pass): `select execution_workspace_snapshots` full row at `remote-snapshot-ledger-settlement.ts:20` (150), `select heartbeat_runs ... for update` at `remote-workspace-unsaved-files-settlement.ts:20` (100), `select workspace_operations ... for update` at `remote-snapshot-ledger-settlement.ts:25` (50), `select execution_workspaces.metadata` at `remote-snapshot-ledger-settlement.ts:36` (50). The `execution_replacement` queue costs 2 statements per wake over the same history (discovery and the deadline read), so it is not the source of the snapshot or lease reads in this shape. ## Verification - `cd server && npx vitest run src/__tests__/recovery-settled-records-census.test.ts src/__tests__/issue-recovery-terminal-run-settling.test.ts` (fails on master: 714/40,800 statements and the native lease read; passes here) - `cd server && npx vitest run src/__tests__/remote-snapshot-ledger-settlement.test.ts src/__tests__/ownership-reconciliation-report.test.ts` (51 passed, unchanged) - `cd server && npx vitest run src/__tests__/recovery-deadline-acceptance.test.ts src/__tests__/legacy-continuation-authority.test.ts src/__tests__/heartbeat-process-recovery.test.ts` (502 passed) - The census test also checks that a preparation-only workspace is still settled in the first pass, an abandoned pending ledger row is still retired, a ledger row held by a stale writer is retired in the next pass once the workspace epoch moves, and an `active` run lease whose run ended is still listed and released. ## Risks - The report shows fewer in-progress records for these two kinds. Records that the settle step can never change (a dirty flag whose writer reached runtime, an uploaded ledger row) are no longer listed, so they no longer appear as `I2_settled` violations in the activity log. On master each process wrote one such violation per record. - A pending ledger row held by its stale writer's epoch is no longer re-checked every 30 s. It is found by the next full pass after the workspace epoch moves. A new writer or an epoch abandonment both come with run signals that wake the pass, but on an instance with no other activity this can now wait until the next wake instead of at most 30 s. - A dirty workspace whose writer run row is missing is no longer listed. On master it was re-checked forever and the settle refused it every time. - No schema, API or UI change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [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 --- ...sue-recovery-terminal-run-settling.test.ts | 38 +++ .../recovery-settled-records-census.test.ts | 304 ++++++++++++++++++ .../services/recovery/ownership-registry.ts | 9 +- .../remote-snapshot-ledger-settlement.ts | 12 +- ...mote-workspace-unsaved-files-settlement.ts | 29 +- server/src/services/recovery/service.ts | 13 +- 6 files changed, 394 insertions(+), 11 deletions(-) create mode 100644 server/src/__tests__/issue-recovery-terminal-run-settling.test.ts create mode 100644 server/src/__tests__/recovery-settled-records-census.test.ts diff --git a/server/src/__tests__/issue-recovery-terminal-run-settling.test.ts b/server/src/__tests__/issue-recovery-terminal-run-settling.test.ts new file mode 100644 index 00000000000..d889689a3a8 --- /dev/null +++ b/server/src/__tests__/issue-recovery-terminal-run-settling.test.ts @@ -0,0 +1,38 @@ +import { randomUUID } from "node:crypto"; +import { expect, it } from "vitest"; +import { heartbeatRuns, issues } from "@paperclipai/db"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; + +describeIssueRecovery("stranded-task check of a terminal latest run", () => { + const state = issueRecoveryFixture({ meter: true }); + + async function seed(run: Partial) { + const f = await state.fixture(); + const issueId = randomUUID(), runId = randomUUID(); + await state.db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Checked task", status: "in_progress", + assigneeAgentId: f.agentId }); + await state.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "failed", + invocationSource: "manual", contextSnapshot: { issueId }, finishedAt: new Date(Date.now() - 60_000), errorCode: "process_lost", + ...run }); + return { ...f, issueId, runId }; + } + + async function leaseReads(f: { companyId: string; issueId: string }) { + state.meter.startLog(); + await state.heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.issueId, + skipExternalConversationSettlement: true, skipRelatedRecovery: true }); + return state.meter.stopLog().filter(entry => /^select "controller_lease_expires_at" from "heartbeat_runs"/.test(entry.sql.trim())); + } + + it("does not read the controller lease of a native latest run, which can never still be settling", async () => { + const f = await seed({ runtimeMode: "native", controllerBootId: randomUUID(), + controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }); + expect(await leaseReads(f)).toEqual([]); + }, 120_000); + + it("still reads the unexpired controller lease of a legacy run another server is settling", async () => { + const f = await seed({ runtimeMode: "legacy", controllerBootId: randomUUID(), + controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }); + expect(await leaseReads(f)).toHaveLength(1); + }, 120_000); +}); diff --git a/server/src/__tests__/recovery-settled-records-census.test.ts b/server/src/__tests__/recovery-settled-records-census.test.ts new file mode 100644 index 00000000000..08ce7379d16 --- /dev/null +++ b/server/src/__tests__/recovery-settled-records-census.test.ts @@ -0,0 +1,304 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { agents, companies, createDb, environmentLeases, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, + issues, nativeRunFinalizations, workspaceOperations } from "@paperclipai/db"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; +import { notifyExecutionRunWork } from "../services/execution-control-notifications.js"; +import { executionControlSchedule, registerExecutionControlWork } from "../services/execution-control-work.js"; +import { registerOwnershipReconciliationWork } from "../services/native-runtime/native-finalization-reconciler.js"; +import { OWNABLE_KINDS } from "../services/recovery/ownership-registry.js"; +import { createOwnershipReportState, recheckSettlingKinds, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js"; +import { invalidateNativeReplacementDiscovery, reconcileSafeNativeReplacements } from "../services/native-runtime/native-safe-replacement.js"; +import { notifyRunDispatch } from "../services/run-dispatch-notifications.js"; +import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; +import { idleWorkSnapshot } from "../services/task-admission.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000); +const quiesced = () => ({ schema: "paperclip.remote-workspace-save-work.v1", activeIds: [], unknown: false, + owners: {}, quiescedAt: minutesAgo(600).toISOString() }); + +type Census = { statements: number; locks: number; byShape: Map }; + +function shapeOf(query: string) { + const text = query.replace(/\s+/g, " ").trim(); + const table = /\bfrom "?([a-z_]+)"?/i.exec(text)?.[1] ?? /^(?:update|insert into) "?([a-z_]+)"?/i.exec(text)?.[1] ?? "?"; + const verb = text.split(" ")[0]!.toLowerCase(); + return `${verb} ${table}${/ for (update|share|no key update)\b/i.test(text) ? " FOR UPDATE" : ""}`; +} + +function callerOf(stack: string) { + const frame = stack.split("\n").slice(1).find(line => line.includes("/server/src/services/") + && !line.includes("delivery-work-coordinator") && !line.includes("task-admission") && !line.includes("activity-log")); + const match = frame && /services\/([^:)]+):(\d+)/.exec(frame); + return match ? `${match[1]}:${match[2]}` : "?"; +} + +describe.skipIf(!support.supported)("recovery passes over settled records (census)", () => { + let database: Awaited>; + let db: ReturnType; + let meter: ReturnType; + let home: string; + let coordinator: ReturnType | undefined; + const errors: unknown[] = []; + let companyId: string, agentId: string; + + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), "recovery-census-home-")); + vi.stubEnv("PAPERCLIP_HOME", home); + vi.stubEnv("SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR", join(home, "orphan-spool")); + database = await startEmbeddedPostgresTestDatabase("recovery-settled-census-"); + db = createDb(database.connectionString, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + meter = meterDatabaseStatements(db, database.connectionString); + }, 120_000); + afterAll(async () => { + meter?.uninstall(); await db?.$client.end({ timeout: 1 }); await database?.cleanup(); + vi.unstubAllEnvs(); + await rm(home, { recursive: true, force: true }); + }); + beforeEach(async () => { + await db.execute(sql`truncate execution_workspace_snapshots, workspace_operations, execution_workspaces, activity_log, + native_run_finalizations, heartbeat_runs, issues, agents, companies cascade`); + companyId = randomUUID(); agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Census", issuePrefix: `C${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer", adapterType: "paperclip_runner" }); + }); + afterEach(async () => { + await coordinator?.stop(); coordinator = undefined; + vi.useRealTimers(); + expect(errors.splice(0)).toEqual([]); + }); + + const runRow = (values: Partial = {}) => ({ id: randomUUID(), companyId, agentId, + status: "failed", invocationSource: "manual", finishedAt: minutesAgo(600), errorCode: "process_lost", ...values }); + + const workspaceRow = (authority: { epoch: number; writerRunId: string | null; dirty: boolean; location?: boolean }) => { + const id = randomUUID(); + return { id, companyId, mode: "isolated_workspace", strategyType: "test", name: id, + metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: authority.epoch, snapshotId: null, + source: { kind: "git", repoUrl: "https://example.invalid/repo.git", ref: null }, dirty: authority.dirty, + writerRunId: authority.writerRunId, + location: authority.location ? { environmentId: randomUUID(), leaseId: randomUUID(), providerLeaseId: `sandbox-${id}`, + remoteCwd: "/workspace/root" } : null } } }; + }; + + type Rows = { runs: Array>; workspaces: Array>; + operations: Array; snapshots: Array }; + + function ledgerRow(rows: Rows, input: { workspaceId: string; runId: string; epoch: number; status: "pending" | "uploaded"; objectKey?: string | null }) { + const operationId = randomUUID(), snapshotId = randomUUID(); + rows.operations.push({ id: operationId, companyId, executionWorkspaceId: input.workspaceId, + heartbeatRunId: input.runId, phase: "remote_workspace_snapshot", status: "failed", + metadata: { epoch: input.epoch, boundary: "final", generation: 1, saveWork: quiesced() } }); + rows.snapshots.push({ id: snapshotId, companyId, executionWorkspaceId: input.workspaceId, + sourceOperationId: operationId, sourceRunId: input.runId, generation: 1, epoch: input.epoch, status: input.status, + objectKey: input.objectKey ?? null, deleteAfter: new Date(Date.now() + 7 * 86400_000), createdAt: minutesAgo(600), + updatedAt: minutesAgo(600) }); + return snapshotId; + } + + async function insert(rows: Rows) { + if (rows.runs.length) await db.insert(heartbeatRuns).values(rows.runs); + if (rows.workspaces.length) await db.insert(executionWorkspaces).values(rows.workspaces); + if (rows.operations.length) await db.insert(workspaceOperations).values(rows.operations); + if (rows.snapshots.length) await db.insert(executionWorkspaceSnapshots).values(rows.snapshots); + } + + /** The staging shape: history that recovery can no longer change, plus a few live runs. */ + async function seedStagingShape() { + const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] }; + for (let index = 0; index < 100; index++) { + const writer = runRow(index % 2 === 0 ? { executionStage: "executing", runtimeMode: "native", + runtimeModeResolvedAt: minutesAgo(601) } : { status: "succeeded", executionStage: "executing" }); + const workspace = workspaceRow({ epoch: 1, writerRunId: writer.id, dirty: true, location: true }); + rows.runs.push(writer); rows.workspaces.push(workspace); + if (index % 2 === 0) ledgerRow(rows, { workspaceId: workspace.id, runId: writer.id, epoch: 1, status: "pending" }); + } + for (let index = 0; index < 100; index++) { + const source = runRow({ status: "succeeded" }); + const workspace = workspaceRow({ epoch: 2, writerRunId: null, dirty: false }); + rows.runs.push(source); rows.workspaces.push(workspace); + ledgerRow(rows, { workspaceId: workspace.id, runId: source.id, epoch: 1, status: "uploaded", + objectKey: `${companyId}/snapshots/${index}.pcws` }); + } + const finished: Array = [], finalizations: Array = []; + for (let index = 0; index < 20; index++) { + const issueId = randomUUID(); + finished.push({ id: issueId, companyId, title: `Finished ${index}`, status: "done", assigneeAgentId: agentId }); + const failed = runRow({ runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId }, + runnerProfileJson: { recoveryEventInventoryVersion: 1, nativeExecutionInput: { provider: { kind: "codex" }, + workspace: { cwd: tmpdir() } } } }); + rows.runs.push(failed); + finalizations.push({ runId: failed.id, companyId, issueId, phase: "terminal_failure", attempt: 1, + failureCode: "native_provider_terminal_failed", failureDetail: { originalFailureCode: "fixture_checkpoint_unusable" } }); + } + const live: Array<{ runId: string; issueId: string }> = []; + for (let index = 0; index < 7; index++) { + const issueId = randomUUID(); + const liveRun = runRow({ status: "running", runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId }, + finishedAt: null, errorCode: null, startedAt: minutesAgo(1) }); + finished.push({ id: issueId, companyId, title: `Live ${index}`, status: "in_progress", assigneeAgentId: agentId }); + rows.runs.push(liveRun); + live.push({ runId: liveRun.id, issueId }); + } + await db.insert(issues).values(finished); + await insert(rows); + await db.insert(nativeRunFinalizations).values(finalizations); + for (const entry of live) await db.update(issues).set({ executionRunId: entry.runId }).where(sql`id = ${entry.issueId}`); + return live; + } + + async function start() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, + onError: error => errors.push(error) }); + const ownership = registerOwnershipReconciliationWork(db, coordinator, () => true); + const replacement = registerExecutionControlWork(coordinator, [replacementDuty()]); + await Promise.all([ownership.ready, replacement.ready]); + } + + function replacementDuty() { + return { queue: DELIVERY_QUEUES.executionReplacement, + run: () => reconcileSafeNativeReplacements(db, new Date(), { verifyStoppedSession: async () => null }), + next: executionControlSchedule(db).replacement, onSettled: () => invalidateNativeReplacementDiscovery(db), + settleEmptyWhilePaused: true }; + } + + async function advance(ms: number, onTick?: () => Promise) { + const until = Date.now() + ms; + while (Date.now() < until) { + await onTick?.(); + await vi.advanceTimersByTimeAsync(Math.min(10_000, until - Date.now())); await delay(1); + while (idleWorkSnapshot().active > 0) await delay(5); + } + } + + async function census(work: () => Promise): Promise { + const result: Census = { statements: 0, locks: 0, byShape: new Map() }; + meter.startLog({ stacks: true }); + try { await work(); } finally { + for (const entry of meter.stopLog()) { + const lock = / for (update|share|no key update)\b/i.test(entry.sql); + const key = `${shapeOf(entry.sql)} <- ${callerOf(entry.stack ?? "")}`; + const row = result.byShape.get(key) ?? { count: 0, locks: 0 }; + row.count += 1; if (lock) row.locks += 1; + result.byShape.set(key, row); + result.statements += 1; if (lock) result.locks += 1; + } + } + return result; + } + + function table(label: string, result: Census) { + const rows = [...result.byShape].sort((a, b) => b[1].count - a[1].count).slice(0, 20) + .map(([key, value]) => ` ${String(value.count).padStart(6)} ${String(value.locks).padStart(5)} ${key}`); + return `${label}: ${result.statements} statements, ${result.locks} row locks\n${rows.join("\n")}`; + } + + const hint = async (live: Array<{ runId: string; issueId: string }>) => { + for (const { runId, issueId } of live) { + await db.transaction(async tx => { + await notifyRunDispatch(tx, { companyId, runId, issueId }); + await notifyExecutionRunWork(tx, { companyId, runId, issueId }); + }); + } + }; + + it("counts statements and row locks of one pass of each worker over staging-shaped history", async () => { + await seedStagingShape(); + const state = createOwnershipReportState(); + await runOwnershipReconciliationPass(db, { state }); + await runOwnershipReconciliationPass(db, { state }); + const fullPass = await census(() => runOwnershipReconciliationPass(db, { state })); + const watchPass = await census(() => recheckSettlingKinds(db)); + const duty = replacementDuty(); + await duty.run(); + invalidateNativeReplacementDiscovery(db); + const replacementPass = await census(async () => { await duty.run(); await duty.next(); }); + console.log([table("ownership full pass", fullPass), table("ownership watch re-check", watchPass), + table("execution replacement pass", replacementPass)].join("\n\n")); + const settled = (result: Census) => [...result.byShape.keys()].filter(key => + /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key)); + expect({ full: settled(fullPass), watch: settled(watchPass) }).toEqual({ full: [], watch: [] }); + expect(fullPass.locks).toBe(0); + expect(watchPass.statements).toBeLessThanOrEqual(30); + expect(replacementPass.statements).toBeLessThanOrEqual(3); + }, 300_000); + + it("runs no statements for half an hour once only settled history is left, and takes no row locks while runs are active", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const live = await seedStagingShape(); + await start(); await advance(60_000); + await db.update(issues).set({ executionRunId: null, status: "done" }).where(sql`execution_run_id is not null`); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(sql`status = 'running'`); + await advance(60_000); + const idle = await census(() => advance(30 * 60_000)); + await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }) + .where(sql`id in (${sql.join(live.map(entry => sql`${entry.runId}`), sql`, `)})`); + const active = await census(() => advance(10 * 60_000, () => hint(live))); + console.log([table("idle 30 min", idle), table("active 10 min", active)].join("\n\n")); + expect(idle.statements).toBe(0); + expect(active.locks).toBe(0); + expect([...active.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]); + }, 1_200_000); + + it("still settles every record that can change promptly, beside staging-shaped history", async () => { + await seedStagingShape(); + const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] }; + const preparing = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) }); + const preparedWorkspace = workspaceRow({ epoch: 1, writerRunId: preparing.id, dirty: true, location: true }); + const saver = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) }); + const movedWorkspace = workspaceRow({ epoch: 3, writerRunId: null, dirty: false }); + const stuckWriter = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) }); + const stuckWorkspace = workspaceRow({ epoch: 1, writerRunId: stuckWriter.id, dirty: true, location: true }); + const leaseRun = runRow({ finishedAt: minutesAgo(2) }); + rows.runs.push(preparing, saver, stuckWriter, leaseRun); + rows.workspaces.push(preparedWorkspace, movedWorkspace, stuckWorkspace); + const abandoned = ledgerRow(rows, { workspaceId: movedWorkspace.id, runId: saver.id, epoch: 1, status: "pending" }); + const held = ledgerRow(rows, { workspaceId: stuckWorkspace.id, runId: stuckWriter.id, epoch: 1, status: "pending" }); + await insert(rows); + const [lease] = await db.insert(environmentLeases).values({ companyId, heartbeatRunId: leaseRun.id, status: "active" }).returning(); + const ledger = async (id: string) => (await db.select().from(executionWorkspaceSnapshots) + .where(eq(executionWorkspaceSnapshots.id, id)))[0]!; + + const state = createOwnershipReportState(); + const first = await runOwnershipReconciliationPass(db, { state }); + const kind = (id: string) => first.kinds.find(entry => entry.kind === id)!; + expect(kind("remote_workspace_unsaved_files")).toMatchObject({ settled: 1 }); + expect(readRemoteWorkspaceAuthority((await db.select().from(executionWorkspaces) + .where(eq(executionWorkspaces.id, preparedWorkspace.id)))[0]!.metadata)).toMatchObject({ dirty: false, writerRunId: null, epoch: 2 }); + expect((await ledger(abandoned)).status).toBe("deleted"); + expect((await ledger(held)).status).toBe("pending"); + expect(kind("environment_run_lease_active")).toMatchObject({ inProgress: 1, settled: 1 }); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease!.id)))[0]!.status).toBe("pending_cleanup"); + + await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { ...readRemoteWorkspaceAuthority(stuckWorkspace.metadata)!, + epoch: 2, writerRunId: null, dirty: false, location: null } } }).where(eq(executionWorkspaces.id, stuckWorkspace.id)); + const second = await runOwnershipReconciliationPass(db, { state }); + expect(second.kinds.find(entry => entry.kind === "remote_snapshot_ledger")).toMatchObject({ settled: 1 }); + expect((await ledger(held)).status).toBe("deleted"); + const settledPass = await census(() => runOwnershipReconciliationPass(db, { state })); + expect([...settledPass.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]); + }, 300_000); + + it("skips a dirty workspace whose writer id is not a UUID without failing the listing", async () => { + const valid = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) }); + const rows: Rows = { runs: [valid], workspaces: [workspaceRow({ epoch: 1, writerRunId: valid.id, dirty: true, location: true })], + operations: [], snapshots: [] }; + const malformed = workspaceRow({ epoch: 1, writerRunId: null, dirty: true, location: true }); + malformed.metadata.remoteWorkspace.writerRunId = "not-a-run-id" as unknown as null; + rows.workspaces.push(malformed); + await insert(rows); + const kind = OWNABLE_KINDS.find(entry => entry.id === "remote_workspace_unsaved_files")!; + const listed = await kind.listInProgress!(db, 200, 0); + expect(listed.records.map(record => record.recordId)).toEqual([rows.workspaces[0]!.id]); + }, 120_000); +}); + diff --git a/server/src/services/recovery/ownership-registry.ts b/server/src/services/recovery/ownership-registry.ts index 66c768dc06a..1d07a28f561 100644 --- a/server/src/services/recovery/ownership-registry.ts +++ b/server/src/services/recovery/ownership-registry.ts @@ -38,8 +38,8 @@ import { } from "../native-runtime/native-accepted-result-lease-settlement.js"; import { settleClaimedWakeRequest } from "./wake-request-claimed-settlement.js"; import { settleAbandonedRemoteSnapshotSave, settleAbandonedWorkspaceCommandOperation, settleAbandonedWorkspaceFinalizeAttempt } from "./workspace-finalize-attempt-settlement.js"; -import { settlePreparationOnlyRemoteWorkspaceEpoch } from "./remote-workspace-unsaved-files-settlement.js"; -import { settleAbandonedRemoteSnapshotLedger } from "./remote-snapshot-ledger-settlement.js"; +import { preparationOnlyWriterCondition, settlePreparationOnlyRemoteWorkspaceEpoch } from "./remote-workspace-unsaved-files-settlement.js"; +import { retirableRemoteSnapshotLedgerCondition, settleAbandonedRemoteSnapshotLedger } from "./remote-snapshot-ledger-settlement.js"; import { LOCAL_WORKSPACE_COMMAND_PHASES, runtimeControlOperationOwnerStamp, settleRuntimeControlOperation } from "../workspace-operations.js"; import { copybackOwnerHoldOwner, settleCopybackOwnerHold } from "./copyback-owner-hold.js"; import { applyObservedFenceProviderProof, observedWorkspaceFenceOwner, settleObservedWorkspaceFence } from "./observed-workspace-fence.js"; @@ -968,7 +968,8 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [ listInProgress: async (db, limit, offset) => { const rows = await db.select({ id: executionWorkspaces.id, companyId: executionWorkspaces.companyId, metadata: executionWorkspaces.metadata, updatedAt: executionWorkspaces.updatedAt }).from(executionWorkspaces) - .where(sql`(${executionWorkspaces.metadata}->'remoteWorkspace'->>'dirty')::boolean is true`).orderBy(asc(executionWorkspaces.id)).limit(limit + 1).offset(offset); + .where(and(sql`(${executionWorkspaces.metadata}->'remoteWorkspace'->>'dirty')::boolean is true`, + preparationOnlyWriterCondition())).orderBy(asc(executionWorkspaces.id)).limit(limit + 1).offset(offset); const result = page(rows, limit); return { truncated: result.truncated, records: result.rows.map(row => { const writerRunId = str(json(json(row.metadata).remoteWorkspace).writerRunId); @@ -983,7 +984,7 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [ listInProgress: async (db, limit, offset) => { const rows = await db.select({ id: executionWorkspaceSnapshots.id, companyId: executionWorkspaceSnapshots.companyId, sourceRunId: executionWorkspaceSnapshots.sourceRunId, updatedAt: executionWorkspaceSnapshots.updatedAt }) - .from(executionWorkspaceSnapshots).where(inArray(executionWorkspaceSnapshots.status, ["pending", "uploaded"])).orderBy(asc(executionWorkspaceSnapshots.id)).limit(limit + 1).offset(offset); + .from(executionWorkspaceSnapshots).where(retirableRemoteSnapshotLedgerCondition()).orderBy(asc(executionWorkspaceSnapshots.id)).limit(limit + 1).offset(offset); const result = page(rows, limit); return { truncated: result.truncated, records: result.rows.map(row => ({ recordId: row.id, companyId: row.companyId, runId: row.sourceRunId, issueId: null, diff --git a/server/src/services/recovery/remote-snapshot-ledger-settlement.ts b/server/src/services/recovery/remote-snapshot-ledger-settlement.ts index 9a5dbe2bf94..dbd6df0a7fb 100644 --- a/server/src/services/recovery/remote-snapshot-ledger-settlement.ts +++ b/server/src/services/recovery/remote-snapshot-ledger-settlement.ts @@ -1,4 +1,4 @@ -import { and, eq, isNull, sql } from "drizzle-orm"; +import { and, eq, isNull, sql, type SQL } from "drizzle-orm"; import { executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { persistActivity, publishActivity, type ActivityPublication } from "../activity-log.js"; @@ -14,6 +14,16 @@ const TERMINAL_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", type Snapshot = typeof executionWorkspaceSnapshots.$inferSelect; +export function retirableRemoteSnapshotLedgerCondition(): SQL { + return and(eq(executionWorkspaceSnapshots.status, "pending"), isNull(executionWorkspaceSnapshots.objectKey), + sql`not exists (select 1 from workspace_operations operation where operation.company_id = ${executionWorkspaceSnapshots.companyId} + and operation.id = ${executionWorkspaceSnapshots.sourceOperationId} and operation.phase <> 'remote_workspace_snapshot')`, + sql`not exists (select 1 from execution_workspaces workspace where workspace.company_id = ${executionWorkspaceSnapshots.companyId} + and workspace.id = ${executionWorkspaceSnapshots.executionWorkspaceId} + and workspace.metadata->'remoteWorkspace'->>'writerRunId' = ${executionWorkspaceSnapshots.sourceRunId}::text + and workspace.metadata->'remoteWorkspace'->>'epoch' = ${executionWorkspaceSnapshots.epoch}::text)`)!; +} + export async function retireEndedRemoteSnapshotLedgerRow(tx: Db, input: { companyId: string; snapshotId: string; now: Date; proof: string; }): Promise<{ retired: true; snapshot: Snapshot; status: "deleted" | "delete_requested" } | { retired: false; reason: string }> { diff --git a/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts b/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts index 5931f763b7e..bdc51aa68b4 100644 --- a/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts +++ b/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts @@ -1,4 +1,4 @@ -import { and, eq, inArray, like, or, sql } from "drizzle-orm"; +import { and, eq, inArray, like, or, sql, type SQL } from "drizzle-orm"; import { executionWorkspaces, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import type { OwnerProof } from "../owner-proof.js"; @@ -11,17 +11,36 @@ const TERMINAL_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", const WORK_STARTED_EVENT_TYPES = ["adapter.invoke", "adapter.progress"]; const WORK_STARTED_EVENT_PREFIXES = ["turn.", "provider.", "native.process_"]; +const WRITER_RUN_ID = sql`${executionWorkspaces.metadata}->'remoteWorkspace'->>'writerRunId'`; + +export function preparationOnlyWriterCondition(): SQL { + const workStarted = sql.join([ + sql`event.event_type in (${sql.join(WORK_STARTED_EVENT_TYPES.map(type => sql`${type}`), sql`, `)})`, + ...WORK_STARTED_EVENT_PREFIXES.map(prefix => sql`event.event_type like ${`${prefix}%`}`), + ], sql` or `); + return sql`(${WRITER_RUN_ID} is null or exists (select 1 from heartbeat_runs writer + where writer.id = (case when ${WRITER_RUN_ID} ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + then (${WRITER_RUN_ID})::uuid end) and writer.company_id = ${executionWorkspaces.companyId} + and writer.execution_stage = 'preparing' and writer.runtime_mode_resolved_at is null + and writer.process_pid is null and writer.process_group_id is null + and writer.native_session_id is null and writer.runner_instance_id is null + and not exists (select 1 from native_run_finalizations finalization + where finalization.company_id = writer.company_id and finalization.run_id = writer.id) + and not exists (select 1 from heartbeat_run_events event where event.run_id = writer.id and (${workStarted}))))`; +} + export async function settlePreparationOnlyRemoteWorkspaceEpoch(db: Db, record: InProgressRecord, context: { now: Date; proof: OwnerProof }): Promise { if (record.owner.kind !== "run" || !record.runId || !record.companyId) return { settled: false, reason: "owner_not_provable" }; const runId = record.runId, companyId = record.companyId; return db.transaction(async (transaction): Promise => { const tx = transaction as unknown as Db; - const [run] = await tx.select({ status: heartbeatRuns.status, executionStage: heartbeatRuns.executionStage, + const readRun = () => tx.select({ status: heartbeatRuns.status, executionStage: heartbeatRuns.executionStage, runtimeModeResolvedAt: heartbeatRuns.runtimeModeResolvedAt, processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, nativeSessionId: heartbeatRuns.nativeSessionId, runnerInstanceId: heartbeatRuns.runnerInstanceId }) - .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId))).for("update"); + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId))); + const [run] = await readRun(); if (!run || !TERMINAL_RUN_STATUSES.includes(run.status)) return { settled: false, reason: "owner_run_active" }; if (run.runtimeModeResolvedAt || run.executionStage !== "preparing") return { settled: false, reason: "writer_reached_runtime", watch: false }; const [finalization] = await tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations) @@ -44,6 +63,10 @@ export async function settlePreparationOnlyRemoteWorkspaceEpoch(db: Db, record: eq(workspaceOperations.phase, "remote_workspace_snapshot"), inArray(workspaceOperations.status, ["running", "pending"]), sql`${workspaceOperations.metadata}->>'epoch' = ${String(authority.epoch)}`)).limit(1); if (save) return { settled: false, reason: "save_in_flight" }; + const [locked] = await readRun().for("update"); + if (!locked || !TERMINAL_RUN_STATUSES.includes(locked.status)) return { settled: false, reason: "owner_run_active" }; + if (locked.runtimeModeResolvedAt || locked.executionStage !== "preparing" || locked.processPid || locked.processGroupId + || locked.nativeSessionId || locked.runnerInstanceId) return { settled: false, reason: "writer_reached_runtime", watch: false }; // A preparation that restored the saved version and then did nothing else // left exactly that version in its root. When the durable unchanged-baseline // proof holds, hand the workspace on at its saved version and keep the root, diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 52b165c4bb5..0cb4576f41e 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -322,6 +322,8 @@ type LatestIssueRun = retryOfRunId?: string | null; scheduledRetryReason?: string | null; runnerProfileJson?: unknown; + runtimeMode?: string | null; + controllerBootId?: string | null; }) | null; type SuccessfulLatestIssueRun = NonNullable & { @@ -1099,6 +1101,8 @@ export function recoveryService( retryOfRunId: heartbeatRuns.retryOfRunId, scheduledRetryReason: heartbeatRuns.scheduledRetryReason, runnerProfileJson: heartbeatRuns.runnerProfileJson, + runtimeMode: heartbeatRuns.runtimeMode, + controllerBootId: heartbeatRuns.controllerBootId, }) .from(heartbeatRuns) .where( @@ -1208,8 +1212,11 @@ export function recoveryService( * a live execution; another process proves it with its unexpired controller * lease, which it clears once settlement (retry scheduling, claim release) * is done. This process's own lease without a live execution is stale. */ - async function terminalRunSettlingUntil(companyId: string, runId: string): Promise { + async function terminalRunSettlingUntil(companyId: string, runId: string, + known?: { runtimeMode?: string | null; controllerBootId?: string | null }): Promise { if (deps.liveRunExecutions?.has(runId)) return new Date(Date.now() + 30_000); + if (known?.runtimeMode !== undefined && (known.runtimeMode !== "legacy" || !known.controllerBootId + || known.controllerBootId === legacyControllerBootId)) return null; const [run] = await db.select({ leaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt }) .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId), eq(heartbeatRuns.runtimeMode, "legacy"), sql`${heartbeatRuns.controllerBootId} is not null`, @@ -4755,7 +4762,7 @@ export function recoveryService( || await isAutomaticRecoverySuppressedByPauseHold(db, issue.companyId, issue.id, treeControlSvc)) continue; // Another server is still settling the run: look again when its lease // lapses, since later generic skips may never reach their own check. - const settlingUntil = await terminalRunSettlingUntil(issue.companyId, run.id); + const settlingUntil = await terminalRunSettlingUntil(issue.companyId, run.id, latestRun); if (settlingUntil) { onDeferredDeadline?.(settlingUntil.getTime()); handled.add(issue.id); @@ -4937,7 +4944,7 @@ export function recoveryService( // and releases the claim itself. Escalating in that window clears the // claim the retry needs. Re-check once its controller lease lapses. const settlingUntil = latestRun && isTerminalIssueRun(latestRun) - ? await terminalRunSettlingUntil(issue.companyId, latestRun.id) : null; + ? await terminalRunSettlingUntil(issue.companyId, latestRun.id, latestRun) : null; if (settlingUntil) { opts?.onDeferredDeadline?.(settlingUntil.getTime()); result.skipped += 1; From f71aa135a0d52a1f86b81bb2a1f3e10db6bf4cde Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:54:23 -0600 Subject: [PATCH 18/20] fix(server): release sandbox leases for runs stopped before runner attach (#21788) 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 in a `sandbox` environment run each task in a paid remote sandbox that an environment lease tracks > - When a run stops, the control plane must release that lease, and terminating an agent waits until every lease of the agent is released > - In a load test, a run stopped after its sandbox was ready but before its runner started never released its lease, so the sandbox kept running and the agent stayed in "terminating" forever > - In the same test, terminating an agent whose failed run had a scheduled same-run retry waited about 18 minutes, until the stale retry time > - This pull request makes lease release finish for every stop window, records any release that must wait with a retry time, adds a hint-driven safety net, and makes termination cancel a pending native retry at once > - The benefit is that a stopped run never leaves a paid sandbox running, and agent termination finishes in seconds without manual repair ## Linked Issues or Issue Description **What happened?** A load test with ten OpenCode agents in a `sandbox` environment stopped its agents mid-run (pause, then terminate). Two defects appeared. 1. A run cancelled while it selected its provider pack (after the sandbox was acquired and the workspace was prepared, before the runner started) kept its environment lease `active` for more than 40 minutes. The agent stayed in lifecycle `terminating`. The lifecycle worker retried every pass and wrote `updatedAt` each time with no recorded reason. Delete returned 409 "Complete termination before deleting the agent". 2. A failed native run with a scheduled bootstrap retry kept its lease until the stale retry time. Agent termination took about 18 minutes. The run still showed "retry_scheduled" after the agent was terminated. **Expected behavior** A stopped run releases its sandbox lease within seconds. If release must wait, the wait has a recorded reason and retry time, and a background pass finishes it. Terminating an agent cancels a pending retry, releases its lease, and reaches `terminated` promptly. **Steps to reproduce** 1. Start a native run in a `sandbox` environment. 2. Stop it after the sandbox is acquired and the workspace is prepared, before the runner starts. 3. Pause and then terminate the agent. 4. See that the lease stays `active` and the agent stays `terminating`. **Paperclip version or commit** Reproduced on `master` at 62033b9994 (load test build 2026.1106.0+2564). **Relevant logs or output** Root causes found in the code: - `releaseEnvironmentLeasesForRun` returned with no record when workspace retention refused a cancelled run. The refusal was permanent when the run's native finalization owner had expired but was not cleared. The owner is cleared only after `agentExecutionsHaveStopped` sees every lease released, so the two waited on each other. - `releaseRunLeases` silently skipped a lease whose prepared native workspace was still "pending export", even for a run that never started a runner and so never changed those files. - The destroy path deferred on any busy warm session in the same environment, also with no record. - `stopInvocationsForAgents` returned on the first run that was still live, so it did not release the leases of the other runs of the agent. - The agent stop cancelled only `queued`, `running` and `scheduled_retry` runs. A failed native run with a pending same-run retry kept its lease until that retry fired. - The lifecycle worker deferred a pending host step by 2 seconds every pass, with no reason and no backoff. ## What Changed - `releaseEnvironmentLeasesForRun` (`run-control.ts`): - A native run with no runner launch evidence (no `native.process_start_requested`, no runner event, no process id) skips workspace retention and warm-session closing. No runner process exists to fence, and no work ran against the prepared files. - When retention is refused only because the run's native finalization owner lease has expired, the release clears that expired owner (compare-and-set on the exact expired owner of a cancelled run with no result) and retries retention once. A recorded recovery then stops and retains the sandbox, so the files stay recoverable. - Every release that cannot finish now records `metadata.releaseDeferral` (`reason`, `attempts`, `retryAt`, disposition) on the active lease and publishes an `orphan-active-leases` hint. The retry time backs off from 30 seconds to 15 minutes, then retries hourly without end. The record keeps `failingSince` and the last reason. A new Stop or terminate operation, or a server restart, triggers an immediate attempt. - `nativeWorkspaceExportPendingForLease` treats a cancelled run with no runner launch evidence as owing no export. - Safety net: `sweepOrphanedActiveLeases` (the existing hint- and deadline-driven orphan-lease work) now retries the run's own release for a due deferral or for a cancelled native run, after the native owner lease has expired. The orphan-lease loader uses the stored `retryAt` as the due time. No new timer or poller. - Agent stop: - It cancels a failed native run that has a pending same-run retry (or an interrupted cancellation of one), through the existing retry-cancellation path. A pause stamps `pauseStop` on those runs too, so a budget resume can continue them. - It releases the leases of every terminal run, and it skips a lease whose deferral is not yet due. - `agentInvocationStopBlocker` and `agentExecutionStopBlocker` return why the stop must still wait. - Lifecycle worker: a pending host or plugin step records `pendingReason` and `pendingPasses` on the operation, and its retry backs off from 2 seconds to a 60 second cap. When a release leaves a run with no unsettled lease, the stopping agent's saved retry time is cleared and the lifecycle queue is notified, so Pause or Terminate finishes on the next pass. - Cancelled-workspace preservation: a stopped run that never started a runner has its prepared reference moved to `nativeWorkspaceSyncReleasedUnchanged` when its lease is released, so the preservation worker no longer selects it. The worker records the same settlement itself for older runs, and waits on a live owner's exact lease expiry. ## Verification - Red on `master`, green on this branch (embedded PostgreSQL, fake plugin sandbox provider): - `server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts`: agent pause then terminate, and board Stop, for each window between sandbox acquire and runner attach (artifact discovery, pack select, pack upload, runner launch, transport connect, session open). Each test checks that the provider gets a stop or destroy call, the lease is released, the run is cancelled, and the agent reaches `terminated` within one extra worker pass. It also checks the orphan-lease safety net for a leaked lease and a recorded deferral that the background pass finishes when due. - `server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts`: terminating an agent whose failed run has a bootstrap retry 17 minutes away cancels the retry, releases the lease and reaches `terminated` at once. The test covers an open task and a cancelled task. - `server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts`: a host step that stays pending records its reason, and its retry delay grows to a 60 second cap. - Related suites pass: run-control, recovery, orphaned active lease sweep, environment runtime, agent lifecycle, native workspace preservation and recovery, held comment wake. - `server` typecheck passes. ## Risks - A cancelled native run with no launch evidence now gets its prepared sandbox destroyed instead of kept. The proof is the same launch evidence that restart recovery uses. - A launched cancelled run whose retention owes nothing is stopped and retained, as before. A retention that throws (lock or write error, or a live owner) now keeps the lease active with a recorded reason and retry time, instead of a silent skip. - Release now clears an expired native finalization owner of a cancelled run. An old controller whose lease already expired then fails its next owner check and stops, which is the normal lease rule. - On the first start after deploy, the orphan-lease work releases leases already leaked by cancelled native runs. - Task state after pause then terminate: the run-scoped stop keeps the task status (an open task stays open, a cancelled task stays cancelled), and a run that held prepared files gets the existing workspace recovery record on its stopped sandbox. No new state is added. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (code search, shell, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ...lease-release-before-runner-attach.test.ts | 285 ++++++++++++++++++ ...eat-terminate-pending-native-retry.test.ts | 140 +++++++++ .../__tests__/driver-scope.test.ts | 4 +- .../__tests__/pending-backoff.test.ts | 86 ++++++ .../agent-lifecycle/adapters/postgres.ts | 30 +- .../agent-lifecycle/application/ports.ts | 4 +- .../agent-lifecycle/application/worker.ts | 7 +- server/src/modules/agent-lifecycle/index.ts | 2 +- server/src/services/agent-execution-stop.ts | 31 +- server/src/services/agent-lifecycle-driver.ts | 11 +- ...environment-lease-release-deferral.test.ts | 61 ++++ .../environment-lease-release-deferral.ts | 96 ++++++ server/src/services/heartbeat.ts | 32 +- .../services/heartbeat/live-recovery-work.ts | 9 +- server/src/services/heartbeat/recovery.ts | 38 +++ .../services/heartbeat/run-control.test.ts | 114 ++++++- server/src/services/heartbeat/run-control.ts | 106 ++++++- ...celled-workspace-preservation-idle.test.ts | 103 +++++++ .../native-failed-workspace-recovery.ts | 10 +- .../native-workspace-finalization-state.ts | 9 +- 20 files changed, 1126 insertions(+), 52 deletions(-) create mode 100644 server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts create mode 100644 server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts create mode 100644 server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts create mode 100644 server/src/services/environment-lease-release-deferral.test.ts create mode 100644 server/src/services/environment-lease-release-deferral.ts create mode 100644 server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts diff --git a/server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts b/server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts new file mode 100644 index 00000000000..f1f5229d7eb --- /dev/null +++ b/server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts @@ -0,0 +1,285 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, + companies, + createDb, + environmentLeases, + environments, + heartbeatRunEvents, + heartbeatRuns, + issues, + nativeRunFinalizations, + plugins, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() })); +vi.mock("../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient })); + +import { heartbeatService } from "../services/heartbeat.ts"; +import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js"; +import { configureAgentLifecycle, createAgentLifecycle } from "../services/agent-lifecycle.js"; +import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "../services/native-local-process-stop.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; + +type Window = "artifact_discovery" | "provider_pack_select" | "provider_pack_upload" | "runner_launch" | "transport_connect" | "session_open"; +const PRE_LAUNCH: Window[] = ["artifact_discovery", "provider_pack_select", "provider_pack_upload"]; +const ALL_WINDOWS: Window[] = [...PRE_LAUNCH, "runner_launch", "transport_connect", "session_open"]; +const PROVIDER_METHODS = ["environmentAcquireLease", "environmentExecute", "environmentReleaseLease", + "environmentDestroyLease", "environmentStopLease"]; + +describeEmbeddedPostgres("environment lease release between sandbox acquire and runner attach", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + const workers: Array<{ stop(): Promise }> = []; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-lease-release-before-attach-"); + db = createDb(tempDb.connectionString); + }, 30_000); + + afterEach(async () => { + for (const worker of workers.splice(0)) await worker.stop(); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + function providerWorker(pluginId: string) { + const call = vi.fn(async (_pluginId: string, method: string, params: { providerLeaseId?: string }) => { + if (method === "environmentDestroyLease") return { providerLeaseId: params.providerLeaseId, state: "destroyed" }; + if (method === "environmentStopLease") return { providerLeaseId: params.providerLeaseId, state: "stopped" }; + if (method === "environmentReleaseLease") return { providerLeaseId: params.providerLeaseId, state: "destroyed" }; + throw new Error(`Unexpected provider method ${method}`); + }); + const manager = { + isRunning: vi.fn((id: string) => id === pluginId), + getWorker: vi.fn(() => ({ supportedMethods: PROVIDER_METHODS })), + call, + } as unknown as PluginWorkerManager; + const teardownCalls = () => call.mock.calls.filter(([, method]) => + method === "environmentDestroyLease" || method === "environmentStopLease" || method === "environmentReleaseLease"); + return { manager, teardownCalls }; + } + + async function seed(window: Window) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const environmentId = randomUUID(), leaseId = randomUUID(), pluginId = randomUUID(); + const providerLeaseId = `sandbox-${randomUUID()}`; + const pluginKey = `paperclip.lease-release-${pluginId.slice(0, 8)}`; + await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@paperclipai/plugin-fake-sandbox", version: "1.0.0", + apiVersion: 1, categories: ["automation"], status: "ready", installOrder: 1, updatedAt: new Date(), + manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fake sandbox", description: "Test provider", + author: "Paperclip", categories: ["automation"], capabilities: ["environment.drivers.register"], + entrypoints: { worker: "dist/worker.js" }, + environmentDrivers: [{ driverKey: "fake-plugin", kind: "sandbox_provider", displayName: "Fake Plugin", + configSchema: { type: "object" } }] } } as never); + await db.insert(companies).values({ id: companyId, name: "Paperclip", + issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false }); + await db.insert(agents).values({ id: agentId, companyId, name: "OpenCoder", role: "engineer", status: "running", + adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" }, runtimeConfig: {}, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, title: "Short task", status: "in_progress", + priority: "medium", assigneeAgentId: agentId }); + const config = { provider: "fake-plugin", image: "fake:test", timeoutMs: 1234, reuseLease: false }; + await db.insert(environments).values({ id: environmentId, name: `Fake sandbox ${environmentId}`, driver: "sandbox", + status: "active", config }); + const startedAt = new Date(Date.now() - 10_000); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", status: "running", + runtimeMode: "native", runtimeModeResolvedAt: startedAt, issueId, nativeIssueId: issueId, startedAt, + contextSnapshot: { issueId }, nextEventSeq: 1, + runnerProfileJson: { nativeWorkspaceSync: { + schema: "paperclip.native-workspace-sync/v3", state: "prepared", descriptorSha256: "a".repeat(64), + baselineSha256: "b".repeat(64), finalHostSha256: null, workspaceId: randomUUID(), leaseId, providerLeaseId, + remoteCwd: "/workspace", resourceDisposition: "destroy" } } }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed", attempt: 1, + controllerGeneration: 1, leaseOwner: `executor-${runId}`, leaseExpiresAt: new Date(Date.now() - 1_000) }); + await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId, + status: "active", leasePolicy: "ephemeral", provider: "fake-plugin", providerLeaseId, + metadata: { ...config, agentId, driver: "sandbox", pluginId, pluginKey, sandboxProviderPlugin: true, + remoteCwd: "/workspace", sandboxState: "started" } }); + const events: Array<{ eventType: string; sourceEventId?: string }> = []; + if (!PRE_LAUNCH.includes(window)) events.push({ eventType: PROCESS_START_REQUESTED }); + if (window === "transport_connect" || window === "session_open") events.push({ eventType: PROCESS_IDENTITY_RECORDED }); + if (window === "session_open") events.push({ eventType: "session.started", sourceEventId: randomUUID() }); + for (const [index, event] of events.entries()) { + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: index + 1, eventType: event.eventType, + stream: "system", level: "info", message: event.eventType, sourceEventId: event.sourceEventId ?? null }); + } + await db.update(heartbeatRuns).set({ nextEventSeq: events.length + 1 }).where(eq(heartbeatRuns.id, runId)); + return { companyId, agentId, issueId, runId, leaseId, providerLeaseId, ...providerWorker(pluginId) }; + } + + async function lease(leaseId: string) { + return (await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]!; + } + + async function run(runId: string) { + return (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!; + } + + async function expectSandboxReleased(fixture: Awaited>) { + let row = await lease(fixture.leaseId); + if (row.status === "pending_cleanup") { + await heartbeatService(db, { pluginWorkerManager: fixture.manager }).sweepPendingCleanupLeases({ backoffMs: 0 }); + row = await lease(fixture.leaseId); + } + expect(row.status).not.toBe("active"); + expect(row.status).not.toBe("pending_cleanup"); + expect(row.releasedAt).not.toBeNull(); + expect(fixture.teardownCalls()).toContainEqual([expect.any(String), expect.any(String), + expect.objectContaining({ providerLeaseId: fixture.providerLeaseId }), expect.any(Number)]); + } + + it.each(ALL_WINDOWS)("terminating the agent releases a sandbox leased during %s", async window => { + const fixture = await seed(window); + const lifecycle = createAgentLifecycle(db); + const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager)); + workers.push(worker); + await lifecycle.pauseAgent(fixture.agentId); + await worker.process(fixture.agentId); + await lifecycle.terminateAgent(fixture.agentId); + let agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + let passes = 0; + for (; agent.lifecycleState !== "terminated" && passes < 4; passes++) { + await db.update(agents).set({ lifecycleOperation: { ...agent.lifecycleOperation!, retryAt: undefined } }) + .where(eq(agents.id, fixture.agentId)); + await worker.process(fixture.agentId); + agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + } + expect(agent.lifecycleState).toBe("terminated"); + expect(passes).toBeLessThanOrEqual(1); + const stopped = await run(fixture.runId); + expect(stopped.status).toBe("cancelled"); + await expectSandboxReleased(fixture); + if (PRE_LAUNCH.includes(window)) { + expect(stopped.runnerProfileJson).not.toHaveProperty("nativeWorkspaceSync"); + expect(stopped.runnerProfileJson).toHaveProperty("nativeWorkspaceSyncReleasedUnchanged.state", "prepared"); + } else { + expect(stopped.resultJson).toHaveProperty("workspaceRestoreRecovery.schema", "paperclip.workspace-restore-recovery.v1"); + } + }, 60_000); + + it.each(ALL_WINDOWS)("stopping the run releases a sandbox leased during %s", async window => { + const fixture = await seed(window); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + await heartbeat.cancelRun(fixture.runId, "Cancelled by a board operator", { + resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator" } }); + expect((await run(fixture.runId)).status).toBe("cancelled"); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + }, 60_000); + + it("records a release a live workspace owner holds back and finishes it in the background once due", async () => { + const fixture = await seed("runner_launch"); + const ownerUntil = new Date(Date.now() + 60_000); + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: ownerUntil }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + await heartbeat.releaseEnvironmentLeasesForRun({ runId: fixture.runId, companyId: fixture.companyId, + agentId: fixture.agentId, status: "cancelled", providerResourceDisposition: "destroy" }); + const deferred = await lease(fixture.leaseId); + expect(deferred.status).toBe("active"); + expect(deferred.metadata?.releaseDeferral).toMatchObject({ reason: "workspace_owner_active", attempts: 1, + providerResourceDisposition: "destroy" }); + expect(fixture.teardownCalls()).toHaveLength(0); + + const deadlines: number[] = []; + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000, + onDeferredDeadline: at => deadlines.push(at) }); + expect((await lease(fixture.leaseId)).status).toBe("active"); + expect(deadlines).toContain(Date.parse(String((deferred.metadata?.releaseDeferral as { retryAt: string }).retryAt))); + + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() - 1_000) }) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + await db.update(environmentLeases).set({ metadata: { ...deferred.metadata, + releaseDeferral: { ...(deferred.metadata?.releaseDeferral as object), retryAt: new Date(Date.now() - 1_000).toISOString() } } }) + .where(eq(environmentLeases.id, fixture.leaseId)); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + }, 60_000); + + async function terminate(fixture: Awaited>) { + const lifecycle = createAgentLifecycle(db); + const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager)); + workers.push(worker); + await lifecycle.terminateAgent(fixture.agentId); + await worker.process(fixture.agentId); + return (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + } + + it("finishes a release that lock conflicts held back, preserving the files, once the locks clear", async () => { + const fixture = await seed("runner_launch"); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + let ready!: () => void, unlock!: () => void; + const locked = new Promise(resolve => { ready = resolve; }); + const released = new Promise(resolve => { unlock = resolve; }); + const holder = db.transaction(async tx => { + await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, fixture.issueId)).for("update"); + ready(); await released; + }); + await locked; + try { + for (let attempt = 1; attempt <= 3; attempt++) { + await heartbeat.releaseEnvironmentLeasesForRun({ runId: fixture.runId, companyId: fixture.companyId, + agentId: fixture.agentId, status: "cancelled", providerResourceDisposition: "destroy" }); + expect((await lease(fixture.leaseId)).metadata?.releaseDeferral).toMatchObject({ reason: "workspace_retention_busy", attempts: attempt }); + } + } finally { unlock(); await holder; } + const deferred = await lease(fixture.leaseId); + await db.update(environmentLeases).set({ metadata: { ...deferred.metadata, releaseDeferral: { + ...(deferred.metadata?.releaseDeferral as object), retryAt: new Date(Date.now() - 1_000).toISOString() } } }) + .where(eq(environmentLeases.id, fixture.leaseId)); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + expect((await run(fixture.runId)).resultJson).toHaveProperty("workspaceRestoreRecovery.schema", "paperclip.workspace-restore-recovery.v1"); + expect((await terminate(fixture)).lifecycleState).toBe("terminated"); + }, 60_000); + + it("attempts a slow-phase deferred release at once when the agent is terminated", async () => { + const fixture = await seed("runner_launch"); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const current = await lease(fixture.leaseId); + await db.update(environmentLeases).set({ metadata: { ...current.metadata, releaseDeferral: { reason: "release_failed", + attempts: 8, retryAt: new Date(Date.now() + 60 * 60_000).toISOString(), failingSince: new Date(Date.now() - 3 * 3_600_000).toISOString(), + providerResourceDisposition: "destroy" } } }).where(eq(environmentLeases.id, fixture.leaseId)); + expect((await terminate(fixture)).lifecycleState).toBe("terminated"); + await expectSandboxReleased(fixture); + }, 60_000); + + it("gives each overlapping stop operation one immediate attempt, then respects the stored retry time", async () => { + const fixture = await seed("runner_launch"); + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() + 60 * 60_000) }) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + const parent = `lifecycle:${randomUUID()}`, child = `lifecycle:${randomUUID()}`; + for (let pass = 0; pass < 30; pass++) { + expect(await heartbeat.agentInvocationStopBlocker([fixture.agentId], "Agent lifecycle stop requested", + { trigger: pass % 2 === 0 ? parent : child })).toMatch(/^environment_lease_release_deferred:workspace_owner_active$/); + } + expect((await lease(fixture.leaseId)).metadata?.releaseDeferral).toMatchObject({ reason: "workspace_owner_active", + attempts: 2, triggers: [parent, child] }); + expect(fixture.teardownCalls()).toHaveLength(0); + }, 60_000); + + it.each(PRE_LAUNCH)("the orphan lease check releases a sandbox a cancelled run leaked during %s", async window => { + const fixture = await seed(window); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + }, 60_000); +}); diff --git a/server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts b/server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts new file mode 100644 index 00000000000..1ab7ee3c733 --- /dev/null +++ b/server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts @@ -0,0 +1,140 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, + companies, + createDb, + environmentLeases, + environments, + heartbeatRunEvents, + heartbeatRuns, + issues, + nativeRunFinalizations, + plugins, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() })); +vi.mock("../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient })); + +import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js"; +import { configureAgentLifecycle, createAgentLifecycle } from "../services/agent-lifecycle.js"; +import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "../services/native-local-process-stop.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; + +describeEmbeddedPostgres("terminating an agent whose failed run has a scheduled bootstrap retry", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + const workers: Array<{ stop(): Promise }> = []; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-terminate-pending-retry-"); + db = createDb(tempDb.connectionString); + }, 30_000); + + afterEach(async () => { + for (const worker of workers.splice(0)) await worker.stop(); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + async function seed(issueStatus: "in_progress" | "cancelled") { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const environmentId = randomUUID(), leaseId = randomUUID(), pluginId = randomUUID(); + const providerLeaseId = `sandbox-${randomUUID()}`; + const pluginKey = `paperclip.pending-retry-${pluginId.slice(0, 8)}`; + await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@paperclipai/plugin-fake-sandbox", version: "1.0.0", + apiVersion: 1, categories: ["automation"], status: "ready", installOrder: 1, updatedAt: new Date(), + manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fake sandbox", description: "Test provider", + author: "Paperclip", categories: ["automation"], capabilities: ["environment.drivers.register"], + entrypoints: { worker: "dist/worker.js" }, + environmentDrivers: [{ driverKey: "fake-plugin", kind: "sandbox_provider", displayName: "Fake Plugin", + configSchema: { type: "object" } }] } } as never); + await db.insert(companies).values({ id: companyId, name: "Paperclip", + issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false }); + await db.insert(agents).values({ id: agentId, companyId, name: "OpenCoder", role: "engineer", status: "idle", + adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" }, runtimeConfig: {}, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, title: "Short task", status: issueStatus, + priority: "medium", assigneeAgentId: agentId }); + const config = { provider: "fake-plugin", image: "fake:test", timeoutMs: 1234, reuseLease: false }; + await db.insert(environments).values({ id: environmentId, name: `Fake sandbox ${environmentId}`, driver: "sandbox", + status: "active", config }); + const failedAt = new Date(Date.now() - 5_000); + const retryAt = new Date(Date.now() + 17 * 60_000); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", status: "failed", + runtimeMode: "native", runtimeModeResolvedAt: failedAt, issueId, nativeIssueId: issueId, startedAt: failedAt, + finishedAt: failedAt, errorCode: "native_runner_process_exited", error: "The runner process exited", + contextSnapshot: { issueId }, nextEventSeq: 3, nativePhase: "retryable_failure", + resultJson: { executionRecovery: { kind: "bootstrap", recoverable: true, recoveryMode: "bootstrap_retry", + nextAttemptAt: retryAt.toISOString() } }, + runnerProfileJson: { nativeWorkspaceSync: { + schema: "paperclip.native-workspace-sync/v3", state: "prepared", descriptorSha256: "a".repeat(64), + baselineSha256: "b".repeat(64), finalHostSha256: null, workspaceId: randomUUID(), leaseId, providerLeaseId, + remoteCwd: "/workspace", resourceDisposition: "destroy" } } }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "retryable_failure", attempt: 1, + controllerGeneration: 1, failureCode: "native_runner_process_exited", recoveryState: "scheduled", nextAttemptAt: retryAt }); + await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId, + status: "active", leasePolicy: "ephemeral", provider: "fake-plugin", providerLeaseId, + metadata: { ...config, agentId, driver: "sandbox", pluginId, pluginKey, sandboxProviderPlugin: true, + remoteCwd: "/workspace", sandboxState: "started" } }); + for (const [index, eventType] of [PROCESS_START_REQUESTED, PROCESS_IDENTITY_RECORDED].entries()) { + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: index + 1, eventType, + stream: "system", level: "info", message: eventType }); + } + const call = vi.fn(async (_pluginId: string, method: string, params: { providerLeaseId?: string }) => { + if (method === "environmentStopLease") return { providerLeaseId: params.providerLeaseId, state: "stopped" }; + if (method === "environmentDestroyLease" || method === "environmentReleaseLease") { + return { providerLeaseId: params.providerLeaseId, state: "destroyed" }; + } + throw new Error(`Unexpected provider method ${method}`); + }); + const manager = { + isRunning: vi.fn((id: string) => id === pluginId), + getWorker: vi.fn(() => ({ supportedMethods: ["environmentReleaseLease", "environmentDestroyLease", "environmentStopLease"] })), + call, + } as unknown as PluginWorkerManager; + return { companyId, agentId, issueId, runId, leaseId, providerLeaseId, manager, call }; + } + + it.each([ + ["in_progress", "in_progress"], + ["cancelled", "cancelled"], + ] as const)("cancels the pending retry and releases its sandbox at once (task %s)", async (issueStatus, finalStatus) => { + const fixture = await seed(issueStatus); + const lifecycle = createAgentLifecycle(db); + const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager)); + workers.push(worker); + const startedAt = Date.now(); + await lifecycle.pauseAgent(fixture.agentId); + await worker.process(fixture.agentId); + await lifecycle.terminateAgent(fixture.agentId); + await worker.process(fixture.agentId); + const agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + expect(agent.lifecycleState).toBe("terminated"); + expect(Date.now() - startedAt).toBeLessThan(15_000); + + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run!.status).toBe("cancelled"); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(coordinator).toMatchObject({ phase: "terminal_failure", nextAttemptAt: null, leaseOwner: null }); + + const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, fixture.leaseId)); + expect(lease!.status).not.toBe("active"); + expect(lease!.releasedAt).not.toBeNull(); + expect(fixture.call).toHaveBeenCalledWith(expect.any(String), expect.stringMatching(/^environment(Stop|Destroy|Release)Lease$/), + expect.objectContaining({ providerLeaseId: fixture.providerLeaseId }), expect.any(Number)); + + expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, fixture.companyId), + eq(heartbeatRuns.retryOfRunId, fixture.runId)))).toHaveLength(0); + const [task] = await db.select().from(issues).where(eq(issues.id, fixture.issueId)); + expect(task!.status).toBe(finalStatus); + expect(run!.resultJson).toMatchObject({ pauseStop: { holds: ["manual"] }, + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [fixture.leaseId] } }); + }, 60_000); +}); diff --git a/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts b/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts index da514753201..96d31c984af 100644 --- a/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts @@ -1,8 +1,8 @@ import type { Db } from "@paperclipai/db"; import { describe, expect, it, vi } from "vitest"; -const stop = vi.hoisted(() => vi.fn(async () => true)); -vi.mock("../../../services/heartbeat.js", () => ({ heartbeatService: () => ({ stopInvocationsForAgents: stop }) })); +const stop = vi.hoisted(() => vi.fn(async () => null)); +vi.mock("../../../services/heartbeat.js", () => ({ heartbeatService: () => ({ agentInvocationStopBlocker: stop }) })); vi.mock("../../../services/agent-harness-verification.js", () => ({ agentHarnessVerificationService: () => ({ verify: vi.fn() }) })); import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js"; diff --git a/server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts b/server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts new file mode 100644 index 00000000000..ea7da2eae97 --- /dev/null +++ b/server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts @@ -0,0 +1,86 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, companies, createDb, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { configureAgentLifecycle, createAgentLifecycle } from "../../../services/agent-lifecycle.js"; +import { lifecyclePendingRetryDelayMs } from "../adapters/postgres.js"; +import { wakeStoppingAgentLifecycle } from "../../../services/environment-lease-release-deferral.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +(support.supported ? describe : describe.skip)("lifecycle host step that stays pending", () => { + let database: Awaited> | undefined; + let db: Db; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-lifecycle-pending-backoff-"); + db = createDb(database.connectionString); + }, 60_000); + + afterAll(async () => { + await database?.cleanup(); + }); + + it("records why termination is waiting and spaces out its passes", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Lifecycle", issuePrefix: `P${companyId.slice(0, 7)}` }); + const [agent] = await db.insert(agents).values({ companyId, name: "Stuck", role: "engineer", status: "idle", + adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }).returning(); + let hostCalls = 0; + const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", + runHost: async () => { hostCalls += 1; return { pending: "environment_lease_unreleased" }; } }); + try { + await createAgentLifecycle(db).terminateAgent(agent!.id); + const delays: number[] = []; + for (let pass = 1; pass <= 7; pass++) { + const before = Date.now(); + await worker.process(agent!.id); + await worker.process(agent!.id); + const [current] = await db.select().from(agents).where(eq(agents.id, agent!.id)); + expect(current!.lifecycleState).toBe("terminating"); + expect(current!.lifecycleOperation).toMatchObject({ pendingReason: "environment_lease_unreleased", pendingPasses: pass }); + delays.push(Date.parse(current!.lifecycleOperation!.retryAt!) - before); + await db.update(agents).set({ lifecycleOperation: { ...current!.lifecycleOperation!, retryAt: new Date(0).toISOString() } }) + .where(eq(agents.id, agent!.id)); + } + expect(hostCalls).toBe(7); + for (const [index, delay] of delays.entries()) { + expect(delay).toBeGreaterThanOrEqual(lifecyclePendingRetryDelayMs(index + 1) - 1_000); + } + expect(delays.at(-1)).toBeGreaterThanOrEqual(60_000 - 1_000); + expect(delays.at(-1)).toBeLessThanOrEqual(60_000 + 1_000); + expect(lifecyclePendingRetryDelayMs(11)).toBe(60_000); + expect(lifecyclePendingRetryDelayMs(500)).toBe(60_000); + } finally { + await worker.stop(); + } + }, 60_000); + + it("finishes a stop at once when its blocker clears, without waiting out the backoff", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Lifecycle", issuePrefix: `W${companyId.slice(0, 7)}` }); + const [agent] = await db.insert(agents).values({ companyId, name: "Waiting", role: "engineer", status: "idle", + adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }).returning(); + let blocked = true; + const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", + runHost: async () => blocked ? { pending: "environment_lease_unreleased" } : "complete" }); + try { + await createAgentLifecycle(db).terminateAgent(agent!.id); + for (let pass = 1; pass <= 11; pass++) { + await worker.process(agent!.id); + const [current] = await db.select().from(agents).where(eq(agents.id, agent!.id)); + if (pass < 11) await db.update(agents).set({ lifecycleOperation: { ...current!.lifecycleOperation!, + retryAt: new Date(0).toISOString() } }).where(eq(agents.id, agent!.id)); + } + const [waiting] = await db.select().from(agents).where(eq(agents.id, agent!.id)); + expect(Date.parse(waiting!.lifecycleOperation!.retryAt!)).toBeGreaterThan(Date.now() + 30_000); + blocked = false; + expect(await db.transaction(tx => wakeStoppingAgentLifecycle(tx as unknown as Db, agent!.id))).toBe(true); + await worker.process(agent!.id); + expect((await db.select().from(agents).where(eq(agents.id, agent!.id)))[0]!.lifecycleState).toBe("terminated"); + } finally { + await worker.stop(); + } + }, 60_000); +}); diff --git a/server/src/modules/agent-lifecycle/adapters/postgres.ts b/server/src/modules/agent-lifecycle/adapters/postgres.ts index 6378e51dd05..99871678dc5 100644 --- a/server/src/modules/agent-lifecycle/adapters/postgres.ts +++ b/server/src/modules/agent-lifecycle/adapters/postgres.ts @@ -11,6 +11,13 @@ export function assertRootDatabase(db: Db) { } type LifecycleRow = typeof agents.$inferSelect; + +const LIFECYCLE_PENDING_BASE_MS = 2_000; +const LIFECYCLE_PENDING_MAX_MS = 60_000; + +export function lifecyclePendingRetryDelayMs(passes: number) { + return Math.min(LIFECYCLE_PENDING_MAX_MS, LIFECYCLE_PENDING_BASE_MS * 2 ** Math.max(0, passes - 1)); +} type ChangeOptions = { version?: number; owner?: string; reason?: string }; // Prepared drafts wait for the wizard; they have no background verification obligation. @@ -83,6 +90,24 @@ export async function requestAgentLifecycleRecheckInTransaction( return true; } +export async function wakeStoppingAgentLifecycleInTransaction( + tx: Pick, + agentId: string, + notify: () => Promise, +): Promise { + if (!("nestedIndex" in tx)) throw new AgentLifecycleConflict("Lifecycle wakes require the producer transaction"); + const [agent] = await tx.select({ lifecycleState: agents.lifecycleState, lifecycleOperation: agents.lifecycleOperation }) + .from(agents).where(eq(agents.id, agentId)).for("update"); + const operation = agent?.lifecycleOperation; + if (!agent || !operation || !["pausing", "terminating", "cleaning_up"].includes(agent.lifecycleState) + || (!operation.retryAt && !operation.leaseOwner)) return false; + await notify(); + await tx.update(agents).set({ lifecycleOperation: sql`(${agents.lifecycleOperation} - 'retryAt') + || case when ${agents.lifecycleOperation} ? 'leaseOwner' then '{"recheckRequested":true}'::jsonb else '{}'::jsonb end` }) + .where(eq(agents.id, agentId)); + return true; +} + /** The caller owns the accounting transaction and has locked this agent. */ async function changeLockedAgent(tx: Db, effects: LifecycleEffects, agent: LifecycleRow, command: LifecycleCommand, options: ChangeOptions = {}, policyHolds?: string[], restartPause = false) { @@ -268,9 +293,12 @@ export function createLifecycleStore(db: Db, effects: LifecycleEffects): Lifecyc sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id }); return rows.length > 0; } + const previousPasses = (agent.lifecycleOperation as { pendingPasses?: unknown } | null)?.pendingPasses; + const pendingPasses = options?.pendingReason ? (typeof previousPasses === "number" ? previousPasses : 0) + 1 : undefined; const retry: Partial = options?.retryRequired && ["verifying", "resuming"].includes(agent.lifecycleState) ? { retryRequired: true } - : { retryAt: new Date(now.getTime() + (error ? 60_000 : 2_000)).toISOString() }; + : { retryAt: new Date(now.getTime() + (error ? 60_000 : pendingPasses ? lifecyclePendingRetryDelayMs(pendingPasses) : 2_000)).toISOString() }; + if (options?.pendingReason && pendingPasses) Object.assign(retry, { pendingReason: options.pendingReason, pendingPasses }); if (options?.verificationFailures !== undefined && agent.lifecycleState === "verifying") { retry.verificationFailures = options.verificationFailures; } diff --git a/server/src/modules/agent-lifecycle/application/ports.ts b/server/src/modules/agent-lifecycle/application/ports.ts index ade8e539011..a7e99599c30 100644 --- a/server/src/modules/agent-lifecycle/application/ports.ts +++ b/server/src/modules/agent-lifecycle/application/ports.ts @@ -20,14 +20,14 @@ export interface LifecycleStore { setRequiredPlugins(agent: LifecycleAgent, owner: string, pluginIds: string[]): Promise; completeHost(agent: LifecycleAgent, owner: string): Promise; completePlugin(agent: LifecycleAgent, owner: string, pluginId: string): Promise; - defer(agent: LifecycleAgent, owner: string, error: string | null, now: Date, options?: { retryRequired?: boolean; verificationFailures?: number; waitForSignal?: boolean }): Promise; + defer(agent: LifecycleAgent, owner: string, error: string | null, now: Date, options?: { retryRequired?: boolean; verificationFailures?: number; waitForSignal?: boolean; pendingReason?: string }): Promise; pending(limit: number, now: Date): Promise; } export interface LifecycleDriver { requiredPluginIds(agent: LifecycleAgent): Promise; /** waiting is only a healthy verifying phase owned by an external event. */ - runHost(agent: LifecycleAgent): Promise<"complete" | "pending" | "waiting">; + runHost(agent: LifecycleAgent): Promise<"complete" | "pending" | "waiting" | { pending: string }>; runPlugin(agent: LifecycleAgent, pluginId: string): Promise<"complete" | "pending">; /** Notify the scheduler only after readiness has committed. */ onReady?(agent: LifecycleAgent): Promise; diff --git a/server/src/modules/agent-lifecycle/application/worker.ts b/server/src/modules/agent-lifecycle/application/worker.ts index 5a83aec531e..b45f0564533 100644 --- a/server/src/modules/agent-lifecycle/application/worker.ts +++ b/server/src/modules/agent-lifecycle/application/worker.ts @@ -51,8 +51,9 @@ export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDr if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { waitForSignal: true }))) continue; return; } - if (host === "pending") { - if (!await runStep("defer", () => store.defer(agent, owner, null, new Date()))) continue; + if (host === "pending" || typeof host === "object") { + const pendingReason = typeof host === "object" ? host.pending : "host_step_pending"; + if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason }))) continue; return; } if (!await runStep("complete_host", () => store.completeHost(agent, owner))) continue; @@ -65,7 +66,7 @@ export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDr } if (!await runStep("renew", () => store.renew(agent, owner, new Date()))) continue phase; if (await runStep("plugin", () => driver.runPlugin(agent, pluginId), pluginId) === "pending") { - if (!await runStep("defer", () => store.defer(agent, owner, null, new Date()))) continue phase; + if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason: "plugin_step_pending" }))) continue phase; return; } if (!await runStep("complete_plugin", () => store.completePlugin(agent, owner, pluginId), pluginId)) continue phase; diff --git a/server/src/modules/agent-lifecycle/index.ts b/server/src/modules/agent-lifecycle/index.ts index a958e8e65b9..33c9d8f73ae 100644 --- a/server/src/modules/agent-lifecycle/index.ts +++ b/server/src/modules/agent-lifecycle/index.ts @@ -15,7 +15,7 @@ import { hasCompanyHoldMismatch, projectCompanyHolds } from "./adapters/company- import { createLifecycleWorker } from "./application/worker.js"; import type { LifecycleDriver } from "./application/ports.js"; -export { applyAgentPolicyHoldsInTransaction, releaseAgentLifecycleLeaseOfHolderInTransaction, requestAgentLifecycleRecheckInTransaction } from "./adapters/postgres.js"; +export { applyAgentPolicyHoldsInTransaction, releaseAgentLifecycleLeaseOfHolderInTransaction, requestAgentLifecycleRecheckInTransaction, wakeStoppingAgentLifecycleInTransaction } from "./adapters/postgres.js"; export { companyHoldMismatch, fenceActiveCompanyAgentStopsInTransaction } from "./adapters/company-policy.js"; export { AgentLifecycleConflict, canConfigureAgentConnection, isAgentAwaitingSetup, isAgentSetupDraft } from "./domain/policy.js"; diff --git a/server/src/services/agent-execution-stop.ts b/server/src/services/agent-execution-stop.ts index 92e9e5964bb..481b216e6d3 100644 --- a/server/src/services/agent-execution-stop.ts +++ b/server/src/services/agent-execution-stop.ts @@ -1,4 +1,5 @@ import { readProcessStartedAt } from "./hot-restart.js"; +import { readLeaseReleaseDeferral } from "./environment-lease-release-deferral.js"; import { runUsedConversationAdapter } from "./conversation-continuation.js"; import { and, eq, inArray, isNull, or, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db"; @@ -8,20 +9,26 @@ import { isCancelledNativeStartup } from "./cancelled-native-startup.js"; /** Cancellation changes admission. Process and lease evidence controls cleanup. */ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { - if (!agentIds.length) return true; + return (await agentExecutionStopBlocker(db, agentIds)) === null; +} + +export async function agentExecutionStopBlocker(db: Db, agentIds: string[]): Promise { + if (!agentIds.length) return null; const runs = await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds)); const runIds = db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds)); const leases = await db.select().from(environmentLeases).where(or( inArray(environmentLeases.heartbeatRunId, runIds), inArray(sql`${environmentLeases.metadata}->>'agentId'`, agentIds), )); - if (leases.some(lease => (!lease.releasedAt && !(lease.status === "retained" && lease.cleanupStatus === "success")) || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return false; + const deferred = leases.find(lease => lease.status === "active" && readLeaseReleaseDeferral(lease.metadata)); + if (deferred) return `environment_lease_release_deferred:${readLeaseReleaseDeferral(deferred.metadata)!.reason}`; + if (leases.some(lease => (!lease.releasedAt && !(lease.status === "retained" && lease.cleanupStatus === "success")) || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return "environment_lease_unreleased"; const coordinators = await db.select().from(nativeRunFinalizations) .where(inArray(nativeRunFinalizations.runId, runIds)); const now = new Date(); const abandoned = coordinators.filter(row => row.leaseOwner); if (abandoned.some(row => !row.leaseExpiresAt || row.leaseExpiresAt > now || row.resultId || - runs.find(run => run.id === row.runId)?.status !== "cancelled")) return false; + runs.find(run => run.id === row.runId)?.status !== "cancelled")) return "native_finalization_owned"; const absent = (pid: number) => { try { process.kill(pid, 0); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; } @@ -30,14 +37,14 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { if (!coordinator.controllerPid || absent(coordinator.controllerPid)) continue; const observed = await readProcessStartedAt(coordinator.controllerPid).catch(() => null); if (!observed || !coordinator.controllerProcessStartedAt || - new Date(observed).getTime() === coordinator.controllerProcessStartedAt.getTime()) return false; + new Date(observed).getTime() === coordinator.controllerProcessStartedAt.getTime()) return "native_controller_alive"; } for (const run of runs) { - if (!["succeeded", "failed", "cancelled", "timed_out", "interrupted"].includes(run.status)) return false; - if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return false; + if (!["succeeded", "failed", "cancelled", "timed_out", "interrupted"].includes(run.status)) return "run_not_terminal"; + if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return "run_controller_lease_held"; const runLeases = leases.filter(lease => lease.heartbeatRunId === run.id); if (runLeases.some(lease => lease.provider && lease.provider !== "local")) { - if (run.status === "cancelled" && !runLeases.every(hasRemoteTerminationReceipt)) return false; + if (run.status === "cancelled" && !runLeases.every(hasRemoteTerminationReceipt)) return "remote_stop_unconfirmed"; continue; } let processAlive = Boolean(run.processPid && !absent(run.processPid)); @@ -49,15 +56,15 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { if (run.processGroupId === run.processPid) groupAlive = false; } } - if (processAlive || groupAlive) return false; + if (processAlive || groupAlive) return "run_process_alive"; if (run.status !== "cancelled" || !run.startedAt) continue; if (run.runtimeMode === "native" && !run.processPid && !run.processGroupId && !await hasNativeLocalProcessStop(db, run.companyId, run.id) && - !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return false; + !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return "native_stop_unproven"; if (run.runtimeMode === "legacy" && !run.processPid && !run.processGroupId && (run.resultJson?.executionCancellation as Record | undefined)?.state !== "acknowledged" && !(run.executionStage === "settled" && !await runUsedConversationAdapter(db, run)) && - !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return false; + !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return "legacy_stop_unproven"; } // Release an expired owner only after its cancelled execution has stop proof. for (const coordinator of abandoned) { @@ -68,7 +75,7 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { eq(nativeRunFinalizations.controllerGeneration, coordinator.controllerGeneration), eq(nativeRunFinalizations.phase, coordinator.phase), isNull(nativeRunFinalizations.resultId))) .returning({ runId: nativeRunFinalizations.runId }); - if (!cleared) return false; + if (!cleared) return "native_finalization_release_raced"; } - return true; + return null; } diff --git a/server/src/services/agent-lifecycle-driver.ts b/server/src/services/agent-lifecycle-driver.ts index a74ff0c5115..8cbc3a2c272 100644 --- a/server/src/services/agent-lifecycle-driver.ts +++ b/server/src/services/agent-lifecycle-driver.ts @@ -1,4 +1,5 @@ -import { and, eq, inArray, sql } from "drizzle-orm"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { pendingFailedNativeRetryCancellationCondition } from "./native-runtime/native-cancellation-request.js"; import { CANCELLABLE_HEARTBEAT_RUN_STATUSES } from "./heartbeat/recovery.js"; import { promoteDeferredWorkIntents } from "./work-intent-outbox.js"; import { agents, companies, environments, heartbeatRuns, plugins, pluginCompanySettings, type Db } from "@paperclipai/db"; @@ -87,11 +88,13 @@ export function createLifecycleDriver(db: Db, manager: PluginWorkerManager): Lif await db.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${pauseStop}`, }).where(and(eq(heartbeatRuns.companyId, agent.companyId), eq(heartbeatRuns.agentId, agent.id), - inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), + or(inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), pendingFailedNativeRetryCancellationCondition()), sql`not (coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ? 'pauseStop')`)); } - if (!await heartbeat.stopInvocationsForAgents(ids, reason, - { preservePauseDeferred: agent.lifecycleState === "pausing" })) return "pending"; + const blocker = await heartbeat.agentInvocationStopBlocker(ids, reason, + { preservePauseDeferred: agent.lifecycleState === "pausing", + ...(agent.lifecycleOperation?.id ? { trigger: `lifecycle:${agent.lifecycleOperation.id}` } : {}) }); + if (blocker) return { pending: blocker }; } return "complete"; }, diff --git a/server/src/services/environment-lease-release-deferral.test.ts b/server/src/services/environment-lease-release-deferral.test.ts new file mode 100644 index 00000000000..1b867624f1b --- /dev/null +++ b/server/src/services/environment-lease-release-deferral.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from "vitest"; + +const boot = vi.hoisted(() => ({ id: "boot-a" })); +vi.mock("./controller-process-identity.js", async importOriginal => ({ + ...await importOriginal(), + currentControllerBootId: () => boot.id, +})); + +import { leaseReleaseRetryDueAt, nextLeaseReleaseBootIds, nextLeaseReleaseRetryAt, + type LeaseReleaseDeferral } from "./environment-lease-release-deferral.js"; + +describe("lease release retry across live server boots", () => { + function fail(previous: LeaseReleaseDeferral | null, now: number): LeaseReleaseDeferral { + const attempts = (previous?.attempts ?? 0) + 1; + return { reason: "release_failed", attempts, retryAt: nextLeaseReleaseRetryAt(previous, attempts, now), + failingSince: previous?.failingSince ?? new Date(now).toISOString(), attemptedByBootIds: nextLeaseReleaseBootIds(previous), + providerResourceDisposition: null }; + } + + function simulate(boots: string[]) { + const start = Date.parse("2026-11-15T12:00:00Z"); + boot.id = boots[0]!; + let deferral = fail(null, start); + let attempts = 1; + let latestRetryAt = Date.parse(deferral.retryAt); + for (let minute = 1; minute <= 60; minute++) { + const now = start + minute * 60_000; + for (const id of [...boots].reverse()) { + boot.id = id; + if (leaseReleaseRetryDueAt(deferral, now) > now) continue; + deferral = fail(deferral, now); + attempts += 1; + const retryAt = Date.parse(deferral.retryAt); + expect(retryAt).toBeGreaterThanOrEqual(latestRetryAt); + latestRetryAt = retryAt; + } + } + return { deferral, attempts }; + } + + it("keeps the saved retry time for every live boot after each has made its first attempt", () => { + const single = simulate(["boot-a"]); + const overlapping = simulate(["boot-a", "boot-b"]); + expect(overlapping.deferral.attemptedByBootIds).toEqual(["boot-a", "boot-b"]); + expect(overlapping.attempts).toBeLessThanOrEqual(single.attempts + 1); + }); + + it("gives a restarted server one immediate attempt and keeps the boot list bounded", () => { + const now = Date.parse("2026-11-15T12:00:00Z"); + let deferral: LeaseReleaseDeferral | null = null; + for (let index = 0; index < 15; index++) { + boot.id = `boot-${index}`; + deferral = fail(deferral, now); + } + expect(deferral!.attemptedByBootIds).toHaveLength(10); + boot.id = "boot-restarted"; + expect(leaseReleaseRetryDueAt(deferral!, now)).toBe(now); + boot.id = "boot-14"; + expect(leaseReleaseRetryDueAt(deferral!, now)).toBe(Date.parse(deferral!.retryAt)); + }); +}); diff --git a/server/src/services/environment-lease-release-deferral.ts b/server/src/services/environment-lease-release-deferral.ts new file mode 100644 index 00000000000..058b4510c89 --- /dev/null +++ b/server/src/services/environment-lease-release-deferral.ts @@ -0,0 +1,96 @@ +import { and, eq, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { currentControllerBootId } from "./controller-process-identity.js"; +import { wakeStoppingAgentLifecycleInTransaction } from "../modules/agent-lifecycle/index.js"; +import type { ProviderResourceDisposition } from "./environment-runtime.js"; +import { executionStartedEventPredicate } from "./pre-dispatch-execution-evidence.js"; + +export const LEASE_RELEASE_DEFERRAL_KEY = "releaseDeferral"; +const LEASE_RELEASE_RETRY_BASE_MS = 30_000; +const LEASE_RELEASE_RETRY_MAX_MS = 15 * 60_000; +export const LEASE_RELEASE_FAST_ATTEMPTS = 6; +export const LEASE_RELEASE_SLOW_RETRY_MS = 60 * 60_000; + +export type LeaseReleaseDeferral = { + reason: string; + attempts: number; + retryAt: string; + failingSince: string; + triggers?: string[]; + attemptedByBootIds?: string[]; + providerResourceDisposition: ProviderResourceDisposition | null; +}; + +const LEASE_RELEASE_TRIGGER_LIMIT = 20; + +const LEASE_RELEASE_BOOT_LIMIT = 10; + +export function leaseReleaseAttemptedByThisBoot(deferral: LeaseReleaseDeferral | null) { + return Boolean(deferral?.attemptedByBootIds?.includes(currentControllerBootId())); +} + +export function leaseReleaseRetryDueAt(deferral: LeaseReleaseDeferral, now = Date.now()) { + if (!leaseReleaseAttemptedByThisBoot(deferral)) return now; + const retryAt = Date.parse(deferral.retryAt); + return Number.isFinite(retryAt) ? retryAt : now; +} + +export function nextLeaseReleaseBootIds(previous: LeaseReleaseDeferral | null) { + const current = currentControllerBootId(); + const bootIds = (previous?.attemptedByBootIds ?? []).filter(bootId => bootId !== current); + return [...bootIds, current].slice(-LEASE_RELEASE_BOOT_LIMIT); +} + +export function nextLeaseReleaseRetryAt(previous: LeaseReleaseDeferral | null, attempts: number, now = Date.now()) { + const scheduled = now + leaseReleaseRetryDelayMs(attempts); + const saved = previous ? Date.parse(previous.retryAt) : Number.NaN; + return new Date(Number.isFinite(saved) && saved > scheduled ? saved : scheduled).toISOString(); +} + +export function nextLeaseReleaseTriggers(previous: LeaseReleaseDeferral | null, trigger: string | undefined) { + const triggers = [...(previous?.triggers ?? [])]; + if (trigger && !triggers.includes(trigger)) triggers.push(trigger); + return triggers.slice(-LEASE_RELEASE_TRIGGER_LIMIT); +} + +export function readLeaseReleaseDeferral(metadata: Record | null | undefined): LeaseReleaseDeferral | null { + const value = metadata?.[LEASE_RELEASE_DEFERRAL_KEY]; + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const deferral = value as Record; + if (typeof deferral.reason !== "string" || typeof deferral.retryAt !== "string" || typeof deferral.attempts !== "number") return null; + return deferral as LeaseReleaseDeferral; +} + +export function leaseReleaseRetryDelayMs(attempts: number) { + if (attempts > LEASE_RELEASE_FAST_ATTEMPTS) return LEASE_RELEASE_SLOW_RETRY_MS; + return Math.min(LEASE_RELEASE_RETRY_MAX_MS, LEASE_RELEASE_RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1)); +} + +export function wakeStoppingAgentLifecycle(tx: Db, agentId: string) { + return wakeStoppingAgentLifecycleInTransaction(tx, agentId, () => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle)); +} + +export async function settleUnchangedNativeWorkspace(db: Db, runId: string, companyId: string): Promise { + const settled = await db.update(heartbeatRuns).set({ + runnerProfileJson: sql`(${heartbeatRuns.runnerProfileJson} - 'nativeWorkspaceSync') + || jsonb_build_object('nativeWorkspaceSyncReleasedUnchanged', ${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync')`, + }).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.status, "cancelled"), + sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' = 'prepared'`, + sql`coalesce(${heartbeatRuns.runnerProfileJson}->'remoteWorkspace', 'null'::jsonb) = 'null'::jsonb`, + sql`not exists (select 1 from ${environmentLeases} where ${environmentLeases.companyId} = ${companyId} + and ${environmentLeases.heartbeatRunId} = ${runId} and (${environmentLeases.status} in ('active', 'pending_cleanup', 'retained') + or coalesce(${environmentLeases.metadata}, '{}'::jsonb) ? 'sandboxStopAndRetainReceipt'))`)) + .returning({ id: heartbeatRuns.id }); + return settled.length > 0; +} + +export async function nativeRunNeverLaunchedRunner(db: Db, runId: string, companyId: string): Promise { + const [run] = await db.select({ processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))); + if (!run || run.processPid || run.processGroupId) return false; + const [started] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, companyId), eq(heartbeatRunEvents.runId, runId), executionStartedEventPredicate(), + )).limit(1); + return !started; +} diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 4d66ec03d4a..3648d2c5770 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -81,7 +81,7 @@ import { formatIssueIdentifierLink, } from "./heartbeat/scheduling.js"; import { canApplyTaskWorkspaceSelectionAtAdmission, taskWorkspaceRuntimeSelectionEnabled } from "./execution-workspace-policy.js"; -import { agentExecutionsHaveStopped } from "./agent-execution-stop.js"; +import { agentExecutionStopBlocker } from "./agent-execution-stop.js"; import { cancelHeartbeatNativeRun, terminateHeartbeatRunProcess, @@ -4444,31 +4444,45 @@ export function heartbeatService( } } - async function stopInvocationsForAgents(agentIds: string[], reason: string, options: StopInvocationOptions = {}) { + async function agentInvocationStopBlocker(agentIds: string[], reason: string, options: StopInvocationOptions = {}) { await cancelInvocationsForAgentsInternal(agentIds, reason, options); const runs = await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds)); const leasesToRelease = await db.select({ runId: environmentLeases.heartbeatRunId }).from(environmentLeases) .innerJoin(heartbeatRuns, eq(heartbeatRuns.id, environmentLeases.heartbeatRunId)) .where(and(inArray(heartbeatRuns.agentId, agentIds), or(and(eq(heartbeatRuns.status, "cancelled"), inArray(environmentLeases.status, ["active", "pending_cleanup"])), - and(eq(environmentLeases.status, "retained"), eq(environmentLeases.cleanupStatus, "failed"))))); + and(eq(environmentLeases.status, "retained"), eq(environmentLeases.cleanupStatus, "failed"))), + sql`not (coalesce((${environmentLeases.metadata}->'releaseDeferral'->>'retryAt')::timestamptz > now(), false) + and (${options.trigger ?? null}::text is null + or coalesce(${environmentLeases.metadata}->'releaseDeferral'->'triggers', '[]'::jsonb) ? ${options.trigger ?? ""}::text))`)); const needsRelease = new Set(leasesToRelease.map(lease => lease.runId)); + let blocker: string | null = null; for (const run of runs) { - if (!isHeartbeatRunTerminalStatus(run.status) || liveRunExecutions.has(run.id) || - adapterExecutionControls.has(run.id) || processRunCancellationSettlements.has(run.id) || - (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date())) return false; + const runBlocker = !isHeartbeatRunTerminalStatus(run.status) ? "run_not_terminal" + : liveRunExecutions.has(run.id) || adapterExecutionControls.has(run.id) || processRunCancellationSettlements.has(run.id) + ? "run_executing_here" + : run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date() ? "run_controller_lease_held" : null; + if (runBlocker) { + blocker ??= runBlocker; + continue; + } if (needsRelease.has(run.id)) { - // Retry incomplete cleanup after a run becomes terminal. await releaseEnvironmentLeasesForRun({ runId: run.id, companyId: run.companyId, - agentId: run.agentId, status: run.status, providerResourceDisposition: "destroy" }); + agentId: run.agentId, status: run.status, providerResourceDisposition: "destroy", + ...(options.trigger ? { trigger: options.trigger } : {}) }); } } - return agentExecutionsHaveStopped(db, agentIds); + return blocker ?? agentExecutionStopBlocker(db, agentIds); + } + + async function stopInvocationsForAgents(agentIds: string[], reason: string, options: StopInvocationOptions = {}) { + return (await agentInvocationStopBlocker(agentIds, reason, options)) === null; } return { recoverLegacyAccountingReceipt, stopInvocationsForAgents, + agentInvocationStopBlocker, waitForRunExecutionDrain: async ( runId: string, options: { timeoutMs?: number; intervalMs?: number } = {}, diff --git a/server/src/services/heartbeat/live-recovery-work.ts b/server/src/services/heartbeat/live-recovery-work.ts index 07bc8d14950..c5698decb97 100644 --- a/server/src/services/heartbeat/live-recovery-work.ts +++ b/server/src/services/heartbeat/live-recovery-work.ts @@ -7,6 +7,12 @@ import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator import { DELIVERY_QUEUES, type DeliveryQueue } from "../delivery-work-notifications.js"; import type { LiveResourceRecoveryScope, LiveRunRecoveryScope } from "../live-run-recovery-notifications.js"; import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; +import { leaseReleaseRetryDueAt, readLeaseReleaseDeferral } from "../environment-lease-release-deferral.js"; + +function leaseDueAt(metadata: Record | null) { + const deferral = readLeaseReleaseDeferral(metadata); + return deferral ? leaseReleaseRetryDueAt(deferral) : 0; +} const TERMINAL = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"]; const SETTLED_PENDING_BASE_DELAY_MS = 30_000; @@ -64,7 +70,8 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType)?.deadlineAt)) || Date.now(), })); } else if (kind === "settled") { diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 186f855e7e7..1d595baf587 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -2,6 +2,7 @@ import { settleOwnableKind } from "../recovery/ownership-invariant-report.js"; import { isRunHandedOffForShutdown, markRunHandedOffForShutdown } from "./shutdown-handoff.js"; import { ORPHANED_RUN_LEASE_FAILURE_REASON } from "../environment-run-lease-settlement.js"; import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "../environment-lease-controller.js"; +import { leaseReleaseRetryDueAt, readLeaseReleaseDeferral } from "../environment-lease-release-deferral.js"; import { readNativeStartupCleanup, readNativeStartupContext } from "../native-runtime/native-startup-cleanup.js"; import { legacyWorkspaceRecoveryNotMigrated } from "../legacy-workspace-recovery-migration.js"; import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js"; @@ -1676,6 +1677,40 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD ); } + async function retryTerminalRunLeaseRelease(lease: typeof environmentLeases.$inferSelect, + localRuns: { has(runId: string): boolean }, onDeferredDeadline?: (at: number) => void): Promise { + if (!lease.heartbeatRunId || localRuns.has(lease.heartbeatRunId)) return false; + const deferral = readLeaseReleaseDeferral(lease.metadata); + const dueAt = deferral ? leaseReleaseRetryDueAt(deferral) : Number.NaN; + if (deferral && dueAt > Date.now()) { + onDeferredDeadline?.(dueAt); + return false; + } + const [run] = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + status: heartbeatRuns.status, error: heartbeatRuns.error, runtimeMode: heartbeatRuns.runtimeMode, + controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.id, lease.heartbeatRunId), eq(heartbeatRuns.companyId, lease.companyId))); + if (!run || !HEARTBEAT_RUN_TERMINAL_STATUSES.some(status => status === run.status)) return false; + if (!deferral && !(run.runtimeMode === "native" && run.status === "cancelled")) return false; + const [owner] = await db.select({ leaseOwner: nativeRunFinalizations.leaseOwner, leaseExpiresAt: nativeRunFinalizations.leaseExpiresAt }) + .from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.runId, run.id), eq(nativeRunFinalizations.companyId, run.companyId))); + const heldUntil = Math.max(run.controllerLeaseExpiresAt?.getTime() ?? 0, + owner?.leaseOwner ? owner.leaseExpiresAt?.getTime() ?? 0 : 0); + if (heldUntil > Date.now()) { + onDeferredDeadline?.(heldUntil); + return false; + } + await releaseEnvironmentLeasesForRun({ runId: run.id, companyId: run.companyId, agentId: run.agentId, + status: run.status, failureReason: run.error ?? undefined, + providerResourceDisposition: deferral ? deferral.providerResourceDisposition ?? undefined : "destroy" }); + const [after] = await db.select({ status: environmentLeases.status, metadata: environmentLeases.metadata }) + .from(environmentLeases).where(eq(environmentLeases.id, lease.id)); + if (after?.status !== "active") return true; + const next = readLeaseReleaseDeferral(after.metadata); + if (next) onDeferredDeadline?.(Date.parse(next.retryAt)); + return false; + } + // A run's active lease outlives a crash between the terminal run write and // the lease release, or a release that skipped the lease (for example when // its environment row is gone). No production query finds such a lease by @@ -1730,6 +1765,9 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD && await nativeWorkspaceExportPendingForLease(db, lease) && await preserveOrphanedNativeWorkspace(db, lease, { onDeferredDeadline: opts.onDeferredDeadline })) recovered += 1; } + for (const { lease } of scoped) { + if (await retryTerminalRunLeaseRelease(lease, localRuns, opts.onDeferredDeadline)) recovered += 1; + } const runIds = [...new Set(scoped.flatMap(({ lease }) => lease.heartbeatRunId ? [lease.heartbeatRunId] : []))]; if (runIds.length > 0) { diff --git a/server/src/services/heartbeat/run-control.test.ts b/server/src/services/heartbeat/run-control.test.ts index 81955fcd065..bfbaff21d1f 100644 --- a/server/src/services/heartbeat/run-control.test.ts +++ b/server/src/services/heartbeat/run-control.test.ts @@ -30,6 +30,8 @@ import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js"; import { acknowledgedNativeApiStopExecutionHasStopped } from "../acknowledged-native-stop.js"; import { nativeSha256 } from "../native-runtime/canonical.js"; import { callbacks, runControlPostgresSupport, setupRunControlDatabase } from "./__tests__/run-control-fixtures.js"; +import { LEASE_RELEASE_FAST_ATTEMPTS, LEASE_RELEASE_SLOW_RETRY_MS } from "../environment-lease-release-deferral.js"; +import { agentExecutionStopBlocker } from "../agent-execution-stop.js"; vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() })); vi.mock("../acknowledged-native-stop.js", async (importOriginal) => { @@ -125,7 +127,7 @@ describe("heartbeat run-control module boundary", () => { expect(database.access).not.toHaveBeenCalled(); }); - it("defers destruction when a warm session remains busy", async () => { + it("defers destruction and records a retry when a warm session remains busy", async () => { const database = guardedDatabase(); const deps = callbacks(database.db); deps.getRunCleanupState.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run); @@ -133,7 +135,7 @@ describe("heartbeat run-control module boundary", () => { await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "busy", companyId: "company", agentId: "agent", status: "failed", providerResourceDisposition: "destroy" }); expect(deps.options.closeWarmNativeSessionsForRun).toHaveBeenCalledWith({ runId: "busy", reason: "terminal heartbeat run destroyed its environment lease" }); expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled(); - expect(database.access).not.toHaveBeenCalled(); + expect(database.access).toHaveBeenCalledWith(expect.anything(), "select", expect.anything()); }); }); @@ -869,6 +871,8 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId, issueId: issue.id, provider: "daytona", providerLeaseId, status: "active", leasePolicy, metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } }); + await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, seq: 1, + eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); const deps = callbacks(db), control = createHeartbeatRunControl(db, deps); let ready!: () => void, release!: () => void; const acquired = new Promise(resolve => { ready = resolve; }); @@ -883,7 +887,8 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat status: "cancelled", providerResourceDisposition: "stop_and_retain" }); expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled(); expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]) - .toMatchObject({ status: "active", leasePolicy }); + .toMatchObject({ status: "active", leasePolicy, metadata: expect.objectContaining({ releaseDeferral: expect.objectContaining({ + reason: "workspace_retention_busy", attempts: 1, providerResourceDisposition: "stop_and_retain" }) }) }); } finally { release(); await holding; } await preserveCancelledNativeWorkspaces(db); expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]) @@ -898,6 +903,109 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0].status).toBe("in_progress"); }, 15_000); + async function deferralFixture(runtimeMode: "legacy" | "native") { + const { company, agent } = await fixture(); + const runId = randomUUID(), leaseId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id, runtimeMode, + status: "cancelled", finishedAt: new Date() }); + await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId, + provider: "daytona", providerLeaseId: randomUUID(), status: "active", leasePolicy: "ephemeral", + metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true } }); + if (runtimeMode === "native") await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, + seq: 1, eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); + const deferral = async () => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]! + .metadata?.releaseDeferral as { reason: string; attempts: number; retryAt: string; providerResourceDisposition: string | null }; + return { company, agent, runId, deferral }; + } + + it("records a failed release with its disposition and a growing retry time", async () => { + const { company, agent, runId, deferral } = await deferralFixture("legacy"); + const deps = callbacks(db); + vi.mocked(deps.envOrchestrator.releaseForRun).mockResolvedValue({ released: [], errors: [{ leaseId: "*", error: new Error("provider down") }] }); + const control = createHeartbeatRunControl(db, deps); + const before = Date.now(); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + const first = await deferral(); + expect(first).toMatchObject({ reason: "release_failed", attempts: 1, providerResourceDisposition: null }); + expect(Date.parse(first.retryAt) - before).toBeGreaterThanOrEqual(30_000); + expect(Date.parse(first.retryAt) - before).toBeLessThan(40_000); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + const second = await deferral(); + expect(second).toMatchObject({ reason: "release_failed", attempts: 2 }); + expect(Date.parse(second.retryAt) - before).toBeGreaterThanOrEqual(60_000); + }); + + it("never gives up on a failing release: hourly retries after the fast backoff, then release and wake the stopping agent", async () => { + const { company, agent, runId, deferral } = await deferralFixture("legacy"); + const leaseId = (await db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, runId)))[0]!.id; + await db.update(agents).set({ lifecycleState: "terminating", lifecycleOperation: { id: randomUUID(), hostComplete: false, + completedPluginIds: [], attempts: 3, retryAt: new Date(Date.now() + 60_000).toISOString() } }).where(eq(agents.id, agent.id)); + const deps = callbacks(db); + let outageCalls = 0; + vi.mocked(deps.envOrchestrator.releaseForRun).mockImplementation(async () => { + outageCalls += 1; + return { released: [], errors: [{ leaseId: "*", error: new Error("provider down") }] }; + }); + const control = createHeartbeatRunControl(db, deps); + const fastSteps = LEASE_RELEASE_FAST_ATTEMPTS; + const dueRetriesInThreeHours = fastSteps + 3; + let firstFailure: string | undefined; + for (let attempt = 1; attempt <= dueRetriesInThreeHours; attempt++) { + const before = Date.now(); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + const current = await deferral() as Record & { retryAt: string }; + firstFailure ??= current.failingSince as string; + expect(current).toMatchObject({ reason: "release_failed", attempts: attempt, failingSince: firstFailure }); + const delay = Date.parse(current.retryAt) - before; + if (attempt > fastSteps) expect(delay).toBeGreaterThanOrEqual(LEASE_RELEASE_SLOW_RETRY_MS - 1_000); + else expect(delay).toBeLessThanOrEqual(15 * 60_000 + 1_000); + } + expect(outageCalls).toBe(dueRetriesInThreeHours); + expect(await agentExecutionStopBlocker(db, [agent.id])).toBe("environment_lease_release_deferred:release_failed"); + vi.mocked(deps.envOrchestrator.releaseForRun).mockImplementation(async () => { + await db.update(environmentLeases).set({ status: "expired", releasedAt: new Date(), cleanupStatus: "success" }) + .where(eq(environmentLeases.id, leaseId)); + return { released: [{} as never], errors: [] }; + }); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]!.status).toBe("expired"); + expect((await db.select().from(agents).where(eq(agents.id, agent.id)))[0]!.lifecycleOperation).not.toHaveProperty("retryAt"); + }); + + it("records a destroy held back by a busy warm session", async () => { + const { company, agent, runId, deferral } = await deferralFixture("native"); + const deps = callbacks(db); + deps.options.closeWarmNativeSessionsForRun.mockResolvedValue({ closed: 0, busy: 1, failed: 0 }); + await createHeartbeatRunControl(db, deps).releaseEnvironmentLeasesForRun({ runId, companyId: company.id, + agentId: agent.id, status: "cancelled", providerResourceDisposition: "destroy" }); + expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled(); + expect(await deferral()).toMatchObject({ reason: "warm_session_busy", attempts: 1, providerResourceDisposition: "destroy" }); + }); + + it("stops and retains a launched cancelled run's sandbox when no file retention is owed", async () => { + const { company, agent } = await fixture(); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Stopped task", + status: "in_progress", assigneeAgentId: agent.id }).returning(); + const runId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id, + issueId: issue.id, nativeIssueId: issue.id, runtimeMode: "native", status: "cancelled", finishedAt: new Date(), + runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared", + descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null, + workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } } }); + await db.insert(nativeRunFinalizations).values({ runId, companyId: company.id, issueId: issue.id, + phase: "terminal_failure", failureCode: "native_retry_cancelled" }); + await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId, + issueId: null, provider: "daytona", providerLeaseId, status: "active", leasePolicy: "ephemeral", + metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } }); + await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, seq: 1, + eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); + const deps = callbacks(db); + await createHeartbeatRunControl(db, deps).releaseEnvironmentLeasesForRun({ runId, companyId: company.id, + agentId: agent.id, status: "cancelled", providerResourceDisposition: "destroy" }); + expect(deps.envOrchestrator.releaseForRun).toHaveBeenCalledWith(expect.objectContaining({ + heartbeatRunId: runId, providerResourceDisposition: "stop_and_retain" })); + }); + it("reports a missing run without entering cancellation", async () => { const deps = callbacks(db); await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(randomUUID())).rejects.toThrow("Heartbeat run not found"); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index ccc2a21b872..3b26f4f01cc 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -7,6 +7,10 @@ import { notifyChatInboundWakeNotices } from "../chat-inbound-wake-notice-notifi import { resumeDeferredChatWake } from "../durable-chat-wakeup.js"; import { notifyEnvironmentCleanup } from "../environment-cleanup-notifications.js"; import { readNativeStopExecutionEvidence } from "./native-stop-evidence-read.js"; +import { LEASE_RELEASE_DEFERRAL_KEY, nativeRunNeverLaunchedRunner, readLeaseReleaseDeferral, + settleUnchangedNativeWorkspace, wakeStoppingAgentLifecycle, nextLeaseReleaseTriggers, nextLeaseReleaseBootIds, nextLeaseReleaseRetryAt, + type LeaseReleaseDeferral } from "../environment-lease-release-deferral.js"; +import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js"; import { readTaskRetryIntent, reconcileTaskChatRetryReceipts } from "../task-retry.js"; import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, readNativeLocalProcessStop, recordedLocalExecutionStopped } from "../native-local-process-stop.js"; import { isHeartbeatRunTerminalStatus } from "./run-lifecycle.js"; @@ -20,8 +24,9 @@ import { type WakeupOptions, } from "./run-preparation.js"; import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js"; -import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; +import { nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; import { preserveNativeFailedWorkspace } from "../native-runtime/native-failed-workspace-recovery.js"; +import { NativeWorkspaceFinalizationBusyError } from "../native-runtime/native-workspace-finalization-ownership.js"; import { readNativeWorkspaceSyncReference } from "../native-runtime/native-workspace-sync.js"; import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; import { @@ -182,7 +187,7 @@ async function withBudgetStopDelivery(db: Db, work: () => Promise): Promis /** `preservePauseDeferred`: the stop comes from a pause, which keeps the * messages it deferred for delivery once the pause lifts. */ -export type StopInvocationOptions = { preservePauseDeferred?: boolean }; +export type StopInvocationOptions = { preservePauseDeferred?: boolean; trigger?: string }; /** Cancellation shares executor ownership and delegates lifecycle and admission effects. */ @@ -382,6 +387,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont failureReason?: string | null; providerResourceDisposition?: ProviderResourceDisposition; respectCleanupDeadlines?: boolean; + trigger?: string; nativeLifecycleTelemetry?: { provider: string; harness: string; @@ -402,21 +408,34 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont input.providerResourceDisposition, status, ); + let neverLaunched: boolean | undefined; + const runnerNeverLaunched = async () => neverLaunched ??= leaseOwnerRun?.runtimeMode === "native" + && isHeartbeatRunTerminalStatus(status) && await nativeRunNeverLaunchedRunner(db, input.runId, input.companyId); + const defer = (reason: string) => deferEnvironmentLeaseRelease(input, reason, providerResourceDisposition); if (cancelledRun?.runtimeMode === "native" && status === "cancelled" && readNativeWorkspaceSyncReference(cancelledRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared" - && !nativeRunHasNoWorkspaceAccess(cancelledRun)) { - try { - const preserved = await preserveNativeFailedWorkspace(db, cancelledRun, { allowPreterminal: true }); - if (!preserved || !hasRequiredWorkspaceRecovery(preserved.resultJson)) return; - } catch { + && !nativeRunHasNoWorkspaceAccess(cancelledRun) && !await runnerNeverLaunched()) { + let deferral: string | null = null; + for (let attempt = 0; attempt < 2; attempt++) { + try { + await preserveNativeFailedWorkspace(db, cancelledRun, { allowPreterminal: true }); + deferral = null; + break; + } catch (error) { + const busy = error instanceof NativeWorkspaceFinalizationBusyError; + deferral = busy ? "workspace_owner_active" : "workspace_retention_busy"; + if (!busy || attempt > 0 || !await clearExpiredNativeFinalizationOwner(input.runId, input.companyId)) break; + } + } + if (deferral) { // Keep the active source eligible for the bounded retention sweep. // Teardown must not release it after retention lost a lock or DB write. logger.warn({ runId: input.runId }, "Deferred cancelled workspace teardown until file retention is recorded"); - return; + return await defer(deferral); } providerResourceDisposition = "stop_and_retain"; } - if (providerResourceDisposition === "destroy") { + if (providerResourceDisposition === "destroy" && !await runnerNeverLaunched()) { const closeResult = await ( options.closeWarmNativeSessionsForRun ?? (async ({ runId, reason }) => { @@ -476,7 +495,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont { runId: input.runId, warmNativeSessions: closeResult }, "deferred environment lease destruction until warm native sessions close", ); - return; + return await defer(closeResult.busy > 0 ? "warm_session_busy" : "warm_session_close_failed"); } } const releaseResult = await envOrchestrator @@ -507,9 +526,71 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont "failed to release environment lease for heartbeat run", ); } + if (isHeartbeatRunTerminalStatus(status) && (!releaseResult || releaseResult.errors.length > 0)) await defer("release_failed"); + else if (isHeartbeatRunTerminalStatus(status) && leaseOwnerRun?.runtimeMode === "native") await defer("release_skipped"); + if (cancelledRun && neverLaunched + && readNativeWorkspaceSyncReference(cancelledRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared") { + await settleUnchangedNativeWorkspace(db, input.runId, input.companyId).catch(() => { + logger.warn({ runId: input.runId }, "could not record that a stopped run left no files to recover"); + }); + } + if (isHeartbeatRunTerminalStatus(status) && releaseResult?.released.length) await wakeAgentAfterRunLeasesSettled(input).catch(() => { + logger.warn({ runId: input.runId }, "could not wake the agent's stop after its run leases settled"); + }); await acknowledgeRemoteStop(input.runId, input.companyId); } + async function wakeAgentAfterRunLeasesSettled(input: { runId: string; companyId: string; agentId: string }) { + const [unsettled] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( + eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, input.runId), + inArray(environmentLeases.status, ["active", "pending_cleanup"]))).limit(1); + if (!unsettled) await db.transaction(tx => wakeStoppingAgentLifecycle(tx as unknown as Db, input.agentId)); + } + + async function clearExpiredNativeFinalizationOwner(runId: string, companyId: string) { + const cleared = await db.update(nativeRunFinalizations).set({ leaseOwner: null, leaseExpiresAt: null, updatedAt: new Date() }) + .where(and(eq(nativeRunFinalizations.runId, runId), eq(nativeRunFinalizations.companyId, companyId), + isNotNull(nativeRunFinalizations.leaseOwner), lte(nativeRunFinalizations.leaseExpiresAt, new Date()), + isNull(nativeRunFinalizations.resultId), + sql`exists (select 1 from ${heartbeatRuns} where ${heartbeatRuns.id} = ${runId} + and ${heartbeatRuns.companyId} = ${companyId} and ${heartbeatRuns.status} = 'cancelled')`)) + .returning({ runId: nativeRunFinalizations.runId }); + return cleared.length > 0; + } + + async function deferEnvironmentLeaseRelease(input: { runId: string; companyId: string; trigger?: string }, reason: string, + providerResourceDisposition: ProviderResourceDisposition | undefined) { + const leases = await Promise.resolve().then(() => db.select({ id: environmentLeases.id, metadata: environmentLeases.metadata }) + .from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId), + eq(environmentLeases.heartbeatRunId, input.runId), eq(environmentLeases.status, "active")))) + .catch(() => { + logger.warn({ runId: input.runId, reason }, "could not record a deferred environment lease release"); + return []; + }); + for (const lease of leases) { + const previous = readLeaseReleaseDeferral(lease.metadata); + const attempts = (previous?.attempts ?? 0) + 1; + const deferral: LeaseReleaseDeferral = { reason, attempts, + retryAt: nextLeaseReleaseRetryAt(previous, attempts), + failingSince: previous?.failingSince ?? new Date().toISOString(), + triggers: nextLeaseReleaseTriggers(previous, input.trigger), attemptedByBootIds: nextLeaseReleaseBootIds(previous), + providerResourceDisposition: providerResourceDisposition ?? null }; + const recorded = await db.transaction(async tx => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.orphanActiveLeases, + JSON.stringify({ companyId: input.companyId, runId: input.runId, leaseId: lease.id })); + await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) + || ${JSON.stringify({ [LEASE_RELEASE_DEFERRAL_KEY]: deferral })}::jsonb` }) + .where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.status, "active"))); + }).then(() => true, () => false); + if (!recorded) { + logger.warn({ runId: input.runId, leaseId: lease.id, reason }, "could not record a deferred environment lease release"); + continue; + } + logger.warn({ runId: input.runId, leaseId: lease.id, reason, attempts, retryAt: deferral.retryAt, + failingSince: deferral.failingSince }, "deferred environment lease release; a background pass retries it"); + } + } + async function acknowledgeRemoteStop(runId: string, companyId: string) { // The provider receipt arrives after adapter settlement. A remote ACP child // has no host PID, so only this target-aware boundary can acknowledge Stop. @@ -1728,12 +1809,13 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont errorCode = "cancelled", ) { const runs = await db - .select() + .select({ id: heartbeatRuns.id }) .from(heartbeatRuns) .where( and( eq(heartbeatRuns.agentId, agentId), - inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), + or(inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), + pendingFailedNativeRetryCancellationCondition()), ), ); diff --git a/server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts b/server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts new file mode 100644 index 00000000000..34ebec77d61 --- /dev/null +++ b/server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts @@ -0,0 +1,103 @@ +import { randomUUID } from "node:crypto"; +import { eq, inArray } from "drizzle-orm"; +import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; +import { agents, companies, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issues, + nativeRunFinalizations } from "@paperclipai/db"; +import { recoveryPostgresSupport, startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js"; +import { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; +import { registerCancelledWorkspacePreservationWork } from "./native-failed-workspace-recovery.js"; + +(recoveryPostgresSupport.supported ? describe : describe.skip)("cancelled workspace preservation idle cost", () => { + let database: Awaited>; + let db: ReturnType; + const fixtures = new Set(); + + async function seed(input: { launched: boolean; lease: "destroyed" | "active" }) { + if (!database) { + database = await startRecoveryPostgres("cancelled-workspace-idle-"); + db = createDb(database.connectionString); + } + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const leaseId = randomUUID(), environmentId = randomUUID(), providerLeaseId = `allocation-${randomUUID()}`; + fixtures.add(runId); + await db.insert(companies).values({ id: companyId, name: "Stopped native files", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Stopped worker", adapterType: "paperclip_runner", + status: "terminated", lifecycleState: "terminating" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Stopped task", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(environments).values({ id: environmentId, name: `Idle ${runId}`, driver: "sandbox" }); + const nativeCancellation = { schema: "paperclip.native-cancellation.v1", companyId, issueId, runId, + scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true, + intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(), acknowledgedAt: new Date().toISOString(), + effects: ["release_run_resources"] }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, issueId, nativeIssueId: issueId, + runtimeMode: "native", runtimeModeResolvedAt: new Date(), status: "cancelled", errorCode: "cancelled", + error: "Agent lifecycle stop requested", finishedAt: new Date(), contextSnapshot: { issueId }, + nextEventSeq: input.launched ? 2 : 1, + runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared", + descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null, + workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } }, + resultJson: { nativeCancellation, startupCancellation: { beforeNativeSelection: false } } }); + await db.insert(nativeRunFinalizations).values(input.launched + ? { runId, companyId, issueId, phase: "terminal_failure", failureCode: "native_retry_cancelled" } + : { runId, companyId, issueId, phase: "observed", attempt: 1, controllerGeneration: 1, + leaseOwner: `executor-${runId}`, leaseExpiresAt: new Date(Date.now() - 60_000) }); + if (input.launched) await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1, + eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); + const destroyed = input.lease === "destroyed"; + await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId, + provider: "daytona", providerLeaseId, leasePolicy: "ephemeral", status: destroyed ? "expired" : "active", + releasedAt: destroyed ? new Date() : null, cleanupStatus: destroyed ? "success" : null, + metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work", + ...(destroyed ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", state: "destroyed", + runId, leaseId, companyId, provider: "daytona", providerLeaseId, confirmedAt: new Date().toISOString() } } : {}) } }); + return { companyId, runId, leaseId }; + } + + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + afterEach(async () => { + vi.useRealTimers(); vi.restoreAllMocks(); + if (fixtures.size) await db.update(heartbeatRuns).set({ status: "failed" }).where(inArray(heartbeatRuns.id, [...fixtures])); + fixtures.clear(); + }); + + async function idleStatements(minutes: number) { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + const reads = vi.spyOn(db, "select"), transactions = vi.spyOn(db, "transaction"), writes = vi.spyOn(db, "update"); + await vi.advanceTimersByTimeAsync(minutes * 60_000); + const count = reads.mock.calls.length + transactions.mock.calls.length + writes.mock.calls.length; + reads.mockRestore(); transactions.mockRestore(); writes.mockRestore(); vi.useRealTimers(); + return count; + } + + it("leaves a stopped run that never started a runner alone, before and after a restart", async () => { + const f = await seed({ launched: false, lease: "destroyed" }); + for (let boot = 0; boot < 2; boot++) { + const worker = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } }); + const checks = vi.spyOn(db, "update"); + try { + await registerCancelledWorkspacePreservationWork(db, worker, () => true, async () => true).ready; + expect(checks.mock.calls.length).toBe(boot === 0 ? 1 : 0); + checks.mockRestore(); + expect(worker.nextWakeAt()).toBeNull(); + expect(await idleStatements(30)).toBe(0); + } finally { checks.mockRestore(); await worker.stop(); } + } + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.runnerProfileJson).not.toHaveProperty("nativeWorkspaceSync"); + expect(run.runnerProfileJson).toHaveProperty("nativeWorkspaceSyncReleasedUnchanged.state", "prepared"); + expect(run.resultJson).not.toHaveProperty("workspaceRestoreRecovery"); + }, 120_000); + + it("still preserves the files of a stopped run that started a runner, then goes idle", async () => { + const f = await seed({ launched: true, lease: "active" }); + const worker = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } }); + try { + await registerCancelledWorkspacePreservationWork(db, worker, () => true, async () => true).ready; + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.resultJson).toMatchObject({ workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", + leaseIds: [f.leaseId] } }); + expect(worker.nextWakeAt()).toBeNull(); + expect(await idleStatements(30)).toBe(0); + } finally { await worker.stop(); } + }, 120_000); +}); diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.ts index f693698265d..54de27f1887 100644 --- a/server/src/services/native-runtime/native-failed-workspace-recovery.ts +++ b/server/src/services/native-runtime/native-failed-workspace-recovery.ts @@ -9,6 +9,7 @@ import { recordRequiredWorkspaceRestoreFailure } from "../legacy-execution-recov import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; import { logActivity } from "../activity-log.js"; import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js"; +import { nativeRunNeverLaunchedRunner, settleUnchangedNativeWorkspace } from "../environment-lease-release-deferral.js"; import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js"; import { NativeWorkspaceFinalizationBusyError } from "./native-workspace-finalization-ownership.js"; import { hasAcknowledgedNativeRunStopRequest } from "../acknowledged-native-stop.js"; @@ -329,9 +330,16 @@ export function registerCancelledWorkspacePreservationWork(db: Db, eq(nativeRunFinalizations.issueId, run.nativeIssueId!), )); if (finalization?.resultId && !stoppedAcceptedCopyback(finalization)) return null; - if (finalization?.phase !== "terminal_failure" || finalization.leaseOwner) + if (finalization?.phase !== "terminal_failure" || finalization.leaseOwner) { + const ownerDeadline = finalization?.leaseOwner ? finalization.leaseExpiresAt?.getTime() ?? null : null; + if (ownerDeadline && ownerDeadline > Date.now()) return { ...entry, dueAt: ownerDeadline }; + if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId) + && await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null; return { ...entry, dueAt: Date.now() + 30_000 }; + } if (await cancelledWorkspaceSource(db, run)) await preserveNativeFailedWorkspace(db, run, { allowPreterminal: true, requireCancelledStop: true }); + else if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId) + && await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null; const [current] = await db.select().from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId))); const currentControllerDeadline = current?.controllerLeaseExpiresAt?.getTime(); diff --git a/server/src/services/native-runtime/native-workspace-finalization-state.ts b/server/src/services/native-runtime/native-workspace-finalization-state.ts index 1921029dafb..430096da99d 100644 --- a/server/src/services/native-runtime/native-workspace-finalization-state.ts +++ b/server/src/services/native-runtime/native-workspace-finalization-state.ts @@ -1,4 +1,5 @@ -import { environmentLeases, executionWorkspaces, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; +import { environmentLeases, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; +import { executionStartedEventPredicate } from "../pre-dispatch-execution-evidence.js"; import { and, eq, exists, sql } from "drizzle-orm"; import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; import { recordRequiredWorkspaceRestoreFailure } from "../legacy-execution-recovery.js"; @@ -63,6 +64,10 @@ function nativeWorkspaceRunProjection() { 'schema', ${input}->'schema', 'binding', ${input}->'binding', 'workspace', ${input}->'workspace', 'provider', jsonb_build_object('kind', ${input}#>'{provider,kind}', 'bridgeRevision', ${input}#>'{provider,bridgeRevision}'))`, controllerBootId: heartbeatRuns.controllerBootId, + cancelledBeforeRunnerLaunch: sql`${heartbeatRuns.status} = 'cancelled' + and ${heartbeatRuns.processPid} is null and ${heartbeatRuns.processGroupId} is null + and not exists (select 1 from ${heartbeatRunEvents} where ${and(eq(heartbeatRunEvents.companyId, heartbeatRuns.companyId), + eq(heartbeatRunEvents.runId, heartbeatRuns.id), executionStartedEventPredicate())})`, contextIssueId: sql`${heartbeatRuns.contextSnapshot}->>'issueId'`, remoteReference: sql`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'`, }; @@ -71,9 +76,11 @@ function nativeWorkspaceRunProjection() { function nativeWorkspaceSourcePending(run: Pick & { reference: unknown; executionScope: Record; observedRemoteWorkspace: boolean; + cancelledBeforeRunnerLaunch: boolean; }, lease: WorkspaceSourceLease) { if (run.runtimeMode !== "native") return false; if (run.observedRemoteWorkspace) return true; + if (run.cancelledBeforeRunnerLaunch) return false; if (nativeRunHasNoWorkspaceAccess({ ...run, runnerProfileJson: { nativeExecutionInput: run.executionScope } })) return false; const reference = readNativeWorkspaceSyncReference(run.reference); return reference?.state === "prepared" && reference.leaseId === lease.id From 304e40fe9c6dde1d273710c30c137f62f1db4593 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 15 Nov 2026 12:49:54 -0800 Subject: [PATCH 19/20] fix(auth): report effective Cloud owner access to the board UI (#21817) ## Thinking Path > - Paperclip manages AI agents and the environments where they run. > - Cloud owners can receive instance-admin rights for their own dedicated instance through the existing owner setting. > - Authentication computes these rights for each request without storing an instance-admin role. > - The board UI reads `/api/cli-auth/me` to decide whether to show administration controls such as Tailscale. > - That response used only stored roles, hiding controls that the Cloud backend already authorized. > - This change reports the effective Cloud request rights so the UI agrees with the backend. ## Linked Issues or Issue Description **What happened?** A Cloud owner with `enableOwnerInstanceAdmin` enabled can successfully read Tailscale connections, while `/api/cli-auth/me` reports `isInstanceAdmin: false`. The Connectors page therefore hides Tailscale. The same stale summary can hide other instance administration controls. **Expected behavior** The access summary should reflect the Cloud request's effective privileges. Turning off owner elevation must remove those privileges on the next request. Session and board-key callers must continue to use the fresh stored-role snapshot. **Steps to reproduce** Sign in as a Cloud stack owner with owner instance-admin elevation enabled and no stored instance-admin role. Open Connectors and compare the access summary with a Tailscale connections request: the summary reports no admin access even though the backend permits the request. Searched existing PRs for `"cli-auth/me" cloud` and `tailscale access`; no duplicate fix was found. Related: [#21526](https://github.com/paperclipai/paperclip/pull/21526), which added device sign-in and exposed this hosted permission-summary gap. ## What Changed - `/api/cli-auth/me` uses the trusted Cloud actor's computed `isInstanceAdmin` value for `cloud_tenant` requests. - Session and board-key requests retain fresh stored-role checks. No roles are persisted and no authorization gates or owner settings change. - Regression tests cover Cloud elevation and de-elevation, non-Cloud stored access, and rejection of anonymous/agent callers. Tailscale documentation explains Cloud owner access. ## Verification - Reproduced the deployed mismatch in an authenticated Cloud owner browser session: the access summary reported false while the Tailscale list request succeeded. No feature connection or configuration was changed. - Both Cloud access regression cases failed before the fix. - `pnpm exec vitest run server/src/__tests__/cli-auth-routes.test.ts server/src/middleware/cloud-tenant-actor.test.ts ui/src/pages/apps/TailscaleConnector.test.tsx` passes: 88 tests. - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify --explain` exits 2 and selects broad CI. All 57 checks pass on final head `6044d5097396de95f49bcbb7ce7bbb1e445a80fa`; no checks remain pending. Greptile scored this head 5/5 with no unresolved comments, and the branch is conflict-free. - `git diff --check` and a local credential/PII scan pass. - The fix has not been deployed or accepted in a hosted browser yet. ## Risks The summary exposes administration controls to Cloud owners already authorized by the backend. Non-owner access and disabled elevation remain denied by the existing authentication policy. No migration, provider configuration, or deployment change. ## Model Used OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, with xhigh reasoning. Context window size was not exposed. No subagents. ## 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 searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR following the bug template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket or instance details - [x] I have run tests locally and they pass - [x] I have added regression tests - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no unresolved comments - [x] I will address actionable reviewer comments before requesting merge Co-authored-by: Paperclip --- doc/tailscale-environments.md | 3 ++ server/src/__tests__/cli-auth-routes.test.ts | 32 ++++++++++++++++++++ server/src/routes/access.ts | 4 ++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/doc/tailscale-environments.md b/doc/tailscale-environments.md index 3f40328ce48..cdcfd7d9f3b 100644 --- a/doc/tailscale-environments.md +++ b/doc/tailscale-environments.md @@ -74,6 +74,9 @@ tools or enter MCP discovery. Management requires an instance administrator with access to the company. Only the person who started a pending sign-in can retrieve its sign-in link. Existing SSH environment access governs which agents execute there. Cloud and self-hosted instances use the same Tailscale device sign-in. +For Cloud owners, the board access summary reports the effective instance-admin +rights computed by Cloud authentication while `enableOwnerInstanceAdmin` is +enabled. Disabling that setting removes those rights on the next request. The instance starts a private userspace Tailscale device and returns its generated `https://login.tailscale.com/a/...` sign-in address. Pending device state is stored diff --git a/server/src/__tests__/cli-auth-routes.test.ts b/server/src/__tests__/cli-auth-routes.test.ts index 24b6857ecb9..dc2e52d24d3 100644 --- a/server/src/__tests__/cli-auth-routes.test.ts +++ b/server/src/__tests__/cli-auth-routes.test.ts @@ -106,6 +106,38 @@ describe("cli auth routes", () => { await Promise.all([import("../routes/access.js"), import("../middleware/index.js")]); }); + it.each([ + [true, false], + [false, true], + ])("reports effective Cloud owner access when actor admin=%s and stored admin=%s", async (effectiveAdmin, storedAdmin) => { + mockBoardAuthService.resolveBoardAccess.mockResolvedValue({ + user: { id: "user-1", name: "User One", email: "user@example.com" }, + companyIds: ["company-1"], + memberships: [{ companyId: "company-1", membershipRole: "owner", status: "active" }], + isInstanceAdmin: storedAdmin, + }); + const app = await createApp({ type: "board", source: "cloud_tenant", userId: "user-1", isInstanceAdmin: effectiveAdmin }); + const res = await request(app).get("/api/cli-auth/me"); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ source: "cloud_tenant", isInstanceAdmin: effectiveAdmin, companyIds: ["company-1"] }); + }); + + it.each(["session", "board_key"])("keeps the fresh stored access snapshot for %s authentication", async source => { + mockBoardAuthService.resolveBoardAccess.mockResolvedValue({ user: null, companyIds: [], isInstanceAdmin: false }); + const app = await createApp({ type: "board", source, userId: "user-1", isInstanceAdmin: true }); + const res = await request(app).get("/api/cli-auth/me"); + expect(res.status).toBe(200); + expect(res.body.isInstanceAdmin).toBe(false); + }); + + it.each([{ type: "none", source: "none" }, { type: "agent", source: "agent_key", agentId: "agent-1" }])( + "denies the board access summary to $type callers", async actor => { + const app = await createApp(actor); + expect((await request(app).get("/api/cli-auth/me")).status).toBe(401); + expect(mockBoardAuthService.resolveBoardAccess).not.toHaveBeenCalled(); + }, + ); + it("creates a CLI auth challenge with approval metadata", async () => { mockBoardAuthService.createCliAuthChallenge.mockResolvedValue({ challenge: { diff --git a/server/src/routes/access.ts b/server/src/routes/access.ts index 96e549afdfa..67071145726 100644 --- a/server/src/routes/access.ts +++ b/server/src/routes/access.ts @@ -2892,7 +2892,9 @@ export function accessRoutes( res.json({ user: accessSnapshot.user, userId: req.actor.userId, - isInstanceAdmin: accessSnapshot.isInstanceAdmin, + isInstanceAdmin: req.actor.source === "cloud_tenant" + ? req.actor.isInstanceAdmin === true + : accessSnapshot.isInstanceAdmin, companyIds: accessSnapshot.companyIds, memberships: accessSnapshot.memberships, source: req.actor.source ?? "none", From 8299f7c38956db97e6a4a538770bd2ecbae13cda Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sun, 15 Nov 2026 14:17:52 -0800 Subject: [PATCH 20/20] perf(runner): check a listening Runner's backlog every 10 ms, not every reconnect delay (#21821) 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 remote `paperclip_runner` agent runs `paperclip-runnerd` in a sandbox or VM. A provider ingress proxies Core's WebSocket to a Runner that listens (`--listen-address`). > - In listen mode, the Runner checks for an incoming connection only once per `--reconnect-delay-ms` (default 250 ms). It waits that delay again after each disconnect, and it backs off after a failed handshake. > - That delay exists to pace redials in dial mode. A listener never dials. Core's connection waits in the kernel backlog until the next `accept`. > - Every listen-mode connect pays part of that wait. A warm run attachment pays it in full: the Runner disconnects at the authority rotation, and Core's new-authority connect then waits up to 250 ms or more. > - This pull request makes a listening Runner check for a connection every 10 ms. Dial mode keeps the configured reconnect delay. > - The benefit is about 0.4 s less on each warm run attachment and about 0.1 s less on each cold start, for every listen-mode Runner. ## Linked Issues or Issue Description **What happened?** A warm follow-up turn on a listen-mode remote Runner reached its first turn later than a cold turn on the same agent. In traces, a cold start makes one Core→Runner connect of 134–178 ms. Each warm attachment makes an old-authority reconnect (72–233 ms) and then a new-authority connect of 411–504 ms. This was 6 of 6 warm runs. **Expected behavior** A connect to a listening Runner completes in about one network round trip plus the WebSocket handshake. It does not wait for a reconnect timer. **Steps to reproduce** 1. Start `paperclip-runnerd` in listen mode with the default `--reconnect-delay-ms`. 2. Let it reach the disconnected wait (startup, a park claim, or a `run.attach` authority rotation). 3. Connect to the listener. The upgrade is not answered until the next 250 ms check. **Root cause** `durable/runner.rs` schedules the next `accept` at `now + config.reconnect_delay` when no connection is pending, after a disconnect, and as the base of the failure backoff. The Launcher-style hosts do not pass `--reconnect-delay-ms`, so the 250 ms default applies. The tests use a 1 ms delay, so they did not show the wait. ## What Changed - `durable/transport.rs`: add `RunnerTransportEndpoint::retry_delay()`. A listener returns `min(configured, 10 ms)`. A dial endpoint returns the configured delay without change. - `durable/runner.rs`: the four places that waited `config.reconnect_delay` (no pending connection, failure backoff base, two disconnect paths) now use `endpoint.retry_delay(config.reconnect_delay)`. - `DURABLE_TRANSPORT.md`: document the listen-mode connection check interval. - Add a unit test for the listener and dial delays. - Add `tests/listener_accept.rs`. It starts `paperclip-runnerd` in listen mode with the default reconnect delay. One connection drops before authentication, as a superseded route's redial does. The test then checks that the next upgrade is answered in under 120 ms. Before this change, that upgrade waited 188–313 ms. ## Verification - `cargo test -p paperclip-runner-core --lib` passes locally. - `cargo clippy -p paperclip-runner-core --all-targets` reports no new findings in the changed files. - `cargo fmt --all -- --check` passes. - New tests: `durable::transport::tests::listener_checks_its_backlog_sooner_than_a_dial_reconnects` and `tests/listener_accept.rs`. - `tests/listener_accept.rs` fails on the previous `runner.rs` and passes with this change (3 runs each). - Existing listener and warm-attachment tests pass (`listener_*`, `warm_run_attachment_*`, `warm_external_attachment_*`). - I did not measure the change on a live host. The effect is visible in the next deployment as a shorter `runner.transport.registration` on warm attachments. ## Risks - Low risk. Dial mode does not change. - A disconnected listener now wakes every 10 ms instead of every 250 ms. Each wake is one non-blocking `accept` and a non-blocking host-control read. The loop already slept in 25 ms steps. - Failed handshakes on a listener now back off from 10 ms (10, 20, 40 … 320 ms) instead of from 250 ms. Core's own reconnect loop still paces its redials, and the ingress requires credentials, so this does not create a hot loop. - The change needs a Runner release before hosts pick it up. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, trace queries). ## 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: Paperclip Co-authored-by: Claude Opus 5.5 --- .../runner/DURABLE_TRANSPORT.md | 6 + .../crates/runner-core/src/durable/runner.rs | 13 +- .../runner-core/src/durable/transport.rs | 29 ++++ .../runner-core/tests/listener_accept.rs | 138 ++++++++++++++++++ 4 files changed, 180 insertions(+), 6 deletions(-) create mode 100644 packages/paperclip-runner/runner/crates/runner-core/tests/listener_accept.rs diff --git a/packages/paperclip-runner/runner/DURABLE_TRANSPORT.md b/packages/paperclip-runner/runner/DURABLE_TRANSPORT.md index 3b61ad38db9..24d651c0d37 100644 --- a/packages/paperclip-runner/runner/DURABLE_TRANSPORT.md +++ b/packages/paperclip-runner/runner/DURABLE_TRANSPORT.md @@ -8,6 +8,12 @@ agent or recovery of its persisted run. On a fresh launch or restart, - With `--listen-address 0.0.0.0 --listen-path /api/runner/v1/connect/`, the Runner listens for Core. `--listen-port` defaults to `43127`. +A dialing Runner waits `--reconnect-delay-ms` (default 250) between +connection attempts and backs off after a failed one. A listening Runner +checks for an incoming connection every 10 ms (or sooner, when that delay is +smaller). It never redials, so a connection does not wait out the reconnect +delay after a disconnect or an authority rotation. + Choose one form. Both require `PAPERCLIP_RUNNER_BOOTSTRAP_TICKET`. Recovery uses the same entry point. The Runner rejects `--source-reconcile`. diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs index ae1d3bb7aa4..e9c2eafc585 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs @@ -730,7 +730,8 @@ pub fn run_durable_runner_with_host_control( let (mut transport, welcome) = match connection { Ok(Some(connection)) => connection, Ok(None) => { - next_connection_attempt = Instant::now() + config.reconnect_delay; + next_connection_attempt = + Instant::now() + endpoint.retry_delay(config.reconnect_delay); continue; } Err(error) => { @@ -749,7 +750,7 @@ pub fn run_durable_runner_with_host_control( } next_connection_attempt = Instant::now() + reconnect_delay( - config.reconnect_delay, + endpoint.retry_delay(config.reconnect_delay), connect_deadline.saturating_duration_since(Instant::now()), &mut reconnect_attempt, ); @@ -1055,8 +1056,8 @@ pub fn run_durable_runner_with_host_control( .map(|credential| credential.expires_at_unix_ms), ); next_connection_attempt = Instant::now() - + config - .reconnect_delay + + endpoint + .retry_delay(config.reconnect_delay) .min(reconnect_deadline.saturating_duration_since(Instant::now())); continue; } @@ -1419,8 +1420,8 @@ pub fn run_durable_runner_with_host_control( .map(|credential| credential.expires_at_unix_ms), ); next_connection_attempt = Instant::now() - + config - .reconnect_delay + + endpoint + .retry_delay(config.reconnect_delay) .min(reconnect_deadline.saturating_duration_since(Instant::now())); } } diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs index 8b245375882..578419e8bb4 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs @@ -32,6 +32,7 @@ const QUEUED_CONTROL_READ_TIMEOUT: Duration = Duration::from_millis(1); const CONNECT_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(3); const CONNECT_TOTAL_TIMEOUT: Duration = Duration::from_secs(10); const MAX_CA_BUNDLE_BYTES: u64 = 4 * 1024 * 1024; +const LISTENER_ACCEPT_INTERVAL: Duration = Duration::from_millis(10); type HmacSha256 = Hmac; @@ -252,6 +253,13 @@ impl RunnerTransportEndpoint { Ok(()) } + pub(crate) fn retry_delay(&self, configured: Duration) -> Duration { + match self { + Self::Dial(_) => configured, + Self::Listen { .. } => configured.min(LISTENER_ACCEPT_INTERVAL), + } + } + fn open( &self, max_frame_bytes: usize, @@ -2172,6 +2180,27 @@ mod tests { } } + #[test] + fn listener_checks_its_backlog_sooner_than_a_dial_reconnects() { + let configured = Duration::from_millis(250); + let listener = RunnerTransportEndpoint::Listen { + listener: TcpListener::bind("0.0.0.0:0").unwrap(), + path: "/api/runner/v1/connect/run_1".to_owned(), + }; + assert_eq!(listener.retry_delay(configured), LISTENER_ACCEPT_INTERVAL); + assert!(LISTENER_ACCEPT_INTERVAL <= Duration::from_millis(25)); + assert_eq!( + listener.retry_delay(Duration::from_millis(1)), + Duration::from_millis(1) + ); + let dial = RunnerTransportEndpoint::new( + "ws://127.0.0.1:43127/api/runner/v1/connect/run_1", + "run_1", + ) + .unwrap(); + assert_eq!(dial.retry_delay(configured), configured); + } + #[test] fn listener_path_is_exact_and_unambiguous() { validate_listener_path("/api/runner/v1/connect/run_1").unwrap(); diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/listener_accept.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/listener_accept.rs new file mode 100644 index 00000000000..5af4fc24bf8 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/listener_accept.rs @@ -0,0 +1,138 @@ +#![cfg(unix)] + +use std::fs; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +struct Runner { + process: Child, + directory: PathBuf, +} + +impl Drop for Runner { + fn drop(&mut self) { + let _ = self.process.kill(); + let _ = self.process.wait(); + let _ = fs::remove_dir_all(&self.directory); + } +} + +const RUN_ID: &str = "run_accept"; + +fn upgrade(stream: &mut TcpStream) -> Duration { + let started = Instant::now(); + stream + .write_all( + format!( + "GET /api/runner/v1/connect/{RUN_ID} HTTP/1.1\r\nHost: 127.0.0.1\r\n\ + Upgrade: websocket\r\nConnection: Upgrade\r\n\ + Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n" + ) + .as_bytes(), + ) + .unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut response = Vec::new(); + let mut byte = [0_u8; 1]; + while !response.ends_with(b"\r\n\r\n") { + assert_eq!( + stream.read(&mut byte).unwrap(), + 1, + "Runner closed the upgrade" + ); + response.push(byte[0]); + } + assert!( + response.starts_with(b"HTTP/1.1 101"), + "{}", + String::from_utf8_lossy(&response) + ); + started.elapsed() +} + +fn spawn_listening_runner() -> (Runner, u16, TcpStream) { + for _ in 0..10 { + let reservation = TcpListener::bind("0.0.0.0:0").unwrap(); + let port = reservation.local_addr().unwrap().port(); + drop(reservation); + let directory = + std::env::temp_dir().join(format!("runner-accept-{}", uuid::Uuid::new_v4())); + fs::create_dir(&directory).unwrap(); + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap(); + let process = Command::new(env!("CARGO_BIN_EXE_paperclip-runnerd")) + .env( + "PAPERCLIP_RUNNER_BOOTSTRAP_TICKET", + "fixture-bootstrap-ticket", + ) + .args([ + "--listen-address", + "0.0.0.0", + "--listen-port", + &port.to_string(), + "--listen-path", + &format!("/api/runner/v1/connect/{RUN_ID}"), + "--state-dir", + directory.to_str().unwrap(), + "--runner-id", + "runner", + "--environment-lease-id", + "lease", + "--run-id", + RUN_ID, + "--session-id", + "session", + "--turn-id", + "turn", + "--item-id", + "item", + "--runner-version", + "0.0.0", + "--runner-digest", + &format!("sha256:{}", "a".repeat(64)), + "--max-runtime-ms", + "20000", + ]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut runner = Runner { process, directory }; + let deadline = Instant::now() + Duration::from_secs(5); + loop { + if let Some(status) = runner.process.try_wait().unwrap() { + match TcpListener::bind(("0.0.0.0", port)) { + Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => break, + _ => panic!("Runner exited before listening: {status}"), + } + } + if let Ok(stream) = TcpStream::connect(("127.0.0.1", port)) { + return (runner, port, stream); + } + assert!(Instant::now() < deadline, "Runner did not bind its port"); + thread::sleep(Duration::from_millis(10)); + } + } + panic!("could not acquire an available Runner port"); +} + +#[test] +fn listener_answers_the_next_connection_without_waiting_out_the_reconnect_delay() { + let (_runner, port, mut stale) = spawn_listening_runner(); + upgrade(&mut stale); + drop(stale); + thread::sleep(Duration::from_millis(30)); + + let mut current = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let waited = upgrade(&mut current); + assert!( + waited < Duration::from_millis(120), + "listener answered after {waited:?}" + ); +}