Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(large-pages): bounded batched chunk writes with one prune and content-keyed row reuse (A3/T44)

garrytan28645d1efe7c
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 035cb2e399..e76d369cf1 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -61,6 +61,7 @@ const VETTED_BUILDERS: Record<string, string> = {
quoteIdentifier: 'src/core/search/embedding-column.ts: double-quoted identifier (embedded quotes doubled); callers pass registry-resolved or COLUMN_NAME_REGEX-checked embedding column names',
vectorCastSuffix: 'src/core/search/embedding-column.ts: constant ::vector / ::halfvec cast suffix from the resolved column type',
safeChunksFilter: 'src/core/search/safe-chunks.ts: constant safe-chunk predicate over a caller alias',
+ movableChunkSql: 'src/core/search/safe-chunks.ts: constant vector-matches-its-text predicate over a caller-quoted embedding column; no values',
bodyWriteChunkVersion: 'src/core/search/safe-chunks.ts: constant chunker-version CASE over caller column expressions (or master\'s literal $1/$2 bind reuse); no values',
privateLinkOriginFilterFragment: 'src/core/search/private-visibility.ts: constant link-origin visibility predicate over a caller alias',
privateTimelineEventFilterFragment: 'src/core/search/private-visibility.ts: constant timeline-event visibility predicate over a caller alias',
diff --git a/src/core/batch-rows.ts b/src/core/batch-rows.ts
index df3cb860bf..d634a86516 100644
--- a/src/core/batch-rows.ts
+++ b/src/core/batch-rows.ts
@@ -197,3 +197,32 @@ export function buildTakeRows(rowsIn: TakeBatchInput[]): { rows: TakeRow[]; weig
});
return { rows, weightClamped };
}
+
+/** Rows per encoded batch of a page-scale chunk write (A3). */
+export const ROW_BATCH_MAX_ROWS = 500;
+/** UTF-8 bytes per encoded batch, measured on the batch's own JSON document. */
+export const ROW_BATCH_MAX_BYTES = 16 * 1024 ** 2;
+
+/**
+ * Encode `items` as JSON array documents for `jsonb_to_recordset`, one batch at
+ * a time, each at most ROW_BATCH_MAX_ROWS rows and ROW_BATCH_MAX_BYTES bytes (a
+ * single larger row travels alone). Only the batch being built is held as
+ * JSON, so a page's statement size and staging memory stay bounded whatever
+ * the page size.
+ */
+export function* jsonRowBatches<T>(items: Iterable<T>, encode: (item: T) => unknown): Generator<string> {
+ let rows: string[] = [];
+ let bytes = 2;
+ for (const item of items) {
+ const row = JSON.stringify(encode(item));
+ const size = Buffer.byteLength(row) + 1;
+ if (rows.length > 0 && (rows.length === ROW_BATCH_MAX_ROWS || bytes + size > ROW_BATCH_MAX_BYTES)) {
+ yield `[${rows.join(',')}]`;
+ rows = [];
+ bytes = 2;
+ }
+ rows.push(row);
+ bytes += size;
+ }
+ if (rows.length > 0) yield `[${rows.join(',')}]`;
+}
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 01d96262e0..8bad815046 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -22,7 +22,8 @@ import { assertPageRevision } from '../page-state/types.ts';
import type { BrainEngine } from '../engine.ts';
import type { Chunk, ChunkInput, ChunklessPageRow, ResolvedColumn, StaleChunkRow } from '../types.ts';
import { rowToChunk, validateSlug } from '../utils.ts';
-import { sanitizeText } from '../batch-rows.ts';
+import { createHash } from 'node:crypto';
+import { jsonRowBatches, sanitizeText } from '../batch-rows.ts';
import {
normalizeEngineColumn,
vectorCastSuffix,
@@ -31,7 +32,7 @@ import {
COLUMN_NAME_REGEX,
EmbeddingColumnNotRegisteredError,
} from '../search/embedding-column.ts';
-import { chunkWriteInvalidation, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from '../search/safe-chunks.ts';
+import { chunkWriteInvalidations, currentTextProjectionFilter, movableChunkSql, requiresSafeChunks, safeChunksFilter } from '../search/safe-chunks.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
import { splitEmbeddingSignature, lockEmbeddingSources } from '../embedding-invalidation.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from '../embed-skip.ts';
@@ -116,14 +117,10 @@ export async function upsertChunksOnce(
if (seal === undefined) {
// A fragment write cannot certify the full-body fence boundary. Import seals
// only after its complete replacement succeeds in the same transaction.
- const invalidation = chunkWriteInvalidation(pageId, chunks);
- await exec.unsafe(invalidation.sql, invalidation.params);
-
- // Remove chunks that no longer exist (chunk_index beyond new count)
- const newIndices = chunks.map(c => c.chunk_index);
- if (newIndices.length > 0) {
- await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId} AND chunk_index != ALL(${newIndices})`);
- } else {
+ for (const invalidation of chunkWriteInvalidations(pageId, chunks)) {
+ if ((await exec.unsafe(invalidation.sql, invalidation.params)).rows.length > 0) break;
+ }
+ if (chunks.length === 0) {
await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId}`);
return;
}
@@ -168,6 +165,8 @@ export async function upsertChunksOnce(
const writeColId = quoteIdentifier(writeCol.name);
const writeCast = vectorCastSuffix(writeCol);
const col = trustedSql(writeColId);
+ // Prune once, before any insert batch: a later batch never deletes an earlier one.
+ if (seal === undefined) await moveDisplacedChunksAndPrune(exec, pageId, chunks, writeColId);
// #4246: embedded_text_hash records md5(chunk_text) AT EMBED TIME so a
// later text rewrite that keeps the vector is detectable as content
@@ -181,9 +180,10 @@ export async function upsertChunksOnce(
}
if (!resolvedModel) resolvedModel = 'unconfigured';
- // #5984: one statement text per brain whatever the chunk count (the rows bind as one
+ // #5984: one statement text per brain whatever the chunk count (each batch binds as one
// JSON document), so a prepared connection pays no describe round trip per page.
- const incoming = chunks.map(chunk => {
+ // A3: rows are encoded one bounded batch at a time (jsonRowBatches), never the whole page.
+ const batches = jsonRowBatches(chunks, chunk => {
const embedding = chunk.embedding ? '[' + Array.from(chunk.embedding).join(',') + ']' : null;
return {
chunk_index: chunk.chunk_index,
@@ -247,14 +247,14 @@ export async function upsertChunksOnce(
// embedding_pending_since follows the vector that wins: NULL when one
// lands, kept while the row stays without one, now() when this write
// NULLs it (doctor ages the embedding backlog from it).
- const { text, params } = renderFragment(sqlFragment`INSERT INTO content_chunks ${trustedSql(cols)}
+ const insertBatch = (json: string) => renderFragment(sqlFragment`INSERT INTO content_chunks ${trustedSql(cols)}
SELECT ${pageId}::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding${trustedSql(writeCast)}, c.model, c.token_count,
CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END,
CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END,
c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,
c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector,
CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END
- FROM jsonb_to_recordset(${JSON.stringify(incoming)}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,
+ FROM jsonb_to_recordset(${json}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,
embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text,
start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text)
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
@@ -317,11 +317,66 @@ export async function upsertChunksOnce(
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now()
ELSE content_chunks.embedding_pending_since
END`);
- if (sealed === undefined || opts?.deferSeal) { await exec.query(text, params); return; }
- const [{ rows }] = await pipelined({ kind: exec.dialect }, [sealPage, () => exec.query(text, params)]) as [{ rows: Array<{ id: number }> }];
- if (rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);
- if (Number(rows[0]!.id) !== Number(sealed)) throw new Error(`Page ${slug} (source=${sourceId}) is not the page this transaction wrote`);
+ const write = (json: string) => { const { text, params } = insertBatch(json); return exec.query(text, params); };
+ // Every batch runs in the caller's transaction, so a failure in any batch rolls back the whole replacement.
+ const first = batches.next().value as string;
+ if (sealed === undefined || opts?.deferSeal) await write(first);
+ else {
+ const [{ rows }] = await pipelined({ kind: exec.dialect }, [sealPage, () => write(first)]) as [{ rows: Array<{ id: number }> }];
+ if (rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);
+ if (Number(rows[0]!.id) !== Number(sealed)) throw new Error(`Page ${slug} (source=${sourceId}) is not the page this transaction wrote`);
+ }
+ for (const json of batches) await write(json);
+ }
+
+/**
+ * A4: content-keyed reuse for a write that replaces a page's chunks in place
+ * (the rebuild paths), then the one prune of the write. A stored row follows
+ * its exact chunk (source and text), not its index: each movable row whose
+ * chunk the new set holds at another index, where that index does not already
+ * hold it, moves there with its id, vector, metadata, timestamps and #5553
+ * input provenance, so a top insert keeps the vectors (and code edges) of
+ * shifted chunks instead of re-embedding them. A legacy vector without a text
+ * hash never moves. Rows park at negative indices, rows that
+ * left the set or sit on a move target are deleted, and the parked rows land;
+ * the insert batches then find their text unchanged and keep the vector under
+ * the D24 rule. Validity against the page context stays with the caller
+ * (installPageProjection nulls vectors whose recorded input no longer matches
+ * before it writes; the recorded input does not depend on the index).
+ */
+async function moveDisplacedChunksAndPrune(exec: SqlExecutor, pageId: number, chunks: ChunkInput[], writeColId: string): Promise<void> {
+ const newIndices = chunks.map(c => c.chunk_index);
+ const { rows } = await exec.run<{ id: number; chunk_index: number; chunk_source: string | null; text_md5: string; movable: boolean }>(sqlFragment`
+ SELECT id, chunk_index, chunk_source, md5(chunk_text) AS text_md5, ${trustedSql(movableChunkSql(writeColId))} AS movable
+ FROM content_chunks WHERE page_id = ${pageId} ORDER BY chunk_index`);
+ const key = (source: string | null | undefined, md5: string) => JSON.stringify([source ?? null, md5]);
+ const incoming = new Map(rows.some(r => r.movable) ? chunks.map(c => [c.chunk_index, key(c.chunk_source, createHash('md5').update(c.chunk_text).digest('hex'))]) : []);
+ const candidates = new Map<string, Array<{ id: number }>>();
+ for (const row of rows.filter(r => r.movable)) {
+ const own = key(row.chunk_source, row.text_md5);
+ if (incoming.get(Number(row.chunk_index)) === own) continue;
+ const queue = candidates.get(own);
+ if (queue) queue.push({ id: Number(row.id) });
+ else candidates.set(own, [{ id: Number(row.id) }]);
+ }
+ const held = new Map(rows.map(row => [Number(row.chunk_index), key(row.chunk_source, row.text_md5)]));
+ const ids: number[] = [];
+ const targets: number[] = [];
+ for (const [index, wanted] of incoming) {
+ if (held.get(index) === wanted) continue;
+ const row = candidates.get(wanted)?.shift();
+ if (row) { ids.push(row.id); targets.push(index); }
}
+ if (ids.length === 0) {
+ await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId} AND chunk_index != ALL(${newIndices})`);
+ return;
+ }
+ await exec.run(sqlFragment`UPDATE content_chunks c SET chunk_index = -1 - m.target
+ FROM unnest(${ids}::int[], ${targets}::int[]) AS m(id, target) WHERE c.page_id = ${pageId} AND c.id = m.id`);
+ await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId} AND chunk_index >= 0
+ AND (chunk_index != ALL(${newIndices}) OR chunk_index = ANY(${targets}::int[]))`);
+ await exec.run(sqlFragment`UPDATE content_chunks SET chunk_index = -1 - chunk_index WHERE page_id = ${pageId} AND chunk_index < 0`);
+}
export async function getChunks(
exec: ScopedRead,
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index ef9ed93f07..39fdee9f86 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -83,7 +83,7 @@ import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defa
import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';
import { PageMissingError } from './engine-errors.ts';
-import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
+import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
import { acquireLock, pgliteLockDirFor, releaseLock, type LockHandle } from './pglite-lock.ts';
import { assertPgliteGraduationOpenable } from './persistence/graduation-custody.ts';
// Engine-live path (#3596): static import, never a lazy `import()` in the
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 3f7fd515c2..7a670b0675 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -81,7 +81,7 @@ import {
} from './search/embedding-column.ts';
import { getFtsLanguage, applyFtsLanguagePolicy } from './fts-language.ts';
import { splitEmbeddingSignature, currentSpaceChunkPredicate, lockEmbeddingSources } from './embedding-invalidation.ts';
-import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
+import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
import type {
Page, PageInput, PageFilters, PageType,
Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,
diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.ts
index 8e96f4b6af..22bba5bc49 100644
--- a/src/core/search/safe-chunks.ts
+++ b/src/core/search/safe-chunks.ts
@@ -1,4 +1,5 @@
import type { ChunkInput, PageReadScope } from '../types.ts';
+import { jsonRowBatches } from '../batch-rows.ts';
/** First markdown index built from the strict full-body fence sanitizer. */
export const SAFE_FENCE_CHUNKER_VERSION = 4;
@@ -53,27 +54,44 @@ export function safeChunksFilter(alias: string): string {
* the first mutation, including partial failures outside an import transaction.
* Both engines canonicalize chunk_text before calling, and persist/hash those
* same bytes. Identity and enum fields retain their existing rejection policy.
+ *
+ * One statement per encoded batch of the incoming set (`jsonRowBatches`), so a
+ * large page is compared without one whole-page JSON document; each statement
+ * also checks for stored chunks missing from the complete incoming index set.
+ * The caller stops at the first statement that invalidates (RETURNING id).
*/
-export function chunkWriteInvalidation(pageId: number, chunks: ChunkInput[]): { sql: string; params: unknown[] } {
+export function* chunkWriteInvalidations(pageId: number, chunks: ChunkInput[]): Generator<{ sql: string; params: unknown[] }> {
const metadata = ['language', 'symbol_name', 'symbol_type', 'start_line', 'end_line', 'parent_symbol_path', 'doc_comment', 'symbol_name_qualified'] as const;
- const incoming = chunks.map(chunk => Object.fromEntries(
- ['chunk_index', 'chunk_text', 'chunk_source', 'modality', ...metadata].map(key => [key, chunk[key as keyof ChunkInput] ?? null]),
- ));
- return {
- sql: `UPDATE pages SET chunker_version = -1 WHERE id = $1 AND (
- NOT (${safeChunksFilter('pages')}) OR EXISTS (
- SELECT 1 FROM (SELECT * FROM content_chunks WHERE page_id = $1) cc
- FULL JOIN jsonb_to_recordset($2::text::jsonb) AS incoming(
+ const sql = `UPDATE pages SET chunker_version = -1 WHERE id = $1 AND (
+ NOT (${safeChunksFilter('pages')})
+ OR EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = $1 AND cc.chunk_index <> ALL($3::int[]))
+ OR EXISTS (
+ SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) AS incoming(
chunk_index int, chunk_text text, chunk_source text, modality text,
language text, symbol_name text, symbol_type text, start_line int,
end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text)
- ON incoming.chunk_index = cc.chunk_index
- WHERE cc.id IS NULL OR incoming.chunk_index IS NULL
+ LEFT JOIN content_chunks cc ON cc.page_id = $1 AND cc.chunk_index = incoming.chunk_index
+ WHERE cc.id IS NULL
OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text
OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source
OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text')
${metadata.map(key => `OR cc.${key} IS DISTINCT FROM COALESCE(incoming.${key}, cc.${key})`).join('\n ')}
- ))`,
- params: [pageId, JSON.stringify(incoming)],
- };
+ )) RETURNING id`;
+ const indices = chunks.map(chunk => chunk.chunk_index);
+ const batches = jsonRowBatches(chunks, chunk => Object.fromEntries(
+ ['chunk_index', 'chunk_text', 'chunk_source', 'modality', ...metadata].map(key => [key, chunk[key as keyof ChunkInput] ?? null])));
+ let sent = false;
+ for (const batch of batches) {
+ sent = true;
+ yield { sql, params: [pageId, batch, indices] };
+ }
+ if (!sent) yield { sql, params: [pageId, '[]', indices] };
+}
+
+/**
+ * A stored row whose vector provably describes its own text (#4246), the only
+ * rows a content-keyed rebuild moves to a new index. `col` is a quoted column.
+ */
+export function movableChunkSql(col: string): string {
+ return `(${col} IS NOT NULL AND embedded_text_hash IS NOT DISTINCT FROM md5(chunk_text))`;
}
diff --git a/test/engine-sql-chunks-batched-write.test.ts b/test/engine-sql-chunks-batched-write.test.ts
new file mode 100644
index 0000000000..93de53dca9
--- /dev/null
+++ b/test/engine-sql-chunks-batched-write.test.ts
@@ -0,0 +1,180 @@
+/**
+ * A3 / T44 + A4: `upsertChunksOnce` writes a page's chunks in bounded batches
+ * inside the caller's transaction, prunes once before the first batch, and a
+ * stored chunk follows its exact text to a new index.
+ *
+ * Authoring gate. (1) Contract: a page-scale chunk replacement never binds the
+ * whole page as one JSON document (<= 500 rows and <= 16 MiB per statement),
+ * keeps every unchanged chunk's vector and embedding metadata in every batch,
+ * rolls back completely when any batch fails, and keeps the vectors of
+ * chunks a top insert only shifted. (2) Regressions it catches: a per-slice
+ * replacement that deletes earlier batches, a prune between batches, a whole-
+ * page statement (the 256 MB jsonb ceiling at ~31 MB of page), a partial
+ * commit, and index-keyed vector loss on a shift. (3) Existing coverage writes
+ * one or two chunks. (4) No production seam: the statements are observed
+ * through a wrapper over the engine's own executor.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { upsertChunksOnce } from '../src/core/engine-sql/chunks.ts';
+import type { SqlExecutor } from '../src/core/engine-sql/executor.ts';
+import type { ChunkInput } from '../src/core/types.ts';
+import { ROW_BATCH_MAX_BYTES, ROW_BATCH_MAX_ROWS } from '../src/core/batch-rows.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+let engine: PGLiteEngine;
+let dims = 0;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const [row] = await engine.executeRaw<{ dim: number }>(
+ `SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0`);
+ dims = Number(row!.dim);
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const SLUG = 'notes/batched-chunks-alice-example';
+
+const vec = (seed: number, width = dims) => {
+ const v = new Float32Array(width);
+ v[seed % width] = 1;
+ v[(seed * 7 + 3) % width] = -0.5;
+ return v;
+};
+const text = (i: number, pad = 0) => `Chunk ${i} of acme-example notes.${pad ? ' ' + 'x'.repeat(pad) : ''}`;
+
+const tokens = (chunk: string) => 3 + (chunk.length % 11);
+
+function embedded(texts: string[]): ChunkInput[] {
+ return texts.map((chunk_text, i) => ({
+ chunk_index: i, chunk_text, chunk_source: 'compiled_truth', embedding: vec(i), model: 'test:batched-model',
+ token_count: tokens(chunk_text), embedding_input_hash: `input-${i}`, modality: 'text',
+ }));
+}
+
+function bare(texts: string[]): ChunkInput[] {
+ return texts.map((chunk_text, i) => ({ chunk_index: i, chunk_text, chunk_source: 'compiled_truth', token_count: tokens(chunk_text) }));
+}
+
+interface RowState {
+ id: number; chunk_index: number; chunk_text: string; vector_md5: string | null; model: string | null; token_count: number | null;
+ embedded_at: string | null; embedded_text_hash: string | null; embedding_input_hash: string | null; modality: string;
+}
+
+async function state(): Promise<RowState[]> {
+ return (await engine.executeRaw<RowState>(`SELECT cc.id, cc.chunk_index, cc.chunk_text, md5(cc.embedding::text) AS vector_md5, cc.model,
+ cc.token_count, cc.embedded_at::text AS embedded_at, cc.embedded_text_hash, cc.embedding_input_hash, cc.modality
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = 'default' ORDER BY cc.chunk_index`, [SLUG]))
+ .map(r => ({ ...r, id: Number(r.id), chunk_index: Number(r.chunk_index), token_count: r.token_count === null ? null : Number(r.token_count) }));
+}
+
+async function seed(chunks: ChunkInput[]): Promise<RowState[]> {
+ await engine.putPage(SLUG, { type: 'note', title: 'Batched chunks', compiled_truth: 'body' });
+ await engine.upsertChunks(SLUG, chunks);
+ return state();
+}
+
+interface Insert { rows: number; bytes: number }
+
+/** Run one replacement through the engine's own executor, recording each chunk INSERT's JSON batch. */
+async function write(chunks: ChunkInput[]): Promise<Insert[]> {
+ const inserts: Insert[] = [];
+ await engine.transaction(async tx => {
+ const exec = (tx as unknown as { engineSql: SqlExecutor }).engineSql;
+ const observed: SqlExecutor = new Proxy(exec, {
+ get(target, key) {
+ if (key === 'query') return (sql: string, params?: unknown[], opts?: unknown) => {
+ if (/^\s*INSERT INTO content_chunks \(page_id, chunk_index, chunk_text/.test(sql)) {
+ const json = params!.find(p => typeof p === 'string' && p.startsWith('[')) as string;
+ inserts.push({ rows: (JSON.parse(json) as unknown[]).length, bytes: Buffer.byteLength(json) });
+ }
+ return target.query(sql, params, opts as never);
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ await upsertChunksOnce(observed, {
+ lockPageKeys: keys => tx.lockPageKeys(keys),
+ readPageSnapshot: (slug, opts) => tx.readPageSnapshot(slug, opts),
+ }, SLUG, chunks);
+ });
+ return inserts;
+}
+
+describe('A3 / T44: batched chunk replacement', () => {
+ for (const n of [499, 500, 501, 1000, 1001]) {
+ test(`${n} chunks: ceil(n/500) bounded batches, every vector and its metadata kept`, async () => {
+ const texts = Array.from({ length: n }, (_, i) => text(i));
+ const before = await seed(embedded(texts));
+ expect(before.every(r => r.vector_md5 !== null && r.embedding_input_hash !== null)).toBe(true);
+ const inserts = await write(bare(texts));
+ expect(inserts.map(i => i.rows)).toEqual(Array.from({ length: Math.ceil(n / ROW_BATCH_MAX_ROWS) },
+ (_, b) => Math.min(ROW_BATCH_MAX_ROWS, n - b * ROW_BATCH_MAX_ROWS)));
+ expect(await state()).toEqual(before);
+ }, 120_000);
+ }
+
+ test('the encoded-byte limit splits a batch below the row limit and loses nothing', async () => {
+ const texts = Array.from({ length: 420 }, (_, i) => text(i, 40_000));
+ const before = await seed(embedded(texts));
+ const inserts = await write(bare(texts));
+ expect(inserts.length).toBe(2);
+ expect(inserts.every(i => i.bytes <= ROW_BATCH_MAX_BYTES && i.rows < ROW_BATCH_MAX_ROWS)).toBe(true);
+ expect(inserts.reduce((sum, i) => sum + i.rows, 0)).toBe(420);
+ expect(await state()).toEqual(before);
+ }, 120_000);
+
+ test('a failure in batch 2 rolls back the prune, the moves and batch 1', async () => {
+ const before = await seed(embedded(Array.from({ length: 1001 }, (_, i) => text(i))));
+ const [{ chunker_version: sealBefore }] = await engine.executeRaw<{ chunker_version: number | null }>(
+ 'SELECT chunker_version FROM pages WHERE slug = $1', [SLUG]);
+ // A top insert that also drops the tail: moves every row, prunes 102, then batch 2
+ // carries a vector of the wrong width.
+ const next = bare(['A new opening paragraph.', ...Array.from({ length: 900 }, (_, i) => text(i))]);
+ next[700] = { ...next[700]!, embedding: vec(1, dims + 1) };
+ const error = await write(next).then(() => null, (e: unknown) => e);
+ expect(String(error)).toMatch(/dimension/i);
+ expect(await state()).toEqual(before);
+ const [{ chunker_version: sealAfter }] = await engine.executeRaw<{ chunker_version: number | null }>(
+ 'SELECT chunker_version FROM pages WHERE slug = $1', [SLUG]);
+ expect(sealAfter).toBe(sealBefore);
+ }, 120_000);
+});
+
+describe('A4: a stored chunk follows its exact text to a new index', () => {
+ test('a top insert keeps the row, vector and metadata of every shifted chunk; only the new chunk waits for a vector', async () => {
+ const texts = Array.from({ length: 1001 }, (_, i) => text(i));
+ const before = await seed(embedded(texts));
+ await write(bare(['A new opening paragraph.', ...texts]));
+ const after = await state();
+ expect(after).toHaveLength(1002);
+ expect(after[0]).toMatchObject({ chunk_index: 0, chunk_text: 'A new opening paragraph.', vector_md5: null, embedded_at: null });
+ expect(after.slice(1)).toEqual(before.map(r => ({ ...r, chunk_index: r.chunk_index + 1 })));
+ }, 120_000);
+
+ test('a removed opening chunk shifts the rest down without losing their vectors, and its row is gone', async () => {
+ const texts = Array.from({ length: 600 }, (_, i) => text(i));
+ const before = await seed(embedded(texts));
+ await write(bare(texts.slice(1)));
+ expect(await state()).toEqual(before.slice(1).map(r => ({ ...r, chunk_index: r.chunk_index - 1 })));
+ }, 120_000);
+
+ test('a changed chunk still loses its vector while its unchanged neighbours keep theirs', async () => {
+ const texts = Array.from({ length: 5 }, (_, i) => text(i));
+ const before = await seed(embedded(texts));
+ await write(bare([texts[0]!, 'Rewritten chunk.', texts[2]!, texts[3]!, texts[4]!]));
+ const after = await state();
+ expect(after[1]).toMatchObject({ chunk_text: 'Rewritten chunk.', vector_md5: null, embedded_at: null, embedding_input_hash: null });
+ expect([after[0], after[2], after[3], after[4]]).toEqual([before[0], before[2], before[3], before[4]]);
+ });
+});
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 57aaea1c12..b5c750dd33 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -661,13 +661,22 @@
"via": "unsafe"
},
{
- "paramCount": 2,
+ "paramCount": 3,
"unsafeOptions": {
"prepare": false,
"simple": false
},
"via": "unsafe"
},
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 2,
"unsafeOptions": {
@@ -743,13 +752,22 @@
"via": "unsafe"
},
{
- "paramCount": 2,
+ "paramCount": 3,
"unsafeOptions": {
"prepare": false,
"simple": false
},
"via": "unsafe"
},
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 2,
"unsafeOptions": {
@@ -816,13 +834,22 @@
"via": "unsafe"
},
{
- "paramCount": 2,
+ "paramCount": 3,
"unsafeOptions": {
"prepare": false,
"simple": false
},
"via": "unsafe"
},
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 2,
"unsafeOptions": {
@@ -889,7 +916,7 @@
"via": "unsafe"
},
{
- "paramCount": 2,
+ "paramCount": 3,
"unsafeOptions": {
"prepare": false,
"simple": false
@@ -970,13 +997,22 @@
"via": "unsafe"
},
{
- "paramCount": 2,
+ "paramCount": 3,
"unsafeOptions": {
"prepare": false,
"simple": false
},
"via": "unsafe"
},
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 2,
"unsafeOptions": {
diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.json
index d184810596..0377b7b9c9 100644
--- a/test/fixtures/goldens/sql-text/chunks.json
+++ b/test/fixtures/goldens/sql-text/chunks.json
@@ -662,10 +662,20 @@
"params": [
"number",
"number",
- "string"
+ "array<number>",
+ "string",
+ "number"
],
- "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS ( SELECT 1 FROM (SELECT * FROM content_chunks WHERE page_id = $2) cc FULL JOIN jsonb_to_recordset($3::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) ON incoming.chunk_index = cc.chunk_index WHERE cc.id IS NULL OR incoming.chunk_index IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) ))",
- "textSha256": "6db2c904feb7479e571d913076af75cc9c32170451bfa4afa47e7e60724db006"
+ "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = $2 AND cc.chunk_index <> ALL($3::int[])) OR EXISTS ( SELECT 1 FROM jsonb_to_recordset($4::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) LEFT JOIN content_chunks cc ON cc.page_id = $5 AND cc.chunk_index = incoming.chunk_index WHERE cc.id IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) )) RETURNING id",
+ "textSha256": "45390784bf03117ba45ef1e224d394d346bc274e2103481e357397ff7ec76451"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "number"
+ ],
+ "sql": "SELECT id, chunk_index, chunk_source, md5(chunk_text) AS text_md5, (\"embedding\" IS NOT NULL AND embedded_text_hash IS NOT DISTINCT FROM md5(chunk_text)) AS movable FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index",
+ "textSha256": "b4071d9374604e925cefb4ab2f0324b59411c79a3b9ace1dd1ea2a8496425954"
},
{
"lane": "tx",
@@ -750,10 +760,20 @@
"params": [
"number",
"number",
- "string"
+ "array<number>",
+ "string",
+ "number"
],
- "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS ( SELECT 1 FROM (SELECT * FROM content_chunks WHERE page_id = $2) cc FULL JOIN jsonb_to_recordset($3::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) ON incoming.chunk_index = cc.chunk_index WHERE cc.id IS NULL OR incoming.chunk_index IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) ))",
- "textSha256": "6db2c904feb7479e571d913076af75cc9c32170451bfa4afa47e7e60724db006"
+ "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = $2 AND cc.chunk_index <> ALL($3::int[])) OR EXISTS ( SELECT 1 FROM jsonb_to_recordset($4::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) LEFT JOIN content_chunks cc ON cc.page_id = $5 AND cc.chunk_index = incoming.chunk_index WHERE cc.id IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) )) RETURNING id",
+ "textSha256": "45390784bf03117ba45ef1e224d394d346bc274e2103481e357397ff7ec76451"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "number"
+ ],
+ "sql": "SELECT id, chunk_index, chunk_source, md5(chunk_text) AS text_md5, (\"embedding\" IS NOT NULL AND embedded_text_hash IS NOT DISTINCT FROM md5(chunk_text)) AS movable FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index",
+ "textSha256": "b4071d9374604e925cefb4ab2f0324b59411c79a3b9ace1dd1ea2a8496425954"
},
{
"lane": "tx",
@@ -832,10 +852,20 @@
"params": [
"number",
"number",
- "string"
+ "array<number>",
+ "string",
+ "number"
],
- "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS ( SELECT 1 FROM (SELECT * FROM content_chunks WHERE page_id = $2) cc FULL JOIN jsonb_to_recordset($3::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) ON incoming.chunk_index = cc.chunk_index WHERE cc.id IS NULL OR incoming.chunk_index IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) ))",
- "textSha256": "6db2c904feb7479e571d913076af75cc9c32170451bfa4afa47e7e60724db006"
+ "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = $2 AND cc.chunk_index <> ALL($3::int[])) OR EXISTS ( SELECT 1 FROM jsonb_to_recordset($4::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) LEFT JOIN content_chunks cc ON cc.page_id = $5 AND cc.chunk_index = incoming.chunk_index WHERE cc.id IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) )) RETURNING id",
+ "textSha256": "45390784bf03117ba45ef1e224d394d346bc274e2103481e357397ff7ec76451"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "number"
+ ],
+ "sql": "SELECT id, chunk_index, chunk_source, md5(chunk_text) AS text_md5, (\"embedding_voyage\" IS NOT NULL AND embedded_text_hash IS NOT DISTINCT FROM md5(chunk_text)) AS movable FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index",
+ "textSha256": "f7ab7c9cef4efbb5088a72eb81eab87d438868abccc5e1bea71e91788b3e9dbe"
},
{
"lane": "tx",
@@ -914,10 +944,12 @@
"params": [
"number",
"number",
- "string"
+ "array<>",
+ "string",
+ "number"
],
- "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS ( SELECT 1 FROM (SELECT * FROM content_chunks WHERE page_id = $2) cc FULL JOIN jsonb_to_recordset($3::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) ON incoming.chunk_index = cc.chunk_index WHERE cc.id IS NULL OR incoming.chunk_index IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) ))",
- "textSha256": "6db2c904feb7479e571d913076af75cc9c32170451bfa4afa47e7e60724db006"
+ "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = $2 AND cc.chunk_index <> ALL($3::int[])) OR EXISTS ( SELECT 1 FROM jsonb_to_recordset($4::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) LEFT JOIN content_chunks cc ON cc.page_id = $5 AND cc.chunk_index = incoming.chunk_index WHERE cc.id IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) )) RETURNING id",
+ "textSha256": "45390784bf03117ba45ef1e224d394d346bc274e2103481e357397ff7ec76451"
},
{
"lane": "tx",
@@ -1003,10 +1035,20 @@
"params": [
"number",
"number",
- "string"
+ "array<number>",
+ "string",
+ "number"
+ ],
+ "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = $2 AND cc.chunk_index <> ALL($3::int[])) OR EXISTS ( SELECT 1 FROM jsonb_to_recordset($4::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) LEFT JOIN content_chunks cc ON cc.page_id = $5 AND cc.chunk_index = incoming.chunk_index WHERE cc.id IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) )) RETURNING id",
+ "textSha256": "45390784bf03117ba45ef1e224d394d346bc274e2103481e357397ff7ec76451"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "number"
],
- "sql": "UPDATE pages SET chunker_version = -1 WHERE id = $1 AND ( NOT (COALESCE(pages.chunker_version, 0) >= 4) OR EXISTS ( SELECT 1 FROM (SELECT * FROM content_chunks WHERE page_id = $2) cc FULL JOIN jsonb_to_recordset($3::text::jsonb) AS incoming( chunk_index int, chunk_text text, chunk_source text, modality text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text) ON incoming.chunk_index = cc.chunk_index WHERE cc.id IS NULL OR incoming.chunk_index IS NULL OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text') OR cc.language IS DISTINCT FROM COALESCE(incoming.language, cc.language) OR cc.symbol_name IS DISTINCT FROM COALESCE(incoming.symbol_name, cc.symbol_name) OR cc.symbol_type IS DISTINCT FROM COALESCE(incoming.symbol_type, cc.symbol_type) OR cc.start_line IS DISTINCT FROM COALESCE(incoming.start_line, cc.start_line) OR cc.end_line IS DISTINCT FROM COALESCE(incoming.end_line, cc.end_line) OR cc.parent_symbol_path IS DISTINCT FROM COALESCE(incoming.parent_symbol_path, cc.parent_symbol_path) OR cc.doc_comment IS DISTINCT FROM COALESCE(incoming.doc_comment, cc.doc_comment) OR cc.symbol_name_qualified IS DISTINCT FROM COALESCE(incoming.symbol_name_qualified, cc.symbol_name_qualified) ))",
- "textSha256": "6db2c904feb7479e571d913076af75cc9c32170451bfa4afa47e7e60724db006"
+ "sql": "SELECT id, chunk_index, chunk_source, md5(chunk_text) AS text_md5, (\"embedding\" IS NOT NULL AND embedded_text_hash IS NOT DISTINCT FROM md5(chunk_text)) AS movable FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index",
+ "textSha256": "b4071d9374604e925cefb4ab2f0324b59411c79a3b9ace1dd1ea2a8496425954"
},
{
"lane": "tx",
diff --git a/test/helpers/engine-sql-rollback-cases.ts b/test/helpers/engine-sql-rollback-cases.ts
index a7ab6c186d..46a2491660 100644
--- a/test/helpers/engine-sql-rollback-cases.ts
+++ b/test/helpers/engine-sql-rollback-cases.ts
@@ -14,6 +14,7 @@
* connect time) makes the write commit outside the transaction and fails.
*/
import { expect, test } from 'bun:test';
+import { ROW_BATCH_MAX_ROWS } from '../../src/core/batch-rows.ts';
import type { BrainEngine } from '../../src/core/engine.ts';
import { invalidateStaleSignatureEmbeddingsGuarded } from '../../src/core/embedding-invalidation.ts';
import { reconcileContextualEmbeddingInputs } from '../../src/core/page-state/contextual-proof.ts';
@@ -144,6 +145,20 @@ export const ROLLBACK_CASES: RollbackCase[] = [
},
observe: chunkTexts,
},
+ {
+ // A3: a replacement larger than one row batch commits as several INSERTs
+ // after one prune; all of them leave with the transaction.
+ domain: 'chunks (upsertChunks, several row batches)',
+ async seed(engine) {
+ await seedPage(engine);
+ await engine.upsertChunks(SLUG, [{ chunk_index: 0, chunk_text: 'seeded chunk', chunk_source: 'compiled_truth' }]);
+ },
+ async write(tx) {
+ await tx.upsertChunks(SLUG, Array.from({ length: ROW_BATCH_MAX_ROWS * 2 + 1 }, (_, i) => ({
+ chunk_index: i, chunk_text: `rolled-back chunk ${i}`, chunk_source: 'compiled_truth' as const })));
+ },
+ observe: chunkTexts,
+ },
{
domain: 'chunks (deleteChunks)',
async seed(engine) {