diff --git a/doc/idle-tool-review-expiry.md b/doc/idle-tool-review-expiry.md index 25cf4df743d..88ecf4d502e 100644 --- a/doc/idle-tool-review-expiry.md +++ b/doc/idle-tool-review-expiry.md @@ -59,7 +59,10 @@ expiry has its own startup pass or worker. Approved-action recovery, interrupted execution quarantine, and terminal projection repair retain their behavior. An unknown external outcome is never replayed by this expiry worker. -The next deadline comes from pending rows only, using a partial expiry index. +The next deadline comes from pending rows only. Startup uses the existing +partial expiry index to reconstruct company deadlines. A company notification +uses an ordered, single-row lookup backed by the partial `(company_id, +expires_at)` index, rather than aggregating that company's pending backlog. Null-expiry unsigned requests and retained resolved history do not keep this worker active. The concurrent index migration uses the existing top-level executor and is safe to apply again after interruption. @@ -94,3 +97,40 @@ The external test database override requires a disposable database ending in This is one worker migration, not proof that the instance can sleep. Other tool review duties remain periodic. Existing Cloud sleep-safety gates and external alarm coverage are unchanged. An in-process deadline cannot wake a stopped host. + +## Scoped lookup review repair (2026-10-27) + +The original scoped aggregate examined 12,004 rows to return one deadline in a +real PostgreSQL regression. The repaired lookup returns the earliest non-null +pending expiry for the requested company with `ORDER BY expires_at LIMIT 1`. +The grouped startup inventory remains unchanged. Existing company signals, +authority checks, expiry settlement, paging, backoff, and sleep gates remain +owned by their existing services. + +The generated additive migration reserves number 0402 because later PRs in this +stack already own 0380 through 0401. It builds the new index concurrently and +idempotently through the existing top-level migration executor. No old SQL +migration is edited. Combined snapshots must be generated from each branch's +merged schema, retaining the five newest snapshots, so the reserved later +number cannot hide descendant schema changes from future generation. + +Two failures shaped the repair. The first migration attempt omitted its explicit +top-level registration and PostgreSQL rejected the concurrent build inside a +transaction; adding the registration fixed application and replay. An initial +three-column index also lost to the global expiry index in the planner, which +filtered 12,001 foreign-company rows before returning a result. The final index +omits the unused request ID. With 12,000 additional pending rows in each of two +companies, including earlier foreign deadlines, all three measured reloads +examine one row. The assertion counts filtered rows as well as returned rows. +This is evidence for the recorded fixture and query plan, not a production +latency guarantee or a claim that PostgreSQL can never choose another plan. + +The complete gateway service, gateway acceptance, credential expiry, startup, +custom-image deadline, and schema snapshot suites pass: 223 tests across six +files. The run also exposed a credential test-clock overshoot; its correction +belongs to the earlier gateway PR and waits for real SQL before advancing to +an actually armed follow-up. Commit/rollback and exact expiry assertions remain. +Server typechecking passes. Combined-stack migration upgrades, full build, and +fresh remote checks remain required. Full local test:run is still unverified +because of embedded PostgreSQL startup/capacity limits; real gateway suites used +isolated, migrated test databases in the task-owned PostgreSQL instance. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index ddeb79670ee..14e88fe471d 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -503,6 +503,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0369_late_logan.sql", "0378_mean_scream.sql", "0379_narrow_the_executioner.sql", + "0402_tool_review_company_expiry.sql", ]); async function applyPendingMigrationsManually( diff --git a/packages/db/src/migrations/0402_tool_review_company_expiry.sql b/packages/db/src/migrations/0402_tool_review_company_expiry.sql new file mode 100644 index 00000000000..75a364ecdf1 --- /dev/null +++ b/packages/db/src/migrations/0402_tool_review_company_expiry.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "tool_action_requests_company_pending_expiry_idx" ON "tool_action_requests" USING btree ("company_id","expires_at") WHERE "tool_action_requests"."status" = 'pending'; \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0375_snapshot.json b/packages/db/src/migrations/meta/0402_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0375_snapshot.json rename to packages/db/src/migrations/meta/0402_snapshot.json index 7bd1861bd2c..6eb9085d3b4 100644 --- a/packages/db/src/migrations/meta/0375_snapshot.json +++ b/packages/db/src/migrations/meta/0402_snapshot.json @@ -1,6 +1,6 @@ { - "id": "3e17203b-ec95-41e9-8363-685982450199", - "prevId": "945c31ed-f39f-4272-a91d-85de925f5361", + "id": "99cc707d-cf42-4cf5-84c2-22550ff080b3", + "prevId": "b8e3cf47-6bf6-487f-adee-5642c0f97ea8", "version": "7", "dialect": "postgresql", "tables": { @@ -52787,6 +52787,50 @@ "method": "btree", "with": {} }, + "tool_action_requests_pending_expiry_idx": { + "name": "tool_action_requests_pending_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_company_pending_expiry_idx": { + "name": "tool_action_requests_company_pending_expiry_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_action_requests_invocation_idx": { "name": "tool_action_requests_invocation_idx", "columns": [ @@ -55197,6 +55241,21 @@ "method": "btree", "with": {} }, + "tool_gateway_sessions_expiry_idx": { + "name": "tool_gateway_sessions_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_gateway_sessions_run_idx": { "name": "tool_gateway_sessions_run_idx", "columns": [ diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 37bb3bf609e..ff9cc3344ce 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2647,6 +2647,13 @@ "when": 1792861791949, "tag": "0379_narrow_the_executioner", "breakpoints": true + }, + { + "idx": 402, + "version": "7", + "when": 1793080350746, + "tag": "0402_tool_review_company_expiry", + "breakpoints": true } ] -} \ No newline at end of file +} diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index 000922351bb..2ebdbcb94e0 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -830,6 +830,8 @@ export const toolActionRequests = pgTable( index("tool_action_requests_company_status_idx").on(table.companyId, table.status), index("tool_action_requests_pending_expiry_idx").on(table.expiresAt, table.id) .where(sql`${table.status} = 'pending'`), + index("tool_action_requests_company_pending_expiry_idx").on(table.companyId, table.expiresAt) + .where(sql`${table.status} = 'pending'`), index("tool_action_requests_invocation_idx").on(table.invocationId), index("tool_action_requests_issue_idx").on(table.companyId, table.issueId), ], diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 1dee432b5d1..c4f7e8a2681 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -332,7 +332,7 @@ describeEmbeddedPostgres("tool gateway service", () => { const debug = db.$client.options.debug; db.$client.options.debug = (_id, query, params) => { if (/^select/i.test(query) && query.includes('"tool_action_requests"') && - (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + (query.includes('min(') || query.includes('"expires_at" <=') || query.includes('"expires_at" is not null'))) reads.push({ query, params: [...params] }); }; try { for (let index = 0; index < 3; index++) { @@ -352,6 +352,60 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt!.getTime()); }); + it("reads one indexed deadline from a large company backlog on repeated reloads", async () => { + const pending = await request(); + const foreignContext = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(foreignContext.company)); + const foreign = await requestWithExpiry(new Date(Date.now() + 1000), foreignContext); + await db.execute(sql`insert into tool_action_requests + (company_id, invocation_id, canonical_arguments_hash, canonical_arguments_summary, expires_at) + select ${fixture.company.id}, ${pending.invocationId}, 'backlog', '{}'::jsonb, + ${pending.expiresAt!.toISOString()}::timestamptz + n * interval '1 second' + from generate_series(1, 12000) n`); + await db.execute(sql`insert into tool_action_requests + (company_id, invocation_id, canonical_arguments_hash, canonical_arguments_summary, expires_at) + select ${foreignContext.company.id}, ${foreign.invocationId}, 'foreign backlog', '{}'::jsonb, + ${foreign.expiresAt!.toISOString()}::timestamptz - n * interval '1 second' + from generate_series(1, 12000) n`); + await db.insert(toolActionRequests).values([ + { ...pending, id: randomUUID(), interactionId: null, expiresAt: null }, + { ...pending, id: randomUUID(), interactionId: null, status: "rejected", expiresAt: new Date(0) }, + ]); + await db.execute(sql`analyze tool_action_requests`); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"')) reads.push({ query, params: [...params] }); + }; + try { + for (let i = 0; i < 3; i++) { + expect(await gateway.actionReviewExpiryDeadlines(fixture.company.id)).toEqual([ + { companyId: fixture.company.id, dueAt: pending.expiresAt!.getTime() }, + ]); + } + } finally { db.$client.options.debug = debug; } + expect(reads).toHaveLength(3); + type Plan = { "Node Type": string; "Actual Rows": number; "Actual Loops": number; + "Rows Removed by Filter"?: number; "Rows Removed by Index Recheck"?: number; Plans?: Plan[] }; + const scannedRows = (plan: Plan): number => + (/Scan/.test(plan["Node Type"]) ? (plan["Actual Rows"] + (plan["Rows Removed by Filter"] ?? 0) + + (plan["Rows Removed by Index Recheck"] ?? 0)) * plan["Actual Loops"] : 0) + + (plan.Plans ?? []).reduce((count, child) => count + scannedRows(child), 0); + for (const read of reads) { + const [result] = await db.$client.unsafe( + `explain (analyze, buffers, format json) ${read.query}`, + read.params as Parameters[1], + ); + const plan = result["QUERY PLAN"][0].Plan as Plan; + expect(scannedRows(plan), JSON.stringify(plan)).toBeLessThanOrEqual(1); + } + expect(await gateway.actionReviewExpiryDeadlines(randomUUID())).toEqual([]); + expect(await gateway.actionReviewExpiryDeadlines()).toEqual(expect.arrayContaining([ + { companyId: fixture.company.id, dueAt: pending.expiresAt!.getTime() }, + { companyId: foreignContext.company.id, dueAt: foreign.expiresAt!.getTime() - 12_000_000 }, + ])); + }); + it("preserves a five-second deadline and an earlier committed replacement", async () => { await start(); await quiet(); const later = await requestWithExpiry(new Date(Date.now() + 120_000)); await settle(1); @@ -373,10 +427,10 @@ describeEmbeddedPostgres("tool gateway service", () => { const debug = db.$client.options.debug; db.$client.options.debug = (_id, query, params) => { if (/^select/i.test(query) && query.includes('"tool_action_requests"') && - (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + (query.includes('min(') || query.includes('"expires_at" <=') || query.includes('"expires_at" is not null'))) reads.push({ query, params: [...params] }); }; try { await settle(6000); } finally { db.$client.options.debug = debug; } - expect(reads.some(read => read.query.includes('"expires_at" <='))).toBe(true); + expect(reads.some(read => read.query.includes('"expires_at" <=') || query.includes('"expires_at" is not null'))).toBe(true); for (const read of reads) { expect(read.query).toContain('"tool_action_requests"."company_id" ='); expect(read.params).toContain(fixture.company.id); diff --git a/server/src/services/tool-review-expiry.ts b/server/src/services/tool-review-expiry.ts index 69e9b557349..8db647ce149 100644 --- a/server/src/services/tool-review-expiry.ts +++ b/server/src/services/tool-review-expiry.ts @@ -18,12 +18,15 @@ export function toolReviewExpiryService(db: Db, onExpired: (input: { sweep, sweepForCompany: (companyId: string) => sweep(new Date(), companyId, 1), async deadlines(companyId?: string) { - const rows = await db.select({ companyId: toolActionRequests.companyId, - at: sql`min(${toolActionRequests.expiresAt})` }) - .from(toolActionRequests).where(and(eq(toolActionRequests.status, "pending"), - isNotNull(toolActionRequests.expiresAt), - companyId === undefined ? undefined : eq(toolActionRequests.companyId, companyId))) - .groupBy(toolActionRequests.companyId); + const pendingExpiry = and(eq(toolActionRequests.status, "pending"), isNotNull(toolActionRequests.expiresAt)); + const rows = companyId === undefined + ? await db.select({ companyId: toolActionRequests.companyId, + at: sql`min(${toolActionRequests.expiresAt})` }) + .from(toolActionRequests).where(pendingExpiry).groupBy(toolActionRequests.companyId) + : await db.select({ companyId: toolActionRequests.companyId, + at: sql`${toolActionRequests.expiresAt}` }) + .from(toolActionRequests).where(and(pendingExpiry, eq(toolActionRequests.companyId, companyId))) + .orderBy(asc(toolActionRequests.expiresAt)).limit(1); return rows.map(row => ({ companyId: row.companyId, dueAt: new Date(row.at).getTime() })); }, };