diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 318c9f09317..22b07ed7279 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -550,6 +550,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0396_tan_paladin.sql", "0397_known_madrox.sql", "0398_yielding_random.sql", + "0399_ambitious_onslaught.sql", "0384_funny_adam_warlock.sql", diff --git a/packages/db/src/migrations/0399_ambitious_onslaught.sql b/packages/db/src/migrations/0399_ambitious_onslaught.sql new file mode 100644 index 00000000000..21bcfb687ad --- /dev/null +++ b/packages/db/src/migrations/0399_ambitious_onslaught.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_continuation_work_idx" ON "chat_actions" USING btree ("company_id","id") WHERE "chat_actions"."kind" = 'interaction_wakeup' AND "chat_actions"."status" IN ('issued', 'processing'); diff --git a/packages/db/src/migrations/meta/0394_snapshot.json b/packages/db/src/migrations/meta/0399_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0394_snapshot.json rename to packages/db/src/migrations/meta/0399_snapshot.json index 2f97a908044..05df360fe1f 100644 --- a/packages/db/src/migrations/meta/0394_snapshot.json +++ b/packages/db/src/migrations/meta/0399_snapshot.json @@ -1,6 +1,6 @@ { - "id": "633afb6b-4b89-44ea-81d5-a477a3696eb5", - "prevId": "e1ddc6f7-6335-4b3d-aeec-a5df27793874", + "id": "9ca01952-f1fa-4c54-a189-3f5a3a3a3761", + "prevId": "7f056258-4b1a-4828-b950-33f070fc0c47", "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,50 @@ } }, "indexes": { + "chat_actions_continuation_work_idx": { + "name": "chat_actions_continuation_work_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\" = 'interaction_wakeup' AND \"chat_actions\".\"status\" IN ('issued', 'processing')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "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 +14232,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 +14272,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 +15040,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": { diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index b9355079da4..62fad4474c4 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2780,6 +2780,13 @@ "when": 1793216165150, "tag": "0398_yielding_random", "breakpoints": true + }, + { + "idx": 399, + "version": "7", + "when": 1793218102114, + "tag": "0399_ambitious_onslaught", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/chat_channels.ts b/packages/db/src/schema/chat_channels.ts index b6aeb4c9efd..1bb91f2603c 100644 --- a/packages/db/src/schema/chat_channels.ts +++ b/packages/db/src/schema/chat_channels.ts @@ -673,6 +673,9 @@ export const chatActions = pgTable( .defaultNow(), }, (table) => [ + index("chat_actions_continuation_work_idx") + .on(table.companyId, table.id) + .where(sql`${table.kind} = 'interaction_wakeup' AND ${table.status} IN ('issued', 'processing')`), index("chat_actions_confirmation_recovery_idx") .on(table.companyId, table.id) .where(sql`${table.kind} = 'confirmation_response' AND ${table.status} = 'processing'`), diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 76a179b5746..b84bda2b3b5 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -45693,6 +45693,92 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { return { fixture, callbacks, onAction: callbacks.onAction, endpoint, service, wakeup, settlementBarrier, dm, conversation, linkedUserId, principal, interaction, publication, acceptAction, actionEvent }; } + it("bounds interaction continuation recovery reads with completed history", async () => { + const context = await telegramConfirmationRecoveryFixture(); + await expect(context.onAction(context.actionEvent)) + .rejects.toThrow("injected post-interaction confirmation settlement crash"); + const [action] = await db.select().from(chatActions).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + )); + expect(action).toBeDefined(); + await db.update(chatActions).set({ status: "processing", updatedAt: new Date() }).where(eq(chatActions.id, action.id)); + const prefix = `continuation-plan:${randomUUID()}:`; + await db.execute(sql` + INSERT INTO chat_actions (company_id, endpoint_id, kind, provider_action_id, status) + SELECT ${context.fixture.companyId}::uuid, ${context.endpoint.id}::uuid, + CASE WHEN n <= 10000 THEN 'interaction_wakeup' ELSE 'unrelated_action' END, + ${prefix} || n, + CASE WHEN n <= 10000 THEN 'processed' ELSE 'processing' END + FROM generate_series(1, 20000) AS n + `); + await db.execute(sql`VACUUM (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.params.includes("interaction_wakeup") || statement.sql.includes("'interaction_wakeup'")) { + 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 context.service.registerInteractionContinuationWork(coordinator, () => true).ready; + expect(statements.length).toBeGreaterThan(0); + const startup = statements[0], beforeHint = statements.length; + await db.transaction(async tx => { + await signalDatabaseWork(tx, DELIVERY_QUEUES.chatInteractionContinuations, + JSON.stringify({ companyId: context.fixture.companyId })); + }); + await vi.waitFor(() => expect(statements.length).toBeGreaterThan(beforeHint), { timeout: 5_000 }); + const scoped = statements.at(-1)!; + expect(scoped.params).toContain(context.fixture.companyId); + await coordinator.stop(); reads.mockRestore(); + for (const statement of [startup, scoped]) { + expect(await db.$client.unsafe(statement.sql, statement.params as Parameters[1])) + .toMatchObject([{ id: action.id }]); + const result = await db.$client.unsafe( + `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${statement.sql}`, + statement.params as Parameters[1], + ); + type PlanNode = { Plans?: PlanNode[]; [key: string]: unknown }; + const nodes = (node: PlanNode): PlanNode[] => [node, ...(node.Plans ?? []).flatMap(nodes)]; + const actionReads = nodes(result[0]["QUERY PLAN"][0].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, action.id)); + await db.execute(sql`ANALYZE chat_actions`); + expect(await db.$client.unsafe(scoped.sql, scoped.params as Parameters[1])).toHaveLength(0); + const empty = await db.$client.unsafe( + `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${scoped.sql}`, scoped.params as Parameters[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.each(["accept", "reject", "drain", "restart", "deferred", "failure", "paused endpoint", "future publication", "stale claim"] as const)("wakes interaction continuations from a committed response through %s", async mode => { const context = await telegramConfirmationRecoveryFixture(mode === "reject" ? "reject" : "accept"); const errors: unknown[] = []; diff --git a/server/src/services/chat-channels/interactions/continuations.ts b/server/src/services/chat-channels/interactions/continuations.ts index 82d153668e7..4492a7629e2 100644 --- a/server/src/services/chat-channels/interactions/continuations.ts +++ b/server/src/services/chat-channels/interactions/continuations.ts @@ -7,7 +7,6 @@ import { asc, desc, eq, - gt, inArray, sql, isNotNull, @@ -474,18 +473,18 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC (!scope.issueId || value.issueId === scope.issueId)), load: async (scope?: ChatContinuationScope, signal?: AbortSignal): Promise => { const entries: Entry[] = []; - let cursor: string | undefined; + let cursor: { companyId: string; id: string } | undefined; while (!signal?.aborted) { const rows = await db.select(selection).from(chatActions).where(and( - eq(chatActions.kind, "interaction_wakeup"), inArray(chatActions.status, ["issued", "processing"]), + sql`${chatActions.kind} = 'interaction_wakeup' AND ${chatActions.status} IN ('issued', 'processing')`, scope ? eq(chatActions.companyId, scope.companyId) : undefined, scope?.actionId ? eq(chatActions.id, scope.actionId) : undefined, scope?.issueId ? eq(sql`${chatActions.payload}->>'issueId'`, scope.issueId) : undefined, - cursor ? gt(chatActions.id, cursor) : undefined, - )).orderBy(asc(chatActions.id)).limit(100); + cursor ? sql`(${chatActions.companyId}, ${chatActions.id}) > (${cursor.companyId}, ${cursor.id})` : undefined, + )).orderBy(asc(chatActions.companyId), asc(chatActions.id)).limit(100); entries.push(...rows.map(entry)); if (rows.length < 100) return entries; - cursor = rows[rows.length - 1].id; + cursor = rows[rows.length - 1]; } throw signal?.reason ?? new Error("Interaction continuation recovery stopped"); },