diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 47f849b72b7..15ecde9114a 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -184,6 +184,26 @@ still apply, including `prepare: false` and simple-protocol execution. With the setting unset, ORM queries keep their existing unprepared behavior and tagged SQL uses the driver default. With `false`, preparation stays disabled. +With `true`, a database client and its private pools prepare at most 1,000 +distinct SQL texts, and never a text longer than 8 KB; other texts run +unprepared. A transaction-mode pooler +(PgBouncer 1.22 or later, Neon `-pooler` hosts) shares prepared statements by +SQL text across clients, so after a migration changes a column type, the +pooler's statement for an affected text keeps failing with `cached plan must +not change result type` for every client and every process. When a statement +fails with that error, `prepared statement does not exist` (26000), or a +duplicate statement name (42P05), the client stops preparing that text for the +rest of the process and retries once without preparation. A pooled statement +is retried on its own. When the failed statement is the first one that the +transaction ran (after `SET TRANSACTION` only), the client rolls back, begins +again with the same options, repeats the `SET TRANSACTION` statements, and runs +the statement unprepared on the same connection. The transaction callback does +not run again and receives the result. A later statement in a transaction, or a +statement in a savepoint, is not retried, so that transaction or savepoint fails +once for each affected text in each process. `preparedStatementStats(db)` +reports the prepared texts and the unprepared, demoted, retried, and restarted +counts. + ## Switching between modes The database mode is controlled by `DATABASE_URL`: diff --git a/doc/plans/2026-11-13-thousand-concurrent-agents.md b/doc/plans/2026-11-13-thousand-concurrent-agents.md index 852a9fdf72a..825f67dcdfa 100644 --- a/doc/plans/2026-11-13-thousand-concurrent-agents.md +++ b/doc/plans/2026-11-13-thousand-concurrent-agents.md @@ -445,12 +445,44 @@ A missing source is reported as "not measured", never as zero. | Lease renewals that miss their deadline | finish line | 0 | metrics endpoint | | Kill one server process | finish line | runs resume, no Retry | not measured by this harness | -The server has no metrics endpoint today. `PAPERCLIP_SCALE_METRICS_URL` must -answer a JSON object with any of `mainThreadCpu`, `eventLoopUtilization` -(0 to 1, highest server process), `eventLoopDelayP99Ms`, -`statementsPerSecond`, `poolWaitP99Ms`, `runEventLatenessP99Ms`, -`agentApiPreHandlerP99Ms` and `leaseRenewalsMissed` (a counter). Without it, -the four server criteria are not measured, and a run can be at best +**Server metrics.** Each server process can serve +`GET /api/instance/server-metrics`, a JSON snapshot of that process over the +last 50 to 60 s (`windowMs`), with its `processId` (random per process +start), `uptimeSec` and `buildRevision`. It is off by default: set +`PAPERCLIP_SERVER_METRICS=true` on the stack before the run (read once at +start; off, the path answers 404 and nothing is collected). Only an instance +admin can read it, so the board token must belong to an instance admin. +Point the harness at it on the target origin, and the harness sends the board +token in its `Authorization: Bearer` header (never in the URL; +`PAPERCLIP_SCALE_METRICS_TOKEN` overrides it, and a URL on another origin gets +no token unless that variable is set): + +```sh +export PAPERCLIP_SCALE_METRICS_URL=https://$H/api/instance/server-metrics +``` + +| Field | Meaning | Source | +| --- | --- | --- | +| `mainThreadCpu` | main-thread CPU per wall second, 0 to 1 (Linux only, else null) | `/proc/self/task//stat` | +| `eventLoopUtilization` | 0 to 1 | `performance.eventLoopUtilization()` | +| `eventLoopDelayP99Ms` | highest 10 s p99 in the window | `monitorEventLoopDelay` (20 ms) | +| `statementsPerSecond` | Drizzle statements per second (not BEGIN/COMMIT or raw driver calls) | Drizzle logger counter | +| `runEventLatenessP99Ms` | runner `emittedAt` to committed row, p99 (null with no events) | runner event append | +| `agentApiPreHandlerP99Ms` | agent API request arrival to the API router, p99 (null with no agent requests) | two middlewares | +| `leaseRenewalsMissed` | counter since process start: native run leases whose deadline passed unrenewed | lease deadline timer | + +`processCpu`, `runEventLatenessSamples`, `agentApiPreHandlerSamples` and +`dedicatedConnections` are extra context. `dedicatedConnections` is the +process's dedicated-connection bound at the time of the request: `limit`, +`inUse`, `waiting` (gauges), `peakInUse`, `queued`, `overLimit` and +`nestedOverLimit` (counts since start); queueing there shows a restart burst. `poolWaitP99Ms` is absent: postgres.js exposes no cheap hook +for time spent queued for a connection, so pool wait stays not measured. With +several processes, each request reaches one of them; the harness keeps the +highest gauge and sums the counter's growth per `processId`; a process +whose `uptimeSec` shows it started during the run counts its whole counter. +After an event-loop block longer than the window, `windowMs` reports the real, +longer span so the block stays visible. Without the +endpoint, the four server criteria are not measured, and a run can be at best `incomplete`. The harness does not read the database. **Proof order.** A hosted stack that is not `paperclip.staging` first diff --git a/docs/deploy/database.md b/docs/deploy/database.md index a61a1b400ce..7d9ea38fe3e 100644 --- a/docs/deploy/database.md +++ b/docs/deploy/database.md @@ -68,6 +68,10 @@ queries inside transactions and reserved or dedicated connections. Check the provider's configuration before you enable it. Preparation caches statement metadata, not query results. Unset preserves the existing ORM behavior and the driver default for tagged SQL. Explicit per-query options still apply. +Each database client prepares at most 1,000 distinct statements and skips +statements longer than 8 KB. If a prepared statement fails because the pooler's copy is +stale after a schema change or was lost, Paperclip stops preparing that +statement and retries it once unprepared. Related optional client tuning: `DATABASE_POOL_MAX`, `DATABASE_IDLE_TIMEOUT_SECONDS`, `DATABASE_CONNECT_TIMEOUT_SECONDS`, `DATABASE_MAX_LIFETIME_SECONDS`, `DATABASE_APPLICATION_NAME`. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (`DATABASE_IDLE_TIMEOUT_SECONDS=0` keeps them open) and the pool reports `application_name=paperclip`. See [Connection pool settings](#connection-pool-settings). diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index d0bc17061f4..61d2e52b9d4 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; import postgres from "postgres"; import { installDatabaseWorkSignals } from "./work-signals.js"; import { installDatabaseResponseCapture } from "./response-capture.js"; -import { installPreparedQueries } from "./prepared-queries.js"; +import { createPreparedQueryState, installPreparedQueries, preparedQueryStats, type PreparedQueryState, type PreparedQueryStats } from "./prepared-queries.js"; import { drizzleWithLazyTransactionQueries } from "./lazy-transaction-queries.js"; import * as schema from "./schema/index.js"; @@ -377,6 +377,13 @@ export function databaseConnectionBudget(options: DatabaseClientOptions = {}) { total: main + privatePools + DATABASE_LISTENER_CONNECTIONS + dedicated }; } +const preparedQueryStates = new WeakMap(); + +export function preparedStatementStats(db: Db): PreparedQueryStats | null { + const state = preparedQueryStates.get(db); + return state ? preparedQueryStats(state) : null; +} + export function dedicatedDbConnectionStats(db: Db): DedicatedDbConnectionStats | null { const set = dedicatedConnectionSets.get(db); return set ? { ...set.stats } : null; @@ -573,7 +580,10 @@ export function createDb(url: string, options?: DatabaseClientOptions) { function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: object, dedicatedSet?: DedicatedConnectionSet) { const sql = postgres(url, postgresJsOptions(resolved)); - if (resolved.prepare === true) installPreparedQueries(sql); + const preparedState = resolved.prepare === true + ? (owner && preparedQueryStates.get(owner)) || createPreparedQueryState() + : undefined; + if (preparedState) installPreparedQueries(sql, preparedState); const key = hostPortKeyOrNull(url); if (key) registerClient(key, sql); // A disconnect can lose the response after a statement has committed. @@ -583,6 +593,7 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob const db = installDatabaseWorkSignals(drizzleWithLazyTransactionQueries(sql, schema), owner); installDatabaseResponseCapture(db, schema); markOpenTransactions(db); + if (preparedState) preparedQueryStates.set(db, preparedState); const ownerSet = owner ? dedicatedConnectionSets.get(owner) : undefined; if (dedicatedSet) { trackClientEnd(db, () => { dedicatedSet.ended.add(db); }); diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 9b84a1ce668..c5b68087976 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -8,6 +8,7 @@ export { dedicatedDbConnectionStats, type DedicatedDbConnectionStats, type DedicatedDbConnectionOptions, + preparedStatementStats, databaseConnectionBudget, PRIVATE_POOL_MAX_CONNECTIONS, createOwnedDatabaseListener, @@ -65,3 +66,4 @@ export * from "./schema/index.js"; export { databaseWorkScopeKey, primeDatabaseWorkTransactionId, signalDatabaseWork, subscribeDatabaseWork, databaseWorkPending, reconcileDatabaseWork } from "./work-signals.js"; export { withDatabaseOperation } from "./response-capture.js"; +export { databaseStatementCount } from "./statement-count.js"; diff --git a/packages/db/src/lazy-transaction-queries.test.ts b/packages/db/src/lazy-transaction-queries.test.ts index 2cefdf6c8a6..4c7828fc796 100644 --- a/packages/db/src/lazy-transaction-queries.test.ts +++ b/packages/db/src/lazy-transaction-queries.test.ts @@ -5,6 +5,7 @@ import postgres from "postgres"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { createDb, type Db } from "./client.js"; import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "./response-capture.js"; +import { databaseStatementCount } from "./statement-count.js"; import { announcementDismissals, announcementPublications } from "./schema/index.js"; import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, @@ -48,6 +49,17 @@ describeEmbeddedPostgres("transactions on the Paperclip database client", () => }); afterAll(async () => { await database?.cleanup(); }); + it("counts each statement, inside transactions and savepoints too", async () => { + const before = databaseStatementCount(); + await db.select().from(announcementPublications); + await db.transaction(async (tx) => { + await publication(tx, "counted"); + await tx.transaction(async nested => { await nested.select().from(announcementPublications); }); + await tx.query.announcementPublications.findMany(); + }); + expect(databaseStatementCount() - before).toBe(4); + }); + describe("relational query builders", () => { it("builds none for a transaction or savepoint that never reads tx.query", async () => { const schemaTables = Object.keys(db.query).length; diff --git a/packages/db/src/lazy-transaction-queries.ts b/packages/db/src/lazy-transaction-queries.ts index e153ca6452b..c99a2deb19b 100644 --- a/packages/db/src/lazy-transaction-queries.ts +++ b/packages/db/src/lazy-transaction-queries.ts @@ -3,6 +3,7 @@ import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; import type { TableRelationalConfig } from "drizzle-orm"; import type postgres from "postgres"; +import { statementCountingLogger } from "./statement-count.js"; type Callback = (tx: Transaction) => unknown; type Transaction = { @@ -27,18 +28,19 @@ type Transaction = { * built, bound to that transaction's session, and `tx._` still describes the * schema. * - * Both clients and the builders' dialect take Drizzle's defaults. A Drizzle - * option added here (`casing`, `logger`, `cache`) must go to all three. + * Both clients count each statement through `statementCountingLogger`, and + * otherwise both clients and the builders' dialect take Drizzle's defaults. A + * Drizzle option added here (`casing`, `cache`) must go to all three. */ export function drizzleWithLazyTransactionQueries, TClient extends postgres.Sql>( client: TClient, schema: TSchema, ): PostgresJsDatabase & { $client: TClient } { - const db = drizzle(client, { schema }); + const db = drizzle(client, { schema, logger: statementCountingLogger }); const tables = db._.schema; if (!tables) return db; const { fullSchema, tableNamesMap } = db._; - const transactions = drizzle(client) as unknown as Transaction; + const transactions = drizzle(client, { logger: statementCountingLogger }) as unknown as Transaction; const dialect = new PgDialect(); const resolved = (value: unknown): PropertyDescriptor => ({ value, writable: true, enumerable: true, configurable: true }); const lazyQuery: PropertyDescriptor = { diff --git a/packages/db/src/prepared-queries-postgres.test.ts b/packages/db/src/prepared-queries-postgres.test.ts index edef6dc060e..c021db95429 100644 --- a/packages/db/src/prepared-queries-postgres.test.ts +++ b/packages/db/src/prepared-queries-postgres.test.ts @@ -1,11 +1,14 @@ import { eq, sql } from "drizzle-orm"; +import postgres from "postgres"; import { integer, jsonb, pgTable, text } from "drizzle-orm/pg-core"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; -import { closeLivenessDb, createDb, databaseClientOptionsFromEnv, livenessDb, withDedicatedDbConnection, type DatabaseClientOptions, type Db } from "./client.js"; +import { closeLivenessDb, createDb, databaseClientOptionsFromEnv, livenessDb, preparedStatementStats, withDedicatedDbConnection, type DatabaseClientOptions, type Db } from "./client.js"; +import { createPreparedQueryState, installPreparedQueries, preparedQueryStats } from "./prepared-queries.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; import { runEventPayload } from "./run-event-payload.js"; const records = pgTable("prepared_query_fixture", { id: text("id").primaryKey(), companyId: text("company_id").notNull(), value: integer("value").notNull(), payload: jsonb("payload") }); +const stale = pgTable("prepared_stale_fixture", { id: text("id").primaryKey(), value: integer("value").notNull() }); const encoded = pgTable("prepared_encoded_fixture", { id: text("id").primaryKey(), payload: runEventPayload("payload") }); const support = await getEmbeddedPostgresTestSupport(); @@ -19,6 +22,8 @@ describe.skipIf(!support.supported)("explicit ORM prepared statements on Postgre await setup.execute(sql`create table prepared_query_fixture(id text primary key, company_id text not null, value integer not null, payload jsonb)`); await setup.execute(sql`create table prepared_encoded_fixture(id text primary key, payload jsonb)`); await setup.execute(sql`create table prepared_schema_change_fixture(id text primary key)`); + await setup.execute(sql`create table prepared_stale_fixture(id text primary key, value integer not null)`); + await setup.execute(sql`insert into prepared_stale_fixture(id, value) values ('stale', 5)`); await setup.execute(sql`insert into prepared_schema_change_fixture(id) values ('retained')`); }, 90_000); beforeEach(async () => { @@ -172,4 +177,181 @@ describe.skipIf(!support.supported)("explicit ORM prepared statements on Postgre await setup.execute(sql`alter table prepared_schema_change_fixture drop column if exists extra`); } }); + + async function changeStaleValueType(type: "bigint" | "integer") { + await setup.execute(sql.raw(`alter table prepared_stale_fixture alter column value type ${type}`)); + } + + it("restarts a transaction whose first statement meets an invalidated plan without running the callback again", async () => { + const db = fixture({ prepare: true }); + let calls = 0; + const read = () => db.transaction(tx => { calls++; return tx.select().from(stale).where(eq(stale.id, "stale")); }); + expect(await read()).toEqual([{ id: "stale", value: 5 }]); + await changeStaleValueType("bigint"); + try { + expect(await read()).toEqual([{ id: "stale", value: 5 }]); + expect(calls).toBe(2); + expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 1, demoted: 1 }); + } finally { + await changeStaleValueType("integer"); + } + }); + + it("restarts a transaction whose first statement lost its prepared statement and keeps its later work", async () => { + const db = fixture({ prepare: true }); + const run = (value: number) => db.transaction(async tx => { + const [row] = await tx.select({ value: records.value }).from(records).where(eq(records.id, "a")); + await tx.execute(sql`update prepared_query_fixture set value = ${value} where id = ${"b"} ${sql.raw(`/* run ${value} */`)}`); + return row; + }); + expect(await run(3)).toEqual({ value: 1 }); + const [{ name }] = await statements(db, 'select "value" from "prepared_query_fixture"%'); + await db.$client.unsafe(`deallocate "${String(name)}"`); + expect(await run(4)).toEqual({ value: 1 }); + expect(await setup.select({ value: records.value }).from(records).where(eq(records.id, "b"))).toEqual([{ value: 4 }]); + expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 1, demoted: 1 }); + }); + + it("keeps the isolation level and access mode of a restarted transaction", async () => { + const db = fixture({ prepare: true }); + const settings = "select current_setting('transaction_isolation') as isolation, current_setting('transaction_read_only') as read_only, $1::integer as marker"; + const snapshot = { isolation: "repeatable read", read_only: "on", marker: 1 }; + const readDriver = () => db.$client.begin("isolation level repeatable read read only", async tx => { + const rows = await tx.unsafe("select id, value from prepared_stale_fixture where id = $1", ["stale"]); + return [rows, await tx.unsafe(settings, [1])]; + }); + const readOrm = () => db.transaction(async tx => [ + await tx.select().from(stale).where(eq(stale.id, "stale")), + await tx.execute(sql`select current_setting('transaction_isolation') as isolation, current_setting('transaction_read_only') as read_only, ${1}::integer as marker`), + ], { isolationLevel: "repeatable read", accessMode: "read only" }); + expect(await readDriver()).toEqual([[{ id: "stale", value: 5 }], [snapshot]]); + expect(await readOrm()).toEqual([[{ id: "stale", value: 5 }], [snapshot]]); + await changeStaleValueType("bigint"); + try { + expect(await readDriver()).toEqual([[{ id: "stale", value: "5" }], [snapshot]]); + expect(await readOrm()).toEqual([[{ id: "stale", value: 5 }], [snapshot]]); + expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 2, demoted: 2 }); + } finally { + await changeStaleValueType("integer"); + } + }); + + it("does not restart a transaction after its first statement and runs the invalidated text unprepared", async () => { + const db = fixture({ prepare: true }); + let calls = 0; + const update = () => db.transaction(async tx => { + calls++; + await tx.update(records).set({ value: 7 }).where(eq(records.id, "b")); + return tx.select().from(stale).where(eq(stale.id, "stale")); + }); + expect(await update()).toEqual([{ id: "stale", value: 5 }]); + await changeStaleValueType("bigint"); + try { + await expect(update()).rejects.toMatchObject({ cause: { code: "0A000" } }); + expect(calls).toBe(2); + expect(await update()).toEqual([{ id: "stale", value: 5 }]); + expect(await statements(db, '%"prepared_stale_fixture"%')).toHaveLength(1); + expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 }); + } finally { + await changeStaleValueType("integer"); + } + }); + + it("counts a tagged statement as the first statement of a transaction", async () => { + const db = fixture({ prepare: true }); + const read = "select id, value from prepared_stale_fixture where id = $1"; + expect(await db.$client.unsafe(read, ["stale"])).toEqual([{ id: "stale", value: 5 }]); + await changeStaleValueType("bigint"); + try { + await expect(db.$client.begin(async tx => { + await tx`update prepared_query_fixture set value = value + 1 where id = 'a'`; + return tx.unsafe(read, ["stale"]); + })).rejects.toMatchObject({ code: "0A000" }); + expect(await setup.select({ value: records.value }).from(records).where(eq(records.id, "a"))).toEqual([{ value: 1 }]); + expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 }); + } finally { + await changeStaleValueType("integer"); + } + }); + + it("rolls back only the savepoint whose first statement fails and continues the outer transaction once", async () => { + const db = fixture({ prepare: true }); + const nestedRead = (tx: Parameters[0]>[0]) => + tx.transaction(nested => nested.select().from(stale).where(eq(stale.id, "stale"))); + await db.transaction(async tx => { await nestedRead(tx); }); + await changeStaleValueType("bigint"); + let outerCalls = 0; + try { + const result = await db.transaction(async tx => { + outerCalls++; + await tx.execute(sql`update prepared_query_fixture set value = value + 10 where id = ${"a"}`); + const nested = await nestedRead(tx).catch((error: { cause?: { code?: string } }) => error.cause?.code); + await tx.execute(sql`update prepared_query_fixture set value = value + 100 where id = ${"b"}`); + return [nested, await tx.select().from(stale).where(eq(stale.id, "stale"))]; + }); + expect(result).toEqual(["0A000", [{ id: "stale", value: 5 }]]); + expect(outerCalls).toBe(1); + expect(await setup.select({ id: records.id, value: records.value }).from(records).orderBy(records.id)) + .toEqual([{ id: "a", value: 11 }, { id: "b", value: 102 }]); + expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 }); + } finally { + await changeStaleValueType("integer"); + } + }); + + async function occupyNextStatementName(db: Db) { + const names = (await statements(db, "%")).map(row => String(row.name)); + const prefix = names.find(name => /\d$/.test(name) && !name.includes(" "))!.replace(/\d+$/, ""); + const counters = names.filter(name => name.startsWith(prefix)).map(name => Number(name.slice(prefix.length))); + await db.$client.unsafe(`prepare "${prefix}${Math.max(...counters) + 1}" as select 1`, [], { prepare: false }); + } + + it("retries a pooled statement unprepared when its prepared statement cannot be created", async () => { + const db = fixture({ prepare: true }); + await statements(db, "%"); + await occupyNextStatementName(db); + expect(await db.select({ value: records.value }).from(records).where(eq(records.id, "b"))).toEqual([{ value: 2 }]); + await occupyNextStatementName(db); + expect(await db.$client.unsafe("select $1::integer as raw_retry_marker", [3]).values()).toEqual([[3]]); + expect(await statements(db)).toHaveLength(0); + expect(await statements(db, "%raw_retry_marker%")).toHaveLength(0); + expect(preparedStatementStats(db)).toMatchObject({ retried: 2, demoted: 2 }); + }); + + it("does not restart a transaction when a query created first executes after another statement", async () => { + const db = fixture({ prepare: true }); + const read = "select id, value from prepared_stale_fixture where id = $1"; + expect(await db.$client.unsafe(read, ["stale"])).toEqual([{ id: "stale", value: 5 }]); + await changeStaleValueType("bigint"); + let calls = 0; + try { + await expect(db.$client.begin(async tx => { + calls++; + const saved = tx.unsafe(read, ["stale"]); + await tx.unsafe("select $1::integer as ordering_marker", [1]); + return await saved; + })).rejects.toMatchObject({ code: "0A000" }); + expect(calls).toBe(1); + expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 }); + } finally { + await changeStaleValueType("integer"); + } + }); + + it("prepares at most the configured number of distinct texts and skips long texts", async () => { + const raw = postgres(temporary.connectionString, { max: 1, prepare: true, onnotice: () => {} }); + const state = createPreparedQueryState({ limit: 2, maxLength: 80 }); + installPreparedQueries(raw, state); + try { + for (const marker of ["cap_a", "cap_b", "cap_c", "cap_d"]) { + expect(await raw.unsafe(`select $1::integer as ${marker}`, [1])).toEqual([{ [marker]: 1 }]); + } + const long = `select $1::integer as cap_long /* ${"x".repeat(80)} */`; + expect(await raw.unsafe(long, [2])).toEqual([{ cap_long: 2 }]); + expect((await raw.unsafe("select name from pg_prepared_statements where statement like 'select $1::integer as cap_%'", [], { prepare: false })).length).toBe(2); + expect(preparedQueryStats(state)).toMatchObject({ texts: 2, unprepared: 3 }); + } finally { + await raw.end(); + } + }); }); diff --git a/packages/db/src/prepared-queries.ts b/packages/db/src/prepared-queries.ts index 7622722027a..0efa5ac1d97 100644 --- a/packages/db/src/prepared-queries.ts +++ b/packages/db/src/prepared-queries.ts @@ -1,9 +1,108 @@ type Method = (this: unknown, ...args: unknown[]) => unknown; -export function installPreparedQueries(client: unknown): void { +export const PREPARED_QUERY_TEXT_LIMIT = 1_000; +export const PREPARED_QUERY_TEXT_MAX_LENGTH = 8_192; + +export type PreparedQueryStats = { + texts: number; + unprepared: number; + demoted: number; + retried: number; + restartedTransactions: number; +}; + +export type PreparedQueryState = { + limit: number; + maxLength: number; + texts: Set; + demoted: Set; + stats: Omit; +}; + +type Counts = { created: number; executed: number; setup: string[] }; +type Scope = { retry: "statement" | "restart" | "none"; begin?: string; counts: Counts }; + +type PendingQuery = { + options: Record; + reject(error: unknown): void; + resolve(value: unknown): void; + isRaw?: unknown; + cursorFn?: unknown; + forEachFn?: unknown; + onlyDescribe?: unknown; + then(onFulfilled: (value: unknown) => void, onRejected: (error: unknown) => void): unknown; +}; + +export function createPreparedQueryState(options: { limit?: number; maxLength?: number } = {}): PreparedQueryState { + return { + limit: options.limit ?? PREPARED_QUERY_TEXT_LIMIT, + maxLength: options.maxLength ?? PREPARED_QUERY_TEXT_MAX_LENGTH, + texts: new Set(), + demoted: new Set(), + stats: { unprepared: 0, demoted: 0, retried: 0, restartedTransactions: 0 }, + }; +} + +export function preparedQueryStats(state: PreparedQueryState): PreparedQueryStats { + return { texts: state.texts.size, ...state.stats }; +} + +export function isPreparedStatementFailure(error: unknown): boolean { + if (typeof error !== "object" || error === null) return false; + const { code, routine, message } = error as { code?: unknown; routine?: unknown; message?: unknown }; + if (code === "26000" || code === "42P05") return true; + return code === "0A000" && (routine === "RevalidateCachedQuery" + || (typeof message === "string" && message.includes("cached plan must not change result type"))); +} + +function shouldPrepare(state: PreparedQueryState, text: string): boolean { + if (state.texts.has(text)) return true; + if (state.demoted.has(text) || text.length > state.maxLength || state.texts.size >= state.limit) { + state.stats.unprepared++; + return false; + } + state.texts.add(text); + return true; +} + +function demote(state: PreparedQueryState, text: string): void { + if (state.demoted.has(text)) return; + state.texts.delete(text); + state.demoted.add(text); + state.stats.demoted++; +} + +const TRANSACTION_SETUP = /^\s*set\s+transaction\b/i; + +function scope(retry: Scope["retry"], begin?: string, counts: Counts = { created: 0, executed: 0, setup: [] }): Scope { + return { retry, begin, counts }; +} + +function track(query: PendingQuery, current: Counts, text: string | undefined, decide: () => unknown) { + current.created++; + let explicit: unknown = "prepare" in query.options ? query.options.prepare : undefined; + const execution = { started: false, first: false }; + Object.defineProperty(query.options, "prepare", { + enumerable: true, + configurable: true, + get: () => { + if (!execution.started) { + execution.started = true; + execution.first = current.executed === current.setup.length; + current.executed++; + if (execution.first && text !== undefined && query.options.simple && TRANSACTION_SETUP.test(text)) current.setup.push(text); + } + return explicit ?? decide(); + }, + set: (value: unknown) => { explicit = value; }, + }); + return { execution, explicit: () => explicit }; +} + +export function installPreparedQueries(client: unknown, state: PreparedQueryState = createPreparedQueryState()): void { const visited = new WeakSet(); - function visit(value: unknown): void { + function visit(value: unknown, current: Scope): void { if ((typeof value !== "object" || value === null) && typeof value !== "function") return; if (visited.has(value)) return; visited.add(value); @@ -12,22 +111,52 @@ export function installPreparedQueries(client: unknown): void { if (typeof unsafe === "function") { target.unsafe = function (this: unknown, ...args: unknown[]) { const index = args.length === 2 && !Array.isArray(args[1]) ? 1 : 2; - const options = args[index]; + const options = args[index] as Record | undefined; if (options !== undefined && (options === null || typeof options !== "object")) { return Reflect.apply(unsafe, this, args); } if (index === 2 && args.length < 2) args[1] = []; + const text = args[0]; args[index] = { prepare: true, ...options }; - return Reflect.apply(unsafe, this, args); - }; + if (typeof text !== "string") return Reflect.apply(unsafe, this, args); + const query = Reflect.apply(unsafe, this, args) as PendingQuery; + const caller = (options !== undefined && "prepare" in options) || query.options.simple; + if (!caller) delete query.options.prepare; + const tracked = track(query, current.counts, text, () => shouldPrepare(state, text)); + const reject = query.reject; + query.reject = (error: unknown) => { + if (tracked.explicit() !== undefined || !isPreparedStatementFailure(error)) return reject(error); + demote(state, text); + if (query.cursorFn || query.forEachFn || query.onlyDescribe || options?.onexecute) return reject(error); + const params = index === 2 ? args[1] : []; + const unprepared = { ...options, prepare: false }; + if (current.retry === "statement") { + state.stats.retried++; + const retry = Reflect.apply(unsafe, this, [text, params, unprepared]) as PendingQuery; + retry.isRaw = query.isRaw; + retry.then(query.resolve, reject); + return; + } + if (current.retry !== "restart" || !tracked.execution.first || current.counts.created !== current.counts.executed) return reject(error); + state.stats.restartedTransactions++; + const run = (sql: string, ...rest: unknown[]) => Reflect.apply(unsafe, this, [sql, ...rest]) as PendingQuery; + const steps = [run("rollback"), run(`begin ${current.begin ?? ""}`.trim()), ...current.counts.setup.map(setup => run(setup))]; + const retry = run(text, params, unprepared); + retry.isRaw = query.isRaw; + Promise.all([...steps, retry]).then(results => query.resolve(results[results.length - 1]), reject); + }; + return query; + } satisfies Method; } - for (const method of ["begin", "savepoint"]) { + for (const method of ["begin", "savepoint"] as const) { const original = target[method]; if (typeof original !== "function") continue; target[method] = function (this: unknown, ...args: unknown[]) { - const wrapped = args.map(arg => typeof arg !== "function" ? arg : function (this: unknown, ...inner: unknown[]) { - visit(inner[0]); - return Reflect.apply(arg, this, inner); + const begin = method === "begin" && typeof args[0] === "string" ? args[0].replace(/[^a-z ]/ig, "") : undefined; + const inner = method === "begin" ? scope("restart", begin) : scope("none", undefined, current.counts); + const wrapped = args.map(arg => typeof arg !== "function" ? arg : function (this: unknown, ...params: unknown[]) { + visit(params[0], inner); + return Reflect.apply(arg, this, [counted(params[0], inner), ...params.slice(1)]); }); return Reflect.apply(original, this, wrapped); } satisfies Method; @@ -36,12 +165,26 @@ export function installPreparedQueries(client: unknown): void { if (typeof reserve === "function") { target.reserve = function (this: unknown, ...args: unknown[]) { return Promise.resolve(Reflect.apply(reserve, this, args)).then(reserved => { - visit(reserved); + visit(reserved, scope("none")); return reserved; }); } satisfies Method; } } - visit(client); + function counted(sql: unknown, current: Scope): unknown { + if (typeof sql !== "function") return sql; + return new Proxy(sql, { + apply(target, self, args) { + const result = Reflect.apply(target, self, args) as unknown; + const strings = args[0] as { raw?: unknown } | undefined; + if (Array.isArray(strings?.raw) && result instanceof Promise && "options" in result) { + track(result as unknown as PendingQuery, current.counts, undefined, () => true); + } + return result; + }, + }); + } + + visit(client, scope("statement")); } diff --git a/packages/db/src/statement-count.ts b/packages/db/src/statement-count.ts new file mode 100644 index 00000000000..da0f00f1478 --- /dev/null +++ b/packages/db/src/statement-count.ts @@ -0,0 +1,13 @@ +import type { Logger } from "drizzle-orm"; + +let statements = 0; + +export const statementCountingLogger: Logger = { + logQuery(): void { + statements += 1; + }, +}; + +export function databaseStatementCount(): number { + return statements; +} diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index 1362b860048..9f93fe24866 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -137,7 +137,7 @@ export { RunnerdDotDriver, type RunnerdDotDriverOptions } from "./drivers/dot/ru export type { RunnerExecutionDriver } from "./control-plane/runner-execution-driver.js"; -export { RUNNER_GITHUB_LAUNCHER_VERSION, bindRunnerLaunchResources, createRunnerProviderLaunch, runnerProviderLaunchRequirements, runnerLaunchRequirementsDigest, validatePreparedRunnerLaunch } from "./live/runner-provider-launch.js"; +export { RUNNER_GITHUB_LAUNCHER_VERSION, bindRunnerLaunchResources, createRunnerProviderLaunch, runnerProviderLaunchRequirements, runnerLaunchPreparationDigest, runnerLaunchRequirementsDigest, runnerLaunchRunDigest, validatePreparedRunnerLaunch } from "./live/runner-provider-launch.js"; export type { RunnerProviderLaunchRequirements, RunnerProviderLaunchEnvironment, PreparedRunnerProviderLaunch, RunnerLaunchPreparer } from "./live/runner-provider-launch.js"; export { resolveGrokDisableWebSearch } from "./drivers/acpx/grok-web-search.js"; diff --git a/packages/paperclip-runner/src/live/runner-launch-preparation.test.ts b/packages/paperclip-runner/src/live/runner-launch-preparation.test.ts index 53ec6a9d828..f091b4ad685 100644 --- a/packages/paperclip-runner/src/live/runner-launch-preparation.test.ts +++ b/packages/paperclip-runner/src/live/runner-launch-preparation.test.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { canonicalNativeRuntimeContextDigest, composeNativeSystemInstructions, NATIVE_RUNTIME_ASSET_SCHEMA } from "../contracts/runtime-context.js"; import { describe, expect, it } from "vitest"; -import { bindRunnerLaunchResources, createRunnerProviderLaunch, runnerLaunchRequirementsDigest, runnerProviderLaunchRequirements, +import { bindRunnerLaunchResources, createRunnerProviderLaunch, runnerLaunchPreparationDigest, runnerLaunchRequirementsDigest, runnerLaunchRunDigest, runnerProviderLaunchRequirements, validatePreparedRunnerLaunch, type RunnerProviderLaunchRequirements } from "./runner-provider-launch.js"; const identity = { runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "run", @@ -96,3 +96,83 @@ describe("environment-owned launch contract", () => { } }); }); + +describe("launch preparation and run digests", () => { + const nextRun = { ...identity, runId: "next-run", turnId: "next-turn", itemId: "next-item" }; + const withIdentity = (value: typeof identity) => ({ ...requirements(), identity: value }); + + it("keeps the preparation digest across runs of one Runner and changes the run digest", () => { + const first = runnerLaunchPreparationDigest(requirements()); + expect(runnerLaunchPreparationDigest(withIdentity(nextRun))).toBe(first); + expect(first).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(first).not.toBe(runnerLaunchRequirementsDigest(requirements())); + const run = runnerLaunchRunDigest(first, withIdentity(identity)); + expect(run).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(runnerLaunchRunDigest(first, withIdentity(nextRun))).not.toBe(run); + expect(runnerLaunchRunDigest(first, withIdentity({ ...identity, itemId: "other-item" }))).not.toBe(run); + expect(runnerLaunchRunDigest(first, withIdentity(identity))).toBe(run); + }); + + const zero = "0".repeat(64); + const one = "1".repeat(64); + type Context = NonNullable; + const baseContext = (): Omit => ({ + prompt: { revision: "fixture", text: "Core policy", digest: createHash("sha256").update("Core policy").digest("hex") }, + instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, + rootPath: "/controller/instructions", digest: zero, manifestDigest: zero, fileCount: 1, totalBytes: 1 } }, + skills: [{ key: "assigned", runtimeName: "assigned", versionId: "v1", bundle: { + schema: NATIVE_RUNTIME_ASSET_SCHEMA, rootPath: "/controller/skill", digest: zero, manifestDigest: zero, fileCount: 1, totalBytes: 1 } }], + mcp: { assignmentSetId: "assigned", digest: zero, bindingId: "native-mcp:run" }, + }); + const withContext = (value: typeof identity, change: (context: Omit) => void = () => {}): RunnerProviderLaunchRequirements => { + const context = baseContext(); + change(context); + return { ...requirements(), identity: value, runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) } }; + }; + + // MCP reaches the Runner through Core's tool authority on every run attachment, never through files the environment + // publishes, and Core keeps a warm session across an MCP-only change. So MCP belongs to the run digest only. + it("keeps the preparation digest across warm runs whose runtime context changes only in MCP", () => { + const first = withContext(identity); + const digest = runnerLaunchPreparationDigest(first); + const mcpChanges: Array<[string, RunnerProviderLaunchRequirements]> = [ + ["the run's binding", withContext(nextRun, context => { context.mcp.bindingId = "native-mcp:next-run"; })], + ["no binding", withContext(nextRun, context => { context.mcp.bindingId = null; })], + ["the assigned access set", withContext(nextRun, context => { context.mcp = { assignmentSetId: "other-set", digest: one, bindingId: "native-mcp:next-run" }; })], + ]; + for (const [label, next] of mcpChanges) { + expect(runnerLaunchPreparationDigest(next), label).toBe(digest); + expect(runnerLaunchRunDigest(digest, next), label).not.toBe(runnerLaunchRunDigest(digest, first)); + } + // Within one run, an MCP change still changes the run digest. + const sameRun = withContext(identity, context => { context.mcp.assignmentSetId = "other-set"; }); + expect(runnerLaunchRunDigest(digest, sameRun)).not.toBe(runnerLaunchRunDigest(digest, first)); + }); + + it.each([ + ["instruction bundle", (context: Omit) => { context.instructions.bundle.digest = one; }], + ["instruction entry", (context: Omit) => { context.instructions.entryPath = "CLAUDE.md"; }], + ["skill bundle", (context: Omit) => { context.skills[0]!.bundle.digest = one; }], + ["skill set", (context: Omit) => { context.skills = []; }], + ["instruction working copy", (context: Omit) => { + context.instructions.workingCopy = { rootPath: "/workspace/.paperclip-runtime/agent-files/agent/run", entryPath: "AGENTS.md", kind: "agent_files" }; }], + ["connection instructions", (context: Omit) => { context.connectionInstructions = { text: "Use the connector.", digest: one }; }], + ])("changes the preparation digest when the %s changes", (_label, change) => { + expect(runnerLaunchPreparationDigest(withContext(identity, change))).not.toBe(runnerLaunchPreparationDigest(withContext(identity))); + }); + + it.each([ + ["runner instance", withIdentity({ ...identity, runnerInstanceId: "other-runner" })], + ["environment lease", withIdentity({ ...identity, environmentLeaseId: "other-lease" })], + ["session", withIdentity({ ...identity, normalizedSessionId: "other-session" })], + ["instructions", { ...requirements(), instructions: "Changed instructions" }], + ["model", { ...requirements(), model: "other-model" }], + ["approval policy", { ...requirements(), approvalPolicy: "never" as const }], + ["settings", { ...requirements(), settings: { ...requirements().settings, disableCodexWebSearch: true } }], + ])("changes the preparation digest when the %s changes", (_label, changed) => { + const before = runnerLaunchPreparationDigest(requirements()); + const after = runnerLaunchPreparationDigest(changed as RunnerProviderLaunchRequirements); + expect(after).not.toBe(before); + expect(runnerLaunchRunDigest(after, withIdentity(identity))).not.toBe(runnerLaunchRunDigest(before, withIdentity(identity))); + }); +}); diff --git a/packages/paperclip-runner/src/live/runner-provider-launch.ts b/packages/paperclip-runner/src/live/runner-provider-launch.ts index cff4b9a4154..c224a665536 100644 --- a/packages/paperclip-runner/src/live/runner-provider-launch.ts +++ b/packages/paperclip-runner/src/live/runner-provider-launch.ts @@ -93,13 +93,51 @@ export function bindRunnerLaunchResources( }; } -export function runnerLaunchRequirementsDigest(requirements: RunnerProviderLaunchRequirements): string { - const canonical = JSON.stringify(requirements, (_key, value: unknown) => - value && typeof value === "object" && !Array.isArray(value) - ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value); +function canonicalDigest(value: unknown): string { + const canonical = JSON.stringify(value, (_key, entry: unknown) => + entry && typeof entry === "object" && !Array.isArray(entry) + ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : entry); return `sha256:${createHash("sha256").update(canonical).digest("hex")}`; } +export function runnerLaunchRequirementsDigest(requirements: RunnerProviderLaunchRequirements): string { + return canonicalDigest(requirements); +} + +/** + * The launch requirements an environment reconciles when it prepares a Runner: the runner, lease and session identity, + * provider, model and settings, the prompt and instruction text, and the runtime context's instruction and skill + * bundles, working copy and connection instructions. It leaves out what names one run (the run, turn and item ids) and + * the runtime context's MCP assignment and binding: MCP reaches the Runner through Core's tool authority on every run + * attachment, never through files the environment publishes, and Core already continues a warm session across an + * MCP-only change (`nativeRuntimeContextsMatch` with tool refresh). The context's `aggregateDigest` is left out with it, + * since it hashes the MCP assignment and every other field it covers is in this digest directly. + */ +export function runnerLaunchPreparationDigest(requirements: RunnerProviderLaunchRequirements): string { + const { runId: _runId, turnId: _turnId, itemId: _itemId, ...identity } = requirements.identity; + let runtimeContext: Omit | null = null; + if (requirements.runtimeContext) { + const { mcp: _mcp, aggregateDigest: _aggregateDigest, ...prepared } = requirements.runtimeContext; + runtimeContext = prepared; + } + return canonicalDigest({ schema: "paperclip.runner.launch-preparation-digest.v1", requirements: { ...requirements, identity, runtimeContext } }); +} + +/** + * The preparation digest plus everything it leaves out: the run, turn and item ids, and the MCP assignment and binding. + * It is unique to one run's launch. + */ +export function runnerLaunchRunDigest(preparationDigest: string, requirements: { + identity: Pick; + runtimeContext: Pick | null; +}): string { + const { identity } = requirements; + const mcp = requirements.runtimeContext?.mcp; + return canonicalDigest({ schema: "paperclip.runner.launch-run-digest.v1", preparationDigest, + runId: identity.runId, turnId: identity.turnId, itemId: identity.itemId, + mcp: mcp ? { assignmentSetId: mcp.assignmentSetId, digest: mcp.digest, bindingId: mcp.bindingId } : null }); +} + function runnerLaunchPolicy(requirements: RunnerProviderLaunchRequirements): Record { return createRunnerProviderLaunch(requirements, { options: { codexArgs: [] }, root: "/", cwd: "/", codexHome: "/", diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index 0e99adb1512..e1b60f9b279 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -95,6 +95,8 @@ export const environmentTaskOperationSchema = z.discriminatedUnion("kind", [ githubBroker: githubBroker.optional(), recovery: preparedLaunch.optional(), resumeFrom: providerId.optional(), priorIdentity: durableIdentity.optional(), accountIdentity: z.string().min(1).max(1024).optional(), + preparationDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), + runDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), projectIds: z.array(z.string().uuid()).max(64).refine(ids => new Set(ids).size === ids.length, "Duplicate project IDs"), }).strict(), z.object({ @@ -186,7 +188,8 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [ sha256: z.string().regex(/^[a-f0-9]{64}$/), }).strict(), z.object({ kind: z.literal("state"), taskId: providerId, state: z.record(z.string(), z.unknown()) }).strict(), - z.object({ kind: z.literal("prepared"), taskId: providerId, launch: preparedLaunch, projectAuthCheckAtSubmit: z.literal(true).optional() }).strict(), + z.object({ kind: z.literal("prepared"), taskId: providerId, launch: preparedLaunch, projectAuthCheckAtSubmit: z.literal(true).optional(), + projectAuthChecked: z.literal(true).optional() }).strict(), z.object({ kind: z.literal("credentials"), taskId: providerId, /** Null proves that cancellation fenced admission before the task could start. It must not mean an unavailable export. */ credential: environmentTaskCredentialSchema.nullable() }).strict(), z.object({ kind: z.literal("description"), taskId: providerId, @@ -205,6 +208,7 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [ githubCredentialBrokerVersion: z.literal(1).optional(), configuredEnvironmentVersion: z.literal(1).optional(), resumeLaunchInputsVersion: z.literal(1).optional(), + launchDigestVersion: z.literal(1).optional(), }).strict(), z.object({ kind: z.literal("status"), taskId: providerId, diff --git a/rules/company-scope-exceptions.mdc b/rules/company-scope-exceptions.mdc index a68dbb9d2e6..7d907af4a09 100644 --- a/rules/company-scope-exceptions.mdc +++ b/rules/company-scope-exceptions.mdc @@ -1,6 +1,6 @@ --- -description: The known instance-wide data is announcement dismissals, the announcement publication-ID registry, personal workspace presentation preferences, and the per-user sidebar company order; these grant no authority, and a new exception must be added to this list. -globs: "packages/db/src/schema/announcement_dismissals.ts,packages/shared/src/announcements.ts,server/src/routes/announcements.ts,server/src/services/announcements.ts,server/src/services/announcement-feed.ts,packages/db/src/schema/user_workspace_preferences.ts,packages/shared/src/workspace-preferences.ts,server/src/routes/workspace-preferences.ts,server/src/services/workspace-preferences.ts,packages/db/src/schema/user_sidebar_preferences.ts,packages/shared/src/types/sidebar-preferences.ts,server/src/routes/sidebar-preferences.ts,server/src/services/sidebar-preferences.ts" +description: The known instance-wide data is announcement dismissals, the announcement publication-ID registry, personal workspace presentation preferences, the per-user sidebar company order, and the instance-admin server metrics snapshot; these grant no authority, and a new exception must be added to this list. +globs: "packages/db/src/schema/announcement_dismissals.ts,packages/shared/src/announcements.ts,server/src/routes/announcements.ts,server/src/services/announcements.ts,server/src/services/announcement-feed.ts,packages/db/src/schema/user_workspace_preferences.ts,packages/shared/src/workspace-preferences.ts,server/src/routes/workspace-preferences.ts,server/src/services/workspace-preferences.ts,packages/db/src/schema/user_sidebar_preferences.ts,packages/shared/src/types/sidebar-preferences.ts,server/src/routes/sidebar-preferences.ts,server/src/services/sidebar-preferences.ts,server/src/routes/instance-server-metrics.ts,server/src/services/server-metrics.ts" alwaysApply: false --- @@ -29,6 +29,13 @@ company scope here. - **The sidebar company order** in `user_sidebar_preferences` is instance-wide by user, because it orders the user's companies. Sidebar preferences inside one company stay company-scoped in `company_user_sidebar_preferences`. +- **The server metrics snapshot** (`GET /api/instance/server-metrics`) describes + one server process: CPU, event-loop load, statement rate, latency + percentiles and missed lease renewals. Company scope does not fit, because the + process serves every company and the numbers cannot be split by company. Only + an instance admin can read it, it is off unless `PAPERCLIP_SERVER_METRICS` is + set, and it returns numbers and a build revision only: no SQL, names, IDs or + hostnames. It persists nothing and changes nothing. ## Requirements diff --git a/scripts/scale-ramp/config.ts b/scripts/scale-ramp/config.ts index 769331262d2..2165cbbe75d 100644 --- a/scripts/scale-ramp/config.ts +++ b/scripts/scale-ramp/config.ts @@ -104,6 +104,16 @@ export function readSecrets(env: NodeJS.ProcessEnv, credentialKey: string | null }; } +export function metricsCredential(options: Pick, secrets: Secrets): string | null { + if (secrets.metricsToken) return secrets.metricsToken; + if (!options.metricsUrl) return null; + try { + return new URL(options.metricsUrl).origin === options.target.baseUrl ? secrets.token : null; + } catch { + return null; + } +} + function adapterOverrides(raw: string | undefined): Record { if (!raw) return {}; let parsed: unknown; diff --git a/scripts/scale-ramp/main.ts b/scripts/scale-ramp/main.ts index 4099781ce2f..db4cab28fe0 100644 --- a/scripts/scale-ramp/main.ts +++ b/scripts/scale-ramp/main.ts @@ -3,7 +3,7 @@ import path from "node:path"; import { createInterface } from "node:readline/promises"; import { cleanupRun, discoverState, type CleanupReport } from "./cleanup.ts"; import { PaperclipClient, Redactor, realClock, type Clock, type Fetcher } from "./client.ts"; -import { FALLBACK_TOKEN_ENV, parseOptions, readSecrets, TOKEN_ENV, type Options } from "./config.ts"; +import { FALLBACK_TOKEN_ENV, metricsCredential, parseOptions, readSecrets, TOKEN_ENV, type Options } from "./config.ts"; import { criteriaTable } from "./criteria.ts"; import { checkSpend, estimateSpend, type SpendEstimate } from "./estimate.ts"; import { Ramp, type RampOutcome } from "./ramp.ts"; @@ -121,7 +121,7 @@ export async function main(argv: readonly string[], deps: MainDeps): Promise interrupted, }); outcome = await ramp.run(); diff --git a/scripts/scale-ramp/ramp.ts b/scripts/scale-ramp/ramp.ts index 2a329474559..9dc68a00faa 100644 --- a/scripts/scale-ramp/ramp.ts +++ b/scripts/scale-ramp/ramp.ts @@ -130,12 +130,42 @@ function rows(body: unknown): Json[] { return []; } -export function serverMetrics(samples: ReadonlyArray>): ServerMetrics { +type Sample = Record; +const processOf = (sample: Sample) => typeof sample.processId === "string" ? sample.processId : ""; + +function counterBaseline(first: Sample, earlier: readonly Sample[], runStartedAt: number | null, counter: string): number { + const processId = processOf(first); + for (let index = earlier.length - 1; index >= 0; index -= 1) { + const value = num(earlier[index]![counter]); + if (processOf(earlier[index]!) === processId && value !== null) return value; + } + const uptimeSec = num(first.uptimeSec); + const sampledAt = num(first.sampledAt); + if (runStartedAt !== null && uptimeSec !== null && sampledAt !== null && sampledAt - uptimeSec * 1_000 > runStartedAt) return 0; + return num(first[counter]) ?? 0; +} + +function counterGrowth(samples: readonly Sample[], earlier: readonly Sample[], runStartedAt: number | null, counter: string): number | null { + const byProcess = new Map(); + for (const sample of samples) { + if (num(sample[counter]) === null) continue; + const processId = processOf(sample); + byProcess.set(processId, [...byProcess.get(processId) ?? [], sample]); + } + if (byProcess.size === 0) return null; + let growth = 0; + for (const processSamples of byProcess.values()) { + const last = num(processSamples[processSamples.length - 1]![counter])!; + growth += Math.max(0, last - counterBaseline(processSamples[0]!, earlier, runStartedAt, counter)); + } + return growth; +} + +export function serverMetrics(samples: ReadonlyArray, history: { earlier?: readonly Sample[]; runStartedAt?: number | null } = {}): ServerMetrics { const max = (key: string) => { const values = samples.map(sample => num(sample[key])).filter((value): value is number => value !== null); return values.length ? Math.max(...values) : null; }; - const missed = samples.map(sample => num(sample.leaseRenewalsMissed)).filter((value): value is number => value !== null); return { mainThreadCpuMax: max("mainThreadCpu"), eventLoopUtilizationMax: max("eventLoopUtilization"), @@ -144,7 +174,7 @@ export function serverMetrics(samples: ReadonlyArray>): poolWaitP99MsMax: max("poolWaitP99Ms"), runEventLatenessP99MsMax: max("runEventLatenessP99Ms"), agentApiPreHandlerP99MsMax: max("agentApiPreHandlerP99Ms"), - leaseRenewalsMissed: missed.length ? missed[missed.length - 1]! - missed[0]! : null, + leaseRenewalsMissed: counterGrowth(samples, history.earlier ?? [], history.runStartedAt ?? null, "leaseRenewalsMissed"), samples: samples.length, }; } @@ -467,7 +497,10 @@ export class Ramp { firstActivityMs: distribution(accumulator.firstActivityMs), runDurationMs: distribution(runs.flatMap(run => run.startedAt !== null && run.finishedAt !== null ? [run.finishedAt - run.startedAt] : [])), board: { requests: accumulator.boardRequests, failures: accumulator.boardFailures, ms: distribution(accumulator.boardMs) }, - server: serverMetrics(accumulator.serverSamples), + server: serverMetrics(accumulator.serverSamples, { + earlier: this.accumulators.slice(0, stepIndex).flatMap(earlier => earlier.serverSamples), + runStartedAt: this.accumulators[0]?.startedAt ?? null, + }), recordedSpendUsd: Math.round(spend * 100) / 100, }; } diff --git a/scripts/scale-ramp/scale-ramp.test.ts b/scripts/scale-ramp/scale-ramp.test.ts index 8751bde83ad..6a34655e617 100644 --- a/scripts/scale-ramp/scale-ramp.test.ts +++ b/scripts/scale-ramp/scale-ramp.test.ts @@ -1,16 +1,17 @@ import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; import { mkdtemp, readdir, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { after, describe, it } from "node:test"; import { PaperclipClient, Redactor } from "./client.ts"; -import { parseOptions, QUALIFIED_OPENCODE_MODEL } from "./config.ts"; +import { metricsCredential, parseOptions, QUALIFIED_OPENCODE_MODEL, readSecrets } from "./config.ts"; import { evaluate, type StepMetrics } from "./criteria.ts"; import { checkSpend, estimateSpend } from "./estimate.ts"; import { FakePaperclip, VirtualClock, type FakeConfig } from "./fake-paperclip.ts"; import { classifyHost, resolveTarget, TargetRefused } from "./guard.ts"; import { EXIT, main, type MainDeps } from "./main.ts"; -import { Ramp } from "./ramp.ts"; +import { Ramp, serverMetrics } from "./ramp.ts"; import { verdictOf, type RampResult } from "./report.ts"; import { ensureAgents, prepareCompany } from "./setup.ts"; import { distribution } from "./stats.ts"; @@ -246,6 +247,75 @@ describe("criteria", () => { }); }); +describe("server metrics endpoint contract", () => { + const fixture = JSON.parse(readFileSync(new URL("./server-metrics.fixture.json", import.meta.url), "utf8")) as Record; + const SERVER_METRICS_URL = `${ORIGIN}/api/instance/server-metrics`; + + it("parses every finish-line field of the server's own serialized response except pool wait, which the server does not measure", () => { + const parsed = serverMetrics([fixture, { ...fixture, leaseRenewalsMissed: 3 }]); + assert.deepEqual(parsed, { + mainThreadCpuMax: fixture.mainThreadCpu, eventLoopUtilizationMax: fixture.eventLoopUtilization, eventLoopDelayP99MsMax: fixture.eventLoopDelayP99Ms, + statementsPerSecondMax: fixture.statementsPerSecond, poolWaitP99MsMax: null, runEventLatenessP99MsMax: fixture.runEventLatenessP99Ms, + agentApiPreHandlerP99MsMax: fixture.agentApiPreHandlerP99Ms, leaseRenewalsMissed: 2, samples: 2, + }); + assert.equal("poolWaitP99Ms" in fixture, false); + }); + + it("counts missed lease renewals per server process, so samples from several processes never cancel out", () => { + const parsed = serverMetrics([ + { processId: "a", leaseRenewalsMissed: 5 }, { processId: "b", leaseRenewalsMissed: 0 }, + { processId: "a", leaseRenewalsMissed: 6 }, { processId: "b", leaseRenewalsMissed: 2 }, { processId: "a", leaseRenewalsMissed: 6 }, + ]); + assert.equal(parsed.leaseRenewalsMissed, 3); + }); + + it("counts the full counter of a process that started during the run, so a restart cannot hide a missed renewal", () => { + const runStartedAt = 1_000_000; + const earlier = [{ processId: "a", uptimeSec: 3_600, sampledAt: runStartedAt + 10_000, leaseRenewalsMissed: 4 }]; + const parsed = serverMetrics([ + { processId: "a", uptimeSec: 3_630, sampledAt: runStartedAt + 40_000, leaseRenewalsMissed: 4 }, + { processId: "b", uptimeSec: 20, sampledAt: runStartedAt + 70_000, leaseRenewalsMissed: 1 }, + { processId: "b", uptimeSec: 35, sampledAt: runStartedAt + 85_000, leaseRenewalsMissed: 1 }, + ], { earlier, runStartedAt }); + assert.equal(parsed.leaseRenewalsMissed, 1); + }); + + it("keeps a process's counter baseline from earlier steps", () => { + const runStartedAt = 1_000_000; + const earlier = [ + { processId: "a", uptimeSec: 3_600, sampledAt: runStartedAt + 10_000, leaseRenewalsMissed: 4 }, + { processId: "a", uptimeSec: 3_650, sampledAt: runStartedAt + 60_000, leaseRenewalsMissed: 6 }, + ]; + const parsed = serverMetrics([{ processId: "a", uptimeSec: 3_700, sampledAt: runStartedAt + 110_000, leaseRenewalsMissed: 7 }], + { earlier, runStartedAt }); + assert.equal(parsed.leaseRenewalsMissed, 1); + assert.equal(serverMetrics([{ processId: "a", uptimeSec: 3_700, sampledAt: runStartedAt + 110_000, leaseRenewalsMissed: 7 }], { runStartedAt }) + .leaseRenewalsMissed, 0, "a process that predates the run and is first seen now starts from its first sample"); + }); + + it("sends the board token to a metrics URL on the target origin, and no token to another origin", () => { + const options = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack"], { PAPERCLIP_SCALE_METRICS_URL: SERVER_METRICS_URL }, 0); + assert.equal(metricsCredential(options, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN }, null)), TOKEN); + assert.equal(metricsCredential(options, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN, PAPERCLIP_SCALE_METRICS_TOKEN: METRICS_TOKEN }, null)), METRICS_TOKEN); + const elsewhere = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack"], { PAPERCLIP_SCALE_METRICS_URL: METRICS_URL }, 0); + assert.equal(metricsCredential(elsewhere, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN }, null)), null); + }); + + it("measures the server criteria from the server metrics endpoint with the board token in the authorization header", async () => { + const out = await tempDir(); + const h = harness({ metricsUrl: SERVER_METRICS_URL, metrics: () => fixture }, { PAPERCLIP_SCALE_METRICS_URL: SERVER_METRICS_URL }); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + const metricsRequests = h.fake.requests.filter(request => request.url === SERVER_METRICS_URL); + assert.ok(metricsRequests.length > 0); + assert.ok(metricsRequests.every(request => request.authorization === `Bearer ${TOKEN}`)); + assert.equal(result.sources.serverMetrics, "PAPERCLIP_SCALE_METRICS_URL"); + const statuses = Object.fromEntries(result.steps[0]!.criteriaFinal.map(criterion => [criterion.id, criterion.status])); + for (const id of ["main_thread_cpu", "run_event_lateness_p99", "agent_api_pre_handler_p99"]) assert.equal(statuses[id], "pass", id); + assert.equal(statuses.lease_renewals_missed_zero, "pass"); + }); +}); + describe("ramp against the fake API", () => { it("ramps every step, measures it, passes with a metrics endpoint and cleans up", async () => { const out = await tempDir(); diff --git a/scripts/scale-ramp/server-metrics.fixture.json b/scripts/scale-ramp/server-metrics.fixture.json new file mode 100644 index 00000000000..6897aaedfc5 --- /dev/null +++ b/scripts/scale-ramp/server-metrics.fixture.json @@ -0,0 +1,27 @@ +{ + "schema": "paperclip.server-metrics.v1", + "processId": "a1b2c3d4e5f60718", + "buildRevision": "0123456789abcdef0123456789abcdef01234567", + "uptimeSec": 160, + "sampledAt": "2026-11-14T12:01:00.000Z", + "windowMs": 50000, + "mainThreadCpu": 0.42, + "processCpu": 0.55, + "eventLoopUtilization": 0.42, + "eventLoopDelayP99Ms": 0, + "statementsPerSecond": 180, + "runEventLatenessP99Ms": 120.063, + "runEventLatenessSamples": 50, + "agentApiPreHandlerP99Ms": 15.007, + "agentApiPreHandlerSamples": 50, + "leaseRenewalsMissed": 1, + "dedicatedConnections": { + "limit": 24, + "inUse": 3, + "peakInUse": 9, + "waiting": 1, + "queued": 12, + "overLimit": 0, + "nestedOverLimit": 0 + } +} diff --git a/server/src/__tests__/authorization-request-reads.test.ts b/server/src/__tests__/authorization-request-reads.test.ts new file mode 100644 index 00000000000..3a61bd4f7ba --- /dev/null +++ b/server/src/__tests__/authorization-request-reads.test.ts @@ -0,0 +1,290 @@ +import express from "express"; +import request from "supertest"; +import { eq } from "drizzle-orm"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { and, eq as equals } from "drizzle-orm"; +import { authUsers, companyMemberships, instanceUserRoles, issues, projects } from "@paperclipai/db"; +import { actorMiddleware } from "../middleware/auth.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { issueRoutes } from "../routes/issues.js"; +import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerRequest } from "../services/authorization-read-scope.js"; +import { readInstanceAdmin } from "../services/authorization.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; + +describeEmbeddedPostgres("authorization reads per request", () => { + const ctx = useEmbeddedPostgres("authorization-request-reads-"); + + function appFor(userId: string) { + const app = express(); + app.use(express.json()); + app.use(actorMiddleware(ctx.db, { + deploymentMode: "authenticated", + resolveSession: async () => ({ + session: { id: `session-${userId}`, userId }, + user: { id: userId, name: "Reader", email: `${userId}@example.test` }, + }), + })); + app.use(authorizationReadScope); + app.use("/api", issueRoutes(ctx.db, {} as never)); + app.use(errorHandler); + return app; + } + + async function seed(name: string) { + const company = await seedCompanyWithBoardAccess(ctx.db, name); + const now = new Date(); + await ctx.db.insert(authUsers).values({ + id: company.userId, name, email: `${company.userId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now, + }); + const [project] = await ctx.db.insert(projects).values({ companyId: company.companyId, name: `${name} project` }).returning(); + const [issue] = await ctx.db.insert(issues).values({ + companyId: company.companyId, title: `${name} task`, status: "todo", projectId: project!.id, createdByUserId: company.userId, + }).returning(); + return { ...company, issue: issue! }; + } + + it("reads the instance role once per request and the membership once for the authorization of one issue read", async () => { + const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options; + const meter = meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/authorization`); + try { + const fixture = await seed("Reads"); + const app = appFor(fixture.userId); + await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200); + meter.startLog(); + await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200); + const log = meter.stopLog(); + const roleReads = log.filter((entry) => /from "instance_user_roles"/.test(entry.sql)); + const membershipReads = log.filter((entry) => /from "company_memberships"/.test(entry.sql)); + expect(roleReads).toHaveLength(1); + expect(membershipReads).toHaveLength(2); + + meter.startLog(); + await request(app).get(`/api/companies/${fixture.companyId}/issues`).expect(200); + await request(app).get(`/api/companies/${fixture.companyId}/issues/summaries?ids=${fixture.issue.id}`).expect(200); + const listLog = meter.stopLog(); + expect(listLog.filter((entry) => /from "instance_user_roles"/.test(entry.sql))).toHaveLength(2); + } finally { + meter.uninstall(); + } + }, 60_000); + + it("denies the very next request after the membership is removed", async () => { + const fixture = await seed("Revoked"); + const app = appFor(fixture.userId); + await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200); + await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId)); + await request(app).get(`/api/issues/${fixture.issue.id}`).expect(404); + }, 60_000); + function membershipRead(companyId: string, userId: string) { + return readOncePerRequest(`membership:${companyId}:user:${userId}`, () => ctx.db.select({ id: companyMemberships.id }) + .from(companyMemberships) + .where(and(equals(companyMemberships.companyId, companyId), equals(companyMemberships.principalId, userId), + equals(companyMemberships.status, "active"))) + .then((rows) => rows.length > 0)); + } + + function streamApp(userId: string, companyId: string, events: { afterRevoke: Promise; late: (allowed: boolean) => void }) { + const app = express(); + app.use(actorMiddleware(ctx.db, { + deploymentMode: "authenticated", + resolveSession: async () => ({ + session: { id: `session-${userId}`, userId }, + user: { id: userId, name: "Reader", email: `${userId}@example.test` }, + }), + })); + app.use(authorizationReadScope); + app.get("/stream", async (_req, res) => { + const atConnect = await membershipRead(companyId, userId); + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.flushHeaders(); + res.write(`data: ${atConnect}\n\n`); + await events.afterRevoke; + res.end(`data: ${await membershipRead(companyId, userId)}\n\n`); + }); + app.get("/later", async (_req, res) => { + await membershipRead(companyId, userId); + setTimeout(() => { void events.afterRevoke.then(() => membershipRead(companyId, userId)).then(events.late); }, 0); + res.json({ ok: true }); + }); + return app; + } + + it("re-reads the membership during a stream after it is removed", async () => { + const fixture = await seed("Stream"); + let revoked!: () => void; + const afterRevoke = new Promise((resolve) => { revoked = resolve; }); + const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late: () => {} }); + const pending = request(app).get("/stream").buffer(true).parse((res, done) => { + let text = ""; + res.on("data", (chunk: Buffer) => { + text += chunk.toString(); + if (text.includes("data: true") && !text.includes("data: false")) { + void ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId)).then(revoked); + } + }); + res.on("end", () => done(null, text)); + }); + const response = await pending; + expect(response.body).toBe("data: true\n\ndata: false\n\n"); + }, 60_000); + + it("re-reads in a callback that runs after the response and after a revoke", async () => { + const fixture = await seed("Later"); + let revoked!: () => void; + const afterRevoke = new Promise((resolve) => { revoked = resolve; }); + let late!: (allowed: boolean) => void; + const lateResult = new Promise((resolve) => { late = resolve; }); + const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late }); + await request(app).get("/later").expect(200); + await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId)); + revoked(); + expect(await lateResult).toBe(false); + }, 60_000); + + it("seeds the instance role from a session read that matches the authorization predicate", async () => { + const now = new Date(); + const cases = [ + { userId: `user-admin-${Date.now()}`, roles: ["instance_admin"], expected: true }, + { userId: `user-other-${Date.now()}`, roles: ["instance_viewer"], expected: false }, + { userId: `user-none-${Date.now()}`, roles: [], expected: false }, + ]; + for (const entry of cases) { + await ctx.db.insert(authUsers).values({ id: entry.userId, name: entry.userId, email: `${entry.userId}@example.test`, + emailVerified: true, createdAt: now, updatedAt: now }); + if (entry.roles.length) await ctx.db.insert(instanceUserRoles).values(entry.roles.map((role) => ({ userId: entry.userId, role }))); + const app = express(); + app.use(actorMiddleware(ctx.db, { + deploymentMode: "authenticated", + resolveSession: async () => ({ session: { id: `session-${entry.userId}`, userId: entry.userId }, + user: { id: entry.userId, name: "Admin check", email: `${entry.userId}@example.test` } }), + })); + app.get("/actor", (req, res) => { res.json({ isInstanceAdmin: req.actor.isInstanceAdmin }); }); + const seeded = (await request(app).get("/actor").expect(200)).body.isInstanceAdmin; + expect({ seeded, read: await readInstanceAdmin(ctx.db, entry.userId) }).toEqual({ seeded: entry.expected, read: entry.expected }); + } + await ctx.db.delete(instanceUserRoles); + }, 60_000); + + it("treats HEAD like GET for an authorized read and denies it after a revoke", async () => { + const fixture = await seed("Head"); + const app = appFor(fixture.userId); + await request(app).head(`/api/issues/${fixture.issue.id}`).expect(200); + await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId)); + await request(app).head(`/api/issues/${fixture.issue.id}`).expect(404); + }, 60_000); +}); + +describe("authorization read scope boundaries", () => { + afterEach(() => { vi.useRealTimers(); }); + + function countingApp(actor: Express.Request["actor"] = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false }) { + let reads = 0; + const gates: Array<() => void> = []; + const app = express(); + app.use((req, _res, next) => { + req.actor = actor; + next(); + }); + app.use(authorizationReadScope); + app.all("/read", async (req, res) => { + const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => ++reads); + const first = await read(); + if (req.query.wait) await new Promise((resolve) => gates.push(resolve)); + res.json({ first, second: await read(), admin: await readOncePerRequest("admin:user-1", async () => "read") }); + }); + return { app, gates, reads: () => reads }; + } + + it("shares a read only inside one GET request", async () => { + const { app, reads } = countingApp(); + expect((await request(app).get("/read")).body).toEqual({ first: 1, second: 1, admin: false }); + expect((await request(app).get("/read")).body).toEqual({ first: 2, second: 2, admin: false }); + expect(reads()).toBe(2); + }); + + it("reads again for every call in a write request", async () => { + const { app, reads } = countingApp(); + expect((await request(app).post("/read")).body).toEqual({ first: 1, second: 2, admin: "read" }); + expect((await request(app).delete("/read")).body).toEqual({ first: 3, second: 4, admin: "read" }); + expect(reads()).toBe(4); + }); + + it("keeps overlapping GET requests apart", async () => { + const { app, gates } = countingApp(); + const slow = request(app).get("/read?wait=1").then((res) => res.body); + while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5)); + const fast = await request(app).get("/read"); + gates[0]!(); + expect(await slow).toEqual({ first: 1, second: 1, admin: false }); + expect(fast.body).toEqual({ first: 2, second: 2, admin: false }); + }); + it("ignores an entry older than the age bound", async () => { + const { app, gates, reads } = countingApp(); + vi.useFakeTimers({ toFake: ["Date"] }); + const pending = request(app).get("/read?wait=1").then((res) => res.body); + while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5)); + vi.setSystemTime(Date.now() + AUTHORIZATION_READ_MAX_AGE_MS + 1); + gates[0]!(); + expect(await pending).toEqual({ first: 1, second: 2, admin: "read" }); + expect(reads()).toBe(2); + }); + + it("does not keep a rejected read", async () => { + let attempts = 0; + const app = express(); + app.use((req, _res, next) => { + req.actor = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false }; + next(); + }); + app.use(authorizationReadScope); + app.get("/read", async (_req, res) => { + const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => { + attempts += 1; + if (attempts === 1) throw new Error("connection reset"); + return attempts; + }); + const first = await read().catch((error: Error) => error.message); + res.json({ first, second: await read(), third: await read() }); + }); + expect((await request(app).get("/read")).body).toEqual({ first: "connection reset", second: 2, third: 2 }); + }); + + it.each([ + ["an agent key", { type: "agent", source: "agent_key", agentId: "agent-1", companyId: "company-1" }], + ["a board key", { type: "board", source: "board_key", userId: "user-1", isInstanceAdmin: true }], + ["a cloud tenant", { type: "board", source: "cloud_tenant", userId: "user-1", isInstanceAdmin: true }], + ] as const)("seeds nothing for %s", async (_label, actor) => { + const { app } = countingApp(actor as Express.Request["actor"]); + expect((await request(app).get("/read")).body.admin).toBe("read"); + }); + it("keeps response hooks that later middleware installs", async () => { + const app = express(); + app.use(authorizationReadScope); + app.use((_req, res, next) => { + const { writeHead, write } = res; + let writes = 0; + res.writeHead = function (this: typeof res, ...args: Parameters) { + this.setHeader("x-late-hook", "kept"); + return writeHead.apply(this, args); + } as typeof res.writeHead; + res.write = function (this: typeof res, ...args: Parameters) { + writes += 1; + res.locals.writes = writes; + return write.apply(this, args); + } as typeof res.write; + next(); + }); + app.get("/json", (_req, res) => { res.json({ ok: true }); }); + app.get("/stream", (_req, res) => { + res.write("a"); + res.write("b"); + res.end(String(res.locals.writes)); + }); + const json = await request(app).get("/json").expect(200); + expect(json.headers["x-late-hook"]).toBe("kept"); + const stream = await request(app).get("/stream").expect(200); + expect(stream.headers["x-late-hook"]).toBe("kept"); + expect(stream.text).toBe("ab2"); + }); +}); diff --git a/server/src/__tests__/board-route-statement-census.test.ts b/server/src/__tests__/board-route-statement-census.test.ts new file mode 100644 index 00000000000..e2c8d58bf28 --- /dev/null +++ b/server/src/__tests__/board-route-statement-census.test.ts @@ -0,0 +1,29 @@ +import { writeFileSync } from "node:fs"; +import request from "supertest"; +import { expect, it } from "vitest"; +import { boardCensusRoutes, boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js"; +import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; +import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js"; + +describeEmbeddedPostgres("board route statement census", () => { + const ctx = useEmbeddedPostgres("board-route-census-"); + + it("answers every polled and page-load board route and reports statements per request", async () => { + const census = createStatementCensus(ctx.db); + try { + const fixture = await seedBoardRouteFixture(ctx.db, "Census"); + const app = boardSessionApp(ctx.db, () => fixture.userId); + const report: string[] = []; + for (const [label, path] of boardCensusRoutes(fixture)) { + const warm = await request(app).get(path); + expect(warm.status, `${label}: ${JSON.stringify(warm.body)}`).toBe(200); + const measured = await census.measure(() => request(app).get(path).expect(200), { stacks: true }); + expect(measured.statements, label).toBeGreaterThan(0); + report.push(formatStatementCensus(label, measured, Number(process.env.PAPERCLIP_STATEMENT_CENSUS_TOP ?? 5))); + } + if (process.env.PAPERCLIP_STATEMENT_CENSUS) writeFileSync(process.env.PAPERCLIP_STATEMENT_CENSUS, `${report.join("\n\n")}\n`); + } finally { + census.uninstall(); + } + }, 120_000); +}); diff --git a/server/src/__tests__/company-skills-list-statements.test.ts b/server/src/__tests__/company-skills-list-statements.test.ts new file mode 100644 index 00000000000..848ffc7a456 --- /dev/null +++ b/server/src/__tests__/company-skills-list-statements.test.ts @@ -0,0 +1,104 @@ +import request from "supertest"; +import { and, eq, like } from "drizzle-orm"; +import { expect, it } from "vitest"; +import { folders } from "@paperclipai/db"; +import { companySkillRoutes } from "../routes/company-skills.js"; +import { folderService } from "../services/folders.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { describeEmbeddedPostgres, routeApp, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; + +describeEmbeddedPostgres("GET /api/companies/:companyId/skills statements per request", () => { + const ctx = useEmbeddedPostgres("company-skills-list-statements-"); + + function meter() { + const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options; + return meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/skills`); + } + + const bundledFolders = (companyId: string) => ctx.db.select().from(folders) + .where(and(eq(folders.companyId, companyId), like(folders.systemKey, "bundled%"))); + + it("lists skills with plain reads once the bundled folders exist", async () => { + const statements = meter(); + try { + const company = await seedCompanyWithBoardAccess(ctx.db, "Skills list"); + const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db)); + const first = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200); + expect(first.body.length).toBeGreaterThan(0); + const foldersAfterFirst = await bundledFolders(company.companyId); + + const before = statements.read(); + statements.startLog(); + const second = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200); + const log = statements.stopLog(); + const after = statements.read(); + + expect(second.body).toEqual(first.body); + expect(after.transactions - before.transactions).toBe(0); + expect(log.filter((entry) => /pg_advisory/.test(entry.sql))).toEqual([]); + expect(after.statements - before.statements).toBeLessThanOrEqual(45); + expect(await bundledFolders(company.companyId)).toEqual(foldersAfterFirst); + } finally { + statements.uninstall(); + } + }, 60_000); + + it("creates exactly one folder when two first requests ensure the same category at once", async () => { + const company = await seedCompanyWithBoardAccess(ctx.db, "Skills race"); + const [left, right] = await Promise.all([ + folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"), + folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"), + ]); + expect(left.id).toBe(right.id); + const rows = await bundledFolders(company.companyId); + expect(rows.filter((row) => row.systemKey === "bundled:race-category")).toHaveLength(1); + expect(rows.filter((row) => row.systemKey === "bundled")).toHaveLength(1); + + const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db)); + await Promise.all([ + request(app).get(`/api/companies/${company.companyId}/skills`).expect(200), + request(app).get(`/api/companies/${company.companyId}/skills`).expect(200), + ]); + const systemKeys = (await bundledFolders(company.companyId)).map((row) => row.systemKey); + expect(new Set(systemKeys).size).toBe(systemKeys.length); + }, 60_000); + + it("still renames a changed category and prunes an empty one under the lock", async () => { + const statements = meter(); + try { + const company = await seedCompanyWithBoardAccess(ctx.db, "Skills repair"); + const svc = folderService(ctx.db); + const locked = async (write: () => Promise) => { + const before = statements.read(); + statements.startLog(); + await write(); + const log = statements.stopLog(); + const lockIndex = log.findIndex((entry) => /pg_advisory_xact_lock/.test(entry.sql)); + const writes = log.filter((entry) => /^\s*(insert|update|delete)\b/i.test(entry.sql)); + return { + transactions: statements.read().transactions - before.transactions, + lockedBeforeWrite: lockIndex >= 0 && writes.every((entry) => entry.inTransaction && log.indexOf(entry) > lockIndex), + writes: writes.length, + }; + }; + + const created = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category")); + expect(created).toMatchObject({ transactions: 1, lockedBeforeWrite: true }); + expect(created.writes).toBeGreaterThan(0); + const [category] = (await bundledFolders(company.companyId)).filter((row) => row.systemKey === "bundled:repair-category"); + await ctx.db.update(folders).set({ name: "Renamed by hand" }).where(eq(folders.id, category!.id)); + const renamed = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category")); + expect(renamed).toMatchObject({ transactions: 1, lockedBeforeWrite: true, writes: 1 }); + expect((await bundledFolders(company.companyId)).find((row) => row.id === category!.id)?.name).toBe("Repair Category"); + + expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, ["Repair Category"]))) + .toEqual({ transactions: 0, lockedBeforeWrite: false, writes: 0 }); + expect((await bundledFolders(company.companyId)).map((row) => row.id)).toContain(category!.id); + expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, []))) + .toEqual({ transactions: 1, lockedBeforeWrite: true, writes: 1 }); + expect((await bundledFolders(company.companyId)).map((row) => row.id)).not.toContain(category!.id); + } finally { + statements.uninstall(); + } + }, 60_000); +}); diff --git a/server/src/__tests__/environment-task-runtime.test.ts b/server/src/__tests__/environment-task-runtime.test.ts index 35df7431481..68e1df593b0 100644 --- a/server/src/__tests__/environment-task-runtime.test.ts +++ b/server/src/__tests__/environment-task-runtime.test.ts @@ -5,6 +5,7 @@ import { environmentTaskErrorCodeData, environmentTaskOperationSchema, parseEnvi readEnvironmentTaskErrorCode, readEnvironmentTaskErrorDiagnostic } from "@paperclipai/plugin-sdk"; import { executeEnvironmentTask, isSettledReadyRunnerState, settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js"; import { NativeExecutionContext } from "../services/native-runtime/native-execution-context.js"; +import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js"; const state = vi.hoisted(() => ({ plugin: {} as any, release: vi.fn(), identity: vi.fn(), config: vi.fn() })); vi.mock("../services/provider-fresh-workspace.js", () => ({ @@ -344,7 +345,7 @@ describe("plugin-provided Runner execution", () => { await expect(executeEnvironmentTask(database(row(), []).db, denied as never, { companyId: "company", leaseId, operation })).rejects.toThrow("project unavailable"); expect(denied.call).not.toHaveBeenCalled(); }); - it.each([false, true])("prepares scoped configuration with submit-time auth %s", async atSubmit => { + it("accepts prepare launch digests only when they match the requirements", async () => { const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: { schema: "paperclip.runner.launch-requirements.v1" as const, identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run", @@ -353,7 +354,35 @@ describe("plugin-provided Runner execution", () => { settings: {}, approvalPolicy: "on-request" as const, readOnly: false, preparedConversation: false, includeCollaborationModeInstructions: true, } }; - const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}), launch: { configurationId: "configuration-1", + const preparationDigest = runnerLaunchPreparationDigest(operation.requirements); + const runDigest = runnerLaunchRunDigest(preparationDigest, operation.requirements); + const result = { kind: "prepared", taskId: "attempt-1", launch: { configurationId: "configuration-1", + requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } }; + const accepted = worker(result); + await expect(executeEnvironmentTask(database().db, accepted as never, { companyId: "company", leaseId, + operation: { ...operation, preparationDigest, runDigest } })).resolves.toEqual(result); + expect(accepted.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({ + operation: expect.objectContaining({ preparationDigest, runDigest }) }), 15_000); + const forged = `sha256:${"b".repeat(64)}`; + for (const digests of [{ preparationDigest: forged, runDigest }, { preparationDigest, runDigest: forged }, + { preparationDigest }, { runDigest }]) { + const refused = worker(result); + await expect(executeEnvironmentTask(database().db, refused as never, { companyId: "company", leaseId, + operation: { ...operation, ...digests } })).rejects.toThrow("launch digest mismatch"); + expect(refused.call).not.toHaveBeenCalled(); + } + }); + it.each([[false, false], [true, false], [false, true], [true, true]])("prepares scoped configuration with submit-time auth %s and in-prepare auth %s", async (atSubmit, checked) => { + const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: { + schema: "paperclip.runner.launch-requirements.v1" as const, + identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run", + normalizedSessionId: "session", turnId: "turn", itemId: "item" }, + provider: "codex" as const, model: "selected", instructions: "Core instructions", runtimeContext: null, + settings: {}, approvalPolicy: "on-request" as const, readOnly: false, + preparedConversation: false, includeCollaborationModeInstructions: true, + } }; + const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}), + ...(checked ? {projectAuthChecked: true} : {}), launch: { configurationId: "configuration-1", requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } }; const workers = worker(result), store = database(); await expect(executeEnvironmentTask(store.db, workers as never, { companyId: "company", leaseId, operation })) @@ -361,9 +390,10 @@ describe("plugin-provided Runner execution", () => { expect(workers.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({ companyId: "company", runId: "run", agentId: "agent", projectIds: [projectId], operation, }), 15_000); - expect(store.sets).toHaveLength(atSubmit ? 2 : 1); - if (atSubmit) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({ - runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId], atSubmit: true }, + expect(store.sets).toHaveLength(atSubmit || checked ? 2 : 1); + if (atSubmit || checked) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({ + runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId], + ...(checked ? {} : { atSubmit: true }) }, })); const denied = worker(result); const inactive = row(); inactive.lease.status = "released"; diff --git a/server/src/__tests__/fixtures/issue-detail-response.json b/server/src/__tests__/fixtures/issue-detail-response.json new file mode 100644 index 00000000000..e1d98dc1f95 --- /dev/null +++ b/server/src/__tests__/fixtures/issue-detail-response.json @@ -0,0 +1,280 @@ +{ + "id": "", + "companyId": "", + "conversationAgentId": null, + "conversationUserId": null, + "conversationState": null, + "conversationSessionGeneration": 0, + "conversationBoundaryCommentId": null, + "projectId": "", + "projectWorkspaceId": null, + "goalId": null, + "parentId": "", + "visibility": "open", + "privacyRootIssueId": null, + "privacyParentIssueId": null, + "title": "Detail task", + "titleNeedsGeneration": false, + "description": "Uses [@Detail project](project://)", + "status": "in_progress", + "statusVersion": 0, + "lastStatusDecisionId": null, + "workMode": "standard", + "harnessKind": null, + "priority": "high", + "reviewPolicy": null, + "assigneeAgentId": "", + "assigneeUserId": null, + "checkoutRunId": null, + "executionRunId": null, + "executionAgentNameKey": null, + "executionLockedAt": null, + "createdByAgentId": null, + "createdByUserId": "", + "responsibleUserId": null, + "issueNumber": null, + "identifier": null, + "originKind": "manual", + "originId": null, + "originRunId": null, + "originIssueId": null, + "originIdentityContextId": null, + "continuationIdentityContextId": null, + "originFingerprint": "default", + "requestDepth": 0, + "billingCode": null, + "assigneeAdapterOverrides": null, + "executionPolicy": null, + "executionState": null, + "monitorNextCheckAt": null, + "monitorWakeRequestedAt": null, + "monitorLastTriggeredAt": null, + "monitorAttemptCount": 0, + "monitorNotes": null, + "monitorScheduledBy": null, + "executionWorkspaceId": null, + "workspaceBindingRevision": 0, + "workspaceSelection": null, + "workspacePendingSelection": null, + "executionWorkspacePreference": null, + "executionWorkspaceSettings": null, + "sourceTrust": null, + "unblockDescriptor": null, + "blockedTransitionAt": null, + "blockedOwnerNotifiedAt": null, + "startedAt": null, + "completedAt": null, + "cancelledAt": null, + "hiddenAt": null, + "createdAt": "