Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migration): self-retrieval smoke check samples distinct pages (#5334)

time-attacka50adb0caffb
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9f6d355d8f..deecb37f75 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -32,7 +32,7 @@ src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 150
src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)
src/commands/sources.ts 2042 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts)
src/core/link-extraction.ts 2158 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note
-src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify
+src/core/embedding-migration.ts 1586 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query)
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 2fc7436fa9..c847de9216 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -891,6 +891,9 @@ export async function readMigrationStatus(engine: BrainEngine): Promise<Migratio
};
}
+const SMOKE_SAMPLE_BATCH = 25;
+const SMOKE_SAMPLE_SCAN_CHUNKS = 1000;
+
export interface VerifySearchOutcome {
status: 'pass' | 'warn' | 'skipped';
/** Content-free per-sample record — safe to stamp into the completion marker. */
@@ -924,16 +927,28 @@ export async function verifySearchRoundTrip(
AND p.text_projection_revision=p.knowledge_revision AND p.embedding_signature=$2
AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')
AND (cc.modality IS NULL OR cc.modality='text') AND ${currentSpaceChunkPredicate('embedding', 3, 4)}`;
- const rows = await engine.executeRaw<{ id: number; slug: string; page_id: number; source_id: string }>(
- `SELECT cc.id, p.slug, cc.page_id, p.source_id
- FROM content_chunks cc
- JOIN pages p ON p.id = cc.page_id
- JOIN sources s ON s.id=p.source_id
- WHERE ${eligible}
- ORDER BY cc.id DESC
- LIMIT $1`,
- [n, signature, queryModel, dims],
- );
+ // One sample per page: walk the newest eligible chunks in small
+ // index-ordered batches (bounded) to pick distinct pages; the longest
+ // eligible chunk of each page is re-read under its page lock.
+ const rows: Array<{ slug: string; page_id: number; source_id: string }> = [];
+ for (let before = '9223372036854775807', scanned = 0; rows.length < n && scanned < SMOKE_SAMPLE_SCAN_CHUNKS;) {
+ const batch = await engine.executeRaw<{ id: number; slug: string; page_id: number; source_id: string }>(
+ `SELECT cc.id, p.slug, cc.page_id, p.source_id
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ JOIN sources s ON s.id=p.source_id
+ WHERE ${eligible} AND cc.id < $5::bigint
+ ORDER BY cc.id DESC
+ LIMIT $1`,
+ [SMOKE_SAMPLE_BATCH, signature, queryModel, dims, before],
+ );
+ for (const row of batch) {
+ if (rows.length < n && !rows.some(r => Number(r.page_id) === Number(row.page_id))) rows.push(row);
+ }
+ if (batch.length < SMOKE_SAMPLE_BATCH) break;
+ scanned += batch.length;
+ before = String(batch[batch.length - 1].id);
+ }
if (rows.length === 0) {
return { status: 'skipped', samples: [], reason_code: 'no_embedded_chunks' };
}
@@ -942,12 +957,14 @@ export async function verifySearchRoundTrip(
try {
const current = await engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug }]);
- return tx.executeRaw<{ chunk_text: string }>(`SELECT cc.chunk_text FROM content_chunks cc
+ return tx.executeRaw<{ title: string | null; chunk_text: string }>(`SELECT p.title, cc.chunk_text FROM content_chunks cc
JOIN pages p ON p.id=cc.page_id JOIN sources s ON s.id=p.source_id
- WHERE cc.id=$1 AND ${eligible}`, [row.id, signature, queryModel, dims]);
+ WHERE cc.page_id=$1 AND ${eligible}
+ ORDER BY length(cc.chunk_text) DESC, cc.id DESC LIMIT 1`, [row.page_id, signature, queryModel, dims]);
});
if (!current.length) continue;
- const query = current[0].chunk_text.slice(0, 160);
+ const title = current[0].title?.trim().slice(0, 160);
+ const query = `${title ? `${title}\n` : ''}${current[0].chunk_text.slice(0, 512)}`;
const vec = await embedQuery(query);
const results = await engine.searchVector(vec, {
limit: 10,
diff --git a/test/e2e/migrate-embeddings-postgres.test.ts b/test/e2e/migrate-embeddings-postgres.test.ts
index 6edce07e39..239bd5d4b9 100644
--- a/test/e2e/migrate-embeddings-postgres.test.ts
+++ b/test/e2e/migrate-embeddings-postgres.test.ts
@@ -30,6 +30,7 @@ import {
completeEmbeddingMigration,
migrationSignature,
MIGRATION_STATE_KEY,
+ verifySearchRoundTrip,
} from '../../src/core/embedding-migration.ts';
import { runSchemaTransition } from '../../src/core/embedding-migration.ts';
import { annIndexValidity, buildDeferredAnnIndexes } from '../../src/core/embedding-ann-build.ts';
@@ -255,4 +256,35 @@ d('embedding migration (live Postgres + pgvector)', () => {
await completeEmbeddingMigration(engine, plan);
expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeFalsy();
}, 120000);
+
+ test('#5334: smoke samples are distinct pages with a bounded title-prefixed query', async () => {
+ const dims = await columnDims();
+ const model = (await engine.getConfig('embedding_model'))!;
+ const vector = `[${new Array(dims).fill(0).map((_, i) => Math.cos(i) * 0.01 + 0.002).join(',')}]`;
+ const queries: string[] = [];
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ queries.push(...values);
+ return { embeddings: values.map(() => new Array(dims).fill(0).map((_, i) => Math.cos(i) * 0.01 + 0.002)), usage: { tokens: values.length * 4 } } as never;
+ });
+ const slugs = ['smoke/page-a', 'smoke/page-b', 'smoke/page-c'];
+ for (const [page, slug] of slugs.entries()) {
+ await engine.putPage(slug, { type: 'note', title: `${slug} ${'title '.repeat(100)}`, compiled_truth: 'Migration smoke evidence.' });
+ const order = page === 2 ? [2, 1, 0, 0, 0, 0] : [0, 1, 2];
+ await installFixtureChunks(engine, slug, order.map((c, chunk_index) => ({ chunk_index, chunk_source: 'compiled_truth', token_count: 200,
+ chunk_text: `${slug} representative ${c} ${'Useful migration evidence. '.repeat((c + 1) * 20)}` })));
+ await engine.setPageEmbeddingSignature(slug, { signature: migrationSignature(model, dims) });
+ await engine.executeRaw(`UPDATE content_chunks SET embedding = $1::vector, model = $2, embedded_at = now(), embedded_text_hash = md5(chunk_text)
+ WHERE page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = 'default')`, [vector, model, slug]);
+ }
+ const ids = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug LIKE 'smoke/%' ORDER BY slug DESC`);
+ const result = await verifySearchRoundTrip(engine, { samples: 3 });
+ expect(result.samples.map(s => s.page_id)).toEqual(ids.map(r => Number(r.id)));
+ expect(queries).toHaveLength(3);
+ expect(queries.every(q => q.length <= 160 + 1 + 512)).toBe(true);
+ expect(queries.every(q => q.includes('representative 2'))).toBe(true);
+ for (const slug of slugs) expect(queries.some(q => q.startsWith(slug))).toBe(true);
+ expect(JSON.stringify(result)).not.toContain('representative');
+
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'smoke/%'`);
+ }, 60000);
});
diff --git a/test/migrate-embeddings-hardening.serial.test.ts b/test/migrate-embeddings-hardening.serial.test.ts
index ff720481d1..9bfc2af83f 100644
--- a/test/migrate-embeddings-hardening.serial.test.ts
+++ b/test/migrate-embeddings-hardening.serial.test.ts
@@ -875,6 +875,47 @@ describe('marker integrity across surfaces', () => {
});
describe('smoke-check miss + heartbeat resilience', () => {
+ test('verifySearchRoundTrip samples one representative chunk per distinct eligible page (#5334)', async () => {
+ const targetModel = 'openai:text-embedding-3-small';
+ const sig = `${targetModel}:${TO_DIMS}`;
+ const titles = ['Distinct canary 0', `Distinct canary 1${' long title'.repeat(100)}`, 'Distinct canary 2'];
+ const vector = '[' + new Array(TO_DIMS).fill(0).map((_, i) => Math.sin(i) * 0.01 + 0.001).join(',') + ']';
+ const seed = async (slug: string, title: string, chunks: string[], signature: string) => {
+ await engine.putPage(slug, { type: 'note', title, compiled_truth: `# ${title}\n\nbody` });
+ await installFixtureChunks(engine, slug, chunks.map((chunk_text, chunk_index) => ({ chunk_index, chunk_text, chunk_source: 'compiled_truth', token_count: 30 })));
+ await engine.setPageEmbeddingSignature(slug, { signature });
+ await engine.executeRaw(`UPDATE content_chunks SET embedding = $1::vector, model = $2, embedded_at = now(), embedded_text_hash = md5(chunk_text)
+ WHERE page_id = (SELECT id FROM pages WHERE slug = $3)`, [vector, targetModel, slug]);
+ };
+ const body = (page: number, chunk: number) =>
+ `${'Recommendation: review this imported evidence. '.repeat(4)}distinct page ${page} chunk ${chunk} ${'More useful context. '.repeat((chunk + 1) * 20)}`;
+ try {
+ await seed('srm-diverse-a', titles[0], [0, 1, 2].map(c => body(0, c)), sig);
+ await seed('srm-diverse-b', titles[1], [0, 1, 2].map(c => body(1, c)), sig);
+ // The newest chunks all belong to one page: the old ORDER BY chunk id
+ // sampled it three times.
+ await seed('srm-diverse-c', titles[2], [2, 1, 0, 0, 0, 0].map(c => body(2, c)), sig);
+ // A newer page in another embedding space is never a sample.
+ await seed('srm-diverse-stale', 'Stale space', [body(9, 2)], 'old:model:1536');
+
+ embeddedTexts = [];
+ const outcome = await verifySearchRoundTrip(engine, { samples: 3 });
+ const ids = Object.fromEntries((await engine.executeRaw<{ slug: string; id: number }>(
+ "SELECT slug, id FROM pages WHERE slug LIKE 'srm-diverse-%'")).map(r => [r.slug, Number(r.id)]));
+ expect(outcome.samples.map(sample => sample.page_id)).toEqual([ids['srm-diverse-c'], ids['srm-diverse-b'], ids['srm-diverse-a']]);
+ expect(embeddedTexts).toHaveLength(3);
+ for (const page of [0, 1, 2]) {
+ expect(embeddedTexts.some(text => text.startsWith(`${titles[page].slice(0, 160)}\n`) && text.includes(`distinct page ${page} chunk 2`))).toBe(true);
+ }
+ expect(embeddedTexts.every(text => text.length <= 160 + 1 + 512)).toBe(true);
+ expect(JSON.stringify(outcome)).not.toContain('distinct page');
+ } finally {
+ await engine.executeRaw(`DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE slug LIKE 'srm-diverse-%')`);
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'srm-diverse-%'`);
+ embeddedTexts = [];
+ }
+ }, 60000);
+
test('verifySearchRoundTrip reports warn/self_retrieval_miss with content-free samples', async () => {
const canary = 'sealed-privacy-canary-text';
const targetModel = 'openai:text-embedding-3-small';