Merge bounded company review deadline lookup into sleep-06-interrupted-tool-recovery

Preserve the additive index migration and generate the combined snapshot for this PR schema; keep existing migration history intact.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-27 00:58:52 -05:00
commit 94e0cbefde
10 files changed
+3847 -3628

No files matched your search

+7
View File
@@ -111,3 +111,10 @@ behavioral evidence; combined-stack and fresh remote checks remain required.
The full local test:run remains unverified because of embedded PostgreSQL
startup/capacity limits; the two real gateway suites used separate migrated,
task-owned disposable PostgreSQL databases.
A later combined run exposed a test-clock overshoot: repeated blind 30-second
advances could expire the future session before its intermediate assertion.
The settlement helper now lets real SQL settle and advances only to an actually
armed follow-up within the coalescing window. All 12 credential expiry tests pass
on the owning gateway branch with the existing exact-deadline and transaction
assertions intact. This follow-up changes the test fixture only.
+41 -1
View File
@@ -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.
+1
View File
@@ -505,6 +505,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
"0379_narrow_the_executioner.sql",
"0381_open_madame_web.sql",
"0380_funny_adam_warlock.sql",
"0402_tool_review_company_expiry.sql",
]);
async function applyPendingMigrationsManually(
@@ -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';
File diff suppressed because it is too large. Load diff
+8 -1
View File
@@ -2661,6 +2661,13 @@
"when": 1792863626931,
"tag": "0381_open_madame_web",
"breakpoints": true
},
{
"idx": 402,
"version": "7",
"when": 1793080350746,
"tag": "0402_tool_review_company_expiry",
"breakpoints": true
}
]
}
}
+2
View File
@@ -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_executing_deadline_idx").on(table.updatedAt, table.id).where(sql`${table.status} = 'executing'`),
index("tool_action_requests_approved_idx").on(table.id).where(sql`${table.status} = 'approved'`),
index("tool_action_requests_invocation_idx").on(table.invocationId),
@@ -60,8 +60,15 @@ describe.skipIf(!supported)("gateway credential expiry", () => {
async function settle(ms = 60_000) {
await vi.advanceTimersByTimeAsync(ms);
if (!draining) await vi.waitFor(async () => {
// SQL may finish after the clock jump and arm a coalesced follow-up pass.
if (idleWorkSnapshot().active > 0) await vi.advanceTimersByTimeAsync(30_000);
// Let real SQL settle before advancing only to an actually armed follow-up.
// Repeated blind clock jumps can expire the future credential under test.
if (idleWorkSnapshot().active > 0) {
await db.execute(sql`select pg_sleep(0.01)`);
const next = coordinator!.nextWakeAt();
if (next !== null && next <= Date.now() + 30_000) {
await vi.advanceTimersByTimeAsync(Math.max(0, next - Date.now()));
}
}
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 5000 });
}
@@ -1092,7 +1092,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++) {
@@ -1112,6 +1112,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<typeof db.$client.unsafe>[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);
@@ -1133,10 +1187,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);
+9 -6
View File
@@ -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<string | Date>`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<string | Date>`min(${toolActionRequests.expiresAt})` })
.from(toolActionRequests).where(pendingExpiry).groupBy(toolActionRequests.companyId)
: await db.select({ companyId: toolActionRequests.companyId,
at: sql<Date>`${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() }));
},
};