|
1 | 1 | /** |
2 | 2 | * @vitest-environment node |
3 | 3 | */ |
4 | | -import { backfillProjectionSourceAcl } from '@sim/db/script-migrations/0021_embedding_search_connector' |
| 4 | +import { |
| 5 | + backfillProjectionSourceAcl, |
| 6 | + PROJECTION_SOURCE_ACL_PAGE_RETRIES, |
| 7 | +} from '@sim/db/script-migrations/0021_embedding_search_connector' |
5 | 8 | import type { Sql } from 'postgres' |
6 | | -import { describe, expect, it, vi } from 'vitest' |
| 9 | +import { afterEach, describe, expect, it, vi } from 'vitest' |
7 | 10 |
|
8 | 11 | /** A session that must never be reached: every case below is refused before the first page. */ |
9 | 12 | const untouched = { begin: vi.fn() } as unknown as Sql |
10 | 13 |
|
| 14 | +type PageRow = { scanned: number; filled: number; last_id: string | null } |
| 15 | + |
| 16 | +/** The message the database pairs with each cancellation SQLSTATE. */ |
| 17 | +const CANCELLATION_MESSAGES: Record<string, string> = { |
| 18 | + '55P03': 'canceling statement due to lock timeout', |
| 19 | + '57014': 'canceling statement due to statement timeout', |
| 20 | +} |
| 21 | + |
| 22 | +/** A driver error carrying a SQLSTATE, the shape `postgres` throws. */ |
| 23 | +function postgresError(code: string, message = CANCELLATION_MESSAGES[code] ?? 'failed'): Error { |
| 24 | + return Object.assign(new Error(`${message} (SQLSTATE ${code})`), { code }) |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * A session whose page statement answers from `outcomes` in order — a row, or an error to throw — |
| 29 | + * and records the cursor each page was bound to. `beforePage` runs with the page's index before |
| 30 | + * it answers. |
| 31 | + */ |
| 32 | +function sessionOf(outcomes: Array<PageRow | Error>, beforePage?: (index: number) => void) { |
| 33 | + const cursors: string[] = [] |
| 34 | + const tx = { |
| 35 | + unsafe: vi.fn(async (query: string, params?: unknown[]) => { |
| 36 | + if (!query.includes('WITH page')) return [] |
| 37 | + beforePage?.(cursors.length) |
| 38 | + cursors.push(String(params?.[0])) |
| 39 | + const outcome = outcomes.shift() |
| 40 | + if (outcome === undefined) throw new Error('No outcome left for this page') |
| 41 | + if (outcome instanceof Error) throw outcome |
| 42 | + return [outcome] |
| 43 | + }), |
| 44 | + } |
| 45 | + const session = { |
| 46 | + begin: vi.fn(async (work: (tx: unknown) => Promise<unknown>) => work(tx)), |
| 47 | + unsafe: vi.fn(async () => []), |
| 48 | + } as unknown as Sql |
| 49 | + return { session, cursors } |
| 50 | +} |
| 51 | + |
| 52 | +/** Runs a backfill under fake timers, so its retry pauses pass without waiting. */ |
| 53 | +async function backfillNow(...args: Parameters<typeof backfillProjectionSourceAcl>) { |
| 54 | + vi.useFakeTimers() |
| 55 | + const result = backfillProjectionSourceAcl(...args) |
| 56 | + /** A rejection must not surface as unhandled while the timers are still being drained. */ |
| 57 | + const settled = result.catch(() => undefined) |
| 58 | + await vi.runAllTimersAsync() |
| 59 | + await settled |
| 60 | + return result |
| 61 | +} |
| 62 | + |
11 | 63 | describe('backfillProjectionSourceAcl', () => { |
| 64 | + afterEach(() => { |
| 65 | + vi.useRealTimers() |
| 66 | + }) |
| 67 | + |
| 68 | + it.each(['55P03', '57014'])( |
| 69 | + 'retries the page after a %s timeout and moves the cursor only once it commits', |
| 70 | + async (code) => { |
| 71 | + const { session, cursors } = sessionOf([ |
| 72 | + { scanned: 2, filled: 2, last_id: 'id-2' }, |
| 73 | + postgresError(code), |
| 74 | + postgresError(code), |
| 75 | + { scanned: 1, filled: 1, last_id: 'id-3' }, |
| 76 | + { scanned: 0, filled: 0, last_id: null }, |
| 77 | + ]) |
| 78 | + await expect( |
| 79 | + backfillNow(session, 'embedding_keyword_tin', { pauseMs: 0 }) |
| 80 | + ).resolves.toMatchObject({ scanned: 3, written: 3, afterId: 'id-3', done: true }) |
| 81 | + expect(cursors).toEqual(['', 'id-2', 'id-2', 'id-2', 'id-3']) |
| 82 | + } |
| 83 | + ) |
| 84 | + |
| 85 | + it('gives up on a page that times out more than the retry limit in a row', async () => { |
| 86 | + const { session, cursors } = sessionOf( |
| 87 | + Array.from({ length: PROJECTION_SOURCE_ACL_PAGE_RETRIES + 1 }, () => postgresError('55P03')) |
| 88 | + ) |
| 89 | + await expect(backfillNow(session, 'embedding_keyword_tin', { pauseMs: 0 })).rejects.toThrow( |
| 90 | + 'SQLSTATE 55P03' |
| 91 | + ) |
| 92 | + expect(cursors).toHaveLength(PROJECTION_SOURCE_ACL_PAGE_RETRIES + 1) |
| 93 | + expect(new Set(cursors)).toEqual(new Set([''])) |
| 94 | + }) |
| 95 | + |
| 96 | + it('propagates an error that is not a timeout without retrying', async () => { |
| 97 | + const { session, cursors } = sessionOf([postgresError('42P01')]) |
| 98 | + await expect(backfillNow(session, 'embedding_search', { pauseMs: 0 })).rejects.toThrow( |
| 99 | + 'SQLSTATE 42P01' |
| 100 | + ) |
| 101 | + expect(cursors).toEqual(['']) |
| 102 | + }) |
| 103 | + |
| 104 | + it('propagates an explicit cancellation, which shares the statement timeout SQLSTATE', async () => { |
| 105 | + const { session, cursors } = sessionOf([ |
| 106 | + postgresError('57014', 'canceling statement due to user request'), |
| 107 | + ]) |
| 108 | + await expect(backfillNow(session, 'embedding_search', { pauseMs: 0 })).rejects.toThrow( |
| 109 | + 'user request' |
| 110 | + ) |
| 111 | + expect(cursors).toEqual(['']) |
| 112 | + }) |
| 113 | + |
| 114 | + it('does not start another page when the budget ran out during the retry pause', async () => { |
| 115 | + const { session, cursors } = sessionOf([ |
| 116 | + { scanned: 1, filled: 1, last_id: 'id-1' }, |
| 117 | + postgresError('57014'), |
| 118 | + ]) |
| 119 | + await expect( |
| 120 | + backfillNow(session, 'embedding_search', { pauseMs: 0, budgetMs: 1000 }) |
| 121 | + ).resolves.toMatchObject({ afterId: 'id-1', done: false }) |
| 122 | + expect(cursors).toEqual(['', 'id-1']) |
| 123 | + }) |
| 124 | + |
| 125 | + it('leaves a page still failing at the budget to the continuation, from the last committed page', async () => { |
| 126 | + const { session, cursors } = sessionOf( |
| 127 | + [{ scanned: 1, filled: 1, last_id: 'id-1' }, postgresError('57014')], |
| 128 | + /** The second page spends the budget before the database cancels it. */ |
| 129 | + (index) => { |
| 130 | + if (index === 1) vi.advanceTimersByTime(1000) |
| 131 | + } |
| 132 | + ) |
| 133 | + await expect( |
| 134 | + backfillNow(session, 'embedding_search', { pauseMs: 0, budgetMs: 1000 }) |
| 135 | + ).resolves.toMatchObject({ afterId: 'id-1', done: false }) |
| 136 | + expect(cursors).toEqual(['', 'id-1']) |
| 137 | + }) |
| 138 | + |
12 | 139 | it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])( |
13 | 140 | 'refuses a page size of %s instead of reporting the projection filled', |
14 | 141 | async (pageSize) => { |
|
0 commit comments