mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
Preserve fair seeding retries and bootstrap external test databases
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
a1dc7bc192
commit
7948136ef8
4 files changed
+94
-12
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { activityLog, approvals, companies, createDb, decisionQueueItems, decisionQueues, decisionRetention, decisionTriageEvents, issueApprovals, issues, issueWorkProducts, subscribeDatabaseWork, type Db } from "@paperclipai/db";
|
||||
import { activityLog, approvals, companies, createDb, applyPendingMigrations, decisionQueueItems, decisionQueues, decisionRetention, decisionTriageEvents, issueApprovals, issues, issueWorkProducts, subscribeDatabaseWork, type Db } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { approvalRecords } from "../services/approvals.js";
|
||||
@@ -26,7 +26,8 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
let draining = false;
|
||||
const errors: unknown[] = [];
|
||||
beforeAll(async () => {
|
||||
if (!external) temporary = await startEmbeddedPostgresTestDatabase("approval-queue-");
|
||||
if (external) await applyPendingMigrations(external);
|
||||
else temporary = await startEmbeddedPostgresTestDatabase("approval-queue-");
|
||||
db = createDb(external ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
||||
}, 30_000);
|
||||
beforeEach(async () => {
|
||||
@@ -310,6 +311,57 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
expect(await service.next()).toBeNull();
|
||||
});
|
||||
|
||||
it("resets consecutive failure backoff after a successful batch with remaining debt", async () => {
|
||||
const target = await issue(); await product(target.id);
|
||||
const rows = await db.insert(approvals).values(Array.from({ length: 101 }, () => ({
|
||||
companyId, type: "request_board_approval", payload: {},
|
||||
}))).returning();
|
||||
await db.insert(issueApprovals).values(rows.map(row => ({ companyId, issueId: target.id, approvalId: row.id })));
|
||||
const service = approvalQueueSeedingService(db);
|
||||
await db.execute(sql`create function approval_queue_fail() returns trigger language plpgsql as $$ begin raise exception 'projection unavailable'; end $$`);
|
||||
const fail = () => db.execute(sql`create trigger approval_queue_fail before insert on decision_queue_items for each row execute function approval_queue_fail()`);
|
||||
await fail();
|
||||
for (let attempt = 0; attempt < 7; attempt++) {
|
||||
await expect(service.sweep()).rejects.toThrow();
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
}
|
||||
await db.execute(sql`drop trigger approval_queue_fail on decision_queue_items`);
|
||||
await service.sweep();
|
||||
expect(await memberships()).toHaveLength(1); expect(service.next()).not.toBeNull();
|
||||
await fail();
|
||||
const at = Date.now(); const clock = vi.spyOn(Date, "now").mockReturnValue(at);
|
||||
try {
|
||||
await expect(service.sweep()).rejects.toThrow("Approval queue seeding failed");
|
||||
expect(service.next()).toBe(at + 1000);
|
||||
} finally { clock.mockRestore(); }
|
||||
await db.execute(sql`drop trigger approval_queue_fail on decision_queue_items`);
|
||||
await vi.advanceTimersByTimeAsync(60_000); await service.sweep();
|
||||
expect(service.next()).not.toBeNull(); await service.sweep();
|
||||
expect(await memberships()).toHaveLength(101); expect(service.next()).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves outage backoff across an empty cursor rollover", async () => {
|
||||
const target = await issue(); await product(target.id);
|
||||
const rows = await db.insert(approvals).values(Array.from({ length: 100 }, () => ({
|
||||
companyId, type: "request_board_approval", payload: {},
|
||||
}))).returning();
|
||||
await db.insert(issueApprovals).values(rows.map(row => ({ companyId, issueId: target.id, approvalId: row.id })));
|
||||
const service = approvalQueueSeedingService(db);
|
||||
await db.execute(sql`create function approval_queue_fail() returns trigger language plpgsql as $$ begin raise exception 'projection unavailable'; end $$`);
|
||||
await db.execute(sql`create trigger approval_queue_fail before insert on decision_queue_items for each row execute function approval_queue_fail()`);
|
||||
await expect(service.sweep()).rejects.toThrow("Approval queue seeding failed");
|
||||
await vi.advanceTimersByTimeAsync(1000); await service.sweep();
|
||||
expect(await memberships()).toEqual([]); expect(service.next()).not.toBeNull();
|
||||
const at = Date.now(); const clock = vi.spyOn(Date, "now").mockReturnValue(at);
|
||||
try {
|
||||
await expect(service.sweep()).rejects.toThrow("Approval queue seeding failed");
|
||||
expect(service.next()).toBe(at + 2000);
|
||||
} finally { clock.mockRestore(); }
|
||||
await db.execute(sql`drop trigger approval_queue_fail on decision_queue_items`);
|
||||
await vi.advanceTimersByTimeAsync(60_000); await service.sweep(); await service.sweep();
|
||||
expect(await memberships()).toHaveLength(100); expect(service.next()).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps backoff SQL-quiet while another company's committed work proceeds", async () => {
|
||||
const service = approvalQueueSeedingService(db), sweep = service.sweep;
|
||||
let running = false;
|
||||
@@ -377,6 +429,31 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
await service.sweep(); expect(await memberships()).toHaveLength(101); expect(await service.next()).toBeNull();
|
||||
});
|
||||
|
||||
it("retries a failed membership while new matching pages keep arriving", async () => {
|
||||
const target = await issue(); await product(target.id);
|
||||
const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
|
||||
const append = async (start: number, count: number) => {
|
||||
const rows = await db.insert(approvals).values(Array.from({ length: count }, (_, offset) => ({
|
||||
id: id(start + offset), companyId, type: "request_board_approval", payload: {},
|
||||
}))).returning();
|
||||
await db.insert(issueApprovals).values(rows.map(row => ({ companyId, issueId: target.id, approvalId: row.id })));
|
||||
};
|
||||
const service = approvalQueueSeedingService(db); await service.sweep();
|
||||
await append(1, 101); service.request(new Set([companyId]));
|
||||
await db.execute(sql`create function approval_queue_fail() returns trigger language plpgsql as $$ begin
|
||||
if new.source_id = TG_ARGV[0] then raise exception 'projection unavailable'; end if; return new; end $$`);
|
||||
await db.execute(sql`create trigger approval_queue_fail before insert on decision_queue_items for each row execute function approval_queue_fail(${sql.raw("'" + id(1) + "'")})`);
|
||||
await expect(service.sweep()).rejects.toThrow("Failed query");
|
||||
await append(102, 100); service.request(new Set([companyId]));
|
||||
await vi.advanceTimersByTimeAsync(1000); await service.sweep();
|
||||
await append(202, 100); service.request(new Set([companyId]));
|
||||
await db.execute(sql`drop trigger approval_queue_fail on decision_queue_items`);
|
||||
await service.sweep();
|
||||
expect((await memberships()).some(row => row.sourceId === id(1))).toBe(true);
|
||||
for (let pass = 0; pass < 4 && service.next() !== null; pass++) await service.sweep();
|
||||
expect(await memberships()).toHaveLength(301); expect(service.next()).toBeNull();
|
||||
});
|
||||
|
||||
it("rechecks the approval after a concurrent resolution commits", async () => {
|
||||
const approval = await pending(); let release!: () => void, locked!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; }), admitted = new Promise<void>(resolve => { locked = resolve; });
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
agents,
|
||||
approvals,
|
||||
companies,
|
||||
createDb,
|
||||
createDb, applyPendingMigrations,
|
||||
decisionQueueItems,
|
||||
decisionQueues,
|
||||
decisionTriage,
|
||||
@@ -42,7 +42,8 @@ describeEmbeddedPostgres("decision queue routes", () => {
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!external) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-decision-queues-");
|
||||
if (external) await applyPendingMigrations(external);
|
||||
else tempDb = await startEmbeddedPostgresTestDatabase("paperclip-decision-queues-");
|
||||
db = createDb(external ?? tempDb!.connectionString);
|
||||
}, 30_000);
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
agents,
|
||||
approvals,
|
||||
companies,
|
||||
createDb,
|
||||
createDb, applyPendingMigrations,
|
||||
documents,
|
||||
heartbeatRuns,
|
||||
issueComments,
|
||||
@@ -45,7 +45,8 @@ describeEmbeddedPostgres("task watchdog scheduler", () => {
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!externalUrl) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-task-watchdogs-scheduler-");
|
||||
if (externalUrl) await applyPendingMigrations(externalUrl);
|
||||
else tempDb = await startEmbeddedPostgresTestDatabase("paperclip-task-watchdogs-scheduler-");
|
||||
db = createDb(externalUrl ?? tempDb!.connectionString);
|
||||
}, 20_000);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, asc, eq, gt, sql, type SQL } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, gt, lte, sql, type SQL } from "drizzle-orm";
|
||||
import { approvals, companies, issues, issueWorkProducts, type Db } from "@paperclipai/db";
|
||||
import { firstApprovalIssueId } from "./approval-visibility.js";
|
||||
import { executionIssueCondition } from "./issue-visibility.js";
|
||||
@@ -10,7 +10,7 @@ import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
|
||||
const linkedIssue = firstApprovalIssueId();
|
||||
|
||||
export function approvalQueueSeedingService(db: Db) {
|
||||
const pending = new Map<string | undefined, { cursor?: string; generation: number; failures: number; retryAt: number }>([[undefined, { generation: 0, failures: 0, retryAt: 0 }]]);
|
||||
const pending = new Map<string | undefined, { cursor?: string; end?: string; generation: number; failures: number; retryAt: number }>([[undefined, { generation: 0, failures: 0, retryAt: 0 }]]);
|
||||
function request(companyIds: ReadonlySet<string> | undefined) {
|
||||
for (const companyId of companyIds ?? []) {
|
||||
const existing = pending.get(companyId);
|
||||
@@ -18,7 +18,7 @@ export function approvalQueueSeedingService(db: Db) {
|
||||
else pending.set(companyId, { generation: 0, failures: 0, retryAt: 0 });
|
||||
}
|
||||
}
|
||||
function candidates(database: Db, companyId: string | undefined, condition?: SQL) {
|
||||
function candidates(database: Db, companyId: string | undefined, condition?: SQL, order = asc) {
|
||||
return database.select({ id: approvals.id, companyId: approvals.companyId, issueId: linkedIssue }).from(approvals)
|
||||
.innerJoin(companies, eq(companies.id, approvals.companyId))
|
||||
.where(and(eq(approvals.status, "pending"), eq(companies.status, "active"), companyId === undefined ? undefined : eq(approvals.companyId, companyId), condition,
|
||||
@@ -29,7 +29,7 @@ export function approvalQueueSeedingService(db: Db) {
|
||||
sql`not exists (select 1 from decision_queues queue where queue.company_id = ${approvals.companyId} and queue.key = 'prs'
|
||||
and (not queue.seed_rules_enabled or exists (select 1 from decision_queue_items item where item.queue_id = queue.id
|
||||
and item.company_id = ${approvals.companyId} and item.source_kind = 'approval' and item.source_id = ${approvals.id}::text)))`,
|
||||
)).orderBy(asc(approvals.id));
|
||||
)).orderBy(order(approvals.id));
|
||||
}
|
||||
async function sweep(signal?: AbortSignal) {
|
||||
const scope = [...pending.entries()].find(([, state]) => state.retryAt <= Date.now());
|
||||
@@ -37,7 +37,9 @@ export function approvalQueueSeedingService(db: Db) {
|
||||
const [companyId, state] = scope;
|
||||
try {
|
||||
const generation = state.generation;
|
||||
const rows = await candidates(db, companyId, state.cursor ? gt(approvals.id, state.cursor) : undefined).limit(100);
|
||||
state.end ??= (await candidates(db, companyId, undefined, desc).limit(1))[0]?.id;
|
||||
const rows = state.end ? await candidates(db, companyId, and(lte(approvals.id, state.end),
|
||||
state.cursor ? gt(approvals.id, state.cursor) : undefined)).limit(100) : [];
|
||||
const errors: unknown[] = [];
|
||||
for (const row of rows) {
|
||||
if (signal?.aborted) break;
|
||||
@@ -53,11 +55,12 @@ export function approvalQueueSeedingService(db: Db) {
|
||||
} catch (error) { errors.push(error); }
|
||||
state.cursor = row.id;
|
||||
}
|
||||
if (rows.length < 100) state.cursor = undefined;
|
||||
if (rows.length < 100) { state.cursor = undefined; state.end = undefined; }
|
||||
const remaining = await candidates(db, companyId).limit(1);
|
||||
if (!signal?.aborted && generation === state.generation && remaining.length === 0) pending.delete(companyId);
|
||||
if (errors.length === 1) throw errors[0];
|
||||
if (errors.length) throw new AggregateError(errors, "Approval queue seeding failed");
|
||||
if (rows.length > 0 || remaining.length === 0) state.failures = 0;
|
||||
state.retryAt = 0;
|
||||
} catch (error) {
|
||||
state.failures = Math.min(state.failures + 1, 7);
|
||||
|
||||
Reference in new issue
Block a user