Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): page keyword vector indexes a bounded timeline prefix (v245 rebuilds long-timeline pages)

garrytan6861f77126f8
diff --git a/src/core/engine.ts b/src/core/engine.ts
index adf44dd30d..9b2e6f0fb1 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1156,10 +1156,11 @@ export interface BrainEngine {
* doc_comment + symbol_name_qualified + chunk_text), so a page whose
* title tokens are absent from its body is unreachable by searchKeyword.
* This arm queries the PAGE-GRAIN DOCUMENT vector pages.search_vector —
- * NOT titles alone: per trg_pages_search_vector it is title (weight 'A')
- * + compiled_truth ('B') + timeline text ('C'). Ranked by ts_rank_cd,
- * the 'A'-weighted title dominates, but body/timeline matches also
- * produce (lower-ranked) candidates. Returns page-grain hits joined to
+ * NOT titles alone: per pageSearchVectorSql it is title (weight 'A') +
+ * the first PAGE_TIMELINE_FTS_MAX_CHARS characters of the sanitized
+ * timeline ('C'); compiled_truth is not indexed since v124. Ranked by
+ * ts_rank_cd, the 'A'-weighted title dominates, but timeline matches
+ * also produce (lower-ranked) candidates. Returns page-grain hits joined to
* ONE representative chunk per page (compiled_truth preferred, else
* lowest chunk_index) so rows are shaped like searchKeyword's output and
* can enter RRF fusion in hybridSearch.
diff --git a/src/core/fts-language.ts b/src/core/fts-language.ts
index 385be39de2..94da29e9fb 100644
--- a/src/core/fts-language.ts
+++ b/src/core/fts-language.ts
@@ -148,16 +148,28 @@ $fn$;`;
/** POSIX regex (SQL `~`) matching text that holds a CJK/ASCII-alnum boundary `gbrain_fts_input` splits. */
export const FTS_CJK_BOUNDARY_REGEX = `${CJK_CLASS}[A-Za-z0-9]|[A-Za-z0-9]${CJK_CLASS}`;
+/**
+ * Characters of the page timeline the page keyword vector indexes, and of
+ * the joined timeline entries the trigger adds. A tsvector's lexeme strings
+ * cap at 1 MB; the densest text measured (hyphenated astral and CJK pairs)
+ * yields about 7.5 lexeme bytes per character under Postgres 16, so 65,536 +
+ * 32,768 characters stay under 750 KB with room for the title, while a
+ * diverse multi-MB timeline used to fail the whole page write. Chunk search
+ * still covers the full timeline.
+ */
+export const PAGE_TIMELINE_FTS_MAX_CHARS = 65_536;
+export const PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS = 32_768;
+
/**
* The page keyword vector every sealed writer stores: the title (weight A) and
- * the SANITIZED timeline (weight C, bound by the caller; never the raw column,
- * which can hold private or withdrawn fence text). `title` and `timeline` are
- * SQL expressions. Shared by the seal, the import seal,
- * `reindex-search-vector` and the fts-cjk-boundary migration, so they cannot
- * drift.
+ * the first PAGE_TIMELINE_FTS_MAX_CHARS characters of the SANITIZED timeline
+ * (weight C, bound by the caller; never the raw column, which can hold
+ * private or withdrawn fence text). `title` and `timeline` are SQL
+ * expressions. Shared by the seal, the import seal, `reindex-search-vector`
+ * and the fts-cjk-boundary migration, so they cannot drift.
*/
export function pageSearchVectorSql(title: string, timeline: string, lang: string = getFtsLanguage()): string {
- return `setweight(to_tsvector('${lang}',gbrain_fts_input(COALESCE(${title},''))),'A') || setweight(to_tsvector('${lang}',gbrain_fts_input(${timeline}::text)),'C')`;
+ return `setweight(to_tsvector('${lang}',gbrain_fts_input(COALESCE(${title},''))),'A') || setweight(to_tsvector('${lang}',gbrain_fts_input(left(${timeline}::text,${PAGE_TIMELINE_FTS_MAX_CHARS}))),'C')`;
}
/** The chunk keyword vector, over a row's own columns (`NEW.` in the trigger, bare in a backfill). */
@@ -173,7 +185,9 @@ export function chunkSearchVectorSql(lang: string, row = ''): string {
* bodies are byte-identical to src/schema.sql's for 'english' (pinned by
* test/fts-cjk-boundary.test.ts), so the blob replay that every boot runs
* after a migration leaves the catalog unchanged. #2704: compiled_truth is not
- * indexed (it overflows the 1MB tsvector cap). `SET search_path = pg_catalog,
+ * indexed (it overflows the 1MB tsvector cap); the timeline and the joined
+ * entries are cut to their FTS caps for the same reason, the entries in id
+ * order so the cut is deterministic. `SET search_path = pg_catalog,
* public` keeps the v120/#1647 hardening, which CREATE OR REPLACE would
* otherwise reset.
*/
@@ -182,15 +196,15 @@ export function pageSearchVectorTriggerFnSql(lang: string): string {
DECLARE
timeline_text TEXT;
BEGIN
- SELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')
+ SELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')
INTO timeline_text
FROM timeline_entries
WHERE page_id = NEW.id;
NEW.search_vector :=
setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||
- setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||
- setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');
+ setweight(to_tsvector('${lang}', gbrain_fts_input(left(coalesce(NEW.timeline, ''), ${PAGE_TIMELINE_FTS_MAX_CHARS}))), 'C') ||
+ setweight(to_tsvector('${lang}', gbrain_fts_input(left(coalesce(timeline_text, ''), ${PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS}))), 'C');
RETURN NEW;
END;
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 4a0fe95b8d..b7671a802d 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -637,15 +637,15 @@ CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET searc
DECLARE
timeline_text TEXT;
BEGIN
- SELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')
+ SELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')
INTO timeline_text
FROM timeline_entries
WHERE page_id = NEW.id;
NEW.search_vector :=
setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||
- setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||
- setweight(to_tsvector('english', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');
+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, ''), 65536))), 'C') ||
+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(timeline_text, ''), 32768))), 'C');
RETURN NEW;
END;
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index facc053723..d0613547c8 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1157,15 +1157,15 @@ CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET searc
DECLARE
timeline_text TEXT;
BEGIN
- SELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')
+ SELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')
INTO timeline_text
FROM timeline_entries
WHERE page_id = NEW.id;
NEW.search_vector :=
setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||
- setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||
- setweight(to_tsvector('english', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');
+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, ''), 65536))), 'C') ||
+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(timeline_text, ''), 32768))), 'C');
RETURN NEW;
END;
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index fe278501ec..d0bb19dbe3 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 = 244;
+export const LATEST_SCHEMA_VERSION = 245;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index e75c32535d..2baf8fc1a1 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -245,6 +245,7 @@ import { v241 } from './v241-persistence-request-slug-intent-index.ts';
import { v242 } from './v242-extract-atoms-partial-input.ts';
import { v243 } from './v243-persistence-consumer-process-start.ts';
import { v244 } from './v244-chunk-projected-spans.ts';
+import { v245 } from './v245-page-search-vector-bounded-timeline.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -488,4 +489,5 @@ export const MIGRATIONS: Migration[] = [
v242,
v243,
v244,
+ v245,
];
diff --git a/src/core/schema-migrations/v245-page-search-vector-bounded-timeline.ts b/src/core/schema-migrations/v245-page-search-vector-bounded-timeline.ts
new file mode 100644
index 0000000000..d8186218b1
--- /dev/null
+++ b/src/core/schema-migrations/v245-page-search-vector-bounded-timeline.ts
@@ -0,0 +1,35 @@
+import type { Migration } from './types.ts';
+import { checkpointKey } from '../backfill-base.ts';
+import { getFtsLanguage, PAGE_TIMELINE_FTS_MAX_CHARS, pageSearchVectorTriggerFnSql } from '../fts-language.ts';
+import { backfillPageVectors } from '../search-vector-backfill.ts';
+import { migrationNotice } from './helpers.ts';
+
+const BOUNDED_TIMELINE_CHECKPOINT = 'page_vector_bounded_timeline';
+
+// Large pages: the page keyword vector indexed the whole timeline, and a
+// diverse timeline past about 1 MB overflowed the tsvector lexeme cap, which
+// failed the page write. The vector now indexes the first
+// PAGE_TIMELINE_FTS_MAX_CHARS characters of the timeline and
+// PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS of the joined timeline entries (in id
+// order). Recreates the pages trigger function under the configured language,
+// then rebuilds the vectors of pages whose timeline is longer than the
+// smaller cap, with the seal's own expression; shorter timelines index
+// byte-identically and are not touched. Handler-only: the language must be a
+// literal (getFtsLanguage() validates it). Batches run outside a transaction
+// with a per-batch keyset checkpoint, so an interrupted run resumes; re-running
+// is safe (the rebuild is idempotent).
+export const v245: Migration = {
+ version: 245,
+ name: 'page_search_vector_bounded_timeline',
+ idempotent: true,
+ sql: '',
+ handler: async (engine) => {
+ const lang = getFtsLanguage();
+ await engine.executeRaw(pageSearchVectorTriggerFnSql(lang));
+ const pages = await backfillPageVectors(engine, {
+ lang, checkpoint: BOUNDED_TIMELINE_CHECKPOINT, where: `char_length(timeline) > ${PAGE_TIMELINE_FTS_MAX_CHARS / 2}`,
+ });
+ await engine.unsetConfig(checkpointKey(BOUNDED_TIMELINE_CHECKPOINT));
+ migrationNotice(` page_search_vector_bounded_timeline: page keyword vectors index the first ${PAGE_TIMELINE_FTS_MAX_CHARS} timeline characters; rebuilt ${pages} page(s) with longer timelines\n`);
+ },
+};
diff --git a/src/schema.sql b/src/schema.sql
index f4037666ea..db8218bd24 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1153,15 +1153,15 @@ CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET searc
DECLARE
timeline_text TEXT;
BEGIN
- SELECT coalesce(string_agg(summary || ' ' || detail, ' '), '')
+ SELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')
INTO timeline_text
FROM timeline_entries
WHERE page_id = NEW.id;
NEW.search_vector :=
setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||
- setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.timeline, ''))), 'C') ||
- setweight(to_tsvector('english', gbrain_fts_input(coalesce(timeline_text, ''))), 'C');
+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, ''), 65536))), 'C') ||
+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(timeline_text, ''), 32768))), 'C');
RETURN NEW;
END;
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 755fafdf1a..5c9c2c35cf 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 239,
+ "count": 240,
"gaps": [
17,
18,
@@ -9,6 +9,7 @@
],
"helpers": {
"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",
+ "BOUNDED_TIMELINE_CHECKPOINT": "385c4da3e28732343148795d6e9a86670813a7a7cfa1e52f8a5bb494680a3c0d",
"CHECKPOINT": "3c6ff909363c4ba1c9d730e748654ab90aa07549ddf4bf36b8f93c5f4ea3680b",
"FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c",
"FACT_PURGES_SUBJECT_INDEX": "f4fba07082f2e26da3fa51b0b689f3fe78a3d09afd20c1924dbc2fbe6b1560f1",
@@ -20,6 +21,7 @@
"OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX": "e9b472d9db37733e908ea40512ad3f9520d7a6729ce207b0d279d43d3beb5b2f",
"PAGES_NAME_LOOKUP_INDEXES": "1ca830342164b5606e96cf0090645364f9145d36178d90f166230189fe8d2705",
"PAGES_RECONCILE_NAME_INDEXES": "8805e35341b22324b932b1cc05030cc8f2bfc95532bf810ec35330783f29c59a",
+ "PAGE_TIMELINE_FTS_MAX_CHARS": "f7d29264f4144976bbe2e1ded0251095b638175f8e1d711c36f1e80d2263e172",
"PERSISTENCE_COMMITTED_WATERMARK_INDEX": "f472fa0acb542c1caebaaa3bc69fb2da1647e5e201239429fc02ccef0d669533",
"PERSISTENCE_COMPACTABLE_INDEX": "25ee657878efb41ba9ea3a7624464ddcf66407d861659456c230366e57f230a0",
"PERSISTENCE_DATABASE_PENDING_INDEX_SQL": "6e0f618be33d037454933ea4dea11438413d45aef35d3bd4f33e89624d6e199e",
@@ -44,7 +46,7 @@
"migrateConnectorCheckpoints": "e0403022a56559556c82a9fa1e90d928f36e1d09c7db570e1d788a87d2dc9521",
"migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c",
"migrationNotice": "9a6607b26a9719ef1833571b137bc8ebfcd1e16d545e89ff8728cf3ccbcbb409",
- "pageSearchVectorTriggerFnSql": "c31a80562c8053479344d6060115a24854b1f419f6e09945f36b1403305f54e6",
+ "pageSearchVectorTriggerFnSql": "f9f083978d2a5cd756a889781ee07a921132c4db9d3cfa1b041da2af95a4a4b5",
"quietMigrationNotices": "4045c32034a8f46204dd5d89e185ff5c35e8073f560f14caa8b127f8a695957c",
"readExistingEmbeddingShape": "16d92d7cd52d8ebd7e89982f02e1bbdd8e8d08a6712a4ce57fbcf0952b7a6ca5",
"repairLegacyClientGrants": "c1dc6b1d0c4933c041583aa1c4eacaefc0ff0ae2a67f56cfad7534f87a5ab309",
@@ -54,7 +56,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 244,
+ "latest": 245,
"records": [
{
"handler": {
@@ -3710,6 +3712,32 @@
"transaction": "absent",
"verify": "absent",
"version": 244
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "BOUNDED_TIMELINE_CHECKPOINT",
+ "PAGE_TIMELINE_FTS_MAX_CHARS",
+ "backfillPageVectors",
+ "checkpointKey",
+ "getFtsLanguage",
+ "migrationNotice",
+ "pageSearchVectorTriggerFnSql",
+ "quietMigrationNotices"
+ ],
+ "sha256": "fd60ac122a6cc9ccc3986dad825d76b1322eaf2760689c6523198165aa4a4d22"
+ },
+ "idempotent": true,
+ "name": "page_search_vector_bounded_timeline",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 245
}
],
"versions": [
@@ -3951,7 +3979,8 @@
241,
242,
243,
- 244
+ 244,
+ 245
]
},
"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 90a3f40dbb..cf72a05e56 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -466,7 +466,7 @@
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",
- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f255236df404045eebb7bc67cda1339c5be26cf508a95bca2595c8ee8f064784"
+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"
},
"grants": {
"access_tokens": [
diff --git a/test/helpers/diverse-timeline.ts b/test/helpers/diverse-timeline.ts
new file mode 100644
index 0000000000..6c907b8f29
--- /dev/null
+++ b/test/helpers/diverse-timeline.ts
@@ -0,0 +1,66 @@
+/**
+ * Timeline text that stresses the page keyword vector: hyphenated pairs of
+ * astral or CJK code points are the densest tsvector input measured (every
+ * character lands in two lexemes, the compound and its part, at up to 4
+ * bytes each; about 7.5-7.8 lexeme-area bytes per character under Postgres
+ * 16), and distinct code points keep every lexeme unique.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PAGE_TIMELINE_FTS_MAX_CHARS } from '../../src/core/fts-language.ts';
+
+export const PREFIX_NEEDLE = 'zzprefixneedle';
+export const BEYOND_NEEDLE = 'zzbeyondneedle';
+/** Postgres's limit on a tsvector's lexeme and position area (MAXSTRPOS). */
+export const TSVECTOR_MAX_STRING_BYTES = 1_048_575;
+
+/** `count` space-separated `A-B` words of `width` consecutive code points each, from `start`. */
+export function hyphenPairs(start: number, count: number, width = 1): string {
+ const words: string[] = [];
+ let cp = start;
+ const take = () => {
+ let s = '';
+ for (let w = 0; w < width; w++) s += String.fromCodePoint(cp++);
+ return s;
+ };
+ for (let i = 0; i < count; i++) words.push(`${take()}-${take()}`);
+ return words.join(' ');
+}
+
+/** Code points `hyphenPairs(start, count, width)` consumes. */
+export const pairsSpan = (count: number, width = 1) => 2 * count * width;
+
+/**
+ * About `chars` characters: PREFIX_NEEDLE, then dense astral pairs past the
+ * indexed timeline prefix, then BEYOND_NEEDLE, then distinct ASCII tokens
+ * (an old full-timeline vector of this overflows the lexeme cap many times).
+ */
+export function diverseTimeline(chars: number): string {
+ const dense = hyphenPairs(0x20000, Math.ceil(PAGE_TIMELINE_FTS_MAX_CHARS / 10) + 100, 4);
+ const head = `- 2026-01-01 ${PREFIX_NEEDLE} ${dense}\n- 2026-01-02 ${BEYOND_NEEDLE}\n`;
+ const tokens: string[] = [];
+ let length = head.length - 1;
+ for (let i = 0; length < chars; i++) {
+ const token = `tok${i.toString(36)}`;
+ tokens.push(token);
+ length += token.length + 1;
+ }
+ return head + tokens.join(' ');
+}
+
+/** The vector's lexeme and position area in bytes (what MAXSTRPOS limits), uncompressed. */
+export async function vectorStringBytes(engine: BrainEngine, slug: string): Promise<number> {
+ const [row] = await engine.executeRaw<{ bytes: number }>(
+ `SELECT (pg_column_size(search_vector || ''::tsvector) - 8 - 4 * length(search_vector))::int AS bytes FROM pages WHERE slug = $1`,
+ [slug],
+ );
+ return Number(row!.bytes);
+}
+
+/** Whether the page vector (the title arm's document) matches `words`. */
+export async function vectorMatches(engine: BrainEngine, slug: string, words: string): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ hit: boolean }>(
+ `SELECT search_vector @@ plainto_tsquery('english', $2) AS hit FROM pages WHERE slug = $1`,
+ [slug, words],
+ );
+ return row!.hit === true;
+}
diff --git a/test/large-pages/page-timeline-tsvector-bound.test.ts b/test/large-pages/page-timeline-tsvector-bound.test.ts
new file mode 100644
index 0000000000..4b72c581ac
--- /dev/null
+++ b/test/large-pages/page-timeline-tsvector-bound.test.ts
@@ -0,0 +1,106 @@
+/**
+ * The page keyword vector indexes a bounded timeline prefix, so a page with
+ * a large diverse timeline writes instead of overflowing the tsvector cap.
+ *
+ * 1. Protects: page writes with multi-MB timelines (a diverse timeline over
+ * about 1 MB failed the whole write with "string is too long for
+ * tsvector"), and identical vectors from every writer: the trigger, the
+ * seal's pageSearchVectorSql, the reindex backfill and the v245 upgrade.
+ * 2. Fails when: either timeline cut is dropped or raised past what fits
+ * (the densest measured text, worst title included, must stay under the
+ * lexeme cap), the writers drift apart, or the upgrade misses a long
+ * page or rewrites a short one.
+ * 3. Existing coverage: test/page-search-vector-overflow.test.ts covers the
+ * compiled_truth half (#2704); test/fts-cjk-boundary.test.ts pins the
+ * trigger body against schema.sql. Postgres half:
+ * test/e2e/page-timeline-tsvector-bound-postgres.test.ts.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { MIGRATIONS } from '../../src/core/migrate.ts';
+import { backfillPageVectors } from '../../src/core/search-vector-backfill.ts';
+import { PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS, PAGE_TIMELINE_FTS_MAX_CHARS, pageSearchVectorSql } from '../../src/core/fts-language.ts';
+import { sanitizeRemoteBody } from '../../src/core/remote-body.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import {
+ BEYOND_NEEDLE,
+ diverseTimeline,
+ hyphenPairs,
+ pairsSpan,
+ PREFIX_NEEDLE,
+ TSVECTOR_MAX_STRING_BYTES,
+ vectorMatches,
+ vectorStringBytes,
+} from '../helpers/diverse-timeline.ts';
+
+let engine: PGLiteEngine;
+const TIMELINE = diverseTimeline(2_000_000);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); }, 60_000);
+beforeEach(async () => { await resetPgliteState(engine); });
+
+const vectorText = async (slug: string) =>
+ (await engine.executeRaw<{ v: string }>(`SELECT search_vector::text AS v FROM pages WHERE slug = $1`, [slug]))[0]!.v;
+
+describe('page timeline tsvector bound (PGLite)', () => {
+ test('a 2 MB diverse timeline writes; the vector holds the prefix, not text past the cut', async () => {
+ expect(TIMELINE.length).toBeGreaterThanOrEqual(2_000_000);
+ await engine.putPage('large/diverse', { type: 'note', title: 'Diverse timeline', compiled_truth: 'Body.', timeline: TIMELINE });
+ expect(await vectorStringBytes(engine, 'large/diverse')).toBeLessThan(TSVECTOR_MAX_STRING_BYTES);
+ expect(await vectorMatches(engine, 'large/diverse', PREFIX_NEEDLE)).toBe(true);
+ expect(await vectorMatches(engine, 'large/diverse', BEYOND_NEEDLE)).toBe(false);
+ }, 60_000);
+
+ test('worst title + densest timeline + densest entries stay under the lexeme cap', async () => {
+ // The title btree (idx_pages_source_title_lower, 2,704-byte rows) caps a
+ // title near 2.7 KB; 200 CJK pairs are 2,400 bytes of the densest text.
+ const title = hyphenPairs(0x4e00, 200);
+ const timeline = hyphenPairs(0x20000, Math.ceil(PAGE_TIMELINE_FTS_MAX_CHARS / 10) + 500, 4);
+ const page = await engine.putPage('large/worst', { type: 'note', title, compiled_truth: 'Body.', timeline: 'seed' });
+ let cp = 0x20000 + pairsSpan(Math.ceil(PAGE_TIMELINE_FTS_MAX_CHARS / 10) + 500, 4);
+ const entries: string[] = [];
+ for (let length = 0; length < PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS + 2_000; ) {
+ const summary = hyphenPairs(cp, 20, 4);
+ cp += pairsSpan(20, 4);
+ entries.push(summary);
+ length += summary.length;
+ }
+ for (let i = 0; i < 1_500; i++) entries.push(`carol${i.toString(36)} met acme-example`);
+ await engine.executeRaw(
+ `INSERT INTO timeline_entries (page_id, date, summary) SELECT $1, DATE '2026-01-01', s FROM unnest($2::text[]) AS s`,
+ [page.id, entries],
+ );
+ await engine.executeRaw(`UPDATE pages SET timeline = $2 WHERE slug = $1`, ['large/worst', timeline]);
+ const bytes = await vectorStringBytes(engine, 'large/worst');
+ // Near the measured worst case, and still under the cap.
+ expect(bytes).toBeGreaterThan(600_000);
+ expect(bytes).toBeLessThan(TSVECTOR_MAX_STRING_BYTES);
+ }, 60_000);
+
+ test('trigger, seal expression, reindex backfill and the v245 upgrade build the same vector', async () => {
+ await engine.putPage('large/parity', { type: 'note', title: 'Parity page', compiled_truth: 'Body.', timeline: TIMELINE });
+ await engine.putPage('large/short', { type: 'note', title: 'Short page', compiled_truth: 'Body.', timeline: '- 2026-01-01 Short entry.' });
+ const fresh = await vectorText('large/parity');
+ expect(sanitizeRemoteBody(TIMELINE)).toBe(TIMELINE);
+ const [sealed] = await engine.executeRaw<{ v: string }>(`SELECT (${pageSearchVectorSql('$1', '$2', 'english')})::text AS v`, ['Parity page', TIMELINE]);
+ expect(sealed!.v).toBe(fresh);
+
+ await engine.executeRaw(`UPDATE pages SET search_vector = to_tsvector('english', 'stale') WHERE slug LIKE 'large/%'`);
+ await backfillPageVectors(engine, { lang: 'english', checkpoint: 'test_timeline_bound_reindex' });
+ expect(await vectorText('large/parity')).toBe(fresh);
+
+ await engine.executeRaw(`UPDATE pages SET search_vector = to_tsvector('english', 'stale') WHERE slug LIKE 'large/%'`);
+ const migration = MIGRATIONS.find(m => m.name === 'page_search_vector_bounded_timeline')!;
+ expect({ sql: migration.sql, idempotent: migration.idempotent }).toEqual({ sql: '', idempotent: true });
+ await migration.handler!(engine);
+ expect(await vectorText('large/parity')).toBe(fresh);
+ expect(await vectorText('large/short')).toBe(`'stale':1`);
+ await migration.handler!(engine);
+ expect(await vectorText('large/parity')).toBe(fresh);
+ }, 120_000);
+});