From 009c8884a4fee1ef7e406ea03fdadd4ac7c40d08 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:05:59 -0600 Subject: [PATCH 1/6] perf(attention): read blocker retention state once per page (#21595) 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 `attention-retention` queue archives old attention items. One kind is `blocker_attention`: a blocked task whose terminal blocker needs a person. > - When the queue loads a page of blocked tasks, it reads `keep` and `archived_at` from `decision_retention` for each of them, one full-row `select` per task. > - A company hint walks every page. On a hosted instance with 2,112 blocker attention items and one active run, these per-task reads ran at about 16 per second. > - This pull request reads the retention state for the whole page in one narrow statement. It also scopes three remaining run-path attention hints to the task graph. > - The benefit is one retention read per page instead of one per blocked task, with the same decisions. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** The `blocker_attention` eligibility read in `server/src/services/attention-retention.ts` (`eligible()`), and three run-path producers of company-wide attention hints. **Subsystem affected** Server background retention (`attention-retention.ts`, `native-runtime/native-provider-capacity-retry.ts`, `native-runtime/native-review-participant.ts`, `native-runtime/native-workspace-reconstruction.ts`). **Current behavior** - For each blocked task whose blocker attention is terminal (and for the owner variant), `eligible()` ran `select from decision_retention where company_id = $1 and source_kind = $2 and source_id = $3`. It did this during `load`, once per task, on every company hint. - The hosted statement is identified by that column prefix: `id, company_id, source_kind, source_id, source_activity_at, …`. - I checked every other full-row reader of `decision_retention`. None fires per run event: - `syncItems`: attention summary and list requests, which a board calls once per load; retention `check` and the sweep, which run for due entries only; Keep and Archive actions. - `getState`: user actions only. - `archiveReviewedManifest`: proposal acceptance only. - `decisions.list`: only when archive proposals exist. - `native-provider-capacity-retry`, `native-review-participant` and `native-workspace-reconstruction` sent `{ companyId }` attention hints, which make the queue walk every page. **Proposed behavior** - `pageEvidence` reads `source_id`, `keep` and `archived_at` for every blocker root and every terminal blocker on the page in one statement (ids passed as one JSON parameter). `eligible()` uses that map when it has page evidence. - A missing row means "not kept, not archived", exactly as the per-task read returning no row did. - The per-entry `check` path still reads one row, now only `keep` and `archived_at`. - The three producers send `notifyIssueAttentionRetentionWork` with their task (and run). That is the task, its parents and the tasks it blocks, with a company fallback past 100. - A capacity retry changes the failed-run items of its task. - A review participant claim changes the review of its task. - A workspace reconstruction resolves the recovery action of its task, which can also change the blocker attention of the tasks it blocks. - The configuration, lifecycle, import and fallback producers keep their company hints. **Reason and benefit** Background work must not grow with the backlog. A page now costs one retention read instead of up to 100. ## What Changed - `server/src/services/attention-retention.ts`: batched and narrowed blocker retention read; `PageEvidence.blockerRetention`. - `server/src/services/native-runtime/native-provider-capacity-retry.ts`, `native-review-participant.ts`, `native-workspace-reconstruction.ts`: scoped attention hints. - Tests in `server/src/__tests__/attention-retention-work.test.ts` and `server/src/services/native-runtime/native-workspace-reconstruction.test.ts`. ## Verification - `reads blocker retention state once per page, not once per blocked task` (I saw it fail first). 160 blocked tasks, each behind its own unassigned blocker; the blockers' retention rows are kept (40), archived (40), plain (40) or missing (40). The full-size response capture and the statement log measure the load of both pages: - before: one `decision_retention` read per task (160), 26,240 result bytes; - after: 2 reads (one per page), 5,480 bytes, none of them selecting `source_activity_at`. - The same tasks are listed: only plain and missing. - `check` still drops the kept and archived ones. - `scopes the attention retention hint of a reconstruction to the task graph` (I saw it fail first): before, the reconstruction sent `{ companyId }`; after, it sends a hint that names the task. - `batches 100 blocker graphs with exact terminal timestamps and fresh terminal visibility` pinned 200 retention reads per page (one per root and variant). It now expects 1; the rest of that test is unchanged and passes. - Not separately tested: the capacity-retry and review-participant hint changes. Each is one line that passes the task the function already holds, the same pattern as the reconstruction test. - `attention-retention-work` (58), `attention-retention-candidates`, `native-workspace-reconstruction`, `native-review-participant` and `heartbeat-run-dispatch-work` pass, each file run alone (in `server/`, against dedicated local `_test` databases). - `pnpm check:module-boundaries` passes. ## Risks - The page read happens once, before the per-entry decisions of that page. Before, each decision read its row just in time. A Keep or Archive that lands between the page read and an entry's decision is seen by the next load or by `check`, which re-reads under a row lock, as before. - A run-path hint that changes more than its task graph would now miss the wider effect. The 90-day archive delay makes a missed reload cheap. - No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] 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 --- .../attention-retention-work.test.ts | 50 ++++++++++++++++++- server/src/services/attention-retention.ts | 15 ++++-- .../native-provider-capacity-retry.ts | 4 +- .../native-review-participant.ts | 4 +- .../native-workspace-reconstruction.test.ts | 12 +++++ .../native-workspace-reconstruction.ts | 4 +- 6 files changed, 79 insertions(+), 10 deletions(-) diff --git a/server/src/__tests__/attention-retention-work.test.ts b/server/src/__tests__/attention-retention-work.test.ts index fbbae5a232e..e13d8a1931c 100644 --- a/server/src/__tests__/attention-retention-work.test.ts +++ b/server/src/__tests__/attention-retention-work.test.ts @@ -290,6 +290,54 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000; expect(bytes("issues")).toBeLessThan(60_000); }); + it("reads blocker retention state once per page, not once per blocked task", async () => { + const blockers = await db.insert(issues).values(Array.from({ length: 160 }, () => ({ companyId, title: randomUUID(), + status: "todo", createdByAgentId: agentId, createdAt: old(), updatedAt: old() }))).returning({ id: issues.id }); + const blocked = await db.insert(issues).values(blockers.map(() => ({ companyId, title: randomUUID(), status: "blocked", + createdByAgentId: agentId, createdAt: old(), updatedAt: old() }))).returning({ id: issues.id }); + await db.insert(issueRelations).values(blocked.map((row, index) => ({ companyId, issueId: blockers[index].id, + relatedIssueId: row.id, type: "blocks" as const }))); + const at = old(); + const kept = blockers.slice(0, 40), archived = blockers.slice(40, 80), plain = blockers.slice(80, 120), missing = blockers.slice(120); + await db.insert(decisionRetention).values([ + ...kept.map(row => ({ companyId, sourceKind: "blocker_attention", sourceId: row.id, sourceActivityAt: at, keep: true })), + ...archived.map(row => ({ companyId, sourceKind: "blocker_attention", sourceId: row.id, sourceActivityAt: at, archivedAt: new Date() })), + ...plain.map(row => ({ companyId, sourceKind: "blocker_attention", sourceId: row.id, sourceActivityAt: at })), + ]); + const service = attentionRetentionService(db), scope = { companyId, sourceKind: "blocker_attention" as const }; + const observed = createDb(externalUrl ?? temporary!.connectionString), events: Array> = [], now = Date.now(); + const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { decisionRetention }, capture); + const retentionReads: string[] = []; + observed.$client.options.debug = (_connection, query) => { if (query.includes('from "decision_retention"')) retentionReads.push(query); }; + const entries: Array<{ id: string; sourceId: string; rootId: string; variant?: string }> = []; + let pages = 0; + try { + const observedService = attentionRetentionService(observed); + for (; pages < 4; pages++) { + const loaded = await observedService.load(scope); + entries.push(...(loaded.rows ?? [])); + if (loaded.complete) { pages++; break; } + } + capture.flush(); + } finally { capture.flush(); await observed.$client.end(); } + const retentionBytes = events.filter(event => event.table === "decision_retention") + .reduce((total, event) => total + Number(event.responseValueBytes), 0); + expect(retentionBytes).toBeLessThan(10_000); + expect(retentionReads.length).toBeLessThanOrEqual(pages); + expect(retentionReads.every(query => !query.includes('"source_activity_at"'))).toBe(true); + const listed = new Set(entries.filter(entry => entry.variant === "terminal").map(entry => entry.sourceId)); + expect(listed).toEqual(new Set([...plain, ...missing].map(row => row.id))); + const byRoot = new Map(blocked.map((row, index) => [row.id, blockers[index].id])); + for (const root of [blocked[0].id, blocked[40].id]) { + const candidate = { sourceKind: "blocker_attention" as const, sourceId: root, companyId, activityAt: at.toISOString(), + deadlineAt: Number.MAX_SAFE_INTEGER, issueId: root, id: `blocker_attention:${root}:terminal`, rootId: root, + variant: "terminal" as const, dueAt: Number.MAX_SAFE_INTEGER }; + expect(byRoot.get(root)).toBeTruthy(); + expect(await service.check(candidate)).toBeNull(); + } + }); + it("batches 100 failed runs and rechecks late visibility and supersession before archive", async () => { const origins = await db.insert(issues).values(Array.from({ length: 100 }, () => ({ companyId, title: randomUUID(), status: "todo", updatedAt: old() }))).returning(); @@ -332,7 +380,7 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000; const queries = [...statements]; expect(page.rows).toHaveLength(200); expect(page.complete).toBe(false); const retentionReads = queries.filter(query => query.includes('from "decision_retention"')); - expect(retentionReads).toHaveLength(200); + expect(retentionReads).toHaveLength(1); expect(queries.length - retentionReads.length).toBeLessThanOrEqual(30); const terminal = page.rows!.find(entry => entry.rootId === roots[99].id && entry.variant === "terminal")!; expect(terminal.sourceId).toBe(terminals[99].id); diff --git a/server/src/services/attention-retention.ts b/server/src/services/attention-retention.ts index 930d27eeba6..8f980f785d8 100644 --- a/server/src/services/attention-retention.ts +++ b/server/src/services/attention-retention.ts @@ -44,6 +44,7 @@ type PageEvidence = { newerRuns: Set; deferredRoots: Set; blockers: Awaited["listBlockerAttention"]>>; + blockerRetention: Map; }; const sourceTables: Record = { @@ -247,11 +248,18 @@ export function attentionRetentionService(db: Db) { const terminalIds = [...blockers.values()].filter(terminalBlockerRequiresAttention) .map(attention => attention.terminalBlockerIssueId).filter((id): id is string => id != null && !visible.has(id)); for (const row of await readIssues(terminalIds)) visible.set(row.id, row); + const retentionIds = [...new Set([...blockerIds, ...[...blockers.values()].filter(terminalBlockerRequiresAttention) + .map(attention => attention.terminalBlockerIssueId).filter((id): id is string => id != null)])]; + const blockerRetention = new Map(retentionIds.length ? (await database.select({ sourceId: decisionRetention.sourceId, + keep: decisionRetention.keep, archivedAt: decisionRetention.archivedAt }).from(decisionRetention).where(and( + eq(decisionRetention.companyId, companyId), eq(decisionRetention.sourceKind, "blocker_attention"), + sql`${decisionRetention.sourceId} in (select jsonb_array_elements_text(${JSON.stringify(retentionIds)}::jsonb))`))) + .map(row => [row.sourceId, { keep: row.keep, archivedAt: row.archivedAt }]) : []); result.set(companyId, { decisions: new Map(decisionRows.map(row => [row.id, row])), recoveries: new Map(recoveryRows.map(row => [row.id, row])), runs: new Map(runRows.map(row => [row.id, row])), agents: new Set(runAgents.map(row => row.id)), visibleIssues: visible, newerRuns: await listFailedRunsWithNewerRun(database, companyId, - runRows), blockers, deferredRoots: blockerBatch.deferredRootIds, + runRows), blockers, deferredRoots: blockerBatch.deferredRootIds, blockerRetention, }); } return result; @@ -307,8 +315,9 @@ export function attentionRetentionService(db: Db) { where company_id = ${candidate.companyId}::uuid and id = ${sourceId}::uuid`) as unknown as Array<{ at: string; due: string }>)[0]; activityAt = activity.at; dueAt = Number(activity.due); } - const [retention] = await database.select().from(decisionRetention).where(and(eq(decisionRetention.companyId, candidate.companyId), - eq(decisionRetention.sourceKind, candidate.sourceKind), eq(decisionRetention.sourceId, sourceId))); + const retention = evidence ? evidence.blockerRetention.get(sourceId) : (await database.select({ keep: decisionRetention.keep, + archivedAt: decisionRetention.archivedAt }).from(decisionRetention).where(and(eq(decisionRetention.companyId, candidate.companyId), + eq(decisionRetention.sourceKind, candidate.sourceKind), eq(decisionRetention.sourceId, sourceId))))[0]; if (retention?.keep || retention?.archivedAt) return null; } else if (candidate.sourceKind === "failed_run") { const run: RunProbe | undefined = evidence ? evidence.runs.get(sourceId) : (await database.select(runProbeColumns).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.id, sourceId))))[0]; diff --git a/server/src/services/native-runtime/native-provider-capacity-retry.ts b/server/src/services/native-runtime/native-provider-capacity-retry.ts index 334e5880226..a472054ee17 100644 --- a/server/src/services/native-runtime/native-provider-capacity-retry.ts +++ b/server/src/services/native-runtime/native-provider-capacity-retry.ts @@ -1,4 +1,4 @@ -import { notifyAttentionRetentionWork } from "../retention-work-notifications.js"; +import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js"; import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js"; import { randomUUID } from "node:crypto"; import { and, eq } from "drizzle-orm"; @@ -51,7 +51,7 @@ export async function materializeNativeProviderCapacityRetry(input: { scheduledRetryAt: dueAt.toISOString(), executionRetryAccounting: accountingForScheduledRetry(run, NATIVE_PROVIDER_OVERLOADED_CODE, attempt), }; - await notifyAttentionRetentionWork(input.tx, { companyId: input.companyId }); + await notifyIssueAttentionRetentionWork(input.tx, { companyId: input.companyId, issueId: input.issueId, runId: run.id }); await notifyScheduledRetryDispatch(input.tx, { companyId: run.companyId, runId: run.id }); const [wake] = await input.tx.insert(agentWakeupRequests).values({ companyId: run.companyId, agentId: run.agentId, source: "automation", triggerDetail: "system", diff --git a/server/src/services/native-runtime/native-review-participant.ts b/server/src/services/native-runtime/native-review-participant.ts index b51627d1352..ccd832f3ecb 100644 --- a/server/src/services/native-runtime/native-review-participant.ts +++ b/server/src/services/native-runtime/native-review-participant.ts @@ -1,5 +1,5 @@ import { notifyStatusCardIssueChange } from "../status-card-notifications.js"; -import { notifyAttentionRetentionWork } from "../retention-work-notifications.js"; +import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js"; import { agents, heartbeatRuns, @@ -243,7 +243,7 @@ export async function claimNativeReviewExecutionLock(db: Db, input: { || admitted.nativeReviewInteractionId !== expected.nativeReviewInteractionId || admitted.nativeReviewDecisionId !== expected.nativeReviewDecisionId) return false; await notifyStatusCardIssueChange(tx, input.companyId); - await notifyAttentionRetentionWork(tx, { companyId: input.companyId }); + await notifyIssueAttentionRetentionWork(tx, { companyId: input.companyId, issueId: input.issueId, runId: input.runId }); const claimed = await tx.update(issues).set({ executionRunId: input.runId, executionAgentNameKey: input.agentNameKey, diff --git a/server/src/services/native-runtime/native-workspace-reconstruction.test.ts b/server/src/services/native-runtime/native-workspace-reconstruction.test.ts index 8afb9820bee..08b26099219 100644 --- a/server/src/services/native-runtime/native-workspace-reconstruction.test.ts +++ b/server/src/services/native-runtime/native-workspace-reconstruction.test.ts @@ -161,6 +161,18 @@ describe("reconstruction after confirmed native workspace loss", () => { } finally { unsubscribe(); unsubscribeRoutine(); } }); + it("scopes the attention retention hint of a reconstruction to the task graph", async () => { + const f = await seed(); + const hints: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.attentionRetention, (event, values) => { + if (event === "settled") hints.push(...values ?? []); + }); + try { await db.transaction(tx => reconstructNativeWorkspace({ ...f, db: tx as unknown as Db })); } finally { unsubscribe(); } + expect(hints).not.toContain(JSON.stringify({ companyId: f.companyId })); + expect(hints.some(hint => (JSON.parse(hint) as { issueIds?: string[]; issueId?: string }).issueIds?.includes(f.issueId) + || (JSON.parse(hint) as { issueId?: string }).issueId === f.issueId)).toBe(true); + }); + it("pins a historical cancelled workspace through public heartbeat startup without replaying its turn", async () => { const f = await seed(); const later = await interveningCancelledRun(f, false); diff --git a/server/src/services/native-runtime/native-workspace-reconstruction.ts b/server/src/services/native-runtime/native-workspace-reconstruction.ts index aa20b852e14..9d95f5b22db 100644 --- a/server/src/services/native-runtime/native-workspace-reconstruction.ts +++ b/server/src/services/native-runtime/native-workspace-reconstruction.ts @@ -1,5 +1,5 @@ import { notifyStatusCardIssueChange } from "../status-card-notifications.js"; -import { notifyAttentionRetentionWork } from "../retention-work-notifications.js"; +import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js"; import { notifyRoutineExecutionStatus } from "../routine-execution-status-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js"; import { notifyUnsafeWorkspaceExportRecovery } from "../unsafe-workspace-export-notifications.js"; @@ -183,7 +183,7 @@ export async function reconstructNativeWorkspace(input: { ...(source.interveningExecutions.length ? { interveningExecutions: source.interveningExecutions } : {}) } }; await markExecutionReconciliation(db, source.action, decision, input.actorId); const now = new Date(); - await notifyAttentionRetentionWork(tx, { companyId: input.companyId }); + await notifyIssueAttentionRetentionWork(tx, { companyId: input.companyId, issueId: input.issueId }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.companyId, issueId: input.issueId }); await tx.update(issueRecoveryActions).set({ status: "resolved", outcome: "handed_back", resolvedAt: now, updatedAt: now, resolutionNote: "workspace_reconstruction_authorized", nextAction: "Continue from saved sources. The original unexported edits are lost; verify the selected attachments before rebuilding. Do not repeat completed external actions or reset the original work limits.", From d25667f370d1049c445a7dec8f0ca579034db491 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:46:41 -0600 Subject: [PATCH 2/6] perf(db): keep postgres.js connection queues proportional to live connections (#21601) 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 reads PostgreSQL through postgres.js, with a patched driver in `patches/postgres@3.4.9.patch` > - The driver keeps its pool connections in small FIFO queues (`open`, `busy`, `full` and others) in `src/queue.js` > - The `open` queue keeps an empty slot for every connection it hands out until it is completely empty, and `remove` scans every slot > - A busy pool always has some idle connections, so `open` never empties. Each query then scans one slot for every query the process has already run > - The main thread of a long-running server therefore spends more time on each query as the process ages > - This pull request compacts the queue once empty slots outnumber queued items, and makes `remove` search only the queued items > - The benefit is that query dispatch cost stays flat for the life of the process instead of growing linearly ## Linked Issues or Issue Description **What happened?** A hosted Paperclip server spends more of its main thread in the postgres.js dispatcher the longer it runs. A CPU profile 14 minutes after start showed the driver's `handler` (`src/index.js:350`) at 9.6% self time, plus 3.8% more in the same inlined queue work. The server had about 117 open sockets, a pool maximum of 500, and about 1,000 statements per second. The cause is in `src/queue.js` (and `cjs/src/queue.js`). `shift` resets its backing array only when the queue is completely empty. Otherwise it leaves an `undefined` slot. `handler` takes a connection with `open.shift()`. Then `move` calls `open.remove(c)` for a connection that `shift` already took out, so `indexOf` scans the whole backing array and finds nothing. When the query finishes, `move(c, open)` pushes the connection back. The backing array grows by about one slot per query. **Steps to reproduce** 1. Open a pool with more connections than the number of concurrent queries (for example 24 connections and 8 concurrent queries). 2. Run 200,000 `select 1` queries. 3. Measure main-thread CPU per query for each block of 20,000 queries. It grows from 30.6 µs to 48.7 µs. 4. Or run the same queue operations without a database: with 117 connections and 8 in flight, the cost per query is 16 µs at 200,000 queries and 151 µs at 1,000,000 queries. **Expected behavior** The cost to dispatch a query depends on the number of connections in the queues, not on how many queries the process has run. **Environment** postgres.js 3.4.9 with the Paperclip patch, Node.js 24 and 26, PostgreSQL 17/18, hosted and local servers. ## What Changed - `patches/postgres@3.4.9.patch`: adds one hunk each to `src/queue.js` (ESM, which the server loads) and `cjs/src/queue.js` (CommonJS). All existing hunks are unchanged. The added hunk is: ```diff remove: (x) => { - const index = xs.indexOf(x) - return index === -1 + const at = xs.indexOf(x, index) + return at === -1 ? null - : (xs.splice(index, 1), x) + : (xs.splice(at, 1), x) }, ... if (index === xs.length) { index = 0 xs = [] + } else if (index > 1024 && index * 2 > xs.length) { + xs = xs.slice(index) + index = 0 } else { xs[index - 1] = undefined } ``` The compaction copies only the queued items, and only after more than 1,024 shifts and after empty slots outnumber queued items. Its cost is therefore amortized O(1) per `shift`. FIFO order, `length`, `push`, `shift` (including `shift` on an empty queue) and `remove` (including `null` for an absent item) keep the same results. - `packages/db/src/postgres-queue.test.ts`: for both the ESM and CommonJS builds, checks FIFO order, `length` and `remove` results. It compares the queue with a plain array over 300,000 random operations that cross the compaction threshold. It also runs 1,000,000 queries in the pattern where `open` never empties, and checks that the slots scanned by `remove` and the backing array size stay bounded by the live connections. - `packages/db/src/__fixtures__/postgres-queue-pool.mjs` and `packages/db/src/postgres-queue-pool.test.ts`: run a real pool (24 connections, 8 concurrent queries, 20,000 queries) against embedded PostgreSQL for both builds. They check that a dispatch scans no more slots than there are connections. - `packages/db/scripts/benchmark-postgres-queue.ts`: reports per-query cost for the queue simulation (1,000,000 queries) and for the real pool (200,000 queries, 10 blocks). - `doc/DATABASE.md`: describes the fix, the tests and the benchmark command. - `pnpm-lock.yaml` is not changed. The lockfile refresh workflow updates the patch hash, as it did after #21432. ## Verification - Red before the fix: `pnpm --filter @paperclipai/db exec vitest run src/postgres-queue.test.ts src/postgres-queue-pool.test.ts` failed 4 tests. The unit test scanned 13,340 slots (limit 125). The real pool scanned 5,017 slots in its first 5,000 queries (limit 24). The semantic tests passed before and after the fix. - Green after the fix: the same command, plus `src/postgres-receive-buffer.test.ts` and `src/postgres-connection-recovery.test.ts`, passes 32 of 32 tests. - `pnpm --filter @paperclipai/db exec tsc --noEmit` passes. - `pnpm verify` exits 2 because the patch is a global CI input. Required CI supplies the broad coverage. - Benchmark: `pnpm --filter @paperclipai/db exec tsx scripts/benchmark-postgres-queue.ts` on Apple Silicon, Node.js 26.4, embedded PostgreSQL 18: | Measurement | Before | After | | --- | --- | --- | | Simulation, µs per query at 200k / 400k / 600k / 800k / 1M queries | 16.0 / 50.4 / 81.3 / 128.4 / 150.7 | 0.070 / 0.070 / 0.071 / 0.073 / 0.072 | | Real pool, main-thread CPU µs per query, first vs last 20k of 200k | 30.6 vs 48.7 (+59%) | 22.8 vs 14.6 (first block includes warm-up) | | Real pool, CPU µs per query, blocks 2 to 10 | 29.6 rising to 48.7 | 13.3 to 15.9, flat | ## Risks - Low risk. The change is limited to the driver's internal queue. The results of every queue operation are the same, and the semantic test compares them with a plain array over 300,000 random operations in both builds. - `remove` now searches from the first queued item. Slots before it are always empty, so it cannot miss a queued item. Before this change, `remove(undefined)` could remove an empty slot. The driver never calls it that way. - Compaction allocates a new array with only the queued items. It runs at most once per 1,024 shifts, so memory use falls. - The lockfile refresh workflow updates the patch hash in `pnpm-lock.yaml` after merge, as it did after #21432. - A possible follow-up is to offer the same fix to the upstream postgres.js project. This pull request does not do that. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file editing, test execution) 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 --- doc/DATABASE.md | 15 ++ .../db/scripts/benchmark-postgres-queue.ts | 69 +++++++++ .../src/__fixtures__/postgres-queue-pool.mjs | 60 ++++++++ packages/db/src/postgres-queue-pool.test.ts | 43 ++++++ packages/db/src/postgres-queue.test.ts | 145 ++++++++++++++++++ patches/postgres@3.4.9.patch | 56 +++++++ 6 files changed, 388 insertions(+) create mode 100644 packages/db/scripts/benchmark-postgres-queue.ts create mode 100644 packages/db/src/__fixtures__/postgres-queue-pool.mjs create mode 100644 packages/db/src/postgres-queue-pool.test.ts create mode 100644 packages/db/src/postgres-queue.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 197b10cb495..fc54cebf220 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -1131,6 +1131,21 @@ in the middle, and when the operating system chooses the chunks. Measure it with `pnpm --filter @paperclipai/db exec node --expose-gc --import tsx scripts/benchmark-postgres-receive-buffer.ts` (`CONNECTIONS` and `ROW_BYTES` are optional). +The patch also keeps the driver's connection queues proportional to the +connections they hold. Without this fix, the queue of idle connections keeps an +empty slot for every query it has handed out until it is completely empty. A +busy pool always has some idle connections, so that queue never empties. Each +new query then scans one slot for every query the process has already run. In a +simulation at 1,000 statements per second, dispatching a query used about 15% +of the main thread after 17 minutes, and the cost kept growing. The patched queue removes +the empty slots once there are more than 1,024 of them and more empty slots +than queued connections. It also searches only the queued connections. +`packages/db/src/postgres-queue.test.ts` checks the queue order and the work per +query, and `packages/db/src/postgres-queue-pool.test.ts` checks a real pool. +Measure it with +`pnpm --filter @paperclipai/db exec tsx scripts/benchmark-postgres-queue.ts` +(`SIMULATED_QUERIES` and `QUERIES` are optional). + Trusted-header actor synchronization retries transient connection failures, including `CONNECT_TIMEOUT`, at most twice. This retry applies only to the idempotent actor synchronization operations, not arbitrary transactions. A diff --git a/packages/db/scripts/benchmark-postgres-queue.ts b/packages/db/scripts/benchmark-postgres-queue.ts new file mode 100644 index 00000000000..ca5b8f707f4 --- /dev/null +++ b/packages/db/scripts/benchmark-postgres-queue.ts @@ -0,0 +1,69 @@ +import { execFile } from "node:child_process"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { promisify } from "node:util"; +import { startEmbeddedPostgresTestDatabase } from "../src/test-embedded-postgres.js"; + +type Item = { queue: Queue | null }; +type Queue = { readonly length: number; push(item: Item): Item; shift(): Item | undefined; remove(item: Item): Item | null }; + +const simulatedQueries = Number(process.env.SIMULATED_QUERIES ?? 1_000_000); +const poolQueries = Number(process.env.QUERIES ?? 200_000); +const driverRoot = path.resolve(path.dirname(createRequire(import.meta.url).resolve("postgres")), "../.."); +const Queue: () => Queue = (await import(pathToFileURL(path.join(driverRoot, "src/queue.js")).href)).default; + +function simulate() { + const open = Queue(); + const busy = Queue(); + const move = (c: Item, queue: Queue) => { + c.queue?.remove(c); + queue.push(c); + c.queue = queue; + }; + for (let id = 0; id < 117; id++) move({ queue: null }, open); + const running: Item[] = new Array(8); + const windows: number[] = []; + let started = performance.now(); + for (let query = 1; query <= simulatedQueries; query++) { + const c = open.shift()!; + move(c, busy); + const slot = query % running.length; + if (running[slot]) move(running[slot], open); + running[slot] = c; + if (query % (simulatedQueries / 5) === 0) { + windows.push(Number((((performance.now() - started) * 1000) / (simulatedQueries / 5)).toFixed(3))); + started = performance.now(); + } + } + return { queries: simulatedQueries, connections: 117, inFlight: 8, microsPerQueryByWindow: windows }; +} + +const temporary = process.env.DATABASE_URL ? null : await startEmbeddedPostgresTestDatabase("postgres-queue-benchmark-"); +try { + const simulation = simulate(); + const { stdout } = await promisify(execFile)(process.execPath, [ + fileURLToPath(new URL("../src/__fixtures__/postgres-queue-pool.mjs", import.meta.url)), + ], { + env: { + ...process.env, + TEST_DATABASE_URL: process.env.DATABASE_URL ?? temporary!.connectionString, + QUERIES: String(poolQueries), + WINDOWS: "10", + MEASURE_SCANS: "0", + }, + timeout: 600_000, + }); + const pool = JSON.parse(stdout) as { windows: Array<{ cpuMicrosPerQuery: number; wallMicrosPerQuery: number }> }; + console.log(JSON.stringify({ + simulation, + pool: { + ...pool, + windows: undefined, + cpuMicrosPerQueryByWindow: pool.windows.map((window) => window.cpuMicrosPerQuery), + wallMicrosPerQueryByWindow: pool.windows.map((window) => window.wallMicrosPerQuery), + }, + })); +} finally { + await temporary?.cleanup(); +} diff --git a/packages/db/src/__fixtures__/postgres-queue-pool.mjs b/packages/db/src/__fixtures__/postgres-queue-pool.mjs new file mode 100644 index 00000000000..7058009ca75 --- /dev/null +++ b/packages/db/src/__fixtures__/postgres-queue-pool.mjs @@ -0,0 +1,60 @@ +import { createRequire } from "node:module"; + +const queries = Number(process.env.QUERIES ?? 20_000); +const connections = Number(process.env.CONNECTIONS ?? 24); +const concurrency = Number(process.env.CONCURRENCY ?? 8); +const windows = Number(process.env.WINDOWS ?? 4); +const measured = process.env.MEASURE_SCANS !== "0"; + +const scans = { max: 0 }; +const indexOf = Array.prototype.indexOf; +if (measured) { + Array.prototype.indexOf = function (item, from) { + if (item && typeof item === "object" && "idleTimer" in item && "execute" in item) { + scans.max = Math.max(scans.max, this.length - Math.max(0, from ?? 0)); + } + return indexOf.call(this, item, from); + }; +} + +const postgres = process.env.DRIVER_FORMAT === "cjs" + ? createRequire(import.meta.url)("postgres") + : (await import("postgres")).default; +const sql = postgres(process.env.TEST_DATABASE_URL, { + max: connections, + idle_timeout: 0, + max_lifetime: 0, + connection: { application_name: "driver-queue-pool" }, + onnotice() {}, +}); + +try { + await Promise.all(Array.from({ length: connections }, () => sql`select pg_sleep(0.05)`)); + const [{ count }] = await sql`select count(*)::int as count from pg_stat_activity where application_name = 'driver-queue-pool'`; + if (count !== connections) throw new Error(`expected ${connections} open connections, found ${count}`); + + const perWindow = Math.floor(queries / windows); + const results = []; + for (let window = 0; window < windows; window++) { + scans.max = 0; + let remaining = perWindow; + const cpu = process.cpuUsage(); + const started = performance.now(); + await Promise.all(Array.from({ length: concurrency }, async () => { + while (remaining-- > 0) { + const [row] = await sql`select 1 as value`; + if (row.value !== 1) throw new Error("unexpected result"); + } + })); + const used = process.cpuUsage(cpu); + results.push({ + cpuMicrosPerQuery: Number(((used.user + used.system) / perWindow).toFixed(2)), + wallMicrosPerQuery: Number((((performance.now() - started) * 1000) / perWindow).toFixed(2)), + maxScan: scans.max, + }); + } + console.log(JSON.stringify({ queries: perWindow * windows, connections, concurrency, windows: results })); +} finally { + Array.prototype.indexOf = indexOf; + await sql.end({ timeout: 1 }); +} diff --git a/packages/db/src/postgres-queue-pool.test.ts b/packages/db/src/postgres-queue-pool.test.ts new file mode 100644 index 00000000000..787db398a42 --- /dev/null +++ b/packages/db/src/postgres-queue-pool.test.ts @@ -0,0 +1,43 @@ +import { execFile } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, + type EmbeddedPostgresTestDatabase, +} from "./test-embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const run = promisify(execFile); +const fixture = fileURLToPath(new URL("./__fixtures__/postgres-queue-pool.mjs", import.meta.url)); + +describe.skipIf(!support.supported)("postgres connection queue in a busy pool", () => { + let database: EmbeddedPostgresTestDatabase; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-driver-queue-pool-"); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { await database?.cleanup(); }); + + for (const format of ["esm", "cjs"]) { + it(`${format}: dispatching a query scans only live connections while idle ones stay open`, async () => { + const connections = 24; + const { stdout, stderr } = await run(process.execPath, [fixture], { + env: { + ...process.env, + TEST_DATABASE_URL: database.connectionString, + DRIVER_FORMAT: format, + QUERIES: "20000", + CONNECTIONS: String(connections), + CONCURRENCY: "8", + }, + timeout: 60_000, + }); + expect(stderr).toBe(""); + const result = JSON.parse(stdout) as { queries: number; windows: Array<{ maxScan: number }> }; + expect(result.queries).toBe(20_000); + for (const window of result.windows) expect(window.maxScan).toBeLessThanOrEqual(connections); + }, 70_000); + } +}); diff --git a/packages/db/src/postgres-queue.test.ts b/packages/db/src/postgres-queue.test.ts new file mode 100644 index 00000000000..4ec4717cc43 --- /dev/null +++ b/packages/db/src/postgres-queue.test.ts @@ -0,0 +1,145 @@ +import { createRequire } from "node:module"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { describe, expect, it } from "vitest"; + +type Queue = { + readonly length: number; + push(item: T): T; + shift(): T | undefined; + remove(item: T): T | null; +}; +type QueueFactory = (initial?: T[]) => Queue; + +const require = createRequire(import.meta.url); +const driverRoot = path.resolve(path.dirname(require.resolve("postgres")), "../.."); +const builds: Array<[string, () => Promise]> = [ + ["esm", async () => (await import(pathToFileURL(path.join(driverRoot, "src/queue.js")).href)).default], + ["cjs", async () => require(path.join(driverRoot, "cjs/src/queue.js"))], +]; + +class Item { + queue: Queue | null = null; + constructor(readonly id: number) {} +} + +function random(seed: number) { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function measureBackingWork(work: (stats: { scanned: number; backing: number }) => T) { + const indexOf = Array.prototype.indexOf; + const push = Array.prototype.push; + const stats = { scanned: 0, backing: 0 }; + Array.prototype.indexOf = function (this: unknown[], item: unknown, from?: number) { + if (item instanceof Item) stats.scanned = Math.max(stats.scanned, this.length - Math.max(0, from ?? 0)); + return indexOf.call(this, item, from); + }; + Array.prototype.push = function (this: unknown[], ...items: unknown[]) { + const length = push.apply(this, items); + if (items[0] instanceof Item) stats.backing = Math.max(stats.backing, length); + return length; + }; + try { + return work(stats); + } finally { + Array.prototype.indexOf = indexOf; + Array.prototype.push = push; + } +} + +describe.each(builds)("postgres.js connection queue (%s)", (_format, load) => { + it("keeps FIFO order, length and remove results", async () => { + const Queue = await load(); + const [a, b, c, d] = [1, 2, 3, 4].map((id) => new Item(id)); + const initial = [a, b]; + const queue = Queue(initial); + initial.push(c); + expect(queue.length).toBe(2); + expect(queue.push(c)).toBe(c); + expect(queue.push(d)).toBe(d); + expect(queue.remove(c)).toBe(c); + expect(queue.remove(c)).toBeNull(); + expect(queue.remove(new Item(9))).toBeNull(); + expect(queue.length).toBe(3); + expect(queue.shift()).toBe(a); + expect(queue.remove(a)).toBeNull(); + expect(queue.shift()).toBe(b); + expect(queue.shift()).toBe(d); + expect(queue.length).toBe(0); + expect(queue.shift()).toBeUndefined(); + expect(queue.length).toBe(0); + expect(queue.remove(a)).toBeNull(); + queue.push(a); + expect(queue.length).toBe(1); + expect(queue.shift()).toBe(a); + }); + + it("matches a plain array queue across random interleavings", async () => { + const Queue = await load(); + const next = random(21_595); + const queue = Queue(); + const model: Item[] = []; + const removed: Item[] = []; + let created = 0; + for (let step = 0; step < 300_000; step++) { + const target = [4, 150, 2_500][Math.floor(step / 20_000) % 3]; + const roll = next(); + if (roll < (model.length < target ? 0.55 : 0.4)) { + const item = removed.length && next() < 0.3 ? removed.pop()! : new Item(created++); + expect(queue.push(item)).toBe(item); + model.push(item); + } else if (roll < 0.9) { + expect(queue.shift()).toBe(model.shift()); + } else if (roll < 0.97 && model.length) { + const item = model[Math.floor(next() * model.length)]; + expect(queue.remove(item)).toBe(item); + model.splice(model.indexOf(item), 1); + removed.push(item); + } else { + expect(queue.remove(removed[removed.length - 1] ?? new Item(-1))).toBeNull(); + } + expect(queue.length).toBe(model.length); + } + while (model.length) expect(queue.shift()).toBe(model.shift()); + expect(queue.length).toBe(0); + }); + + it("keeps per-query work bounded by live connections when the open queue never drains", async () => { + const Queue = await load(); + const connections = 117; + const inFlight = 8; + const queries = 1_000_000; + const limit = { scanned: connections + inFlight, backing: 2 * connections + 1_100 }; + const open = Queue(); + const busy = Queue(); + const move = (c: Item, queue: Queue) => { + c.queue?.remove(c); + queue.push(c); + c.queue = queue; + }; + const stats = measureBackingWork((stats) => { + for (let id = 0; id < connections; id++) move(new Item(id), open); + const running: Item[] = new Array(inFlight); + for (let query = 0; query < queries; query++) { + const c = open.shift()!; + move(c, busy); + const slot = query % inFlight; + if (running[slot]) move(running[slot], open); + running[slot] = c; + if (stats.backing > 10 * limit.backing) break; + } + return { ...stats }; + }); + expect(open.length + busy.length).toBe(connections); + expect(stats.scanned).toBeLessThanOrEqual(limit.scanned); + expect(stats.backing).toBeLessThanOrEqual(limit.backing); + }); +}); diff --git a/patches/postgres@3.4.9.patch b/patches/postgres@3.4.9.patch index 20854f067b8..b9cd7a82c8f 100644 --- a/patches/postgres@3.4.9.patch +++ b/patches/postgres@3.4.9.patch @@ -102,6 +102,34 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..04dded5c7e2cdc34ac01b29a87cc9324 c.queue === full ? queries.push(q) : c.execute(q) || move(c, full) +diff --git a/cjs/src/queue.js b/cjs/src/queue.js +index 8438f5da92cf7637d98a33491d75c75b1c817c25..1c9a330fa173ecae84219055368cf630feadbda2 100644 +--- a/cjs/src/queue.js ++++ b/cjs/src/queue.js +@@ -9,10 +9,10 @@ function Queue(initial = []) { + return xs.length - index + }, + remove: (x) => { +- const index = xs.indexOf(x) +- return index === -1 ++ const at = xs.indexOf(x, index) ++ return at === -1 + ? null +- : (xs.splice(index, 1), x) ++ : (xs.splice(at, 1), x) + }, + push: (x) => (xs.push(x), x), + shift: () => { +@@ -21,6 +21,9 @@ function Queue(initial = []) { + if (index === xs.length) { + index = 0 + xs = [] ++ } else if (index > 1024 && index * 2 > xs.length) { ++ xs = xs.slice(index) ++ index = 0 + } else { + xs[index - 1] = undefined + } diff --git a/src/connection.js b/src/connection.js index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..0a4c4cc185f14afa30c7c6a294bafe689e685683 100644 --- a/src/connection.js @@ -206,3 +234,31 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..f0888986add8ba02c8853f792ae42dd1 c.queue === full ? queries.push(q) : c.execute(q) || move(c, full) +diff --git a/src/queue.js b/src/queue.js +index c4ef97164f057db99dce1b9af3401dbb1af37e31..46e7ade55c0a3250137a21117c03ce9166b40bc2 100644 +--- a/src/queue.js ++++ b/src/queue.js +@@ -9,10 +9,10 @@ function Queue(initial = []) { + return xs.length - index + }, + remove: (x) => { +- const index = xs.indexOf(x) +- return index === -1 ++ const at = xs.indexOf(x, index) ++ return at === -1 + ? null +- : (xs.splice(index, 1), x) ++ : (xs.splice(at, 1), x) + }, + push: (x) => (xs.push(x), x), + shift: () => { +@@ -21,6 +21,9 @@ function Queue(initial = []) { + if (index === xs.length) { + index = 0 + xs = [] ++ } else if (index > 1024 && index * 2 > xs.length) { ++ xs = xs.slice(index) ++ index = 0 + } else { + xs[index - 1] = undefined + } From 0b2b7aa737dfeee4b2e57287306bd5d3060a7e98 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:49:06 +0000 Subject: [PATCH 3/6] chore(lockfile): refresh pnpm lockfiles (#21604) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip uses a dependency lock for reproducible builds. > - Dependency changes on master need matching lock entries. > - Paid eval reports also pin a reviewed offline correction. > - Reports must install before paid model work starts. > - This automated PR keeps the lock and report proof together. ## Linked Issues or Issue Description **What happened?** Dependency manifests on master changed after the last committed lock refresh. **Expected behavior** Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. **Steps to reproduce** Run a frozen install before and after this lock refresh. ## What Changed - Refresh the dependency lock from the manifests on master. - Refresh the sandbox provider lockfiles from their manifests on master. - Include the matching offline report correction and hashes. - Resync the SDK public source proof's lock pins from the refreshed lock. ## Verification - Pinned pnpm resolution completed with lifecycle scripts disabled. - The report proof refresh accepted the reviewed committed baseline. - The workflow rejected changes outside the lock and report proof files. ## Risks The lockfile bot merges this PR without CI or review when every added package version is at least 3 days old on npm. Otherwise the PR waits for a maintainer, and the daily refresh tries again. The bot merges only the exact commit this workflow generated from manifests already reviewed on master. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. ## Model Used None — generated by pnpm and the deterministic report-lock updater. ## Checklist - [x] Thinking path and problem description included - [x] Generated lock and matching report proof included - [x] Release-age gate decides between bot merge and maintainer review Co-authored-by: lockfile-bot --- pnpm-lock.yaml | 34 ++-- tests/runner-e2e/report-lock.json | 6 +- tests/runner-e2e/report-lock.patch | 161 +++++++++++++++--- .../runner-e2e/source-sdk-public-inputs.json | 4 +- 4 files changed, 162 insertions(+), 43 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 48c18aed9df..05644099489 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -46,7 +46,7 @@ patchedDependencies: hash: 55uhvnotpqyiy37rn3pqpukhei path: patches/embedded-postgres@18.1.0-beta.16.patch postgres@3.4.9: - hash: eq2va53hqrnbmnygljtudtaoge + hash: 7s673zkrux4f7d7y4kyzk7opyu path: patches/postgres@3.4.9.patch importers: @@ -139,7 +139,7 @@ importers: version: 17.4.2 drizzle-orm: specifier: 0.45.2 - version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) + version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) embedded-postgres: specifier: ^18.1.0-beta.16 version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) @@ -411,13 +411,13 @@ importers: version: link:../shared drizzle-orm: specifier: ^0.45.2 - version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) + version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) embedded-postgres: specifier: ^18.1.0-beta.16 version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) postgres: specifier: ^3.4.9 - version: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) + version: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) devDependencies: '@types/node': specifier: ^24.0.0 @@ -1018,7 +1018,7 @@ importers: version: 2.2.0(@grpc/grpc-js@1.14.5)(nice-grpc-common@2.0.4)(nice-grpc@2.1.17) '@vercel/connect': specifier: 2.3.3 - version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) + version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) acorn: specifier: 8.18.0 version: 8.18.0 @@ -1036,7 +1036,7 @@ importers: version: 3.0.1(ajv@8.20.0) better-auth: specifier: 1.7.16 - version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) + version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) chat: specifier: 4.39.0 version: 4.39.0(ai@7.0.130(zod@4.6.7))(zod@4.6.7) @@ -1057,7 +1057,7 @@ importers: version: 17.4.2 drizzle-orm: specifier: ^0.45.2 - version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) + version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) embedded-postgres: specifier: ^18.1.0-beta.16 version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) @@ -10089,12 +10089,12 @@ snapshots: optionalDependencies: '@opentelemetry/api': 1.9.1 - '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))': + '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))': dependencies: '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) '@better-auth/utils': 0.5.1 optionalDependencies: - drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) + drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) '@better-auth/kysely-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5)': dependencies: @@ -14013,14 +14013,14 @@ snapshots: dependencies: execa: 5.1.1 - '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': + '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': dependencies: '@vercel/oidc': 3.8.9 optionalDependencies: '@chat-adapter/slack': 4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7) '@modelcontextprotocol/sdk': 1.31.0(zod@4.6.7) ai: 7.0.130(zod@4.6.7) - better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) + better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) '@vercel/oidc@3.2.0': {} @@ -14279,10 +14279,10 @@ snapshots: before-after-hook@4.0.0: {} - better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): + better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): dependencies: '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) - '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge))) + '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu))) '@better-auth/kysely-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5) '@better-auth/memory-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) '@better-auth/mongo-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) @@ -14300,7 +14300,7 @@ snapshots: zod: 4.6.7 optionalDependencies: drizzle-kit: 0.31.11 - drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) + drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) pg: 8.18.0 react: 19.2.8 react-dom: 19.2.8(react@19.2.8) @@ -14895,12 +14895,12 @@ snapshots: esbuild: 0.25.12 tsx: 4.23.15 - drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)): + drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)): optionalDependencies: '@opentelemetry/api': 1.9.1 kysely: 0.29.5 pg: 8.18.0 - postgres: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) + postgres: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) dunder-proto@1.0.1: dependencies: @@ -16813,7 +16813,7 @@ snapshots: dependencies: xtend: 4.0.2 - postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge): {} + postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu): {} powershell-utils@0.1.0: {} diff --git a/tests/runner-e2e/report-lock.json b/tests/runner-e2e/report-lock.json index 3b2bd453ba6..33962ba7299 100644 --- a/tests/runner-e2e/report-lock.json +++ b/tests/runner-e2e/report-lock.json @@ -1,6 +1,6 @@ { - "inputSha256": "33360fbf59530ddddd735eba7dbcbcdf05797b68b6418799e6470265c875accb", - "outputSha256": "a56b6acc8743f6163d4af60b072d66c694c1061f4242f499c361d85fce318f3a", - "patchSha256": "bdc263636dcb54cd914af76cdffe74823d1c223948d49f2ce7482350082ad514", + "inputSha256": "a56b6acc8743f6163d4af60b072d66c694c1061f4242f499c361d85fce318f3a", + "outputSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", + "patchSha256": "325e0a90b5cb215a361ab3c3d59935161367b09b59f361080fa292a96566c95a", "basis": "Generated with the trusted master lockfile refresh. Review this offline correction and its hashes with the dependency changes." } diff --git a/tests/runner-e2e/report-lock.patch b/tests/runner-e2e/report-lock.patch index f56f99ad468..98e9fc14c63 100644 --- a/tests/runner-e2e/report-lock.patch +++ b/tests/runner-e2e/report-lock.patch @@ -1,24 +1,143 @@ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml -index 678a3412..48c18aed 100644 +index 48c18aed..05644099 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml -@@ -515,6 +515,9 @@ importers: - '@agentclientprotocol/codex-acp': - specifier: 1.6.2 - version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) -+ '@agentclientprotocol/sdk': -+ specifier: 1.9.0 -+ version: 1.9.0(zod@4.6.7) - '@openai/codex': - specifier: 0.160.0 - version: 0.160.0 -@@ -905,6 +908,9 @@ importers: - '@agentclientprotocol/codex-acp': - specifier: 1.6.2 - version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) -+ '@agentclientprotocol/sdk': -+ specifier: 1.9.0 -+ version: 1.9.0(zod@4.6.7) - '@ai-sdk/amazon-bedrock': - specifier: 5.0.113 - version: 5.0.113(zod@4.6.7) +@@ -46,7 +46,7 @@ patchedDependencies: + hash: 55uhvnotpqyiy37rn3pqpukhei + path: patches/embedded-postgres@18.1.0-beta.16.patch + postgres@3.4.9: +- hash: eq2va53hqrnbmnygljtudtaoge ++ hash: 7s673zkrux4f7d7y4kyzk7opyu + path: patches/postgres@3.4.9.patch + + importers: +@@ -139,7 +139,7 @@ importers: + version: 17.4.2 + drizzle-orm: + specifier: 0.45.2 +- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) ++ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) + embedded-postgres: + specifier: ^18.1.0-beta.16 + version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) +@@ -411,13 +411,13 @@ importers: + version: link:../shared + drizzle-orm: + specifier: ^0.45.2 +- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) ++ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) + embedded-postgres: + specifier: ^18.1.0-beta.16 + version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) + postgres: + specifier: ^3.4.9 +- version: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) ++ version: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) + devDependencies: + '@types/node': + specifier: ^24.0.0 +@@ -1018,7 +1018,7 @@ importers: + version: 2.2.0(@grpc/grpc-js@1.14.5)(nice-grpc-common@2.0.4)(nice-grpc@2.1.17) + '@vercel/connect': + specifier: 2.3.3 +- version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) ++ version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) + acorn: + specifier: 8.18.0 + version: 8.18.0 +@@ -1036,7 +1036,7 @@ importers: + version: 3.0.1(ajv@8.20.0) + better-auth: + specifier: 1.7.16 +- version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) ++ version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) + chat: + specifier: 4.39.0 + version: 4.39.0(ai@7.0.130(zod@4.6.7))(zod@4.6.7) +@@ -1057,7 +1057,7 @@ importers: + version: 17.4.2 + drizzle-orm: + specifier: ^0.45.2 +- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) ++ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) + embedded-postgres: + specifier: ^18.1.0-beta.16 + version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) +@@ -10089,12 +10089,12 @@ snapshots: + optionalDependencies: + '@opentelemetry/api': 1.9.1 + +- '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))': ++ '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))': + dependencies: + '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) + '@better-auth/utils': 0.5.1 + optionalDependencies: +- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) ++ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) + + '@better-auth/kysely-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5)': + dependencies: +@@ -14013,14 +14013,14 @@ snapshots: + dependencies: + execa: 5.1.1 + +- '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': ++ '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': + dependencies: + '@vercel/oidc': 3.8.9 + optionalDependencies: + '@chat-adapter/slack': 4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7) + '@modelcontextprotocol/sdk': 1.31.0(zod@4.6.7) + ai: 7.0.130(zod@4.6.7) +- better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) ++ better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) + + '@vercel/oidc@3.2.0': {} + +@@ -14279,10 +14279,10 @@ snapshots: + + before-after-hook@4.0.0: {} + +- better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): ++ better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): + dependencies: + '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) +- '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge))) ++ '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu))) + '@better-auth/kysely-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5) + '@better-auth/memory-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) + '@better-auth/mongo-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) +@@ -14300,7 +14300,7 @@ snapshots: + zod: 4.6.7 + optionalDependencies: + drizzle-kit: 0.31.11 +- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) ++ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) + pg: 8.18.0 + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) +@@ -14895,12 +14895,12 @@ snapshots: + esbuild: 0.25.12 + tsx: 4.23.15 + +- drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)): ++ drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)): + optionalDependencies: + '@opentelemetry/api': 1.9.1 + kysely: 0.29.5 + pg: 8.18.0 +- postgres: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) ++ postgres: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) + + dunder-proto@1.0.1: + dependencies: +@@ -16813,7 +16813,7 @@ snapshots: + dependencies: + xtend: 4.0.2 + +- postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge): {} ++ postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu): {} + + powershell-utils@0.1.0: {} + diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 46250ab43be..5aa706fe695 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -541,12 +541,12 @@ "packages/shared/src/worktree-seed-source.test.ts": "852856b1b5b8f4d0d3dada6501886fe50a2c2dde", "packages/shared/src/worktree-seed-source.ts": "3d1a09bed2d969feabef3400ff84fd499c1408f4", "packages/shared/tsconfig.json": "5a24989cd30dcf3749ca7e60d4e83d6ddbb14714", - "pnpm-lock.yaml": "48c18aed9dfd8e559d8a7e97d5c8938cbd25b6d1", + "pnpm-lock.yaml": "05644099489b569367f982b14bb412439ba1b207", "scripts/ensure-plugin-build-deps.mjs": "356e0e0f80e50890067027da3003485cf5d2ccbe", "tsconfig.base.json": "2d0e41f723add0c678936eb9ae1c60eab710f8e0", "tsconfig.json": "994ee490fb97be7cc0954f4dfd88cf0723290e6c" }, - "lockSha256": "a56b6acc8743f6163d4af60b072d66c694c1061f4242f499c361d85fce318f3a", + "lockSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", "compilerPackageSha256": "3722b30210616a13a3213ded11575ba6b2dbab10c32a5ef67afca8513e27017e", "parserPackageSha256": "6d6a65b879cd7cd249a4367c0b57cce00e78c728de45056ac2a5ca1d1f528d1a", "parserEntrySha256": "6969920ae0610df927b6b3e675d1309372c268e36d391652af8e3e0183cbe8f8", From 0ab63cf4d91951e92c2c171ba43e07d0d12e7ef0 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:56:51 -0600 Subject: [PATCH 4/6] fix(restart-chaos): ignore a done the server rejected as incomplete (#21598) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness runs staging-mix waves and grades each task for duplicated side effects and extra turns > - The grader counts a run as a completer when its last accepted result reports `done` > - The server can reject that `done` as incomplete. The status arbiter then queues a same-agent continuation wake with key `native-completion-incomplete` > - The grader ignores the rejection. It reports a false duplicate completion and anchors completion on the rejected run, so the continuation run that finished the work shows as an extra turn > - This pull request marks a `done` as rejected when a `native-completion-incomplete` wake for the issue follows it, and ignores that `done` unless the same run posted the DONE comment > - The benefit is that wave results stop reporting false duplicates and false extra turns, so real regressions stay visible ## Linked Issues or Issue Description **What happened?** In wave `w-20261114T081656-s7105`, task t005, run d80d3ab3 reported `done` with no DONE comment. The server rejected it as incomplete and queued a `native-completion-incomplete` continuation wake. Run a777038c then posted the only DONE comment and completed the issue. The grader reported "duplicate completion: runs d80d3ab3, a777038c" and listed a777038c as an extra turn. **Expected behavior** The grader reports one completer (a777038c), anchors completion on a777038c, and lists no extra turn. **Steps to reproduce** 1. Build wake evidence where run A has an accepted `done` result and no DONE comment. 2. Add a continuation wake with payload `continuationIdempotencyKey: "native-completion-incomplete"` created after A's result. 3. Add run B from that wake. B posts the DONE comment and reports `done`. 4. Grade the task with `gradeStagingMix`, `completedAtAnchor` and `runsAfterDone`. **Additional context** This is a test-harness change only. It changes no product code. ## What Changed - `tests/restart-chaos/follow-up-delivery.ts`: add `rejectedDoneRuns`. It attributes each `native-completion-incomplete` wake to the latest run whose accepted `done` came at or before the wake. - `tests/restart-chaos/wake-evidence.ts` (`completionEvidence`) and `tests/restart-chaos/staging-mix-retry.ts` (`evidenceCompletion`): set a new optional `doneRejected` flag on each completion run. - `tests/restart-chaos/staging-mix.ts`: `completedAtAnchor` and `completionRunIds` ignore a rejected `done`, unless that run posted the DONE comment. - `tests/restart-chaos/staging-mix-retry.test.ts`: add the t005 red/green test, a test for a rejected run that posted DONE itself, and a G5c t004 guard. - `tests/restart-chaos/README.md`: document the rule. ## Verification - Red on master, green with the fix: `a done the server rejected as incomplete > anchors on the run that finished the work, with one completer and no extra turn (w-20261114T081656-s7105 t005)`. On master the anchor is the rejected run's result time (1794646168026) instead of the finisher's (1794646218506). - Guard, green on master and with the fix: `a done the server rejected as incomplete > keeps a run woken by recovery after a real completion as an extra turn and a duplicate completion (G5c t004)`. - `npx vitest run --config tests/restart-chaos/vitest.config.ts --maxWorkers=3`: 71 files, 816 tests pass. - `tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean. - The real t005 evidence from the wave now grades as one completer (a777038c) with no extra turns. - `pnpm verify` exits 2 because `follow-up-delivery.ts` is a global CI input. Required CI supplies the broad coverage. ## Risks - Low risk. The change affects only the restart-chaos grader. - The grader trusts the wake key. If the server queued `native-completion-incomplete` for another reason, the grader would skip the latest `done` before it. The server queues this key only from the incomplete branch of `arbitrateNativeStatus`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- tests/restart-chaos/README.md | 8 +- tests/restart-chaos/follow-up-delivery.ts | 16 ++++ tests/restart-chaos/staging-mix-retry.test.ts | 88 +++++++++++++++++++ tests/restart-chaos/staging-mix-retry.ts | 6 +- tests/restart-chaos/staging-mix.ts | 14 ++- tests/restart-chaos/wake-evidence.ts | 6 +- 6 files changed, 128 insertions(+), 10 deletions(-) diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index 16a8f0e517d..46b5d94723f 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -1647,11 +1647,15 @@ listed under "Follow-ups the running turn did not receive, answered in a later r server's delivery rule (`task_history.read`, cited evidence, child-result reads) is covered by the server's own tests. `completion_once` stays the independent side-effect check. The first run that reported completion is always the -baseline. A later completion counts as a duplicate unless its run answered a comment as above. +baseline. A later completion counts as a duplicate unless its run answered a comment as above. A `done` result that the +server rejected as incomplete is not a completion: the server shows the rejection by queueing a same-agent continuation +wake with key `native-completion-incomplete` for the issue, and the latest accepted result before that wake is the +`done`. A wake that follows a later result, such as a `yielded` one, does not reject an earlier `done`. Such a run counts only when it posted the +DONE comment itself. Otherwise the continuation run that finishes the work is the baseline. The completion time comes from the product's own record, in this order: -1. the earliest accepted run result whose `reportedWorkDisposition` is `done`; +1. the earliest accepted run result whose `reportedWorkDisposition` is `done`, skipping a rejected `done` as above; 2. the issue's `completedAt`; 3. the first bare `DONE-` comment, only when neither exists. diff --git a/tests/restart-chaos/follow-up-delivery.ts b/tests/restart-chaos/follow-up-delivery.ts index 0e907b116ec..88b78754a0a 100644 --- a/tests/restart-chaos/follow-up-delivery.ts +++ b/tests/restart-chaos/follow-up-delivery.ts @@ -49,6 +49,22 @@ export function laterAnswers(evidence: { runs?: readonly DeliveryRun[]; wakes?: return answers; } +export const COMPLETION_INCOMPLETE_KEY = "native-completion-incomplete"; + +export function rejectedDoneRuns(evidence: { runs?: ReadonlyArray<{ runId: string | null; acceptedDisposition?: string | null; acceptedAt?: number | null }>; + wakes?: readonly DeliveryWake[] } | null): Set { + const rejected = new Set(); + const results = (evidence?.runs ?? []).flatMap(run => run.runId && run.acceptedDisposition && typeof run.acceptedAt === "number" + ? [{ runId: run.runId, disposition: run.acceptedDisposition, acceptedAt: run.acceptedAt }] : []); + for (const wake of evidence?.wakes ?? []) { + const at = wake.createdAt; + if (typeof at !== "number" || object(wake.payload).continuationIdempotencyKey !== COMPLETION_INCOMPLETE_KEY) continue; + const cause = results.filter(run => run.acceptedAt <= at).sort((a, b) => b.acceptedAt - a.acceptedAt)[0]; + if (cause?.disposition === "done") rejected.add(cause.runId); + } + return rejected; +} + function percentile(values: readonly number[], fraction: number): number | null { if (!values.length) return null; const sorted = [...values].sort((a, b) => a - b); diff --git a/tests/restart-chaos/staging-mix-retry.test.ts b/tests/restart-chaos/staging-mix-retry.test.ts index 136314815c2..8e2dd18b5a3 100644 --- a/tests/restart-chaos/staging-mix-retry.test.ts +++ b/tests/restart-chaos/staging-mix-retry.test.ts @@ -9,6 +9,7 @@ import { retryAfterSettleStage, runsAfterDone, shouldClickRetryAfterSettle, stagingMixHeadline, summarizeStagingMix, type RetryStageObserver, type WakeEvidenceFile, } from "./staging-mix-retry.js"; import type { OracleArtifacts, TaskPlan, TaskRecord, TaskSample } from "./types.js"; +import { completionEvidence } from "./wake-evidence.js"; const wave = (argv: string[]) => { const command = parseCommand(argv); @@ -264,6 +265,93 @@ describe("staging-mix runs after the task completed", () => { }); }); +describe("a done the server rejected as incomplete", () => { + const nonce = "8c82aea3"; + const rejected = "d80d3ab3-e4ea-4959-b65b-329632dfd684", finisher = "a777038c-095d-438d-96fc-e341efd3d23d"; + const incomplete = { continuationKind: "same_agent", continuationIdempotencyKey: "native-completion-incomplete" }; + const t005 = (): WakeEvidenceFile => ({ + completedAt: 1_794_646_221_835, + runs: [{ runId: rejected, createdAt: 1_794_644_311_531, startedAt: 1_794_644_311_621, invocationSource: "assignment", triggerDetail: "system", + wakeupRequestId: "be501b49", acceptedDisposition: "done", acceptedAt: 1_794_646_168_026 }, + { runId: finisher, createdAt: 1_794_646_171_317, startedAt: 1_794_646_171_426, invocationSource: "automation", triggerDetail: "system", + wakeupRequestId: "68fde0a3", acceptedDisposition: "done", acceptedAt: 1_794_646_218_506 }], + wakes: [{ id: "be501b49", reason: "issue_assigned", source: "assignment", triggerDetail: "system", requestedByActorType: "user", requestedByActorId: "local-board", + createdAt: 1_794_644_311_531 }, + { id: "3f3716f3", reason: "issue_status_changed", source: "automation", triggerDetail: "system", requestedByActorType: "system", requestedByActorId: null, + createdAt: 1_794_646_171_247, payload: incomplete }, + { id: "68fde0a3", reason: "issue_status_changed", source: "automation", triggerDetail: "system", requestedByActorType: "system", requestedByActorId: null, + createdAt: 1_794_646_171_317, payload: incomplete }], + }); + const posted = commentEvidence([ + { body: "All 17 rounds are complete and verified.", authorAgentId: "a", createdByRunId: finisher, createdAt: "2026-11-14T08:50:22.890Z" }, + { body: doneMarker(nonce), authorAgentId: "a", createdByRunId: finisher, createdAt: "2026-11-14T08:49:58.554Z" }, + { body: "Completed and verified all 17 rounds exactly once in `ledger`.", authorAgentId: "a", createdByRunId: rejected, createdAt: "2026-11-14T08:49:32.345Z" }]); + const completionOnce = (comments: typeof posted, completion: CompletionEvidence) => gradeStagingMix(nonce, + { turnMinutes: 15, rounds: 4, subtasks: 0, followUpAfterMs: null, arriveAtMs: 0, holdMs: 0 }, + { issueStatus: "done", documents: { ledger: ledger(nonce, 4) }, agentComments: [], files: {}, commands: {}, workspacePath: null, + stagingMix: { followUp: null, followUpErrors: [], retries: [], comments, completion } }).checks.find(check => check.name === "completion_once")!; + + it("anchors on the run that finished the work, with one completer and no extra turn (w-20261114T081656-s7105 t005)", () => { + const evidence = t005(); + for (const completion of [evidenceCompletion(evidence)!, completionEvidence({ completedAt: evidence.completedAt!, wakes: evidence.wakes, runs: evidence.runs!.map(run => + ({ ...run, acceptedDisposition: run.acceptedDisposition ?? null, acceptedAt: run.acceptedAt ?? null })) })]) { + const anchor = completedAtAnchor(completion, posted, nonce); + expect(anchor).toEqual({ at: 1_794_646_218_506, source: "accepted_result" }); + expect(completionRunIds(posted, nonce, completion)).toEqual([finisher]); + expect(runsAfterDone("t005", evidence, anchor).started).toEqual([]); + expect(completionOnce(posted, completion)).toMatchObject({ ok: true, detail: "runs=1" }); + } + }); + + it("still counts a rejected run that posted the DONE comment itself", () => { + const evidence = t005(); + const comments = [...posted, { body: doneMarker(nonce), runId: rejected, createdAt: 1_794_646_160_000 }]; + expect(completionRunIds(comments, nonce, evidenceCompletion(evidence))).toEqual([rejected, finisher]); + }); + + it("keeps a run woken by recovery after a real completion as an extra turn and a duplicate completion (G5c t004)", () => { + const done = "4a4a4a4a-done", woken = "5b5b5b5b-woken"; + const evidence: WakeEvidenceFile = { + completedAt: 10_000, + runs: [{ runId: done, createdAt: 1_000, startedAt: 1_100, invocationSource: "automation", triggerDetail: null, wakeupRequestId: "w1", acceptedDisposition: "done", acceptedAt: 9_900 }, + { runId: woken, createdAt: 20_000, startedAt: 20_100, invocationSource: "automation", triggerDetail: "system", wakeupRequestId: "w2", acceptedDisposition: "done", acceptedAt: 21_000 }], + wakes: [{ id: "w1", reason: "issue_status_changed", source: "automation", triggerDetail: null, requestedByActorType: "system", requestedByActorId: null, createdAt: 1_000, + payload: incomplete }, + { id: "w2", reason: "issue_recovery_action_restored", source: "automation", triggerDetail: "system", requestedByActorType: "system", requestedByActorId: "sweep", + createdAt: 20_000 }], + }; + const comments = [{ body: doneMarker(nonce), runId: done, createdAt: 9_800 }]; + const completion = evidenceCompletion(evidence)!; + const anchor = completedAtAnchor(completion, comments, nonce); + expect(anchor).toEqual({ at: 9_900, source: "accepted_result" }); + expect(runsAfterDone("t004", evidence, anchor).started.map(turn => [turn.runId, turn.wakeReason])).toEqual([[woken, "issue_recovery_action_restored"]]); + expect(completionOnce(comments, completion)).toMatchObject({ ok: false, detail: "duplicate completion: runs 4a4a4a4a, 5b5b5b5b each reported completion" }); + }); + + it("keeps a real done when a later recovery run yields with an incomplete wake, and still fails the extra run", () => { + const done = "4a4a4a4a-done", yielded = "6c6c6c6c-yield", extra = "7d7d7d7d-extra"; + const evidence: WakeEvidenceFile = { + completedAt: 10_000, + runs: [{ runId: done, createdAt: 1_000, startedAt: 1_100, invocationSource: "assignment", triggerDetail: null, wakeupRequestId: "w1", acceptedDisposition: "done", acceptedAt: 9_900 }, + { runId: yielded, createdAt: 20_000, startedAt: 20_100, invocationSource: "automation", triggerDetail: "system", wakeupRequestId: "w2", + acceptedDisposition: "yielded", acceptedAt: 21_000 }, + { runId: extra, createdAt: 21_100, startedAt: 21_200, invocationSource: "automation", triggerDetail: "system", wakeupRequestId: "w3", + acceptedDisposition: "done", acceptedAt: 22_000 }], + wakes: [{ id: "w1", reason: "issue_assigned", source: "assignment", triggerDetail: null, requestedByActorType: "user", requestedByActorId: "u1", createdAt: 1_000 }, + { id: "w2", reason: "issue_recovery_action_restored", source: "automation", triggerDetail: "system", requestedByActorType: "system", requestedByActorId: "sweep", + createdAt: 20_000 }, + { id: "w3", reason: "issue_status_changed", source: "automation", triggerDetail: "system", requestedByActorType: "system", requestedByActorId: null, + createdAt: 21_050, payload: incomplete }], + }; + const comments: typeof posted = []; + const completion = evidenceCompletion(evidence)!; + const anchor = completedAtAnchor(completion, comments, nonce); + expect(anchor).toEqual({ at: 9_900, source: "accepted_result" }); + expect(runsAfterDone("t004", evidence, anchor).started.map(turn => turn.runId)).toEqual([yielded, extra]); + expect(completionOnce(comments, completion)).toMatchObject({ ok: false, detail: "duplicate completion: runs 4a4a4a4a, 7d7d7d7d each reported completion" }); + }); +}); + describe("a follow-up the running turn did not receive (w-20261113T052703-s7301 t010)", () => { const nonce = "bd13d3bf"; const comment = "fd278a3a-946b-44df-b62f-0e47c982aea1"; diff --git a/tests/restart-chaos/staging-mix-retry.ts b/tests/restart-chaos/staging-mix-retry.ts index 1b52d73dd5f..8d286197c19 100644 --- a/tests/restart-chaos/staging-mix-retry.ts +++ b/tests/restart-chaos/staging-mix-retry.ts @@ -6,7 +6,7 @@ import { bannerShownMs, completedAtAnchor, doneCommentsBeforeCompletion, DUPLICATE_CHECKS, firstDoneCommentAt, noteRetryBanner, type CompletionEvidence, } from "./staging-mix.js"; import type { InterruptionSample, OracleResult, TaskPlan, TaskRecord, TaskSample } from "./types.js"; -import { laterAnswers, laterAnswerWaits, type LaterAnswer } from "./follow-up-delivery.js"; +import { laterAnswers, laterAnswerWaits, rejectedDoneRuns, type LaterAnswer } from "./follow-up-delivery.js"; type Json = Record; @@ -212,8 +212,10 @@ export function evidenceCompletion(evidence: WakeEvidenceFile | null, issueCompl const fromIssue = typeof issueCompletedAt === "string" && Number.isFinite(Date.parse(issueCompletedAt)) ? Date.parse(issueCompletedAt) : null; if (!evidence && fromIssue === null) return null; const answers = laterAnswers(evidence); + const rejected = rejectedDoneRuns(evidence); return { completedAt: evidence?.completedAt ?? fromIssue, runs: (evidence?.runs ?? []).map(run => ({ runId: run.runId, startedAt: run.startedAt ?? null, - acceptedDisposition: run.acceptedDisposition ?? null, acceptedAt: run.acceptedAt ?? null, answersFollowUp: Boolean(run.runId && answers.has(run.runId)) })) }; + acceptedDisposition: run.acceptedDisposition ?? null, acceptedAt: run.acceptedAt ?? null, answersFollowUp: Boolean(run.runId && answers.has(run.runId)), + doneRejected: Boolean(run.runId && rejected.has(run.runId)) })) }; } export function runsAfterDone(taskId: string, evidence: WakeEvidenceFile | null, anchor: { at: number | null; source: string | null }, doneCommentAt: number | null = null): diff --git a/tests/restart-chaos/staging-mix.ts b/tests/restart-chaos/staging-mix.ts index 649e9667fb0..fbadcbc9c46 100644 --- a/tests/restart-chaos/staging-mix.ts +++ b/tests/restart-chaos/staging-mix.ts @@ -61,7 +61,8 @@ export interface StagingMixRecord { export interface CompletionEvidence { completedAt: number | null; - runs: Array<{ runId: string | null; startedAt: number | null; acceptedDisposition: string | null; acceptedAt: number | null; answersFollowUp?: boolean }>; + runs: Array<{ runId: string | null; startedAt: number | null; acceptedDisposition: string | null; acceptedAt: number | null; answersFollowUp?: boolean; + doneRejected?: boolean }>; } export interface RetryBanner { firstShownAt: number; lastShownAt: number; shownMs: number; visibleSince: number | null; errorCode: string | null } @@ -398,9 +399,14 @@ export function hasDispositions(completion: CompletionEvidence | null | undefine return Boolean(completion?.runs.some(run => run.acceptedDisposition !== null)); } +function countsAsDone(run: CompletionEvidence["runs"][number] | undefined, comments: readonly CommentEvidence[], nonce: string): run is CompletionEvidence["runs"][number] { + return run?.acceptedDisposition === "done" + && (!run.doneRejected || comments.some(comment => comment.runId === run.runId && isDoneComment(comment.body, nonce))); +} + export function completedAtAnchor(completion: CompletionEvidence | null | undefined, comments: readonly CommentEvidence[], nonce: string): { at: number | null; source: "accepted_result" | "completed_at" | "done_comment" | null } { - const accepted = (completion?.runs ?? []).filter(run => run.acceptedDisposition === "done" && run.acceptedAt !== null).map(run => run.acceptedAt!); + const accepted = (completion?.runs ?? []).filter(run => countsAsDone(run, comments, nonce) && run.acceptedAt !== null).map(run => run.acceptedAt!); if (accepted.length) return { at: Math.min(...accepted), source: "accepted_result" }; if (completion?.completedAt != null) return { at: completion.completedAt, source: "completed_at" }; const comment = firstDoneCommentAt(comments, nonce); @@ -415,11 +421,11 @@ export function completionRunIds(comments: readonly CommentEvidence[], nonce: st const byId = new Map(completion.runs.flatMap(run => run.runId ? [[run.runId, run] as const] : [])); const reportedAt = (runId: string) => { const run = byId.get(runId); - if (run?.acceptedDisposition === "done" && run.acceptedAt !== null) return run.acceptedAt; + if (countsAsDone(run, comments, nonce) && run.acceptedAt !== null) return run.acceptedAt; const posted = comments.filter(comment => comment.runId === runId && typeof comment.createdAt === "number").map(comment => comment.createdAt!); return posted.length ? Math.min(...posted) : run?.startedAt ?? Number.POSITIVE_INFINITY; }; - const accepted = completion.runs.filter(run => run.acceptedDisposition === "done" && run.runId).map(run => run.runId!); + const accepted = completion.runs.filter(run => countsAsDone(run, comments, nonce) && run.runId).map(run => run.runId!); const ordered = [...new Set([...accepted, ...summaries])].sort((a, b) => reportedAt(a) - reportedAt(b)); return ordered.filter((runId, index) => index === 0 || !byId.get(runId)?.answersFollowUp); } diff --git a/tests/restart-chaos/wake-evidence.ts b/tests/restart-chaos/wake-evidence.ts index 4cb126718a1..0d8793c36e6 100644 --- a/tests/restart-chaos/wake-evidence.ts +++ b/tests/restart-chaos/wake-evidence.ts @@ -4,7 +4,7 @@ import type { ServerProcessWindow } from "./multi-server.js"; import { unshiftJson, unshiftMs, type AgingShift } from "./time-faults.js"; import { ISSUE_STATUSES } from "../../packages/shared/src/constants.js"; import type { CompletionEvidence } from "./staging-mix.js"; -import { laterAnswers, type DeliveryRun, type DeliveryWake } from "./follow-up-delivery.js"; +import { laterAnswers, rejectedDoneRuns, type DeliveryRun, type DeliveryWake } from "./follow-up-delivery.js"; import { AGENT_SLOTS_FILE, agentSlotsFromRows } from "./agent-slots.js"; import { agents, createDb, type Db } from "../../packages/db/src/index.js"; import { maxConcurrentRunsSql } from "../../server/src/services/heartbeat/timer-policy.js"; @@ -168,8 +168,10 @@ export interface EvidenceObserver { export function completionEvidence(evidence: { completedAt: number | null; wakes?: readonly DeliveryWake[]; runs: ReadonlyArray }): CompletionEvidence { const answers = laterAnswers(evidence); + const rejected = rejectedDoneRuns(evidence); return { completedAt: evidence.completedAt, runs: evidence.runs.map(run => ({ runId: run.runId, startedAt: run.startedAt ?? null, - acceptedDisposition: run.acceptedDisposition, acceptedAt: run.acceptedAt, answersFollowUp: Boolean(run.runId && answers.has(run.runId)) })) }; + acceptedDisposition: run.acceptedDisposition, acceptedAt: run.acceptedAt, answersFollowUp: Boolean(run.runId && answers.has(run.runId)), + doneRejected: Boolean(run.runId && rejected.has(run.runId)) })) }; } export function wakeEvidenceOnce(input: { databaseUrl: () => string; companyId: string; waveDir: string; From 30fc64e212a970d8a6a111d118ded5f13575d41f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:57:36 -0600 Subject: [PATCH 5/6] fix(instructions): collect a waiting working copy as soon as its stop proof is written (#21596) 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 run gets a private working copy of the agent's instructions or agent files. A queue collects the copy after the provider is proven to have stopped. > - #21586 stopped this queue from re-reading copies forever: a copy that waits for proof of the stop is now checked again after half of its wait, capped at 6 hours. > - With only that change, a copy whose stop is recorded T after its run finished is collected up to T/2 later (at most 6 h). Before #21586 this took at most 30 seconds. A sandbox that takes minutes to stop therefore delays the save of an agent's instruction changes, and copies of stranded runs wait up to 6 h after their stop is finally recorded. > - This pull request makes the write that records the proof bring the run's waiting copy forward, so the queue checks it on its next pass. > - The benefit: collection is prompt again when the proof arrives, without polling copies that are still waiting. ## Linked Issues or Issue Description Follow-up to #21586. No public issue exists. Bug description: **What happened?** After #21586, a working copy waiting for proof of the provider stop keeps its saved backoff deadline when the proof arrives. Proof is a `native.local_process_stopped` event or a remote lease termination receipt. A copy whose run finished 30 days ago is collected up to 6 hours after its stop is recorded. **Expected behavior** When a stop proof for a run is written, that run's waiting copy is checked on the next queue pass. A write for a run without a waiting copy costs one indexed no-op UPDATE and sends no work signal. **Steps to reproduce** 1. Create a working copy for a native run that finished 30 days ago and has no stop event, then let the collection queue check it once. Its next check is about 6 h later. 2. Record the local stop (`recordNativeLocalProcessStopInTransaction`), or release the run's remote lease with a termination receipt. 3. On master the copy stays in `pending_collection` until the old deadline. **Paperclip version or commit** `origin/master` at 633dec7e43. ## What Changed - New `notifyInstructionCopyStopEvidence(tx, { companyId, runId })` in `instruction-collection-notifications.ts`. - It reads the run's copy by its primary key (`run_id`, scoped by `company_id`), and only if that copy waits in the collection queue or the agent-files cleanup queue. - If there is no such copy, it stops: one SELECT, no write, no signal. - If there is one, it first registers the run-scoped hint for both the collection and the cleanup queue, and then runs one UPDATE by the primary key. The UPDATE sets `next_attempt_at` to `now()` (or keeps an earlier value) and sets a new `updated_at`. All of this happens in the producer's transaction. - The collection claim now compares `updated_at` with the value the worker read (millisecond precision). If a stop proof is written between the worker's evidence read and its backoff write, the claim fails and the worker returns the copy as due, so the next pass collects it. Without this fence, the worker could save a 6 h deadline over the proof. - The writes that record stop proof call it in their own transaction: - `native.local_process_stopped` receipts: `appendLocalProcessStop` (used by `recordNativeLocalProcessStop` and its transaction form), `recordUnidentifiedLocalRunnerStop`, and the operator confirmation in `confirmUnidentifiedLocalRunnerStopped`. - Remote lease termination receipts: `notifyEnvironmentCleanup` when it has a run scope. Every lease release (`releaseLease`) and every `writeEnvironmentCleanup` write calls it, which covers the receipt writes in `environment-runtime`, `environment-task-runtime`, `native-workspace-export-resume`, `sandbox-stop-and-retain` and pending-cleanup recovery. The one remaining receipt write (sandbox absence in `sandbox-stop-and-retain`) calls it directly. - Orchestration's own stop path already calls `collectStopped` directly after it joins the provider, so it collects without the queue and needs no change. ## Verification - `server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts`, 3 new tests (embedded PostgreSQL, real queue registration): - A local copy whose run finished 30 days ago (next check about 6 h away) is collected within 10 seconds after `recordNativeLocalProcessStopInTransaction` records the stop. - A remote copy with the same backoff is collected within 10 seconds after `environmentService.releaseLease` writes a termination receipt. - For a run without a waiting copy, the transaction contains one SELECT and nothing else, and no hint is sent. For a run with a waiting copy, the only hint is `{"companyId":…,"runId":…}` (run-scoped, not company-wide). - A stop recorded between the worker's evidence read and its claim (injected in the claim's transaction hook) is still collected on the next pass. - Red first: with the producer changes reverted, the two collection tests fail (the copies stay in `pending_collection` until the old deadline). Without the `updated_at` fence, the race test fails. - Existing suites, one at a time: see the PR comment for the list and results. - `pnpm check:module-boundaries` passes. ## Risks - Every lease cleanup write with a run scope now runs one extra primary-key SELECT on `agent_instruction_working_copies`, and an UPDATE only when a waiting copy exists. - For agent-files cleanup (scratch files only, the saved data is not at risk), the same race is not fenced. A missed advance there waits for the cleanup backoff. - A lease cleanup write that does not carry a termination receipt can also bring a waiting copy forward. The queue then checks the stop evidence once more (3–5 statements) and moves the copy back to its backoff if the stop is still not proven. - A release written with only a lease scope (no run) does not bring a copy forward. That copy is still collected at its saved deadline. - No schema change and no migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used as a coding agent with tool use (shell, file edits, local 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 --- ...ent-instruction-copy-retry-backoff.test.ts | 82 ++++++++++++++++++- .../agent-instruction-working-copies.ts | 5 +- .../environment-cleanup-notifications.ts | 2 + .../instruction-collection-notifications.ts | 23 ++++++ .../src/services/native-local-process-stop.ts | 4 + .../src/services/sandbox-stop-and-retain.ts | 2 + 6 files changed, 115 insertions(+), 3 deletions(-) diff --git a/server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts b/server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts index ea54b58b6bb..72384a54d0a 100644 --- a/server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts +++ b/server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts @@ -4,7 +4,8 @@ import path from "node:path"; import { createHash, randomUUID } from "node:crypto"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { eq } from "drizzle-orm"; -import { agents, agentInstructionWorkingCopies, authUsers, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { spawnSync } from "node:child_process"; +import { agents, agentInstructionWorkingCopies, authUsers, companies, createDb, environmentLeases, heartbeatRuns, subscribeDatabaseWork } from "@paperclipai/db"; import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; @@ -17,6 +18,10 @@ import { INSTRUCTION_COPY_RETRY_MS, } from "../services/agent-instruction-working-copies.js"; import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js"; +import { recordNativeLocalProcessStopInTransaction } from "../services/native-local-process-stop.js"; +import { notifyInstructionCopyStopEvidence } from "../services/instruction-collection-notifications.js"; +import { environmentService } from "../services/environments.js"; +import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; const external = resolveExternalTestDatabaseUrl("PAPERCLIP_INSTRUCTION_COPY_TEST_DATABASE_URL"); @@ -237,4 +242,79 @@ describe("instruction working copies that cannot make progress", () => { expect(row.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now()); } finally { await worker.stop(); } }, 120_000); + it("collects a copy on the next pass once its local stop is recorded, long after its run finished", async () => { + const [runId] = await unprovenStops(1, 30 * DAY); + clock(); const worker = await start("collection"); + try { + expect((await copy(runId!)).nextAttemptAt!.getTime() - Date.now()).toBeGreaterThan(5 * HOUR); + const deadPid = spawnSync(process.execPath, ["-e", ""]).pid!; + const [run] = await db.update(heartbeatRuns).set({ processPid: deadPid }).where(eq(heartbeatRuns.id, runId!)).returning(); + expect(await db.transaction(tx => recordNativeLocalProcessStopInTransaction(tx as unknown as typeof db, run!))).toBe(true); + await advance(10_000, () => Date.now() + 1000); + expect(await copy(runId!)).toMatchObject({ state: "unchanged", nextAttemptAt: null }); + } finally { await worker.stop(); } + }, 120_000); + + it("collects a remote copy on the next pass once its lease records the termination receipt", async () => { + const [runId] = await runs(1, 30 * DAY); + const environmentId = randomUUID(); + await db.insert(agentInstructionWorkingCopies).values({ runId: runId!, companyId, agentId, responsibleUserId: userId, entryFile: "AGENTS.md", + baseHash: CONTENT_HASH, localRoot: path.dirname(entryPath(runId!)), executionRoot: "/workspace/instructions", + location: `remote:${environmentId}`, state: "prepared" }); + const [lease] = await db.insert(environmentLeases).values({ companyId, heartbeatRunId: runId!, provider: "fake-sandbox", + providerLeaseId: `sandbox-${runId}`, status: "active" }).returning(); + clock(); const worker = await start("collection"); + try { + expect(await copy(runId!)).toMatchObject({ state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED" }); + expect((await copy(runId!)).nextAttemptAt!.getTime() - Date.now()).toBeGreaterThan(5 * HOUR); + await environmentService(db).releaseLease(lease!.id, "released", { cleanupStatus: "success", + remoteExecutionTermination: remoteTerminationReceipt(lease!, { providerLeaseId: lease!.providerLeaseId, state: "stopped" }) }); + await advance(10_000, () => Date.now() + 1000); + expect(await copy(runId!)).toMatchObject({ state: "unavailable", errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE", nextAttemptAt: null }); + } finally { await worker.stop(); } + }, 120_000); + + it("sends a run-scoped hint only when a waiting copy is brought forward, and writes nothing otherwise", async () => { + const [waiting] = await unprovenStops(1, 30 * DAY); + const [none] = await runs(1, DAY); + const due = new Date(Date.now() + 6 * HOUR); + await db.update(agentInstructionWorkingCopies).set({ state: "pending_collection", nextAttemptAt: due }).where(eq(agentInstructionWorkingCopies.runId, waiting!)); + const hints: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.instructionCollection, (event, scoped) => { + if (event === "settled") hints.push(...(scoped ?? ["*"])); + }); + try { + meter.startLog(); + await db.transaction(tx => notifyInstructionCopyStopEvidence(tx, { companyId, runId: none! })); + const quiet = meter.stopLog(); + expect(quiet.filter(entry => !/^(begin|commit)/i.test(entry.sql.trim())).map(entry => entry.sql.trim().split(/\s/)[0])).toEqual(["select"]); + expect(hints).toEqual([]); + await db.transaction(tx => notifyInstructionCopyStopEvidence(tx, { companyId, runId: waiting! })); + await vi.waitFor(() => expect(hints).toEqual([JSON.stringify({ companyId, runId: waiting })])); + expect((await copy(waiting!)).nextAttemptAt!.getTime()).toBeLessThanOrEqual(Date.now()); + } finally { unsubscribe(); } + }, 60_000); + it("collects a copy whose stop is recorded between the worker's evidence read and its backoff write", async () => { + const [runId] = await unprovenStops(1, 30 * DAY); + await db.update(agentInstructionWorkingCopies).set({ state: "pending_collection", nextAttemptAt: new Date(Date.now() - 1000) }) + .where(eq(agentInstructionWorkingCopies.runId, runId!)); + const deadPid = spawnSync(process.execPath, ["-e", ""]).pid!; + const [run] = await db.update(heartbeatRuns).set({ processPid: deadPid }).where(eq(heartbeatRuns.id, runId!)).returning(); + const transaction = db.transaction.bind(db); + let recorded = false; + const transactions = vi.spyOn(db, "transaction").mockImplementation((async (callback, options) => { + if (!recorded) { + recorded = true; + expect(await transaction(tx => recordNativeLocalProcessStopInTransaction(tx as unknown as typeof db, run!))).toBe(true); + } + return transaction(callback, options); + }) as typeof db.transaction); + clock(); const worker = await start("collection"); + try { + transactions.mockRestore(); + expect(recorded).toBe(true); + await advance(10_000, () => Date.now() + 1000); + expect(await copy(runId!)).toMatchObject({ state: "unchanged", nextAttemptAt: null }); + } finally { transactions.mockRestore(); await worker.stop(); } + }, 120_000); }); diff --git a/server/src/services/agent-instruction-working-copies.ts b/server/src/services/agent-instruction-working-copies.ts index 7f2d98b98b6..f588c06284f 100644 --- a/server/src/services/agent-instruction-working-copies.ts +++ b/server/src/services/agent-instruction-working-copies.ts @@ -483,13 +483,14 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen : { nextAttemptAt: evidence === "directory_unavailable" ? retryAt : new Date(Date.now() + INSTRUCTION_COPY_RETRY_MS) }, true, sql`EXISTS (SELECT 1 FROM ${heartbeatRuns} WHERE ${heartbeatRuns.id} = ${copies.runId} AND ${heartbeatRuns.companyId} = ${copies.companyId} - AND ${heartbeatRuns.status} IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted'))`); + AND ${heartbeatRuns.status} IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')) + AND date_trunc('milliseconds', ${copies.updatedAt}) = ${current.copy.updatedAt.toISOString()}::timestamptz`); const settled = claimed && evidence !== null ? await collectRecovered(claimed, evidence, retryAt) : claimed; const remaining = settled === undefined || settled === null ? (await readCollection(entry))?.copy : collectionCandidate(settled) ? settled : null; if (!remaining) return null; const next = { ...entry, dueAt: remaining.nextAttemptAt?.getTime() ?? 0 }; - if (next.dueAt <= Date.now()) throw new Error("Instruction collection remains unresolved without a future retry"); + if (next.dueAt <= Date.now() && claimed) throw new Error("Instruction collection remains unresolved without a future retry"); return next; } async function recoverStopped() { diff --git a/server/src/services/environment-cleanup-notifications.ts b/server/src/services/environment-cleanup-notifications.ts index 6beca498981..06b634454a6 100644 --- a/server/src/services/environment-cleanup-notifications.ts +++ b/server/src/services/environment-cleanup-notifications.ts @@ -5,6 +5,7 @@ import { notifyNativeEnvironmentSettlement, type NativeEnvironmentSettlementScop import type { Db } from "@paperclipai/db"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { notifyQueuedRunDispatch } from "./run-dispatch-notifications.js"; +import { notifyInstructionCopyStopEvidence } from "./instruction-collection-notifications.js"; export type EnvironmentCleanupWorkScope = NativeEnvironmentSettlementScope & { leaseId?: string }; @@ -32,6 +33,7 @@ export async function notifyEnvironmentCleanup(transaction: object, scope?: Envi await notifyQueuedRunDispatch(transaction, scope); // A settled run lease can make that run's abandoned native owner releasable. if (scope?.runId) { + await notifyInstructionCopyStopEvidence(transaction, { companyId: scope.companyId, runId: scope.runId }); await notifyDeliveryWork(transaction, DELIVERY_QUEUES.executionFinalization); await notifyDeliveryWork(transaction, DELIVERY_QUEUES.executionReplacement); } diff --git a/server/src/services/instruction-collection-notifications.ts b/server/src/services/instruction-collection-notifications.ts index d0c19355c00..74c607f8359 100644 --- a/server/src/services/instruction-collection-notifications.ts +++ b/server/src/services/instruction-collection-notifications.ts @@ -1,4 +1,7 @@ +import { sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; import { notifySkillVersionRetention } from "./skill-version-retention-notifications.js"; +import { notifyDirectoryCleanup } from "./directory-cleanup-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; export type InstructionCollectionScope = { companyId: string; runId?: string }; @@ -7,3 +10,23 @@ export async function notifyInstructionCollection(transaction: object, scope?: I if (scope) await notifySkillVersionRetention(transaction, scope.companyId); await notifyDeliveryWork(transaction, DELIVERY_QUEUES.instructionCollection, scope ? JSON.stringify(scope) : "*"); } + +const waitingCopy = (scope: { companyId: string; runId: string }) => sql`company_id = ${scope.companyId} and run_id = ${scope.runId} and ( + (not (coalesce(receipt, '{}'::jsonb) ? 'retainedByRunId') and ( + (attempts < 3 and state in ('prepared', 'pending_collection', 'unchanged_turn', 'warm_saved')) + or (state = 'unavailable' and process_stopped_at is null and location like 'remote:%' + and receipt->>'schema' = 'paperclip.agent-files.v1'))) + or (state in ('saved', 'unchanged', 'resolved', 'unavailable') and process_stopped_at is not null + and receipt->>'schema' = 'paperclip.agent-files.v1' and coalesce(receipt->>'retainedByRunId', '') = '' + and (receipt->>'cleanupPending' = 'true' or (receipt->>'cleanupPending' is distinct from 'false' and receipt ? 'baseline'))))`; + +export async function notifyInstructionCopyStopEvidence(transaction: object, scope: { companyId: string; runId: string }) { + if (typeof (transaction as Db).execute !== "function") return; + const found = await (transaction as Db).execute(sql`select 1 from agent_instruction_working_copies where ${waitingCopy(scope)}`); + if (!Array.isArray(found) || found.length === 0) return; + await notifyInstructionCollection(transaction, scope); + await notifyDirectoryCleanup(transaction, scope); + await (transaction as Db).execute(sql`update agent_instruction_working_copies + set next_attempt_at = least(coalesce(next_attempt_at, now()), now()), updated_at = clock_timestamp() + where ${waitingCopy(scope)}`); +} diff --git a/server/src/services/native-local-process-stop.ts b/server/src/services/native-local-process-stop.ts index 7c7a5e39546..8b1b7c867bc 100644 --- a/server/src/services/native-local-process-stop.ts +++ b/server/src/services/native-local-process-stop.ts @@ -1,4 +1,5 @@ import { notifyLiveRunRecovery } from "./live-run-recovery-notifications.js"; +import { notifyInstructionCopyStopEvidence } from "./instruction-collection-notifications.js"; import { and, desc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; import { notifyRetainedNativeSessionCleanup } from "./retained-native-session-cleanup-notifications.js"; @@ -87,6 +88,7 @@ async function appendLocalProcessStop(db: Db, run: { id: string; companyId: stri message: "Recovery verified the local process stopped before clearing its identity.", payload: { processPid: run.processPid, processGroupId: run.processGroupId, processStartedAt: run.processStartedAt }, }); + await notifyInstructionCopyStopEvidence(db, { companyId: run.companyId, runId: run.id }); } /** Transaction form for callers that clear the process identity: a stopped @@ -151,6 +153,7 @@ export async function recordUnidentifiedLocalRunnerStop(db: Db, run: Pick { await notifyRetainedNativeSessionCleanup(tx, { companyId: lease.companyId, runId: lease.heartbeatRunId! }); + await notifyInstructionCopyStopEvidence(tx, { companyId: lease.companyId, runId: lease.heartbeatRunId! }); return tx.update(environmentLeases).set({ status: "released", cleanupStatus: "success", failureReason: "workspace_source_unavailable", releasedAt: now, updatedAt: now, metadata: sql`(${environmentLeases.metadata} - 'sandboxStopAndRetain' - 'nativeWorkspaceExportResume' - 'sandboxStopAndRetainReceipt') || ${JSON.stringify({ From 12ac7cfd9f8292a889c33710e16cca1c0e8823f3 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:58:47 -0600 Subject: [PATCH 6/6] perf(recovery): read only the run keys that active execution recovery checks use (#21602) 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 > - Live recovery checks each running run when recovery work wakes it. The check is `recoverActiveExecutions` in `server/src/services/heartbeat/recovery.ts`. > - Each check read the full `heartbeat_runs` row and the agent's `adapter_config`. That includes `context_snapshot` and `runner_profile_json`, which are large JSON columns. > - Most checks only defer the run to its lease deadline. They use a few JSON keys and never use the rest of the row. > - Recovery wakes come from runner checkpoints, run events and company work signals. Each running run is checked about 4.5 times per minute under that load, so this read grows with the number of running runs. > - This pull request reads only the JSON keys that the check gates use. A run that recovery settles as lost reads its full context, runner profile and adapter config before the settle. > - The benefit is about 97% fewer bytes per check, with the same recovery decisions. ## Linked Issues or Issue Description **What existing behavior does this improve?** The read that live recovery does for each running run (`recoverActiveExecutions`). **Subsystem affected** Server: heartbeat run recovery (`server/src/services/heartbeat/recovery.ts`). **Current behavior** Each check selects the whole `heartbeat_runs` row plus `agents.adapter_config`. With a realistic row (`context_snapshot` 115 KB of text, 23 KB stored; `runner_profile_json` 48 KB of text, 10 KB stored), one check receives 175 KB from Postgres. A server with 20 running runs did 90 checks per minute, which is 15.7 MB per minute from this one statement. That was 99% of all bytes in the measured window. **Proposed behavior** The check selects all scalar run columns, a small JSON object with only the keys its gates read, and no output excerpts or adapter config. The process-lost settle path reads the full `context_snapshot`, `runner_profile_json` and `adapter_config` for that one run before it decides on a retry. **Reason and benefit** The staging server spends 21-24% of main-thread CPU on postgres.js result parsing at about 26 KB per statement. Whole-row reads in recurring loops cause that overfetch. This change removes about 171 KB from each check. **Breaking changes** None. No schema, API or contract change. **Additional context** I examined the `+1 s` re-arm (when revocation finds a child process that the inventory snapshot did not have). I kept it. It only fires when the revocation sees a changed row. The revocation also writes a new 60-second lease for a random boot ID, so the next pass defers on that live lease. It does not loop on unchanged state. In the 60-second measurement it did not fire. ## What Changed - `recoverActiveExecutions` selects `activeRecoveryRunColumns`. This is all `heartbeat_runs` columns, except that `context_snapshot` holds only `wakeReason`, `issueId` and `nativeQuestionCancellation`, `runner_profile_json` holds only `nativeStartupContext`, `nativeWorkspaceSync` and `remoteWorkspace`, and the stdout/stderr excerpts are null. It does not select `agents.adapter_config`. - New `readActiveRecoverySettlement` reads the full `context_snapshot`, `runner_profile_json` and `adapter_config` of one run. The process-lost settle uses that data for the conversation-adapter check, the retry budget, the process-loss diagnostic, the stop metadata and the first-heartbeat flag. - New tests in `server/src/services/heartbeat/recovery.test.ts`: - A regression test counts the bytes Postgres sends during one deferred check through a TCP proxy. It must be below 32 KB. - A settle test (two cases) gives a lost run its retry budget, first-heartbeat flag and conversation adapter only in the JSON keys outside the narrow read. The test checks that the settle still uses them. - A test checks that a run with `nativeQuestionCancellation` in its context is still skipped. ## Verification - Red/green: the byte test fails on `origin/master` (`expected 454426 to be less than 32768`) and passes with this change. The other three new tests pass both before and after. - Focused local runs pass: `recovery.test.ts`, `live-recovery-work.test.ts`, `native-startup-cleanup-recovery.test.ts`, `ownership-reconciliation-report.test.ts` (4 files, 255 tests). - `pnpm verify` selected 2,715 of 3,541 files (conservative retention). On this machine 1,689 files passed and 32 failed. The failures were `afterAll` hook timeouts (30 s) and unrelated tool-access, email and runner artifact suites under local load. The recovery suites above pass when run alone. Required CI gives the full coverage. - Before/after measurement (local embedded Postgres, a wire proxy that assigns each server response to its statement, the real live-recovery scheduler, 60 s window, 20 running runs: 10 native runs held by a live controller and 10 legacy runs with a live peer lease; a run recovery signal every 5 s for each run, a company work signal every 10 s, legacy lease renewal every 20 s): | | Before | After | | --- | --- | --- | | Checks per minute | 90 | 90 | | Bytes per check (inventory statement) | 174,954 | 4,470 | | Inventory bytes per minute | 15,745,819 | 402,298 | | All bytes per minute in the window | 15,848,137 | 504,640 | ## Risks - Low risk. The narrow read keeps the keys that the gates read. The settle path reads the full row data before it uses it. - The settle path now reads `context_snapshot`, `runner_profile_json` and `adapter_config` after the lease revocation, not at the start of the check. The values can be some milliseconds newer. The revocation already uses the committed row state, so this agrees with the rest of the settle. - The settle path has one more query. It only runs when a run is settled as lost. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used as an agent in Claude Code with tool use (shell, file edits, local test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../src/services/heartbeat/recovery.test.ts | 122 +++++++++++++++++- server/src/services/heartbeat/recovery.ts | 48 +++++-- 2 files changed, 160 insertions(+), 10 deletions(-) diff --git a/server/src/services/heartbeat/recovery.test.ts b/server/src/services/heartbeat/recovery.test.ts index dc7683b7dc9..747a342254f 100644 --- a/server/src/services/heartbeat/recovery.test.ts +++ b/server/src/services/heartbeat/recovery.test.ts @@ -2,9 +2,10 @@ import { retireInheritedRemoteRunnerIdentity } from "../native-runtime/native-in import { randomUUID } from "node:crypto"; import { spawn } from "node:child_process"; import { once } from "node:events"; +import { connect, createServer, type AddressInfo, type Socket } from "node:net"; import type { Db } from "@paperclipai/db"; import { activityLog, agents, applyPendingMigrations, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environments, environmentLeases, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunnerCheckpoints } from "@paperclipai/db"; -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { classifyEnvironmentCapabilities, environmentRuntimeService } from "../environment-runtime.js"; @@ -316,6 +317,125 @@ describePostgres("heartbeat recovery module ownership", () => { } }); + async function byteCountingProxy(connectionString: string) { + const target = new URL(connectionString); + const sockets = new Set(); + let received = 0; + const server = createServer(client => { + const upstream = connect(Number(target.port || "5432"), target.hostname); + sockets.add(client).add(upstream); + upstream.on("data", chunk => { received += chunk.length; }); + client.pipe(upstream); + upstream.pipe(client); + const close = () => { client.destroy(); upstream.destroy(); }; + client.on("error", close); + upstream.on("error", close); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const proxied = new URL(connectionString); + proxied.hostname = "127.0.0.1"; + proxied.port = String((server.address() as AddressInfo).port); + return { + url: proxied.toString(), + received: () => received, + async close() { + for (const socket of sockets) socket.destroy(); + await new Promise(resolve => server.close(resolve)); + }, + }; + } + + async function seedLostLegacyRun(input: { contextSnapshot: Record; runnerProfileJson: Record; + adapterConfig: Record; controllerLeaseExpiresAt: Date }) { + const run = await seedRun(); + await db.update(agents).set({ adapterConfig: input.adapterConfig }).where(eq(agents.id, run.agentId)); + const [updated] = await db.update(heartbeatRuns).set({ controllerBootId: randomUUID(), + controllerLeaseExpiresAt: input.controllerLeaseExpiresAt, executionStage: "dispatching", + contextSnapshot: input.contextSnapshot, runnerProfileJson: input.runnerProfileJson, + stdoutExcerpt: "stdout ".repeat(5_000), stderrExcerpt: "stderr ".repeat(5_000), + }).where(eq(heartbeatRuns.id, run.id)).returning(); + return updated; + } + + it("reads a bounded slice of a running run when active recovery only defers it", async () => { + const leaseExpiresAt = new Date(Date.now() + 60_000); + const run = await seedLostLegacyRun({ + contextSnapshot: { issueId: randomUUID(), wakeReason: "issue_assigned", transcript: "context ".repeat(25_000) }, + runnerProfileJson: { backend: "fixture", manifest: "profile ".repeat(12_000) }, + adapterConfig: { instructions: "config ".repeat(12_000) }, + controllerLeaseExpiresAt: leaseExpiresAt, + }); + const proxy = await byteCountingProxy(externalUrl ?? database.connectionString); + const proxiedDb = createDb(proxy.url, { maxConnections: 1 }); + try { + await proxiedDb.execute(sql`select 1`); + const deps = callbacks(proxiedDb); + const deadlines: number[] = []; + const before = proxy.received(); + await createHeartbeatRecovery(proxiedDb, deps).recoverActiveExecutions({ companyId: run.companyId, runId: run.id, + onDeferredDeadline: at => deadlines.push(at) }); + expect(proxy.received() - before).toBeLessThan(32_768); + expect(deadlines).toEqual([leaseExpiresAt.getTime()]); + expect(deps.setRunStatusFromLive).not.toHaveBeenCalled(); + } finally { + await proxiedDb.$client.end(); + await proxy.close(); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + } + }); + + it.each([ + { serverRestarts: 1, retries: true }, + { serverRestarts: 6, retries: false }, + ])("settles a lost run from its full context, runner profile and adapter config (server restarts $serverRestarts)", async ({ serverRestarts, retries }) => { + const adapterConfig = { model: "fixture", instructions: "config ".repeat(2_000) }; + const run = await seedLostLegacyRun({ + contextSnapshot: { issueId: randomUUID(), wakeReason: "issue_assigned", timerClaimWasFirstHeartbeat: true, + executionRetryAccounting: { version: 1, failureRetries: 0, maxTurnContinuations: 0, serverRestarts, + serverRestartWindowStartedAt: new Date().toISOString() }, + transcript: "context ".repeat(2_000) }, + runnerProfileJson: { adapterDispatch: { adapterType: "claude_local" }, manifest: "profile ".repeat(2_000) }, + adapterConfig, + controllerLeaseExpiresAt: new Date(0), + }); + const deps = { + ...callbacks(db), + timerClaimWasFirstHeartbeat: vi.fn(source => + source.contextSnapshot?.timerClaimWasFirstHeartbeat === true ? true : undefined), + }; + deps.setRunStatusFromLive.mockImplementation(async (_id, status, _from, patch) => + ({ updated: true, run: { ...run, ...patch, status } as Run })); + try { + expect(await createHeartbeatRecovery(db, deps).recoverActiveExecutions({ companyId: run.companyId, runId: run.id }, + { staleThresholdMs: 0 })).toEqual([run.id]); + expect(deps.mergeRunStopMetadataForAgent).toHaveBeenCalledWith({ adapterType: "process", adapterConfig }, "failed", + expect.objectContaining({ conversationContinuationEligible: true })); + const [, , , patch] = deps.setRunStatusFromLive.mock.calls[0]!; + expect(patch?.error?.endsWith("; retrying once")).toBe(retries); + expect(deps.finalizeAgentStatus).toHaveBeenCalledWith(run.agentId, "failed", expect.any(String), { wasFirstHeartbeat: true }); + } finally { + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, run.id)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + } + }); + + it("leaves a lost run that waits on a question cancellation to its own recovery", async () => { + const run = await seedLostLegacyRun({ + contextSnapshot: { issueId: randomUUID(), nativeQuestionCancellation: { kind: "issue_terminal" }, transcript: "context ".repeat(2_000) }, + runnerProfileJson: {}, + adapterConfig: {}, + controllerLeaseExpiresAt: new Date(0), + }); + const deps = callbacks(db); + try { + expect(await createHeartbeatRecovery(db, deps).recoverActiveExecutions({ companyId: run.companyId, runId: run.id }, + { staleThresholdMs: 0 })).toEqual([]); + expect(deps.setRunStatusFromLive).not.toHaveBeenCalled(); + } finally { + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + } + }); + async function ownedProcess() { const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)", `paperclip-recovery-${randomUUID()}`], { stdio: "ignore", detached: true, env: { PATH: process.env.PATH }, diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 210ab21ff02..d56ade41b7f 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -67,6 +67,7 @@ import { asc, desc, eq, + getTableColumns, gt, inArray, isNotNull, @@ -140,6 +141,22 @@ import { requestRestartInterruptedTurnRetry } from "./restart-interrupted-turn.j type HeartbeatRun = typeof heartbeatRuns.$inferSelect; type HeartbeatRetries = ReturnType; +const activeRecoveryRunColumns = { + ...getTableColumns(heartbeatRuns), + contextSnapshot: sql | null>`jsonb_build_object( + 'wakeReason', ${heartbeatRuns.contextSnapshot} -> 'wakeReason', + 'issueId', ${heartbeatRuns.contextSnapshot} -> 'issueId', + 'nativeQuestionCancellation', ${heartbeatRuns.contextSnapshot} -> 'nativeQuestionCancellation' + )`.as("contextSnapshot"), + runnerProfileJson: sql | null>`jsonb_build_object( + 'nativeStartupContext', ${heartbeatRuns.runnerProfileJson} -> 'nativeStartupContext', + 'nativeWorkspaceSync', ${heartbeatRuns.runnerProfileJson} -> 'nativeWorkspaceSync', + 'remoteWorkspace', ${heartbeatRuns.runnerProfileJson} -> 'remoteWorkspace' + )`.as("runnerProfileJson"), + stdoutExcerpt: sql`NULL`.as("stdoutExcerpt"), + stderrExcerpt: sql`NULL`.as("stderrExcerpt"), +} as const; + /** Recovery owns reconciliation; the service retains execution and lifecycle effects. */ export interface HeartbeatRecoveryDependencies extends Pick) { + const [settlement] = await db.select({ + contextSnapshot: heartbeatRuns.contextSnapshot, + runnerProfileJson: heartbeatRuns.runnerProfileJson, + adapterConfig: agents.adapterConfig, + }).from(heartbeatRuns) + .innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)) + .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId))) + .limit(1); + return settlement ?? null; + } + async function recoverActiveExecutions(scope: RecoveryScope = {}, options: { staleThresholdMs?: number; resumedRunIds?: Set; } = {}) { @@ -2468,9 +2497,8 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD // Find all runs stuck in "running" state (queued runs are legitimately waiting; resumeQueuedRuns handles them) const activeRuns = await db .select({ - run: heartbeatRuns, + run: activeRecoveryRunColumns, adapterType: agents.adapterType, - adapterConfig: agents.adapterConfig, nativeCoordinatorPhase: nativeRunFinalizations.phase, nativeRecoveryState: nativeRunFinalizations.recoveryState, nativeControllerBootId: nativeRunFinalizations.controllerBootId, @@ -2571,7 +2599,6 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD for (const { run, adapterType, - adapterConfig, nativeCoordinatorPhase, nativeRecoveryState, nativeControllerBootId, @@ -2831,6 +2858,9 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD scope.onDeferredDeadline?.(Math.max(refTime + staleThresholdMs, Date.now() + 60_000)); continue; } + const settlement = await readActiveRecoverySettlement(run); + if (!settlement) continue; + const settledRun = { ...run, contextSnapshot: settlement.contextSnapshot, runnerProfileJson: settlement.runnerProfileJson }; // A legacy controller persists "dispatching" in the same lease renewal // that admits the adapter. An expired lease that is still "preparing" // proves setup stopped before provider work. @@ -2849,7 +2879,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD // budget, and a conversation adapter continues with a fresh turn. const controllerReplaced = run.runtimeMode === "legacy" && !!run.controllerBootId && run.controllerBootId !== legacyControllerBootId; - const conversationContinuationEligible = await runUsedConversationAdapter(db, run); + const conversationContinuationEligible = await runUsedConversationAdapter(db, settledRun); const shouldRetry = !await pendingCaseHandoffForRun(db, run.id, run.companyId) && // Process loss spends the durable failure retry budget that @@ -2865,15 +2895,15 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD // names its owner process (isReplacedPreparation). !(controllerReplaced && (conversationContinuationEligible || restartInterruptedBeforeDispatch && readControllerProcess(run.controllerProcess) !== null) - ? serverRestartBudgetSpent(run, now) : failedRunRetryBudgetSpent(run)) && + ? serverRestartBudgetSpent(settledRun, now) : failedRunRetryBudgetSpent(settledRun)) && ((tracksLegacyLocalChild && (!!run.processPid || !!run.processGroupId)) || restartInterruptedBeforeDispatch || monitorDispatchLostWithoutFutureWake || (controllerReplaced && conversationContinuationEligible)); - const baseMessage = buildProcessLossMessage(run); + const baseMessage = buildProcessLossMessage(settledRun); const processLossDiagnostic = buildProcessLossDiagnostic({ - run, + run: settledRun, nowMs: Date.now(), observerStartedAtMs: performance.timeOrigin, checksPersistedChildLiveness, @@ -2892,7 +2922,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD ...(restartInterruptedBeforeDispatch && legacyControllerGone ? { controllerLeaseExpiresAt: now } : {}), resultJson: (() => { const result = mergeRunStopMetadataForAgent( - { adapterType, adapterConfig }, + { adapterType, adapterConfig: settlement.adapterConfig }, "failed", { conversationContinuationEligible, @@ -2981,7 +3011,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD }); await finalizeAgentStatus(run.agentId, "failed", baseMessage, { - wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run), + wasFirstHeartbeat: timerClaimWasFirstHeartbeat(settledRun), }); await startNextQueuedRunForAgent(run.agentId); runningProcesses.delete(run.id);