Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): every vector backfill statement scans a bounded id range
time-attack618c2caf9c8c
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 2e465dfb70..f11a6e7923 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -48,5 +48,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/supabase-admin.ts` — Supabase Management-API client (`listProjects`, `discoverPoolerUrl`, `extractProjectRef` — refs are lowercase ALPHANUMERIC, `[a-z0-9]+`). Consumed by the `init --prefer-postgres` ladder's rung 2 (DISCOVERY only — project creation stays dashboard guidance; discovered URLs are candidates, connect-probed before persisting) and by the classifier's Supabase hints. The access token is never persisted, logged, or written to receipts/config.- `src/core/worker-pool.ts` — (must-abort tags: `BUDGET_EXHAUSTED` and `SPEND_GROUP_REFUSED`, a job's spend-group refusal) Canonical sliding-pool + bounded-semaphore primitive (used by the `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts`'s `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem`, then the pool JOINS every worker (each finishes its current item) before rethrowing — the budget cap is a structural ceiling under concurrency and no worker is left running detached past the caller's catch. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.-- `src/core/search-vector-backfill.ts` — keyset-batched rebuilds of stored keyword vectors, shared by `reindex-search-vector` (every row) and the `fts_cjk_boundary` migration (an optional `where` limits it to rows with a CJK boundary). `backfillChunkVectors` recomputes `content_chunks.search_vector` with `chunkSearchVectorSql`; `backfillPageVectors` (#6374) reads each batch through an UPDATE-to-self of `id` (`RETURNING id, slug, source_id, timeline, knowledge_revision` plus whether a `fact_withdrawals`/`fact_purges` row covers the page or its whole source), takes the seal's effective timeline (the raw column, or for a withdrawn/purged page `readPageSnapshot`'s overlaid timeline, so a database withdrawal never returns to the vector), sanitizes it with `sanitizeRemoteBody` as the seal does, and writes `search_vector` through `pageSearchVectorSql` in one `UPDATE … FROM unnest(…)` guarded by the revision read (a page edited in between is skipped; its seal reindexes it). `BACKFILL_BATCH_SIZE` 5000 rows per statement, never one transaction; the cursor persists after every batch under `backfill.<checkpoint>.last_id` and the caller clears it. Pinned by `test/reindex-search-vector.serial.test.ts`, `test/reindex-search-vector-pages.serial.test.ts`, `test/fts-cjk-boundary.test.ts`, `test/search-vector-backfill-withdrawal.test.ts`. FTS write expressions (`src/core/fts-language.ts`, #6370): `FTS_INPUT_FUNCTION_SQL` (`gbrain_fts_input(text)`, IMMUTABLE STRICT PARALLEL SAFE, `search_path = pg_catalog`: two `regexp_replace` passes built from `CJK_SLUG_CHARS` that insert a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary; a byte-for-byte no-op without CJK, idempotent; spliced into src/schema.sql by `build:schema`), `FTS_CJK_BOUNDARY_REGEX` (the rows the `fts_cjk_boundary` migration rebuilds), `pageSearchVectorSql` (the sealed page vector used by the seal, the import seal and `search-vector-backfill.ts`), `chunkSearchVectorSql`, and `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (the two trigger functions under a language, byte-identical to src/schema.sql's for `english` so the blob replay after a migration leaves the catalog unchanged; used by `reindex-search-vector` and the migration). Every indexing `to_tsvector` reads through `gbrain_fts_input`; `applyFtsLanguagePolicy`'s `to_tsvector('english',` prefix rewrite still matches. Pinned by `test/fts-cjk-boundary.test.ts`, `test/fts-cjk-boundary-search.test.ts`, `test/e2e/fts-cjk-boundary-postgres.test.ts`.+- `src/core/search-vector-backfill.ts` — keyset-batched rebuilds of stored keyword vectors, shared by `reindex-search-vector` (every row) and the `fts_cjk_boundary` migration (an optional `where` limits it to rows with a CJK boundary). `backfillChunkVectors` recomputes `content_chunks.search_vector` with `chunkSearchVectorSql`; `backfillPageVectors` (#6374) reads each batch through an UPDATE-to-self of `id` (`RETURNING id, slug, source_id, timeline, knowledge_revision` plus whether a `fact_withdrawals`/`fact_purges` row covers the page or its whole source), takes the seal's effective timeline (the raw column, or for a withdrawn/purged page `readPageSnapshot`'s overlaid timeline, so a database withdrawal never returns to the vector), sanitizes it with `sanitizeRemoteBody` as the seal does, and writes `search_vector` through `pageSearchVectorSql` in one `UPDATE … FROM unnest(…)` guarded by the revision read (a page edited in between is skipped; its seal reindexes it). Each statement scans at most `BACKFILL_RANGE` (50 000) ids past the cursor and rebuilds at most `BACKFILL_BATCH_SIZE` (5000) of them, never one transaction; the cursor advances to the range end even when nothing matched (so a filtered run on a brain with no CJK text never scans the whole table in one statement), and the run stops at the max(id) the first batch read; the cursor persists after every batch under `backfill.<checkpoint>.last_id` and the caller clears it. Pinned by `test/reindex-search-vector.serial.test.ts`, `test/reindex-search-vector-pages.serial.test.ts`, `test/fts-cjk-boundary.test.ts`, `test/search-vector-backfill-withdrawal.test.ts`, `test/search-vector-backfill-range.test.ts`. FTS write expressions (`src/core/fts-language.ts`, #6370): `FTS_INPUT_FUNCTION_SQL` (`gbrain_fts_input(text)`, IMMUTABLE STRICT PARALLEL SAFE, `search_path = pg_catalog`: two `regexp_replace` passes built from `CJK_SLUG_CHARS` that insert a space at every CJK→ASCII-alnum and ASCII-alnum→CJK boundary; a byte-for-byte no-op without CJK, idempotent; spliced into src/schema.sql by `build:schema`), `FTS_CJK_BOUNDARY_REGEX` (the rows the `fts_cjk_boundary` migration rebuilds), `pageSearchVectorSql` (the sealed page vector used by the seal, the import seal and `search-vector-backfill.ts`), `chunkSearchVectorSql`, and `pageSearchVectorTriggerFnSql`/`chunkSearchVectorTriggerFnSql` (the two trigger functions under a language, byte-identical to src/schema.sql's for `english` so the blob replay after a migration leaves the catalog unchanged; used by `reindex-search-vector` and the migration). Every indexing `to_tsvector` reads through `gbrain_fts_input`; `applyFtsLanguagePolicy`'s `to_tsvector('english',` prefix rewrite still matches. Pinned by `test/fts-cjk-boundary.test.ts`, `test/fts-cjk-boundary-search.test.ts`, `test/e2e/fts-cjk-boundary-postgres.test.ts`.- `src/core/schema-migrations/v232-fts-cjk-boundary.ts` — #6370, handler-only and idempotent: creates `gbrain_fts_input`, recreates both search_vector trigger functions under `getFtsLanguage()` with the shared builders, then rebuilds only pages (`title`/`timeline`) and chunks (`chunk_text`/`doc_comment`/`symbol_name_qualified`) matching `FTS_CJK_BOUNDARY_REGEX` through `search-vector-backfill.ts` (checkpoints `fts_cjk_pages`/`fts_cjk_content_chunks`, cleared at the end); every other row's vector is byte-identical under the helper and is not touched. Pinned by `test/fts-cjk-boundary.test.ts` and `test/e2e/fts-cjk-boundary-postgres.test.ts`.diff --git a/src/core/search-vector-backfill.ts b/src/core/search-vector-backfill.tsindex b22687d234..a49c31f04d 100644--- a/src/core/search-vector-backfill.ts+++ b/src/core/search-vector-backfill.ts@@ -8,6 +8,13 @@* it would bank zero progress. The keyset cursor persists after every batch* under `backfill.<checkpoint>.last_id`, so a killed run resumes with at most* one batch redone; the caller clears it when the run finishes.+ *+ * Every batch is bounded by an id range as well as a row count: it scans at+ * most `BACKFILL_RANGE` ids past the cursor and rebuilds at most+ * `BACKFILL_BATCH_SIZE` matching rows, so a filtered run (the migration) costs+ * one bounded scan per statement even when nothing matches, and the cursor+ * advances to the range end either way. The run stops at the table's highest+ * id read by the first batch; rows written later go through the new triggers.*/import type { BrainEngine } from './engine.ts';@@ -17,6 +24,8 @@ import { sanitizeRemoteBody } from './remote-body.ts';/** Rows per backfill UPDATE. Keyset-batched so one statement never locks the whole table. */export const BACKFILL_BATCH_SIZE = 5000;+/** Ids scanned per backfill statement, matched or not. */+export const BACKFILL_RANGE = 50_000;export interface VectorBackfillOpts {lang: string;@@ -24,6 +33,8 @@ export interface VectorBackfillOpts {checkpoint: string;/** Extra SQL predicate over the table's own columns; only matching rows are rebuilt. */where?: string;+ /** Ids scanned per statement; defaults to `BACKFILL_RANGE`. */+ range?: number;tick?: (n: number) => void;}@@ -32,28 +43,40 @@ async function savedCursor(engine: BrainEngine, checkpoint: string): Promise<numreturn Number.isFinite(saved) && saved > 0 ? saved : 0;}-const batchIds = (table: string, cursor: number, where: string | undefined) => `+const batchIds = (table: string, cursor: number, end: number, where: string | undefined) => `SELECT id FROM ${table}- WHERE search_vector IS NOT NULL AND id > ${cursor}${where ? ` AND (${where})` : ''}+ WHERE search_vector IS NOT NULL AND id > ${cursor} AND id <= ${end}${where ? ` AND (${where})` : ''}ORDER BY idLIMIT ${BACKFILL_BATCH_SIZE}`;+/** Where the next batch starts: the last row rebuilt when the row cap was hit, else the range end. */+const nextCursor = (matched: number, lastId: number, end: number) => (matched >= BACKFILL_BATCH_SIZE ? lastId : end);+/** Chunk vectors are a pure function of the row's own columns, so one UPDATE per batch. Returns rows rebuilt. */export async function backfillChunkVectors(engine: BrainEngine, opts: VectorBackfillOpts): Promise<number> {+ const range = opts.range ?? BACKFILL_RANGE;let cursor = await savedCursor(engine, opts.checkpoint);+ let hi: number | undefined;let total = 0;for (;;) {- const rows = await engine.executeRaw<{ id: number }>(`- UPDATE content_chunks SET search_vector = ${chunkSearchVectorSql(opts.lang)}- WHERE id IN (${batchIds('content_chunks', cursor, opts.where)})- RETURNING id+ const end = cursor + range;+ const [batch] = await engine.executeRaw<{ hi: number; n: number; last: number }>(`+ WITH bound AS (SELECT coalesce(max(id), 0) AS hi FROM content_chunks),+ upd AS (+ UPDATE content_chunks SET search_vector = ${chunkSearchVectorSql(opts.lang)}+ WHERE id IN (${batchIds('content_chunks', cursor, end, opts.where)})+ RETURNING id+ )+ SELECT (SELECT hi FROM bound) AS hi, count(*)::int AS n, coalesce(max(upd.id), 0) AS last FROM upd`);- if (rows.length === 0) break;- total += rows.length;- opts.tick?.(rows.length);- cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);+ if (!batch) break;+ hi ??= Number(batch.hi);+ const n = Number(batch.n);+ total += n;+ if (n > 0) opts.tick?.(n);+ cursor = nextCursor(n, Number(batch.last), end);await engine.setConfig(checkpointKey(opts.checkpoint), String(cursor));- if (rows.length < BACKFILL_BATCH_SIZE) break;+ if (cursor >= hi) break;}return total;}@@ -73,17 +96,26 @@ export async function backfillChunkVectors(engine: BrainEngine, opts: VectorBack* already their effective one. Returns rows read.*/export async function backfillPageVectors(engine: BrainEngine, opts: VectorBackfillOpts): Promise<number> {+ const range = opts.range ?? BACKFILL_RANGE;let cursor = await savedCursor(engine, opts.checkpoint);+ let hi: number | undefined;let total = 0;for (;;) {- const rows = await engine.executeRaw<{ id: number; slug: string; source_id: string; timeline: string | null; knowledge_revision: string; withdrawn: boolean }>(`- UPDATE pages SET id = id- WHERE id IN (${batchIds('pages', cursor, opts.where)})- RETURNING id, slug, source_id, timeline, knowledge_revision::text AS knowledge_revision,- (EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = pages.source_id AND (w.subject = '*' OR w.subject = pages.slug))- OR EXISTS (SELECT 1 FROM fact_purges x WHERE x.source_id = pages.source_id AND (x.subject = '*' OR x.subject = pages.slug))) AS withdrawn+ const end = cursor + range;+ const batch = await engine.executeRaw<{ hi: number; id: number | null; slug: string; source_id: string; timeline: string | null; knowledge_revision: string; withdrawn: boolean }>(`+ WITH bound AS (SELECT coalesce(max(id), 0) AS hi FROM pages),+ upd AS (+ UPDATE pages SET id = id+ WHERE id IN (${batchIds('pages', cursor, end, opts.where)})+ RETURNING id, slug, source_id, timeline, knowledge_revision::text AS knowledge_revision,+ (EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = pages.source_id AND (w.subject = '*' OR w.subject = pages.slug))+ OR EXISTS (SELECT 1 FROM fact_purges x WHERE x.source_id = pages.source_id AND (x.subject = '*' OR x.subject = pages.slug))) AS withdrawn+ )+ SELECT bound.hi, upd.* FROM bound LEFT JOIN upd ON true`);- if (rows.length === 0) break;+ if (batch.length === 0) break;+ hi ??= Number(batch[0]!.hi);+ const rows = batch.filter(r => r.id !== null);const ids: number[] = [];const timelines: string[] = [];const revisions: string[] = [];@@ -98,16 +130,16 @@ export async function backfillPageVectors(engine: BrainEngine, opts: VectorBackftimelines.push(sanitizeRemoteBody(timeline));revisions.push(r.knowledge_revision);}- await engine.executeRaw(`+ if (ids.length > 0) await engine.executeRaw(`UPDATE pages p SET search_vector = ${pageSearchVectorSql('p.title', 'v.timeline', opts.lang)}FROM unnest($1::int[], $2::text[], $3::uuid[]) AS v(id, timeline, revision)WHERE p.id = v.id AND p.knowledge_revision = v.revision`, [ids, timelines, revisions]);total += rows.length;- opts.tick?.(rows.length);- cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);+ if (rows.length > 0) opts.tick?.(rows.length);+ cursor = nextCursor(rows.length, rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor), end);await engine.setConfig(checkpointKey(opts.checkpoint), String(cursor));- if (rows.length < BACKFILL_BATCH_SIZE) break;+ if (cursor >= hi) break;}return total;}diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex c39d3ec64e..e866bdb20c 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -26,8 +26,8 @@"PERSISTENCE_SYNC_WATERMARK_INDEX": "93523954a30e8483717f07ec97a3e0cd062b15d8a60cc759281054b06c23bb40","TOKEN_TTL_MAX_SECONDS": "f4a45bec6ec0bacc859dc57732ceb76cec7eb72f242b5a6c89d47190d0525ab4","TOKEN_TTL_MIN_SECONDS": "441d8ce6bd21f753de90abd3013eaa9992a469ea60c590f1005533618199aa25",- "backfillChunkVectors": "4c5dc231904e68639c19f5f5f3006b3b0fdac1cb33b82e94fa09dcb6da1822c9",- "backfillPageVectors": "295d5406304afb20bd7419187e99f3bd071725bc95f0f2ca446b77c82a46fc08",+ "backfillChunkVectors": "1c8cc09a28aa3e906fe2f112b71cd3aa61f750a99984e35a029cff9458272aa1",+ "backfillPageVectors": "a325a5eee3bab49723af311f21b38a1ee4a0eaff1fb3c7e1539aa4dcb287ed66","buildIndexOnline": "ed5378b90f24f7d662e02865cf73af4248e348002661f8fbfd8ee1087c60a3e5","checkpointKey": "337ef776b18f428542093e27c4d570249d6a5856e5a17e4499d26a22877af34b","chunkSearchVectorTriggerFnSql": "93ed4e29aa058949621b4198fe1ec317218f4b9ec0db0626ec6dc7001032047d",diff --git a/test/search-vector-backfill-range.test.ts b/test/search-vector-backfill-range.test.tsnew file mode 100644index 0000000000..58be8fd176--- /dev/null+++ b/test/search-vector-backfill-range.test.ts@@ -0,0 +1,120 @@+/**+ * Every backfill statement scans a bounded id range (fts_cjk_boundary on a+ * brain with little CJK text). Before, a filtered batch was "the next 5000+ * matching rows": on a brain with none, one statement scanned the whole table+ * looking for them, could pass statement_timeout, and never advanced the+ * checkpoint, so every retry failed the same way. Now each statement covers+ * `id > cursor AND id <= cursor + range`, the checkpoint advances to the range+ * end even with zero matches, and the run stops at the first batch's max(id).+ *+ * R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { checkpointKey } from '../src/core/backfill-base.ts';+import { FTS_CJK_BOUNDARY_REGEX } from '../src/core/fts-language.ts';+import { backfillChunkVectors, backfillPageVectors } from '../src/core/search-vector-backfill.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++const RANGE = 100;+const FAR = 1000;+const RE = `'${FTS_CJK_BOUNDARY_REGEX}'`;+const PAGE_WHERE = `title ~ ${RE} OR timeline ~ ${RE}`;+const CHUNK_WHERE = `chunk_text ~ ${RE} OR doc_comment ~ ${RE} OR symbol_name_qualified ~ ${RE}`;+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++async function page(slug: string, title: string, body: string): Promise<void> {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: body, timeline: '', frontmatter: {} });+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));+}++/** Latin rows at low ids, then the id sequences jump so the only CJK rows sit several ranges further on, with stale vectors. */+async function seed(): Promise<void> {+ for (let i = 0; i < 5; i++) await page(`notes/latin-${i}`, `Latin ${i}`, `Redis7 cache note ${i}.`);+ await engine.executeRaw(`SELECT setval(pg_get_serial_sequence('pages', 'id'), ${FAR})`);+ await engine.executeRaw(`SELECT setval(pg_get_serial_sequence('content_chunks', 'id'), ${FAR})`);+ await page('notes/cjk', '升级PostgreSQL17指南', '升级PostgreSQL17后查询Redis7无返回');+ await engine.executeRaw(`ALTER TABLE content_chunks DISABLE TRIGGER chunk_search_vector_trigger`);+ await engine.executeRaw(`UPDATE content_chunks c SET search_vector = 'stale'::tsvector FROM pages p WHERE p.id = c.page_id AND p.slug = 'notes/cjk'`);+ await engine.executeRaw(`ALTER TABLE content_chunks ENABLE TRIGGER chunk_search_vector_trigger`);+ await engine.executeRaw(`UPDATE pages SET search_vector = 'stale'::tsvector WHERE slug = 'notes/cjk'`);+}++/** Records each backfill statement's scanned range and each checkpoint write. */+function observe(failOnBatch?: number) {+ const ranges: Array<[number, number]> = [];+ const checkpoints: number[] = [];+ const real = engine.executeRaw.bind(engine);+ const exec = spyOn(engine, 'executeRaw').mockImplementation((async (sql: string, params?: unknown[]) => {+ const m = /id > (\d+)(?: AND id <= (\d+))?/.exec(sql);+ if (m && /^\s*WITH bound|^\s*UPDATE (pages SET id = id|content_chunks SET search_vector)/.test(sql)) {+ ranges.push([Number(m[1]), m[2] === undefined ? Infinity : Number(m[2])]);+ if (ranges.length === failOnBatch) throw new Error('injected batch failure');+ }+ return real(sql, params);+ }) as typeof engine.executeRaw);+ const realSet = engine.setConfig.bind(engine);+ const set = spyOn(engine, 'setConfig').mockImplementation((async (key: string, value: string) => {+ if (key.startsWith('backfill.range-test')) checkpoints.push(Number(value));+ return realSet(key, value);+ }) as typeof engine.setConfig);+ return { ranges, checkpoints, restore: () => { exec.mockRestore(); set.mockRestore(); } };+}++const chunkVectors = async () => (await engine.executeRaw<{ v: string }>(+ `SELECT c.search_vector::text AS v FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = 'notes/cjk'`)).map(r => r.v);+const pageVector = async () => (await engine.executeRaw<{ v: string }>(`SELECT search_vector::text AS v FROM pages WHERE slug = 'notes/cjk'`))[0]!.v;++describe('backfill statements scan a bounded id range', () => {+ for (const [label, run, rebuilt] of [+ ['chunks', () => backfillChunkVectors(engine, { lang: 'english', checkpoint: 'range-test', where: CHUNK_WHERE, range: RANGE }), chunkVectors],+ ['pages', () => backfillPageVectors(engine, { lang: 'english', checkpoint: 'range-test', where: PAGE_WHERE, range: RANGE }), async () => [await pageVector()]],+ ] as const) {+ test(`${label}: every batch covers one range and advances the checkpoint; the far CJK rows are rebuilt`, async () => {+ await seed();+ const o = observe();+ try {+ await run();+ } finally {+ o.restore();+ }+ expect(o.ranges.length).toBeGreaterThanOrEqual(FAR / RANGE);+ for (const [from, to] of o.ranges) expect(to - from).toBe(RANGE);+ expect(o.ranges.map(r => r[0])).toEqual([0, ...o.ranges.slice(0, -1).map(r => r[1])]);+ expect(o.checkpoints).toEqual(o.ranges.map(r => r[1]));+ for (const v of await rebuilt()) {+ expect(v).not.toBe("'stale'");+ expect(v).toContain("'postgresql17'");+ }+ });++ test(`${label}: an interrupted run resumes from the checkpoint of the last finished batch`, async () => {+ await seed();+ const first = observe(4);+ try {+ await expect(run()).rejects.toThrow('injected batch failure');+ } finally {+ first.restore();+ }+ expect(Number(await engine.getConfig(checkpointKey('range-test')))).toBe(3 * RANGE);+ const second = observe();+ try {+ await run();+ } finally {+ second.restore();+ }+ expect(second.ranges[0]).toEqual([3 * RANGE, 4 * RANGE]);+ for (const v of await rebuilt()) expect(v).toContain("'postgresql17'");+ });+ }+});