mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
Bound confirmation recovery reads with a concurrent partial index
Align company/id keyset pagination with the sparse work index and keep fixed work predicates eligible for prepared plans. Prove real discovery SQL avoids retained completed history. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
f6cbdf6eee
commit
fa5e02f4e2
7 files changed
+304
-7
No files matched your search
@@ -549,6 +549,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
|
||||
"0395_tranquil_firestar.sql",
|
||||
"0396_tan_paladin.sql",
|
||||
"0397_known_madrox.sql",
|
||||
"0398_yielding_random.sql",
|
||||
|
||||
|
||||
"0384_funny_adam_warlock.sql",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_confirmation_recovery_idx" ON "chat_actions" USING btree ("company_id","id") WHERE "chat_actions"."kind" = 'confirmation_response' AND "chat_actions"."status" = 'processing';
|
||||
+201
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"id": "e1ddc6f7-6335-4b3d-aeec-a5df27793874",
|
||||
"prevId": "6974dd25-b8e9-4143-b4b7-ee5a5c3ff54a",
|
||||
"id": "7f056258-4b1a-4828-b950-33f070fc0c47",
|
||||
"prevId": "c7947622-f079-44c9-a57a-5a11d1bec5e8",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
@@ -1350,6 +1350,34 @@
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"activity_log_company_user_issue_actor_idx": {
|
||||
"name": "activity_log_company_user_issue_actor_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "actor_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "entity_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"where": "\"activity_log\".\"actor_type\" = 'user' AND \"activity_log\".\"entity_type\" = 'issue'",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
@@ -9596,6 +9624,28 @@
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"chat_actions_confirmation_recovery_idx": {
|
||||
"name": "chat_actions_confirmation_recovery_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"where": "\"chat_actions\".\"kind\" = 'confirmation_response' AND \"chat_actions\".\"status\" = 'processing'",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"chat_actions_provider_action_uq": {
|
||||
"name": "chat_actions_provider_action_uq",
|
||||
"columns": [
|
||||
@@ -14160,6 +14210,24 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"provider_account_id": {
|
||||
"name": "provider_account_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"cleanup_confirmed_at": {
|
||||
"name": "cleanup_confirmed_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"cleanup_next_attempt_at": {
|
||||
"name": "cleanup_next_attempt_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "timestamp with time zone",
|
||||
@@ -14182,6 +14250,22 @@
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"chat_voice_inbound_cleanup_idx": {
|
||||
"name": "chat_voice_inbound_cleanup_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"where": "\"chat_voice_inbound_calls\".\"cleanup_confirmed_at\" is null",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"chat_voice_inbound_expiry_idx": {
|
||||
"name": "chat_voice_inbound_expiry_idx",
|
||||
"columns": [
|
||||
@@ -14934,6 +15018,28 @@
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"chat_voice_sessions_report_window_idx": {
|
||||
"name": "chat_voice_sessions_report_window_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "ended_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"where": "\"chat_voice_sessions\".\"state\" in ('ended', 'failed', 'expired') and \"chat_voice_sessions\".\"provider_session_id\" is not null",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
@@ -42987,6 +43093,99 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.native_runner_checkpoints": {
|
||||
"name": "native_runner_checkpoints",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"run_id": {
|
||||
"name": "run_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"issue_id": {
|
||||
"name": "issue_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"part": {
|
||||
"name": "part",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"material": {
|
||||
"name": "material",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"native_runner_checkpoints_headers_idx": {
|
||||
"name": "native_runner_checkpoints_headers_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "run_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"where": "\"native_runner_checkpoints\".\"part\" = 'header'",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"native_runner_checkpoints_company_id_issue_id_run_id_heartbeat_runs_company_id_native_issue_id_id_fk": {
|
||||
"name": "native_runner_checkpoints_company_id_issue_id_run_id_heartbeat_runs_company_id_native_issue_id_id_fk",
|
||||
"tableFrom": "native_runner_checkpoints",
|
||||
"tableTo": "heartbeat_runs",
|
||||
"columnsFrom": [
|
||||
"company_id",
|
||||
"issue_id",
|
||||
"run_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"company_id",
|
||||
"native_issue_id",
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {
|
||||
"native_runner_checkpoints_run_id_part_pk": {
|
||||
"name": "native_runner_checkpoints_run_id_part_pk",
|
||||
"columns": [
|
||||
"run_id",
|
||||
"part"
|
||||
]
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.pipeline_automation_executions": {
|
||||
"name": "pipeline_automation_executions",
|
||||
"schema": "",
|
||||
+7
@@ -2773,6 +2773,13 @@
|
||||
"when": 1793195976732,
|
||||
"tag": "0397_known_madrox",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 398,
|
||||
"version": "7",
|
||||
"when": 1793216165150,
|
||||
"tag": "0398_yielding_random",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -673,6 +673,9 @@ export const chatActions = pgTable(
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
index("chat_actions_confirmation_recovery_idx")
|
||||
.on(table.companyId, table.id)
|
||||
.where(sql`${table.kind} = 'confirmation_response' AND ${table.status} = 'processing'`),
|
||||
uniqueIndex("chat_actions_provider_action_uq").on(
|
||||
table.endpointId,
|
||||
table.providerActionId,
|
||||
|
||||
@@ -45837,6 +45837,89 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("bounds terminal confirmation recovery reads with completed history", async () => {
|
||||
const waiting = await telegramConfirmationRecoveryFixture();
|
||||
const prefix = `confirmation-plan:${randomUUID()}:`;
|
||||
await db.execute(sql`
|
||||
INSERT INTO chat_actions (company_id, endpoint_id, kind, provider_action_id, status)
|
||||
SELECT ${waiting.fixture.companyId}::uuid, ${waiting.endpoint.id}::uuid,
|
||||
CASE WHEN n <= 10000 THEN 'confirmation_response' ELSE 'unrelated_action' END,
|
||||
${prefix} || n,
|
||||
CASE WHEN n <= 10000 THEN 'processed' ELSE 'processing' END
|
||||
FROM generate_series(1, 20000) AS n
|
||||
`);
|
||||
await db.update(chatActions).set({ status: "processing", result: null })
|
||||
.where(eq(chatActions.id, waiting.acceptAction.id));
|
||||
await db.execute(sql`ANALYZE chat_actions`);
|
||||
const statements: { sql: string; params: unknown[] }[] = [];
|
||||
const select = db.select.bind(db);
|
||||
const reads = vi.spyOn(db, "select").mockImplementation((...args) => {
|
||||
const selection = select(...args), from = selection.from.bind(selection);
|
||||
vi.spyOn(selection, "from").mockImplementation(table => {
|
||||
const query = from(table);
|
||||
if (table === chatActions) {
|
||||
const execute = query.execute.bind(query);
|
||||
vi.spyOn(query, "execute").mockImplementation(async () => {
|
||||
const statement = query.toSQL();
|
||||
if (statement.sql.includes("'confirmation_response'") && statement.sql.includes("'processing'")) {
|
||||
statements.push(statement);
|
||||
}
|
||||
return execute();
|
||||
});
|
||||
}
|
||||
return query;
|
||||
});
|
||||
return selection;
|
||||
});
|
||||
const errors: unknown[] = [];
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true,
|
||||
canReconcile: () => true, onError: error => errors.push(error) });
|
||||
try {
|
||||
await waiting.service.registerTerminalConfirmationWork(coordinator, () => true).ready;
|
||||
await vi.waitFor(() => expect(statements.length).toBeGreaterThan(0));
|
||||
const startup = statements[0];
|
||||
const beforeHint = statements.length;
|
||||
await db.transaction(async tx => {
|
||||
await signalDatabaseWork(tx, DELIVERY_QUEUES.chatTerminalConfirmations,
|
||||
JSON.stringify({ companyId: waiting.fixture.companyId }));
|
||||
});
|
||||
await vi.waitFor(() => expect(statements.length).toBeGreaterThan(beforeHint), { timeout: 5_000 });
|
||||
const scoped = statements.at(-1)!;
|
||||
expect(scoped.params).toContain(waiting.fixture.companyId);
|
||||
await coordinator.stop();
|
||||
reads.mockRestore();
|
||||
for (const statement of [startup, scoped]) {
|
||||
expect(await db.$client.unsafe(statement.sql, statement.params as Parameters<typeof db.$client.unsafe>[1]))
|
||||
.toMatchObject([{ id: waiting.acceptAction.id }]);
|
||||
const result = await db.$client.unsafe(
|
||||
`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${statement.sql}`, statement.params as Parameters<typeof db.$client.unsafe>[1],
|
||||
);
|
||||
const plan = result[0]["QUERY PLAN"][0].Plan;
|
||||
type PlanNode = { Plans?: PlanNode[]; [key: string]: unknown };
|
||||
const nodes = (node: PlanNode): PlanNode[] => [node, ...(node.Plans ?? []).flatMap(nodes)];
|
||||
const actionReads = nodes(plan).filter(node => node["Relation Name"] === "chat_actions");
|
||||
expect(actionReads).toHaveLength(1);
|
||||
expect(Number(actionReads[0]["Actual Rows"]) + Number(actionReads[0]["Rows Removed by Filter"] ?? 0),
|
||||
JSON.stringify({ params: statement.params, actionReads }))
|
||||
.toBeLessThanOrEqual(2);
|
||||
expect(Number(actionReads[0]["Shared Hit Blocks"]) + Number(actionReads[0]["Shared Read Blocks"]))
|
||||
.toBeLessThan(20);
|
||||
}
|
||||
await db.update(chatActions).set({ status: "processed" }).where(eq(chatActions.id, waiting.acceptAction.id));
|
||||
await db.execute(sql`ANALYZE chat_actions`);
|
||||
expect(await db.$client.unsafe(scoped.sql, scoped.params as Parameters<typeof db.$client.unsafe>[1])).toHaveLength(0);
|
||||
const empty = await db.$client.unsafe(
|
||||
`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${scoped.sql}`, scoped.params as Parameters<typeof db.$client.unsafe>[1],
|
||||
);
|
||||
expect(empty[0]["QUERY PLAN"][0].Plan["Shared Hit Blocks"]
|
||||
+ empty[0]["QUERY PLAN"][0].Plan["Shared Read Blocks"]).toBeLessThan(20);
|
||||
expect(errors).toEqual([]);
|
||||
} finally {
|
||||
await coordinator.stop(); reads.mockRestore();
|
||||
await db.delete(chatActions).where(sql`${chatActions.providerActionId} LIKE ${`${prefix}%`}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("retains a confirmation committed while another settlement is in flight", async () => {
|
||||
const first = await telegramConfirmationRecoveryFixture();
|
||||
const second = await telegramConfirmationRecoveryFixture();
|
||||
|
||||
@@ -673,21 +673,24 @@ export function createChatConfirmationActions(db: Db, options: ChatConfirmationO
|
||||
(entry.companyId === scope.companyId && (!scope.issueId || !entry.issueId || entry.issueId === scope.issueId)),
|
||||
load: async (scope?: ChatConfirmationScope, signal?: AbortSignal): Promise<Entry[]> => {
|
||||
const entries: Entry[] = [];
|
||||
let cursor: string | undefined;
|
||||
let cursor: { companyId: string; id: string } | undefined;
|
||||
while (!signal?.aborted) {
|
||||
const rows = await db.select({
|
||||
id: chatActions.id, companyId: chatActions.companyId, issueId: chatConversations.issueId,
|
||||
}).from(chatActions).leftJoin(chatConversations, and(
|
||||
eq(chatConversations.companyId, chatActions.companyId), eq(chatConversations.id, chatActions.conversationId),
|
||||
)).where(and(
|
||||
eq(chatActions.kind, "confirmation_response"), eq(chatActions.status, "processing"),
|
||||
sql`${chatActions.kind} = 'confirmation_response' AND ${chatActions.status} = 'processing'`,
|
||||
scope ? eq(chatActions.companyId, scope.companyId) : undefined,
|
||||
scope?.issueId ? or(eq(chatConversations.issueId, scope.issueId), isNull(chatConversations.id)) : undefined,
|
||||
cursor ? gt(chatActions.id, cursor) : undefined,
|
||||
)).orderBy(asc(chatActions.id)).limit(100);
|
||||
cursor ? or(
|
||||
gt(chatActions.companyId, cursor.companyId),
|
||||
and(eq(chatActions.companyId, cursor.companyId), gt(chatActions.id, cursor.id)),
|
||||
) : undefined,
|
||||
)).orderBy(asc(chatActions.companyId), asc(chatActions.id)).limit(100);
|
||||
entries.push(...rows.map(row => ({ ...row, dueAt: 0 })));
|
||||
if (rows.length < 100) return entries;
|
||||
cursor = rows[rows.length - 1].id;
|
||||
cursor = rows[rows.length - 1];
|
||||
}
|
||||
throw signal?.reason ?? new Error("Confirmation recovery stopped");
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user