Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(large-pages): carry synopsis vectors of unchanged windows across a segment rewrite (Wave B PR 4 lane 4c)
garrytanc25f6a67b552
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex cb11efdd7c..d1d5a02369 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -53,7 +53,6 @@ import {DEFAULT_SYNOPSIS_MODEL,estimateSynopsisCallUsd,generatePerChunkSynopsis,- SEGMENT_SYNOPSIS_LEAD_BYTES,segmentSynopsisWindows,SYNOPSIS_MAX_TOKENS,SYNOPSIS_PROMPT_VERSION,@@ -76,8 +75,7 @@ import { SEGMENTED_CHUNKER_VERSION } from './page-body/segment-chunks.ts';import { embeddingInputHash, synopsisDocumentHash, type EmbeddingTier } from './embedding-input-hash.ts';import { currentEmbeddingSignature } from './embedding.ts';import { estimatePageEmbedUsd, reservePageSpend, spendGrant } from './page-embedding-budget.ts';-import { overlaidBoundedPrefix, pageLeadSource } from './page-window/bounded-lead.ts';-import { boundedProjectedPrefix } from './page-window/document.ts';+import { segmentSynopsisLead } from './page-body/segment-synopsis.ts';/*** v3 = chunks embed with optional contextual retrieval wrapper. The@@ -537,8 +535,7 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promiconst base = embeddingInputContext(target, page.title, corpusGeneration, []);const titlePrefix = buildContextualPrefix(page.title, null);const embedSignature = currentEmbeddingSignature();- const lead = boundedProjectedPrefix(await overlaidBoundedPrefix(engine,- { slug: page.slug, source_id: page.source_id, compiled_truth: await pageLeadSource(engine, initial) }), SEGMENT_SYNOPSIS_LEAD_BYTES);+ const lead = await segmentSynopsisLead(engine, page);const inputs = { title: page.title, lead_sha256: sha256(lead), synopsis_model: synopsisModel, synopsis_max_tokens: synopsisMaxTokens ?? SYNOPSIS_MAX_TOKENS,chunker_version: SEGMENTED_CHUNKER_VERSION, corpus_generation: corpusGeneration,embedding: { column: target.column.name, model: target.provenanceModel, dimensions: target.column.dimensions } };diff --git a/src/core/import-chunk-reuse.ts b/src/core/import-chunk-reuse.tsindex 4e87688b79..525b074fab 100644--- a/src/core/import-chunk-reuse.ts+++ b/src/core/import-chunk-reuse.ts@@ -12,6 +12,7 @@ import type { SegmentChunkInput } from './page-body/types.ts';import { quoteIdentifier } from './search/embedding-column.ts';import { chunkGenerationFilter } from './search/safe-chunks.ts';import { parseEmbedding } from './utils.ts';+import { segmentSynopsisInputHashes, segmentSynopsisLead } from './page-body/segment-synopsis.ts';/*** A13 reuse for one page import: copies each stored vector the reuse gate@@ -80,9 +81,10 @@ export async function reuseStoredChunkVectors(* the occurrences the write retires (never the whole page): one statement* reads those rows with their vectors, the same gate as* `reuseStoredChunkVectors` admits each (recorded input hash for the write's- * tier, nothing from a page stored under per-chunk synopsis), and each admitted- * vector is copied, with its recorded input, onto the new chunk with the same- * source and text (`chunk_source\0chunk_text`, FIFO for duplicates). So an+ * tier), and each admitted vector is copied, with its recorded input, onto the+ * new chunk with the same source and text (`chunk_source\0chunk_text`, FIFO for+ * duplicates); on a page stored under per-chunk synopsis, onto the new chunk+ * whose synopsis input hashes to the recorded one (its window is unchanged). So an* unchanged chunk inside a rewritten tail keeps its vector and only new text* reaches the provider. Returns how many chunks got one.*/@@ -93,17 +95,26 @@ export async function reuseSegmentChunkVectors(exec: BrainEngine, { pageId, reticonst provenance = embeddingInputContext(target, title, corpusGeneration, []);const col = quoteIdentifier(target.column.name);const rows = await exec.executeRaw<{ chunk_text: string; chunk_source: string; embedding: unknown; token_count: number | null; model: string | null;- embedding_input_hash: string | null; contextual_retrieval_mode: string | null }>(- `SELECT c.chunk_text, c.chunk_source, c.${col} AS embedding, c.token_count, c.model, c.embedding_input_hash, p.contextual_retrieval_mode+ embedding_input_hash: string | null; contextual_retrieval_mode: string | null; slug: string; source_id: string; corpus_generation: string | null }>(+ `SELECT c.chunk_text, c.chunk_source, c.${col} AS embedding, c.token_count, c.model, c.embedding_input_hash, p.contextual_retrieval_mode,+ p.slug, p.source_id, p.corpus_generationFROM content_chunks c JOIN pages p ON p.id = c.page_idWHERE c.page_id = $1 AND c.occurrence_id = ANY($2::bigint[]) AND c.${col} IS NOT NULL AND ${chunkGenerationFilter('p', 'c')}ORDER BY c.chunk_index`, [pageId, [...retiredOccurrences]]);const mode = rows[0]?.contextual_retrieval_mode ?? null;- if (rows.length === 0 || (mode && modeRequiresSynopsis(mode as CRMode))) return 0;+ if (rows.length === 0) return 0;+ // Wave B spec 8.6: on a page stored under per-chunk synopsis, a vector carries over only onto a new chunk whose+ // synopsis input (its segment window over the page lead) hashes to the stored row's recorded input.+ const synopsis = mode && modeRequiresSynopsis(mode as CRMode)+ ? segmentSynopsisInputHashes(embeddingInputContext(target, title, rows[0]!.corpus_generation, []),+ await segmentSynopsisLead(exec, { id: pageId, slug: rows[0]!.slug, source_id: rows[0]!.source_id }), chunks)+ : null;const stored = rows.map(row => ({ chunk_text: row.chunk_text, chunk_source: row.chunk_source, embedding: parseEmbedding(row.embedding),token_count: row.token_count, model: row.model, embedding_input_hash: row.embedding_input_hash }))- .filter(chunk => canReuseMarkdownVector(chunk.embedding_input_hash, mode, tier, provenance, chunk));- const { reuse } = planEmbeddingReuse(stored, chunks, c => `${c.chunk_source}\0${c.chunk_text}`);+ .filter(chunk => synopsis ? chunk.embedding_input_hash !== null : canReuseMarkdownVector(chunk.embedding_input_hash, mode, tier, provenance, chunk));+ const { reuse } = planEmbeddingReuse(stored, chunks, synopsis+ ? c => synopsis.get(c as SegmentChunkInput) ?? (c as { embedding_input_hash?: string | null }).embedding_input_hash ?? ''+ : c => `${c.chunk_source}\0${c.chunk_text}`);for (const [i, matched] of reuse) {const row = matched as typeof stored[number];chunks[i]!.embedding = row.embedding as Float32Array;diff --git a/src/core/page-body/segment-synopsis.ts b/src/core/page-body/segment-synopsis.tsnew file mode 100644index 0000000000..ea3a21412b--- /dev/null+++ b/src/core/page-body/segment-synopsis.ts@@ -0,0 +1,41 @@+/**+ * Contextual synopsis per segment (wave-b spec 8.6): the synopsis input of a segmented page's chunks, shared by the+ * synopsis pass (contextual-retrieval-service.ts) and the staging vector reuse (import-chunk-reuse.ts). A chunk's+ * synopsis document is the page's projected lead (its first SEGMENT_SYNOPSIS_LEAD_BYTES) and the window of its own+ * segment that holds it (segmentSynopsisWindows), so its recorded input depends on that segment and the lead alone.+ */+import type { BrainEngine } from '../engine.ts';+import { embeddingInputHash, synopsisDocumentHash, type EmbeddingInputContext } from '../embedding-input-hash.ts';+import { SEGMENT_SYNOPSIS_LEAD_BYTES, segmentSynopsisWindows } from '../page-summary.ts';+import { overlaidBoundedPrefix, pageLeadSource } from '../page-window/bounded-lead.ts';+import { boundedProjectedPrefix } from '../page-window/document.ts';++/** The lead a segmented page's synopsis documents open with: its stored truth_lead after the withdrawal overlay, sanitized and cut. */+export async function segmentSynopsisLead(engine: BrainEngine, page: { id: number; slug: string; source_id: string }): Promise<string> {+ const truthLead = await pageLeadSource(engine, { id: page.id, body_storage: 'segmented', compiled_truth: '' });+ return boundedProjectedPrefix(await overlaidBoundedPrefix(engine, { slug: page.slug, source_id: page.source_id, compiled_truth: truthLead }), SEGMENT_SYNOPSIS_LEAD_BYTES);+}++type SegmentChunk = { chunk_text: string; chunk_source?: string | null; occurrence_id?: number | null };++/**+ * The per_chunk_synopsis input hash each chunk would record, for chunks given segment by segment in text order (every+ * chunk of a segment, as the segment chunker emits them): each segment's chunks are windowed over `lead` and hashed+ * under `base` with their window document. Image chunks get none.+ */+export function segmentSynopsisInputHashes<C extends SegmentChunk>(base: EmbeddingInputContext, lead: string, chunks: readonly C[]): Map<C, string> {+ const hashes = new Map<C, string>();+ const segments = new Map<number | null, C[]>();+ for (const chunk of chunks) {+ const key = chunk.occurrence_id ?? null;+ const list = segments.get(key);+ if (list) list.push(chunk); else segments.set(key, [chunk]);+ }+ for (const segment of segments.values()) {+ for (const window of segmentSynopsisWindows(segment, lead)) {+ const provenance = { ...base, bodyHash: synopsisDocumentHash(window.document) };+ for (const chunk of window.chunks) hashes.set(chunk, embeddingInputHash(provenance, 'per_chunk_synopsis', chunk));+ }+ }+ return hashes;+}diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.tsindex 300eddb502..ab872a8498 100644--- a/src/core/page-body/segmented-embedding.ts+++ b/src/core/page-body/segmented-embedding.ts@@ -136,8 +136,8 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb}const tier = plainEmbeddingTier(page.contextual_retrieval_mode);const provenance = embeddingInputContext(target, page.title, null, []);- return installSegmentedVectors(engine, page, target, chunks.map((chunk, i) => ({ chunk_index: chunk.chunk_index, chunk_text: chunk.chunk_text,- vector: vectors[i]!, hash: embeddingInputHash(provenance, tier, chunk) })), opts.beforeInstall);+ return { pending: rows.length, installed: await installSegmentedVectors(engine, page, target, chunks.map((chunk, i) => ({ chunk_index: chunk.chunk_index,+ chunk_text: chunk.chunk_text, vector: vectors[i]!, hash: embeddingInputHash(provenance, tier, chunk) })), opts.beforeInstall) };}/** One vector to install on a segmented page: the row's chunk_index and exact text, and the recorded embedding input. */@@ -160,7 +160,7 @@ export async function installSegmentedVectors(engine: BrainEngine, page: Segmentconst now = await embeddingWriteTarget(tx);if (!current || current.slug !== page.slug || current.title !== page.title|| current.contextual_retrieval_mode !== page.contextual_retrieval_mode- || now.column.name !== target.column.name || now.provenanceModel !== target.provenanceModel) return { pending: rows.length, installed: 0 };+ || now.column.name !== target.column.name || now.provenanceModel !== target.provenanceModel) return 0;let installed = 0;for (const batch of jsonRowBatches(updates, update => update)) {installed += (await tx.executeRaw(`UPDATE content_chunks cc SET ${col} = v.embedding${vectorCastSuffix(target.column)},@@ -171,7 +171,7 @@ export async function installSegmentedVectors(engine: BrainEngine, page: SegmentAND ${chunkGenerationFilter('p', 'cc')}RETURNING cc.id`, [page.id, batch, target.model])).length;}- return { pending: rows.length, installed };+ return installed;});}diff --git a/test/helpers/synopsis-segment-hash-cases.ts b/test/helpers/synopsis-segment-hash-cases.tsindex bb9ef742c6..aa74887add 100644--- a/test/helpers/synopsis-segment-hash-cases.ts+++ b/test/helpers/synopsis-segment-hash-cases.ts@@ -7,21 +7,24 @@* 1. Protects: under per_chunk_synopsis a segmented page leaves the title tier: every live chunk gets a synopsis vector* whose document is the title, the projected lead and one window of its own segment (within SYNOPSIS_DOC_MAX_CHARS),* one synopsis derivation row per live occurrence. A rerun calls nothing and reads no chunk row. An append (by a- * remote writer) re-synopsizes only the chunks of its new segments: calls and segment reads equal those, and every- * other chunk keeps its embedding_input_hash and vector. An exhausted per-page cap leaves the page on the title tier+ * remote writer) re-synopsizes only the chunks of the windows it changed: the rewritten tail segment's unchanged+ * windows carry their synopsis vectors onto the new rows at staging, so calls equal the changed windows' chunks, one+ * segment is read, and every other chunk keeps its embedding_input_hash and vector. An exhausted per-page cap leaves the page on the title tier* with no synopsis call; with room, the same page takes the synopsis tier. A refused synopsis embeds its window at* the title tier and settles. An inline page keeps the synopsisBodyHash input.* 2. Fails when: a segmented page never leaves the title tier (the pre-lane skip), the synopsis input is hashed over every- * chunk of the page (an append changes every chunk's input), a settled segment is read or paid for again, or a refused+ * chunk of the page (an append changes every chunk's input), the rewritten tail is re-synopsized whole (staging drops+ * the synopsis vectors of its unchanged windows), a settled segment is read or paid for again, or a refused* reservation still calls the model.*/import { expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../../src/core/engine.ts';import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-retrieval-service.ts';-import { SYNOPSIS_DOC_MAX_CHARS, type GeneratePerChunkSynopsisArgs, type GeneratePerChunkSynopsisResult } from '../../src/core/page-summary.ts';+import { SYNOPSIS_DOC_MAX_CHARS, segmentSynopsisWindows, type GeneratePerChunkSynopsisArgs, type GeneratePerChunkSynopsisResult } from '../../src/core/page-summary.ts';import { embeddingInputHash } from '../../src/core/embedding-input-hash.ts';import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page-state/projections.ts';+import { segmentSynopsisLead } from '../../src/core/page-body/segment-synopsis.ts';import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';import { chunkGenerationFilter } from '../../src/core/search/safe-chunks.ts';import type { AppendBrain } from './append-brain.ts';@@ -78,7 +81,7 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBra/** The cap is set high enough for a whole 2.3 MB page at the upper-bound estimate (uncached prompts at list price). */const roomyCap = () => opts.getBrain().engine.setConfig(PAGE_EMBED_CAP_KEY, '1000');- test('append invalidation: a segmented page leaves the title tier, a rerun does no work, an append pays only for its new segments', async () => {+ test('append invalidation: a segmented page leaves the title tier, a rerun does no work, an append pays only for the windows it changed', async () => {const brain = opts.getBrain();await roomyCap();const slug = 'notes/synopsis-log';@@ -126,11 +129,32 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraexpect(c.embedding_input_hash).toBe(kept.get(c.chunk_index)!.embedding_input_hash);expect(c.vector).toBe(kept.get(c.chunk_index)!.vector);}+ // The changed windows, from the window documents alone: a fresh chunk whose (document, text) no retired window had.+ const lead = await segmentSynopsisLead(brain.engine, { id: seeded.id, slug, source_id: 'default' });+ const retired = done.filter(c => !after.some(a => a.occurrence_id === c.occurrence_id));+ const oldInputs = new Map<string, ChunkRow>();+ for (const w of segmentSynopsisWindows(retired, lead)) for (const c of w.chunks) oldInputs.set(`${w.document}\0${c.chunk_text}`, c);+ const changed: number[] = [];+ const carried: Array<[ChunkRow, ChunkRow]> = [];+ for (const w of segmentSynopsisWindows(fresh, lead)) {+ for (const c of w.chunks) {+ const old = oldInputs.get(`${w.document}\0${c.chunk_text}`);+ if (old) carried.push([c, old]); else if (c.chunk_source !== 'fenced_code') changed.push(c.chunk_index);+ }+ }+ expect(changed.length).toBeGreaterThan(0);+ expect(changed.length).toBeLessThan(fresh.length / 2);+ expect(carried.length).toBe(fresh.length - changed.length);+ for (const [c, old] of carried) {+ expect(c.embedding_input_hash).toBe(old.embedding_input_hash);+ expect(c.vector).toBe(old.vector);+ }reset();- expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: fresh.length });- expect(calls.map(call => call.chunkIndex).sort((a, b) => a - b)).toEqual(nonCode(fresh).map(c => c.chunk_index));+ expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: changed.length });+ expect(calls.map(call => call.chunkIndex).sort((a, b) => a - b)).toEqual(changed);expect(segmentReads).toBe(freshOccurrences.size);+ for (const [c] of carried) expect((await chunks(slug)).find(row => row.chunk_index === c.chunk_index)!.embedding_input_hash).toBe(c.embedding_input_hash);expect(calls.some(call => call.documentText.includes(`## Day ${count + 1}`))).toBe(true);const settled = await synopsisRows(seeded.id);expect(new Set(settled.map(r => r.occurrenceId))).toEqual(new Set(after.map(c => c.occurrence_id!)));