Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: wave 6 (byte-bound chunk cap, inline chunk keep, v225 dup index, pglite wasm prewarm)

time-attack8ad85a61ca05
diff --git a/scripts/bench/efficiency/bench-chunk.ts b/scripts/bench/efficiency/bench-chunk.ts
index 3adb2e8e9b..582a4a1cdb 100644
--- a/scripts/bench/efficiency/bench-chunk.ts
+++ b/scripts/bench/efficiency/bench-chunk.ts
@@ -4,12 +4,14 @@
* synthetic brain directory once, then time the importer's chunk
* projection (`prepareMarkdownChunks`) over all pages, `--n` passes after
* one warm-up pass. `--cjk <pages>` adds a generated mixed CJK / Latin /
- * emoji corpus instead of reading a directory. Prints per-pass p50/p95 and a
+ * emoji corpus instead of reading a directory, and `--cjk-prose <pages>` CJK
+ * prose (frequent characters, sentence punctuation, few Latin terms). Prints per-pass p50/p95 and a
* sha256 over every chunk, so a before/after pair is also an equivalence
* check on the whole corpus. Opt-in, never run in CI; reads only.
*
* bun scripts/bench/efficiency/bench-chunk.ts --data $BENCH_WORK/import/synth-full [--n 20]
* bun scripts/bench/efficiency/bench-chunk.ts --cjk 2000 [--n 20]
+ * bun scripts/bench/efficiency/bench-chunk.ts --cjk-prose 2000 [--n 20]
*/
import { createHash } from 'node:crypto';
import { readdirSync, readFileSync, statSync } from 'node:fs';
@@ -21,6 +23,7 @@ import { flag, machine, pct, rng } from './lib.ts';
const N = Number(flag('n', '20'));
const data = flag('data');
const cjkPages = Number(flag('cjk', '0'));
+const proseCjkPages = Number(flag('cjk-prose', '0'));
function walk(dir: string): string[] {
return readdirSync(dir).flatMap(name => {
@@ -52,7 +55,34 @@ function cjkCorpus(count: number): Array<{ compiled_truth: string; timeline: str
return pages;
}
-const pages = cjkPages > 0
+/** CJK prose shaped like real notes: frequent characters, sentence punctuation, few Latin terms. */
+function cjkProseCorpus(count: number): Array<{ compiled_truth: string; timeline: string }> {
+ const r = rng(74);
+ const common = '的一是不了人我在有他这为之大来以个中上们到说国和地也子时道出而要于就下得可你年生自会那后能对着事其里所去行过家十用发天如然作方成者多日都三小军二无同么经法当起与好看学进种将还分此心前面又定见只主没公从知全己体点长回正但现明问因外由意文重已加战度机位数门理被开位产话样表通无路论系最';
+ const kana = ['です', 'ます', 'した', 'ない', 'という', 'から', 'まで', 'こと', 'もの', 'ように'];
+ const terms = ['gbrain', 'API', 'v0.60', 'PostgreSQL', 'MCP'];
+ const pages: Array<{ compiled_truth: string; timeline: string }> = [];
+ for (let p = 0; p < count; p++) {
+ let body = '';
+ const paragraphs = 2 + Math.floor(r() * 12);
+ for (let g = 0; g < paragraphs; g++) {
+ const sentences = 2 + Math.floor(r() * 10);
+ for (let s = 0; s < sentences; s++) {
+ const len = 8 + Math.floor(r() * 32);
+ for (let i = 0; i < len; i++) body += r() < 0.08 ? kana[Math.floor(r() * kana.length)] : common[Math.floor(r() * common.length)];
+ if (r() < 0.15) body += ` ${terms[Math.floor(r() * terms.length)]} `;
+ body += ['。', ',', '!', '?', '、'][Math.floor(r() * 5)];
+ }
+ body += '\n\n';
+ }
+ pages.push({ compiled_truth: body, timeline: '' });
+ }
+ return pages;
+}
+
+const pages = proseCjkPages > 0
+ ? cjkProseCorpus(proseCjkPages)
+ : cjkPages > 0
? cjkCorpus(cjkPages)
: walk(data ?? (() => { throw new Error('--data <dir> or --cjk <pages>'); })()).map(f => {
const parsed = parseMarkdown(readFileSync(f, 'utf8'), f);
@@ -82,7 +112,7 @@ for (let i = 0; i < N; i++) {
}
console.log(JSON.stringify({
machine: machine(),
- corpus: cjkPages > 0 ? `cjk-${cjkPages}` : data,
+ corpus: proseCjkPages > 0 ? `cjk-prose-${proseCjkPages}` : cjkPages > 0 ? `cjk-${cjkPages}` : data,
pages: pages.length,
chunks: warm.chunks,
chunk_sha256_16: warm.hash,
diff --git a/src/cli/main.ts b/src/cli/main.ts
index cbb0008c56..55f48ac9d1 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -402,6 +402,16 @@ async function main() {
const strictRefusal = helpRequested ? null : strictArgsRefusal(command, subArgs);
if (strictRefusal) exitCliError(strictRefusal, command);
+ // A command that opens the local PGLite brain starts compiling its WASM now,
+ // off the main thread, while the command's own modules load; connect awaits
+ // the same cached promise (and sees any failure there).
+ if (cliOps.has(command) || cliAliases.has(command) || findCliCommand(command)?.phase === 'post-connect') {
+ const cfg = loadConfig();
+ if (cfg?.engine === 'pglite' && cfg.database_path) {
+ void import('../core/pglite-embedded-assets.ts').then(m => m.getEmbeddedPgliteOptions()).catch(() => {});
+ }
+ }
+
// T5 — `gbrain search modes|stats|tune` is the read-only config dashboard,
// NOT a free-text search for the literal word "modes". Free-text
// `gbrain search "<query>"` falls through to the cheap-hybrid `search` op
diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.ts
index e25bc38868..ea571de735 100644
--- a/src/core/chunkers/recursive.ts
+++ b/src/core/chunkers/recursive.ts
@@ -21,7 +21,7 @@
*/
import { countCJKAwareWords, isCJKDominant, wordStats, concatWordStats, wordCountOf, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_DELIMITERS } from '../cjk.ts';
-import { estimateEmbedTokens, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';
+import { estimateEmbedTokens, fitsEmbedTokens, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';
import { safeSplitIndex } from '../text-safe.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import { credentialSafeProjection } from '../credential-projection.ts';
@@ -166,6 +166,7 @@ function capByChars(
knownEst?: number,
): string[] {
if (text.length === 0) return [];
+ if (knownEst === undefined && text.length <= maxChars && fitsEmbedTokens(text, maxTokens)) return [text];
const est = knownEst ?? probeEmbedTokens(text);
const window = est <= maxTokens
? maxChars
@@ -193,7 +194,7 @@ function capByChars(
const end = safeSplitIndex(text, Math.min(text.length, i + window));
const slice = text.slice(i, end).trim();
if (slice.length > 0) {
- const sliceEst = estimateEmbedTokens(slice);
+ const sliceEst = fitsEmbedTokens(slice, maxTokens) ? 0 : estimateEmbedTokens(slice);
if (sliceEst > maxTokens) {
// Denser than the text average — re-derive locally, reusing the exact
// figure just measured (it also guarantees window < slice.length, so
diff --git a/src/core/chunkers/token-estimate.ts b/src/core/chunkers/token-estimate.ts
index 49e217ffae..4a503f3a38 100644
--- a/src/core/chunkers/token-estimate.ts
+++ b/src/core/chunkers/token-estimate.ts
@@ -105,6 +105,7 @@ const PRETOKEN_MEMO_MAX_ENTRIES = 50_000;
const PRETOKEN_MEMO_MAX_CHARS = 64;
const pretokenCounts = new Map<string, number>();
let pieceCounting = true;
+let byteBound = true;
/**
* Same count as encodeCount: segments and pre-tokens go through
@@ -165,6 +166,10 @@ export const __testing = {
setPieceCounting(on: boolean): void {
pieceCounting = on;
},
+ /** false makes fitsEmbedTokens never vouch, so every cap decision counts (the reference path). */
+ setByteBound(on: boolean): void {
+ byteBound = on;
+ },
};
const CJK_CHARS_G = new RegExp(`[${CJK_SLUG_CHARS}]`, 'g');
@@ -188,6 +193,18 @@ export function estimateEmbedTokens(text: string): number {
return Math.max(estimateTokens(text), weightedTokens(text, cjk));
}
+/**
+ * True when `text` provably fits `maxTokens` under estimateEmbedTokens without
+ * counting: its UTF-8 byte length is an upper bound on both halves. cl100k is
+ * a byte-level BPE, so every token covers at least one byte (the len/4
+ * fallback is smaller still), and the weighted form charges at most 1 per
+ * UTF-16 unit while every unit encodes to at least one byte. A typical CJK
+ * chunk (~350 chars, ~1 KB) fits without touching the encoder.
+ */
+export function fitsEmbedTokens(text: string, maxTokens: number): boolean {
+ return byteBound && (text.length * 3 <= maxTokens || Buffer.byteLength(text, 'utf8') <= maxTokens);
+}
+
/** The per-char-class overestimate half of estimateEmbedTokens. Linear (two
* regex scans), unlike the cl100k encoder — see estimateEmbedTokensCeiling. */
function weightedTokens(text: string, cjk: number): number {
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index be5d162dd7..60e4f1a2f5 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -842,9 +842,11 @@ export async function importFromContent(
});
if (existing && !preimage) await tx.createVersion(slug, txOpts); // reads the page itself, so before the page write
- // A prepared import keeps each stored row that is identical to its new chunk
- // and writes only the rest, so an edit rewrites only the chunks it changed.
- const fresh = reusable && opts.prepare ? chunks.map(chunk => ({ ...chunk })) : chunks;
+ // Every import keeps each stored row that is identical to its new chunk and
+ // writes only the rest, so an edit rewrites only the chunks it changed. The
+ // reuse is re-read here, under the page lock, so a kept row is one this
+ // transaction sees; --no-embed and deferred-embed imports keep vectors too.
+ const fresh = reusable ? chunks.map(chunk => ({ ...chunk })) : chunks;
const kept = new Map([...(fresh !== chunks ? await reuseStoredVectors(tx, fresh) : [])].filter(([, id]) => id !== null));
const keptIds = [...kept.values()];
let written: Page | undefined;
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 4f44c97ebc..290290a9b6 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 224;
+export const LATEST_SCHEMA_VERSION = 225;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index a0fd041e3d..f7b0757c3c 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -225,6 +225,7 @@ import { v221 } from './v221-chunk-embedding-pending-since.ts';
import { v222 } from './v222-persistence-consumers.ts';
import { v223 } from './v223-persistence-serve-loop-indexes.ts';
import { v224 } from './v224-page-retrievals.ts';
+import { v225 } from './v225-drop-duplicate-embedding-null-index.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -448,4 +449,5 @@ export const MIGRATIONS: Migration[] = [
v222,
v223,
v224,
+ v225,
];
diff --git a/src/core/schema-migrations/v225-drop-duplicate-embedding-null-index.ts b/src/core/schema-migrations/v225-drop-duplicate-embedding-null-index.ts
new file mode 100644
index 0000000000..0fde25fc6e
--- /dev/null
+++ b/src/core/schema-migrations/v225-drop-duplicate-embedding-null-index.ts
@@ -0,0 +1,35 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// v66's idx_chunks_embedding_null and v103's content_chunks_stale_idx are the
+// same partial btree, `ON content_chunks (page_id, chunk_index) WHERE embedding
+// IS NULL`, and v134 re-creates both. Every chunk insert, and every embedding
+// write that clears or sets the vector, maintained two identical index entries.
+// schema.sql and the PGLite schema carry content_chunks_stale_idx, so it stays;
+// the planner treats the two as interchangeable for `embed --stale`.
+//
+// The duplicate is dropped only while content_chunks_stale_idx is valid and has
+// the same definition, so a failed concurrent build or an operator's redefined
+// index never leaves the stale scan without its index.
+// CONCURRENTLY on Postgres (the handler runs outside a transaction), inline
+// on PGLite. runSchemaTransition replays whichever indexes depend on the
+// embedding column, so a later dimension change does not bring it back.
+export const v225: Migration = {
+ version: 225,
+ name: 'drop_duplicate_embedding_null_index',
+ idempotent: true,
+ sql: '',
+ handler: async engine => {
+ const [dup] = await engine.executeRaw<{ same: boolean }>(
+ `SELECT regexp_replace(pg_get_indexdef(d.indexrelid), '^CREATE INDEX \\S+ ', '')
+ = regexp_replace(pg_get_indexdef(k.indexrelid), '^CREATE INDEX \\S+ ', '') AS same
+ FROM pg_index d, pg_index k
+ WHERE d.indexrelid = to_regclass('idx_chunks_embedding_null')
+ AND k.indexrelid = to_regclass('content_chunks_stale_idx')
+ AND k.indisvalid AND k.indisready`);
+ if (!dup?.same) return;
+ await engine.runMigration(225, `DROP INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}IF EXISTS idx_chunks_embedding_null;`);
+ },
+};
diff --git a/test/chunkers/fits-embed-tokens.test.ts b/test/chunkers/fits-embed-tokens.test.ts
new file mode 100644
index 0000000000..28e92c7e4f
--- /dev/null
+++ b/test/chunkers/fits-embed-tokens.test.ts
@@ -0,0 +1,129 @@
+/**
+ * capByChars skips the token count when a chunk's UTF-8 byte length already
+ * proves it fits the budget (fitsEmbedTokens). That is sound only if the byte
+ * length bounds estimateEmbedTokens from above for every string: the fuzz
+ * checks the bound directly, and the corpora compare whole chunker outputs
+ * with the bound disabled through the test seam (every decision counted).
+ */
+
+import { afterEach, describe, expect, test } from 'bun:test';
+import { __testing, estimateEmbedTokens, estimateTokens, fitsEmbedTokens } from '../../src/core/chunkers/token-estimate.ts';
+import { chunkText } from '../../src/core/chunkers/recursive.ts';
+import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';
+
+afterEach(() => __testing.setByteBound(true));
+
+function rng(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (s + 0x6d2b79f5) >>> 0;
+ let t = s;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+const PIECES = [
+ () => 'granite', () => ' harbor', () => 'API', () => 'v0.60', () => '<|endoftext|>', () => '\n', () => '\n\n', () => ' ', () => '\t',
+ () => '。', () => ',', () => '!?', () => '😀', () => '🚀', () => '\u00e9t\u00e9', () => '\u2019', () => '\ufeff', () => '\ud800',
+ () => '1234567', () => 'https://example.com/a?b=c', () => '## heading', () => '- item',
+];
+
+function fuzzString(r: () => number): string {
+ let s = '';
+ const len = 1 + Math.floor(r() * 400);
+ while (s.length < len) {
+ const roll = r();
+ if (roll < 0.3) s += String.fromCharCode(0x4e00 + Math.floor(r() * 0x5200));
+ else if (roll < 0.4) s += String.fromCharCode(0x3041 + Math.floor(r() * 0xbe));
+ else if (roll < 0.45) s += String.fromCharCode(0xac00 + Math.floor(r() * 0x2ba4));
+ else s += PIECES[Math.floor(r() * PIECES.length)]!();
+ }
+ return s;
+}
+
+function cjkPage(r: () => number, density: number): string {
+ const words = ['gbrain', 'search', 'API', 'v0.60', 'memory', 'note', '😀'];
+ let body = '';
+ const sentences = 20 + Math.floor(r() * 160);
+ for (let s = 0; s < sentences; s++) {
+ const len = 5 + Math.floor(r() * 40);
+ for (let i = 0; i < len; i++) {
+ body += r() < density ? String.fromCharCode((r() < 0.7 ? 0x4e00 : 0x3041) + Math.floor(r() * (r() < 0.7 ? 0x5200 : 0xbe))) : ` ${words[Math.floor(r() * words.length)]} `;
+ }
+ body += ['。', '!', '?', '. ', ',', '\n', '\n\n'][Math.floor(r() * 7)];
+ }
+ return body;
+}
+
+describe('fitsEmbedTokens', () => {
+ test('UTF-8 byte length bounds estimateEmbedTokens and estimateTokens on 5,000 mixed strings', () => {
+ const r = rng(6006);
+ for (let i = 0; i < 5000; i++) {
+ const s = fuzzString(r);
+ const bytes = Buffer.byteLength(s, 'utf8');
+ expect(estimateEmbedTokens(s)).toBeLessThanOrEqual(bytes);
+ expect(estimateTokens(s)).toBeLessThanOrEqual(bytes);
+ for (const max of [16, 64, 512, 2000]) {
+ if (fitsEmbedTokens(s, max)) expect(estimateEmbedTokens(s)).toBeLessThanOrEqual(max);
+ }
+ }
+ });
+
+ test('vouches exactly when the byte length fits', () => {
+ expect(fitsEmbedTokens('a'.repeat(2000), 2000)).toBe(true);
+ expect(fitsEmbedTokens('a'.repeat(2001), 2000)).toBe(false);
+ expect(fitsEmbedTokens('漢'.repeat(666), 2000)).toBe(true);
+ expect(fitsEmbedTokens('漢'.repeat(667), 2000)).toBe(false);
+ expect(fitsEmbedTokens('😀'.repeat(500), 2000)).toBe(true);
+ expect(fitsEmbedTokens('😀'.repeat(501), 2000)).toBe(false);
+ });
+});
+
+describe('chunker output is unchanged by the byte bound', () => {
+ const both = <T>(fn: () => T): [T, T] => {
+ const on = fn();
+ __testing.setByteBound(false);
+ try { return [on, fn()]; } finally { __testing.setByteBound(true); }
+ };
+
+ test('chunkText on CJK pages at three densities and three token budgets', () => {
+ const r = rng(75);
+ for (let p = 0; p < 45; p++) {
+ const text = cjkPage(r, [0.2, 0.5, 0.9][p % 3]!);
+ for (const maxTokens of [64, 500, 2000]) {
+ const [on, off] = both(() => chunkText(text, { maxTokens }));
+ expect(on).toEqual(off);
+ }
+ }
+ });
+
+ test('chunkText on whitespace-less CJK, emoji runs and short maxChars', () => {
+ const r = rng(76);
+ for (let p = 0; p < 20; p++) {
+ const han = Array.from({ length: 500 + Math.floor(r() * 9000) }, () => String.fromCharCode(0x4e00 + Math.floor(r() * 0x5200))).join('');
+ const emoji = '😀🚀'.repeat(200 + Math.floor(r() * 2000));
+ for (const text of [han, emoji, `${han}\n\n${emoji}`]) {
+ for (const opts of [{}, { maxChars: 700 }, { maxTokens: 300 }]) {
+ const [on, off] = both(() => chunkText(text, opts));
+ expect(on).toEqual(off);
+ }
+ }
+ }
+ });
+
+ test('prepareMarkdownChunks on mixed pages', async () => {
+ const r = rng(77);
+ for (let p = 0; p < 30; p++) {
+ const page = { compiled_truth: `# Title ${p}\n\n${cjkPage(r, [0.2, 0.9][p % 2]!)}`, timeline: p % 3 ? '' : cjkPage(r, 0.5) };
+ const on = await prepareMarkdownChunks(page);
+ __testing.setByteBound(false);
+ try {
+ expect(on).toEqual(await prepareMarkdownChunks(page));
+ } finally {
+ __testing.setByteBound(true);
+ }
+ }
+ });
+});
diff --git a/test/e2e/embed-stale-pagination.test.ts b/test/e2e/embed-stale-pagination.test.ts
index d33d2ae70f..e1042645d1 100644
--- a/test/e2e/embed-stale-pagination.test.ts
+++ b/test/e2e/embed-stale-pagination.test.ts
@@ -5,7 +5,8 @@
*
* - Static case: every chunk visited exactly once across multiple batches.
* - Cursor monotonically advances on `(page_id, chunk_index)`.
- * - Migration v66's partial index `idx_chunks_embedding_null` exists.
+ * - The `embedding IS NULL` partial index exists once (`content_chunks_stale_idx`;
+ * v225 dropped v66's identical `idx_chunks_embedding_null`).
* - D7: source-scoped scan returns ONLY that source's NULLs even when
* same-slug pages exist across sources.
* - Failed-page semantics: a failed upsert keeps `embedding IS NULL` and
@@ -117,9 +118,9 @@ describeE2E('embed --stale cursor pagination (D7 + REGRESSION)', () => {
await teardownDB();
});
- test('migration v66 created partial index idx_chunks_embedding_null', async () => {
- const exists = await indexExists('idx_chunks_embedding_null');
- expect(exists).toBe(true);
+ test('the embedding IS NULL partial index exists once (v225 dropped the v66 duplicate)', async () => {
+ expect(await indexExists('content_chunks_stale_idx')).toBe(true);
+ expect(await indexExists('idx_chunks_embedding_null')).toBe(false);
});
test('static case: every chunk visited exactly once across multiple batches', async () => {
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 40b6b0740e..92919eee4b 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -859,7 +859,6 @@
"idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",
"idx_chunks_embedding": "CREATE INDEX idx_chunks_embedding ON public.content_chunks USING hnsw (embedding vector_cosine_ops)",
"idx_chunks_embedding_image": "CREATE INDEX idx_chunks_embedding_image ON public.content_chunks USING hnsw (embedding_image vector_cosine_ops) WHERE (embedding_image IS NOT NULL)",
- "idx_chunks_embedding_null": "CREATE INDEX idx_chunks_embedding_null ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",
"idx_chunks_language": "CREATE INDEX idx_chunks_language ON public.content_chunks USING btree (language) WHERE (language IS NOT NULL)",
"idx_chunks_page": "CREATE INDEX idx_chunks_page ON public.content_chunks USING btree (page_id)",
"idx_chunks_page_index": "CREATE UNIQUE INDEX idx_chunks_page_index ON public.content_chunks USING btree (page_id, chunk_index)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 70f4c3500d..25ec1d213c 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -859,7 +859,6 @@
"idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",
"idx_chunks_embedding": "CREATE INDEX idx_chunks_embedding ON public.content_chunks USING hnsw (embedding vector_cosine_ops)",
"idx_chunks_embedding_image": "CREATE INDEX idx_chunks_embedding_image ON public.content_chunks USING hnsw (embedding_image vector_cosine_ops) WHERE (embedding_image IS NOT NULL)",
- "idx_chunks_embedding_null": "CREATE INDEX idx_chunks_embedding_null ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",
"idx_chunks_language": "CREATE INDEX idx_chunks_language ON public.content_chunks USING btree (language) WHERE (language IS NOT NULL)",
"idx_chunks_page": "CREATE INDEX idx_chunks_page ON public.content_chunks USING btree (page_id)",
"idx_chunks_page_index": "CREATE UNIQUE INDEX idx_chunks_page_index ON public.content_chunks USING btree (page_id, chunk_index)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 5e43d58d05..4061b3f12b 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -858,7 +858,6 @@
"idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",
"idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",
"idx_chunks_embedding_image": "CREATE INDEX idx_chunks_embedding_image ON public.content_chunks USING hnsw (embedding_image vector_cosine_ops) WHERE (embedding_image IS NOT NULL)",
- "idx_chunks_embedding_null": "CREATE INDEX idx_chunks_embedding_null ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",
"idx_chunks_language": "CREATE INDEX idx_chunks_language ON public.content_chunks USING btree (language) WHERE (language IS NOT NULL)",
"idx_chunks_page": "CREATE INDEX idx_chunks_page ON public.content_chunks USING btree (page_id)",
"idx_chunks_page_index": "CREATE UNIQUE INDEX idx_chunks_page_index ON public.content_chunks USING btree (page_id, chunk_index)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index ded8132792..ff337e79e5 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -861,7 +861,6 @@
"idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",
"idx_chunks_embedding": "CREATE INDEX idx_chunks_embedding ON public.content_chunks USING hnsw (embedding vector_cosine_ops)",
"idx_chunks_embedding_image": "CREATE INDEX idx_chunks_embedding_image ON public.content_chunks USING hnsw (embedding_image vector_cosine_ops) WHERE (embedding_image IS NOT NULL)",
- "idx_chunks_embedding_null": "CREATE INDEX idx_chunks_embedding_null ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",
"idx_chunks_language": "CREATE INDEX idx_chunks_language ON public.content_chunks USING btree (language) WHERE (language IS NOT NULL)",
"idx_chunks_page": "CREATE INDEX idx_chunks_page ON public.content_chunks USING btree (page_id)",
"idx_chunks_page_index": "CREATE UNIQUE INDEX idx_chunks_page_index ON public.content_chunks USING btree (page_id, chunk_index)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index c8493f9543..7031a332f8 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -861,7 +861,6 @@
"idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",
"idx_chunks_embedding": "CREATE INDEX idx_chunks_embedding ON public.content_chunks USING hnsw (embedding vector_cosine_ops)",
"idx_chunks_embedding_image": "CREATE INDEX idx_chunks_embedding_image ON public.content_chunks USING hnsw (embedding_image vector_cosine_ops) WHERE (embedding_image IS NOT NULL)",
- "idx_chunks_embedding_null": "CREATE INDEX idx_chunks_embedding_null ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",
"idx_chunks_language": "CREATE INDEX idx_chunks_language ON public.content_chunks USING btree (language) WHERE (language IS NOT NULL)",
"idx_chunks_page": "CREATE INDEX idx_chunks_page ON public.content_chunks USING btree (page_id)",
"idx_chunks_page_index": "CREATE UNIQUE INDEX idx_chunks_page_index ON public.content_chunks USING btree (page_id, chunk_index)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 04de96e6d6..5bd45c05b0 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -860,7 +860,6 @@
"idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",
"idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",
"idx_chunks_embedding_image": "CREATE INDEX idx_chunks_embedding_image ON public.content_chunks USING hnsw (embedding_image vector_cosine_ops) WHERE (embedding_image IS NOT NULL)",
- "idx_chunks_embedding_null": "CREATE INDEX idx_chunks_embedding_null ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",
"idx_chunks_language": "CREATE INDEX idx_chunks_language ON public.content_chunks USING btree (language) WHERE (language IS NOT NULL)",
"idx_chunks_page": "CREATE INDEX idx_chunks_page ON public.content_chunks USING btree (page_id)",
"idx_chunks_page_index": "CREATE UNIQUE INDEX idx_chunks_page_index ON public.content_chunks USING btree (page_id, chunk_index)",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 6cb1a743b5..0ae528e4ec 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 219,
+ "count": 220,
"gaps": [
17,
18,
@@ -39,7 +39,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 224,
+ "latest": 225,
"records": [
{
"handler": {
@@ -3347,6 +3347,23 @@
"transaction": "absent",
"verify": "absent",
"version": 224
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [],
+ "sha256": "2659c6afb6f5c7aa3e5b10c5d5b26b635325ff9e918b8837437027d777eeb8f2"
+ },
+ "idempotent": true,
+ "name": "drop_duplicate_embedding_null_index",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 225
}
],
"versions": [
@@ -3568,7 +3585,8 @@
221,
222,
223,
- 224
+ 224,
+ 225
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 6a053386c1..1da95d38a2 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -859,7 +859,6 @@
"idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",
"idx_chunks_embedding": "CREATE INDEX idx_chunks_embedding ON public.content_chunks USING hnsw (embedding vector_cosine_ops)",
"idx_chunks_embedding_image": "CREATE INDEX idx_chunks_embedding_image ON public.content_chunks USING hnsw (embedding_image vector_cosine_ops) WHERE (embedding_image IS NOT NULL)",
- "idx_chunks_embedding_null": "CREATE INDEX idx_chunks_embedding_null ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",
"idx_chunks_language": "CREATE INDEX idx_chunks_language ON public.content_chunks USING btree (language) WHERE (language IS NOT NULL)",
"idx_chunks_page": "CREATE INDEX idx_chunks_page ON public.content_chunks USING btree (page_id)",
"idx_chunks_page_index": "CREATE UNIQUE INDEX idx_chunks_page_index ON public.content_chunks USING btree (page_id, chunk_index)",
diff --git a/test/import-inline-chunk-keep.test.ts b/test/import-inline-chunk-keep.test.ts
new file mode 100644
index 0000000000..aa29a3b187
--- /dev/null
+++ b/test/import-inline-chunk-keep.test.ts
@@ -0,0 +1,126 @@
+/**
+ * An inline (CLI import / classic sync) edit keeps every stored chunk row that
+ * is identical to its new chunk and rewrites only the rest, with and without
+ * --no-embed. The stored result must equal a fresh import of the same content
+ * in every column but the row id, and a kept row keeps its id and vector.
+ *
+ * PGLite in-memory always; Postgres when DATABASE_URL is set. The embedding
+ * transport is stubbed ($0).
+ */
+
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';
+
+const DIMS = 1536;
+let embedded: string[] = [];
+let counter = 0;
+
+function gateway() {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ embedded.push(...values);
+ return {
+ embeddings: values.map(() => { const v = new Array(DIMS).fill(0); v[counter++ % DIMS] = 1; return v; }),
+ usage: { tokens: values.length },
+ };
+ }) as never);
+}
+
+const paragraph = (word: string) => Array.from({ length: 400 }, (_, i) => `${word}${i}`).join(' ') + '.';
+const page = (title: string, words: string[], extra = '') =>
+ `---\ntype: note\ntitle: ${title}\n---\n\n${words.map(w => `## Section ${w}\n\n${paragraph(w)}`).join('\n\n')}\n${extra}`;
+
+for (const kind of ['pglite', 'postgres'] as const) {
+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;
+ suite(`${kind}: an inline edit keeps unchanged chunk rows`, () => {
+ let engine: BrainEngine;
+ const sourceId = `inline-keep-${kind}-${process.pid}`;
+
+ beforeAll(async () => {
+ resetGateway();
+ gateway();
+ engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+ if (kind === 'postgres') assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);
+ await engine.connect(kind === 'postgres' ? { database_url: process.env.DATABASE_URL! } : {});
+ await engine.initSchema();
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);
+ }, 120_000);
+
+ afterAll(async () => {
+ try {
+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [sourceId]);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
+ } finally {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+ }
+ }, 60_000);
+
+ beforeEach(() => { embedded = []; gateway(); });
+
+ const rows = (slug: string) => engine.executeRaw<Record<string, unknown>>(`SELECT c.id, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::text AS embedding,
+ c.model, c.token_count, c.embedded_text_hash, c.embedding_input_hash, c.search_vector::text AS search_vector, c.modality
+ FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY c.chunk_index`, [sourceId, slug]);
+ const withoutId = (list: Record<string, unknown>[]) => list.map(({ id: _id, ...rest }) => rest);
+ const write = (slug: string, content: string, noEmbed = false) => importFromContent(engine, slug, content, { sourceId, noEmbed });
+
+ test('an embedded edit keeps unchanged rows in place and stores what a fresh import stores', async () => {
+ const words = ['alpha', 'bravo', 'charlie', 'delta', 'foxtrot'];
+ await write('notes/edit', page('Keep', words));
+ const before = await rows('notes/edit');
+ expect(before.length).toBeGreaterThanOrEqual(4);
+ embedded = [];
+ words[2] = 'echo';
+ await write('notes/edit', page('Keep', words));
+ const after = await rows('notes/edit');
+ const kept = after.filter(row => before.some(old => old.id === row.id));
+ expect(kept.length).toBeGreaterThan(0);
+ expect(embedded.length).toBe(after.length - kept.length);
+ for (const row of kept) expect(row).toEqual(before.find(old => old.id === row.id)!);
+ for (const text of embedded) expect(text).toContain('echo');
+ expect(after.every(row => row.embedding !== null)).toBe(true);
+ // A fresh import of the edited content stores the same rows (its vectors come from new stub calls).
+ await write('notes/reference', page('Keep', words));
+ expect(withoutId(await rows('notes/reference')).map(({ embedding: _e, ...rest }) => rest))
+ .toEqual(withoutId(after).map(({ embedding: _e, ...rest }) => rest));
+ }, 120_000);
+
+ test('a --no-embed edit keeps unchanged rows with their vectors and leaves only changed chunks stale', async () => {
+ const words = ['golf', 'hotel', 'india', 'juliet', 'kilo'];
+ await write('notes/no-embed', page('NoEmbed', words));
+ const before = await rows('notes/no-embed');
+ expect(before.every(row => row.embedding !== null)).toBe(true);
+ embedded = [];
+ words[1] = 'lima';
+ await write('notes/no-embed', page('NoEmbed', words), true);
+ expect(embedded).toEqual([]);
+ const after = await rows('notes/no-embed');
+ const kept = after.filter(row => before.some(old => old.id === row.id));
+ expect(kept.length).toBeGreaterThan(0);
+ for (const row of kept) expect(row).toEqual(before.find(old => old.id === row.id)!);
+ const stale = after.filter(row => row.embedding === null);
+ expect(stale.length).toBeGreaterThan(0);
+ expect(stale.every(row => String(row.chunk_text).includes('lima'))).toBe(true);
+ // A fresh --no-embed import of the edited content stores the same text rows.
+ await write('notes/no-embed-reference', page('NoEmbed', words), true);
+ const strip = (list: Record<string, unknown>[]) => withoutId(list).map(({ embedding: _e, model: _m, token_count: _t, embedded_text_hash: _h, embedding_input_hash: _i, ...rest }) => rest);
+ expect(strip(await rows('notes/no-embed-reference'))).toEqual(strip(after));
+ }, 120_000);
+
+ test('an unchanged re-import with a protected fence keeps nothing', async () => {
+ const fence = '\n<!--- gbrain:takes:begin -->\nPRIVATE_CANARY\n<!--- gbrain:takes:end -->\n';
+ await write('notes/protected', page('Protected', ['mike', 'november', 'oscar'], fence));
+ const before = await rows('notes/protected');
+ await write('notes/protected', page('Protected', ['mike', 'november', 'papa'], fence), true);
+ const after = await rows('notes/protected');
+ expect(after.some(row => before.some(old => old.id === row.id))).toBe(false);
+ expect(after.every(row => row.embedding === null)).toBe(true);
+ }, 120_000);
+ });
+}
diff --git a/test/migrate.test.ts b/test/migrate.test.ts
index 80aec108e6..fa4f3d5883 100644
--- a/test/migrate.test.ts
+++ b/test/migrate.test.ts
@@ -894,14 +894,73 @@ describe('migrate runner v66 — partial index materialized on PGLite', () => {
await engine.disconnect();
});
- test('v66 created idx_chunks_embedding_null on PGLite via handler branch', async () => {
- const rows = await (engine as any).db.query(
+ // v225 drops the index again at head (content_chunks_stale_idx is the same
+ // partial index), so the handler branch is exercised directly.
+ test('v66 creates idx_chunks_embedding_null on PGLite via handler branch', async () => {
+ const indexes = async () => (await (engine as any).db.query(
`SELECT indexname FROM pg_indexes WHERE indexname = 'idx_chunks_embedding_null'`
- );
- expect(rows.rows.length).toBe(1);
+ )).rows;
+ expect(await indexes()).toHaveLength(0);
+ await MIGRATIONS.find(m => m.version === 66)!.handler!(engine);
+ expect(await indexes()).toHaveLength(1);
});
});
+// v225: idx_chunks_embedding_null (v66) and content_chunks_stale_idx (v103)
+// were the same partial btree; v225 drops the v66 copy only while the kept
+// index is valid and identical.
+describe('v225 — drop_duplicate_embedding_null_index', () => {
+ const stale = async (engine: PGLiteEngine) => (await engine.executeRaw<{ indexname: string; indexdef: string }>(
+ `SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'content_chunks'
+ AND indexname IN ('idx_chunks_embedding_null', 'content_chunks_stale_idx') ORDER BY indexname`)).map(r => r.indexname);
+
+ test('a fresh brain keeps only content_chunks_stale_idx, and re-running is a no-op', async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ try {
+ await engine.initSchema();
+ expect(await stale(engine)).toEqual(['content_chunks_stale_idx']);
+ await MIGRATIONS.find(m => m.version === 225)!.handler!(engine);
+ expect(await stale(engine)).toEqual(['content_chunks_stale_idx']);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 30000);
+
+ test('a brain at v224 loses the duplicate and keeps the stale index', async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ try {
+ await engine.initSchema();
+ await MIGRATIONS.find(m => m.version === 66)!.handler!(engine);
+ expect(await stale(engine)).toEqual(['content_chunks_stale_idx', 'idx_chunks_embedding_null']);
+ await engine.setConfig('version', '224');
+ await runMigrations(engine);
+ expect(await stale(engine)).toEqual(['content_chunks_stale_idx']);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 30000);
+
+ test('keeps idx_chunks_embedding_null when content_chunks_stale_idx is missing or defined differently', async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ try {
+ await engine.initSchema();
+ const v225 = MIGRATIONS.find(m => m.version === 225)!;
+ await MIGRATIONS.find(m => m.version === 66)!.handler!(engine);
+ await engine.executeRaw(`DROP INDEX content_chunks_stale_idx`);
+ await v225.handler!(engine);
+ expect(await stale(engine)).toEqual(['idx_chunks_embedding_null']);
+ await engine.executeRaw(`CREATE INDEX content_chunks_stale_idx ON content_chunks (page_id) WHERE embedding IS NULL`);
+ await v225.handler!(engine);
+ expect(await stale(engine)).toEqual(['content_chunks_stale_idx', 'idx_chunks_embedding_null']);
+ } finally {
+ await engine.disconnect();
+ }
+ }, 30000);
+});
+
// ────────────────────────────────────────────────────────────────────────
// v0.35.4 — migration v67 (facts_typed_claim_columns)
// Adds four optional typed-claim columns to `facts` + a partial index
@@ -2394,7 +2453,8 @@ describe('v134 — restore_chunks_embedding_null_partial_indexes', () => {
AND indexname IN ('idx_chunks_embedding_null', 'content_chunks_stale_idx')
ORDER BY indexname`,
);
- expect(rows.map(r => r.indexname)).toEqual(['content_chunks_stale_idx', 'idx_chunks_embedding_null']);
+ // v134 re-creates both; v225 then drops the v66 duplicate of content_chunks_stale_idx.
+ expect(rows.map(r => r.indexname)).toEqual(['content_chunks_stale_idx']);
for (const r of rows) {
expect(r.indexdef).toMatch(/WHERE\s+\(?embedding IS NULL\)?/i);
}