diff --git a/DESIGN.md b/DESIGN.md index aa2eba46b29..d092f51a3b7 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -153,6 +153,8 @@ such as `Waiting for maintenance`, agent setup, or another open task of the same routine, visible during admission. Admission normally starts a run within seconds, so this startup feedback lasts at most 30 seconds: a turn still queued after that with no named hold says `Waiting to start`, without spinner or shimmer. +A queued turn's hold is named once, in the turn header; the turn body adds no +second line for it. A run that waits for one of its agent's concurrency slots is a hold too: show `Waiting for · N slots max · P of Q in line · Configure` (the shared `AgentQueueWait` component) with no spinner or elapsed timer, link Configure to the diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 5b1ecb4c9b1..99f28b85a3b 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -916,6 +916,20 @@ DATABASE_MAX_LIFETIME_SECONDS=1800 # recycle a pooled connection after this lo DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; default: paperclip ``` +`withDedicatedDbConnection` gives an action exclusive use of one session outside +the main pool (application name `paperclip-workspace-finalization-lock`). Each +`createDb` owner keeps at most `DEDICATED_CONNECTION_IDLE_MAX` (4) of these +single-connection clients idle for reuse; they follow the same idle timeout and +max lifetime as the main pool. This is not an admission limit: callers hold +advisory locks and nest dedicated actions, so an action that finds no idle +client opens one and closes it on release when four are already retained. A +connection whose action throws is closed, never reused. Actions must keep +session state transaction-scoped (`pg_advisory_xact_lock`, +`set_config(..., true)`). Like the main pool, a retained session sees an +`ALTER DATABASE` or `ALTER ROLE ... SET` change only after it reconnects; a test +that changes such a setting calls `closeDedicatedDbConnections` first. Shutdown +and ending the owner client close the idle set. + An explicit `DATABASE_PREPARED_STATEMENTS=true` enables named prepared statements for parameterized ORM queries, transactions, reserved connections, and dedicated clients. Postgres.js manages the statement cache. This does not cache query @@ -1709,6 +1723,17 @@ pinned history and an empty queue do not cause recurring scans. Deletion fences new adoption, rechecks references, and removes every recorded upload candidate and winning object within the company/workspace prefix. +When retention finds a pinned version, it records the first reference that holds +it in `metadata.retentionPin`: the current pointer, an importing parent, an +operation, an unfinished child, a run, or a recovery action. The candidate query +leaves that version out while the recorded reference still holds, so execution +notifications do not re-examine unchanged history. When the recorded reference +releases, the next pass checks every reference again. It records the next +reference that holds, or schedules or retires the version. The record is durable, +so a restarted server keeps the exclusion. A version without a record, such as +one saved before this change, is examined once. Wakes coalesce for up to one +second. + Database backups contain snapshot receipts, not S3 payloads or encryption keys. Disaster recovery requires the database, object store, and original master key. Unsaved live sandbox edits remain outside that saved-version guarantee. See diff --git a/doc/mcp-discovery-performance.md b/doc/mcp-discovery-performance.md index bed7a912efd..58d06222aee 100644 --- a/doc/mcp-discovery-performance.md +++ b/doc/mcp-discovery-performance.md @@ -139,6 +139,30 @@ counts, process CPU, and elapsed time. The installation dependency returns an empty list for this fixture, which has no installed connections. It does not measure provider work, whole-run latency, or hosted performance. +## Policy selector matching + +A listing decides access once per tool and shares one decision cache. The cache +holds the company's enabled policies compiled once: selectors are parsed once, +and policies are indexed by catalog entry, then by tool name for policies +without a catalog entry selector. Each decision checks only the policies in the +matching buckets plus the policies that select neither key, in the original +priority and creation order. Conditions are parsed once per policy. Decisions +without a cache, including those that consume a rate limit, compile the policies +they read in the same way. Decisions are unchanged. + +To compare against a baseline commit on real PostgreSQL, run from `server/`: + +```sh +pnpm exec tsx scripts/benchmark-tool-policy-matching.ts --baseline-ref origin/master --tools 800 --rounds 9 +``` + +The probe uses 800 catalog tools and 365 enabled policies shaped like the +staging company that showed this cost (342 select a catalog entry, 18 a catalog +entry and connection, 3 several other keys, 17 carry conditions). It checks that +both versions return the same decisions, then alternates one listing per version +per round and reports elapsed time, process CPU, the longest event-loop block, +and selector work per listing. + ## Local profile comparison on 2026-11-02 diff --git a/doc/plans/2026-11-13-thousand-concurrent-agents.md b/doc/plans/2026-11-13-thousand-concurrent-agents.md index c43512d9657..a17a2113b99 100644 --- a/doc/plans/2026-11-13-thousand-concurrent-agents.md +++ b/doc/plans/2026-11-13-thousand-concurrent-agents.md @@ -129,6 +129,104 @@ What it shows: - Lease renewal is under 1 statement/s at 400 agents (15/s at 50 before). - The model does not measure server memory, so it does not show change 1h. +## Load model at recorded rates + +The rates above were assumptions. Recorded hosted native runs show a much +lighter and different load, so the model's default changed on 2026-11-14. + +Source: 40 recent native runs on one hosted workspace (median 26 minutes). +Events stored per run: 0.69/s at the median, 1.5/s at p90. Text deltas: 0.18/s +on average, 1.6–2.7/s in a run's busiest minute; a run streams text for about +8% of its life. Rows by event type: `run.performance.span` 10,030, +`item.delta` 9,502, `tool.execution.progressed` 6,951, `item.completed` 4,705, +`tool.execution.started` and `tool.execution.completed` about 2,150 each. +Controller checkpoint rows: about 1.4 per running run per second. + +| Profile (`PROFILE`) | Deltas/s per agent | Other events/s per agent | Use | +| --- | --- | --- | --- | +| `recorded` (default) | 0.2 | 0.5 | median of the recorded runs | +| `burst` | 2.5 | 3 | a run's busiest minute | +| `stress` | 20 | 1 | the earlier assumption, kept for comparison | + +API requests stay at 0.3/s per agent in every profile. Other events follow the +recorded mix (`EVENT_MIX`), and each type takes the server path it takes in +production: + +| Event type | Share | Server path | +| --- | --- | --- | +| `run.performance.span` | 39% | written by the server's own run trace: one ordinary append, no wake, no checkpoint | +| `tool.execution.progressed` | 27% | runner event with a chat-progress wake: a transaction, then a controller checkpoint save | +| `item.completed` | 18% | the same (a final reply also wakes response presentation) | +| `tool.execution.started`, `tool.execution.completed` | 8% each | the same | + +The model's delta batching now also follows #21520: deltas that arrive while a +batch commits go into one next batch, until the run's next runner event. + +Measured 2026-11-14 on master (after #21511, #21520 and #21528), 60 s window, +main pool of 10 connections, embedded PostgreSQL on the same machine. Each run +started only when the machine's 1-minute load average was below 15; the load +average at the start and the end is shown. The machine is shared, and the +500-agent recorded run had other work start during its window (marked busy). + +| Agents | Profile | Load avg start / end | Event-loop utilization | Statements/s | Per agent per second | Checkpoint pool statements/s | Other events done / offered | Other event lateness p50 / p99 | Delta lateness p50 / p99 | API p50 / p99 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 500 | recorded, busy | 14.9 / 22.2 | 0.66 | 1,979 | 4.0 | 688 | 14,774 / 15,000 | 3 ms / 5.2 s | 2 ms / 5.7 s | 3 ms / 7.1 s | +| 1,000 | recorded | 14.0 / 13.5 | 0.61 | 4,351 | 4.4 | 1,525 | 30,000 / 30,000 | 1 ms / 10 ms | 1 ms / 252 ms | 2 ms / 9 ms | +| 2,000 | recorded | 13.4 / 15.9 | 0.85 | 8,701 | 4.4 | 3,049 | 60,000 / 60,000 | 2 ms / 2.1 s | 1 ms / 2.2 s | 3 ms / 3.0 s | +| 250 | burst | 12.3 / 16.6 | 0.70 | 6,102 | 24.4 | 2,287 | 45,000 / 45,000 | 1 ms / 122 ms | 2 ms / 281 ms | 2 ms / 199 ms | +| 500 | burst | 13.8 / 11.7 | 0.95 | 12,114 | 24.2 | 4,488 | 90,000 / 90,000 | 4 ms / 171 ms | 9 ms / 318 ms | 5 ms / 268 ms | + +No run had a failed operation, a failed checkpoint save or a lost lease. + +What it shows: + +- At recorded rates one process costs about 4.4 statements per agent per + second, and about 35% of them are on the 3-connection checkpoint pool. The + non-delta runner events and their checkpoint saves are most of the cost; text + deltas are now a small share. +- On loopback PostgreSQL one process carries 2,000 agents at recorded rates + (event-loop utilization 0.85, p99 lateness about 2 s), and 500 agents all in + their busiest minute at the same time (0.95, p99 under 0.4 s). +- The 3-connection checkpoint pool kept up locally: about 4,500 statements/s, + or 1,100 saves/s, at 500 agents in a busy minute. Since #21528 a save is 4 + statements (BEGIN, the owner lock with the transaction id, the write, + COMMIT), and 5 where commit-time notifications are on (a `pg_notify` before + COMMIT). Each save holds a connection for those round trips, so with a hosted + round trip of about 1 ms the same 3 connections allow about 600–750 saves/s, + which is about 330–400 agents in a busy minute. That is a per-process limit + on a hosted database (change 1g sizes this pool); it is computed here, not + measured. +- Earlier runs on 2026-11-14 at load averages of 20–55 showed one process + falling behind at 500 agents in a busy minute and at 2,000 at recorded rates. + With the machine quieter and the model's event order corrected, both kept up, + so those earlier results described the machine, not the server code. +- The model saves a checkpoint without blocking the agent's next event. The + controller acknowledges a runner event only after its checkpoint save, so in + production a slow checkpoint pool also delays the run's next events. The + model therefore understates the effect of that pool. +- On the hosted instance a CPU profile of the main thread (2026-11-14, with + these fixes) shows building SQL text in Drizzle costing about as much + main-thread time as postgres.js result parsing (each about a fifth). A + statement with fixed SQL text, as in #21511, therefore saves more CPU there + than its statement count suggests; the next changes should be judged by CPU + per operation, not only by statements. + +## Considered and not done + +- **Stop writing `run.performance.span` rows.** These spans are the largest + event type by rows, but each is one statement with no wake and no + checkpoint. Recorded runs have about 190–250 span rows per run over a median + of 26 minutes, about 0.12–0.16 rows per run per second: about 3% of the + statements per agent. The top names are `tool.request.input_stream` (median + 56 per run), `tool.execute` (25), `execution.plugin_dispatch` (11) and + `authorization.base` (7). Run forensics, the restart-chaos speed scripts and + exports read these rows, so they stay. +- **Save a controller checkpoint only for critical runner events.** After the + routine checkpoint save becomes one statement, this would save about 0.3 + statements per agent per second at recorded rates. It would change the + acknowledgement order and the restore cursor of the runner's control plane, + which is recovery-critical. Not now; revisit with the writer-thread work. + ## Why more servers do not help today | Assumption | Where | Effect with two steady processes | @@ -212,8 +310,9 @@ turn, so memory per session counts for idle agents too. - The load model runs on loopback PostgreSQL on a developer machine. It measures the modelled sources only and has no hosted round-trip time. -- The per-agent rates (20 deltas/s, 1 other event/s, 0.3 API requests/s) are - assumptions, not a recorded workload. Phase 0 step 2 replaces them. +- The first tables used assumed rates (20 deltas/s, 1 other event/s). The + "Load model at recorded rates" section uses rates from recorded hosted runs; + the API rate (0.3/s) is still an assumption. - Staging's pool size and run-log storage mode were not read. - Tool-gateway calls, recovery sweeps, and browser fan-out are not in the model. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 7a362b0ae71..2860e95c383 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -271,9 +271,37 @@ export function postgresJsOptions(options: DatabaseClientOptions): Record Db>(); const ownedDatabaseListenerFactories = new WeakMap Db>(); +export const DEDICATED_CONNECTION_IDLE_MAX = 4; + +type DedicatedConnectionSet = { + create(): Db; + idle: Db[]; + ended: WeakSet; + closed: boolean; +}; +const dedicatedConnectionSets = new WeakMap(); + +function trackClientEnd(client: Db, onEnd: (timeoutSeconds: number | undefined) => Promise | void): void { + const sql = client.$client; + const end = sql.end; + sql.end = async (options?: { timeout?: number }) => { + await Promise.all([onEnd(options?.timeout), end(options)]); + }; +} + +async function endDedicatedConnections(clients: Db[], timeoutSeconds: number): Promise { + await Promise.all(clients.map(client => client.$client.end({ timeout: timeoutSeconds }).catch(() => undefined))); +} + +export async function closeDedicatedDbConnections(db: Db, timeoutSeconds: number): Promise { + const set = dedicatedConnectionSets.get(db); + if (!set) return; + set.closed = true; + await endDedicatedConnections(set.idle.splice(0), timeoutSeconds); +} + export interface OwnedDatabaseListener { listen: Db["$client"]["listen"]; close(): Promise; @@ -290,11 +318,26 @@ export function createOwnedDatabaseListener(db: Db): OwnedDatabaseListener { } export async function withDedicatedDbConnection(db: Db, action: (dedicated: Db) => Promise): Promise { - const factory = dedicatedDbFactories.get(db); - if (!factory) throw new Error("dedicated_connection_requires_create_db"); - const dedicated = factory(); - try { return await action(dedicated); } - finally { await dedicated.$client.end({ timeout: 1 }); } + const set = dedicatedConnectionSets.get(db); + if (!set) throw new Error("dedicated_connection_requires_create_db"); + let dedicated: Db | undefined; + while (!dedicated && set.idle.length) { + const candidate = set.idle.pop()!; + if (!set.ended.has(candidate)) dedicated = candidate; + } + dedicated ??= set.create(); + let completed = false; + try { + const result = await action(dedicated); + completed = true; + return result; + } finally { + if (completed && !set.closed && !set.ended.has(dedicated) && set.idle.length < DEDICATED_CONNECTION_IDLE_MAX) { + set.idle.push(dedicated); + } else if (!set.ended.has(dedicated)) { + await dedicated.$client.end({ timeout: 1 }); + } + } } // postgres.js pipelines a query onto a busy connection when none is idle, so @@ -420,7 +463,7 @@ export function createDb(url: string, options?: DatabaseClientOptions) { return createDbClient(url, resolved); } -function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: object) { +function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: object, dedicatedSet?: DedicatedConnectionSet) { const sql = postgres(url, postgresJsOptions(resolved)); if (resolved.prepare === true) installPreparedQueries(sql); const key = hostPortKeyOrNull(url); @@ -431,9 +474,22 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob // that know the complete operation is idempotent. const db = installDatabaseWorkSignals(drizzleWithLazyTransactionQueries(sql, schema), owner); installDatabaseResponseCapture(db, schema); - dedicatedDbFactories.set(db, () => createDbClient(url, { - ...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock", - }, db)); + const ownerSet = owner ? dedicatedConnectionSets.get(owner) : undefined; + if (dedicatedSet) { + trackClientEnd(db, () => { dedicatedSet.ended.add(db); }); + dedicatedConnectionSets.set(db, dedicatedSet); + } else if (ownerSet) { + dedicatedConnectionSets.set(db, ownerSet); + } else { + const set: DedicatedConnectionSet = { + create: () => createDbClient(url, { + ...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock", + }, db, set), + idle: [], ended: new WeakSet(), closed: false, + }; + dedicatedConnectionSets.set(db, set); + trackClientEnd(db, timeoutSeconds => closeDedicatedDbConnections(db, timeoutSeconds ?? 1)); + } ownedDatabaseListenerFactories.set(db, () => createDbClient(url, { ...resolved, maxConnections: 1, }, db)); diff --git a/packages/db/src/dedicated-connection-pool.test.ts b/packages/db/src/dedicated-connection-pool.test.ts new file mode 100644 index 00000000000..74933f3ec31 --- /dev/null +++ b/packages/db/src/dedicated-connection-pool.test.ts @@ -0,0 +1,194 @@ +import { sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { + DEDICATED_CONNECTION_IDLE_MAX, + closeDedicatedDbConnections, + createDb, + withDedicatedDbConnection, + type Db, +} from "./client.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const APPLICATION_NAME = "paperclip-workspace-finalization-lock"; + +type Session = { pid: number; backendStart: string }; + +async function session(db: Pick): Promise { + const [row] = await db.execute<{ pid: number; backend_start: string }>(sql`select pg_backend_pid() as pid, + (select backend_start::text from pg_stat_activity where pid = pg_backend_pid()) as backend_start`); + return { pid: Number(row.pid), backendStart: String(row.backend_start) }; +} + +const key = (value: Session) => `${value.pid}@${value.backendStart}`; + +async function eventually(read: () => Promise, accept: (value: T) => boolean): Promise { + const deadline = Date.now() + 5_000; + for (;;) { + const value = await read(); + if (accept(value) || Date.now() > deadline) return value; + await new Promise(resolve => setTimeout(resolve, 25)); + } +} + +describe.skipIf(!support.supported)("withDedicatedDbConnection connection reuse", () => { + let temporary: Awaited>; + let observer: Db; + const owners: Db[] = []; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("dedicated-pool-"); + observer = createDb(temporary.connectionString, { maxConnections: 1, applicationName: "dedicated-pool-observer" }); + }, 90_000); + afterEach(async () => { + for (const db of owners.splice(0)) { + await closeDedicatedDbConnections(db, 1); + await db.$client.end({ timeout: 1 }); + } + }); + afterAll(async () => { + await observer?.$client.end({ timeout: 1 }); + await temporary?.cleanup(); + }); + + function owner() { + const db = createDb(temporary.connectionString, { maxConnections: 2 }); + owners.push(db); + return db; + } + + async function openDedicatedSessions(): Promise { + const rows = await observer.execute<{ pid: number; backend_start: string }>(sql`select pid, backend_start::text as backend_start + from pg_stat_activity where application_name = ${APPLICATION_NAME} and datname = current_database()`); + return rows.map(row => ({ pid: Number(row.pid), backendStart: String(row.backend_start) })); + } + + it("reuses a bounded set of physical connections across 200 sequential calls", async () => { + const db = owner(); + const seen = new Set(); + for (let i = 0; i < 200; i++) { + seen.add(key(await withDedicatedDbConnection(db, dedicated => dedicated.transaction(tx => session(tx))))); + } + expect(seen.size).toBe(1); + expect(seen.size).toBeLessThanOrEqual(DEDICATED_CONNECTION_IDLE_MAX); + }); + + it("gives concurrent callers exclusive sessions and keeps at most the cap open afterwards", async () => { + const db = owner(); + const concurrency = DEDICATED_CONNECTION_IDLE_MAX + 3; + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + let arrived = 0; + let allArrived!: () => void; + const everyoneHolding = new Promise(resolve => { allArrived = resolve; }); + const held = Array.from({ length: concurrency }, () => withDedicatedDbConnection(db, dedicated => + dedicated.transaction(async tx => { + const mine = await session(tx); + await tx.execute(sql`select pg_advisory_xact_lock(${mine.pid})`); + if (++arrived === concurrency) allArrived(); + await gate; + expect(await session(tx)).toEqual(mine); + return mine; + }))); + await everyoneHolding; + release(); + const sessions = await Promise.all(held); + expect(new Set(sessions.map(key)).size).toBe(concurrency); + expect((await eventually(openDedicatedSessions, open => open.length <= DEDICATED_CONNECTION_IDLE_MAX)).length) + .toBeLessThanOrEqual(DEDICATED_CONNECTION_IDLE_MAX); + const retained = new Set(sessions.map(key)); + for (let i = 0; i < 20; i++) { + expect(retained.has(key(await withDedicatedDbConnection(db, session)))).toBe(true); + } + }); + + it("discards a connection whose action failed mid-transaction", async () => { + const db = owner(); + let failed: Session | undefined; + await expect(withDedicatedDbConnection(db, dedicated => dedicated.transaction(async tx => { + failed = await session(tx); + await tx.execute(sql`select 1 / 0`); + }))).rejects.toThrow(); + expect(failed).toBeDefined(); + const next = await withDedicatedDbConnection(db, session); + expect(key(next)).not.toBe(key(failed!)); + const open = await eventually(openDedicatedSessions, rows => !rows.map(key).includes(key(failed!))); + expect(open.map(key)).not.toContain(key(failed!)); + }); + + it("discards a connection whose socket broke during the action", async () => { + const db = owner(); + let broken: Session | undefined; + await expect(withDedicatedDbConnection(db, async dedicated => { + broken = await session(dedicated); + await observer.execute(sql`select pg_terminate_backend(${broken.pid})`); + await session(dedicated); + })).rejects.toThrow(); + const next = await withDedicatedDbConnection(db, session); + expect(next.pid).not.toBe(broken!.pid); + }); + + it("recovers when an idle retained connection is terminated between calls", async () => { + const db = owner(); + const first = await withDedicatedDbConnection(db, session); + await observer.execute(sql`select pg_terminate_backend(${first.pid})`); + await eventually(openDedicatedSessions, rows => !rows.some(row => row.pid === first.pid)); + await new Promise(resolve => setTimeout(resolve, 50)); + const second = await withDedicatedDbConnection(db, session); + expect(second.pid).not.toBe(first.pid); + }); + + it("never reuses a connection the action ended itself", async () => { + const db = owner(); + const first = await withDedicatedDbConnection(db, async dedicated => { + const value = await session(dedicated); + await dedicated.$client.end({ timeout: 0 }); + return value; + }); + const second = await withDedicatedDbConnection(db, session); + expect(second.pid).not.toBe(first.pid); + }); + + it("keeps transaction-local settings out of the next action", async () => { + const db = owner(); + await withDedicatedDbConnection(db, dedicated => dedicated.transaction(tx => + tx.execute(sql`select set_config('statement_timeout', '1234', true), set_config('lock_timeout', '567', true)`))); + const [row] = await withDedicatedDbConnection(db, dedicated => dedicated.execute<{ statement_timeout: string; lock_timeout: string }>( + sql`select current_setting('statement_timeout') as statement_timeout, current_setting('lock_timeout') as lock_timeout`)); + expect(row).toEqual({ statement_timeout: "0", lock_timeout: "0" }); + }); + + it("closes every retained connection on shutdown and stays usable without retaining more", async () => { + const db = owner(); + await Promise.all(Array.from({ length: DEDICATED_CONNECTION_IDLE_MAX }, () => + withDedicatedDbConnection(db, dedicated => dedicated.transaction(async tx => { + await tx.execute(sql`select pg_sleep(0.05)`); + })))); + expect((await openDedicatedSessions()).length).toBeGreaterThan(0); + await closeDedicatedDbConnections(db, 1); + expect(await eventually(openDedicatedSessions, rows => rows.length === 0)).toEqual([]); + await withDedicatedDbConnection(db, session); + expect(await eventually(openDedicatedSessions, rows => rows.length === 0)).toEqual([]); + }); + + it("closes retained connections when the owner client ends", async () => { + const db = createDb(temporary.connectionString, { maxConnections: 1 }); + await withDedicatedDbConnection(db, session); + expect((await openDedicatedSessions()).length).toBe(1); + await db.$client.end({ timeout: 1 }); + expect(await eventually(openDedicatedSessions, rows => rows.length === 0)).toEqual([]); + }); + + it("shares one retained set with nested dedicated actions without blocking them", async () => { + const db = owner(); + const [outer, inner] = await withDedicatedDbConnection(db, async dedicated => { + const mine = await session(dedicated); + const nested = await withDedicatedDbConnection(dedicated, session); + return [mine, nested]; + }); + expect(inner.pid).not.toBe(outer.pid); + const reused = new Set(); + for (let i = 0; i < 10; i++) reused.add((await withDedicatedDbConnection(db, session)).pid); + expect([...reused].every(pid => pid === outer.pid || pid === inner.pid)).toBe(true); + }); +}); diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 7e41782d377..fa0e2d7bdde 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -1,6 +1,8 @@ export { createDb, withDedicatedDbConnection, + closeDedicatedDbConnections, + DEDICATED_CONNECTION_IDLE_MAX, createOwnedDatabaseListener, type OwnedDatabaseListener, livenessDb, diff --git a/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts b/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts index 33f017f8e0f..ac6562d55d6 100644 --- a/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts +++ b/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts @@ -219,6 +219,30 @@ describe("HarnessDriverBackend", () => { expect(recover.mock.calls[0]![0].codexUsageBaseline!.latest.inputTokens).toBe(150); }); + it.each([true, false])("carries the provider-turn wait marker through a serialized native checkpoint only while waiting (%s)", async (awaiting) => { + class WaitSession extends FakeHarnessSession { + override async snapshot(): Promise { + return { ...(await super.snapshot()), semanticResult: undefined, activeTurnId: null, + ...(awaiting ? { awaitingProviderTurn: true } : {}) }; + } + } + const original = new HarnessDriverBackend({ ...driver, openSession: async () => new WaitSession() }); + const session = await original.openSession({ identity: { + runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1", + } }); + const checkpoint = JSON.parse(JSON.stringify(await session.snapshot())); + const recover = vi.fn(async (_snapshot: PersistedHarnessSession) => ({ recovered: true, session: new WaitSession() })); + await new HarnessDriverBackend({ ...driver, recoverSession: recover }) + .recoverSession(checkpoint, { signal: new AbortController().signal }); + if (awaiting) { + expect(checkpoint.awaitingProviderTurn).toBe(true); + expect(recover.mock.calls[0]![0].awaitingProviderTurn).toBe(true); + } else { + expect(checkpoint).not.toHaveProperty("awaitingProviderTurn"); + expect(recover.mock.calls[0]![0]).not.toHaveProperty("awaitingProviderTurn"); + } + }); + it("rejects and closes a provider session without a durable provider identity", async () => { let closed = false; class MissingProviderIdentitySession extends FakeHarnessSession { diff --git a/packages/paperclip-runner/src/backends/harness-driver-backend.ts b/packages/paperclip-runner/src/backends/harness-driver-backend.ts index e3922fb36b9..b45e0b9bf50 100644 --- a/packages/paperclip-runner/src/backends/harness-driver-backend.ts +++ b/packages/paperclip-runner/src/backends/harness-driver-backend.ts @@ -153,6 +153,7 @@ export class HarnessDriverBackend implements NativeSessionBackend { pendingRuntimeRequests: snapshot.pendingRuntimeRequests ?? [], goal: snapshot.goal ?? null, lineage: snapshot.lineage ?? [], + ...(snapshot.awaitingProviderTurn === true ? { awaitingProviderTurn: true } : {}), }; const recoveryOptions: HarnessSessionRecoveryOptions = { signal: options.signal, @@ -918,6 +919,7 @@ class HarnessNativeSession implements NativeSession { pendingRuntimeRequests: snapshot.pendingRuntimeRequests ?? [], goal: snapshot.goal ?? null, lineage: snapshot.lineage ?? [], + ...(snapshot.awaitingProviderTurn === true ? { awaitingProviderTurn: true } : {}), }; } diff --git a/packages/paperclip-runner/src/contracts/harness-driver.ts b/packages/paperclip-runner/src/contracts/harness-driver.ts index 14b3aae458f..37091f4042d 100644 --- a/packages/paperclip-runner/src/contracts/harness-driver.ts +++ b/packages/paperclip-runner/src/contracts/harness-driver.ts @@ -505,6 +505,7 @@ export interface PersistedHarnessSession { | "same_session_only" | "allow_replacement_after_governed_wait" | "allow_replacement_after_resume_failure"; + awaitingProviderTurn?: boolean; } /** Runner proof that saved provider state cannot be restored by this runner diff --git a/packages/paperclip-runner/src/contracts/native-session-backend.ts b/packages/paperclip-runner/src/contracts/native-session-backend.ts index fcd43490e2f..e8ce03c19dc 100644 --- a/packages/paperclip-runner/src/contracts/native-session-backend.ts +++ b/packages/paperclip-runner/src/contracts/native-session-backend.ts @@ -80,6 +80,7 @@ export interface PersistedNativeSession { pendingRuntimeRequests?: HarnessRuntimeRequest[]; goal?: HarnessThreadGoal | null; lineage?: HarnessThreadLineageEntry[]; + awaitingProviderTurn?: boolean; } export interface NativeSessionRecoveryResult { diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts index f5fa26a6a28..83feb7983a0 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts @@ -771,6 +771,7 @@ export class CodexAppServerDriver implements HarnessDriver { codexUsageBaseline: snapshot.codexUsageBaseline, dispositionOnlyRecoveryConsumed, dispositionOnlyRecoveryTurnId, + awaitingProviderTurn: snapshot.awaitingProviderTurn, adoptedAcceptedTurnId, lostAcceptedTurnId, stalePendingRuntimeRequests: snapshot.pendingRuntimeRequests ?? [], @@ -1108,6 +1109,7 @@ export class CodexAppServerDriver implements HarnessDriver { codexUsageBaseline?: PersistedHarnessSession["codexUsageBaseline"]; dispositionOnlyRecoveryConsumed?: boolean; dispositionOnlyRecoveryTurnId?: string | null; + awaitingProviderTurn?: boolean; adoptedAcceptedTurnId?: string | null; lostAcceptedTurnId?: string | null; stalePendingRuntimeRequests?: HarnessRuntimeRequest[]; diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts new file mode 100644 index 00000000000..ad30df81663 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts @@ -0,0 +1,232 @@ +import { + FakeCodexTransport, + HarnessOperationAlreadyTerminalError, + HarnessStaleTurnError, + WORKSPACE, + collectUntilTerminal, + describe, + expect, + it, + makeDriver, + result, +} from "./codex-app-server-driver.test-support.js"; +import { RUNNERD_RUN_TERMINAL } from "./codex-driver-values.js"; + +async function completedFirstTurn(awaiting: boolean) { + const transport = new FakeCodexTransport(); + const session = await makeDriver([transport]).openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + await session.startTurn({ message: { role: "user", text: "Start a background install." } }); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "turn-1", status: "inProgress" } }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "completed", items: [] }, + ...(awaiting ? { awaitingProviderTurn: true } : {}) }); + const events = session.events()[Symbol.asyncIterator](); + const first = await collectUntilTerminal({ [Symbol.asyncIterator]: () => events }); + return { transport, session, events, first }; +} + +async function restoredAfterFirstTurn(awaiting: boolean) { + const first = new FakeCodexTransport(); + const second = new FakeCodexTransport(); + const driver = makeDriver([first, second]); + const original = await driver.openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + await original.startTurn({ message: { role: "user", text: "Start a background install." } }); + first.push("turn/started", { threadId: "thread-1", turn: { id: "turn-1", status: "inProgress" } }); + first.push("turn/completed", { threadId: "thread-1", turn: { id: "turn-1", status: "completed", items: [] }, + ...(awaiting ? { awaitingProviderTurn: true } : {}) }); + await collectUntilTerminal(original.events()); + const checkpoint = await original.snapshot(); + await original.close({ reason: "controller restarted" }); + second.readResponse = { thread: { id: "thread-1", sessionId: "provider-session-1", cwd: WORKSPACE, + turns: [{ id: "turn-1", status: "completed", items: [] }] } }; + const recovery = await driver.recoverSession!(checkpoint); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + return { transport: second, session, checkpoint, events: session.events()[Symbol.asyncIterator]() }; +} + +async function reconciledActiveTurn(awaiting: boolean) { + const first = new FakeCodexTransport(); + const second = new FakeCodexTransport(); + const driver = makeDriver([first, second]); + const original = await driver.openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + await original.startTurn({ message: { role: "user", text: "Start a background install." } }); + const checkpoint = await original.snapshot(); + expect(checkpoint.activeTurnId).toBe("turn-1"); + await original.close({ reason: "controller restarted" }); + second.readResponse = { thread: { id: "thread-1", sessionId: "provider-session-1", cwd: WORKSPACE, + turns: [{ id: "turn-1", status: "completed", items: [], ...(awaiting ? { awaitingProviderTurn: true } : {}) }] } }; + const recovery = await driver.recoverSession!(checkpoint); + expect(recovery).toMatchObject({ recovered: true }); + const session = recovery.session!; + return { transport: second, session, events: session.events()[Symbol.asyncIterator]() }; +} + +async function nextUntil(events: AsyncIterator<{ eventType: string; payload: Record }>, done: (eventType: string) => boolean) { + const collected: Array<{ eventType: string; payload: Record; turnId?: string }> = []; + for (;;) { + const next = await events.next(); + if (next.done) return collected; + collected.push(next.value); + if (done(next.value.eventType)) return collected; + } +} + +describe("Codex app-server driver with provider-started turns", () => { + it("marks an awaited terminal and adopts the provider's own next turn with its result", async () => { + const { transport, session, events, first } = await completedFirstTurn(true); + expect(first.at(-1)).toMatchObject({ eventType: "turn.completed", payload: { status: "completed", awaitingProviderTurn: true } }); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + transport.push("paperclip/runResult", { threadId: "thread-1", turnId: "provider-1", result }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "provider-1", status: "completed", items: [] } }); + const second = await nextUntil(events, eventType => eventType === "turn.completed"); + expect(second.some(event => event.eventType === "session.failed")).toBe(false); + expect(second.find(event => event.eventType === "turn.started")).toMatchObject({ turnId: "provider-1", payload: { origin: "provider" } }); + expect(second.at(-1)).toMatchObject({ eventType: "turn.completed", turnId: "provider-1" }); + expect(second.at(-1)!.payload).not.toHaveProperty("awaitingProviderTurn"); + expect((await session.snapshot()).semanticResult).toMatchObject({ result, turnId: "provider-1" }); + await session.close({ reason: "fixture complete" }); + }); + + it("still fails closed on a provider-started turn the Runner did not await", async () => { + const { transport, session, events, first } = await completedFirstTurn(false); + expect(first.at(-1)!.payload).not.toHaveProperty("awaitingProviderTurn"); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + const failed = await nextUntil(events, eventType => eventType === "session.failed"); + expect(failed.at(-1)).toMatchObject({ eventType: "session.failed", payload: { code: "turn_binding_mismatch" } }); + await session.close({ reason: "fixture complete" }).catch(() => undefined); + }); + + it("acknowledges an interrupt during the wait without sending one to the provider", async () => { + const { transport, session, events } = await completedFirstTurn(true); + await session.interrupt!({ reason: "Stop" }); + const acknowledged = await nextUntil(events, eventType => eventType === "item.completed"); + expect(acknowledged.at(-1)).toMatchObject({ payload: { kind: "interrupt_acknowledgement", status: "provider_turn_wait_ended" } }); + expect(transport.calls.some(request => request.method === "turn/interrupt")).toBe(false); + await session.close({ reason: "fixture complete" }); + }); + + it("never interrupts a running provider-started turn for the wait's own end", async () => { + const { transport, session, events } = await completedFirstTurn(true); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + await nextUntil(events, eventType => eventType === "turn.started"); + await expect(session.interrupt!({ turnId: "turn-1", reason: "cap" })).rejects.toBeInstanceOf(HarnessStaleTurnError); + expect(transport.calls.some(request => request.method === "turn/interrupt")).toBe(false); + await session.close({ reason: "fixture complete" }); + }); + + it("ends the wait on the Runner's run.terminal only while awaiting with no turn, and ignores a forged one", async () => { + const forged = await completedFirstTurn(true); + forged.transport.push("paperclip/runTerminal", { threadId: "thread-1" }); + forged.transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + const untouched = await nextUntil(forged.events, eventType => eventType === "turn.started"); + expect(untouched.some(event => event.payload.kind === "interrupt_acknowledgement")).toBe(false); + await forged.session.close({ reason: "fixture complete" }); + + const awaiting = await completedFirstTurn(true); + awaiting.transport.push("paperclip/runTerminal", { [RUNNERD_RUN_TERMINAL]: true, threadId: "thread-1" }); + const ended = await nextUntil(awaiting.events, eventType => eventType === "item.completed"); + expect(ended.filter(event => event.payload.kind === "interrupt_acknowledgement")).toHaveLength(1); + expect(ended.at(-1)).toMatchObject({ payload: { kind: "interrupt_acknowledgement", status: "provider_turn_wait_ended", cause: "run_terminal" } }); + expect(await awaiting.session.snapshot()).not.toHaveProperty("awaitingProviderTurn"); + awaiting.transport.push("paperclip/runTerminal", { [RUNNERD_RUN_TERMINAL]: true, threadId: "thread-1" }); + awaiting.transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + const afterSecond = await nextUntil(awaiting.events, eventType => eventType === "session.failed"); + expect(afterSecond.some(event => event.payload.kind === "interrupt_acknowledgement")).toBe(false); + await awaiting.session.close({ reason: "fixture complete" }).catch(() => undefined); + + const ordinary = await completedFirstTurn(false); + ordinary.transport.push("paperclip/runTerminal", { [RUNNERD_RUN_TERMINAL]: true, threadId: "thread-1" }); + ordinary.transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + const after = await nextUntil(ordinary.events, eventType => eventType === "session.failed"); + expect(after.some(event => event.payload.kind === "interrupt_acknowledgement")).toBe(false); + await ordinary.session.close({ reason: "fixture complete" }).catch(() => undefined); + }); + + it("keeps the wait across a controller restart and adopts the provider's own next turn", async () => { + const { transport, session, checkpoint, events } = await restoredAfterFirstTurn(true); + expect(checkpoint).toMatchObject({ activeTurnId: null, semanticResult: null, awaitingProviderTurn: true }); + expect(await session.snapshot()).toMatchObject({ awaitingProviderTurn: true }); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + transport.push("paperclip/runResult", { threadId: "thread-1", turnId: "provider-1", result }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "provider-1", status: "completed", items: [] } }); + const adopted = await nextUntil(events, eventType => eventType === "turn.completed" || eventType === "session.failed"); + expect(adopted.some(event => event.eventType === "session.failed")).toBe(false); + expect(adopted.find(event => event.eventType === "turn.started")).toMatchObject({ turnId: "provider-1", payload: { origin: "provider" } }); + expect(adopted.at(-1)).toMatchObject({ eventType: "turn.completed", turnId: "provider-1" }); + const settled = await session.snapshot(); + expect(settled.semanticResult).toMatchObject({ result, turnId: "provider-1" }); + expect(settled).not.toHaveProperty("awaitingProviderTurn"); + await session.close({ reason: "fixture complete" }); + }); + + it("marks a persisted active turn that a restart reconciles as awaiting, then adopts the provider's own next turn", async () => { + const { transport, session, events } = await reconciledActiveTurn(true); + const reconciled = await nextUntil(events, eventType => eventType === "turn.completed"); + expect(reconciled.at(-1)).toMatchObject({ eventType: "turn.completed", turnId: "turn-1", + payload: { status: "completed", awaitingProviderTurn: true } }); + expect(await session.snapshot()).toMatchObject({ activeTurnId: null, semanticResult: null, awaitingProviderTurn: true }); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + transport.push("paperclip/runResult", { threadId: "thread-1", turnId: "provider-1", result }); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: "provider-1", status: "completed", items: [] } }); + const adopted = await nextUntil(events, eventType => eventType === "turn.completed" || eventType === "session.failed"); + expect(adopted.some(event => event.eventType === "session.failed")).toBe(false); + expect(adopted.find(event => event.eventType === "turn.started")).toMatchObject({ turnId: "provider-1", payload: { origin: "provider" } }); + expect(adopted.at(-1)).toMatchObject({ eventType: "turn.completed", turnId: "provider-1" }); + expect((await session.snapshot()).semanticResult).toMatchObject({ result, turnId: "provider-1" }); + await session.close({ reason: "fixture complete" }); + }); + + it("reconciles an unmarked persisted active turn as an ordinary terminal", async () => { + const { transport, session, events } = await reconciledActiveTurn(false); + const reconciled = await nextUntil(events, eventType => eventType === "turn.completed"); + expect(reconciled.at(-1)).toMatchObject({ eventType: "turn.completed", turnId: "turn-1" }); + expect(reconciled.at(-1)!.payload).not.toHaveProperty("awaitingProviderTurn"); + expect(await session.snapshot()).not.toHaveProperty("awaitingProviderTurn"); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + const failed = await nextUntil(events, eventType => eventType === "session.failed"); + expect(failed.at(-1)).toMatchObject({ eventType: "session.failed", payload: { code: "turn_binding_mismatch" } }); + await session.close({ reason: "fixture complete" }).catch(() => undefined); + }); + + it("writes no wait marker in a snapshot taken outside a wait", async () => { + const ordinary = await completedFirstTurn(false); + expect(await ordinary.session.snapshot()).not.toHaveProperty("awaitingProviderTurn"); + await ordinary.session.close({ reason: "fixture complete" }); + const opened = await makeDriver([new FakeCodexTransport()]).openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + expect(await opened.snapshot()).not.toHaveProperty("awaitingProviderTurn"); + await opened.close({ reason: "fixture complete" }); + }); + + it("still fails closed on a provider-started turn after a restore with no wait", async () => { + const { transport, session, checkpoint, events } = await restoredAfterFirstTurn(false); + expect(checkpoint).not.toHaveProperty("awaitingProviderTurn"); + transport.push("turn/started", { threadId: "thread-1", turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }); + const failed = await nextUntil(events, eventType => eventType === "session.failed"); + expect(failed.at(-1)).toMatchObject({ eventType: "session.failed", payload: { code: "turn_binding_mismatch" } }); + await session.close({ reason: "fixture complete" }).catch(() => undefined); + }); + + it("acknowledges an interrupt during a restored wait without sending one to the provider", async () => { + const { transport, session, events } = await restoredAfterFirstTurn(true); + await session.interrupt!({ reason: "Stop" }); + let acknowledged = await events.next(); + while (!acknowledged.done && acknowledged.value.payload.kind !== "interrupt_acknowledgement") acknowledged = await events.next(); + expect(acknowledged.value).toMatchObject({ payload: { kind: "interrupt_acknowledgement", status: "provider_turn_wait_ended" } }); + expect(transport.calls.some(request => request.method === "turn/interrupt")).toBe(false); + await session.close({ reason: "fixture complete" }); + }); + + it("keeps rejecting an interrupt after a terminal that does not await", async () => { + const { session } = await completedFirstTurn(false); + await expect(session.interrupt!({ reason: "Stop" })).rejects.toBeInstanceOf(HarnessOperationAlreadyTerminalError); + await session.close({ reason: "fixture complete" }); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/codex/codex-driver-values.ts b/packages/paperclip-runner/src/drivers/codex/codex-driver-values.ts index 241d91e5663..02283ba02ce 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-driver-values.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-driver-values.ts @@ -43,6 +43,7 @@ export const RUNNERD_CANONICAL_ITEM = Symbol.for( ); export const RUNNERD_RUNTIME_ACTIVITY = Symbol("paperclip.runnerd.runtime-activity"); +export const RUNNERD_RUN_TERMINAL = Symbol("paperclip.runnerd.run-terminal"); export function text(value: unknown, fallback = ""): string { return typeof value === "string" ? value : fallback; diff --git a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts index ca2de721d59..ac4cd9d581e 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts @@ -476,6 +476,19 @@ export class CodexHarnessSession ); return; } + if (this.awaitingProviderTurn && this.activeTurnId === null && !this.turnStartPending) { + this.emit( + "item.completed", + { + kind: "interrupt_acknowledgement", + text: "Paperclip stopped waiting for the provider's own next turn.", + status: "provider_turn_wait_ended", + reason: boundedText(input.reason), + }, + { itemId: `interrupt:provider-turn-wait:${++this.interruptSequence}` }, + ); + return; + } if (this.terminal || this.activeTurnId === null) { throw new HarnessOperationAlreadyTerminalError("interruption"); } @@ -836,7 +849,7 @@ export class CodexHarnessSession ["completed", "failed", "interrupted", "cancelled"].includes(status) ) { reconciledTerminalTurnId = expectedTurnId; - mapTerminalTurn(this, expectedTurn, expectedTurnId, true); + mapTerminalTurn(this, expectedTurn, expectedTurnId, true, expectedTurn.awaitingProviderTurn === true); } else { throw new HarnessReconciliationError( `persisted active turn ${expectedTurnId} has unreconcilable status ${status || "missing"}`, @@ -920,6 +933,7 @@ export class CodexHarnessSession this.currentGoal === null ? null : structuredClone(this.currentGoal), lineage: this.lineage(), lastSourceSequence: this.sourceSequence, + ...(this.awaitingProviderTurn ? { awaitingProviderTurn: true } : {}), }; } diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts index 5a2ba36ad28..e33481395e9 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts @@ -30,6 +30,7 @@ import { recordWorkspaceChanges, } from "./codex-session-workspace.js"; import { + RUNNERD_RUN_TERMINAL, RUNNERD_RUNTIME_ACTIVITY, boundedText, differingJsonPaths, @@ -152,6 +153,19 @@ async function mapNotification(state: CodexSessionState, notification: CodexRpcN } async function mapNotificationBody(state: CodexSessionState, notification: CodexRpcNotification): Promise { + if (notification.method === "paperclip/runTerminal") { + if ((notification.params as Record)[RUNNERD_RUN_TERMINAL] !== true) return; + if (state.awaitingProviderTurn && state.activeTurnId === null && !state.turnStartPending) { + state.awaitingProviderTurn = false; + state.emit("item.completed", { + kind: "interrupt_acknowledgement", + text: "The Runner ended the wait for the provider's own next turn.", + status: "provider_turn_wait_ended", + cause: "run_terminal", + }, { itemId: `interrupt:provider-turn-wait:run-terminal:${state.sourceSequence + 1}` }); + } + return; + } if (notification.method === "paperclip/runtimeActivityRecorded") { const params = notification.params; if ((params as Record)[RUNNERD_RUNTIME_ACTIVITY] !== true) return; @@ -538,7 +552,8 @@ async function mapNotificationBody(state: CodexSessionState, notification: Codex state.recordHistoryEvent(notification.method, turnId); return; } - const autonomousGoalTurn = state.currentGoal?.status === "active" + const providerStartedTurn = params.origin === "provider" && state.awaitingProviderTurn; + const autonomousGoalTurn = (state.currentGoal?.status === "active" || providerStartedTurn) && state.activeTurnId === null && !state.turnStartPending && !state.protocolFailed @@ -569,9 +584,10 @@ async function mapNotificationBody(state: CodexSessionState, notification: Codex state.activeTurnId = turnId; state.turnStartPending = false; state.turnStarted = true; + state.awaitingProviderTurn = false; state.emit( "turn.started", - { status: text(turn.status, "inProgress") }, + { status: text(turn.status, "inProgress"), ...(providerStartedTurn ? { origin: "provider" } : {}) }, { turnId }, ); return; @@ -608,7 +624,7 @@ async function mapNotificationBody(state: CodexSessionState, notification: Codex } if (ignoreUnboundRestoredTurnLoss(state, turn, turnId)) return; if (!state.notificationNamesActiveTurn(turnId, "turn terminal")) return; - mapTerminalTurn(state, turn, turnId); + mapTerminalTurn(state, turn, turnId, false, params.awaitingProviderTurn === true); return; } if (notification.method === "item/started") { diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts index 5314dd5ae66..3a7ca9270db 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts @@ -161,6 +161,7 @@ export class CodexSessionState { * stricter consumed marker. */ restartContinuationTurnId: string | null = null; + awaitingProviderTurn = false; turnStarted = false; readonly terminalTurns = new Map(); /** @@ -217,6 +218,7 @@ export class CodexSessionState { codexUsageBaseline?: CodexUsageBaseline; dispositionOnlyRecoveryConsumed?: boolean; dispositionOnlyRecoveryTurnId?: string | null; + awaitingProviderTurn?: boolean; /** A recovered turn whose turn.accepted the previous controller never emitted. */ adoptedAcceptedTurnId?: string | null; /** A turn the runner accepted for an earlier generation that the restore lost. */ @@ -309,6 +311,8 @@ export class CodexSessionState { if (this.activeTurnId && this.terminalTurns.has(this.activeTurnId)) { this.activeTurnId = null; } + this.awaitingProviderTurn = input.awaitingProviderTurn === true && this.activeTurnId === null + && this.result === null && this.terminalTurns.size > 0; const dispositionOnlyRecoveryPreviouslyConsumed = input.dispositionOnlyRecoveryConsumed ?? false; const dispositionOnlyRecoveryTurnId = diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts index f344b5af03b..736c0166349 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts @@ -153,6 +153,7 @@ export function mapTerminalTurn( turn: Record, fallbackTurnId: string, reconciling = false, + awaitingProviderTurn = false, ): void { const turnId = text(turn.id, fallbackTurnId || state.activeTurnId || ""); const reported = turn; @@ -214,9 +215,11 @@ export function mapTerminalTurn( state.cancelPendingRequests("turn_terminal"); state.activeTurnId = null; state.turnStarted = false; + state.awaitingProviderTurn = awaitingProviderTurn && eventType === "turn.completed" && state.result === null; const providerFailure = status === "failed" ? readProviderFailure(record(turn.error).providerFailure) ?? (state.driverKind === "codex_app_server" ? codexProviderFailure(turn.error, "turn", state.diagnosticEnvironment) : null) : null; - const payload = boundedPayload({ status, error: turn.error ?? null }); + const payload = boundedPayload({ status, error: turn.error ?? null, + ...(state.awaitingProviderTurn ? { awaitingProviderTurn: true } : {}) }); if (providerFailure) { payload.status = status; payload.error = { ...record(payload.error), providerFailure }; diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index fd34644dce6..1362b860048 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -34,6 +34,7 @@ export { summarizeCodexTurnDiff, } from "./drivers/codex/codex-turn-diff.js"; export * from "./native-session-runtime.js"; +export * from "./native-provider-turn-wait.js"; export * from "./steering-delivery.js"; export { DurablePrpControlPlane, diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index b983446b565..5169606853d 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -1962,6 +1962,27 @@ it("settles a restored turn from the runner's reconciled result terminal", () => expect(recovered([runTerminal], "turn-1")).toBeNull(); }); +it("carries the provider-turn wait marker on a recovered turn terminal only when the PRP turn.completed has it", () => { + const { runnerdRecoveredTurnTerminal: recovered, runnerdPriorTurnTerminals: prior } = runnerdRecoveryInternals; + const event = (eventType: string, payload: Record) => ({ eventType, envelope: { runId: "run-1", payload: { payload } } }); + const awaited = event("turn.completed", { providerTurnId: "turn-1", awaitingProviderTurn: true }); + const plain = event("turn.completed", { providerTurnId: "turn-1" }); + const failed = event("turn.failed", { providerTurnId: "turn-1", awaitingProviderTurn: true }); + const forged = event("turn.completed", { providerTurnId: "turn-1", awaitingProviderTurn: "true" }); + expect(recovered([awaited], "turn-1")).toEqual({ status: "completed", error: null, awaitingProviderTurn: true }); + expect(recovered([plain], "turn-1")).toStrictEqual({ status: "completed", error: null }); + expect(recovered([failed], "turn-1")).toStrictEqual({ status: "failed", error: null }); + expect(recovered([forged], "turn-1")).toStrictEqual({ status: "completed", error: null }); + expect([...prior([awaited], "run-1", "turn-2").values()]) + .toEqual([{ id: "turn-1", status: "completed", error: null, awaitingProviderTurn: true }]); + for (const unmarked of [plain, failed, forged]) { + expect([...prior([unmarked], "run-1", "turn-2").values()]) + .toStrictEqual([{ id: "turn-1", status: unmarked.eventType.slice("turn.".length), error: null }]); + } + expect(prior([awaited], "run-1", "turn-1").size).toBe(0); + expect(prior([awaited], "run-other", "turn-2").size).toBe(0); +}); + it("requires ACPX command results to preserve the requested turn identity", () => { expect( runnerdRecoveryInternals.turnStartCommandResultValid({ diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 0fbecce161f..6fc75db84f2 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -886,8 +886,35 @@ function turnStartResponseReady(input: { type RunnerdRecoveredTurnTerminal = { status: "completed" | "failed" | "interrupted" | "cancelled"; error: unknown; + awaitingProviderTurn?: true; }; +function awaitingProviderTurnMarker(eventType: string, payload: Record): { awaitingProviderTurn?: true } { + return eventType === "turn.completed" && payload.awaitingProviderTurn === true ? { awaitingProviderTurn: true } : {}; +} + +function runnerdPriorTurnTerminals( + events: readonly Pick[], + runId: string | undefined, + boundTurnId: string, +): Map> { + const priorTerminals = new Map>(); + for (const event of events) { + if (event.envelope.runId !== runId || + !["turn.completed", "turn.failed", "turn.interrupted", "turn.cancelled"].includes(event.eventType)) continue; + const payload = record(record(event.envelope.payload).payload); + const turnId = payload.providerTurnId ?? payload.turnId ?? record(payload.turn).id; + if (typeof turnId !== "string" || !turnId || turnId === boundTurnId) continue; + priorTerminals.set(turnId, { + id: turnId, + status: event.eventType.slice("turn.".length), + error: payload.error ?? record(payload.turn).error ?? null, + ...awaitingProviderTurnMarker(event.eventType, payload), + }); + } + return priorTerminals; +} + const RUNNERD_TURN_TERMINAL_STATUSES = new Set(["completed", "failed", "interrupted", "cancelled"]); /** @@ -916,7 +943,8 @@ function runnerdRecoveredTurnTerminal( // Reconciliation must retain the cause, including the runner's explicit // process-loss marker, rather than inventing error:null. terminal = { status: event.eventType.slice("turn.".length) as RunnerdRecoveredTurnTerminal["status"], - error: payload.error ?? record(payload.turn).error ?? null }; + error: payload.error ?? record(payload.turn).error ?? null, + ...awaitingProviderTurnMarker(event.eventType, payload) }; reconciledEndedTurn = false; } else if (event.eventType === "run.terminal" && reconciledEndedTurn) { const status = String(payload.turnTerminalState); @@ -4652,19 +4680,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { // Keep its prior terminal as the history anchor, so driver recovery can // adopt the later accepted turn instead of submitting it again. Items // remain lazy and fail closed if their start left the retained window. - const priorTerminals = new Map>(); - for (const event of this.#core?.store.state.committedEvents ?? []) { - if (event.envelope.runId !== this.#core?.store.state.identity.runId || - !["turn.completed", "turn.failed", "turn.interrupted", "turn.cancelled"].includes(event.eventType)) continue; - const payload = record(record(event.envelope.payload).payload); - const turnId = payload.providerTurnId ?? payload.turnId ?? record(payload.turn).id; - if (typeof turnId !== "string" || !turnId || turnId === this.#turnId) continue; - priorTerminals.set(turnId, { - id: turnId, - status: event.eventType.slice("turn.".length), - error: payload.error ?? record(payload.turn).error ?? null, - }); - } + const priorTerminals = runnerdPriorTurnTerminals( + this.#core?.store.state.committedEvents ?? [], this.#core?.store.state.identity.runId, this.#turnId); recoveredTurns.unshift(...priorTerminals.values()); this.#recoveryTurnBindingPending = false; this.#pumpEvents(); @@ -9786,6 +9803,7 @@ export const runnerdRecoveryInternals = Object.freeze({ rotatedRunAttachPayload, localRunnerStateArchive, rotateAuthorityEpoch, + runnerdPriorTurnTerminals, runnerdRecoveredTurnTerminal, runnerdTerminalProviderTurnId, terminalMayBelongToPendingTurnStart, diff --git a/packages/paperclip-runner/src/native-provider-turn-wait.ts b/packages/paperclip-runner/src/native-provider-turn-wait.ts new file mode 100644 index 00000000000..3a9919b584e --- /dev/null +++ b/packages/paperclip-runner/src/native-provider-turn-wait.ts @@ -0,0 +1,129 @@ +import { HarnessStaleTurnError } from "./contracts/harness-driver.js"; +import type { NativeSession } from "./contracts/native-session-backend.js"; +import type { PrpEvent } from "./protocol/replay-contract.js"; + +export const PROVIDER_TURN_WAIT_CAP_MS = 600_000; +export const PROVIDER_TURN_WAIT_TIMEOUT_MARGIN_MS = 5_000; +const MAX_TIMER_MS = 2_147_483_647; + +export interface ProviderTurnWaitOptions { + startedAtMs?: number | null; + capMs?: number; + onWait?: (input: { startedAtMs: number; signal: AbortSignal }) => Promise; +} + +export type ProviderTurnWaitEnd = "cap" | "early" | "runner"; + +export function awaitsProviderTurn(event: PrpEvent): boolean { + return event.eventType === "turn.completed" && event.payload.awaitingProviderTurn === true; +} + +export function providerTurnWaitDeadline(input: { + startedAtMs: number; + capMs: number; + overallDeadlineMs: number | null; +}): number { + const cap = input.startedAtMs + input.capMs; + return input.overallDeadlineMs === null + ? cap + : Math.min(cap, input.overallDeadlineMs - PROVIDER_TURN_WAIT_TIMEOUT_MARGIN_MS); +} + +export function createProviderTurnWait(input: { + session: NativeSession; + options?: ProviderTurnWaitOptions; + overallDeadlineMs: number | null; + now?: () => number; +}) { + const now = input.now ?? Date.now; + const lifetime = new AbortController(); + let awaited: PrpEvent | null = null; + let idle = false; + let startedAtMs: number | null = null; + let ending: ProviderTurnWaitEnd | null = null; + let timer: ReturnType | undefined; + let force!: () => void; + const forced = new Promise(resolve => { force = () => resolve(null); }); + + const end = (reason: ProviderTurnWaitEnd) => { + if (ending !== null || lifetime.signal.aborted) return; + ending = reason; + clearTimeout(timer); + if (!idle) return; + const interrupt = input.session.interrupt; + if (interrupt === undefined) { + force(); + return; + } + void Promise.resolve() + .then(() => interrupt.call(input.session, { + ...(awaited?.turnId ? { turnId: awaited.turnId } : {}), + reason: reason === "cap" + ? "The provider did not start its own next turn within the wait limit." + : "A person commented while Paperclip waited for the provider's own next turn.", + })) + .catch((error: unknown) => { + if (!(error instanceof HarnessStaleTurnError)) force(); + }); + }; + + const schedule = (deadlineMs: number) => { + const remaining = deadlineMs - now(); + if (remaining <= 0) { + end("cap"); + return; + } + timer = setTimeout(() => schedule(deadlineMs), Math.min(remaining, MAX_TIMER_MS)); + timer.unref?.(); + }; + + return { + get started() { + return startedAtMs !== null; + }, + get ending() { + return ending; + }, + get awaitedTerminal() { + return awaited; + }, + forced, + begin(event: PrpEvent): boolean { + awaited = event; + idle = true; + if (ending !== null) return false; + if (startedAtMs === null) { + startedAtMs = Math.min(now(), input.options?.startedAtMs ?? Number.POSITIVE_INFINITY); + schedule(providerTurnWaitDeadline({ + startedAtMs, + capMs: input.options?.capMs ?? PROVIDER_TURN_WAIT_CAP_MS, + overallDeadlineMs: input.overallDeadlineMs, + })); + const onWait = input.options?.onWait; + if (ending === null && onWait) { + void Promise.resolve() + .then(() => onWait({ startedAtMs: startedAtMs!, signal: lifetime.signal })) + .then(() => end("early"), () => undefined); + } + } + return ending === null; + }, + observe(event: PrpEvent) { + if (event.eventType === "turn.started" && event.payload.origin === "provider") idle = false; + }, + endedBy(event: PrpEvent): boolean { + const ended = idle && event.eventType === "item.completed" + && event.payload.kind === "interrupt_acknowledgement" + && event.payload.status === "provider_turn_wait_ended"; + if (ended && ending === null && event.payload.cause === "run_terminal") { + ending = "runner"; + clearTimeout(timer); + } + return ended; + }, + dispose() { + clearTimeout(timer); + lifetime.abort(); + }, + }; +} diff --git a/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts b/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts index 04fe166ad75..79f14a7ffdf 100644 --- a/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.provider-turn.test.ts @@ -1,9 +1,10 @@ import { describe, expect, it, vi } from "vitest"; import type { NativeExecutionInputV1 } from "./contracts/native-execution.js"; -import type { NativeSession } from "./contracts/native-session-backend.js"; +import type { NativeSession, PersistedNativeSession } from "./contracts/native-session-backend.js"; import { executeNativeSession } from "./native-session-runtime.js"; -import type { PrpEvent } from "./protocol/replay-contract.js"; +import { providerTurnWaitDeadline, PROVIDER_TURN_WAIT_TIMEOUT_MARGIN_MS, type ProviderTurnWaitOptions } from "./native-provider-turn-wait.js"; +import type { PrpEvent, PrpStructuredRunResult } from "./protocol/replay-contract.js"; const identity = { runId: "run-provider-turn", @@ -29,85 +30,580 @@ const input: NativeExecutionInputV1 = { credentialBindings: [], }; -const event = (sourceSeq: number, eventType: PrpEvent["eventType"], payload: Record): PrpEvent => ({ - schema: "paperclip.prp.event.v1", - sourceEventId: `runner-provider-turn:${identity.runId}:${sourceSeq}`, - sourceSeq, - sourceInstanceId: "runner-provider-turn", - sourceKind: "runner", - runId: identity.runId, - normalizedSessionId: identity.sessionId, - turnId: "turn-1", - eventType, - schemaVersion: 1, - priority: 0, - emittedAt: "2026-11-12T00:00:00.000Z", - payload, -}); +const result: PrpStructuredRunResult = { + schema: "paperclip.run_result.v1", + reportedWorkDisposition: "done", + summary: "Installed and tested after the background install finished.", + completionClaim: { contractRevision: "1", objectiveSatisfied: true, + criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }], remainingWork: [] }, + evidence: [], + verification: [{ commandOrCheck: "pnpm test", status: "passed" }], + attentionRequests: [], + artifacts: [], +}; -const usage = { provider: "acpx", model: null, providerSessionId: null, providerRequestId: null, - cumulative: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, activeSeconds: 0, requests: 1, providerCostUsd: 0 }, - runDeltaAvailable: true, - runDelta: { inputTokens: 6, outputTokens: 4, cacheReadTokens: 0, cacheWriteTokens: 0, activeSeconds: 0, requests: 1, providerCostUsd: 0 } }; +const planReviewWait: PrpStructuredRunResult = { + schema: "paperclip.run_result.v1", + reportedWorkDisposition: "yielded", + summary: "Waiting for the plan review.", + completionClaim: { contractRevision: "1", objectiveSatisfied: false, + criteria: [{ criterionId: "objective", status: "unknown", evidenceRefs: ["interaction:plan"] }], + remainingWork: [{ description: "Resume after the plan review.", blocksCompletion: true }] }, + evidence: [{ ref: "interaction:plan" }], + verification: [], + attentionRequests: [], + artifacts: [{ kind: "issue_thread_interaction", ref: "interaction:plan" }], + continuation: { kind: "response_wake", summary: "Resume from the plan review.", idempotencyKey: "interaction-response:plan" }, +}; -const turnOne = (awaiting: boolean): PrpEvent[] => [ - event(1, "turn.started", { provider: "acpx", providerTurnId: "turn-1", status: "inProgress", turn: { id: "turn-1", status: "inProgress" } }), - event(2, "usage.reported", usage), - event(3, "turn.completed", { provider: "acpx", providerTurnId: "turn-1", status: "completed", error: null, - ...(awaiting ? { awaitingProviderTurn: true } : {}) }), - ...(awaiting ? [] : [event(4, "run.terminal", { schema: "paperclip.prp.terminal.v1", status: "succeeded", turnTerminalState: "completed", - runTerminalState: "succeeded", reportedWorkDisposition: "done", provider: "acpx" })]), +let sequence = 0; +const event = (turnId: string, eventType: PrpEvent["eventType"], payload: Record = {}): PrpEvent => { + sequence += 1; + return { + schema: "paperclip.prp.event.v1", + sourceEventId: `runner-provider-turn:${identity.runId}:${sequence}`, + sourceSeq: sequence, + sourceInstanceId: "runner-provider-turn", + sourceKind: "runner", + runId: identity.runId, + normalizedSessionId: identity.sessionId, + turnId, + eventType, + schemaVersion: 1, + priority: 0, + emittedAt: "2026-11-12T00:00:00.000Z", + payload, + }; +}; + +const usage = { kind: "usage", usage: { runDeltaComplete: true, runDelta: { inputTokens: 6, outputTokens: 4 } } }; +const turnOne = (awaiting: boolean) => [ + event("turn-1", "turn.started", { status: "inProgress" }), + event("turn-1", "item.completed", usage), + event("turn-1", "turn.completed", { status: "completed", error: null, ...(awaiting ? { awaitingProviderTurn: true } : {}) }), +]; +const providerTurn = (turnId: string, options: { result?: boolean; awaiting?: boolean } = {}) => [ + event(turnId, "turn.started", { status: "inProgress", origin: "provider" }), + event(turnId, "item.completed", usage), + ...(options.result ? [event(turnId, "run.result.proposed", result as unknown as Record)] : []), + event(turnId, "turn.completed", { status: "completed", error: null, ...(options.awaiting ? { awaitingProviderTurn: true } : {}) }), ]; -const providerTurn: PrpEvent[] = [ - event(4, "turn.started", { provider: "acpx", providerTurnId: "provider-1", status: "inProgress", - turn: { id: "provider-1", status: "inProgress" }, origin: "provider" }), - event(5, "turn.completed", { provider: "acpx", providerTurnId: "provider-1", status: "completed", error: null }), -]; +const restartFailure = { code: "provider_turn_lost_on_restore", recoverable: true }; +const lostTerminal = { turnId: "turn-recovery", fingerprint: JSON.stringify({ terminalState: "failed", error: restartFailure, result: null }) }; +const completedTerminal = (turnId: string) => ({ turnId, fingerprint: JSON.stringify({ terminalState: "completed", error: null, result: null }) }); +const restartCheckpoint: PersistedNativeSession = { + backendKind: "mock", driverKind: "codex_app_server", sessionId: identity.sessionId, identity, + providerSessionId: "provider-session", cursor: "0", activeTurnId: null, + terminalTurns: [lostTerminal], semanticResult: null, pendingRuntimeRequests: [], lineage: [], +}; -async function finalize(stream: PrpEvent[]) { - const appended: PrpEvent[] = []; - const completeRun = vi.fn(async () => undefined); - const capabilities = { resume: false, typedEvents: true, steering: false, interruption: true, structuredResult: true }; +interface RestartContinuation { + onDisposition?: (push: (...values: Array) => void) => void; + recovery?: { checkpoint: PersistedNativeSession; snapshot: Partial; replay?: PrpEvent[] }; +} + +function harness(options: { withoutInterrupt?: boolean; restart?: RestartContinuation } = {}) { + const queue: Array = []; + let wake: (() => void) | null = null; + let activeProviderTurn: string | null = null; + const push = (...values: Array) => { + for (const value of values) { + if (value !== "end" && value.eventType === "turn.started") activeProviderTurn = value.turnId ?? null; + if (value !== "end" && value.eventType.startsWith("turn.") && value.eventType !== "turn.started") activeProviderTurn = null; + queue.push(value); + } + wake?.(); + }; + const interrupt = vi.fn(async (_input: { turnId?: string; reason?: string }) => { + if (activeProviderTurn) push(event(activeProviderTurn, "turn.cancelled", { status: "cancelled", error: null })); + else push(event("turn-1", "item.completed", { kind: "interrupt_acknowledgement", status: "provider_turn_wait_ended" })); + }); + const capabilities = { resume: options.restart !== undefined, typedEvents: true, steering: false, interruption: true, structuredResult: true }; + const startTurn = vi.fn(async (_input: Parameters[0]) => { + if (!options.restart) return { turnId: "turn-1" }; + if (options.restart.recovery) return { turnId: "turn-fresh" }; + if (startTurn.mock.calls.length === 1) { + push(event("turn-continuation", "turn.started", { status: "inProgress" }), event("turn-continuation", "item.completed", usage), + event("turn-continuation", "turn.completed", { status: "completed", error: null, awaitingProviderTurn: true })); + return { turnId: "turn-continuation", borrowedDispositionMarker: true as const }; + } + options.restart.onDisposition?.(push); + return { turnId: "turn-disposition" }; + }); const session: NativeSession = { identity: () => identity, async capabilities() { return capabilities; }, - async *events() { for (const value of stream) yield structuredClone(value); }, - async startTurn() { return { turnId: "turn-1" }; }, - async result() { return null; }, - async snapshot() { return { backendKind: "mock", sessionId: identity.sessionId, identity, - providerSessionId: "provider-session", cursor: String(stream.length), activeTurnId: "turn-1", pendingRuntimeRequests: [], lineage: [] }; }, - async close() {}, - }; - const outcome = await executeNativeSession({ - input, - backend: { async descriptor() { return { kind: "mock", name: "provider-turn", version: "1", capabilities }; }, async openSession() { return session; } }, - controlPlane: { - async openRun() {}, async checkpointSession() {}, - async appendEvent(value: PrpEvent) { - appended.push(structuredClone(value)); - return { cursor: value.sourceSeq, highestContiguousSourceSeq: value.sourceSeq, disposition: "committed" }; - }, - async replayEvents() { return { events: [], highestContiguousSourceSeq: 0 }; }, - completeRun, + async *events() { + for (;;) { + const next = queue.shift(); + if (next === "end") return; + if (next) { yield structuredClone(next); continue; } + await new Promise(resolve => { wake = resolve; }); + wake = null; + } }, - runnerInstanceId: "runner-provider-turn", controlPlaneInstanceId: "control-provider-turn", timeoutMs: 1000, - resolveMissingResult: async () => null, - }).then(() => "finalized", (error: unknown) => String(error instanceof Error ? error.message : error)); - return { outcome, appended, completeRun }; + startTurn, + ...(options.withoutInterrupt ? {} : { interrupt }), + async result() { return null; }, + async snapshot() { + const base: PersistedNativeSession = { backendKind: "mock", sessionId: identity.sessionId, identity, + providerSessionId: "provider-session", cursor: String(sequence), activeTurnId: null, pendingRuntimeRequests: [], lineage: [] }; + if (!options.restart) return base; + if (options.restart.recovery) return { ...base, ...options.restart.recovery.snapshot }; + const starts = startTurn.mock.calls.length; + return { ...base, semanticResult: null, + terminalTurns: [lostTerminal, ...(starts >= 1 ? [completedTerminal("turn-continuation")] : []), + ...(starts >= 2 ? [completedTerminal("turn-disposition")] : [])], + ...(starts >= 1 ? { dispositionOnlyRecoveryConsumed: starts >= 2, dispositionOnlyRecoveryTurnId: starts >= 2 ? "turn-disposition" : null } : {}) }; + }, + async close() { push("end"); }, + }; + return { session, push, interrupt, startTurn }; } -describe("today's controller consumer with provider-started turn sequences", () => { - it("finalizes a no-result turn with live shells exactly as before when the controller did not opt in", async () => { - const withoutOptIn = await finalize(turnOne(false)); - expect(withoutOptIn.outcome).toContain("native_finalization_missing"); - expect(withoutOptIn.completeRun).not.toHaveBeenCalled(); - expect(withoutOptIn.appended.map(value => value.eventType)).toEqual(["turn.started", "usage.reported", "turn.completed"]); +async function run(options: { + stream: PrpEvent[]; + after?: (control: ReturnType, appended: PrpEvent[]) => Promise | void; + providerTurnWait?: ProviderTurnWaitOptions; + turnTimeoutMs?: number; + missingResult?: (input: { turnId: string | null; terminalEvent: PrpEvent }) => PrpStructuredRunResult | null; + withoutInterrupt?: boolean; + pipelinesDeltas?: boolean; + restart?: RestartContinuation; +}) { + const control = harness({ withoutInterrupt: options.withoutInterrupt, restart: options.restart }); + const appended: PrpEvent[] = []; + const checkpoints: PersistedNativeSession[] = []; + let queued: Array<() => void> = []; + const flushStreamingEvents = vi.fn(() => { + const flushed = queued; + queued = []; + for (const commit of flushed) commit(); + }); + let returned: Awaited> | null = null; + const completeRun = vi.fn(async () => undefined); + const resolveMissingResult = vi.fn(async (value: { turnId: string | null; terminalEvent: PrpEvent }) => options.missingResult?.(value) ?? null); + control.push(...options.stream); + const capabilities = { resume: options.restart !== undefined, typedEvents: true, steering: false, interruption: true, structuredResult: true }; + const started = Date.now(); + const execution = executeNativeSession({ + input, + backend: { async descriptor() { return { kind: "mock", name: "provider-turn", version: "1", capabilities }; }, + async openSession() { return control.session; }, + ...(options.restart ? { async recoverSession() { return { recovered: true, session: control.session }; } } : {}) }, + controlPlane: { + ...(options.pipelinesDeltas ? { pipelinesStreamingEvents: true, flushStreamingEvents } : {}), + async openRun() {}, async checkpointSession(value: PersistedNativeSession) { checkpoints.push(structuredClone(value)); }, + async appendEvent(value: PrpEvent) { + appended.push(structuredClone(value)); + if (options.pipelinesDeltas && value.eventType === "item.delta") await new Promise(resolve => queued.push(resolve)); + return { cursor: value.sourceSeq, highestContiguousSourceSeq: value.sourceSeq, disposition: "committed" }; + }, + async replayEvents(request: { sourceInstanceId: string; afterSourceSeq: number }) { + const events = (options.restart?.recovery?.replay ?? []) + .filter(value => value.sourceInstanceId === request.sourceInstanceId && value.sourceSeq > request.afterSourceSeq); + return { events, highestContiguousSourceSeq: Math.max(0, ...events.map(value => value.sourceSeq)) }; + }, + completeRun, + }, + runnerInstanceId: "runner-provider-turn", controlPlaneInstanceId: "control-provider-turn", timeoutMs: 30_000, + ...(options.turnTimeoutMs === undefined ? {} : { turnTimeoutMs: options.turnTimeoutMs }), + resolveMissingResult, + providerTurnWait: options.providerTurnWait, + ...(options.restart ? { persistedSession: options.restart.recovery?.checkpoint ?? restartCheckpoint, resumeInterruptedTurn: true } : {}), + }).then((value) => { returned = value; return "finalized"; }, (error: unknown) => String(error instanceof Error ? error.message : error)); + await options.after?.(control, appended); + const outcome = await execution; + return { outcome, returned, appended, completeRun, resolveMissingResult, interrupt: control.interrupt, flushStreamingEvents, + startTurn: control.startTurn, checkpoints, elapsedMs: Date.now() - started }; +} + +const types = (events: PrpEvent[]) => events.map(value => value.eventType); +const waitFor = async (condition: () => boolean) => vi.waitFor(() => expect(condition()).toBe(true), { timeout: 5_000, interval: 5 }); + +describe("the controller consumer with provider-started turn sequences", () => { + it("finalizes a no-result turn exactly as before when the Runner did not await", async () => { + const outcome = await run({ stream: [...turnOne(false), ...providerTurn("provider-1", { result: true })] }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.completeRun).not.toHaveBeenCalled(); + expect(types(outcome.appended)).toEqual(["turn.started", "item.completed", "turn.completed"]); + expect(outcome.interrupt).not.toHaveBeenCalled(); }); - it("would end the run at the awaited terminal and never consume the provider-started turn, so the opt-in must stay off", async () => { - const optedIn = await finalize([...turnOne(true), ...providerTurn]); - expect(optedIn.outcome).toContain("native_finalization_missing"); - expect(optedIn.appended.some(value => value.payload.origin === "provider")).toBe(false); + it("consumes the provider-started turn as the next turn of the same run and settles its result normally", async () => { + const outcome = await run({ stream: [...turnOne(true), ...providerTurn("provider-1", { result: true })] }); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.completeRun).toHaveBeenCalledOnce(); + expect(outcome.resolveMissingResult).not.toHaveBeenCalled(); + expect(outcome.appended.filter(value => value.payload.origin === "provider").map(value => value.turnId)).toEqual(["provider-1"]); + expect(outcome.appended.filter(value => value.payload.kind === "usage").map(value => value.turnId)).toEqual(["turn-1", "provider-1"]); + expect(outcome.interrupt).not.toHaveBeenCalled(); + }); + + it("keeps waiting when a provider-started turn also ends awaiting, then settles the later turn's result", async () => { + const outcome = await run({ stream: [...turnOne(true), ...providerTurn("provider-1", { awaiting: true }), + ...providerTurn("provider-2", { result: true })] }); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.appended.filter(value => value.payload.origin === "provider").map(value => value.turnId)).toEqual(["provider-1", "provider-2"]); + }); + + it("ends an idle wait at the cap by stopping the wait, then takes today's missing-result path with the awaited terminal", async () => { + const outcome = await run({ stream: turnOne(true), providerTurnWait: { capMs: 100 } }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).toHaveBeenCalledOnce(); + expect(outcome.interrupt.mock.calls[0]![0]).toMatchObject({ turnId: "turn-1" }); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ + turnId: "turn-1", terminalEvent: expect.objectContaining({ eventType: "turn.completed", payload: expect.objectContaining({ awaitingProviderTurn: true }) }) })); + expect(outcome.elapsedMs).toBeGreaterThanOrEqual(90); + }); + + it("does not restart the cap when a later provider-started turn also ends without a result", async () => { + const outcome = await run({ + stream: turnOne(true), providerTurnWait: { capMs: 300 }, + after: async (control) => { + await new Promise(resolve => setTimeout(resolve, 200)); + control.push(...providerTurn("provider-1", { awaiting: true })); + }, + }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.elapsedMs).toBeLessThan(450); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ turnId: "provider-1" })); + }); + + it.each(["cap", "comment"] as const)("lets a running provider-started turn finish after the %s and settles its result normally", async (trigger) => { + let release!: () => void; + const comment = new Promise(resolve => { release = resolve; }); + const onWait = vi.fn(() => comment); + const outcome = await run({ + stream: turnOne(true), providerTurnWait: trigger === "cap" ? { capMs: 150 } : { capMs: 60_000, onWait }, + after: async (control) => { + control.push(event("provider-1", "turn.started", { status: "inProgress", origin: "provider" })); + if (trigger === "comment") { await waitFor(() => onWait.mock.calls.length === 1); release(); } + await new Promise(resolve => setTimeout(resolve, 300)); + control.push(event("provider-1", "item.completed", usage), event("provider-1", "run.result.proposed", result as unknown as Record), + event("provider-1", "turn.completed", { status: "completed", error: null })); + }, + }); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(outcome.completeRun).toHaveBeenCalledOnce(); + expect(outcome.appended.some(value => value.eventType === "turn.cancelled")).toBe(false); + }); + + it.each(["cap", "comment"] as const)("takes today's path at once when a provider-started turn running past the %s ends awaiting again", async (trigger) => { + let release!: () => void; + const comment = new Promise(resolve => { release = resolve; }); + const onWait = vi.fn(() => comment); + let endedAt = 0; + const outcome = await run({ + stream: turnOne(true), providerTurnWait: trigger === "cap" ? { capMs: 150 } : { capMs: 60_000, onWait }, + after: async (control) => { + control.push(event("provider-1", "turn.started", { status: "inProgress", origin: "provider" })); + if (trigger === "comment") { await waitFor(() => onWait.mock.calls.length === 1); release(); } + await new Promise(resolve => setTimeout(resolve, 300)); + endedAt = Date.now(); + control.push(event("provider-1", "item.completed", usage), + event("provider-1", "turn.completed", { status: "completed", error: null, awaitingProviderTurn: true })); + }, + }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ turnId: "provider-1" })); + expect(Date.now() - endedAt).toBeLessThan(1_000); + }); + + it("settles a batched delta that arrived during the idle wait before the limit ends the turn", async () => { + let delta!: PrpEvent; + const outcome = await run({ + stream: turnOne(true), providerTurnWait: { capMs: 150 }, withoutInterrupt: true, pipelinesDeltas: true, + missingResult: () => result, + after: async (control, appended) => { + await waitFor(() => appended.some(value => value.payload.awaitingProviderTurn === true)); + delta = { ...event("turn-1", "item.delta", { kind: "agentMessage", text: "late chunk" }), itemId: "message-1", priority: 1 }; + control.push(delta); + }, + }); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(outcome.flushStreamingEvents).toHaveBeenCalled(); + expect(outcome.appended.filter(value => value.eventType === "item.delta")).toHaveLength(1); + expect(outcome.returned).toMatchObject({ nativeEventCount: outcome.appended.length, highestContiguousSourceSeq: delta.sourceSeq }); + }); + + it("never waits longer than the run's remaining timeout", async () => { + const turnTimeoutMs = PROVIDER_TURN_WAIT_TIMEOUT_MARGIN_MS + 200; + const outcome = await run({ stream: turnOne(true), turnTimeoutMs }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.outcome).not.toContain("timed out"); + expect(outcome.elapsedMs).toBeLessThan(2_000); + expect(providerTurnWaitDeadline({ startedAtMs: 1_000, capMs: 600_000, overallDeadlineMs: null })).toBe(601_000); + expect(providerTurnWaitDeadline({ startedAtMs: 1_000, capMs: 600_000, overallDeadlineMs: 60_000 })) + .toBe(60_000 - PROVIDER_TURN_WAIT_TIMEOUT_MARGIN_MS); + }); + + it("resumes the cap from the wait start a previous controller recorded", async () => { + const outcome = await run({ stream: turnOne(true), providerTurnWait: { startedAtMs: Date.now() - 599_900 } }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.elapsedMs).toBeLessThan(2_000); + }); + + it("ends the wait early when the control plane reports a new comment", async () => { + let release!: () => void; + const comment = new Promise(resolve => { release = resolve; }); + const onWait = vi.fn(() => comment); + const outcome = await run({ + stream: turnOne(true), providerTurnWait: { capMs: 60_000, onWait }, + after: async () => { await waitFor(() => onWait.mock.calls.length === 1); release(); }, + }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).toHaveBeenCalledOnce(); + expect(outcome.elapsedMs).toBeLessThan(5_000); + }); + + it("ends the wait at once when Stop interrupts the session", async () => { + const outcome = await run({ + stream: turnOne(true), providerTurnWait: { capMs: 60_000 }, + after: async (control, appended) => { + await waitFor(() => appended.some(value => value.payload.awaitingProviderTurn === true)); + await control.session.interrupt!({ reason: "Stop" }); + }, + }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).toHaveBeenCalledOnce(); + expect(outcome.elapsedMs).toBeLessThan(5_000); + }); + + it("tolerates the Runner's held run.terminal during the wait and after Core ends it", async () => { + const heldTerminal = () => event("turn-1", "run.terminal", { schema: "paperclip.prp.terminal.v1", status: "succeeded", + turnTerminalState: "completed", runTerminalState: "succeeded", reportedWorkDisposition: "done", provider: "acpx" }); + const outcome = await run({ + stream: [...turnOne(true), heldTerminal()], providerTurnWait: { capMs: 150 }, + after: async (control) => { + await waitFor(() => control.interrupt.mock.calls.length === 1); + control.push(heldTerminal()); + }, + }); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.appended.filter(value => value.eventType === "run.terminal")).toHaveLength(1); + expect(outcome.resolveMissingResult).toHaveBeenCalledOnce(); + }); + + it.each([false, true])("settles a plan proposed in the provider-started turn as the plan review wait (cap passed during the turn: %s)", async (capPassed) => { + let seen: PrpEvent[] = []; + const outcome = await run({ + stream: turnOne(true), providerTurnWait: { capMs: capPassed ? 100 : 60_000 }, + missingResult: ({ terminalEvent }) => seen.some(value => value.eventType === "plan.proposed") + && terminalEvent.eventType === "turn.completed" ? planReviewWait : null, + after: async (control, appended) => { + seen = appended; + control.push(event("provider-1", "turn.started", { status: "inProgress", origin: "provider" })); + await waitFor(() => appended.some(value => value.payload.origin === "provider")); + if (capPassed) await new Promise(resolve => setTimeout(resolve, 250)); + control.push( + event("provider-1", "plan.proposed", { schema: "paperclip.plan.proposed.v1", proposalId: "toolu_plan", status: "completed", + markdown: "# Plan\n\n1. Install.\n2. Test.", source: "claude_exit_plan_mode" }), + event("provider-1", "item.completed", usage), + event("provider-1", "turn.completed", { status: "completed", error: null }), + event("provider-1", "run.terminal", { schema: "paperclip.prp.terminal.v1", status: "succeeded", turnTerminalState: "completed", + runTerminalState: "succeeded", reportedWorkDisposition: "done", provider: "acpx" }), + ); + }, + }); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(outcome.appended.filter(value => value.eventType === "plan.proposed")).toEqual([expect.objectContaining({ turnId: "provider-1", payload: expect.objectContaining({ status: "completed" }) })]); + expect(outcome.resolveMissingResult).toHaveBeenCalledOnce(); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ + turnId: "provider-1", terminalEvent: expect.objectContaining({ eventType: "turn.completed", turnId: "provider-1" }) })); + expect(outcome.resolveMissingResult.mock.calls[0]![0].terminalEvent.payload).not.toHaveProperty("awaitingProviderTurn"); + expect((outcome.completeRun.mock.calls[0] as unknown[])[0]).toMatchObject({ result: planReviewWait, turnId: "provider-1", + terminal: { runTerminalState: "succeeded", reportedWorkDisposition: "yielded" } }); + }); + + const dispositionRequests = (startTurn: ReturnType["startTurn"]) => + startTurn.mock.calls.filter(([value]) => value.message.text.includes("Paperclip semantic-result recovery")).length; + const dispositionTurn = () => [ + event("turn-disposition", "turn.started", { status: "inProgress" }), + event("turn-disposition", "run.result.proposed", result as unknown as Record), + event("turn-disposition", "turn.completed", { status: "completed", error: null }), + ]; + + const ids = (events: PrpEvent[]) => events.map(value => value.sourceEventId); + const appendedOf = (appended: PrpEvent[], events: PrpEvent[]) => + ids(appended).filter(id => ids(events).includes(id)); + + it("keeps reading the follow-up turn that a forced end of an idle wait starts and settles its result", async () => { + const turn = dispositionTurn(); + const outcome = await run({ + stream: [], providerTurnWait: { capMs: 100 }, withoutInterrupt: true, + restart: { onDisposition: push => push(...turn) }, + }); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.returned).toMatchObject({ result, turnId: "turn-disposition" }); + expect(outcome.resolveMissingResult).not.toHaveBeenCalled(); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(outcome.startTurn).toHaveBeenCalledTimes(2); + expect(dispositionRequests(outcome.startTurn)).toBe(1); + expect(appendedOf(outcome.appended, turn)).toEqual(ids(turn)); + }); + + it("appends exactly once an event that reaches the outstanding read after the forced end was taken", async () => { + const turn = dispositionTurn(); + const outcome = await run({ + stream: [], providerTurnWait: { capMs: 100 }, withoutInterrupt: true, restart: {}, + after: async (control) => { + await waitFor(() => control.startTurn.mock.calls.length === 2); + const [first, ...rest] = turn; + await new Promise(resolve => setTimeout(resolve, 50)); + control.push(first!); + await new Promise(resolve => setTimeout(resolve, 50)); + control.push(...rest); + }, + }); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.appended.filter(value => value.sourceEventId === turn[0]!.sourceEventId)).toHaveLength(1); + expect(appendedOf(outcome.appended, turn)).toEqual(ids(turn)); + expect(dispositionRequests(outcome.startTurn)).toBe(1); + }); + + it.each([true, false])("keeps waiting after a controller restart while the checkpoint still names the awaited turn as active (provider turn arrives: %s)", async (arrives) => { + const recovery = { + checkpoint: { ...restartCheckpoint, activeTurnId: "turn-1", terminalTurns: [] }, + snapshot: { terminalTurns: [completedTerminal("turn-1")], semanticResult: null, awaitingProviderTurn: true }, + }; + const stream = [event("turn-1", "turn.completed", { status: "completed", error: null, awaitingProviderTurn: true })]; + const turn = providerTurn("provider-1", { result: true }); + const outcome = await run({ + stream, restart: { recovery }, turnTimeoutMs: 10_000, + providerTurnWait: { startedAtMs: Date.now() - (arrives ? 599_000 : 599_700) }, + after: async (control) => { + if (!arrives) return; + await new Promise(resolve => setTimeout(resolve, 200)); + control.push(...turn); + }, + }); + expect(outcome.startTurn).not.toHaveBeenCalled(); + if (arrives) { + expect(outcome.outcome).toBe("finalized"); + expect(outcome.returned).toMatchObject({ result, turnId: "provider-1" }); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(appendedOf(outcome.appended, turn)).toEqual(ids(turn)); + } else { + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).toHaveBeenCalledOnce(); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ turnId: "turn-1", + terminalEvent: expect.objectContaining({ eventType: "turn.completed", payload: expect.objectContaining({ awaitingProviderTurn: true }) }) })); + expect(outcome.elapsedMs).toBeLessThan(5_000); + } + }); + + const awaitingSnapshot = { terminalTurns: [completedTerminal("turn-1")], semanticResult: null, awaitingProviderTurn: true }; + const afterTerminalRecovery = (options: { flag?: boolean; replay?: PrpEvent[] } = {}) => ({ + checkpoint: { ...restartCheckpoint, terminalTurns: [completedTerminal("turn-1")], ...(options.flag === false ? {} : { awaitingProviderTurn: true }) }, + snapshot: options.flag === false ? { terminalTurns: [completedTerminal("turn-1")], semanticResult: null } : awaitingSnapshot, + replay: options.replay ?? turnOne(true), + }); + + it.each([true, false])("keeps waiting after a controller restart saved after the awaiting terminal (provider turn arrives: %s)", async (arrives) => { + const turn = providerTurn("provider-1", { result: true }); + const recovery = afterTerminalRecovery(); + const outcome = await run({ + stream: [], restart: { recovery }, turnTimeoutMs: 10_000, + providerTurnWait: { startedAtMs: Date.now() - (arrives ? 599_000 : 599_700) }, + after: async (control) => { + if (!arrives) return; + await new Promise(resolve => setTimeout(resolve, 200)); + control.push(...turn); + }, + }); + expect(outcome.startTurn).not.toHaveBeenCalled(); + expect(appendedOf(outcome.appended, recovery.replay)).toEqual([]); + if (arrives) { + expect(outcome.outcome).toBe("finalized"); + expect(outcome.returned).toMatchObject({ result, turnId: "provider-1" }); + expect(outcome.interrupt).not.toHaveBeenCalled(); + expect(appendedOf(outcome.appended, turn)).toEqual(ids(turn)); + } else { + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).toHaveBeenCalledOnce(); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ turnId: "turn-1", + terminalEvent: expect.objectContaining({ eventType: "turn.completed", payload: expect.objectContaining({ awaitingProviderTurn: true }) }) })); + expect(outcome.elapsedMs).toBeLessThan(5_000); + } + }); + + it.each([false, true])("ends a resumed wait at once through the no-result path when its limit passed before the restart (without interrupt: %s)", async (withoutInterrupt) => { + const outcome = await run({ + stream: [], restart: { recovery: afterTerminalRecovery() }, turnTimeoutMs: 10_000, withoutInterrupt, + providerTurnWait: { startedAtMs: Date.now() - 700_000 }, + }); + expect(outcome.startTurn).not.toHaveBeenCalled(); + expect(outcome.outcome).toContain("native_finalization_missing"); + expect(outcome.interrupt).toHaveBeenCalledTimes(withoutInterrupt ? 0 : 1); + expect(outcome.resolveMissingResult).toHaveBeenCalledOnce(); + expect(outcome.resolveMissingResult).toHaveBeenCalledWith(expect.objectContaining({ turnId: "turn-1", + terminalEvent: expect.objectContaining({ payload: expect.objectContaining({ awaitingProviderTurn: true }) }) })); + expect(outcome.elapsedMs).toBeLessThan(1_000); + }); + + it.each([ + { label: "the replayed terminal has no marker", recovery: afterTerminalRecovery({ replay: turnOne(false) }) }, + { label: "replay has no terminal", recovery: afterTerminalRecovery({ replay: [] }) }, + { label: "the recovered session has no awaiting flag", recovery: afterTerminalRecovery({ flag: false }) }, + ])("sends the disposition-only recovery prompt after a restart as before when $label", async ({ recovery }) => { + const fresh = [ + event("turn-fresh", "turn.started", { status: "inProgress" }), + event("turn-fresh", "run.result.proposed", result as unknown as Record), + event("turn-fresh", "turn.completed", { status: "completed", error: null }), + ]; + const outcome = await run({ + stream: [], restart: { recovery }, turnTimeoutMs: 10_000, providerTurnWait: { startedAtMs: Date.now() - 599_000 }, + after: async (control) => { + await waitFor(() => control.startTurn.mock.calls.length === 1); + control.push(...fresh); + }, + }); + expect(outcome.startTurn).toHaveBeenCalledOnce(); + expect(dispositionRequests(outcome.startTurn)).toBe(1); + expect(outcome.outcome).toBe("finalized"); + expect(outcome.returned).toMatchObject({ result, turnId: "turn-fresh" }); + expect(outcome.interrupt).not.toHaveBeenCalled(); + }); + + it("resumes the wait again after a second restart during a resumed wait", async () => { + const startedAtMs = Date.now() - 599_000; + const first = await run({ + stream: [], restart: { recovery: afterTerminalRecovery() }, turnTimeoutMs: 10_000, providerTurnWait: { startedAtMs }, + }); + expect(first.startTurn).not.toHaveBeenCalled(); + expect(first.checkpoints.length).toBeGreaterThan(0); + const persisted = first.checkpoints.at(-1)!; + expect(persisted).toMatchObject({ activeTurnId: null, awaitingProviderTurn: true }); + expect(persisted.dispositionOnlyRecoveryConsumed).toBeFalsy(); + const turn = providerTurn("provider-1", { result: true }); + const second = await run({ + stream: [], restart: { recovery: { ...afterTerminalRecovery(), checkpoint: persisted } }, turnTimeoutMs: 10_000, + providerTurnWait: { startedAtMs: Date.now() - 599_000 }, + after: async (control) => { + await new Promise(resolve => setTimeout(resolve, 200)); + control.push(...turn); + }, + }); + expect(second.startTurn).not.toHaveBeenCalled(); + expect(second.outcome).toBe("finalized"); + expect(second.returned).toMatchObject({ result, turnId: "provider-1" }); + }); + + it("fails the run as today when the Runner's stream ends during the wait", async () => { + const outcome = await run({ + stream: turnOne(true), providerTurnWait: { capMs: 60_000 }, + after: async (control, appended) => { + await waitFor(() => appended.some(value => value.payload.awaitingProviderTurn === true)); + control.push("end"); + }, + }); + expect(outcome.outcome).toContain("native event stream closed before a turn terminal fact"); + expect(outcome.elapsedMs).toBeLessThan(5_000); }); }); diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.ts index bd54e2f0d7d..73f8aaf9ac0 100644 --- a/packages/paperclip-runner/src/native-session-runtime.ts +++ b/packages/paperclip-runner/src/native-session-runtime.ts @@ -46,6 +46,7 @@ import { type PrpTerminalState, } from "./protocol/replay-contract.js"; import { parsePaperclipQuestionSet } from "./contracts/question-set.js"; +import { awaitsProviderTurn, createProviderTurnWait, type ProviderTurnWaitOptions } from "./native-provider-turn-wait.js"; import { retainedRunnerdCleanupProofIsCurrent, type RetainedRunnerdCleanupProof, @@ -416,6 +417,7 @@ export interface ExecuteNativeSessionOptions { turnId: string | null; event: PrpEvent; }) => PrpStructuredRunResult | null; + providerTurnWait?: ProviderTurnWaitOptions; } function isTurnTerminal(event: PrpEvent): boolean { @@ -1189,8 +1191,15 @@ async function consumeTurn( /** Settles a compaction-only turn, which reports no semantic result. */ compactionResult?: PrpStructuredRunResult, supersededTerminal?: (event: PrpEvent, signal: AbortSignal) => Promise, + providerTurnWaitOptions?: ProviderTurnWaitOptions, + resumedProviderTurnWait?: PrpEvent, ) { let timer: ReturnType | undefined; + const providerTurnWait = createProviderTurnWait({ + session, + options: providerTurnWaitOptions, + overallDeadlineMs: timeoutMs > 0 ? Date.now() + timeoutMs : null, + }); const appendAbort = new AbortController(); const governedCleanupOperations = new Set>(); let governedCancellationCommitted = false; @@ -1389,11 +1398,33 @@ async function consumeTurn( return settleDurableResult(initialGovernedWait.sourceEvent, initialGovernedWait.result, "Paperclip resumed settlement of this durable governed interaction."); } + const endProviderTurnWait = async (terminal: PrpEvent) => { + if (providerTurnWait.ending !== null && semanticResultProposal === null && governedResult === null && + inputTimers.size === 0 && await resumeInterruptedTurn?.(terminal, appendAbort.signal)) return null; + await settlePendingDeltas(); + return { event: terminal, eventCount, highestContiguousSourceSeq, governedResult }; + }; + let pendingRead: Promise> | null = null; + let forcedEndTaken = false; + if (resumedProviderTurnWait) providerTurnWait.begin(resumedProviderTurnWait); while (true) { - const next = await eventIterator.next().catch((error) => { - throw providerFailure ?? error; - }); + if (pendingRead === null) { + pendingRead = eventIterator.next().catch((error) => { + throw providerFailure ?? error; + }); + void pendingRead.catch(() => undefined); + } + const next = providerTurnWait.started && !forcedEndTaken + ? await Promise.race([pendingRead, providerTurnWait.forced]) + : await pendingRead; if (stopConsumer) throw new Error("native event consumer stopped"); + if (next === null) { + forcedEndTaken = true; + const ended = await endProviderTurnWait(providerTurnWait.awaitedTerminal!); + if (ended === null) continue; + return ended; + } + pendingRead = null; if (next.done) { if (providerFailure) throw providerFailure; throw new Error( @@ -1439,6 +1470,11 @@ async function consumeTurn( receipt.highestContiguousSourceSeq, ); } + if (providerTurnWait.endedBy(event)) { + const ended = await endProviderTurnWait(providerTurnWait.awaitedTerminal!); + if (ended !== null) return ended; + } + providerTurnWait.observe(event); const eventGoal = goalFromEvent(event); const goalChanged = eventGoal !== undefined && goalLifecycleFingerprint(eventGoal) !== goalLifecycleFingerprint(previousGoal); @@ -1659,6 +1695,8 @@ async function consumeTurn( governedResult: compactionResult, }; } + if (semanticResultProposal === null && governedResult === null && inputTimers.size === 0 && + awaitsProviderTurn(event) && providerTurnWait.begin(event)) continue; if (semanticResultProposal === null && governedResult === null && inputTimers.size === 0 && await resumeInterruptedTurn?.(event, appendAbort.signal)) continue; await settlePendingDeltas(); @@ -1810,6 +1848,7 @@ async function consumeTurn( quarantineSession("provider_event_teardown_timed_out"); } if (timer !== undefined) clearTimeout(timer); + providerTurnWait.dispose(); removeExternalAbort(); } } @@ -3161,6 +3200,18 @@ export async function executeNativeSession( replayedDisposition !== null || dispositionFallback !== null; const recoveryTerminal = replayedDisposition?.terminal ?? dispositionFallback; + const awaitedTurnId = persistedSession?.terminalTurns?.at(-1)?.turnId ?? null; + const awaitedTerminal = recovered && recoveredSnapshot.awaitingProviderTurn === true && !recoveredActiveTurnId && + !recoveredSnapshot.semanticResult && !governedWait && !checkpointedDispositionTerminal && awaitedTurnId !== null + ? (await replayCheckpointedTurnTerminal({ + controlPlane: options.controlPlane, + runId: input.binding.runId, + sourceInstanceId: options.runnerInstanceId, + priorTerminalTurnIds: [], + expectedTurnId: awaitedTurnId, + }))?.terminal ?? null + : null; + const resumedProviderTurnWait = awaitedTerminal !== null && awaitsProviderTurn(awaitedTerminal) ? awaitedTerminal : undefined; const consumptionAbort = new AbortController(); const consuming = (governedTerminal || governedWait?.settlement) && governedWait @@ -3198,6 +3249,8 @@ export async function executeNativeSession( ? sessionCompactionResult(input, options.sessionCompaction.requestId) : undefined, supersededByRestartContinuation, + options.providerTurnWait, + resumedProviderTurnWait, ) : Promise.resolve({ event: recoveryTerminal, @@ -3221,7 +3274,8 @@ export async function executeNativeSession( (!recoveredActiveTurnId && !adoptedProviderTerminal && !checkpointedDispositionTerminal && - !dispositionRecoveryStillOwned)); + !dispositionRecoveryStillOwned && + !resumedProviderTurnWait)); if (options.sessionCompaction) { // Compaction summarizes existing provider context. A new session or // one that is still running a turn has nothing safe to compact. diff --git a/scripts/benchmark-agent-scaling-load.ts b/scripts/benchmark-agent-scaling-load.ts index 407dba26e51..07e602bf6d7 100644 --- a/scripts/benchmark-agent-scaling-load.ts +++ b/scripts/benchmark-agent-scaling-load.ts @@ -6,10 +6,15 @@ * * deltas an `item.delta` per text chunk, committed as the server's port * commits them: the first after another event at once, later ones - * in one transaction per DELTA_BATCH_MS or 100 deltas - * (DELTA_BATCH_MS=0: one transaction per delta, as before batching) - * events appendHeartbeatRunEvent for an `item.completed`, then the real - * controller checkpoint save, which overlaps the next append + * together after DELTA_BATCH_MS or 100 deltas, and the deltas that + * arrive while a batch commits all in the next batch + * (DELTA_BATCH_MS=0: one append per delta, as before batching) + * events the recorded mix of other events (EVENT_MIX). A runner event + * (`tool.execution.*`, `item.completed`) is a native source append + * that registers a chat progress wake, then the real controller + * checkpoint save, which overlaps the next append. A + * `run.performance.span` is written by the server's own run trace: + * an ordinary append with no wake and no checkpoint * lease every LEASE_S, one renewal of all leases through the shared * schedule (LEASE_MODE=single: one transaction per run, as before). * In batch mode LEASE_S is at most 20: the schedule renews a remote @@ -33,10 +38,17 @@ * * pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-agent-scaling-load.ts * + * PROFILE sets the per-agent rates: `recorded` (default) is the median of + * recorded hosted native runs, 0.2 deltas/s and 0.5 other events/s; `burst` + * is a run's busiest minute, 2.5 deltas/s and 3 other events/s; `stress` is + * the earlier assumption, 20 deltas/s and 1 other event/s. API_PER_S is 0.3 + * in every profile. Each rate can still be set on its own. + * * Optional: AGENTS (50), SECONDS (20), SOURCES (deltas,events,lease,api), - * DELTAS_PER_S (20), EVENTS_PER_S (1), API_PER_S (0.3), LEASE_S (20), - * DELTA_BYTES (120), EVENT_KIB (2), DELTA_BATCH_MS (250), LEASE_MODE (batch), - * DATABASE_POOL_MAX (driver default 10). + * PROFILE (recorded), DELTAS_PER_S, EVENTS_PER_S, API_PER_S, LEASE_S (20), + * EVENT_MIX (recorded, or one event type for all other events), + * DELTA_BYTES (120), EVENT_KIB (2), SPAN_BYTES (600), DELTA_BATCH_MS (250), + * LEASE_MODE (batch), DATABASE_POOL_MAX (driver default 10). */ import assert from "node:assert/strict"; import { randomBytes, randomUUID } from "node:crypto"; @@ -59,12 +71,38 @@ const express = serverRequire("express") as typeof import("express"); const number = (name: string, fallback: number) => Number(process.env[name] ?? fallback); const AGENTS = number("AGENTS", 50), SECONDS = number("SECONDS", 20); -const RATES = { deltas: number("DELTAS_PER_S", 20), events: number("EVENTS_PER_S", 1), api: number("API_PER_S", 0.3), - lease: 1 / number("LEASE_S", 20) }; +const PROFILES = { + recorded: { deltas: 0.2, events: 0.5, api: 0.3 }, + burst: { deltas: 2.5, events: 3, api: 0.3 }, + stress: { deltas: 20, events: 1, api: 0.3 }, +}; +const PROFILE = (process.env.PROFILE ?? "recorded") as keyof typeof PROFILES; +assert(PROFILE in PROFILES, `Unknown PROFILE ${PROFILE}`); +const RATES = { deltas: number("DELTAS_PER_S", PROFILES[PROFILE].deltas), events: number("EVENTS_PER_S", PROFILES[PROFILE].events), + api: number("API_PER_S", PROFILES[PROFILE].api), lease: 1 / number("LEASE_S", 20) }; +// Rows per event type among the other events of recorded hosted native runs. +const RECORDED_EVENT_MIX = { "run.performance.span": 10_030, "tool.execution.progressed": 6_951, "item.completed": 4_705, + "tool.execution.started": 2_150, "tool.execution.completed": 2_150 }; +const EVENT_MIX: Record = !process.env.EVENT_MIX || process.env.EVENT_MIX === "recorded" + ? RECORDED_EVENT_MIX : { [process.env.EVENT_MIX]: 1 }; +// One cycle of 100 slots, each type in proportion to its rows. Agents start +// at different slots so the fleet sends the mix at every moment. +const EVENT_CYCLE = (() => { + const total = Object.values(EVENT_MIX).reduce((sum, rows) => sum + rows, 0); + const shares = Object.entries(EVENT_MIX).map(([type, rows]) => ({ type, exact: rows / total * 100 })); + const slots = shares.map(share => ({ ...share, count: Math.floor(share.exact) })); + for (const slot of [...slots].sort((a, b) => (b.exact - b.count) - (a.exact - a.count)) + .slice(0, 100 - slots.reduce((sum, slot) => sum + slot.count, 0))) slot.count += 1; + const cycle: string[] = []; + for (let index = 0; cycle.length < 100; index++) { + for (const slot of slots) if (index < slot.count) cycle.push(slot.type); + } + return cycle; +})(); type Source = keyof typeof RATES; const SOURCES = (process.env.SOURCES ?? "deltas,events,lease,api").split(",").map(value => value.trim()).filter(Boolean) as Source[]; for (const source of SOURCES) assert(source in RATES, `Unknown source ${source}`); -const DELTA_BYTES = number("DELTA_BYTES", 120), EVENT_KIB = number("EVENT_KIB", 2); +const DELTA_BYTES = number("DELTA_BYTES", 120), EVENT_KIB = number("EVENT_KIB", 2), SPAN_BYTES = number("SPAN_BYTES", 600); const DELTA_BATCH_MS = number("DELTA_BATCH_MS", 250), DELTA_BATCH_MAX = 100; const LEASE_BATCHED = (process.env.LEASE_MODE ?? "batch") !== "single"; // The shared schedule renews a remote lease on its own 20 s after the last @@ -120,7 +158,9 @@ try { fleet.push({ agentId: agent!.id, issueId: issue!.id, runId, leaseOwner, write, records, checkpoint, seq: 0, checkpointTail: Promise.resolve(), appendTail: Promise.resolve() as Promise, deltaQueue: [] as Array<{ input: AppendHeartbeatRunEventInput; settle: (error?: unknown) => void }>, - deltaTimer: null as ReturnType | null, streamedSinceBoundary: false, token: createLocalAgentJwt(agent!.id, companyId, "process", runId, null)! }); + deltaTimer: null as ReturnType | null, streamedSinceBoundary: false, + openBatch: null as Array<{ input: AppendHeartbeatRunEventInput; settle: (error?: unknown) => void }> | null, + eventSlot: Math.floor(index * EVENT_CYCLE.length / Math.max(1, AGENTS)), token: createLocalAgentJwt(agent!.id, companyId, "process", runId, null)! }); } const app = express(); @@ -149,12 +189,29 @@ try { const flushDeltas = (agent: Agent) => { if (agent.deltaTimer !== null) clearTimeout(agent.deltaTimer); agent.deltaTimer = null; - const batch = agent.deltaQueue; - if (batch.length === 0) return; - agent.deltaQueue = []; + if (agent.deltaQueue.length === 0) return; agent.streamedSinceBoundary = true; - agent.appendTail = agent.appendTail.then(() => appendHeartbeatRunEventBatch(db, batch.map(item => item.input), () => {})) - .then(() => { for (const item of batch) item.settle(); }, error => { for (const item of batch) item.settle(error); }); + // As the port: one batch waits behind the batch that is committing, and + // takes every delta queued when it starts, unless a runner event came first. + if (agent.openBatch) { + agent.openBatch.push(...agent.deltaQueue); + agent.deltaQueue = []; + return; + } + const batch = agent.deltaQueue; + agent.deltaQueue = []; + agent.openBatch = batch; + agent.appendTail = agent.appendTail.then(() => { + if (agent.openBatch === batch) { + agent.openBatch = null; + batch.push(...agent.deltaQueue); + agent.deltaQueue = []; + if (agent.deltaTimer !== null) clearTimeout(agent.deltaTimer); + agent.deltaTimer = null; + } + return appendHeartbeatRunEventBatch(db, batch.map(item => item.input), () => {}) + .then(() => { for (const item of batch) item.settle(); }, error => { for (const item of batch) item.settle(error); }); + }); }; const appendDelta = (agent: Agent) => { const { input } = eventInput(agent, "item.delta", DELTA_BYTES); @@ -173,15 +230,29 @@ try { const append = (agent: Agent, eventType: string, bytes: number) => { const { seq, event, input } = eventInput(agent, eventType, bytes); flushDeltas(agent); + agent.openBatch = null; agent.streamedSinceBoundary = false; const queued = agent.appendTail.then(() => appendHeartbeatRunEvent(db, input)).then(() => ({ seq, event })); agent.appendTail = queued.catch(() => undefined); return queued; }; + // The server's run trace appends its spans directly: not a runner event, so + // no source sequence, no wake, no checkpoint, and no place in the run's + // stream of runner events. + const appendSpan = (agent: Agent) => { + const payload = { schema: "paperclip.run-performance-span.v1", span: "tool.call", parentSpan: "task.turn", + durationMs: 12.5, outcome: "ok", detail: randomBytes(Math.ceil(SPAN_BYTES * 0.75)).toString("base64") }; + return appendHeartbeatRunEvent(db, { companyId, agentId: agent.agentId, runId: agent.runId, + eventType: "run.performance.span", stream: "system", level: "info", message: "runner span: tool.call (12.5ms)", payload }); + }; + const eventsByType: Record = {}; const operations: Record Promise> = { deltas: agent => appendDelta(agent), events: async agent => { - const { seq, event } = await append(agent, "item.completed", EVENT_KIB * 1024); + const eventType = EVENT_CYCLE[(agent.eventSlot++) % EVENT_CYCLE.length]!; + eventsByType[eventType] = (eventsByType[eventType] ?? 0) + 1; + if (eventType === "run.performance.span") { await appendSpan(agent); return; } + const { seq, event } = await append(agent, eventType, EVENT_KIB * 1024); const changed = new Map([[`event:${seq}`, JSON.stringify(event)], ["cursor", JSON.stringify({ ackedSourceSeq: seq })]]); for (const [key, value] of changed) agent.records.set(key, value); // The save is serial per controller and does not block the next frame. @@ -203,6 +274,7 @@ try { for (const source of SOURCES) if (!(LEASE_BATCHED && source === "lease")) await operations[source](fleet[0]!); await fleet[0]!.checkpointTail; assert.equal(checkpointFailures, 0, `checkpoint save failed during warm-up: ${firstCheckpointError}`); + for (const eventType of Object.keys(eventsByType)) delete eventsByType[eventType]; const stats = Object.fromEntries(SOURCES.map(source => [source, { done: 0, failed: 0, late: [] as number[], firstError: "" }])) as Record; @@ -298,7 +370,7 @@ try { donePerSecond: round(stat.done / seconds), lateMs: { p50: quantile(stat.late, 0.5), p99: quantile(stat.late, 0.99), max: stat.late.length ? round(stat.late.reduce((max, value) => Math.max(max, value), -Infinity)) : null } }]; })), - deltaBatchMs: DELTA_BATCH_MS, leaseMode: LEASE_BATCHED ? "batch" : "single", leasesLost, + profile: PROFILE, eventsIssuedByType: eventsByType, deltaBatchMs: DELTA_BATCH_MS, leaseMode: LEASE_BATCHED ? "batch" : "single", leasesLost, checkpointSaves: { failed: checkpointFailures, firstError: firstCheckpointError || undefined }, }, null, 2)); } finally { diff --git a/scripts/benchmark-fresh-continuation-deadline.ts b/scripts/benchmark-fresh-continuation-deadline.ts new file mode 100644 index 00000000000..9afedc8066f --- /dev/null +++ b/scripts/benchmark-fresh-continuation-deadline.ts @@ -0,0 +1,228 @@ +// Fresh-continuation scheduler queries on a staging-shaped fixture: the +// disposition worker's deadline (`nextFreshContinuationCheckAt`), its backlog +// listing (`heldExecutionsAwaitingFreshContinuation`) and the left-alone count. +// Compares a baseline revision with the working tree on identical data and +// fails on any difference in complete positional rows. +// +// pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-fresh-continuation-deadline.ts \ +// --baseline-ref= [--context-kib=60] [--samples=7] [--warmups=2] [--print-plans] +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { EXECUTION_RECONCILIATION_CAUSES } from "../packages/shared/src/index.js"; +import { createDb, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import * as treatment from "../server/src/services/fresh-continuation-fallback.js"; + +type Query = { sql: string; params: unknown[] }; +const arg = (name: string, fallback: string) => process.argv.find(value => value.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback; +const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${arg("baseline-ref", "origin/master")}^{commit}`], { encoding: "utf8" }).trim(); +const contextKib = Number(arg("context-kib", "60")); +const sampleCount = Number(arg("samples", "7")); +const warmupCount = Number(arg("warmups", "2")); +const keepAlive = setInterval(() => {}, 1000); +let database: Awaited> | undefined; +let baselineDir: string | undefined; +let db: Db | undefined; +try { + database = await startEmbeddedPostgresTestDatabase("fresh-continuation-deadline-benchmark-"); + db = createDb(database.connectionString); + const sqlClient = db.$client; + baselineDir = await fs.mkdtemp(path.join(fileURLToPath(new URL("../server/scripts/", import.meta.url)), ".fresh-continuation-baseline-")); + const modulePath = "server/src/services/fresh-continuation-fallback.ts"; + const original = new URL(`../${modulePath}`, import.meta.url); + const source = execFileSync("git", ["show", `${baselineRevision}:${modulePath}`], { encoding: "utf8" }); + const baselineFile = path.join(baselineDir, "fresh-continuation-fallback.ts"); + await fs.writeFile(baselineFile, source.replace(/from "(\.{1,2}\/[^"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, original)))}`)); + const baseline = await import(pathToFileURL(baselineFile).href) as typeof treatment; + + // Staging shape (2026-11-14): 5.7k issues, 31.4k runs whose rows carry wide + // context JSON (1.96 GB), 75k recovery records of which ~280 carry a + // fresh-continuation check deadline. + const now = new Date(Date.UTC(2026, 10, 14, 5, 0, 0)); + const nowMs = now.getTime(); + const companyId = randomUUID(), decoyCompanyId = randomUUID(); + const agentIds = [randomUUID(), randomUUID(), randomUUID()]; + const fillerSeed = randomBytes(Math.ceil(contextKib * 1024 * 0.75)).toString("base64"); + const started = performance.now(); + await sqlClient.unsafe(`insert into companies (id, name, issue_prefix) values ($1, 'Synthetic', 'FCD'), ($2, 'Decoy', 'FCX')`, + [companyId, decoyCompanyId]); + await sqlClient.unsafe(`insert into agents (id, company_id, name, adapter_type) + select id, $4::uuid, 'Agent ' || n, 'codex_local' from unnest(array[$1, $2, $3]::uuid[]) with ordinality as a(id, n)`, + [...agentIds, companyId]); + const decoyAgentId = randomUUID(); + await sqlClient.unsafe(`insert into agents (id, company_id, name, adapter_type) values ($1, $2, 'Decoy', 'codex_local')`, [decoyAgentId, decoyCompanyId]); + // Issues: 5,400 in the company (60% done), 269 decoys in another company. + await sqlClient.unsafe(`create temporary table fixture_issue as + select n, gen_random_uuid() as id, case when n <= 5400 then $1::uuid else $2::uuid end as company_id, + case when n > 5400 then $3::uuid else (array[$4, $5, $6]::uuid[])[1 + n % 3] end as agent_id, + case when n % 10 < 6 then 'done' when n % 10 = 6 then 'blocked' when n % 10 = 7 then 'in_progress' else 'todo' end as status + from generate_series(1, 5669) n`, [companyId, decoyCompanyId, decoyAgentId, ...agentIds]); + await sqlClient.unsafe(`insert into issues (id, company_id, title, status, assignee_agent_id) + select id, company_id, 'Fixture task ' || n, status, agent_id from fixture_issue`); + // Runs: 31,399, about five per task, linked by native id, legacy issue id, or context only. + await sqlClient.unsafe(`insert into heartbeat_runs (company_id, agent_id, scope_kind, issue_id, native_issue_id, runtime_mode, + status, error_code, started_at, finished_at, created_at, updated_at, context_snapshot) + select i.company_id, i.agent_id, case when g.n % 5 = 4 then 'company' else 'issue' end, + case when g.n % 5 = 4 then null else i.id end, case when g.n % 5 < 2 then i.id end, + case when g.n % 5 < 2 then 'native' else 'legacy' end, + case when g.n % 7 = 0 then 'failed' when g.n % 11 = 0 then 'cancelled' else 'succeeded' end, + case when g.n % 7 = 0 then 'adapter_failed' end, + $2::timestamptz - (g.n || ' minutes')::interval, $2::timestamptz - (g.n || ' minutes')::interval + interval '30 seconds', + $2::timestamptz - (g.n || ' minutes')::interval - interval '1 second', $2::timestamptz - (g.n || ' minutes')::interval, + jsonb_build_object('issueId', i.id::text, 'wakeReason', 'issue_assigned', 'prompt', $1::text) + from generate_series(1, 31_000) g(n) join fixture_issue i on i.n = 1 + g.n % 5669`, [fillerSeed, now.toISOString()]); + + // Held records with a check deadline (282), in the shapes the predicate distinguishes. + type Held = { issueN: number; runId: string; evidence: Record; status: string; ownerUserId?: string; + cause?: string; recentRun: boolean; errorCode: string; newer?: "native" | "legacy" | "context" | "cancelled_at_dispatch" | "live" }; + const heldRows: Held[] = []; + let issueN = 7; + const nextOpenIssue = () => { do issueN += 1; while (issueN % 10 < 6 || issueN > 5400); return issueN; }; + for (let n = 0; n < 282; n += 1) { + const runId = randomUUID(); + // A third are overdue, so the backlog listing has due work too. + const check = { kind: "exact_recovery_pending", nextCheckAt: nowMs + (n % 3 === 0 ? -1 : 1) * (n + 1) * 1_000, checks: 1 }; + const kind = n % 12; + const base = { runId, automaticRecovery: { replay: "blocked" }, freshContinuationCheck: check }; + heldRows.push({ + issueN: nextOpenIssue(), runId, + evidence: kind === 1 ? { sourceRunId: runId, automaticRecovery: { replay: "blocked" }, freshContinuationCheck: check } + : kind === 2 ? { ...base, runId: runId.toUpperCase() } + : kind === 3 ? { ...base, runId: "not-a-run" } + : base, + status: kind === 4 ? "active" : "resolved", + ownerUserId: kind === 5 ? "user-1" : undefined, + recentRun: kind !== 6 && kind !== 4, + errorCode: kind === 7 ? "adapter_failed" : "process_lost", + newer: kind === 8 ? (["native", "legacy", "context"] as const)[n % 3] : kind === 9 ? "cancelled_at_dispatch" : kind === 10 ? "live" : undefined, + }); + } + const runsSql: unknown[][] = []; + for (const held of heldRows) { + const finished = new Date(nowMs - (held.recentRun ? 2 : 48) * 3_600_000); + runsSql.push([held.runId, held.issueN, held.errorCode, finished.toISOString(), new Date(finished.getTime() - 600_000).toISOString(), null]); + if (held.newer) runsSql.push([randomUUID(), held.issueN, held.newer, finished.toISOString(), + new Date(finished.getTime() + 60_000).toISOString(), held.newer]); + } + await sqlClient.unsafe(`insert into heartbeat_runs (id, company_id, agent_id, scope_kind, issue_id, native_issue_id, runtime_mode, + status, error_code, started_at, finished_at, created_at, updated_at, context_snapshot) + select r.id, i.company_id, i.agent_id, case when r.link = 'context' then 'company' else 'issue' end, + case when r.link in ('context', 'native') then null else i.id end, case when r.link = 'native' then i.id end, + case when r.link = 'native' then 'native' else 'legacy' end, + case when r.link = 'live' then 'queued' when r.link = 'cancelled_at_dispatch' then 'cancelled' + when r.link is null then 'failed' else 'succeeded' end, + case when r.link = 'cancelled_at_dispatch' then 'execution_reconciliation_required' when r.link is null then r.code end, + case when r.link is null then r.created_at end, case when r.link is null then r.finished_at end, r.created_at, r.created_at, + jsonb_build_object('issueId', i.id::text, 'wakeReason', 'issue_assigned', 'prompt', $2::text) + from jsonb_to_recordset($1::jsonb) as r(id uuid, issue_n int, code text, finished_at timestamptz, created_at timestamptz, link text) + join fixture_issue i on i.n = r.issue_n`, + [JSON.stringify(runsSql.map(([id, issue_n, code, finished_at, created_at, link]) => ({ id, issue_n, code, finished_at, created_at, link }))), fillerSeed]); + await sqlClient.unsafe(`insert into issue_recovery_actions (company_id, source_issue_id, kind, status, owner_type, owner_user_id, + cause, fingerprint, evidence, next_action) + select i.company_id, i.id, 'active_run_watchdog', h.status, 'board', h.owner_user_id, 'legacy_execution_requires_reconciliation', + 'held:' || h.ord, h.evidence, 'Fixture' + from jsonb_to_recordset($1::jsonb) as h(ord int, issue_n int, status text, owner_user_id text, evidence jsonb) + join fixture_issue i on i.n = h.issue_n`, + [JSON.stringify(heldRows.map((held, ord) => ({ ord, issue_n: held.issueN, status: held.status, owner_user_id: held.ownerUserId ?? null, + evidence: held.evidence })))]); + // Historical records (75,003): held-shaped records without a deadline on + // finished tasks, settled continuations, and records of other causes. + await sqlClient.unsafe(`insert into issue_recovery_actions (company_id, source_issue_id, kind, status, owner_type, cause, + fingerprint, evidence, next_action, resolved_at) + select i.company_id, i.id, case when g.n % 3 = 0 then 'active_run_watchdog' else 'missing_disposition' end, 'resolved', 'agent', + (case when g.n % 4 = 0 then $1::text[] else array['stranded_assigned_issue', 'missing_disposition'] end)[1 + g.n % 2], + 'history:' || g.n, + case when g.n % 15 = 0 then jsonb_build_object('runId', r.id::text, 'automaticRecovery', jsonb_build_object('replay', 'blocked')) + when g.n % 4 = 0 then jsonb_build_object('runId', r.id::text, 'executionReconciliation', jsonb_build_object('runId', r.id::text), + 'freshContinuation', jsonb_build_object('sourceRunId', r.id::text), 'note', repeat('x', 400)) + else jsonb_build_object('runId', r.id::text, 'note', repeat('y', 400)) end, + 'Fixture', $2::timestamptz + from generate_series(1, 75_003) g(n) + join fixture_issue i on i.n = 1 + (g.n * 7) % 5669 + join lateral (select id from heartbeat_runs where (issue_id = i.id or native_issue_id = i.id) limit 1) r on true`, + [[...EXECUTION_RECONCILIATION_CAUSES].slice(0, 2), now.toISOString()]); + await sqlClient.unsafe("analyze"); + const [sizes] = await sqlClient.unsafe(`select + (select count(*) from heartbeat_runs)::int as runs, pg_size_pretty(pg_total_relation_size('heartbeat_runs')) as runs_size, + (select count(*) from issue_recovery_actions)::int as actions, pg_size_pretty(pg_total_relation_size('issue_recovery_actions')) as actions_size, + (select count(*) from issue_recovery_actions where evidence #>> '{freshContinuationCheck,nextCheckAt}' is not null)::int as with_deadline, + (select count(*) from issues)::int as issues, current_setting('server_version') as server_version, current_setting('jit') as jit, + current_setting('shared_buffers') as shared_buffers`); + const fixtureSeconds = (performance.now() - started) / 1000; + + // Captures the SQL the real service sends, then stops it. + async function capture(invoke: (captureDb: Db) => Promise): Promise { + let query: Query | undefined; + const stop = new Error("captured"); + const captureDb = new Proxy(db!, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args); + selection.execute = async () => { query ??= selection.toSQL(); throw stop; }; + return selection; + }) as typeof builder.from; + return builder; + }; + }}); + try { await invoke(captureDb); } catch (error) { if (error !== stop) throw error; } + assert.ok(query, "no query captured"); + return query; + } + const queries = (module: typeof treatment) => ({ + nextCheckAt: () => capture(captureDb => module.nextFreshContinuationCheckAt(captureDb, now)), + heldListing: async () => module.heldExecutionsAwaitingFreshContinuation(db!, now, 5).toSQL(), + heldListingProbe: async () => module.heldExecutionsAwaitingFreshContinuation(db!, now, 1).toSQL(), + leftAloneCount: () => capture(captureDb => { module.resetBacklogContinuationPacingForTests(); return module.continueHeldExecutions(captureDb, now); }), + }); + async function run(query: Query) { + const start = performance.now(); + const rows = await sqlClient.unsafe(query.sql, query.params as never[]).values(); + return { ms: performance.now() - start, rows }; + } + async function plan(query: Query) { + const [row] = await sqlClient.unsafe(`explain (analyze, buffers, format json) ${query.sql}`, query.params as never[]); + const root = (row!["QUERY PLAN"] as Array<{ "Execution Time": number; Plan: Record }>)[0]!; + return { executionMs: root["Execution Time"], sharedHit: root.Plan["Shared Hit Blocks"], sharedRead: root.Plan["Shared Read Blocks"] }; + } + const before = queries(baseline), after = queries(treatment); + const results = []; + for (const name of Object.keys(before) as Array) { + const [baselineQuery, treatmentQuery] = [await before[name](), await after[name]()]; + const baselineSamples: number[] = [], treatmentSamples: number[] = []; + let baselineRows: unknown[] = [], treatmentRows: unknown[] = []; + // Warmups each, then alternating timed pairs. + for (let n = 0; n < warmupCount; n += 1) { await run(baselineQuery); await run(treatmentQuery); } + for (let n = 0; n < sampleCount; n += 1) { + const first = n % 2 === 0 ? baselineQuery : treatmentQuery, second = first === baselineQuery ? treatmentQuery : baselineQuery; + const a = await run(first), b = await run(second); + const [base, treat] = first === baselineQuery ? [a, b] : [b, a]; + baselineSamples.push(base.ms); treatmentSamples.push(treat.ms); + baselineRows = base.rows; treatmentRows = treat.rows; + } + assert.deepEqual(treatmentRows, baselineRows, `${name}: treatment rows differ from baseline`); + const median = (samples: number[]) => [...samples].sort((x, y) => x - y)[Math.floor(samples.length / 2)]!; + results.push({ name, rows: baselineRows.length, firstRow: baselineRows[0] ?? null, + baselineMedianMs: +median(baselineSamples).toFixed(1), treatmentMedianMs: +median(treatmentSamples).toFixed(1), + speedup: +(median(baselineSamples) / median(treatmentSamples)).toFixed(1), + baselineSamplesMs: baselineSamples.map(ms => +ms.toFixed(1)), treatmentSamplesMs: treatmentSamples.map(ms => +ms.toFixed(1)), + baselinePlan: await plan(baselineQuery), treatmentPlan: await plan(treatmentQuery) }); + } + if (process.argv.includes("--print-plans")) { + for (const [label, module] of [["baseline", baseline], ["treatment", treatment]] as const) { + const query = await queries(module).nextCheckAt(); + const rows = await sqlClient.unsafe(`explain (analyze, buffers) ${query.sql}`, query.params as never[]); + console.error(`--- ${label} nextFreshContinuationCheckAt plan\n${rows.map(row => row["QUERY PLAN"]).join("\n")}`); + } + } + console.log(JSON.stringify({ baselineRevision, fixture: { ...sizes, contextKib, fixtureSeconds: +fixtureSeconds.toFixed(1) }, results }, null, 2)); +} finally { + try { await db?.$client.end({ timeout: 0 }); await database?.cleanup(); + if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } +} diff --git a/server/scripts/benchmark-tool-policy-matching.ts b/server/scripts/benchmark-tool-policy-matching.ts new file mode 100644 index 00000000000..6f9d4073999 --- /dev/null +++ b/server/scripts/benchmark-tool-policy-matching.ts @@ -0,0 +1,183 @@ +/** + * Main-thread cost of the policy decisions in one tools/list response, against + * enabled policies shaped like the staging company (see + * stagingShapedToolPolicies). Uses a throwaway embedded PostgreSQL database; no + * provider calls, production data, or model inference. Alternates the baseline + * and current policy services, one listing (fresh decision cache) per run. + * + * pnpm --filter @paperclipai/server exec tsx scripts/benchmark-tool-policy-matching.ts \ + * --baseline-ref origin/master --tools 800 --rounds 9 + */ +import { execFileSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { rmSync, writeFileSync } from "node:fs"; +import { setTimeout as sleep } from "node:timers/promises"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { monitorEventLoopDelay, performance } from "node:perf_hooks"; +import { createDb, toolPolicies, type Db as DbClient } from "@paperclipai/db"; +import type { ToolAccessDecisionInput } from "@paperclipai/shared"; +import { startEmbeddedPostgresTestDatabase } from "../src/__tests__/helpers/embedded-postgres.js"; +import { createListingFixture } from "../src/__tests__/helpers/tool-gateway-listing-fixture.js"; +import { stagingShapedToolPolicies } from "../src/__tests__/helpers/tool-policy-index-fixture.js"; +import * as current from "../src/services/tool-access-policy.js"; + +function option(name: string, fallback: string) { + const index = process.argv.indexOf(name); + return index < 0 ? fallback : process.argv[index + 1] ?? fallback; +} +const toolCount = Number(option("--tools", "800")); +const rounds = Number(option("--rounds", "9")); +const baselineRef = option("--baseline-ref", "origin/master"); +const concurrency = 16; // LISTING_DECISION_CONCURRENCY in tool-gateway.ts + +// The baseline imports its siblings by relative path, so it sits next to the +// current service for the run. Each run uses its own file, so overlapping runs +// cannot replace or remove another run's baseline. +const baselineSource = execFileSync("git", ["show", `${baselineRef}:server/src/services/tool-access-policy.ts`], { + cwd: fileURLToPath(new URL("..", import.meta.url)), maxBuffer: 64 * 1024 * 1024, +}); +const baselineUrl = new URL( + `../src/services/tool-access-policy.benchmark-baseline-${process.pid}-${randomBytes(4).toString("hex")}.ts`, + import.meta.url, +); +type Service = typeof current.toolAccessPolicyService; +let baseline: { toolAccessPolicyService: Service; createToolAccessDecisionCache: typeof current.createToolAccessDecisionCache }; +try { + writeFileSync(baselineUrl, baselineSource, { flag: "wx" }); + baseline = await import(pathToFileURL(fileURLToPath(baselineUrl)).href); +} finally { + rmSync(baselineUrl, { force: true }); +} + +async function mapWithConcurrency(items: readonly T[], mapper: (item: T) => Promise) { + const results = new Array(items.length); + let next = 0; + await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => { + while (next < items.length) { + const index = next++; + results[index] = await mapper(items[index]!); + } + })); + return results; +} + +type Db = ReturnType; + +/** Counts reads of the raw selectors on every tool_policies row. */ +function countingDb(db: Db) { + const counter = { reads: 0, selectorMatches: 0 }; + const counted = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields); + const from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args); + if (args[0] !== toolPolicies) return selection; + const execute = selection.execute.bind(selection); + selection.execute = (async (...rest: Parameters) => (await execute(...rest) as Array) + .map((row) => ({ ...row, selectors: new Proxy(row.selectors, { + get(selector, property, receiver) { counter.reads += 1; return Reflect.get(selector, property, receiver); }, + // A raw selector match starts with Object.keys(selector). + ownKeys(selector) { counter.reads += 1; counter.selectorMatches += 1; return Reflect.ownKeys(selector); }, + }) }))) as typeof execute; + return selection; + }) as typeof builder.from; + return builder; + }; + } }); + return { db: counted, counter }; +} + +const database = await startEmbeddedPostgresTestDatabase("paperclip-policy-matching-benchmark-"); +const db = createDb(database.connectionString); +try { + const fixture = await createListingFixture(db, toolCount); + await db.insert(toolPolicies).values(stagingShapedToolPolicies({ + catalogEntries: fixture.entries, + agentId: fixture.agent.id, + projectId: fixture.project.id, + applicationId: fixture.application.id, + connectionId: fixture.connection.id, + }).map((values) => ({ ...values, companyId: fixture.company.id }))); + const inputs: ToolAccessDecisionInput[] = fixture.entries.map((entry) => ({ + companyId: fixture.company.id, + actor: { actorType: "agent", actorId: fixture.agent.id, agentId: fixture.agent.id }, + runContext: { heartbeatRunId: fixture.run.id, issueId: fixture.issue.id, projectId: fixture.project.id, gatewayId: fixture.namedGateway.id }, + request: { + toolName: entry.toolName!, applicationId: fixture.application.id, connectionId: fixture.connection.id, + catalogEntryId: entry.id, upstreamToolName: entry.toolName!, riskLevel: entry.riskLevel, arguments: {}, + }, + consumeRateLimit: false, + })); + const policyRows = await db.select().from(toolPolicies); + const implementations = { + baseline: { service: baseline.toolAccessPolicyService(db), cache: baseline.createToolAccessDecisionCache }, + current: { service: current.toolAccessPolicyService(db), cache: current.createToolAccessDecisionCache }, + }; + const listing = async (name: keyof typeof implementations) => { + const { service, cache } = implementations[name]; + const decisionCache = cache(); + return mapWithConcurrency(inputs, (input) => service.decide(input, { cache: decisionCache })); + }; + + // Same decisions from both before measuring. + const [before, after] = [await listing("baseline"), await listing("current")]; + if (JSON.stringify(before) !== JSON.stringify(after)) throw new Error("Baseline and current decisions differ"); + + // Selector work per listing, measured on the raw rows. + const work: Record = {}; + for (const [name, factory] of [["baseline", baseline.toolAccessPolicyService], ["current", current.toolAccessPolicyService]] as const) { + const { db: counted, counter } = countingDb(db); + const service = factory(counted); + const decisionCache = current.createToolAccessDecisionCache(); + await mapWithConcurrency(inputs, (input) => service.decide(input, { cache: decisionCache })); + work[name] = { rawSelectorReads: counter.reads, selectorEvaluations: counter.selectorMatches }; + } + // The current path evaluates compiled selectors, one per candidate policy. + const index = current.indexEnabledToolPolicies(policyRows); + work.current!.selectorEvaluations = fixture.entries.reduce((sum, entry) => sum + index.candidates({ + actorType: "agent", agentId: null, projectId: null, routineId: null, issueId: null, gatewayId: null, applicationId: null, + connectionId: null, catalogEntryId: entry.id, applicationKey: null, providerType: null, toolName: entry.toolName!, + upstreamToolName: entry.toolName!, riskLevel: null, + }).length, 0); + + const samples: Record> = { baseline: [], current: [] }; + for (let round = 0; round < rounds + 2; round += 1) { + const order = round % 2 === 0 ? ["baseline", "current"] as const : ["current", "baseline"] as const; + for (const name of order) { + global.gc?.(); + const delay = monitorEventLoopDelay({ resolution: 1 }); + // The delay timer runs before the timed work starts and after it ends, so + // it also records a long final synchronous stretch. + delay.enable(); + await sleep(5); + const cpu = process.cpuUsage(); + const started = performance.now(); + await listing(name); + const wallMs = performance.now() - started; + const used = process.cpuUsage(cpu); + await sleep(5); + delay.disable(); + // Two warm-up rounds are not recorded. + if (round >= 2) samples[name]!.push({ wallMs, cpuMs: (used.user + used.system) / 1000, maxBlockMs: delay.max / 1e6 }); + } + } + const stats = (values: number[]) => { + const sorted = [...values].sort((left, right) => left - right); + const round1 = (value: number) => Math.round(value * 10) / 10; + return { median: round1(sorted[Math.floor(sorted.length / 2)]!), min: round1(sorted[0]!), max: round1(sorted.at(-1)!) }; + }; + for (const name of ["baseline", "current"] as const) { + const values = samples[name]!; + console.log(JSON.stringify({ + implementation: name, tools: toolCount, policies: policyRows.length, runs: values.length, + wallMs: stats(values.map((sample) => sample.wallMs)), + cpuMs: stats(values.map((sample) => sample.cpuMs)), + maxEventLoopBlockMs: stats(values.map((sample) => sample.maxBlockMs)), + ...work[name], + })); + } +} finally { + await database.cleanup(); +} diff --git a/server/src/__tests__/agent-scaling-load-model.test.ts b/server/src/__tests__/agent-scaling-load-model.test.ts index a6212c1f50a..f7c2b79e981 100644 --- a/server/src/__tests__/agent-scaling-load-model.test.ts +++ b/server/src/__tests__/agent-scaling-load-model.test.ts @@ -13,9 +13,10 @@ describe("agent scaling load model", () => { // The default batches deltas and renews every lease in one tick; the other // mode is the earlier one transaction per delta and per lease. it.each([ - { mode: "batched deltas and shared lease renewal", env: {} }, - { mode: "one transaction per delta and per lease", env: { DELTA_BATCH_MS: "0", LEASE_MODE: "single" } }, - ])("drives every source through the real server code and reports each pool ($mode)", async ({ env }) => { + { mode: "recorded event mix, batched deltas and shared lease renewal", env: {}, profile: "recorded" }, + { mode: "stress profile, one transaction per delta and per lease", + env: { PROFILE: "stress", DELTA_BATCH_MS: "0", LEASE_MODE: "single" }, profile: "stress" }, + ])("drives every source through the real server code and reports each pool ($mode)", async ({ env, profile }) => { const { stdout } = await run(process.execPath, [tsx, script], { cwd: serverRoot, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, AGENTS: "2", SECONDS: "2", DELTAS_PER_S: "5", EVENTS_PER_S: "2", API_PER_S: "1", LEASE_S: "1", ...env }, @@ -24,7 +25,13 @@ describe("agent scaling load model", () => { database: { meteredStatementsPerSecondByPool: Record<"main" | "checkpoint" | "lease", number> }; checkpointSaves: { failed: number }; bySource: Record; + profile: string; + eventsIssuedByType: Record; }; + expect(report.profile).toBe(profile); + // Server trace spans and runner events with a progress wake are both in the mix. + expect(report.eventsIssuedByType["run.performance.span"]).toBeGreaterThan(0); + expect(Object.keys(report.eventsIssuedByType).some(type => type.startsWith("tool.execution.") || type === "item.completed")).toBe(true); expect(Object.keys(report.bySource).sort()).toEqual(["api", "deltas", "events", "lease"]); for (const [source, result] of Object.entries(report.bySource)) { expect(result.failed, source).toBe(0); @@ -41,4 +48,19 @@ describe("agent scaling load model", () => { expect(report.database.meteredStatementsPerSecondByPool.checkpoint).toBeGreaterThan(0); expect(report.database.meteredStatementsPerSecondByPool.lease).toBeGreaterThan(0); }, 240_000); + + it.each([ + { profile: "recorded", env: {}, rates: { deltas: 0.2, events: 0.5, api: 0.3 } }, + { profile: "burst", env: { PROFILE: "burst" }, rates: { deltas: 2.5, events: 3, api: 0.3 } }, + { profile: "stress", env: { PROFILE: "stress" }, rates: { deltas: 20, events: 1, api: 0.3 } }, + { profile: "burst", env: { PROFILE: "burst", DELTAS_PER_S: "1" }, rates: { deltas: 1, events: 3, api: 0.3 } }, + ])("uses the $profile profile's rates unless a rate is set on its own ($env)", async ({ profile, env, rates }) => { + const { stdout } = await run(process.execPath, [tsx, script], { + cwd: serverRoot, maxBuffer: 16 * 1024 * 1024, + env: { ...process.env, AGENTS: "1", SECONDS: "1", SOURCES: "deltas,events,api", ...env }, + }); + const report = JSON.parse(stdout.slice(stdout.indexOf("{"))) as { profile: string; perAgentRatesPerSecond: Record }; + expect(report.profile).toBe(profile); + expect(report.perAgentRatesPerSecond).toEqual(rates); + }, 240_000); }); diff --git a/server/src/__tests__/automatic-run-brake-import.test.ts b/server/src/__tests__/automatic-run-brake-import.test.ts index a46adb46a18..a64c70cbf68 100644 --- a/server/src/__tests__/automatic-run-brake-import.test.ts +++ b/server/src/__tests__/automatic-run-brake-import.test.ts @@ -6,6 +6,6 @@ describe("automatic-run brake module graph", () => { const brake = await import("../services/recovery/automatic-run-brake.js"); const rules = await brake.automaticRunOutcomeRules(); expect(rules.isTransientSetupCode("environment_provider_unavailable")).toBe(true); - expect(rules.isPersonOwnedFailureCode("budget_hard_stop")).toBe(true); + expect(rules.hasNativePreDispatchFailureRecord({ nativePreDispatchFailure: { version: 1, providerWorkStarted: false } })).toBe(true); }, 600_000); }); diff --git a/server/src/__tests__/automatic-run-brake-recovery-passes.test.ts b/server/src/__tests__/automatic-run-brake-recovery-passes.test.ts index a8830f57ea7..e52119ec75d 100644 --- a/server/src/__tests__/automatic-run-brake-recovery-passes.test.ts +++ b/server/src/__tests__/automatic-run-brake-recovery-passes.test.ts @@ -13,6 +13,7 @@ import { taskAutomaticAttempts } from "../services/recovery/task-automatic-attem import { CONTINUATION_CAP } from "../services/recovery/assigned-work-invariant.js"; import { deliverReconciledExecutions } from "../services/execution-recovery-resolution.js"; import { continueHeldExecutions, resetBacklogContinuationPacingForTests } from "../services/fresh-continuation-fallback.js"; +import { createSystemRecovery } from "../services/system-recovery-state.js"; const support = await getEmbeddedPostgresTestSupport(); const suite = support.supported ? describe : describe.skip; @@ -370,6 +371,44 @@ suite("automatic-run brake in the recovery passes", () => { expect(wake).toHaveBeenCalledTimes(1); }, 120_000); + it("the sweep's continuation behind a run refused at dispatch only records, and its delivery creates the run only after the pause", async () => { + await seedCompany(); + const issueId = randomUUID(); + const blockedAt = ago(20 * MINUTE); + await db.insert(issues).values({ id: issueId, companyId, title: "Finish the report", status: "blocked", assigneeAgentId: agentId, + statusVersion: 3, blockedTransitionAt: blockedAt, updatedAt: ago(2 * HOUR), createdAt: ago(5 * HOUR) }); + const [source] = await db.insert(heartbeatRuns).values({ companyId, agentId, invocationSource: "automation", status: "failed", + runtimeMode: "legacy", errorCode: "adapter_failed", error: "native_instruction_materialization_handoff_unavailable", + startedAt: new Date(blockedAt.getTime() - MINUTE), finishedAt: new Date(blockedAt.getTime() - 500), + createdAt: new Date(blockedAt.getTime() - 2 * MINUTE), livenessState: "failed", + runnerProfileJson: { adapterDispatch: { adapterType: "codex_local" } }, resultJson: { workspaceRestoreFailure: "restore_failed" }, + contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_children_completed" } }).returning(); + await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", status: "active", + ownerType: "board", returnOwnerAgentId: agentId, cause: "legacy_execution_requires_reconciliation", + fingerprint: `legacy-execution:${source!.id}`, nextAction: "Held.", createdAt: blockedAt, + evidence: { runId: source!.id, originalFailureCode: "adapter_failed", workspaceRestoreFailure: "restore_failed", + systemRecovery: { ...createSystemRecovery(source!.id), state: "complete" } } }); + await db.insert(heartbeatRuns).values({ companyId, agentId, invocationSource: "automation", status: "cancelled", + errorCode: "execution_reconciliation_required", startedAt: null, retryOfRunId: source!.id, runtimeMode: "legacy", + finishedAt: new Date(blockedAt.getTime() + 1_000), createdAt: new Date(blockedAt.getTime() - 100), resultJson: {}, + contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_continuation_needed", retryReason: "issue_continuation_needed" } }); + const enqueueWakeup = wakeQueue(); + const recovery = recoveryService(db, { enqueueWakeup, scheduleRecoveryRetry: async () => null } as never); + const runsBefore = (await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId))).length; + expect(await recovery.assignedWork.checkIssue({ companyId, issueId })).toMatchObject({ outcome: "repaired" }); + expect((await continuationRecords(source!.id))[0]?.evidence).toMatchObject({ continuationDelivery: "pending" }); + expect(enqueueWakeup).not.toHaveBeenCalled(); + expect((await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId))).length).toBe(runsBefore); + const failures = await openBrake(); + const wake = runWake(); + await deliverReconciledExecutions(db, wake as never); + expect(wake).not.toHaveBeenCalled(); + await recover(failures); + await db.delete(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.status, "running"))); + await deliverReconciledExecutions(db, wake as never); + expect(wake).toHaveBeenCalledTimes(1); + }, 120_000); + it("one held task spends one creation slot while open", async () => { await seedCompany(); await heldBacklog(); diff --git a/server/src/__tests__/automatic-run-brake.test.ts b/server/src/__tests__/automatic-run-brake.test.ts index 48afc8a7c2a..31db15dafb5 100644 --- a/server/src/__tests__/automatic-run-brake.test.ts +++ b/server/src/__tests__/automatic-run-brake.test.ts @@ -436,6 +436,7 @@ suite("automatic-run brake", () => { for (let index = 0; index < AUTOMATIC_RUN_BRAKE.maxRuns + 200; index += 1) { await brake.holdAutomaticRunStart(db, { id: randomUUID(), companyId, contextSnapshot: { wakeReason: "issue_continuation_needed" } }); } - expect(brake.cacheSizes()).toEqual({ companies: AUTOMATIC_RUN_BRAKE.maxCompanies, runs: AUTOMATIC_RUN_BRAKE.maxRuns }); + expect(brake.cacheSizes()).toMatchObject({ companies: AUTOMATIC_RUN_BRAKE.maxCompanies, runs: AUTOMATIC_RUN_BRAKE.maxRuns }); + expect(brake.cacheSizes().wakes).toBeLessThanOrEqual(AUTOMATIC_RUN_BRAKE.maxCompanies); }, 180_000); }); diff --git a/server/src/__tests__/automatic-run-start-gate.test.ts b/server/src/__tests__/automatic-run-start-gate.test.ts new file mode 100644 index 00000000000..72a96dfc9fd --- /dev/null +++ b/server/src/__tests__/automatic-run-start-gate.test.ts @@ -0,0 +1,311 @@ +import { randomUUID } from "node:crypto"; +import { eq, inArray, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { agentWakeupRequests, agents, authUsers, automaticRunBrakes, companies, companyMemberships, createDb, heartbeatRuns, issues } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { heartbeatService } from "../services/heartbeat.ts"; +import { runningProcesses } from "../adapters/index.ts"; +import { AUTOMATIC_RUN_BRAKE, automaticRunBrake, takeDueAutomaticRunWakes } from "../services/recovery/automatic-run-brake.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { registerRunDispatchWork } from "../services/heartbeat/dispatch-work.js"; + +const gate = vi.hoisted(() => ({ open: false, releases: [] as Array<() => void> })); + +const mockAdapterExecute = vi.hoisted(() => vi.fn(async () => { + if (!gate.open) await new Promise(resolve => gate.releases.push(resolve)); + return { exitCode: 0, signal: null, timedOut: false, errorMessage: null, summary: "Start gate test run.", provider: "test", model: "test-model" }; +})); + +vi.mock("../adapters/index.ts", async () => { + const actual = await vi.importActual("../adapters/index.ts"); + return { ...actual, getServerAdapter: vi.fn(() => ({ supportsLocalAgentJwt: false, execute: mockAdapterExecute })) }; +}); + +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; +const MINUTE = 60_000; + +suite("automatic-run start gate in the dispatch pass", () => { + let db!: ReturnType; + let temporary: Awaited> | null = null; + let heartbeat!: ReturnType; + const userId = randomUUID(); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-automatic-run-start-gate-"); + db = createDb(temporary.connectionString); + heartbeat = heartbeatService(db); + await db.insert(authUsers).values({ id: userId, name: "Board", email: `${userId}@example.test`, emailVerified: true, + createdAt: new Date(), updatedAt: new Date() }); + }, 60_000); + + afterEach(async () => { + vi.restoreAllMocks(); + gate.open = true; + for (const release of gate.releases.splice(0)) release(); + await heartbeat.drainActiveRunExecutions(); + gate.open = false; + mockAdapterExecute.mockClear(); + runningProcesses.clear(); + automaticRunBrake.reset(); + await db.execute(sql`truncate table ${companies} cascade`); + }, 180_000); + + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }, 120_000); + + async function seedCompany(agentCount: number, maxConcurrentRuns: number) { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Start gate", status: "active", + issuePrefix: `G${companyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false, + defaultResponsibleUserId: userId }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" }); + const agentIds: string[] = []; + for (let index = 0; index < agentCount; index += 1) { + const agentId = randomUUID(); + await db.insert(agents).values({ id: agentId, companyId, name: `Gate ${index}`, role: "engineer", status: "idle", + adapterType: "codex_local", adapterConfig: {}, permissions: {}, + runtimeConfig: { heartbeat: { enabled: true, intervalSec: 60, wakeOnDemand: true, maxConcurrentRuns } } }); + agentIds.push(agentId); + } + return { companyId, agentIds }; + } + + async function queued(companyId: string, agentId: string, count: number, context: (index: number) => Record, + ageMs = 30 * MINUTE) { + if (count === 0) return []; + const tasks = await db.insert(issues).values(Array.from({ length: count }, (_, index) => ({ companyId, title: `Task ${index}`, + status: "todo", assigneeAgentId: agentId }))).returning({ id: issues.id }); + return db.insert(heartbeatRuns).values(tasks.map((task, index) => ({ companyId, agentId, issueId: task.id, scopeKind: "issue" as const, + invocationSource: "automation", triggerDetail: "system", status: "queued", createdAt: new Date(Date.now() - ageMs + index), + contextSnapshot: { ...context(index), issueId: task.id, taskId: task.id } }))).returning(); + } + + const automatic = () => ({ wakeReason: "issue_continuation_needed", previousRunId: randomUUID() }); + + async function openBrake(companyId: string, agentId: string, options: { probeAllowed: boolean }) { + await db.insert(heartbeatRuns).values(Array.from({ length: 20 }, (_, index) => ({ companyId, agentId, invocationSource: "automation", + triggerDetail: "system", runtimeMode: "legacy", status: "failed", errorCode: "environment_provider_unavailable", + executionStage: "preparing", createdAt: new Date(Date.now() - 4 * MINUTE), startedAt: new Date(Date.now() - 3 * MINUTE), + finishedAt: new Date(Date.now() - MINUTE + index * 100), resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }, + contextSnapshot: { wakeReason: "transient_failure_retry" } }))); + expect((await automaticRunBrake.refresh(db, companyId)).state).toBe("open"); + if (!options.probeAllowed) await db.update(automaticRunBrakes).set({ nextProbeAt: sql`now() + interval '10 minutes'` }) + .where(eq(automaticRunBrakes.companyId, companyId)); + automaticRunBrake.reset(); + } + + const statuses = async (ids: string[]) => db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode }) + .from(heartbeatRuns).where(inArray(heartbeatRuns.id, ids)); + const started = async (ids: string[]) => (await statuses(ids)).filter(run => run.status !== "queued").length; + + function countQueries() { + let count = 0; + for (const method of ["select", "insert", "update", "delete", "execute", "transaction"] as const) { + const original = db[method].bind(db) as (...args: unknown[]) => unknown; + vi.spyOn(db, method).mockImplementation(((...args: unknown[]) => { count += 1; return original(...args); }) as never); + } + return () => count; + } + + async function passCost(heldRuns: number, passes: number) { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + await openBrake(companyId, agentId!, { probeAllowed: false }); + const runs = await queued(companyId, agentId!, heldRuns, automatic); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + const read = countQueries(); + for (let pass = 0; pass < passes; pass += 1) await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + const total = read(); + vi.restoreAllMocks(); + expect(await started(runs.map(run => run.id))).toBe(0); + expect((await statuses(runs.map(run => run.id))).every(run => run.errorCode === null)).toBe(true); + return total; + } + + it("walks hundreds of held runs without a claim attempt or a row read, and still starts other work in the same pass", async () => { + const small = await passCost(10, 100); + const large = await passCost(250, 100); + expect(large).toBeLessThanOrEqual(small + 100); + const beyondCache = await passCost(AUTOMATIC_RUN_BRAKE.maxRuns + 476, 3); + expect(beyondCache).toBeLessThanOrEqual(await passCost(10, 3) + 100); + + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + await openBrake(companyId, agentId!, { probeAllowed: false }); + const held = await queued(companyId, agentId!, 250, automatic); + const [work] = await queued(companyId, agentId!, 1, () => ({ wakeReason: "issue_assigned" }), 0); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await started([work!.id])).toBe(1); + expect(await started(held.map(run => run.id))).toBe(0); + }, 600_000); + + it("returns the probe when its run's claim is declined, so another automatic run starts in the same pass", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 5); + await openBrake(companyId, agentId!, { probeAllowed: true }); + const [declined, next] = await queued(companyId, agentId!, 2, () => ({ wakeReason: "transient_failure_retry" })); + await db.update(heartbeatRuns).set({ runnerProfileJson: { chatControlRecoveryAdmission: { phase: "unknown" } } }) + .where(eq(heartbeatRuns.id, declined!.id)); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await started([declined!.id])).toBe(0); + expect(await started([next!.id])).toBe(1); + const [brake] = await db.select().from(automaticRunBrakes).where(eq(automaticRunBrakes.companyId, companyId)); + expect(brake?.probeRunId).toBe(next!.id); + automaticRunBrake.reset(); + await heartbeatService(db).resumeQueuedRunsAfterDrain({ companyId }); + expect(await started([declined!.id])).toBe(0); + expect((await db.select().from(automaticRunBrakes).where(eq(automaticRunBrakes.companyId, companyId)))[0]?.probeRunId).toBe(next!.id); + }, 300_000); + + it("returns an unused half-open release start to its window", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + const runs = await queued(companyId, agentId!, 4, automatic); + await db.insert(automaticRunBrakes).values({ companyId, state: "half_open", stateChangedAt: sql`date_trunc('milliseconds', now())`, + openedAt: sql`now() - interval '5 minutes'` }); + const reserve = (index: number) => automaticRunBrake.reserveStart(db, runs[index]!, { personOrigin: false }); + const first = await reserve(0); + expect(first.held).toBe(false); + expect((await reserve(1)).held).toBe(false); + automaticRunBrake.reset(); + expect((await reserve(2)).held).toBe(true); + if (!first.held) await first.release(); + expect((await reserve(2)).held).toBe(false); + automaticRunBrake.reset(); + expect((await reserve(3)).held).toBe(true); + }, 300_000); + + it("never holds a person's Retry", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + await openBrake(companyId, agentId!, { probeAllowed: false }); + const held = await queued(companyId, agentId!, 20, automatic); + const [retry] = await queued(companyId, agentId!, 1, () => ({ wakeReason: "task_retry", previousRunId: randomUUID() }), 0); + const [request] = await db.insert(agentWakeupRequests).values({ companyId, agentId: agentId!, source: "on_demand", triggerDetail: "manual", + reason: "task_retry", status: "queued", requestedByActorType: "user", requestedByActorId: userId, runId: retry!.id }).returning(); + await db.update(heartbeatRuns).set({ wakeupRequestId: request!.id }).where(eq(heartbeatRuns.id, retry!.id)); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await started([retry!.id])).toBe(1); + expect(await started(held.map(run => run.id))).toBe(0); + }, 300_000); + + it("never holds the only queued run when it continues a person's Retry", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + await openBrake(companyId, agentId!, { probeAllowed: false }); + const [retry] = await db.insert(heartbeatRuns).values({ companyId, agentId: agentId!, invocationSource: "on_demand", + triggerDetail: "manual", status: "failed", errorCode: "process_lost", startedAt: new Date(Date.now() - 2 * MINUTE), + finishedAt: new Date(Date.now() - MINUTE), contextSnapshot: { wakeReason: "task_retry" } }).returning(); + const [continuation] = await queued(companyId, agentId!, 1, + () => ({ wakeReason: "issue_continuation_needed", previousRunId: retry!.id }), 0); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await started([continuation!.id])).toBe(1); + }, 300_000); + + it("starts exactly one probe across two server instances", async () => { + const { companyId, agentIds } = await seedCompany(2, 5); + await openBrake(companyId, agentIds[0]!, { probeAllowed: true }); + const runs = [...await queued(companyId, agentIds[0]!, 10, automatic), ...await queued(companyId, agentIds[1]!, 10, automatic)]; + const other = heartbeatService(db); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + automaticRunBrake.reset(); + await other.resumeQueuedRunsAfterDrain({ companyId }); + automaticRunBrake.reset(); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await started(runs.map(run => run.id))).toBe(1); + for (const release of gate.releases.splice(0)) release(); + await other.drainActiveRunExecutions(); + }, 300_000); + + it("releases held runs at a doubling rate per window", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 100); + const runs = await queued(companyId, agentId!, 40, automatic); + await db.insert(automaticRunBrakes).values({ companyId, state: "half_open", stateChangedAt: sql`date_trunc('milliseconds', now())`, + openedAt: sql`now() - interval '5 minutes'` }); + const counts: number[] = []; + for (let step = 0; step < 3; step += 1) { + automaticRunBrake.reset(); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + counts.push(await started(runs.map(run => run.id))); + await db.update(automaticRunBrakes).set({ + stateChangedAt: sql`state_changed_at - ${`${AUTOMATIC_RUN_BRAKE.releaseIntervalMs} milliseconds`}::interval`, + releaseWindowStartedAt: sql`release_window_started_at - ${`${AUTOMATIC_RUN_BRAKE.releaseIntervalMs} milliseconds`}::interval`, + }).where(eq(automaticRunBrakes.companyId, companyId)); + } + expect(counts).toEqual([2, 6, 14]); + }, 300_000); + + it("keeps held runs out of the declined-claim backoff, so they start on the first pass after the pause", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 10); + await openBrake(companyId, agentId!, { probeAllowed: false }); + const runs = await queued(companyId, agentId!, 5, automatic); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await started(runs.map(run => run.id))).toBe(0); + await db.delete(automaticRunBrakes).where(eq(automaticRunBrakes.companyId, companyId)); + automaticRunBrake.reset(); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await started(runs.map(run => run.id))).toBeGreaterThanOrEqual(1); + }, 300_000); + + it("wakes the company's dispatch at the next try without polling", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + await openBrake(companyId, agentId!, { probeAllowed: false }); + await db.update(automaticRunBrakes).set({ nextProbeAt: sql`now() + interval '2 seconds'` }).where(eq(automaticRunBrakes.companyId, companyId)); + automaticRunBrake.reset(); + await queued(companyId, agentId!, 3, automatic); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(takeDueAutomaticRunWakes().companyIds).toEqual([]); + const resumed: Array = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => undefined }); + try { + await registerRunDispatchWork(coordinator, { + promoteDueScheduledRetries: async () => undefined, + nextScheduledRetryAt: async () => null, + schedulingSuppressed: async () => false, + resumeQueuedRunsAfterDrain: async scope => { resumed.push(scope?.companyId); }, + listUndispatchedQueuedRuns: async () => [], + }, () => true).ready; + await expect.poll(() => resumed, { timeout: 30_000, interval: 250 }).toContain(companyId); + } finally { + await coordinator.stop(); + } + }, 300_000); + + it("still wakes every held company at its next try when more companies are held than the wake list keeps", async () => { + const companyIds: string[] = []; + for (let index = 0; index < AUTOMATIC_RUN_BRAKE.maxCompanies + 20; index += 1) { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + await openBrake(companyId, agentId!, { probeAllowed: false }); + companyIds.push(companyId); + } + for (const companyId of companyIds) { + expect(await automaticRunBrake.holdAutomaticRunStart(db, { id: randomUUID(), companyId, contextSnapshot: automatic() }, + { personOrigin: false })).toBe(true); + } + expect(automaticRunBrake.cacheSizes().wakes).toBeLessThanOrEqual(AUTOMATIC_RUN_BRAKE.maxCompanies); + const nextAt = automaticRunBrake.takeDueWakes(Number.NEGATIVE_INFINITY).nextAt; + expect(nextAt).not.toBeNull(); + expect(nextAt!).toBeLessThanOrEqual(Date.now() + 11 * MINUTE); + const due = takeDueAutomaticRunWakes(Date.now() + 20 * MINUTE); + expect(due.all || companyIds.every(companyId => due.companyIds.includes(companyId))).toBe(true); + expect(due.all).toBe(true); + }, 600_000); + + it("keeps a held automatic run queued while paused and starts it on its own at the next try", async () => { + const { companyId, agentIds: [agentId] } = await seedCompany(1, 1); + await openBrake(companyId, agentId!, { probeAllowed: false }); + await db.update(automaticRunBrakes).set({ nextProbeAt: sql`now() + interval '3 seconds'` }).where(eq(automaticRunBrakes.companyId, companyId)); + automaticRunBrake.reset(); + const [run] = await queued(companyId, agentId!, 1, () => ({ wakeReason: "transient_failure_retry" })); + const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId: agentId!, source: "automation", triggerDetail: "system", + reason: "transient_failure_retry", status: "queued", requestedByActorType: "system", runId: run!.id }).returning(); + await db.update(heartbeatRuns).set({ wakeupRequestId: wake!.id }).where(eq(heartbeatRuns.id, run!.id)); + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => undefined }); + try { + await heartbeat.registerRunDispatchWork(coordinator, () => true).ready; + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + expect(await statuses([run!.id])).toEqual([{ id: run!.id, status: "queued", errorCode: null }]); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + await expect.poll(() => mockAdapterExecute.mock.calls.length, { timeout: 60_000, interval: 250 }).toBe(1); + expect((await statuses([run!.id]))[0]?.status).toBe("running"); + for (const release of gate.releases.splice(0)) release(); + await expect.poll(async () => (await statuses([run!.id]))[0]?.status, { timeout: 60_000, interval: 250 }).toBe("succeeded"); + } finally { + await coordinator.stop(); + } + }, 300_000); +}); diff --git a/server/src/__tests__/company-skills-observability.test.ts b/server/src/__tests__/company-skills-observability.test.ts index 98db6802775..31cc9a965a9 100644 --- a/server/src/__tests__/company-skills-observability.test.ts +++ b/server/src/__tests__/company-skills-observability.test.ts @@ -7,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { context, SpanStatusCode, trace } from "@opentelemetry/api"; import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"; import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace"; -import { companies, companySkills, companySkillVersions, companySkillRepositorySnapshots, createDb, +import { closeDedicatedDbConnections, companies, companySkills, companySkillVersions, companySkillRepositorySnapshots, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db"; import { eq } from "drizzle-orm"; import { createRunPreparationTiming, withRunExecutionTiming } from "../services/execution-preparation-timing.js"; @@ -133,6 +133,7 @@ describeDatabase("runtime skill observability", () => { const name = new URL(database.connectionString).pathname.slice(1); assert.match(name, /^[a-zA-Z0-9_-]+$/); await db.$client.unsafe(`ALTER DATABASE "${name}" SET lock_timeout TO '100ms'`); + await closeDedicatedDbConnections(db, 1); const entered = deferred(), release = deferred(); const holder = withSkillVersionCacheLock(db, f.companyId, async () => { entered.resolve(); await release.promise; }); try { diff --git a/server/src/__tests__/helpers/tool-policy-index-fixture.ts b/server/src/__tests__/helpers/tool-policy-index-fixture.ts new file mode 100644 index 00000000000..28a0bc1a889 --- /dev/null +++ b/server/src/__tests__/helpers/tool-policy-index-fixture.ts @@ -0,0 +1,87 @@ +import type { toolPolicies } from "@paperclipai/db"; + +type PolicyValues = Pick; + +/** + * Enabled policies shaped like the staging company whose tools/list profile + * showed policy matching on the main thread: 363 policies, of which 342 select + * only a catalog entry, 18 a catalog entry and its connection, 3 several other + * keys, and 17 carry conditions. 359 require approval, 3 are trust rules and 1 + * blocks. + */ +export function stagingShapedToolPolicies(input: { + catalogEntries: ReadonlyArray<{ id: string; connectionId: string | null; toolName: string | null }>; + agentId: string; + projectId: string; + applicationId: string; + connectionId: string; +}): PolicyValues[] { + const { catalogEntries } = input; + if (catalogEntries.length === 0) throw new Error("At least one catalog entry is required"); + const entry = (index: number) => catalogEntries[index % catalogEntries.length]!; + const conditionShapes: Array> = [ + { risk: { isWrite: true } }, + { arguments: { fieldExists: ["query"] } }, + { context: { requireIssue: true } }, + { timeWindow: { daysOfWeekUtc: [0, 1, 2, 3, 4, 5, 6] } }, + ]; + const policies: PolicyValues[] = []; + for (let index = 0; index < 342; index += 1) { + policies.push({ + name: `Ask first ${index}`, + policyType: "require_approval", + priority: 100, + selectors: { catalogEntryId: entry(index).id }, + conditions: index < 17 ? conditionShapes[index % conditionShapes.length]! : null, + config: { source: "connection_intent" }, + }); + } + for (let index = 0; index < 18; index += 1) { + const selected = entry(342 + index); + policies.push({ + name: `Ask first on connection ${index}`, + policyType: "require_approval", + priority: 100, + selectors: { catalogEntryId: selected.id, connectionId: selected.connectionId ?? input.connectionId }, + conditions: null, + config: null, + }); + } + const trustedTool = entry(0).toolName ?? "tool"; + policies.push( + { + name: "Trusted for agent", + policyType: "trust_rule", + priority: 50, + selectors: { agentId: input.agentId, applicationId: input.applicationId, connectionId: input.connectionId, toolName: trustedTool }, + conditions: null, + config: { trustRule: { argumentFilters: { fieldEquals: { query: "status" } }, approvalThreshold: 3 } }, + }, + { + name: "Trusted in project", + policyType: "trust_rule", + priority: 50, + selectors: { projectId: input.projectId, connectionId: input.connectionId, toolName: trustedTool }, + conditions: null, + config: { trustRule: { argumentFilters: { fieldEquals: { query: "list" } }, approvalThreshold: 3 } }, + }, + { + name: "Trusted on application", + policyType: "trust_rule", + priority: 50, + selectors: { applicationId: input.applicationId, agentId: input.agentId, toolName: entry(1).toolName ?? "tool" }, + conditions: null, + config: { trustRule: { argumentFilters: { fieldEquals: { query: "read" } }, approvalThreshold: 3 } }, + }, + ); + // The block replaces one ask-first selector so the counts stay at 363. + policies[341] = { + name: "Block one action", + policyType: "block", + priority: 10, + selectors: { catalogEntryId: entry(341).id }, + conditions: null, + config: null, + }; + return policies; +} diff --git a/server/src/__tests__/status-card-evaluation-work.test.ts b/server/src/__tests__/status-card-evaluation-work.test.ts index 870eba73ea1..09d90c4a4f2 100644 --- a/server/src/__tests__/status-card-evaluation-work.test.ts +++ b/server/src/__tests__/status-card-evaluation-work.test.ts @@ -546,8 +546,8 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu try { const created = await card("reactive", { ...policy(), debounceSeconds: 1 }); const countLocks = async () => Number((await db.execute<{ count: string }>(sql` - select count(*) from pg_stat_activity where datname = current_database() - and application_name = 'paperclip-workspace-finalization-lock'`))[0]!.count); + select count(*) from pg_locks l join pg_database d on d.oid = l.database + where l.locktype = 'advisory' and d.datname = current_database()`))[0]!.count); const baseline = await countLocks(); await issueService(db).create(companyId, { title: "Pool-one blocker", status: "blocked", priority: "medium" }); const service = statusCardEvaluationService(db, { wakeup }); @@ -573,7 +573,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu expect(await service.next()).toBeNull(); expect(idleWorkSnapshot().active).toBe(0); await vi.waitFor(async () => expect(await countLocks()).toBe(baseline)); - // Failure exits also release the physical connection and advisory lock. + // Failure exits also release the advisory lock. await db.update(statusCards).set({ queries: [{ scope: "invalid" } as never], nextEvalAt: new Date() }).where(eq(statusCards.id, created.id)); await service.run(new AbortController().signal); expect((await statusCardService(db).getById(created.id))!.nextEvalReason).toBe("retry"); diff --git a/server/src/__tests__/tool-access-client-credentials.test.ts b/server/src/__tests__/tool-access-client-credentials.test.ts index c39fb3d0b42..f0f45c457ef 100644 --- a/server/src/__tests__/tool-access-client-credentials.test.ts +++ b/server/src/__tests__/tool-access-client-credentials.test.ts @@ -89,13 +89,16 @@ function fakeProvider() { metadataOnlyAtHint: false, /** Runs once when the server first receives a signed-in request (to stage races). */ onAuthorizedMcpRequest: null as null | (() => Promise), + signingAlgorithms: ["RS256", "ES256"], + /** Runs once at the start of the next token request (to stage a paused refresh). */ + onTokenRequest: null as null | (() => Promise), }; const metadata = (issuer: string) => ({ issuer, token_endpoint: `${issuer}/oauth/token`, grant_types_supported: ["client_credentials"], token_endpoint_auth_methods_supported: ["private_key_jwt", "client_secret_basic", "client_secret_post"], - token_endpoint_auth_signing_alg_values_supported: ["RS256", "ES256"], + token_endpoint_auth_signing_alg_values_supported: state.signingAlgorithms, }); const handle = async (input: string | URL | Request, init?: RequestInit): Promise => { const url = String(input instanceof Request ? input.url : input); @@ -118,6 +121,11 @@ function fakeProvider() { if (url === TOKEN_URL) { const body = new URLSearchParams(String(init?.body)); state.tokenRequests.push({ url, body, authorization: headers.get("authorization") }); + if (state.onTokenRequest) { + const hook = state.onTokenRequest; + state.onTokenRequest = null; + await hook(); + } if (state.tokenDelayMs) await new Promise((resolve) => setTimeout(resolve, state.tokenDelayMs)); if (body.get("grant_type") !== "client_credentials") return json({ error: "unsupported_grant_type" }, 400); const assertion = body.get("client_assertion"); @@ -602,6 +610,152 @@ describeEmbeddedPostgres("machine sign-in connections", () => { expect(provider.state.tokenRequests.at(-1)!.authorization).toBe(`Basic ${Buffer.from(`${CLIENT_ID}:switched-secret`).toString("base64")}`); }); + it("never leaves a refused test's secret behind with another client ID", async () => { + const company = await createCompany(); + const provider = useProvider(); + const svc = service(); + const created = await svc.createMachineSignIn(company.id, { + link: MCP_URL, method: "client_secret", clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, + }, actor); + await svc.testMachineSignIn(company.id, created.connectionId, {}, actor); + provider.state.extraClients.set("other-client", "other-secret"); + // While one admin tests another client, a second admin starts a key rotation. + provider.state.onAuthorizedMcpRequest = async () => { + await svc.rotateMachineSignIn(company.id, created.connectionId, { method: "paperclip_key" }, actor); + }; + await expect(svc.testMachineSignIn(company.id, created.connectionId, { clientId: "other-client", clientSecret: "other-secret" }, actor)) + .rejects.toMatchObject({ status: 409, details: expect.objectContaining({ code: "client_credentials_changed" }) }); + expect((await svc.getMachineSignIn(company.id, created.connectionId)).clientId).toBe(CLIENT_ID); + // A normal call (no forced refresh) still runs as the original client: the + // refused test did not swap in its own token. + await svc.checkHealth(created.connectionId, actor); + const used = provider.state.mcpRequests.at(-1)!.authorization!.replace("Bearer ", ""); + expect(provider.state.tokenClients.get(used)).toBe(CLIENT_ID); + // The refused test wrote nothing: the saved ID and secret still belong together. + const grant = await organizationGrant(created.connectionId); + await svc.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: created.connectionId, grantId: grant.id, forceRefresh: true, actor }); + expect(provider.state.tokenRequests.at(-1)!.authorization).toBe(`Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`); + }); + + it("refuses an older retest after another retest replaced both the client ID and secret", async () => { + const company = await createCompany(); + const provider = useProvider(); + const svc = service(); + const created = await svc.createMachineSignIn(company.id, { + link: MCP_URL, method: "client_secret", clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, + }, actor); + await svc.testMachineSignIn(company.id, created.connectionId, {}, actor); + provider.state.extraClients.set("other-client", "other-secret"); + // While one admin re-tests the original client, another replaces both the ID and secret. + provider.state.onAuthorizedMcpRequest = async () => { + await svc.testMachineSignIn(company.id, created.connectionId, { clientId: "other-client", clientSecret: "other-secret" }, actor); + }; + await expect(svc.testMachineSignIn(company.id, created.connectionId, { clientId: CLIENT_ID, clientSecret: CLIENT_SECRET }, actor)) + .rejects.toMatchObject({ status: 409, details: expect.objectContaining({ code: "client_credentials_changed" }) }); + expect((await svc.getMachineSignIn(company.id, created.connectionId)).clientId).toBe("other-client"); + const grant = await organizationGrant(created.connectionId); + await svc.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: created.connectionId, grantId: grant.id, forceRefresh: true, actor }); + expect(provider.state.tokenRequests.at(-1)!.authorization).toBe(`Basic ${Buffer.from("other-client:other-secret").toString("base64")}`); + }); + + it("reloads accepted key types for a connection saved before they were recorded", async () => { + const company = await createCompany(); + const provider = useProvider(); + provider.state.signingAlgorithms = ["ES256"]; + const svc = service(); + const created = await svc.createMachineSignIn(company.id, { + link: MCP_URL, method: "client_secret", clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, + }, actor); + await svc.testMachineSignIn(company.id, created.connectionId, {}, actor); + const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, created.connectionId)); + const { tokenEndpointAuthSigningAlgValuesSupported: _dropped, ...olderOauth } = row!.config.oauth as Record; + const olderConfig = { ...row!.config, oauth: olderOauth }; + await db.update(toolConnections).set({ config: olderConfig, transportConfig: olderConfig }).where(eq(toolConnections.id, row!.id)); + const started = await svc.rotateMachineSignIn(company.id, created.connectionId, { method: "paperclip_key" }, actor); + expect(started.machineSignIn.pendingPublicKey?.algorithm).toBe("ES256"); + }); + + it("lets a retest that replaces the secret and normal token refreshes finish together", async () => { + const company = await createCompany(); + const provider = useProvider(); + const svc = service(); + const created = await svc.createMachineSignIn(company.id, { + link: MCP_URL, method: "client_secret", clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, + }, actor); + await svc.testMachineSignIn(company.id, created.connectionId, {}, actor); + const grant = await organizationGrant(created.connectionId); + const refresh = () => service().refreshOAuthGrantCredentials({ companyId: company.id, connectionId: created.connectionId, grantId: grant.id, forceRefresh: true, actor }); + const started = Date.now(); + await Promise.all([ + svc.testMachineSignIn(company.id, created.connectionId, { clientSecret: CLIENT_SECRET }, actor), + refresh(), refresh(), refresh(), + ]); + expect(Date.now() - started).toBeLessThan(15_000); + }, 60_000); + + it("recovers from a refresh abandoned by a stopped server", async () => { + const company = await createCompany(); + const provider = useProvider(); + const { svc, created } = await setupKeyConnection(company.id, provider); + const grant = await organizationGrant(created.connectionId); + const abandoned = async () => { + const current = await organizationGrant(created.connectionId); + await db.update(connectionGrants).set({ + providerTenant: { ...(current.providerTenant ?? {}), oauth: { + ...((current.providerTenant ?? {}).oauth as object ?? {}), + accessTokenExpiresAt: "2000-01-01T00:00:00.000Z", + refreshLease: { id: "stopped-server", expiresAt: "2000-01-01T00:00:00.000Z" }, + } }, + }).where(eq(connectionGrants.id, grant.id)); + }; + // The next request takes over the abandoned lease and gets a new token. + await abandoned(); + const before = provider.state.issued; + await svc.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: created.connectionId, grantId: grant.id, actor }); + expect(provider.state.issued).toBe(before + 1); + // A successful retest also clears an abandoned lease. + await abandoned(); + await svc.testMachineSignIn(company.id, created.connectionId, {}, actor); + expect(((await organizationGrant(created.connectionId)).providerTenant?.oauth as Record).refreshLease).toBeUndefined(); + }); + + it("never saves the token of a refresh whose lease was taken over", async () => { + const company = await createCompany(); + const provider = useProvider(); + const { created } = await setupKeyConnection(company.id, provider); + const grant = await organizationGrant(created.connectionId); + const input = { companyId: company.id, connectionId: created.connectionId, grantId: grant.id, forceRefresh: true, actor }; + // Refresh A pauses past its lease; refresh B on another server takes over and finishes. + provider.state.onTokenRequest = async () => { + const current = await organizationGrant(created.connectionId); + const oauth = (current.providerTenant ?? {}).oauth as Record; + await db.update(connectionGrants).set({ + providerTenant: { ...(current.providerTenant ?? {}), oauth: { ...oauth, refreshLease: { ...(oauth.refreshLease as object), expiresAt: "2000-01-01T00:00:00.000Z" } } }, + }).where(eq(connectionGrants.id, grant.id)); + await service().refreshOAuthGrantCredentials(input); + }; + const issuedBefore = provider.state.issued; + await expect(service().refreshOAuthGrantCredentials(input)) + .rejects.toMatchObject({ details: expect.objectContaining({ code: "oauth_refresh_superseded" }) }); + const takeoverToken = `machine-token-${issuedBefore + 1}`; + // Normal calls use the takeover's token, not the one the paused refresh received later. + await service().checkHealth(created.connectionId, actor); + expect(provider.state.mcpRequests.at(-1)!.authorization).toBe(`Bearer ${takeoverToken}`); + }); + + it("creates the kind of key the sign-in service accepts when switching from a secret", async () => { + const company = await createCompany(); + const provider = useProvider(); + provider.state.signingAlgorithms = ["ES256"]; + const svc = service(); + const created = await svc.createMachineSignIn(company.id, { + link: MCP_URL, method: "client_secret", clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, + }, actor); + await svc.testMachineSignIn(company.id, created.connectionId, {}, actor); + const started = await svc.rotateMachineSignIn(company.id, created.connectionId, { method: "paperclip_key" }, actor); + expect(started.machineSignIn.pendingPublicKey?.algorithm).toBe("ES256"); + }); + it("tries a new client secret before replacing the old one", async () => { const company = await createCompany(); const provider = useProvider(); diff --git a/server/src/__tests__/tool-access-policy-index.test.ts b/server/src/__tests__/tool-access-policy-index.test.ts new file mode 100644 index 00000000000..1eb798ddd78 --- /dev/null +++ b/server/src/__tests__/tool-access-policy-index.test.ts @@ -0,0 +1,419 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { createDb, toolPolicies, type Db as DbClient } from "@paperclipai/db"; +import { toolPolicyConditionsSchema, type ToolAccessDecisionInput } from "@paperclipai/shared"; +import { + createToolAccessDecisionCache, + evaluatePolicyConditions, + indexEnabledToolPolicies, + matchEnabledToolPolicies, + policyConditions, + selectorMatches, + toolAccessPolicyService, + type EnabledToolPolicyMatch, + type ToolAccessContext, +} from "../services/tool-access-policy.js"; +import { compilePolicySelector } from "../services/tool-access/policy-selector-index.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { createListingFixture } from "./helpers/tool-gateway-listing-fixture.js"; +import { stagingShapedToolPolicies } from "./helpers/tool-policy-index-fixture.js"; + +type PolicyRow = typeof toolPolicies.$inferSelect; + +/** The unindexed matching that decisions used before the policy index. */ +function unindexedMatch(policies: PolicyRow[], ctx: ToolAccessContext): EnabledToolPolicyMatch { + for (const policy of policies) { + const conditions = policyConditions(policy); + if (conditions && selectorMatches(policy.selectors, ctx)) { + const parsed = toolPolicyConditionsSchema.safeParse(conditions); + if (!parsed.success) { + return { + unsupportedConditions: { + policy, + issues: parsed.error.issues.map((issue) => ({ path: issue.path.join("."), message: issue.message })), + }, + }; + } + } + } + return { + matching: policies + .map((policy) => ({ policy, conditionEvaluation: evaluatePolicyConditions(policyConditions(policy), ctx) })) + .filter(({ policy, conditionEvaluation }) => selectorMatches(policy.selectors, ctx) && conditionEvaluation.matched), + }; +} + +function seeded(seed: number) { + let state = seed >>> 0; + const next = () => { + 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; + }; + const pick = (values: readonly T[]): T => values[Math.floor(next() * values.length)]!; + return { next, pick }; +} + +const ids = (count: number) => Array.from({ length: count }, () => randomUUID()); +const catalogIds = ids(30); +const connectionIds = ids(3); +const applicationIds = ids(2); +const agentIds = ids(3); +const projectIds = ids(2); +const toolNames = ["search", "deploy", "read_file", "write_file", "delete_repo", "list_issues"]; +const upstreamNames = ["upstream_search", "deploy", "upstream_delete", null]; +const riskLevels = ["read", "write", "destructive", "low", "high", null] as const; +const policyTypes = ["require_approval", "block", "trust_rule", "rate_limit", "allow", "redact"] as const; + +function policyRow(index: number, values: Partial): PolicyRow { + return { + id: randomUUID(), + companyId: "company", + name: `Policy ${index}`, + description: null, + policyType: "require_approval", + priority: 100, + enabled: true, + selectors: {}, + conditions: null, + config: null, + createdByAgentId: null, + createdByUserId: null, + createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)), + updatedAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)), + ...values, + }; +} + +function randomSelector(random: ReturnType): Record { + const { next, pick } = random; + const roll = next(); + if (roll < 0.35) return { catalogEntryId: pick(catalogIds) }; + if (roll < 0.45) return { catalogEntryId: pick(catalogIds), connectionId: pick(connectionIds) }; + if (roll < 0.5) { const id = pick(catalogIds); return { catalogEntryIds: [id, pick(catalogIds), id] }; } + if (roll < 0.53) return { catalogEntryIds: ` ${pick(catalogIds)} ` }; + if (roll < 0.56) return { catalogEntryId: "", toolName: pick(toolNames) }; + if (roll < 0.6) return { toolNames: [pick(toolNames), pick(upstreamNames.filter(Boolean))] }; + if (roll < 0.64) return { toolName: pick([...toolNames, "upstream_search"]), riskLevel: pick(riskLevels.filter(Boolean)) }; + if (roll < 0.67) return {}; + if (roll < 0.7) return { riskLevels: ["write", "destructive"] }; + if (roll < 0.73) return { actorType: "agent", agentIds: [pick(agentIds), pick(agentIds)] }; + if (roll < 0.75) return { catalogEntryId: 42, toolNames: [] }; + if (roll < 0.77) return { catalogEntryId: pick(catalogIds), catalogEntryIds: [pick(catalogIds)] }; + if (roll < 0.79) return { catalogEntryIds: ["", " ", pick(catalogIds)] }; + if (roll < 0.81) return { toolName: "", projectId: pick(projectIds) }; + // Several other keys, with no catalog entry or tool name. + const selector: Record = {}; + if (next() < 0.5) selector.agentId = pick(agentIds); + if (next() < 0.5) selector.applicationIds = [pick(applicationIds)]; + if (next() < 0.5) selector.connectionId = pick(connectionIds); + if (next() < 0.5) selector.projectIds = projectIds; + if (next() < 0.3) selector.providerType = pick(["mcp_remote_http", "paperclip_self"]); + if (next() < 0.3) selector.applicationKeys = "github"; + if (next() < 0.3) selector.gatewayId = "gateway-1"; + if (next() < 0.3) selector.issueIds = ["issue-1", "issue-2"]; + if (next() < 0.3) selector.routineId = "routine-1"; + return selector; +} + +function randomConditions(random: ReturnType): Record | null { + const { next, pick } = random; + if (next() < 0.75) return null; + return pick>([ + { risk: { isWrite: true } }, + { risk: { max: "read" } }, + { arguments: { fieldExists: ["query"] } }, + { arguments: { fieldEquals: { mode: "dry_run" } } }, + { context: { requireIssue: true } }, + { actor: { actorTypes: ["agent"] } }, + { trustBoundary: { remoteHttpOnly: true } }, + { timeWindow: { daysOfWeekUtc: [0, 1, 2, 3, 4, 5, 6] } }, + { timeWindow: { startAt: "2999-01-01T00:00:00Z" } }, + // Conditions the runtime cannot evaluate deny a selected call. + { unknownGroup: { enabled: true } }, + { arguments: { fieldEquals: {} } }, + ]); +} + +function randomPolicies(seed: number, count: number): PolicyRow[] { + const random = seeded(seed); + return Array.from({ length: count }, (_, index) => policyRow(index, { + // "redact" is a legacy type the runtime no longer supports. + policyType: random.pick(policyTypes) as PolicyRow["policyType"], + priority: random.pick([10, 50, 100, 100, 100, 200]), + selectors: randomSelector(random), + conditions: randomConditions(random), + })).sort((left, right) => left.priority - right.priority || left.createdAt.getTime() - right.createdAt.getTime()); +} + +function randomContext(random: ReturnType): ToolAccessContext { + const { next, pick } = random; + return { + companyId: "company", + actorType: pick(["agent", "agent", "user", "system"] as const), + actorId: "actor", + agentId: next() < 0.8 ? pick(agentIds) : null, + heartbeatRunId: null, + issueId: pick(["issue-1", "issue-3", null]), + projectId: next() < 0.7 ? pick(projectIds) : null, + routineId: pick(["routine-1", null]), + gatewayId: pick(["gateway-1", null]), + applicationId: pick([...applicationIds, null]), + connectionId: next() < 0.9 ? pick(connectionIds) : null, + // Some contexts name catalog entries that no policy selects, or none. + catalogEntryId: next() < 0.85 ? pick(catalogIds) : pick([randomUUID(), null, ""]), + catalogStatus: "active", + catalogVersionHash: null, + catalogSchemaHash: null, + providerType: pick(["mcp_remote_http", "paperclip_self", null]), + applicationKey: pick(["github", "linear", null]), + upstreamToolName: pick(upstreamNames), + toolName: pick([...toolNames, ""]), + riskLevel: pick(riskLevels), + argumentsHash: "hash", + arguments: pick([{}, { query: "x" }, { mode: "dry_run" }]), + }; +} + +function summary(match: EnabledToolPolicyMatch) { + if ("unsupportedConditions" in match) { + return { unsupported: match.unsupportedConditions.policy.id, issues: match.unsupportedConditions.issues }; + } + return { matching: match.matching.map(({ policy, conditionEvaluation }) => ({ id: policy.id, conditionEvaluation })) }; +} + +describe("tool policy index", () => { + it("compiles selectors that match exactly the contexts the raw selector matches", () => { + const random = seeded(7); + const selectors = [ + ...Array.from({ length: 400 }, () => randomSelector(random)), + { catalogEntryIds: " " }, + { toolName: 7, toolNames: "deploy" }, + { actorTypes: "agent" }, + { riskLevel: "" }, + ]; + let compared = 0; + for (let index = 0; index < 300; index += 1) { + const ctx = randomContext(random); + for (const selector of selectors) { + expect(compilePolicySelector(selector).matches(ctx)).toBe(selectorMatches(selector, ctx)); + compared += 1; + } + } + expect(compared).toBe(300 * selectors.length); + }); + + it("selects the same policies, in the same order, as unindexed matching", () => { + let unsupported = 0; + let matched = 0; + for (const seed of [1, 2, 3, 4, 5]) { + const policies = randomPolicies(seed, 400); + const index = indexEnabledToolPolicies(policies); + const random = seeded(seed * 101); + for (let call = 0; call < 400; call += 1) { + const ctx = randomContext(random); + const expected = summary(unindexedMatch(policies, ctx)); + // A reused index must give the same answer as a fresh one. + expect(summary(matchEnabledToolPolicies(index, ctx))).toEqual(expected); + expect(summary(matchEnabledToolPolicies(indexEnabledToolPolicies(policies), ctx))).toEqual(expected); + if ("unsupported" in expected) unsupported += 1; + else if (expected.matching.length > 0) matched += 1; + } + } + // The generated cases exercise both outcomes. + expect(unsupported).toBeGreaterThan(50); + expect(matched).toBeGreaterThan(250); + }); + + it("selects the same policies as unindexed matching for a staging-shaped set", () => { + const random = seeded(11); + const catalogEntries = Array.from({ length: 800 }, (_, index) => ({ + id: randomUUID(), connectionId: connectionIds[index % connectionIds.length]!, toolName: `tool_${index}`, + })); + const policies = stagingShapedToolPolicies({ + catalogEntries, agentId: agentIds[0]!, projectId: projectIds[0]!, applicationId: applicationIds[0]!, connectionId: connectionIds[0]!, + }).map((values, position) => policyRow(position, { + ...values, priority: values.priority ?? 100, selectors: values.selectors ?? {}, conditions: values.conditions ?? null, config: values.config ?? null, + })).sort((left, right) => left.priority - right.priority || left.createdAt.getTime() - right.createdAt.getTime()); + const index = indexEnabledToolPolicies(policies); + let matched = 0; + for (const [position, entry] of catalogEntries.entries()) { + const ctx: ToolAccessContext = { + ...randomContext(random), + agentId: agentIds[0]!, projectId: projectIds[0]!, applicationId: applicationIds[0]!, + connectionId: entry.connectionId, catalogEntryId: entry.id, toolName: entry.toolName, + upstreamToolName: position % 2 === 0 ? entry.toolName : null, + }; + const expected = summary(unindexedMatch(policies, ctx)); + expect(summary(matchEnabledToolPolicies(index, ctx))).toEqual(expected); + if ((expected.matching?.length ?? 0) > 0) matched += 1; + } + expect(matched).toBeGreaterThan(300); + }); + + it("applies an earlier policy from another index bucket before a catalog-entry policy", () => { + const catalogEntryId = randomUUID(); + const otherCatalogEntryId = randomUUID(); + const policies = [ + // No catalog entry: indexed by tool name, matched through the upstream name. + policyRow(0, { priority: 5, policyType: "require_approval", selectors: { toolNames: ["upstream_deploy"] } }), + // Neither key: a candidate for every call. + policyRow(1, { priority: 6, policyType: "trust_rule", selectors: { riskLevel: "write" } }), + // An empty catalog entry selector does not constrain the call. + policyRow(2, { priority: 7, policyType: "allow", selectors: { catalogEntryId: "", toolName: "deploy" } }), + policyRow(3, { priority: 10, policyType: "block", selectors: { catalogEntryId } }), + policyRow(4, { priority: 20, policyType: "require_approval", selectors: { catalogEntryIds: [otherCatalogEntryId, catalogEntryId] } }), + policyRow(5, { priority: 30, policyType: "block", selectors: { catalogEntryId: otherCatalogEntryId } }), + ]; + const ctx: ToolAccessContext = { + ...randomContext(seeded(3)), + catalogEntryId, toolName: "deploy", upstreamToolName: "upstream_deploy", riskLevel: "write", + }; + const match = matchEnabledToolPolicies(indexEnabledToolPolicies(policies), ctx); + expect(summary(match)).toEqual(summary(unindexedMatch(policies, ctx))); + expect("matching" in match && match.matching.map(({ policy }) => policy.name)) + .toEqual(["Policy 0", "Policy 1", "Policy 2", "Policy 3", "Policy 4"]); + + // A selected policy with unsupported conditions denies the call even when + // a catalog-entry policy sits earlier in a different bucket. + const unsupported = [ + policyRow(0, { priority: 1, selectors: { catalogEntryId } }), + policyRow(1, { priority: 2, selectors: { toolName: "deploy" }, conditions: { unknownGroup: true } }), + ]; + expect(matchEnabledToolPolicies(indexEnabledToolPolicies(unsupported), ctx)).toMatchObject({ + unsupportedConditions: { policy: { name: "Policy 1" } }, + }); + }); +}); + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +type Db = ReturnType; + +/** A db handle whose tool_policies rows count every read of their selectors. */ +function countingPolicySelectorReads(db: Db) { + const counter = { reads: 0 }; + const counted = new Proxy(db, { + get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields); + const from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args); + if (args[0] !== toolPolicies) return selection; + const execute = selection.execute.bind(selection); + selection.execute = (async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs) as PolicyRow[]; + return rows.map((row) => ({ + ...row, + selectors: new Proxy(row.selectors, { + get(selector, property, receiver) { + counter.reads += 1; + return Reflect.get(selector, property, receiver); + }, + ownKeys(selector) { + counter.reads += 1; + return Reflect.ownKeys(selector); + }, + }), + })); + }) as typeof execute; + return selection; + }) as typeof builder.from; + return builder; + }; + }, + }); + return { db: counted, counter }; +} + +describeEmbeddedPostgres("tool policy index decisions", () => { + let db!: Db; + let tempDb: Awaited> | null = null; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-policy-index-"); + db = createDb(tempDb.connectionString); + }, 20_000); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + function decisionInput( + fixture: Awaited>, + entry: Awaited>["entries"][number], + ): ToolAccessDecisionInput { + return { + companyId: fixture.company.id, + actor: { actorType: "agent", actorId: fixture.agent.id, agentId: fixture.agent.id }, + runContext: { heartbeatRunId: fixture.run.id, issueId: fixture.issue.id, projectId: fixture.project.id, gatewayId: fixture.namedGateway.id }, + request: { + toolName: entry.toolName!, applicationId: fixture.application.id, connectionId: fixture.connection.id, + catalogEntryId: entry.id, upstreamToolName: entry.toolName!, riskLevel: entry.riskLevel, arguments: { query: "status" }, + }, + consumeRateLimit: false, + }; + } + + it("reads policy selectors once per decision batch, however many tools it decides", async () => { + const fixture = await createListingFixture(db, 40); + await db.insert(toolPolicies).values(stagingShapedToolPolicies({ + catalogEntries: Array.from({ length: 800 }, (_, index) => fixture.entries[index] ?? { id: randomUUID(), connectionId: null, toolName: null }), + agentId: fixture.agent.id, + projectId: fixture.project.id, + applicationId: fixture.application.id, + connectionId: fixture.connection.id, + }).map((values) => ({ ...values, companyId: fixture.company.id }))); + const { db: counted, counter } = countingPolicySelectorReads(db); + const policy = toolAccessPolicyService(counted); + const cache = createToolAccessDecisionCache(); + + const first = await policy.decide(decisionInput(fixture, fixture.entries[0]!), { cache }); + const readsForOneTool = counter.reads; + const rest = []; + for (const entry of fixture.entries.slice(1)) rest.push(await policy.decide(decisionInput(fixture, entry), { cache })); + + expect(readsForOneTool).toBeGreaterThan(0); + expect(counter.reads).toBe(readsForOneTool); + const uncached = toolAccessPolicyService(db); + const expected = []; + for (const entry of fixture.entries) expected.push(await uncached.decide(decisionInput(fixture, entry))); + expect([first, ...rest]).toEqual(expected); + expect(new Set(expected.map((decision) => decision.reasonCode))).toEqual(new Set([ + "allow_profile", "deny_default", "deny_policy_block", "requires_approval_policy", + ])); + }, 30_000); + + it("lets an earlier tool-name policy decide before a catalog-entry block", async () => { + const fixture = await createListingFixture(db, 6); + const [blocked, written] = [fixture.entries[2]!, fixture.entries[3]!]; + // The fixture blocks entries[2] at priority 10 and asks first for writes at 20. + const [byToolName] = await db.insert(toolPolicies).values({ + companyId: fixture.company.id, + name: `Ask first by tool name ${randomUUID()}`, + description: "Ask before this action.", + policyType: "require_approval", + priority: 5, + selectors: { toolNames: [blocked.toolName!] }, + }).returning(); + const policy = toolAccessPolicyService(db); + for (const cache of [undefined, createToolAccessDecisionCache()]) { + const blockedDecision = await policy.decide(decisionInput(fixture, blocked), { cache }); + expect(blockedDecision).toMatchObject({ + decision: "require_approval", + reasonCode: "requires_approval_policy", + explanation: "Ask before this action.", + matchedPolicyIds: [byToolName!.id], + policyExplanation: { policyId: byToolName!.id, selectorMatched: true, conditionsMatched: [] }, + }); + const writeDecision = await policy.decide(decisionInput(fixture, written), { cache }); + expect(writeDecision).toMatchObject({ decision: "require_approval", reasonCode: "requires_approval_policy" }); + expect(writeDecision.matchedPolicyIds).not.toContain(byToolName!.id); + } + }, 30_000); +}); diff --git a/server/src/index.ts b/server/src/index.ts index 8da56303243..af3393d0076 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -131,6 +131,7 @@ import { closeLivenessDb, closeCheckpointDb, closeFileStorageDb, + closeDedicatedDbConnections, } from "@paperclipai/db"; import detectPort from "detect-port"; import { createApp } from "./app.js"; @@ -752,7 +753,7 @@ async function startServerWithDatabaseTeardown( const closeDatabaseClients = async () => { setSentryRunLinkResolver(null); const clients = pluginMigrationDb === db ? [db] : [db, pluginMigrationDb]; - await Promise.all([...clients.map((client) => endDatabaseClient(client, 5)), closeLivenessDb(db, 5), closeCheckpointDb(db, 5), closeFileStorageDb(db, 5)]); + await Promise.all([...clients.map((client) => endDatabaseClient(client, 5)), closeLivenessDb(db, 5), closeCheckpointDb(db, 5), closeFileStorageDb(db, 5), closeDedicatedDbConnections(db, 5)]); }; startupDatabase.close = closeDatabaseClients; startupTimeline.mark("database"); diff --git a/server/src/services/chat-channels/discord/command-work.test.ts b/server/src/services/chat-channels/discord/command-work.test.ts new file mode 100644 index 00000000000..510faae31f3 --- /dev/null +++ b/server/src/services/chat-channels/discord/command-work.test.ts @@ -0,0 +1,173 @@ +import { createDb } from "@paperclipai/db"; +import { reconcileDatabaseWorkNotifications } from "@paperclipai/db/work-signals"; +import { describe, expect, it, vi } from "vitest"; +import { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; +import { isIdleTaskDrainActive, readTaskDrain, startTaskDrain, stopTaskDrain } from "../../task-admission.js"; +import { registerDiscordCommandWork } from "./command-work.js"; +import type { CommandRegistrationDeadline } from "./command-schedule.js"; + +async function fixture(options: { drain?: boolean; ttlMs?: number; empty?: boolean; failChecks?: number } = {}) { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + vi.setSystemTime(new Date("2026-11-14T00:00:00Z")); + if (options.drain) startTaskDrain({ purpose: "idle", ttlMs: options.ttlMs }); + const owner = createDb("postgres://paperclip:unused@127.0.0.1:1/unused", { maxConnections: 1 }); + let allowed = true; + const canRun = vi.fn(() => allowed && !isIdleTaskDrainActive()); + const entry: CommandRegistrationDeadline = { id: "endpoint-1", companyId: "company-1", connectionId: "connection-1", dueAt: Date.now() }; + let entries: CommandRegistrationDeadline[] = options.empty ? [] : [entry]; + const load = vi.fn(async () => entries); + let remainingFailures = options.failChecks ?? 0; + const check = vi.fn(async () => { + if (remainingFailures-- > 0) throw new Error("Provider attempt failed"); + entries = []; + return null; + }); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner, canRun, canReconcile: () => true, onError: error => errors.push(error) }); + const worker = registerDiscordCommandWork(coordinator, { load, check }, canRun); + await worker.ready; + return { owner, coordinator, worker, canRun, load, check, errors, entry, + allow(value: boolean) { allowed = value; }, + owe() { entries = [entry]; }, + async close() { + try { await coordinator.stop(); } + finally { + try { await owner.$client.end({ timeout: 1 }); } + finally { stopTaskDrain(); vi.useRealTimers(); } + } + }, + }; +} + +describe("Discord command registration admission drain", () => { + it("reconciles a retained due registration on release before the coordinator fallback", async () => { + const f = await fixture({ drain: true }); + try { + expect(f.load).not.toHaveBeenCalled(); + const fallback = f.coordinator.nextWakeAt(); + expect(fallback).toBeGreaterThan(Date.now()); + expect(fallback).toBeLessThanOrEqual(Date.now() + 30_000); + await vi.advanceTimersByTimeAsync(1_000); + stopTaskDrain(); + await vi.advanceTimersByTimeAsync(10); + expect(Date.now()).toBeLessThan(fallback!); + expect(f.check.mock.calls).toEqual([["endpoint-1", expect.any(AbortSignal)]]); + expect(f.load).toHaveBeenCalledOnce(); + expect(f.coordinator.nextWakeAt()).toBeNull(); + await vi.advanceTimersByTimeAsync(120_000); + expect(f.check).toHaveBeenCalledOnce(); + expect(f.load).toHaveBeenCalledOnce(); + expect(f.errors).toEqual([]); + } finally { await f.close(); } + }); + + it("reconciles a retained due registration on observed expiry before the coordinator fallback", async () => { + const f = await fixture({ drain: true, ttlMs: 1_000 }); + try { + const fallback = f.coordinator.nextWakeAt(); + expect(fallback).toBeGreaterThan(Date.now()); + expect(fallback).toBeLessThanOrEqual(Date.now() + 30_000); + await vi.advanceTimersByTimeAsync(1_001); + expect(readTaskDrain(new Date())).toBeNull(); + await vi.advanceTimersByTimeAsync(10); + expect(Date.now()).toBeLessThan(fallback!); + expect(f.check.mock.calls).toEqual([["endpoint-1", expect.any(AbortSignal)]]); + expect(f.load).toHaveBeenCalledOnce(); + expect(f.coordinator.nextWakeAt()).toBeNull(); + expect(f.errors).toEqual([]); + } finally { await f.close(); } + }); + + it("does not refresh a due registration while another admission gate remains closed", async () => { + const f = await fixture({ drain: true }); + try { + f.allow(false); + stopTaskDrain(); + await vi.advanceTimersByTimeAsync(1_000); + expect(f.load).not.toHaveBeenCalled(); + expect(f.check).not.toHaveBeenCalled(); + expect(f.errors).toEqual([]); + } finally { await f.close(); } + }); + + it("keeps a retained hint behind its future earliest deadline on release", async () => { + const f = await fixture({ empty: true }); + try { + expect(f.load).toHaveBeenCalledOnce(); + f.owe(); + startTaskDrain({ purpose: "idle" }); + reconcileDatabaseWorkNotifications(f.owner); + await vi.advanceTimersByTimeAsync(1_000); + const earliest = f.coordinator.nextWakeAt(); + expect(earliest).toBeGreaterThan(Date.now()); + stopTaskDrain(); + await vi.advanceTimersByTimeAsync(10); + expect(f.load).toHaveBeenCalledOnce(); + expect(f.check).not.toHaveBeenCalled(); + expect(f.coordinator.nextWakeAt()).toBe(earliest); + await vi.advanceTimersByTimeAsync(earliest! - Date.now()); + expect(f.check).toHaveBeenCalledOnce(); + expect(f.coordinator.nextWakeAt()).toBeNull(); + expect(f.errors).toEqual([]); + } finally { await f.close(); } + }); + + it("preserves per-item exponential failure backoff across release", async () => { + const f = await fixture({ failChecks: 2 }); + try { + expect(f.check).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(30_000); + expect(f.check).toHaveBeenCalledTimes(2); + const retryAt = Date.now() + 60_000; + expect(f.coordinator.nextWakeAt()).toBeGreaterThan(Date.now()); + startTaskDrain({ purpose: "idle" }); + await vi.advanceTimersByTimeAsync(1_000); + stopTaskDrain(); + await vi.advanceTimersByTimeAsync(10); + expect(f.check).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(retryAt - Date.now() - 1); + expect(f.check).toHaveBeenCalledTimes(2); + expect(f.coordinator.nextWakeAt()).toBe(retryAt); + await vi.advanceTimersByTimeAsync(1); + expect(f.check).toHaveBeenCalledTimes(3); + expect(f.errors).toHaveLength(2); + expect(f.coordinator.nextWakeAt()).toBeNull(); + } finally { await f.close(); } + }); + + it("does not scan an empty owner or retain recurring work after release and expiry", async () => { + const f = await fixture({ empty: true }); + try { + expect(f.coordinator.nextWakeAt()).toBeNull(); + startTaskDrain({ purpose: "idle" }); + stopTaskDrain(); + startTaskDrain({ purpose: "idle", ttlMs: 1_000 }); + await vi.advanceTimersByTimeAsync(1_001); + expect(readTaskDrain(new Date())).toBeNull(); + await vi.advanceTimersByTimeAsync(120_000); + expect(f.load).toHaveBeenCalledOnce(); + expect(f.check).not.toHaveBeenCalled(); + expect(f.coordinator.nextWakeAt()).toBeNull(); + expect(f.errors).toEqual([]); + } finally { await f.close(); } + }); + + it.each(["worker", "coordinator"] as const)("unsubscribes release and expiry refresh after %s stop", async mode => { + const f = await fixture({ drain: true }); + try { + if (mode === "worker") await f.worker.stop(); + else await f.coordinator.stop(); + f.canRun.mockClear(); + stopTaskDrain(); + startTaskDrain({ purpose: "idle", ttlMs: 1_000 }); + await vi.advanceTimersByTimeAsync(1_001); + expect(readTaskDrain(new Date())).toBeNull(); + await vi.advanceTimersByTimeAsync(120_000); + expect(f.canRun).not.toHaveBeenCalled(); + expect(f.load).not.toHaveBeenCalled(); + expect(f.check).not.toHaveBeenCalled(); + expect(f.coordinator.nextWakeAt()).toBeNull(); + expect(f.errors).toEqual([]); + } finally { await f.close(); } + }); +}); diff --git a/server/src/services/chat-channels/discord/command-work.ts b/server/src/services/chat-channels/discord/command-work.ts index af826d9cf1b..7a169961295 100644 --- a/server/src/services/chat-channels/discord/command-work.ts +++ b/server/src/services/chat-channels/discord/command-work.ts @@ -1,3 +1,4 @@ +import { subscribeTaskDrainChanges, subscribeTaskDrainExpiry } from "../../task-admission.js"; import { takeCompanyWorkBatch } from "../../company-work-batch.js"; import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js"; @@ -37,9 +38,11 @@ export function registerDiscordCommandWork( } return at; } - return coordinator.register(DELIVERY_QUEUES.chatCommandRegistration, { + let unsubscribeRefresh: (() => void) | undefined; + const worker = coordinator.register(DELIVERY_QUEUES.chatCommandRegistration, { retryMs, pausePassiveMaintenance: true, + onStop: () => { unsubscribeRefresh?.(); unsubscribeRefresh = undefined; }, onSettled: hints => { for (const hint of hints ?? ["*"]) dirty.add(hint); }, run: async signal => { if (!canRun() || Date.now() < earliest) return; @@ -93,4 +96,12 @@ export function registerDiscordCommandWork( hasPending: async () => canRun() && dirty.size > 0, nextRunAt: next, }); + const refresh = () => { + if (!canRun()) return; + const at = next(); + if (at !== null && at <= Date.now()) worker.wake(); + }; + const unsubscribe = [subscribeTaskDrainChanges(refresh), subscribeTaskDrainExpiry(refresh)]; + unsubscribeRefresh = () => { for (const stop of unsubscribe) stop(); }; + return worker; } diff --git a/server/src/services/fresh-continuation-fallback.ts b/server/src/services/fresh-continuation-fallback.ts index f8ad3bb99d0..4dce0254bb3 100644 --- a/server/src/services/fresh-continuation-fallback.ts +++ b/server/src/services/fresh-continuation-fallback.ts @@ -28,6 +28,7 @@ import { readRunCancellation } from "./run-cancellation.js"; import { readSystemRecovery } from "./system-recovery-state.js"; import { RESTART_CLASS_FAILURE_CODES, continuationCauseIsSystemOwned, continuationCauseIsSystemOwnedSql, continuesAutomaticallySql, isPersonOwnedFailureCode, recoveryRunSql } from "./continuation-cause.js"; import { sharedContinuationAttempts } from "./recovery/continuation-ledger.js"; +import { canonicalExecutionUuid } from "./execution-identity.js"; export { AUTOMATIC_CONTINUATION_WAKE_REASONS, PERSON_OWNED_FAILURE_CODES, isPersonOwnedFailureCode, isRecoveryRun } from "./continuation-cause.js"; @@ -772,7 +773,7 @@ export function heldExecutionsAwaitingFreshContinuation(db: Db, now: Date, limit .where(and(heldExecutionWhere(), freshContinuationCheckDue(now), recentInterruptionSourceSql(now))) // Newest interruption first: the most recent work is the work someone is waiting for. .orderBy(desc(sql`(select source.finished_at from ${heartbeatRuns} source where source.company_id = ${issueRecoveryActions.companyId} - and source.id::text = coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId'))`), + and source.id = ${sourceRunKey(heldRunIdSql())})`), asc(issueRecoveryActions.id)) .limit(limit); } @@ -799,13 +800,15 @@ function liveDispositionHoldSql() { const cancelledAtDispatch = (alias: "newer" | "held") => sql.raw(`coalesce(${alias}.status = 'cancelled' and ${alias}.started_at is null and ${alias}.error_code = 'execution_reconciliation_required', false)`); -const runOfTask = (alias: "newer" | "held", issueId: SQL) => sql`(${sql.raw(alias)}.native_issue_id::text = ${issueId}::text - or ${sql.raw(alias)}.issue_id::text = ${issueId}::text or ${sql.raw(alias)}.context_snapshot->>'issueId' = ${issueId}::text)`; +// The issue id is a uuid (a column or a task's id), so each link is compared on +// its own indexed column; a cast of the column would scan every run's context. +const runOfTask = (alias: "newer" | "held", issueId: SQL) => sql`(${sql.raw(alias)}.native_issue_id = ${issueId}::uuid + or ${sql.raw(alias)}.issue_id = ${issueId}::uuid or ${sql.raw(alias)}.context_snapshot->>'issueId' = ${issueId}::text)`; function interruptionEligibility(input: { now: Date; companyId: SQL; issueId: SQL; sourceRunId: SQL }) { const since = sql`${new Date(input.now.getTime() - BACKLOG_CONTINUATION_MAX_AGE_MS).toISOString()}::timestamptz`; const source = (condition: SQL) => sql`exists (select 1 from ${heartbeatRuns} source where source.company_id = ${input.companyId} - and source.id::text = ${input.sourceRunId}::text and ${condition})`; + and source.id = ${sourceRunKey(input.sourceRunId)} and ${condition})`; const refusedLater = sql`held.company_id = source.company_id and held.id <> source.id and ${runOfTask("held", input.issueId)} and (held.created_at, held.id) > (source.created_at, source.id) and ${cancelledAtDispatch("held")}`; const personAsked = source(sql`(exists (select 1 from ${agentWakeupRequests} retry where retry.company_id = source.company_id @@ -822,10 +825,10 @@ function interruptionEligibility(input: { now: Date; companyId: SQL; issueId: SQ } /** The backlog pass's eligibility: the one predicate its listing and its deadline query share. */ -function recentInterruptionSourceSql(now: Date) { +export function recentInterruptionSourceSql(now: Date) { const { recent, personAsked } = interruptionEligibility({ now, companyId: sql`${issueRecoveryActions.companyId}`, issueId: sql`${issueRecoveryActions.sourceIssueId}`, - sourceRunId: sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId')` }); + sourceRunId: heldRunIdSql() }); return sql`(${recent} or ${personAsked})`; } @@ -847,7 +850,7 @@ let lastLeftAloneLogAt = 0; const LEFT_ALONE_LOG_INTERVAL_MS = 10 * 60_000; /** Held reconciliation records of a task's latest unfinished run (joined to its task). */ -function heldExecutionWhere(options: { includeActive?: boolean } = {}) { +export function heldExecutionWhere(options: { includeActive?: boolean } = {}) { return and( inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), sql`${issueRecoveryActions.evidence}->'executionReconciliation' is null`, @@ -868,7 +871,7 @@ function heldExecutionWhere(options: { includeActive?: boolean } = {}) { sql`${issues.assigneeAgentId} is not null`, // Only the task's latest run, unfinished and still its assignee's: other sql`exists (select 1 from ${heartbeatRuns} source where source.company_id = ${issueRecoveryActions.companyId} - and source.id::text = coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') + and source.id = ${sourceRunKey(heldRunIdSql())} and source.status in ('failed', 'timed_out', 'interrupted', 'cancelled') and source.finished_at is not null and source.agent_id = ${issues.assigneeAgentId} and not exists (select 1 from ${heartbeatRuns} newer where newer.company_id = source.company_id and newer.id <> source.id @@ -878,6 +881,10 @@ function heldExecutionWhere(options: { includeActive?: boolean } = {}) { )!; } +const heldRunIdSql = () => sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId')`; +/** The recorded run id as the run's key: the same match as `id::text = text`, but an index lookup. */ +const sourceRunKey = (runId: SQL) => canonicalExecutionUuid(sql`(${runId})::text`); + /** The earliest time a deferred check becomes due again, if any. */ export async function nextFreshContinuationCheckAt(db: Db, now = new Date()): Promise { // The same records the held-run query and the disposition pass would select; diff --git a/server/src/services/fresh-continuation-schedule-queries.test.ts b/server/src/services/fresh-continuation-schedule-queries.test.ts new file mode 100644 index 00000000000..0b894b8c060 --- /dev/null +++ b/server/src/services/fresh-continuation-schedule-queries.test.ts @@ -0,0 +1,269 @@ +import { randomUUID } from "node:crypto"; +import { and, asc, desc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agentWakeupRequests, agents, companies, createDb, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db"; +import { EXECUTION_RECONCILIATION_CAUSES } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { BACKLOG_CONTINUATION_MAX_AGE_MS, freshContinuationCheckDue, heldExecutionWhere, heldExecutionsAwaitingFreshContinuation, + nextFreshContinuationCheckAt, recentInterruptionSourceSql } from "./fresh-continuation-fallback.js"; +import { continuationCauseIsSystemOwnedSql, continuesAutomaticallySql, recoveryRunSql } from "./continuation-cause.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; + +// The predicates as they were before they became index lookups (2026-11-14): +// `id::text = text` on the run key and cast issue columns, one OR scan per +// newer-run probe. Kept verbatim as the oracle the rewrite must match. +const previousCancelledAtDispatch = (alias: "newer" | "held") => sql.raw(`coalesce(${alias}.status = 'cancelled' and ${alias}.started_at is null + and ${alias}.error_code = 'execution_reconciliation_required', false)`); +const previousRunOfTask = (alias: "newer" | "held", issueId: SQL) => sql`(${sql.raw(alias)}.native_issue_id::text = ${issueId}::text + or ${sql.raw(alias)}.issue_id::text = ${issueId}::text or ${sql.raw(alias)}.context_snapshot->>'issueId' = ${issueId}::text)`; + +function previousRecentInterruptionSourceSql(now: Date) { + const input = { companyId: sql`${issueRecoveryActions.companyId}`, issueId: sql`${issueRecoveryActions.sourceIssueId}`, + sourceRunId: sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId')` }; + const since = sql`${new Date(now.getTime() - BACKLOG_CONTINUATION_MAX_AGE_MS).toISOString()}::timestamptz`; + const source = (condition: SQL) => sql`exists (select 1 from ${heartbeatRuns} source where source.company_id = ${input.companyId} + and source.id::text = ${input.sourceRunId}::text and ${condition})`; + const refusedLater = sql`held.company_id = source.company_id and held.id <> source.id and ${previousRunOfTask("held", input.issueId)} + and (held.created_at, held.id) > (source.created_at, source.id) and ${previousCancelledAtDispatch("held")}`; + const personAsked = source(sql`(exists (select 1 from ${agentWakeupRequests} retry where retry.company_id = source.company_id + and retry.status = 'deferred_issue_execution' and retry.reason = 'task_retry' and retry.requested_by_actor_type = 'user' + and retry.run_id is null and retry.payload->>'issueId' = ${input.issueId}::text and retry.requested_at > source.finished_at) + or exists (select 1 from ${heartbeatRuns} held where ${refusedLater} + and held.context_snapshot->>'wakeReason' = 'task_retry' and held.finished_at > ${since}))`); + const systemRetriedSource = sql`(${continuationCauseIsSystemOwnedSql("source")} + and coalesce(source.context_snapshot->>'wakeReason', '') <> 'task_retry' and not coalesce(source.context_snapshot ? 'explicitUserContinuation', false) + and exists (select 1 from ${heartbeatRuns} held where ${refusedLater} and ${recoveryRunSql("held")}))`; + const recent = source(sql`(${continuesAutomaticallySql("source")} or ${systemRetriedSource}) + and greatest(source.finished_at, (select max(held.finished_at) from ${heartbeatRuns} held where ${refusedLater})) > ${since}`); + return sql`(${recent} or ${personAsked})`; +} + +function previousHeldExecutionWhere(options: { includeActive?: boolean } = {}) { + return and( + inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), + sql`${issueRecoveryActions.evidence}->'executionReconciliation' is null`, + sql`${issueRecoveryActions.evidence}->'freshContinuation' is null`, + sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') is not null`, + or( + sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, + and(inArray(issueRecoveryActions.status, ["active", "escalated"]), + sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('complete', 'exhausted')`), + options.includeActive ? and(inArray(issueRecoveryActions.status, ["active", "escalated"]), + eq(issueRecoveryActions.kind, "active_run_watchdog")) : undefined, + sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('scheduled', 'running', 'awaiting_evidence')`, + ), + isNull(issueRecoveryActions.ownerUserId), + sql`${issues.status} not in ('done', 'cancelled')`, + sql`${issues.assigneeAgentId} is not null`, + sql`exists (select 1 from ${heartbeatRuns} source where source.company_id = ${issueRecoveryActions.companyId} + and source.id::text = coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') + and source.status in ('failed', 'timed_out', 'interrupted', 'cancelled') and source.finished_at is not null + and source.agent_id = ${issues.assigneeAgentId} + and not exists (select 1 from ${heartbeatRuns} newer where newer.company_id = source.company_id and newer.id <> source.id + and (newer.native_issue_id = ${issues.id} or newer.issue_id = ${issues.id} or newer.context_snapshot->>'issueId' = ${issues.id}::text) + and not ${previousCancelledAtDispatch("newer")} + and (newer.status in ('queued', 'running', 'scheduled_retry') or (newer.created_at, newer.id) > (source.created_at, source.id))))`, + )!; +} + +function random(seed: number) { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let value = state; + value = Math.imul(value ^ (value >>> 15), value | 1); + value ^= value + Math.imul(value ^ (value >>> 7), value | 61); + return ((value ^ (value >>> 14)) >>> 0) / 4294967296; + }; +} + +type PlanNode = { "Relation Name"?: string; "Actual Loops"?: number; "Actual Rows"?: number; + "Rows Removed by Filter"?: number; "Rows Removed by Index Recheck"?: number; Plans?: PlanNode[] }; + +function heartbeatRunRowsRead(node: PlanNode): number { + const own = node["Relation Name"] === "heartbeat_runs" ? (node["Actual Loops"] ?? 0) + * ((node["Actual Rows"] ?? 0) + (node["Rows Removed by Filter"] ?? 0) + (node["Rows Removed by Index Recheck"] ?? 0)) : 0; + return own + (node.Plans ?? []).reduce((total, child) => total + heartbeatRunRowsRead(child), 0); +} + +suite("fresh-continuation schedule queries", () => { + let db!: ReturnType; + let temporary: Awaited> | null = null; + const now = new Date(Date.UTC(2026, 10, 14, 5, 0, 0)); + const tenants: Array<{ companyId: string; agentIds: string[] }> = []; + let actions = 0; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-fresh-continuation-schedule-"); + db = createDb(temporary.connectionString); + for (const prefix of ["FCA", "FCB"]) { + const companyId = randomUUID(), agentIds = [randomUUID(), randomUUID()]; + await db.insert(companies).values({ id: companyId, name: prefix, issuePrefix: prefix, requireBoardApprovalForNewAgents: false }); + await db.insert(agents).values(agentIds.map((id, index) => ({ id, companyId, name: `Coder ${index}`, role: "engineer", + status: "idle", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} }))); + tenants.push({ companyId, agentIds }); + } + actions = await seedVariedFixture(20261114, 900); + // Run history that is not linked to any held task, so a scan per candidate shows. + await db.$client.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, context_snapshot, created_at) + select $1::uuid, $2::uuid, 'succeeded', jsonb_build_object('issueId', gen_random_uuid()::text, 'prompt', repeat('x', 4000)), + $3::timestamptz - (n || ' minutes')::interval from generate_series(1, 3000) n`, + [tenants[0]!.companyId, tenants[0]!.agentIds[0]!, now.toISOString()]); + await db.execute(sql`analyze`); + }, 120_000); + + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + /** Held tasks in every shape the predicates distinguish: run keys, run links, statuses, ages, retries. */ + async function seedVariedFixture(seed: number, count: number) { + const next = random(seed); + const pick = (values: readonly T[]): T => values[Math.floor(next() * values.length)]!; + const chance = (probability: number) => next() < probability; + const at = (minutesAgo: number) => new Date(now.getTime() - minutesAgo * 60_000); + const issueRows: Array = []; + const runRows: Array = []; + const wakeRows: Array = []; + const actionRows: Array = []; + const link = (issueId: string, kind: string) => kind === "native" ? { scopeKind: "issue" as const, issueId, nativeIssueId: issueId } + : kind === "issue" ? { scopeKind: "issue" as const, issueId } : kind === "context" ? { scopeKind: "company" as const } + : { scopeKind: "company" as const }; + for (let index = 0; index < count; index += 1) { + const tenant = chance(0.9) ? tenants[0]! : tenants[1]!; + const other = tenant === tenants[0] ? tenants[1]! : tenants[0]!; + const issueId = randomUUID(), runId = randomUUID(); + const assignee = chance(0.9) ? pick(tenant.agentIds) : null; + issueRows.push({ id: issueId, companyId: tenant.companyId, title: `Held ${index}`, assigneeAgentId: assignee, + status: pick(["todo", "in_progress", "blocked", "blocked", "in_review", "done", "cancelled"]) }); + const finishedMinutesAgo = pick([30, 120, 600, 1_200, 1_430, 1_450, 2_000, 4_000]); + const sourceLink = pick(["native", "issue", "context"]); + const errorCode = pick(["process_lost", "native_session_interrupted", "server_shutdown_interrupted", "controller_lease_lost", + "adapter_failed", "reusable_sandbox_resume_failed", "budget_exceeded", null]); + const sourceCreated = chance(0.92); + if (sourceCreated) { + const finished = chance(0.92) ? at(finishedMinutesAgo) : null; + runRows.push({ id: runId, companyId: chance(0.95) ? tenant.companyId : other.companyId, + agentId: chance(0.85) && assignee ? assignee : pick(tenant.agentIds), ...link(issueId, sourceLink), + status: pick(["failed", "failed", "timed_out", "interrupted", "cancelled", "succeeded", "running"]), + errorCode, error: errorCode === "reusable_sandbox_resume_failed" ? pick(["resume failed (cause=transport_timeout)", "resume failed"]) : errorCode, + startedAt: at(finishedMinutesAgo + 10), finishedAt: finished, createdAt: at(finishedMinutesAgo + 11), updatedAt: at(finishedMinutesAgo), + retryOfRunId: null, scheduledRetryReason: chance(0.1) ? "process_lost" : null, + contextSnapshot: { issueId, wakeReason: pick(["issue_assigned", "task_retry", "process_lost_retry"]), + ...(chance(0.1) ? { explicitUserContinuation: { runId } } : {}), ...(chance(0.1) ? { previousRunId: randomUUID() } : {}) } }); + } + for (let extra = Math.floor(next() * 3); extra > 0; extra -= 1) { + const extraLink = pick(["native", "issue", "context", "unrelated"]); + const cancelledAtDispatch = chance(0.35); + const createdMinutesAgo = pick([finishedMinutesAgo + 11, finishedMinutesAgo + 30, finishedMinutesAgo - 5, 5]); + runRows.push({ companyId: chance(0.95) ? tenant.companyId : other.companyId, agentId: pick(tenant.agentIds), + ...link(issueId, extraLink), + status: cancelledAtDispatch ? "cancelled" : pick(["queued", "running", "scheduled_retry", "succeeded", "failed", "cancelled"]), + errorCode: cancelledAtDispatch ? "execution_reconciliation_required" : null, + startedAt: cancelledAtDispatch && chance(0.8) ? null : at(createdMinutesAgo - 1), + finishedAt: chance(0.8) ? at(pick([createdMinutesAgo - 2, 60, 2_000])) : null, createdAt: at(createdMinutesAgo), + retryOfRunId: sourceCreated && chance(0.3) ? runId : null, + contextSnapshot: extraLink === "unrelated" ? { issueId: randomUUID() } + : { issueId, wakeReason: pick(["task_retry", "issue_assigned", "process_lost_retry"]) } }); + } + if (chance(0.25)) { + wakeRows.push({ companyId: tenant.companyId, agentId: pick(tenant.agentIds), source: "on_demand", reason: pick(["task_retry", "issue_assigned"]), + status: pick(["deferred_issue_execution", "deferred_issue_execution", "coalesced"]), + requestedByActorType: pick(["user", "user", "system"]), runId: !sourceCreated || chance(0.8) ? null : runId, + requestedAt: at(pick([finishedMinutesAgo - 5, finishedMinutesAgo + 5])), payload: { issueId } }); + } + const recordedRunId = pick(["runId", "runId", "runId", "runId", "runId", "sourceRunId", "sourceRunId", "upper", "invalid", "number", "missing", "unknown", + "braced", "padded", "both"]); + const runKey = recordedRunId === "sourceRunId" ? { sourceRunId: runId } + : recordedRunId === "upper" ? { runId: runId.toUpperCase() } : recordedRunId === "invalid" ? { runId: "not-a-run" } + : recordedRunId === "number" ? { runId: 42 } : recordedRunId === "missing" ? {} + : recordedRunId === "unknown" ? { runId: randomUUID() } : recordedRunId === "braced" ? { runId: `{${runId}}` } + : recordedRunId === "padded" ? { runId: ` ${runId}` } : recordedRunId === "both" ? { runId: "not-a-run", sourceRunId: runId } + : { runId }; + actionRows.push({ companyId: tenant.companyId, sourceIssueId: issueId, kind: pick(["active_run_watchdog", "missing_disposition"]), + status: pick(["active", "escalated", "resolved", "resolved"]), ownerType: "board", ownerUserId: chance(0.05) ? "user-1" : null, + cause: pick(["legacy_execution_requires_reconciliation", "native_continuation_requires_reconciliation", "stranded_assigned_issue"]), + fingerprint: `held:${index}`, nextAction: "Fixture", + evidence: { ...runKey, + ...(chance(0.7) ? { automaticRecovery: { replay: pick(["blocked", "blocked", "blocked", "allowed"]) } } : {}), + ...(chance(0.2) ? { systemRecovery: { state: pick(["complete", "exhausted", "scheduled", "running", "failed"]) } } : {}), + ...(chance(0.05) ? { executionReconciliation: { runId } } : {}), + ...(chance(0.05) ? { freshContinuation: { sourceRunId: runId } } : {}), + ...(chance(0.7) ? { freshContinuationCheck: { kind: "backoff", nextCheckAt: now.getTime() + Math.round((next() - 0.5) * 7_200_000) } } : {}) } }); + } + await db.insert(issues).values(issueRows); + // One statement, so a retry may name a source run listed after it. + await db.insert(heartbeatRuns).values(runRows); + if (wakeRows.length) await db.insert(agentWakeupRequests).values(wakeRows); + for (let start = 0; start < actionRows.length; start += 500) + await db.insert(issueRecoveryActions).values(actionRows.slice(start, start + 500)); + return actionRows.length; + } + + const verdicts = (where: { held: SQL; heldWithActive: SQL; eligible: SQL }) => db.select({ id: issueRecoveryActions.id, + held: sql`coalesce(${where.held}, false)`, heldWithActive: sql`coalesce(${where.heldWithActive}, false)`, + eligible: sql`coalesce(${where.eligible}, false)` }) + .from(issueRecoveryActions).innerJoin(issues, and(eq(issues.id, issueRecoveryActions.sourceIssueId), + eq(issues.companyId, issueRecoveryActions.companyId))).orderBy(asc(issueRecoveryActions.id)); + + it("selects exactly the records the previous predicates selected, for every run key, link and status", async () => { + const before = await verdicts({ held: previousHeldExecutionWhere(), heldWithActive: previousHeldExecutionWhere({ includeActive: true }), + eligible: previousRecentInterruptionSourceSql(now) }); + const after = await verdicts({ held: heldExecutionWhere(), heldWithActive: heldExecutionWhere({ includeActive: true }), + eligible: recentInterruptionSourceSql(now) }); + expect(after).toEqual(before); + expect(before).toHaveLength(actions); + // The fixture reaches both outcomes of each predicate, so equality is meaningful. + for (const key of ["held", "heldWithActive", "eligible"] as const) { + expect(before.filter(row => row[key]).length).toBeGreaterThan(5); + expect(before.filter(row => !row[key]).length).toBeGreaterThan(5); + } + expect(before.filter(row => row.heldWithActive && row.eligible).length).toBeGreaterThan(5); + }, 60_000); + + it("returns the deadline and the backlog listing the previous queries returned", async () => { + const liveHold = and(inArray(issueRecoveryActions.status, ["active", "escalated"]), eq(issueRecoveryActions.kind, "active_run_watchdog"))!; + const [previousDeadline] = await db.select({ at: sql`min((${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}')::bigint)` }) + .from(issueRecoveryActions).innerJoin(issues, and(eq(issues.id, issueRecoveryActions.sourceIssueId), + eq(issues.companyId, issueRecoveryActions.companyId))) + .where(and(previousHeldExecutionWhere({ includeActive: true }), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}' is not null`, + or(liveHold, previousRecentInterruptionSourceSql(now)))); + expect(previousDeadline?.at).not.toBeNull(); + expect(await nextFreshContinuationCheckAt(db, now)).toBe(Number(previousDeadline!.at)); + + const previousListing = await db.select({ id: issueRecoveryActions.id, companyId: issueRecoveryActions.companyId, + runId: sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId')` }) + .from(issueRecoveryActions).innerJoin(issues, and(eq(issues.id, issueRecoveryActions.sourceIssueId), + eq(issues.companyId, issueRecoveryActions.companyId))) + .where(and(previousHeldExecutionWhere(), freshContinuationCheckDue(now), previousRecentInterruptionSourceSql(now))) + .orderBy(desc(sql`(select source.finished_at from ${heartbeatRuns} source where source.company_id = ${issueRecoveryActions.companyId} + and source.id::text = coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId'))`), + asc(issueRecoveryActions.id)).limit(1_000); + expect(previousListing.length).toBeGreaterThan(0); + expect(await heldExecutionsAwaitingFreshContinuation(db, now, 1_000)).toEqual(previousListing); + }, 60_000); + + it("finds the deadline by run-key and task-link lookups, not a scan of run history per record", async () => { + let captured: { sql: string; params: unknown[] } | undefined; + const capture = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args); + selection.execute = async () => { captured = selection.toSQL(); return [{ at: null }]; }; + return selection; + }) as typeof builder.from; + return builder; + }; + } }); + await nextFreshContinuationCheckAt(capture as typeof db, now); + const [row] = await db.$client.unsafe(`explain (analyze, format json) ${captured!.sql}`, captured!.params as never[]); + const plan = (row!["QUERY PLAN"] as Array<{ Plan: PlanNode }>)[0]!.Plan; + const [{ runs }] = await db.$client.unsafe(`select count(*)::int as runs from heartbeat_runs`) as unknown as Array<{ runs: number }>; + // The previous query read the whole run history once per held record + // (hundreds of times here); the lookups read a few rows per record. + expect(heartbeatRunRowsRead(plan)).toBeLessThan(2 * runs); + }, 60_000); +}); diff --git a/server/src/services/heartbeat/dispatch-work.ts b/server/src/services/heartbeat/dispatch-work.ts index f3ce5834046..6e757b94fdd 100644 --- a/server/src/services/heartbeat/dispatch-work.ts +++ b/server/src/services/heartbeat/dispatch-work.ts @@ -4,6 +4,7 @@ import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator import { registerDeadlineWork } from "../deadline-work.js"; import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; import { createQueuedRunRedriveSchedule, type QueuedRunRedrivePlan, type UndispatchedQueuedRun } from "../queued-run-dispatch-liveness.js"; +import { nextAutomaticRunWakeAt, takeDueAutomaticRunWakes } from "../recovery/automatic-run-brake.js"; export function registerRunDispatchWork( coordinator: ReturnType, @@ -39,6 +40,9 @@ export function registerRunDispatchWork( onSettled: hints => { for (const hint of hints ?? ["*"]) scopes.add(hint); }, onStop: () => { unsubscribeRefresh?.(); unsubscribeRefresh = undefined; }, run: async signal => { + const dueWakes = takeDueAutomaticRunWakes(); + if (dueWakes.all) scopes.add("*"); + for (const companyId of dueWakes.companyIds) scopes.add(JSON.stringify({ companyId })); const requested = scopes.has("*") ? ["*"] : [...scopes]; if (requested[0] === "*") scopes.clear(); else for (const hint of requested) scopes.delete(hint); @@ -78,7 +82,8 @@ export function registerRunDispatchWork( throw error; } for (const companyId of plan.companyIds) scopes.add(JSON.stringify({ companyId })); - return plan.nextAt; + const wakeAt = nextAutomaticRunWakeAt(); + return plan.nextAt === null ? wakeAt : wakeAt === null ? plan.nextAt : Math.min(plan.nextAt, wakeAt); }, }); const refresh = () => { diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index f382ea499ba..18606daa274 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -13,6 +13,7 @@ import { deferredWorkIntentWait } from "../work-intent-outbox.js"; import { notifyIssueRecovery } from "../issue-recovery-notifications.js"; import { createHeartbeatTimerPolicy } from "./timer-policy.js"; import { QUEUED_RUN_AGING_MS, RECOVERY_WAKE_REASONS, createQueuedRunDispatcher, hasQueuedRunAged, queuedRunDispatchClass } from "./queued-run-dispatch-order.js"; +import { reserveAutomaticRunStart } from "../recovery/automatic-run-brake.js"; import { queuedRunDispatchFacts } from "./queued-run-line.js"; import { notifyExecutionRunWork } from "../execution-control-notifications.js"; import { PersistedExecutionWaitRefusal, writeDeferredExecutionWait } from "../deferred-execution-wait.js"; @@ -2478,7 +2479,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const now = new Date(); pruneDeclinedAgedClaims(now); const runById = new Map(queuedRuns.map(run => [run.id, run])); - const { facts, dispatchInput } = await queuedRunDispatchFacts(db, { + const { facts, dispatchInput, personOriginChecked } = await queuedRunDispatchFacts(db, { agent, queuedRuns, dependencyReadiness, issueById, now, shareDeferred: runId => declinedAgedClaimAt.has(runId) || claimBackedOff(runId, now, queuedRunTaskStamp(runById.get(runId)!, issueById)) }); const dispatcher = createQueuedRunDispatcher(facts, dispatchInput); @@ -2490,7 +2491,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const entry = byRun.get(run); return Boolean(entry && queuedRunDispatchClass(entry, now) === "person"); }, - personOrigin: (run: QueuedRunCandidate) => byRun.get(run)?.requestedByUser ?? false, + personOrigin: (run: QueuedRunCandidate) => personOriginChecked ? byRun.get(run)?.requestedByUser ?? false : undefined, }; } @@ -2599,15 +2600,21 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende continuesChain: true, triedRunIds: new Set([...triedRunIds, ...triedThisPass]) }); break; } + const start = await reserveAutomaticRunStart(db, candidate, { personOrigin: dispatcher.personOrigin(candidate) }); + if (start.held) continue; claimAttempts += 1; triedThisPass.push(candidate.id); const [queuedRun] = await db.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.id, candidate.id), eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.status, "queued"))); - if (!queuedRun) continue; + if (!queuedRun) { + await start.release(); + continue; + } let claimed: typeof heartbeatRuns.$inferSelect | null; try { claimed = await claimQueuedRun(queuedRun, companyAgents, deferredPostCommitEffects, deferredCancellations, slots); } catch (err) { + await start.release(); if (isPermanentClaimRejection(err)) { rejectedClaims.push({ run: queuedRun, err }); continue; @@ -2622,6 +2629,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende continue; } if (!claimed) { + await start.release(); if (slots.full) break; noteDeclinedAgedClaim(candidate, "claim_declined"); backOffClaim(candidate, dispatcher.personRun(candidate), taskStamp); diff --git a/server/src/services/heartbeat/queued-run-line.ts b/server/src/services/heartbeat/queued-run-line.ts index 9fb3047faba..573b7e3e348 100644 --- a/server/src/services/heartbeat/queued-run-line.ts +++ b/server/src/services/heartbeat/queued-run-line.ts @@ -106,17 +106,18 @@ export async function queuedRunDispatchFacts( shareDeferred?: (runId: string) => boolean; now: Date; }, -): Promise<{ facts: Array; dispatchInput: QueuedRunDispatchInput }> { +): Promise<{ facts: Array; dispatchInput: QueuedRunDispatchInput; personOriginChecked: boolean }> { const { agent, queuedRuns, dependencyReadiness, issueById, now } = input; const wakeReasonOf = (run: R) => readNonEmptyString(parseObject(run.contextSnapshot).wakeReason); + const personOriginChecked = queuedRuns.length > 1; const requestIds = [...new Set(queuedRuns.flatMap(run => run.wakeupRequestId ? [run.wakeupRequestId] : []))]; - const userRequests = queuedRuns.length > 1 && requestIds.length + const userRequests = personOriginChecked && requestIds.length ? await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( eq(agentWakeupRequests.companyId, agent.companyId), inArray(agentWakeupRequests.id, requestIds), eq(agentWakeupRequests.requestedByActorType, "user"))) : []; const userRequestIds = new Set(userRequests.map(row => row.id)); - const joinedUserRequests = queuedRuns.length > 1 + const joinedUserRequests = personOriginChecked ? await db.select({ runId: agentWakeupRequests.runId }).from(agentWakeupRequests).where(and( eq(agentWakeupRequests.companyId, agent.companyId), inArray(agentWakeupRequests.runId, queuedRuns.map(run => run.id)), eq(agentWakeupRequests.agentId, agent.id), eq(agentWakeupRequests.requestedByActorType, "user"))) @@ -126,7 +127,7 @@ export async function queuedRunDispatchFacts( userRunIds.has(run.id) || Boolean(run.wakeupRequestId && userRequestIds.has(run.wakeupRequestId)); const sourceRunIdOf = (run: R) => readNonEmptyString(parseObject(run.contextSnapshot).previousRunId) ?? run.retryOfRunId ?? null; - const sourceRunIds = queuedRuns.length > 1 + const sourceRunIds = personOriginChecked ? [...new Set(queuedRuns.flatMap(run => { const sourceRunId = joinedByUser(run) ? null : sourceRunIdOf(run); return sourceRunId && RUN_ID_PATTERN.test(sourceRunId) ? [sourceRunId] : []; @@ -184,7 +185,7 @@ export async function queuedRunDispatchFacts( const recentStarts = startRows.map(row => ({ ...row, personOrigin: personStarts.has(row.id), personWaiting: personStarts.has(row.id) || Boolean(row.issueId && personTaskIds.has(row.issueId)) })); const { startsSinceRecovery, startsSinceOldest } = dispatchCountersFromStarts(facts, recentStarts, now); - return { facts, dispatchInput: { now, startsSinceRecovery, startsSinceOldest } }; + return { facts, dispatchInput: { now, startsSinceRecovery, startsSinceOldest }, personOriginChecked }; } /** At most this many agents' lines are computed for one projection read. */ diff --git a/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts b/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts index bd179a05724..7e564f8ae98 100644 --- a/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts +++ b/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts @@ -1,6 +1,6 @@ import { randomBytes, randomUUID } from "node:crypto"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { eq, sql } from "drizzle-orm"; import { agents, checkpointDb, closeCheckpointDb, companies, createDb, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, subscribeDatabaseWork } from "@paperclipai/db"; import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; @@ -12,13 +12,16 @@ const support = await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("native runner checkpoint save", () => { let temporary: Awaited>; let db: ReturnType; + let otherDb: ReturnType; beforeAll(async () => { process.env.PAPERCLIP_SECRETS_MASTER_KEY ??= randomBytes(32).toString("base64"); temporary = await startEmbeddedPostgresTestDatabase("paperclip-checkpoint-save-"); db = createDb(temporary.connectionString); + otherDb = createDb(temporary.connectionString); }, 60_000); afterAll(async () => { if (db) await closeCheckpointDb(db, 1); + await otherDb?.$client.end({ timeout: 1 }); await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); @@ -41,7 +44,7 @@ const support = await getEmbeddedPostgresTestSupport(); recoveryEvidence: { runnerInstanceId: "test", normalizedSessionId: "test", authenticatedConnectionCount: 1, highestRecordedSourceSeq: 0 }, restoreSessionDirectory() {}, }) as unknown as Parameters[0]; - return { runId, write, checkpoint }; + return { runId, companyId: company!.id, issueId: issue!.id, write, checkpoint }; }; const sentStatements = async (action: () => Promise) => { @@ -51,23 +54,109 @@ const support = await getEmbeddedPostgresTestSupport(); try { await action(); return statements; } finally { options.debug = undefined; } }; - it("saves a checkpoint with the owner lock, the write and the commit, and registers its wake before the write", async () => { - const f = await fixture(new Date(Date.now() + 3_600_000)); - await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true)); + const parts = async (runId: string) => (await db.select({ part: nativeRunnerCheckpoints.part }) + .from(nativeRunnerCheckpoints).where(eq(nativeRunnerCheckpoints.runId, runId))).map(row => row.part).sort(); + const recoveryWakes = () => { const events: string[] = []; const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.nativeProcessSessions, event => { events.push(event); }); + return { events, unsubscribe }; + }; + + it("saves a routine checkpoint in one statement that checks the owner, and registers no recovery wake", async () => { + const f = await fixture(new Date(Date.now() + 3_600_000)); + await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true)); + const wakes = recoveryWakes(); let statements: string[]; try { statements = await sentStatements(() => f.write(f.checkpoint(new Map([["event:1", "{}"], ["cursor", "{\"ackedSourceSeq\":1}"]]), false))); - } finally { unsubscribe(); } - expect(statements).toHaveLength(4); + } finally { wakes.unsubscribe(); } + expect(statements).toHaveLength(1); + expect(statements[0]).toMatch(/^with locked_owner as .* for update .* lease_expires_at > clock_timestamp\(\) .* insert into "native_runner_checkpoints"/); + expect(wakes.events).toEqual([]); + expect(await parts(f.runId)).toEqual(["cursor", "event:1", "header"]); + }); + + it("saves a reset with the owner lock, the write and the commit, and registers its recovery wake before the write", async () => { + const f = await fixture(new Date(Date.now() + 3_600_000)); + await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true)); + const wakes = recoveryWakes(); + let statements: string[]; + try { + statements = await sentStatements(() => f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":2}"]]), true))); + } finally { wakes.unsubscribe(); } expect(statements[0]).toMatch(/^begin/i); expect(statements[1]).toMatch(/pg_current_xact_id\(\)/); - expect(statements[2]).toMatch(/^insert into "native_runner_checkpoints"/); - expect(statements[3]).toMatch(/^commit/i); - expect(events).toEqual(["intent", "settled"]); - expect((await db.select({ part: nativeRunnerCheckpoints.part }).from(nativeRunnerCheckpoints) - .where(eq(nativeRunnerCheckpoints.runId, f.runId))).map(row => row.part).sort()).toEqual(["cursor", "event:1", "header"]); + expect(statements.at(-1)).toMatch(/^commit/i); + expect(wakes.events).toEqual(["intent", "settled"]); + expect(await parts(f.runId)).toEqual(["cursor", "header"]); + }); + + it.each(["takeover", "takeover with a reset"])("falls back to the full owner check when a routine save races a lease %s", async (race) => { + const f = await fixture(new Date(Date.now() + 3_600_000)); + await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true)); + let release!: () => void, locked!: () => void; + const released = new Promise(resolve => { release = resolve; }); + const lockedOwner = new Promise(resolve => { locked = resolve; }); + const holder = otherDb.transaction(async tx => { + await tx.execute(sql`select run_id from native_run_finalizations where run_id = ${f.runId} for update`); + await tx.update(nativeRunFinalizations).set({ leaseOwner: randomUUID(), controllerGeneration: 2 }) + .where(eq(nativeRunFinalizations.runId, f.runId)); + if (race === "takeover with a reset") { + await tx.delete(nativeRunnerCheckpoints).where(eq(nativeRunnerCheckpoints.runId, f.runId)); + await tx.insert(nativeRunnerCheckpoints).values({ companyId: f.companyId, issueId: f.issueId, runId: f.runId, + part: "header", material: { successor: true } }); + } + locked(); + await released; + }); + void holder.catch(() => undefined); + await lockedOwner; + const saved = f.write(f.checkpoint(new Map([["event:1", "{}"], ["cursor", "{\"ackedSourceSeq\":1}"]]), false)) + .then(() => "saved", (error: Error) => error.message); + try { + await vi.waitFor(async () => { + const [waiting] = await otherDb.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity + where datname = current_database() and wait_event_type = 'Lock' and query like '%with locked_owner as%'`); + expect(waiting?.count).toBe(1); + }, { timeout: 10_000, interval: 20 }); + } finally { + release(); + await holder; + } + expect(await saved).toBe("native_runner_checkpoint_owner_lost"); + expect(await parts(f.runId)).toEqual(race === "takeover" ? ["cursor", "header"] : ["header"]); + }); + + it("judges the lease after the owner lock, so a lease that expires while a routine save waits writes nothing", async () => { + const f = await fixture(new Date(Date.now() + 3_600_000)); + await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true)); + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: sql`clock_timestamp() + interval '1 second'` }) + .where(eq(nativeRunFinalizations.runId, f.runId)); + let release!: () => void, locked!: () => void; + const released = new Promise(resolve => { release = resolve; }); + const lockedOwner = new Promise(resolve => { locked = resolve; }); + const holder = otherDb.transaction(async tx => { + await tx.execute(sql`select run_id from native_run_finalizations where run_id = ${f.runId} for update`); + locked(); + await released; + }); + void holder.catch(() => undefined); + await lockedOwner; + const saved = f.write(f.checkpoint(new Map([["event:1", "{}"], ["cursor", "{\"ackedSourceSeq\":1}"]]), false)) + .then(() => "saved", (error: Error) => error.message); + try { + await vi.waitFor(async () => { + const [waiting] = await otherDb.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity + where datname = current_database() and wait_event_type = 'Lock' and query like '%with locked_owner as%'`); + expect(waiting?.count).toBe(1); + }, { timeout: 10_000, interval: 20 }); + await otherDb.execute(sql`select pg_sleep(1.2)`); + } finally { + release(); + await holder; + } + expect(await saved).toBe("native_runner_checkpoint_owner_lost"); + expect(await parts(f.runId)).toEqual(["cursor", "header"]); }); it("refuses a save after the owner's lease expired and writes nothing", async () => { diff --git a/server/src/services/native-runtime/native-runner-checkpoint.ts b/server/src/services/native-runtime/native-runner-checkpoint.ts index 8582d339ed7..055168d68e5 100644 --- a/server/src/services/native-runtime/native-runner-checkpoint.ts +++ b/server/src/services/native-runtime/native-runner-checkpoint.ts @@ -128,12 +128,39 @@ export async function assertNativeRunnerCheckpointOwner(tx: CheckpointTransactio await validateNativeRunnerCheckpointOwner(tx, owner, locked, newWork); } +const ROUTINE_CHECKPOINT_SAVE_SQL = ` + with locked_owner as ( + select lease_expires_at from native_run_finalizations + where company_id = $1::uuid and issue_id = $2::uuid and run_id = $3::uuid and controller_boot_id = $4::text + and controller_generation = $5::integer and lease_owner = $6::text + for update + ), owner as ( + select 1 from locked_owner where lease_expires_at > clock_timestamp() + ), written as ( + insert into "native_runner_checkpoints" (company_id, issue_id, run_id, part, material) + select $1::uuid, $2::uuid, $7::uuid, part.value ->> 'part', part.value -> 'material' + from owner cross join jsonb_array_elements($8::jsonb) as part(value) + on conflict (run_id, part) do update set material = excluded.material, updated_at = now() + returning 1 + ) + select (select count(*)::int from owner) as owned, (select count(*)::int from written) as written`; + export function nativeRunnerCheckpointWriter(db: Db, owner: NativeRunnerCheckpointOwner) { const persistenceDb = checkpointDb(db); let previousWork = new Set(); return async (checkpoint: DurablePrpCheckpoint): Promise => { if (checkpoint.runId !== owner.runId) throw new Error("native_runner_checkpoint_binding_mismatch"); const changed = encryptParts(owner, checkpoint.changedRecords); + if (changed.length > 0 && !checkpoint.reset && checkpoint.removedRecords.length === 0 && !checkpoint.changedRecords.has("header") + && !checkpoint.predecessor && owner.runId === owner.authorityRunId) { + const [saved] = await persistenceDb.$client.unsafe<{ owned: number; written: number }[]>(ROUTINE_CHECKPOINT_SAVE_SQL, [ + owner.companyId, owner.issueId, owner.authorityRunId, owner.bootId, String(owner.generation), owner.leaseOwner, owner.runId, + JSON.stringify(changed.map(part => ({ part: part.part, material: part.material })))]); + if (saved?.owned === 1 && saved.written === changed.length) { + previousWork = new Set(checkpoint.workCommandIds); + return; + } + } await persistenceDb.transaction(async tx => { if (owner.runId !== owner.authorityRunId) { await lockSourceRecoveryCoordinators(tx, owner.companyId, [owner.runId, owner.authorityRunId]); diff --git a/server/src/services/native-runtime/native-workspace-finalizer.test.ts b/server/src/services/native-runtime/native-workspace-finalizer.test.ts index 5b5e18b3049..ae98d0f80a3 100644 --- a/server/src/services/native-runtime/native-workspace-finalizer.test.ts +++ b/server/src/services/native-runtime/native-workspace-finalizer.test.ts @@ -22,6 +22,7 @@ import { agentWakeupRequests, agents, companies, + closeDedicatedDbConnections, completionContracts, createDb, environmentLeases, @@ -1050,6 +1051,7 @@ describe("native workspace finalization recovery", () => { const rows = await db.execute(sql`select current_user as name`); const role = String(rows[0].name); await db.execute(sql`alter role ${sql.identifier(role)} set idle_in_transaction_session_timeout = '1s'`); + await closeDedicatedDbConnections(db, 1); try { const result = await withNativeWorkspaceFinalizationOwnership({ db, companyId, runId: seeded.runId }, async ownership => { await new Promise(resolve => setTimeout(resolve, 3200)); diff --git a/server/src/services/recovery/automatic-run-brake.ts b/server/src/services/recovery/automatic-run-brake.ts index fa345482221..9964f23cbf2 100644 --- a/server/src/services/recovery/automatic-run-brake.ts +++ b/server/src/services/recovery/automatic-run-brake.ts @@ -1,7 +1,8 @@ import { eq, sql } from "drizzle-orm"; import { automaticRunBrakes, type Db } from "@paperclipai/db"; import { logger } from "../../middleware/logger.js"; -import { PERSON_WAKE_REASONS, RECOVERY_WAKE_REASONS } from "../heartbeat/queued-run-dispatch-order.js"; +import { PERSON_WAKE_REASONS } from "../heartbeat/queued-run-dispatch-order.js"; +import { isPersonOwnedFailureCode, isRecoveryRun, isRestartClassFailureCode } from "../continuation-cause.js"; import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "../environment-provider-unavailable-error.js"; export const AUTOMATIC_RUN_BRAKE = { @@ -37,15 +38,12 @@ export type AutomaticRunFacts = { contextSnapshot?: Record | null; }; -const EXTRA_AUTOMATIC_WAKE_REASONS: ReadonlySet = new Set(["issue_assignment_recovery", "transient_failure_retry"]); - export function isAutomaticRun(run: AutomaticRunFacts): boolean { const context = run.contextSnapshot ?? {}; const reason = typeof context.wakeReason === "string" ? context.wakeReason : null; - if (context.explicitUserContinuation || context.taskRetryRequestId || (reason && PERSON_WAKE_REASONS.has(reason))) return false; - return Boolean(run.retryOfRunId || run.scheduledRetryReason || context.previousRunId || context.retryReason - || context.freshContinuationIsolation - || (reason && (RECOVERY_WAKE_REASONS.has(reason) || EXTRA_AUTOMATIC_WAKE_REASONS.has(reason)))); + if (context.taskRetryRequestId || (reason && PERSON_WAKE_REASONS.has(reason))) return false; + return isRecoveryRun({ retryOfRunId: run.retryOfRunId ?? null, scheduledRetryReason: run.scheduledRetryReason ?? null, + contextSnapshot: context }); } export type AutomaticRunOutcome = "failed_before_starting" | "healthy" | "neutral"; @@ -62,8 +60,6 @@ export type AutomaticRunOutcomeFacts = { }; export type AutomaticRunOutcomeRules = { - isPersonOwnedFailureCode: (code: string | null) => boolean; - restartCodes: readonly string[]; isTransientSetupCode: (code: string | null) => boolean; hasNativePreDispatchFailureRecord: (resultJson: unknown) => boolean; listPersonOriginSourceRunIds: (db: Db, companyId: string, runIds: string[]) => Promise; @@ -72,11 +68,9 @@ export type AutomaticRunOutcomeRules = { let outcomeRules: Promise | null = null; export function automaticRunOutcomeRules(): Promise { - outcomeRules ??= Promise.all([import("../fresh-continuation-fallback.js"), import("../heartbeat/retries.js"), + outcomeRules ??= Promise.all([import("../heartbeat/retries.js"), import("../heartbeat/run-failure-cause.js"), import("../heartbeat/queued-run-line.js")]) - .then(([fallback, retries, failureCause, queuedRunLine]) => ({ - isPersonOwnedFailureCode: fallback.isPersonOwnedFailureCode, - restartCodes: fallback.BACKLOG_CONTINUATION_SOURCE_CODES, + .then(([retries, failureCause, queuedRunLine]) => ({ isTransientSetupCode: retries.isTransientWorkspacePreparationCode, hasNativePreDispatchFailureRecord: failureCause.hasNativePreDispatchFailureRecord, listPersonOriginSourceRunIds: queuedRunLine.listPersonOriginSourceRunIds, @@ -88,8 +82,8 @@ export function automaticRunOutcomeRules(): Promise { export function classifyAutomaticRunOutcome(run: AutomaticRunOutcomeFacts, rules: AutomaticRunOutcomeRules): AutomaticRunOutcome { if (run.status === "running") return run.executionStage === "dispatching" || run.hasOutput ? "healthy" : "neutral"; if (!run.startedAt || run.status === "cancelled" || !["succeeded", "failed", "timed_out", "interrupted"].includes(run.status)) return "neutral"; - if (run.status === "succeeded" || rules.isPersonOwnedFailureCode(run.errorCode)) return "healthy"; - if (run.errorCode && rules.restartCodes.includes(run.errorCode)) return "neutral"; + if (run.status === "succeeded" || isPersonOwnedFailureCode(run.errorCode)) return "healthy"; + if (isRestartClassFailureCode(run.errorCode)) return "neutral"; const startPhase = run.providerWorkStarted === "false" || rules.isTransientSetupCode(run.errorCode) || rules.hasNativePreDispatchFailureRecord({ nativePreDispatchFailure: run.nativePreDispatchFailure }) || (run.runtimeMode === "legacy" && run.executionStage === "preparing"); @@ -156,6 +150,7 @@ function boundedMap(max: number) { while (map.size > max) map.delete(map.keys().next().value as K); }, delete(key: K) { map.delete(key); }, + entries() { return [...map.entries()]; }, clear() { map.clear(); }, get size() { return map.size; }, }; @@ -212,6 +207,10 @@ export type AutomaticWork = { issueId: string; sourceRunId: string | null }; export type AutomaticRunCreationSlot = { heldUntil: Date } | { heldUntil: null; release: () => Promise }; +export type AutomaticRunStartSlot = { held: true } | { held: false; release: () => Promise }; + +const NOT_HELD: AutomaticRunStartSlot = { held: false, release: async () => undefined }; + const NO_RESERVATION = async () => undefined; type CacheEntry = { snapshot: AutomaticRunBrakeSnapshot; readAt: number; skewMs: number; heldUntil: number }; @@ -220,6 +219,8 @@ export function createAutomaticRunBrake(options: { loadRules?: () => Promise(AUTOMATIC_RUN_BRAKE.maxCompanies); const personOrigin = boundedMap(AUTOMATIC_RUN_BRAKE.maxRuns); + const wakes = boundedMap(AUTOMATIC_RUN_BRAKE.maxCompanies); + let evictedWakeAt: number | null = null; let rulesFailureLogged = false; async function rulesOrNull() { @@ -476,15 +477,22 @@ export function createAutomaticRunBrake(options: { loadRules?: () => Promise { + await db.update(automaticRunBrakes).set({ probeRunId: null, nextProbeAt: null, updatedAt: sql`now()` }) + .where(sql`${automaticRunBrakes.companyId} = ${run.companyId} and ${automaticRunBrakes.state} = 'open' + and ${automaticRunBrakes.probeRunId} = ${run.id}::uuid + and not exists (select 1 from heartbeat_runs p where p.company_id = ${run.companyId} and p.id = ${run.id}::uuid + and p.started_at is not null)`); + companies.delete(run.companyId); + }; } const nextProbeAt = entry.snapshot.nextProbeAt ? entry.snapshot.nextProbeAt.getTime() - entry.skewMs : 0; entry.heldUntil = Math.max(now + AUTOMATIC_RUN_BRAKE.cacheTtlMs, nextProbeAt); - return false; + return null; } async function grantRelease(db: Db, entry: CacheEntry, companyId: string) { - const [granted] = [...await db.execute<{ starts: number; window_ends_at: string | Date }>(sql` + const [granted] = [...await db.execute<{ starts: number; window_start: string | Date; window_ends_at: string | Date }>(sql` with ramp as ( select b.company_id, b.state_changed_at + floor(extract(epoch from now() - b.state_changed_at) * 1000 / ${AUTOMATIC_RUN_BRAKE.releaseIntervalMs}) * ${`${AUTOMATIC_RUN_BRAKE.releaseIntervalMs} milliseconds`}::interval as window_start, @@ -498,25 +506,71 @@ export function createAutomaticRunBrake(options: { loadRules?: () => Promise { + await db.update(automaticRunBrakes).set({ releaseWindowStarts: sql`${automaticRunBrakes.releaseWindowStarts} - 1`, updatedAt: sql`now()` }) + .where(sql`${automaticRunBrakes.companyId} = ${companyId} and ${automaticRunBrakes.state} = 'half_open' + and ${automaticRunBrakes.releaseWindowStartedAt} = ${windowStart}::timestamptz and ${automaticRunBrakes.releaseWindowStarts} > 0`); + companies.delete(companyId); + }; + } const step = rampStep(entry.snapshot.stateChangedAt ?? entry.snapshot.dbNow, new Date(Date.now() + entry.skewMs)); const windowEnds = (entry.snapshot.stateChangedAt?.getTime() ?? 0) + (step + 1) * AUTOMATIC_RUN_BRAKE.releaseIntervalMs; entry.heldUntil = Math.max(Date.now() + 1_000, windowEnds - entry.skewMs); - return false; + return null; } - async function holdAutomaticRunStart(db: Db, run: AutomaticRunFacts, options: { personOrigin?: boolean } = {}): Promise { - if (!isAutomaticRun(run)) return false; + async function reserveStart(db: Db, run: AutomaticRunFacts, options: { personOrigin?: boolean } = {}): Promise { + if (!isAutomaticRun(run)) return NOT_HELD; const cached = companies.get(run.companyId); - if (cached && cached.snapshot.state === "closed" && Date.now() - cached.readAt < AUTOMATIC_RUN_BRAKE.cacheTtlMs) return false; - if (options.personOrigin ?? await isPersonOrigin(db, run)) return false; - if (cached && cached.heldUntil > Date.now()) return true; + if (cached && cached.snapshot.state === "closed" && Date.now() - cached.readAt < AUTOMATIC_RUN_BRAKE.cacheTtlMs) return NOT_HELD; + if (options.personOrigin ?? await isPersonOrigin(db, run)) return NOT_HELD; + if (cached && cached.heldUntil > Date.now()) return held(cached); const entry = await current(db, run.companyId); - if (entry.snapshot.state === "closed") return false; - if (entry.heldUntil > Date.now()) return true; - const allowed = entry.snapshot.state === "open" ? await grantProbe(db, entry, run) : await grantRelease(db, entry, run.companyId); - return !allowed; + if (entry.snapshot.state === "closed") return NOT_HELD; + if (entry.heldUntil > Date.now()) return held(entry); + const release = entry.snapshot.state === "open" ? await grantProbe(db, entry, run) : await grantRelease(db, entry, run.companyId); + if (!release) return held(entry); + return { held: false, release: () => release().catch(error => { + logger.warn({ err: error, companyId: run.companyId, runId: run.id }, "Automatic work pause could not return an unused start"); + }) }; + } + + async function holdAutomaticRunStart(db: Db, run: AutomaticRunFacts, options: { personOrigin?: boolean } = {}) { + return (await reserveStart(db, run, options)).held; + } + + function held(entry: CacheEntry): AutomaticRunStartSlot { + const now = Date.now(); + const nextProbeAt = entry.snapshot.nextProbeAt ? entry.snapshot.nextProbeAt.getTime() - entry.skewMs : 0; + const due = entry.snapshot.state === "open" ? Math.max(entry.heldUntil, nextProbeAt) : entry.heldUntil; + const at = due - now < 1_000 ? now + AUTOMATIC_RUN_BRAKE.probeIntervalMs : due; + const known = wakes.get(entry.snapshot.companyId); + if (known === undefined && wakes.size >= AUTOMATIC_RUN_BRAKE.maxCompanies) { + const [oldest] = wakes.entries(); + if (oldest) { + evictedWakeAt = evictedWakeAt === null ? oldest[1] : Math.min(evictedWakeAt, oldest[1]); + wakes.delete(oldest[0]); + } + } + if (known === undefined || known <= now || at < known) wakes.set(entry.snapshot.companyId, at); + return { held: true }; + } + + function takeDueWakes(now = Date.now()) { + const due: string[] = []; + let nextAt: number | null = null; + for (const [companyId, at] of wakes.entries()) { + if (at <= now) due.push(companyId); + else nextAt = nextAt === null ? at : Math.min(nextAt, at); + } + for (const companyId of due) wakes.delete(companyId); + const all = evictedWakeAt !== null && evictedWakeAt <= now; + if (all) evictedWakeAt = null; + else if (evictedWakeAt !== null) nextAt = nextAt === null ? evictedWakeAt : Math.min(nextAt, evictedWakeAt); + return { companyIds: due, all, nextAt }; } return { @@ -525,13 +579,27 @@ export function createAutomaticRunBrake(options: { loadRules?: () => Promise ({ companies: companies.size, runs: personOrigin.size }), - reset: () => { companies.clear(); personOrigin.clear(); }, + reserveStart, + takeDueWakes, + cacheSizes: () => ({ companies: companies.size, runs: personOrigin.size, wakes: wakes.size }), + reset: () => { companies.clear(); personOrigin.clear(); wakes.clear(); evictedWakeAt = null; }, }; } export const automaticRunBrake = createAutomaticRunBrake(); +export function reserveAutomaticRunStart(db: Db, run: AutomaticRunFacts, options: { personOrigin?: boolean } = {}) { + return automaticRunBrake.reserveStart(db, run, options); +} + +export function takeDueAutomaticRunWakes(now = Date.now()) { + return automaticRunBrake.takeDueWakes(now); +} + +export function nextAutomaticRunWakeAt() { + return automaticRunBrake.takeDueWakes(Number.NEGATIVE_INFINITY).nextAt; +} + export function automaticRunCreationHeldUntil(db: Db, companyId: string, work: AutomaticWork) { return automaticRunBrake.creationHeldUntil(db, companyId, work); } diff --git a/server/src/services/remote-workspace-snapshot-retention.test.ts b/server/src/services/remote-workspace-snapshot-retention.test.ts index 88612a5583a..9805168ba8c 100644 --- a/server/src/services/remote-workspace-snapshot-retention.test.ts +++ b/server/src/services/remote-workspace-snapshot-retention.test.ts @@ -6,8 +6,8 @@ import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { eq, sql } from "drizzle-orm"; -import { applyPendingMigrations, closeRegisteredClients, companies, createDb, executionWorkspaceSnapshots, - executionWorkspaces, issueRecoveryActions, issues, workspaceOperations } from "@paperclipai/db"; +import { agents, applyPendingMigrations, closeRegisteredClients, companies, createDb, executionWorkspaceSnapshots, + executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, workspaceOperations } from "@paperclipai/db"; import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; import { createStorageService } from "../storage/service.js"; import { createS3StorageProvider } from "../storage/s3-provider.js"; @@ -16,6 +16,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; import { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; import { idleWorkSnapshot } from "./task-admission.js"; +import { notifyExecutionRunWork } from "./execution-control-notifications.js"; import { issueRecoveryActionService } from "./issue-recovery-actions.js"; import { notifyRemoteWorkspaceSnapshots, registerRemoteWorkspaceSnapshotRetentionWork, remoteWorkspaceSnapshotRetentionService } from "./remote-workspace-snapshot-retention.js"; @@ -108,6 +109,7 @@ describe.skipIf(!support.supported)("remote workspace snapshot retention", () => beforeEach(async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), "pc-retention-test-")); storage = createStorageService(createLocalDiskStorageProvider(root)); }); afterEach(async () => { await db.delete(issueRecoveryActions); await db.delete(workspaceOperations); await db.delete(executionWorkspaceSnapshots); + await db.delete(heartbeatRuns); await db.delete(agents); await db.delete(issues); await db.delete(executionWorkspaces); await db.delete(companies); await fs.rm(root, { recursive: true, force: true }); vi.unstubAllEnvs(); @@ -340,6 +342,96 @@ describe.skipIf(!support.supported)("remote workspace snapshot retention", () => ownerType: "board", cause: "workspace_recovery", fingerprint: randomUUID(), nextAction: "Recover saved files" }); expect(await owner.tick()).toMatchObject({ pinned: 1, deleted: 0 }); expect(await owner.nextDeadlineAt()).toBeNull(); }); + type Fixture = Awaited>; + const failedMigration = (f: Fixture) => db.insert(workspaceOperations).values({ id: f.operationId, companyId: f.companyId, + executionWorkspaceId: f.workspaceId, phase: "remote_workspace_migration", status: "failed", + metadata: { lastFailure: { code: "source_expired_during_import", cohortId: randomUUID() } } }); + const pins: Record Promise<() => Promise> }> = { + workspace: { hold: async f => { + await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { snapshotId: f.row.id } } }).where(eq(executionWorkspaces.id, f.workspaceId)); + return () => db.update(executionWorkspaces).set({ metadata: {} }).where(eq(executionWorkspaces.id, f.workspaceId)); + } }, + import: { hold: async f => { + const [parent] = await db.insert(executionWorkspaceSnapshots).values({ companyId: f.companyId, executionWorkspaceId: randomUUID(), + sourceOperationId: randomUUID(), generation: 1, epoch: 1, status: "superseded", deleteAfter: new Date(now.getTime() + 86400_000), + metadata: { importedWorkspaceChildren: [{ workspaceId: f.workspaceId, snapshotId: f.row.id }] } }).returning(); + return () => db.update(executionWorkspaceSnapshots).set({ status: "deleted", deleteAfter: null }).where(eq(executionWorkspaceSnapshots.id, parent!.id)); + } }, + operation: { hold: async f => { + await failedMigration(f); + return () => db.update(workspaceOperations).set({ metadata: { lastFailure: { code: "source_expired_during_import" }, + retiredSave: { snapshotId: randomUUID() } } }).where(eq(workspaceOperations.id, f.operationId)); + } }, + child: { hold: async f => { + const [child] = await db.insert(executionWorkspaceSnapshots).values({ companyId: f.companyId, executionWorkspaceId: f.workspaceId, + sourceOperationId: randomUUID(), parentSnapshotId: f.row.id, generation: 2, epoch: 1, status: "pending", + deleteAfter: new Date(now.getTime() + 86400_000) }).returning(); + return () => db.update(executionWorkspaceSnapshots).set({ status: "deleted", deleteAfter: null }).where(eq(executionWorkspaceSnapshots.id, child!.id)); + } }, + run: { hold: async f => { + const [agent] = await db.insert(agents).values({ companyId: f.companyId, name: "Remote worker" }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: agent!.id, status: "running", + runnerProfileJson: { remoteWorkspace: { workspaceId: f.workspaceId, snapshotId: f.row.id } } }).returning(); + return () => db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run!.id)); + } }, + recovery: { hold: async f => { + const [action] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", + ownerType: "board", cause: "workspace_recovery", fingerprint: randomUUID(), nextAction: "Recover saved files" }).returning(); + return () => db.update(issueRecoveryActions).set({ status: "resolved" }).where(eq(issueRecoveryActions.id, action!.id)); + } }, + }; + it.each(Object.keys(pins))("leaves %s-pinned history out of later passes, across restarts, until that pin is released", async kind => { + const f = await seed(), release = await pins[kind]!.hold(f); + expect(await service().tick()).toMatchObject({ pinned: 1, deleted: 0 }); + const owner = service(); + expect(await owner.tick()).toMatchObject({ checked: 0, pinned: 0, deleted: 0 }); + expect(await owner.tick()).toMatchObject({ checked: 0 }); + expect((await db.select().from(executionWorkspaceSnapshots).where(eq(executionWorkspaceSnapshots.id, f.row.id)))[0]) + .toMatchObject({ status: "superseded", deleteAfter: null }); + for (const key of f.keys) expect((await storage.headObject(f.companyId, key)).exists).toBe(true); + await release(); + expect(await owner.tick()).toMatchObject({ checked: 1, pinned: 0, deleted: 1 }); + for (const key of f.keys) expect((await storage.headObject(f.companyId, key)).exists).toBe(false); + }); + it("re-examines a pinned snapshot when its recorded pin is released but another still holds it", async () => { + const f = await seed(); + const releaseRun = await pins.run!.hold(f); + const owner = service(); + expect(await owner.tick()).toMatchObject({ pinned: 1 }); + await failedMigration(f); + expect(await owner.tick()).toMatchObject({ checked: 0 }); + await releaseRun(); + expect(await owner.tick()).toMatchObject({ checked: 1, pinned: 1, deleted: 0 }); + expect(await owner.tick()).toMatchObject({ checked: 0 }); + for (const key of f.keys) expect((await storage.headObject(f.companyId, key)).exists).toBe(true); + }); + it("revisits a failed save's recorded pin once its abandoned upload is settled", async () => { + const f = await seed("pending"); + await db.insert(workspaceOperations).values({ id: f.operationId, companyId: f.companyId, executionWorkspaceId: f.workspaceId, + phase: "remote_workspace_snapshot", status: "failed", metadata: { lastFailure: { code: "remote_workspace_save_abandoned" } } }); + const owner = service(); + expect(await owner.tick()).toMatchObject({ pinned: 1 }); + expect(await owner.tick()).toMatchObject({ checked: 0 }); + const [row] = await db.select().from(executionWorkspaceSnapshots).where(eq(executionWorkspaceSnapshots.id, f.row.id)); + await db.update(executionWorkspaceSnapshots).set({ status: "delete_requested", objectKey: null, + metadata: { ...row!.metadata, abandonedUpload: { operationId: f.operationId } } }).where(eq(executionWorkspaceSnapshots.id, f.row.id)); + expect(await owner.tick()).toMatchObject({ checked: 1, deleted: 1 }); + }); + it("does not re-examine unchanged pinned history on execution notifications", async () => { + for (let index = 0; index < 3; index++) await failedMigration(await seed()); + const results: Array<{ checked: number; pinned: number }> = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } }); + const worker = registerRemoteWorkspaceSnapshotRetentionWork(coordinator, service(), result => { results.push(result); }); + try { + await vi.waitFor(() => expect(results.reduce((sum, result) => sum + result.pinned, 0)).toBe(3)); + const settled = results.length; + for (let index = 1; index <= 3; index++) { + await db.transaction(async tx => { await notifyExecutionRunWork(tx); }); + await vi.waitFor(() => expect(results.length).toBeGreaterThanOrEqual(settled + index), { timeout: 4000 }); + } + expect(results.slice(settled).reduce((sum, result) => sum + result.checked, 0)).toBe(0); + } finally { await worker.stop(); await coordinator.stop(); } + }); it("rejects a foreign upload key without deleting another company's object", async () => { const f = await seed(); const foreignKey = `${randomUUID()}/workspace-snapshots/foreign`; await db.update(executionWorkspaceSnapshots).set({ metadata: { uploads: [{ objectKey: foreignKey }] } }).where(eq(executionWorkspaceSnapshots.id, f.row.id)); @@ -355,7 +447,7 @@ describe.skipIf(!support.supported)("remote workspace snapshot retention", () => await new Promise(resolve => setTimeout(resolve, 30)); expect(run).toHaveBeenCalledOnce(); const f = await seed(); await db.transaction(async tx => { await notifyRemoteWorkspaceSnapshots(tx, `workspace:${f.workspaceId}`); }); - await vi.waitFor(async () => expect((await storage.headObject(f.companyId, f.keys[0]!)).exists).toBe(false)); + await vi.waitFor(async () => expect((await storage.headObject(f.companyId, f.keys[0]!)).exists).toBe(false), { timeout: 4000 }); expect(run).toHaveBeenCalledTimes(2); } finally { await worker.stop(); await coordinator.stop(); } }); @@ -407,7 +499,7 @@ describe.skipIf(!support.supported)("remote workspace snapshot retention", () => status: "resolved", outcome: "restored", resolutionNote: "Verified saved files" }); expect(resolved?.status).toBe("resolved"); try { - await vi.waitFor(() => expect(secondDeleteHeld).toBe(true)); + await vi.waitFor(() => expect(secondDeleteHeld).toBe(true), { timeout: 4000 }); expect((await storage.headObject(f.companyId, f.keys[0]!)).exists).toBe(false); expect((await storage.headObject(f.companyId, f.keys[1]!)).exists).toBe(true); expect((await db.select().from(executionWorkspaceSnapshots).where(eq(executionWorkspaceSnapshots.id, f.row.id)))[0]) @@ -422,7 +514,7 @@ describe.skipIf(!support.supported)("remote workspace snapshot retention", () => expect(await owner.nextDeadlineAt()).toBeNull(); expect(idleWorkSnapshot().active).toBe(0); expect(coordinator.nextWakeAt()).toBeNull(); - }); + }, { timeout: 4000 }); } finally { releaseSecondDelete(); await worker.stop(); await coordinator.stop(); } }); }); diff --git a/server/src/services/remote-workspace-snapshot-retention.ts b/server/src/services/remote-workspace-snapshot-retention.ts index 904558671c2..54da5e93e72 100644 --- a/server/src/services/remote-workspace-snapshot-retention.ts +++ b/server/src/services/remote-workspace-snapshot-retention.ts @@ -1,4 +1,5 @@ -import { and, asc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm"; +import { and, asc, eq, exists, inArray, isNotNull, isNull, lte, ne, or, sql, type SQL } from "drizzle-orm"; +import { alias } from "drizzle-orm/pg-core"; import { executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, issueRecoveryActions, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority, type EnvironmentLease } from "@paperclipai/shared"; import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; @@ -10,6 +11,7 @@ import { logger } from "../middleware/logger.js"; export const REMOTE_WORKSPACE_SNAPSHOT_GRACE_MS = 7 * 86400_000; export const REMOTE_WORKSPACE_SNAPSHOT_RETRY_MS = 15 * 60_000; +export const REMOTE_WORKSPACE_SNAPSHOT_COALESCE_MS = 1_000; const SNAPSHOT_ABORT_CONCURRENCY = 8; type Snapshot = typeof executionWorkspaceSnapshots.$inferSelect; type Tx = Parameters[0]>[0]; @@ -58,56 +60,112 @@ function abandonedUploadOperationId(row: Snapshot) { return typeof abandoned?.operationId === "string" && abandoned.operationId === row.sourceOperationId ? abandoned.operationId : null; } -async function pinned(db: ReadDb, row: Snapshot) { - const [workspace] = await db.select({ id: executionWorkspaces.id, sourceIssueId: executionWorkspaces.sourceIssueId, - metadata: executionWorkspaces.metadata }).from(executionWorkspaces).where(and( - eq(executionWorkspaces.companyId, row.companyId), eq(executionWorkspaces.id, row.executionWorkspaceId), - )); - if ((workspace?.metadata?.remoteWorkspace as { snapshotId?: unknown } | undefined)?.snapshotId === row.id) return true; - const [importedBy] = await db.select({ id: executionWorkspaceSnapshots.id }).from(executionWorkspaceSnapshots).where(and( - eq(executionWorkspaceSnapshots.companyId, row.companyId), ne(executionWorkspaceSnapshots.status, "deleted"), - sql`${executionWorkspaceSnapshots.metadata} ? 'importedWorkspaceChildren'`, - sql`${executionWorkspaceSnapshots.metadata}->'importedWorkspaceChildren' @> ${JSON.stringify([ - { workspaceId: row.executionWorkspaceId, snapshotId: row.id }, - ])}::jsonb`, - )).limit(1); - if (importedBy) return true; - const [operation] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and( - eq(workspaceOperations.companyId, row.companyId), eq(workspaceOperations.executionWorkspaceId, row.executionWorkspaceId), - or(inArray(workspaceOperations.status, ["running", "pending"]), - // A failed save keeps its snapshot pinned for its retry, as while it ran, - // until the final save retires it. - sql`(${workspaceOperations.status} = 'failed' and ${workspaceOperations.metadata} ? 'lastFailure' - and ${workspaceOperations.metadata}->'retiredSave' is null - and ${workspaceOperations.id}::text is distinct from ${abandonedUploadOperationId(row)})`, - sql`(${workspaceOperations.metadata}->'saveWork'->>'schema' = 'paperclip.remote-workspace-save-work.v1' - and (${workspaceOperations.metadata}#>'{saveWork,unknown}' is distinct from 'false'::jsonb - or case when jsonb_typeof(${workspaceOperations.metadata}#>'{saveWork,activeIds}') = 'array' - then jsonb_array_length(${workspaceOperations.metadata}#>'{saveWork,activeIds}') <> 0 else true end))`), - sql`(${workspaceOperations.id} = ${row.sourceOperationId}::uuid - or ${workspaceOperations.metadata}->>'snapshotId' = ${row.id} - or ${workspaceOperations.metadata}->>'parentSnapshotId' = ${row.id})`, - )).limit(1); - if (operation) return true; - const [child] = await db.select({ id: executionWorkspaceSnapshots.id }).from(executionWorkspaceSnapshots).where(and( - eq(executionWorkspaceSnapshots.companyId, row.companyId), eq(executionWorkspaceSnapshots.executionWorkspaceId, row.executionWorkspaceId), - eq(executionWorkspaceSnapshots.parentSnapshotId, row.id), inArray(executionWorkspaceSnapshots.status, ["pending", "uploaded"]), - )).limit(1); - if (child) return true; - const [run] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, row.companyId), - inArray(heartbeatRuns.status, ["queued", "running"]), - sql`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'->>'workspaceId' = ${row.executionWorkspaceId}`, - sql`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'->>'snapshotId' = ${row.id}`, - )).limit(1); - if (run) return true; - const [recovery] = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and( - eq(issueRecoveryActions.companyId, row.companyId), inArray(issueRecoveryActions.status, ["active", "escalated"]), - sql`(${workspace?.sourceIssueId ? sql`${issueRecoveryActions.sourceIssueId} = ${workspace.sourceIssueId}::uuid` : sql`false`} - or ${issueRecoveryActions.evidence}->>'snapshotId' = ${row.id} - or ${issueRecoveryActions.evidence}->>'workspaceId' = ${row.executionWorkspaceId} - or ${issueRecoveryActions.evidence}->'remoteWorkspace'->>'snapshotId' = ${row.id})`, - )).limit(1); - return Boolean(recovery); +type Pin = { kind: "workspace" } | { kind: "import" | "child"; snapshotId: string } | { kind: "operation"; operationId: string } + | { kind: "run"; runId: string } | { kind: "recovery"; actionId: string }; +type PinRow = { companyId: SQL; id: SQL; workspaceId: SQL; sourceOperationId: SQL; abandonedOperationId: SQL; sourceIssueId: SQL; importedChild: SQL }; +const RETENTION_PIN = "retentionPin"; +const UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; +const pinSource = alias(executionWorkspaceSnapshots, "retention_pin_source"); +const snapshot = executionWorkspaceSnapshots; + +function literalPinRow(row: Snapshot, sourceIssueId: string | null | undefined): PinRow { + return { companyId: sql`${row.companyId}::uuid`, id: sql`${row.id}::uuid`, workspaceId: sql`${row.executionWorkspaceId}::uuid`, + sourceOperationId: sql`${row.sourceOperationId}::uuid`, abandonedOperationId: sql`${abandonedUploadOperationId(row)}::text`, + sourceIssueId: sourceIssueId ? sql`${sourceIssueId}::uuid` : sql`null::uuid`, + importedChild: sql`${JSON.stringify([{ workspaceId: row.executionWorkspaceId, snapshotId: row.id }])}::jsonb` }; +} + +const correlatedPinRow: PinRow = { + companyId: sql`${snapshot.companyId}`, id: sql`${snapshot.id}`, workspaceId: sql`${snapshot.executionWorkspaceId}`, + sourceOperationId: sql`${snapshot.sourceOperationId}`, + abandonedOperationId: sql`(case when ${snapshot.status} = 'delete_requested' + and ${snapshot.metadata}->'abandonedUpload'->>'operationId' = ${snapshot.sourceOperationId}::text + then ${snapshot.sourceOperationId}::text end)`, + sourceIssueId: sql`(select w.source_issue_id from ${executionWorkspaces} w + where w.company_id = ${snapshot.companyId} and w.id = ${snapshot.executionWorkspaceId})`, + importedChild: sql`jsonb_build_array(jsonb_build_object('workspaceId', ${snapshot.executionWorkspaceId}::text, 'snapshotId', ${snapshot.id}::text))`, +}; + +const importPin = (row: PinRow) => and(sql`${pinSource.companyId} = ${row.companyId}`, ne(pinSource.status, "deleted"), + sql`${pinSource.metadata} ? 'importedWorkspaceChildren'`, + sql`${pinSource.metadata}->'importedWorkspaceChildren' @> ${row.importedChild}`); + +const operationPin = (row: PinRow) => and(sql`${workspaceOperations.companyId} = ${row.companyId}`, + sql`${workspaceOperations.executionWorkspaceId} = ${row.workspaceId}`, + or(inArray(workspaceOperations.status, ["running", "pending"]), + sql`(${workspaceOperations.status} = 'failed' and ${workspaceOperations.metadata} ? 'lastFailure' + and ${workspaceOperations.metadata}->'retiredSave' is null + and ${workspaceOperations.id}::text is distinct from ${row.abandonedOperationId})`, + sql`(${workspaceOperations.metadata}->'saveWork'->>'schema' = 'paperclip.remote-workspace-save-work.v1' + and (${workspaceOperations.metadata}#>'{saveWork,unknown}' is distinct from 'false'::jsonb + or case when jsonb_typeof(${workspaceOperations.metadata}#>'{saveWork,activeIds}') = 'array' + then jsonb_array_length(${workspaceOperations.metadata}#>'{saveWork,activeIds}') <> 0 else true end))`), + sql`(${workspaceOperations.id} = ${row.sourceOperationId} + or ${workspaceOperations.metadata}->>'snapshotId' = ${row.id}::text + or ${workspaceOperations.metadata}->>'parentSnapshotId' = ${row.id}::text)`); + +const childPin = (row: PinRow) => and(sql`${pinSource.companyId} = ${row.companyId}`, + sql`${pinSource.executionWorkspaceId} = ${row.workspaceId}`, sql`${pinSource.parentSnapshotId} = ${row.id}`, + inArray(pinSource.status, ["pending", "uploaded"])); + +const runPin = (row: PinRow) => and(sql`${heartbeatRuns.companyId} = ${row.companyId}`, inArray(heartbeatRuns.status, ["queued", "running"]), + sql`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'->>'workspaceId' = ${row.workspaceId}::text`, + sql`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'->>'snapshotId' = ${row.id}::text`); + +const recoveryPin = (row: PinRow) => and(sql`${issueRecoveryActions.companyId} = ${row.companyId}`, + inArray(issueRecoveryActions.status, ["active", "escalated"]), + sql`(${issueRecoveryActions.sourceIssueId} = ${row.sourceIssueId} + or ${issueRecoveryActions.evidence}->>'snapshotId' = ${row.id}::text + or ${issueRecoveryActions.evidence}->>'workspaceId' = ${row.workspaceId}::text + or ${issueRecoveryActions.evidence}->'remoteWorkspace'->>'snapshotId' = ${row.id}::text)`); + +async function pinned(db: ReadDb, row: Snapshot): Promise { + const [workspace] = await db.select({ sourceIssueId: executionWorkspaces.sourceIssueId, metadata: executionWorkspaces.metadata }) + .from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, row.companyId), eq(executionWorkspaces.id, row.executionWorkspaceId))); + if ((workspace?.metadata?.remoteWorkspace as { snapshotId?: unknown } | undefined)?.snapshotId === row.id) return { kind: "workspace" }; + const ref = literalPinRow(row, workspace?.sourceIssueId); + const [importedBy] = await db.select({ id: pinSource.id }).from(pinSource).where(importPin(ref)).limit(1); + if (importedBy) return { kind: "import", snapshotId: importedBy.id }; + const [operation] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(operationPin(ref)).limit(1); + if (operation) return { kind: "operation", operationId: operation.id }; + const [child] = await db.select({ id: pinSource.id }).from(pinSource).where(childPin(ref)).limit(1); + if (child) return { kind: "child", snapshotId: child.id }; + const [run] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(runPin(ref)).limit(1); + if (run) return { kind: "run", runId: run.id }; + const [recovery] = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(recoveryPin(ref)).limit(1); + return recovery ? { kind: "recovery", actionId: recovery.id } : null; +} + +function recordedPinId(key: "snapshotId" | "operationId" | "runId" | "actionId") { + const value = sql`${snapshot.metadata}->${sql.raw(`'${RETENTION_PIN}'`)}->>${sql.raw(`'${key}'`)}`; + return sql`(case when ${value} ~* ${UUID_PATTERN} then (${value})::uuid end)`; +} + +function recordedPinHolds(db: Db) { + const row = correlatedPinRow; + return sql`(case ${snapshot.metadata}->${sql.raw(`'${RETENTION_PIN}'`)}->>'kind' + when 'workspace' then exists (select 1 from ${executionWorkspaces} w where w.company_id = ${row.companyId} + and w.id = ${row.workspaceId} and w.metadata->'remoteWorkspace'->>'snapshotId' = ${row.id}::text) + when 'import' then ${exists(db.select({ id: pinSource.id }).from(pinSource).where(and(eq(pinSource.id, recordedPinId("snapshotId")), importPin(row))))} + when 'operation' then ${exists(db.select({ id: workspaceOperations.id }).from(workspaceOperations) + .where(and(eq(workspaceOperations.id, recordedPinId("operationId")), operationPin(row))))} + when 'child' then ${exists(db.select({ id: pinSource.id }).from(pinSource).where(and(eq(pinSource.id, recordedPinId("snapshotId")), childPin(row))))} + when 'run' then ${exists(db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, recordedPinId("runId")), runPin(row))))} + when 'recovery' then ${exists(db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions) + .where(and(eq(issueRecoveryActions.id, recordedPinId("actionId")), recoveryPin(row))))} + else false end)`; +} + +function samePin(value: unknown, pin: Pin) { + if (!value || typeof value !== "object") return false; + const recorded = value as Record, entries = Object.entries(pin); + return Object.keys(recorded).length === entries.length && entries.every(([key, item]) => recorded[key] === item); +} + +function withoutPin(metadata: Snapshot["metadata"]) { + if (!metadata || !Object.hasOwn(metadata, RETENTION_PIN)) return {}; + const { [RETENTION_PIN]: _released, ...rest } = metadata; + return { metadata: rest }; } /** Producers wake this owner; pinned history carries no speculative retry. */ @@ -135,6 +193,7 @@ export function remoteWorkspaceSnapshotRetentionService(db: Db, options: { or(isNull(executionWorkspaceSnapshots.deleteAfter), lte(executionWorkspaceSnapshots.deleteAfter, at), eq(executionWorkspaceSnapshots.status, "committed")), + sql`not (${executionWorkspaceSnapshots.deleteAfter} is null and ${recordedPinHolds(db)})`, after ? sql`${executionWorkspaceSnapshots.id} > ${after}::uuid` : undefined, )).orderBy(asc(executionWorkspaceSnapshots.id)).limit(batch + 1); result.truncated = rows.length > batch; @@ -144,32 +203,38 @@ export function remoteWorkspaceSnapshotRetentionService(db: Db, options: { const claimed = await db.transaction(async tx => { const [row] = await tx.select().from(executionWorkspaceSnapshots).where(eq(executionWorkspaceSnapshots.id, candidate.id)).for("update"); if (!row || row.status === "deleted") return null; - if (await pinned(tx, row)) { + const pin = await pinned(tx, row); + if (pin) { result.pinned++; - const metadata = { ...row.metadata }; + const metadata: Record = { ...row.metadata, [RETENTION_PIN]: pin }; if (row.status === "superseded" && row.deleteAfter) metadata.retentionDueAt = row.deleteAfter.toISOString(); if (row.status === "committed") delete metadata.retentionDueAt; - if (row.deleteAfter) await tx.update(executionWorkspaceSnapshots).set({ deleteAfter: null, metadata }).where(eq(executionWorkspaceSnapshots.id, row.id)); + if (row.deleteAfter || !samePin(row.metadata?.[RETENTION_PIN], pin)) { + await tx.update(executionWorkspaceSnapshots).set({ deleteAfter: null, metadata }).where(eq(executionWorkspaceSnapshots.id, row.id)); + } return null; } const deadline = row.deleteAfter ?? (row.status === "superseded" ? date(row.metadata?.retentionDueAt) : null) ?? new Date((row.status === "pending" || row.status === "uploaded" ? row.createdAt.getTime() : at.getTime()) + REMOTE_WORKSPACE_SNAPSHOT_GRACE_MS); if (row.status !== "delete_requested" && deadline > at) { result.scheduled++; - await tx.update(executionWorkspaceSnapshots).set({ deleteAfter: deadline, + await tx.update(executionWorkspaceSnapshots).set({ deleteAfter: deadline, ...withoutPin(row.metadata), ...(row.status === "committed" ? { status: "superseded" as const } : {}) }).where(eq(executionWorkspaceSnapshots.id, row.id)); return null; } if (row.status === "delete_requested" && row.deleteAfter && row.deleteAfter > at) return null; - const [saved] = await tx.update(executionWorkspaceSnapshots).set({ status: "delete_requested", deleteAfter: at, lastError: null }) + const [saved] = await tx.update(executionWorkspaceSnapshots).set({ status: "delete_requested", deleteAfter: at, lastError: null, ...withoutPin(row.metadata) }) .where(eq(executionWorkspaceSnapshots.id, row.id)).returning(); return saved!; }); if (!claimed) continue; // New readers cannot adopt a delete_requested record. Recheck all // durable references immediately before any irreversible object I/O. - if (await pinned(db, claimed)) { - await db.update(executionWorkspaceSnapshots).set({ deleteAfter: null }).where(eq(executionWorkspaceSnapshots.id, claimed.id)); + const pin = await pinned(db, claimed); + if (pin) { + await db.update(executionWorkspaceSnapshots).set({ deleteAfter: null, + metadata: sql`coalesce(${executionWorkspaceSnapshots.metadata}, '{}'::jsonb) || ${JSON.stringify({ [RETENTION_PIN]: pin })}::jsonb` }) + .where(eq(executionWorkspaceSnapshots.id, claimed.id)); result.pinned++; continue; } const uploads = Array.isArray(claimed.metadata?.uploads) ? claimed.metadata.uploads : []; @@ -226,7 +291,7 @@ export function registerRemoteWorkspaceSnapshotRetentionWork( ) { let next: number | null = null; return coordinator.register(DELIVERY_QUEUES.remoteWorkspaceSnapshots, { - retryMs: REMOTE_WORKSPACE_SNAPSHOT_RETRY_MS, pausePassiveMaintenance: true, + retryMs: REMOTE_WORKSPACE_SNAPSHOT_RETRY_MS, coalesceMs: REMOTE_WORKSPACE_SNAPSHOT_COALESCE_MS, pausePassiveMaintenance: true, onSettled: () => service.resetCursor(), run: async signal => { next = null; const result = await service.tick(signal); onResult(result); next = result.truncated ? Date.now() + 1000 : await service.nextDeadlineAt(); }, diff --git a/server/src/services/tool-access-policy.ts b/server/src/services/tool-access-policy.ts index 839c2a43c54..3ee19aa3fd4 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -54,6 +54,13 @@ import { } from "./tool-profile-binding-precedence.js"; import { recordToolRuntimeAuditWriteFailure } from "./tool-runtime-metrics.js"; import { canonicalToolArguments, readSignedToolArgumentsPayload, toolRequestIdentityHash } from "./tool-content-guards.js"; +import { + compilePolicySelector, + indexPoliciesBySelector, + listValues, + type CompiledPolicySelector, + type PolicySelectorIndex, +} from "./tool-access/policy-selector-index.js"; class RejectedInvocationAdmission extends Error { constructor(readonly decision: ToolAccessDecision) { @@ -61,7 +68,7 @@ class RejectedInvocationAdmission extends Error { } } -type ToolAccessContext = { +export type ToolAccessContext = { companyId: string; actorType: "agent" | "user" | "system" | "plugin"; actorId: string; @@ -399,12 +406,6 @@ function decision( }; } -function listValues(value: unknown): string[] { - if (typeof value === "string" && value.trim()) return [value.trim()]; - if (!Array.isArray(value)) return []; - return value.filter((item): item is string => typeof item === "string" && item.trim().length > 0); -} - function asToolRiskLevel(value: unknown): ToolRiskLevel | null { if ( value === "low" @@ -420,7 +421,7 @@ function asToolRiskLevel(value: unknown): ToolRiskLevel | null { return null; } -function selectorMatches(selector: ToolAccessSelector | Record | null | undefined, ctx: ToolAccessContext): boolean { +export function selectorMatches(selector: ToolAccessSelector | Record | null | undefined, ctx: ToolAccessContext): boolean { if (!selector || Object.keys(selector).length === 0) return true; const s = selector as Record; // Tool/action names are exact selectors. Glob-looking values are treated as literal names. @@ -507,7 +508,7 @@ function timeWindowMatches(condition: Record, now: Date): boole return true; } -function policyConditions(policy: typeof toolPolicies.$inferSelect): ToolPolicyConditions | null { +export function policyConditions(policy: typeof toolPolicies.$inferSelect): ToolPolicyConditions | null { return isRecord(policy.conditions) && Object.keys(policy.conditions).length > 0 ? policy.conditions as ToolPolicyConditions : null; @@ -517,7 +518,7 @@ function conditionGroupFail(group: string, reason: string): PolicyConditionEvalu return { matched: false, matchedGroups: [], failedGroup: group, reason }; } -function evaluatePolicyConditions( +export function evaluatePolicyConditions( conditions: ToolPolicyConditions | null | undefined, ctx: ToolAccessContext, now = new Date(), @@ -623,6 +624,61 @@ function evaluatePolicyConditions( return { matched: true, matchedGroups }; } +type EnabledToolPolicy = { + policy: typeof toolPolicies.$inferSelect; + selector: CompiledPolicySelector; + conditions: ToolPolicyConditions | null; + conditionsCheck?: ReturnType; +}; + +/** + * Compiles a company's enabled policies, already in priority and createdAt + * order, once per decision batch: selectors are parsed once and policies are + * indexed so that each decision checks only the policies that can match it. + */ +export function indexEnabledToolPolicies( + policies: ReadonlyArray, +): PolicySelectorIndex { + return indexPoliciesBySelector( + policies.map((policy) => ({ policy, selector: compilePolicySelector(policy.selectors), conditions: policyConditions(policy) })), + (entry) => entry.selector, + ); +} + +export type EnabledToolPolicyMatch = + | { unsupportedConditions: { policy: typeof toolPolicies.$inferSelect; issues: Array<{ path: string; message: string }> } } + | { matching: Array<{ policy: typeof toolPolicies.$inferSelect; conditionEvaluation: PolicyConditionEvaluation }> }; + +/** + * The enabled policies that apply to one call, in evaluation order. The first + * selected policy with conditions the runtime cannot evaluate wins over every + * match, so the caller denies the call. + */ +export function matchEnabledToolPolicies( + index: PolicySelectorIndex, + ctx: ToolAccessContext, +): EnabledToolPolicyMatch { + const selected = index.candidates(ctx).filter((entry) => entry.selector.matches(ctx)); + for (const entry of selected) { + if (!entry.conditions) continue; + entry.conditionsCheck ??= toolPolicyConditionsSchema.safeParse(entry.conditions); + if (!entry.conditionsCheck.success) { + return { + unsupportedConditions: { + policy: entry.policy, + issues: entry.conditionsCheck.error.issues.map((issue) => ({ path: issue.path.join("."), message: issue.message })), + }, + }; + } + } + const matching = []; + for (const { policy, conditions } of selected) { + const conditionEvaluation = evaluatePolicyConditions(conditions, ctx); + if (conditionEvaluation.matched) matching.push({ policy, conditionEvaluation }); + } + return { matching }; +} + function profileEntryMatches(entry: typeof toolProfileEntries.$inferSelect, ctx: ToolAccessContext): boolean { const selected = entry.selectorType === "application" ? entry.applicationId === ctx.applicationId : entry.selectorType === "connection" ? entry.connectionId === ctx.connectionId @@ -1550,38 +1606,29 @@ export function toolAccessPolicyService(db: Pick entry.effect === "exclude") && (profile.defaultAction === "allow" || matchingEntries.some((entry) => entry.effect === "include")); }); - const policies = await cachedRead(cache, `enabled-policies:${ctx.companyId}`, async () => - db.select().from(toolPolicies).where(and(eq(toolPolicies.companyId, ctx.companyId), eq(toolPolicies.enabled, true))).orderBy(asc(toolPolicies.priority), asc(toolPolicies.createdAt))); - for (const policy of policies) { - const conditions = policyConditions(policy); - if (conditions && selectorMatches(policy.selectors, ctx)) { - const parsed = toolPolicyConditionsSchema.safeParse(conditions); - if (!parsed.success) { - return decision( - "deny", - "deny_policy_block", - "Tool access denied because a matching policy uses unsupported runtime conditions.", - effectiveProfileIds, - [policy.id], - { - redactionPlan: redaction.redactionPlan, - policyExplanation: { - policyId: policy.id, - policyType: policy.policyType, - selectorMatched: true, - conditionsError: parsed.error.issues.map((issue) => ({ - path: issue.path.join("."), - message: issue.message, - })), - }, - }, - ); - } - } + const enabledPolicies = await cachedRead(cache, `enabled-policies:${ctx.companyId}`, async () => indexEnabledToolPolicies( + await db.select().from(toolPolicies).where(and(eq(toolPolicies.companyId, ctx.companyId), eq(toolPolicies.enabled, true))).orderBy(asc(toolPolicies.priority), asc(toolPolicies.createdAt)))); + const policyMatch = matchEnabledToolPolicies(enabledPolicies, ctx); + if ("unsupportedConditions" in policyMatch) { + const { policy, issues } = policyMatch.unsupportedConditions; + return decision( + "deny", + "deny_policy_block", + "Tool access denied because a matching policy uses unsupported runtime conditions.", + effectiveProfileIds, + [policy.id], + { + redactionPlan: redaction.redactionPlan, + policyExplanation: { + policyId: policy.id, + policyType: policy.policyType, + selectorMatched: true, + conditionsError: issues, + }, + }, + ); } - const matchingPolicies = policies - .map((policy) => ({ policy, conditionEvaluation: evaluatePolicyConditions(policyConditions(policy), ctx) })) - .filter(({ policy, conditionEvaluation }) => selectorMatches(policy.selectors, ctx) && conditionEvaluation.matched); + const matchingPolicies = policyMatch.matching; const explicitBlock = matchingPolicies.find(({ policy }) => policy.policyType === "block"); for (const { policy, conditionEvaluation } of matchingPolicies) { const policyExplanation = { diff --git a/server/src/services/tool-access/oauth/client-credentials-service.ts b/server/src/services/tool-access/oauth/client-credentials-service.ts index 3ef09066467..880fd550c93 100644 --- a/server/src/services/tool-access/oauth/client-credentials-service.ts +++ b/server/src/services/tool-access/oauth/client-credentials-service.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; import { and, eq, ne, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { connectionGrants, toolApplications, toolConnections } from "@paperclipai/db"; @@ -253,6 +254,19 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { * recorded at setup. If the MCP server now advertises other services and not * that one, refuse rather than follow it. */ + /** + * The signing algorithms the pinned sign-in service accepts. Connections set + * up before this was saved reload it from that same issuer's metadata. + */ + async function acceptedSigningAlgorithms(oauth: Record, settings: ClientCredentialsSettings): Promise { + if (Array.isArray(oauth.tokenEndpointAuthSigningAlgValuesSupported)) { + return normalizeOauthScopes(oauth.tokenEndpointAuthSigningAlgValuesSupported); + } + if (!settings.issuer) return []; + const reloaded = await signInServiceMetadata(settings.issuer).catch(() => null); + return reloaded?.signingAlgorithms ?? []; + } + async function assertPinnedSignInService(connection: typeof toolConnections.$inferSelect, settings: ClientCredentialsSettings) { if (!settings.issuer) return; const serverUrl = typeof connection.config.url === "string" ? connection.config.url : null; @@ -390,24 +404,60 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { return { secretId: secret.id, versionSelector: "latest", configPath, required: false, label }; } + type ConnectionPatch = Partial; + + /** + * One locked commit: the connection must still sign in the way `previous` + * did (same method, key and credential references) and not be removed. Any + * new credential is written in the same transaction, so a client ID and its + * secret always land together or not at all. + */ async function saveConnection( previous: typeof toolConnections.$inferSelect, - patch: Partial, + patch: ConnectionPatch | ((written: Record) => ConnectionPatch), + credentials: Array<{ configPath: string; label: string; value: string; required?: boolean }> = [], + actor?: ActorInfo, ) { - // Commit only if nothing that decides how this connection signs in changed - // since it was read (a rotation or another test), and it was not removed. - const clientAuth = asRecord(oauthConfig(previous).clientAuth); - const [updated] = await db.update(toolConnections) - .set({ ...patch, ...(patch.config ? { transportConfig: patch.config } : {}), updatedAt: now() }) - .where(and( - eq(toolConnections.id, previous.id), - eq(toolConnections.companyId, previous.companyId), - ne(toolConnections.status, "archived"), - sql`coalesce(${toolConnections.config} -> 'oauth' -> 'clientAuth', '{}'::jsonb) = ${JSON.stringify(clientAuth)}::jsonb`, - sql`${toolConnections.credentialSecretRefs} = ${JSON.stringify(previous.credentialSecretRefs)}::jsonb`, - )) - .returning(); - if (!updated) throw machineSignInChangedError(); + // Everything that decides who this connection signs in as. Writes rotate + // vault entries in place (same secret ID), so a revision counter, bumped by + // every commit, catches a concurrent change the references alone would miss. + const signInState = (row: typeof toolConnections.$inferSelect) => { + const oauth = oauthConfig(row); + return JSON.stringify([asRecord(oauth.clientAuth), oauth.clientId ?? null, oauth.credentialRevision ?? 0, row.credentialSecretRefs]); + }; + // Take the company's secret-write lock before any database lock and hold it + // through commit. Each vault write takes it too (re-entrantly here); taking + // it per write inside this transaction could deadlock with a token refresh + // that holds it while waiting on a row this transaction has locked. + const updated = await withAccountHomeSecretMutationLock(undefined, previous.companyId, () => db.transaction(async (tx) => { + const [locked] = await tx.select().from(toolConnections) + .where(and(eq(toolConnections.id, previous.id), eq(toolConnections.companyId, previous.companyId))) + .for("update"); + if (!locked || locked.status === "archived" || signInState(locked) !== signInState(previous)) { + throw machineSignInChangedError(); + } + const written: Record = {}; + for (const credential of credentials) { + const existing = locked.credentialSecretRefs.find((ref) => ref.configPath === credential.configPath); + const { secret } = await writeConnectionCredential(tx, { + companyId: locked.companyId, connectionName: locked.name, configPath: credential.configPath, + label: credential.label, value: credential.value, existingRef: existing, actor: actorForSecret(actor), + }); + written[credential.configPath] = { + secretId: secret.id, versionSelector: "latest", configPath: credential.configPath, + required: credential.required ?? false, label: credential.label, + }; + } + const resolved = typeof patch === "function" ? patch(written) : patch; + const baseConfig = resolved.config ?? locked.config; + const revision = Number(oauthConfig(locked).credentialRevision ?? 0) + 1; + const config = { ...baseConfig, oauth: { ...asRecord(asRecord(baseConfig).oauth), credentialRevision: revision } }; + const [row] = await tx.update(toolConnections) + .set({ ...resolved, config, transportConfig: config, updatedAt: now() }) + .where(eq(toolConnections.id, locked.id)) + .returning(); + return row!; + })); await store.syncCredentialBindings(updated); if (updated.status === "active") await deps.ensureDefaultOrganizationGrant(updated); emitConnectionUpdated(updated, previous, "gallery"); @@ -452,6 +502,7 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { scopes: scopesFrom(input.scopes) ?? [], clientId: input.clientId ?? null, tokenEndpointAuthMethodsSupported: service.authMethods, + tokenEndpointAuthSigningAlgValuesSupported: service.signingAlgorithms, clientAuth: { method: authMethod, ...(generated ? { key: generated.publicKey } : {}), configuredAt: createdAt.toISOString() }, }; @@ -546,20 +597,6 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { // failed retest must leave a working connection's credentials untouched. await deps.probeServerWithToken(connection, `Bearer ${token.accessToken}`, actor); // The settings worked: keep them. - const credentialSecretRefs = [...connection.credentialSecretRefs]; - if (input.clientSecret) { - const existing = credentialSecretRefs.find((ref) => ref.configPath === CLIENT_SECRET_PATH); - const ref = await writeVaultCredential(connection, CLIENT_SECRET_PATH, "Machine sign-in client secret", input.clientSecret, actor, existing); - if (!existing) credentialSecretRefs.push(ref); - } - const accessRef = await store.createOrRotateOAuthSecret({ - companyId, - connection, - configPath: "oauth.access_token", - label: "OAuth access token", - value: token.accessToken, - actor, - }); const at = now(); const expiresAt = token.expiresIn ? new Date(at.getTime() + token.expiresIn * 1000).toISOString() : null; const oauth = oauthConfig(connection); @@ -576,19 +613,35 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { refreshedAt: at.toISOString(), }, }; - connection = await saveConnection(connection, { - config: nextConfig, - credentialSecretRefs: [...credentialSecretRefs.filter((ref) => ref.configPath !== "oauth.access_token"), accessRef], - credentialRefs: [ - ...connection.credentialRefs.filter((ref) => ref.name !== "oauth.access_token"), - { name: "oauth.access_token", secretId: accessRef.secretId, version: "latest", placement: "header", key: "Authorization", prefix: "Bearer " }, - ], - }); + // The new token, any replacement secret and the settings commit together, + // after the check that nothing changed: a refused test changes nothing. + connection = await saveConnection(connection, (written) => { + const accessRef = written["oauth.access_token"]!; + const secretRef = written[CLIENT_SECRET_PATH]; + return { + config: nextConfig, + credentialSecretRefs: [ + ...connection.credentialSecretRefs.filter((ref) => + ref.configPath !== "oauth.access_token" && (!secretRef || ref.configPath !== CLIENT_SECRET_PATH)), + ...(secretRef ? [secretRef] : []), + accessRef, + ], + credentialRefs: [ + ...connection.credentialRefs.filter((ref) => ref.name !== "oauth.access_token"), + { name: "oauth.access_token", secretId: accessRef.secretId, version: "latest", placement: "header", key: "Authorization", prefix: "Bearer " }, + ], + }; + }, [ + { configPath: "oauth.access_token", label: "OAuth access token", value: token.accessToken, required: true }, + ...(input.clientSecret ? [{ configPath: CLIENT_SECRET_PATH, label: "Machine sign-in client secret", value: input.clientSecret }] : []), + ], actor); // The organization grant is what tool calls run on; give it the token now, // with this token's expiry (the grant's own expiry wins over the connection's). await deps.ensureDefaultOrganizationGrant(connection); await db.update(connectionGrants).set({ - providerTenant: sql`jsonb_set(coalesce(${connectionGrants.providerTenant}, '{}'::jsonb), '{oauth}', (coalesce(${connectionGrants.providerTenant}->'oauth', '{}'::jsonb) || ${JSON.stringify({ accessTokenExpiresAt: expiresAt, tokenType: token.tokenType, refreshedAt: at.toISOString() })}::jsonb) - 'refreshLease')`, + providerTenant: sql`jsonb_set(coalesce(${connectionGrants.providerTenant}, '{}'::jsonb), '{oauth}', (coalesce(${connectionGrants.providerTenant}->'oauth', '{}'::jsonb) || ${JSON.stringify({ accessTokenExpiresAt: expiresAt, tokenType: token.tokenType, refreshedAt: at.toISOString() })}::jsonb) + -- A live refresh keeps its lease; one abandoned by a stopped server is cleared with the tested credentials. + - (case when (${connectionGrants.providerTenant} #>> '{oauth,refreshLease,expiresAt}')::timestamptz <= ${at.toISOString()}::timestamptz then 'refreshLease' else '' end))`, updatedAt: now(), }).where(and( eq(connectionGrants.companyId, companyId), @@ -647,27 +700,25 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { : settings.authMethod; await assertPinnedSignInService(connection, settings); await requestClientCredentialsToken(connection, actor, { clientSecret: input.clientSecret, authMethod }); - const existing = connection.credentialSecretRefs.find((ref) => ref.configPath === CLIENT_SECRET_PATH); - const ref = await writeVaultCredential(connection, CLIENT_SECRET_PATH, "Machine sign-in client secret", input.clientSecret, actor, existing); const retired = connection.credentialSecretRefs.filter((candidate) => candidate.configPath === CLIENT_PRIVATE_KEY_PATH || candidate.configPath === CLIENT_PRIVATE_KEY_NEXT_PATH); - const updated = await saveConnection(connection, { + const updated = await saveConnection(connection, (written) => ({ config: { ...connection.config, oauth: { ...oauth, clientAuth: { method: authMethod, configuredAt: now().toISOString() } } }, credentialSecretRefs: [ ...connection.credentialSecretRefs.filter((candidate) => candidate.configPath !== CLIENT_SECRET_PATH && !retired.includes(candidate)), - ref, + written[CLIENT_SECRET_PATH]!, ], - }); + }), [{ configPath: CLIENT_SECRET_PATH, label: "Machine sign-in client secret", value: input.clientSecret }], actor); for (const old of retired) await secrets.remove(old.secretId).catch(() => undefined); return { connectionId, connection: toConnection(updated), machineSignIn: machineSignInStatus(updated), completed: true }; } - const generated = await generateClientKeyPair(settings.key?.algorithm ?? "RS256", now()); - const existing = connection.credentialSecretRefs.find((ref) => ref.configPath === CLIENT_PRIVATE_KEY_NEXT_PATH); - const ref = await writeVaultCredential(connection, CLIENT_PRIVATE_KEY_NEXT_PATH, "Machine sign-in replacement key", generated.privateKeyPem, actor, existing); - const updated = await saveConnection(connection, { + // Keep the current key's algorithm; switching from a secret uses what the sign-in service accepts. + const algorithm = settings.key?.algorithm ?? chooseAssertionAlgorithm(await acceptedSigningAlgorithms(oauth, settings)); + const generated = await generateClientKeyPair(algorithm, now()); + const updated = await saveConnection(connection, (written) => ({ config: { ...connection.config, oauth: { ...oauth, clientAuth: { ...clientAuth, pendingKey: generated.publicKey } } }, - credentialSecretRefs: [...connection.credentialSecretRefs.filter((candidate) => candidate.configPath !== CLIENT_PRIVATE_KEY_NEXT_PATH), ref], - }); + credentialSecretRefs: [...connection.credentialSecretRefs.filter((candidate) => candidate.configPath !== CLIENT_PRIVATE_KEY_NEXT_PATH), written[CLIENT_PRIVATE_KEY_NEXT_PATH]!], + }), [{ configPath: CLIENT_PRIVATE_KEY_NEXT_PATH, label: "Machine sign-in replacement key", value: generated.privateKeyPem }], actor); return { connectionId, connection: toConnection(updated), machineSignIn: machineSignInStatus(updated), completed: false }; } @@ -695,7 +746,7 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { }); const pendingRef = connection.credentialSecretRefs.find((ref) => ref.configPath === CLIENT_PRIVATE_KEY_NEXT_PATH); // One locked step: the row still stages this key, then the vault and config change together. - const updated = await db.transaction(async (tx) => { + const updated = await withAccountHomeSecretMutationLock(undefined, companyId, () => db.transaction(async (tx) => { const [locked] = await tx.select().from(toolConnections) .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId))) .for("update"); @@ -712,7 +763,11 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { const lockedOauth = oauthConfig(locked); const nextConfig = { ...locked.config, - oauth: { ...lockedOauth, clientAuth: { method: "private_key_jwt", key: promoted, configuredAt: now().toISOString() } }, + oauth: { + ...lockedOauth, + clientAuth: { method: "private_key_jwt", key: promoted, configuredAt: now().toISOString() }, + credentialRevision: Number(lockedOauth.credentialRevision ?? 0) + 1, + }, }; const [row] = await tx.update(toolConnections).set({ config: nextConfig, @@ -725,7 +780,7 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) { updatedAt: now(), }).where(eq(toolConnections.id, locked.id)).returning(); return row!; - }); + })); await store.syncCredentialBindings(updated); if (updated.status === "active") await deps.ensureDefaultOrganizationGrant(updated); emitConnectionUpdated(updated, connection, "gallery"); diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index e3ee3c79d95..1754f2c43be 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -1,6 +1,7 @@ import { notifyGitHubCredentialChange } from "../../github-connection-notifications.js"; import { writeToolConnectionHealthChange } from "../../tool-connection-health-notifications.js"; -import type { ActorInfo } from "../types.js"; +import type { ActorInfo, DbTransaction } from "../types.js"; +import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; import { createOAuthClientProtocol, storedOAuthTokenEndpointAuthMethod } from "./client.js"; import { oauthConfig, normalizeOauthScopes, resolveGrantedOauthScopes } from "./metadata.js"; import { googleWorkspaceEffectiveScopes, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; @@ -478,7 +479,7 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo : undefined, }); } - const accessRef = await createOrRotateOAuthSecret({ + const writeAccessToken = (client?: DbTransaction) => createOrRotateOAuthSecret({ companyId: connection.companyId, connection, configPath: "oauth.access_token", @@ -491,14 +492,18 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo grant.kind === "user" ? (grant.subjectUserId ?? undefined) : undefined, - }); - const nextCredentialSecretRefs = [ + }, client ? { dbClient: client, secretClient: secretService(client) } : undefined); + // Machine sign-in may take over a lease abandoned by a paused server, so + // its token is written only inside the commit that proves this refresh + // still owns the lease (below). Other grants keep their existing order. + const accessRef = machineSignIn ? null : await writeAccessToken(); + const credentialSecretRefsWith = (access: ToolCredentialSecretRef) => [ ...grant.credentialSecretRefs.filter( (ref) => ref.configPath !== "oauth.access_token" && (!nextRefreshRef || ref.configPath !== "oauth.refresh_token"), ), - accessRef, + access, ...(nextRefreshRef ? [nextRefreshRef] : []), ]; const expiresAt = token.expiresIn @@ -540,11 +545,11 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo tokenType: token.tokenType, refreshedAt: now().toISOString(), }; - const [updated] = await writeToolConnectionHealthChange(db, connection, tx => tx + const commitGrant = (tx: Db, access: ToolCredentialSecretRef) => tx .update(connectionGrants) .set({ providerTenant: sql`jsonb_set(coalesce(${connectionGrants.providerTenant}, '{}'::jsonb), '{oauth}', (coalesce(${connectionGrants.providerTenant}->'oauth', '{}'::jsonb) || ${JSON.stringify(oauthUpdates)}::jsonb) - 'refreshLease')`, - credentialSecretRefs: nextCredentialSecretRefs, + credentialSecretRefs: credentialSecretRefsWith(access), status: "active", updatedAt: now(), }) @@ -556,7 +561,22 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo sql`${connectionGrants.providerTenant} -> 'oauth' -> 'refreshLease' ->> 'id' = ${lease.leaseId}`, ), ) - .returning()); + .returning(); + const [updated] = machineSignIn + ? await withAccountHomeSecretMutationLock(undefined, connection.companyId, () => + writeToolConnectionHealthChange(db, connection, async (tx) => { + const [owned] = await tx.select({ id: connectionGrants.id }).from(connectionGrants) + .where(and( + eq(connectionGrants.id, grant.id), + eq(connectionGrants.companyId, grant.companyId), + eq(connectionGrants.status, "active"), + sql`${connectionGrants.providerTenant} -> 'oauth' -> 'refreshLease' ->> 'id' = ${lease.leaseId}`, + )) + .for("update"); + if (!owned) return []; + return commitGrant(tx, await writeAccessToken(tx as unknown as DbTransaction)); + })) + : await writeToolConnectionHealthChange(db, connection, (tx) => commitGrant(tx, accessRef!)); if (!updated) { throw conflict( "OAuth credentials changed while refresh was in progress. Retry the request.", @@ -615,7 +635,7 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo ), ); const nextKeys = new Set( - nextCredentialSecretRefs.map( + updated.credentialSecretRefs.map( (ref) => `${ref.secretId}:${ref.configPath}`, ), ); diff --git a/server/src/services/tool-access/oauth/refresh-leases.ts b/server/src/services/tool-access/oauth/refresh-leases.ts index c3040b8828d..f3f4323d52c 100644 --- a/server/src/services/tool-access/oauth/refresh-leases.ts +++ b/server/src/services/tool-access/oauth/refresh-leases.ts @@ -1,4 +1,5 @@ import { oauthConfig } from "./metadata.js"; +import { usesClientCredentials } from "./client-credentials.js"; import { randomUUID } from "node:crypto"; import { and, eq, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -267,6 +268,33 @@ export function createOAuthRefreshLeases(db: Db, now: () => Date, getConnectionR .returning(); if (claimed) return { grant: claimed, leaseId }; } + if (currentLeaseId && !leaseIsActive && usesClientCredentials(connection)) { + // Machine sign-in has no refresh token that an interrupted refresh + // could have consumed, so an abandoned lease is safe to take over: + // the next request simply asks for a new token. + const leaseId = randomUUID(); + const providerTenant = { + ...(latest.providerTenant ?? {}), + oauth: { + ...withoutOAuthGrantRefreshLease(oauth), + refreshLease: { id: leaseId, expiresAt: new Date(Date.now() + OAUTH_REFRESH_LEASE_MS).toISOString() }, + }, + }; + const [claimed] = await db + .update(connectionGrants) + .set({ providerTenant, updatedAt: now() }) + .where( + and( + eq(connectionGrants.id, latest.id), + eq(connectionGrants.companyId, latest.companyId), + eq(connectionGrants.status, "active"), + sql`${connectionGrants.providerTenant} #>> '{oauth,refreshLease,id}' = ${currentLeaseId}`, + ), + ) + .returning(); + if (claimed) return { grant: claimed, leaseId }; + continue; + } if (currentLeaseId && !leaseIsActive) { throw unprocessable( "The previous OAuth refresh did not finish. Reconnect this app before retrying.", diff --git a/server/src/services/tool-access/policy-selector-index.ts b/server/src/services/tool-access/policy-selector-index.ts new file mode 100644 index 00000000000..178f5ab3dcb --- /dev/null +++ b/server/src/services/tool-access/policy-selector-index.ts @@ -0,0 +1,160 @@ +/** + * Compiled tool-policy selectors and the per-company policy index. + * + * A tools/list decision runs once per listed tool. Matching every enabled + * policy's raw selector for every tool made each listing cost tools x policies + * selector checks on the main thread. Compiling the selectors once per decision + * batch and indexing policies by the selector key that rejects most + * (catalogEntryId, then toolName) limits each decision to the policies that can + * match the tool. The compiled matcher has the same semantics as the raw + * selector match in tool-access-policy.ts. + */ + +export type PolicySelectorContext = { + actorType: string; + agentId: string | null; + projectId: string | null; + routineId: string | null; + issueId: string | null; + gatewayId: string | null; + applicationId: string | null; + connectionId: string | null; + catalogEntryId: string | null; + applicationKey: string | null; + providerType: string | null; + toolName: string; + upstreamToolName: string | null; + riskLevel: string | null; +}; + +type ExactKey = Exclude; + +// Selector key pairs matched against one context value each. +const EXACT_SELECTOR_KEYS: ReadonlyArray = [ + ["actorType", "actorTypes"], + ["agentId", "agentIds"], + ["projectId", "projectIds"], + ["routineId", "routineIds"], + ["issueId", "issueIds"], + ["gatewayId", "gatewayIds"], + ["applicationId", "applicationIds"], + ["connectionId", "connectionIds"], + ["catalogEntryId", "catalogEntryIds"], + ["applicationKey", "applicationKeys"], + ["providerType", "providerTypes"], + ["riskLevel", "riskLevels"], +]; + +export function listValues(value: unknown): string[] { + if (typeof value === "string" && value.trim()) return [value.trim()]; + if (!Array.isArray(value)) return []; + return value.filter((item): item is string => typeof item === "string" && item.trim().length > 0); +} + +type Constraint = { single: string | null; many: string[] }; + +export type CompiledPolicySelector = { + matches(ctx: PolicySelectorContext): boolean; + /** Values the context catalogEntryId must equal, or null when unconstrained. */ + readonly catalogEntryIds: readonly string[] | null; + /** Values one of the context tool names must equal, or null when unconstrained. */ + readonly toolNames: readonly string[] | null; +}; + +function constraint(selector: Record, singleKey: string, pluralKey: string): Constraint | null { + const raw = selector[singleKey]; + // An empty single value does not constrain, as in the raw selector match. + const single = typeof raw === "string" && raw ? raw : null; + const many = listValues(selector[pluralKey]); + return single || many.length > 0 ? { single, many } : null; +} + +function indexValues(value: Constraint | null): string[] | null { + if (!value) return null; + return value.single ? [value.single] : [...new Set(value.many)]; +} + +export function compilePolicySelector(selector: unknown): CompiledPolicySelector { + const s: Record = selector && typeof selector === "object" ? selector as Record : {}; + const exact: Array<{ key: ExactKey } & Constraint> = []; + let catalogEntry: Constraint | null = null; + for (const [singleKey, pluralKey] of EXACT_SELECTOR_KEYS) { + const value = constraint(s, singleKey, pluralKey); + if (!value) continue; + exact.push({ key: singleKey, ...value }); + if (singleKey === "catalogEntryId") catalogEntry = value; + } + const toolName = constraint(s, "toolName", "toolNames"); + return { + catalogEntryIds: indexValues(catalogEntry), + toolNames: indexValues(toolName), + matches(ctx) { + for (const { key, single, many } of exact) { + const actual = ctx[key]; + if (single && actual !== single) return false; + if (many.length > 0 && !(actual && many.includes(actual))) return false; + } + if (toolName) { + const { single, many } = toolName; + // Constraint values are never empty, so an empty context name never matches. + const names = [ctx.toolName, ctx.upstreamToolName]; + if (single && !names.includes(single)) return false; + if (many.length > 0 && !many.some((value) => names.includes(value))) return false; + } + return true; + }, + }; +} + +export type PolicySelectorIndex = { + readonly entries: readonly T[]; + /** Entries whose selector can match the context, in their original order. */ + candidates(ctx: PolicySelectorContext): T[]; +}; + +/** + * Indexes entries (already in evaluation order) by catalogEntryId, then by + * toolName for entries without a catalogEntryId selector. Entries with neither + * are candidates for every context. A context that a selector rejects on its + * index key can never match it, so leaving it out changes no decision. + */ +export function indexPoliciesBySelector( + entries: readonly T[], + selectorOf: (entry: T) => CompiledPolicySelector, +): PolicySelectorIndex { + const byCatalogEntryId = new Map(); + const byToolName = new Map(); + const unindexed: number[] = []; + const add = (buckets: Map, keys: readonly string[], position: number) => { + for (const key of keys) { + const bucket = buckets.get(key); + if (bucket) bucket.push(position); + else buckets.set(key, [position]); + } + }; + entries.forEach((entry, position) => { + const selector = selectorOf(entry); + if (selector.catalogEntryIds) add(byCatalogEntryId, selector.catalogEntryIds, position); + else if (selector.toolNames) add(byToolName, selector.toolNames, position); + else unindexed.push(position); + }); + return { + entries, + candidates(ctx) { + const lists: number[][] = []; + if (ctx.catalogEntryId) { + const bucket = byCatalogEntryId.get(ctx.catalogEntryId); + if (bucket) lists.push(bucket); + } + for (const name of new Set([ctx.toolName, ctx.upstreamToolName])) { + const bucket = name ? byToolName.get(name) : undefined; + if (bucket) lists.push(bucket); + } + if (unindexed.length > 0) lists.push(unindexed); + if (lists.length === 0) return []; + if (lists.length === 1) return lists[0]!.map((position) => entries[position]!); + const positions = [...new Set(lists.flat())].sort((left, right) => left - right); + return positions.map((position) => entries[position]!); + }, + }; +} diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx index 4c5286945fe..0e3f04c5abb 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -3552,7 +3552,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { items={tailItems} emptyMessage={ tailStatus === "queued" - ? "Waiting to start..." + ? undefined : (liveRun && liveRun.id === tailRunId ? liveRun.currentStatusMessage : null) || diff --git a/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx b/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx index 0864dfd42a7..a79889ab350 100644 --- a/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx +++ b/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx @@ -99,6 +99,7 @@ describe("TaskChatRunnerTurn", () => { ["agent_setup_failed", "Agent setup needs attention"], ["server_restarting", "Waiting for server restart"], ["previous_run_settling", "Waiting for previous run to stop"], + ["routine_execution_in_progress", "Waiting for PAP-5656 to finish"], ])("shows the server's %s wait while admission is held", (cause, label) => { render([], "queued", "run-1", undefined, false, false, { phase: "queued", label, cause, @@ -107,7 +108,8 @@ describe("TaskChatRunnerTurn", () => { permittedActions: ["inspect_run"], predecessorRunId: null, successorRunId: null, }); expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain(label); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent).toBe(label); + expect(container.textContent?.split(label)).toHaveLength(2); + expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); expect(container.textContent).not.toContain("Thinking"); }); @@ -123,7 +125,8 @@ describe("TaskChatRunnerTurn", () => { expect(container.textContent).not.toContain("Waiting to start"); act(() => { vi.advanceTimersByTime(2_000); }); expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Waiting to start"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent).toBe("Waiting to start"); + expect(container.textContent?.split("Waiting to start")).toHaveLength(2); + expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); expect(container.textContent).not.toContain("Working"); } finally { vi.useRealTimers(); diff --git a/ui/src/components/task-chat/TaskChatRunnerTurn.tsx b/ui/src/components/task-chat/TaskChatRunnerTurn.tsx index 3b1b6780087..8fed3a440d0 100644 --- a/ui/src/components/task-chat/TaskChatRunnerTurn.tsx +++ b/ui/src/components/task-chat/TaskChatRunnerTurn.tsx @@ -338,8 +338,7 @@ export function TaskChatRunnerTurn({ /> ) : null} - {/* The header's waiting line already names the agent's queue; no second line. */} - {!final && currentActivityItems.length === 0 && !agentQueueWaitFor({ status, execution }) + {!final && currentActivityItems.length === 0 && !(status === "queued" && runId && (waitingLabel || agentQueueWaitFor({ status, execution }))) ? : null} ); diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index aa311babc4b..14f866a0215 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -2834,7 +2834,7 @@ function StandardConnectionSetupFlow({ connectApp(); }} machineSignIn={effectiveGrantKind === "organization" && selectedCompanyId && !reconnectConnectionId - ? { companyId: selectedCompanyId, onConnected: acceptMachineSignInResult } + ? { companyId: selectedCompanyId, applicationId: prefill.applicationId, onConnected: acceptMachineSignInResult } : null} /> )} diff --git a/ui/src/features/connections/GenericMcpConnectStep.tsx b/ui/src/features/connections/GenericMcpConnectStep.tsx index 34dc87c8c9d..09e2e1eddf8 100644 --- a/ui/src/features/connections/GenericMcpConnectStep.tsx +++ b/ui/src/features/connections/GenericMcpConnectStep.tsx @@ -141,7 +141,7 @@ export function GenericMcpConnectStep({ onBack: () => void; onConnect: () => void; /** Offered only for organization connections: personal connections sign in as the person. */ - machineSignIn?: { companyId: string; onConnected: (result: ConnectToolAppResult) => void } | null; + machineSignIn?: { companyId: string; applicationId?: string | null; onConnected: (result: ConnectToolAppResult) => void } | null; }) { const [clientFieldsOpen, setClientFieldsOpen] = useState(false); // Machine sign-in runs its own setup and test, so it is a choice beside the modes, not one of them. @@ -417,6 +417,7 @@ export function GenericMcpConnectStep({
{ status: vi.fn(), }; await act(async () => { - root.render( undefined} onConnected={() => undefined} />); + root.render( undefined} onConnected={() => undefined} />); }); expect(button("Test connection")?.disabled).toBe(true); await type("machine-sign-in-client-id", "id-1"); await type("machine-sign-in-client-secret", "secret-1"); await click("Test connection"); - expect(client.create).toHaveBeenCalledWith("company-1", expect.objectContaining({ method: "client_secret", clientId: "id-1", clientSecret: "secret-1" })); + expect(client.create).toHaveBeenCalledWith("company-1", expect.objectContaining({ method: "client_secret", clientId: "id-1", clientSecret: "secret-1", applicationId: "app-1" })); expect(client.test).toHaveBeenCalledWith("connection-1", { clientId: "id-1", scopes: "" }); }); @@ -115,7 +115,7 @@ describe("Machine sign-in setup", () => { }); it("resumes the key draft this tab started instead of creating another", async () => { - sessionStorage.setItem("paperclip.machine-sign-in-draft:company-1:https://mcp.example/mcp", "connection-1"); + sessionStorage.setItem("paperclip.machine-sign-in-draft.v2:company-1:new:https://mcp.example/mcp", "connection-1"); let finish!: (value: typeof draft.machineSignIn) => void; const client: MachineSignInClient = { create: vi.fn(), @@ -134,4 +134,28 @@ describe("Machine sign-in setup", () => { expect(client.create).not.toHaveBeenCalled(); sessionStorage.clear(); }); + + it("never resumes a draft started for a different app", async () => { + const client: MachineSignInClient = { + create: vi.fn(async () => draft), + test: vi.fn(), + status: vi.fn(async () => draft.machineSignIn), + }; + // App A's setup creates a key draft in this tab, then the admin leaves it. + await act(async () => { + root.render( undefined} onConnected={() => undefined} />); + }); + await click("Create key"); + await act(async () => root.unmount()); + root = createRoot(container); + // Setup for app B at the same address starts fresh instead of adopting A's draft. + await act(async () => { + root.render( undefined} onConnected={() => undefined} />); + }); + await flush(); + expect(client.status).not.toHaveBeenCalled(); + await click("Create key"); + expect(client.create).toHaveBeenLastCalledWith("company-1", expect.objectContaining({ applicationId: "app-b" })); + sessionStorage.clear(); + }); }); diff --git a/ui/src/features/connections/MachineSignInSetup.tsx b/ui/src/features/connections/MachineSignInSetup.tsx index 98f29980b62..073fdf5d3e6 100644 --- a/ui/src/features/connections/MachineSignInSetup.tsx +++ b/ui/src/features/connections/MachineSignInSetup.tsx @@ -36,8 +36,9 @@ type MachineSignInDraft = Pick(initialSetup); const [error, setError] = useState(initialError); const [busy, setBusy] = useState<"creating" | "testing" | null>(null); - const storageKey = draftStorageKey(companyId, link); + const storageKey = draftStorageKey(companyId, applicationId, link); // While a saved draft loads, creating another would race it; wait for it. const [restoring, setRestoring] = useState(() => !initialSetup && Boolean(readDraftId(storageKey))); @@ -141,6 +145,7 @@ export function MachineSignInSetup({ ...(clientId.trim() ? { clientId: clientId.trim() } : {}), ...(method === "client_secret" && clientSecret ? { clientSecret } : {}), ...(trimmedScopes ? { scopes: trimmedScopes } : {}), + ...(applicationId ? { applicationId } : {}), }); setSetup(created); writeDraftId(storageKey, created.connectionId); diff --git a/ui/storybook/stories/runs-adapters/agent-queue-wait.stories.tsx b/ui/storybook/stories/runs-adapters/agent-queue-wait.stories.tsx index 1abe417eb4e..23ab7f056e5 100644 --- a/ui/storybook/stories/runs-adapters/agent-queue-wait.stories.tsx +++ b/ui/storybook/stories/runs-adapters/agent-queue-wait.stories.tsx @@ -4,7 +4,7 @@ import { expect, within } from "storybook/test"; import { AgentQueueWait } from "@/components/AgentQueueWait"; import { InboxIssueMetaLeading } from "@/components/IssueColumns"; import { TaskChatLiveRunPill } from "@/components/task-chat/TaskChatLiveRunPill"; -import { TaskChatRunnerHeader } from "@/components/task-chat/TaskChatRunnerTurn"; +import { TaskChatRunnerHeader, TaskChatRunnerTurn } from "@/components/task-chat/TaskChatRunnerTurn"; const codieQueue: ExecutionAgentQueue = { agentId: "8f14e45f-ceea-467a-9575-6f1d0b2c9a01", @@ -117,9 +117,11 @@ export const WaitingToStart: Story = { /** A routine task that waits for the routine's open execution. */ export const WaitingForRoutine: Story = { - render: () => , play: async ({ canvasElement }) => { - await expect(within(canvasElement).getByText(/Waiting for PAP-3093 to finish/)).toBeVisible(); + const holds = within(canvasElement).getAllByText(/Waiting for PAP-3093 to finish/); + await expect(holds).toHaveLength(1); + await expect(holds[0]).toBeVisible(); }, };