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 + } 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/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/__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/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/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/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/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); 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 { } 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.", diff --git a/server/src/services/sandbox-stop-and-retain.ts b/server/src/services/sandbox-stop-and-retain.ts index 20f8c2de44a..c138aac096a 100644 --- a/server/src/services/sandbox-stop-and-retain.ts +++ b/server/src/services/sandbox-stop-and-retain.ts @@ -1,5 +1,6 @@ import { notifyRetainedNativeSessionCleanup } from "./retained-native-session-cleanup-notifications.js"; import { writeEnvironmentCleanup } from "./environment-cleanup-notifications.js"; +import { notifyInstructionCopyStopEvidence } from "./instruction-collection-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { randomUUID } from "node:crypto"; import { and, eq, sql, type SQL } from "drizzle-orm"; @@ -277,6 +278,7 @@ export async function settleAbsentSandbox(db: Db, lease: typeof environmentLease const now = new Date(); const changed = await db.transaction(async tx => { 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({ 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; 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",