Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(segmented synopsis): hold the page embedding lease from segment read through install; installs compare-and-set on the recorded input as read

garrytan8af72ae564a9
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index d1d5a02369..7364a8df7f 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -70,6 +70,7 @@ import { digest, sha256 } from './persistence/digest.ts';
import { isLargePageBytes } from './page-size-policy.ts';
import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';
import { installSegmentedVectors, listLiveEmbedSegments, listSegmentChunkRows, readSegmentedEmbedPage } from './page-body/segmented-embedding.ts';
+import { acquirePageEmbeddingLease } from './page-embedding-lease.ts';
import { planSegmentDerivations, segmentDerivationContextHash } from './page-body/derivations.ts';
import { SEGMENTED_CHUNKER_VERSION } from './page-body/segment-chunks.ts';
import { embeddingInputHash, synopsisDocumentHash, type EmbeddingTier } from './embedding-input-hash.ts';
@@ -550,6 +551,7 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promi
let embedded = 0;
let fallbackKind: SynopsisFailureKind | null = null;
for (const segment of plan.todo) {
+ await using _lease = await acquirePageEmbeddingLease(engine, page.id, { signal: args.abortSignal });
const anchors: Array<{ first_chunk: number; last_chunk: number; chunks: number; document_sha256: string; tier: EmbeddingTier }> = [];
let segmentFallback: SynopsisFailureKind | null = null;
for (const window of segmentSynopsisWindows(await listSegmentChunkRows(engine, page.id, segment.occurrenceId), lead)) {
@@ -584,7 +586,7 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promi
return { kind: 'transient_error', cause: 'embed', detail: 'Embedding provider returned an incomplete or invalid batch' };
}
const installed = await installSegmentedVectors(engine, page, target, todo.map((c, i) => ({ chunk_index: c.chunk_index, chunk_text: c.chunk_text,
- vector: built.vectors[i]!, hash: embeddingInputHash(built.tier === 'title' ? base : provenance, built.tier, c) })));
+ vector: built.vectors[i]!, hash: embeddingInputHash(built.tier === 'title' ? base : provenance, built.tier, c), expected: c.embedding_input_hash ?? null })));
if (installed < todo.length) return superseded;
embedded += installed;
if (built.fallback) segmentFallback ??= built.fallback;
diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.ts
index ab872a8498..bf23588ad0 100644
--- a/src/core/page-body/segmented-embedding.ts
+++ b/src/core/page-body/segmented-embedding.ts
@@ -127,6 +127,7 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb
const missing = opts.includeEmbedded ? null : await vectorlessChunkIndexes(engine, page.id, target.column.name);
const rows = missing ? listed.filter(row => missing.has(row.chunk_index)) : listed;
if (rows.length === 0) return { pending: 0, installed: 0 };
+ const asRead = await readChunkInputHashes(engine, page.id, rows.map(row => row.chunk_index));
const metered = await meterPageBatch(engine, page, rows, { signature: opts.signature ?? null, approvedCapUsd: opts.approvedCapUsd });
if (!metered) return null;
const chunks = metered.chunks;
@@ -137,21 +138,33 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb
const tier = plainEmbeddingTier(page.contextual_retrieval_mode);
const provenance = embeddingInputContext(target, page.title, null, []);
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) };
+ chunk_text: chunk.chunk_text, vector: vectors[i]!, hash: embeddingInputHash(provenance, tier, chunk), expected: asRead.get(chunk.chunk_index) ?? null })), opts.beforeInstall) };
}
-/** One vector to install on a segmented page: the row's chunk_index and exact text, and the recorded embedding input. */
-export interface SegmentedVectorUpdate { chunk_index: number; chunk_text: string; vector: Float32Array; hash: string }
+/** The recorded embedding input of a segmented page's live rows at `chunkIndexes`, as read now (null: none recorded). */
+async function readChunkInputHashes(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, chunkIndexes: readonly number[]): Promise<Map<number, string | null>> {
+ const rows = await engine.executeRaw<{ chunk_index: number; embedding_input_hash: string | null }>(
+ `SELECT cc.chunk_index, cc.embedding_input_hash FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE cc.page_id = $1 AND cc.chunk_index = ANY($2::int[]) AND ${chunkGenerationFilter('p', 'cc')}`, [pageId, [...chunkIndexes]]);
+ return new Map(rows.map(row => [Number(row.chunk_index), row.embedding_input_hash]));
+}
+
+/**
+ * One vector to install on a segmented page: the row's chunk_index and exact text, the recorded embedding input, and
+ * `expected`, the row's recorded input as the writer read it before building the vector (null: none).
+ */
+export interface SegmentedVectorUpdate { chunk_index: number; chunk_text: string; vector: Float32Array; hash: string; expected: string | null }
/**
* Install vectors with their recorded inputs on the live rows of a segmented page with the same chunk_index and text,
* under the page lock, while the page's slug, title and contextual mode and the write target (column, provenance
- * model) are those the inputs were built under; 0 when any moved. `beforeInstall` runs after the lock; throwing
- * installs nothing. Returns the rows that took a vector.
+ * model) are those the inputs were built under; 0 when any moved. A row whose recorded input is no longer `expected`
+ * (another writer installed since the read) is left as it is: a stale install is a no-op. `beforeInstall` runs after
+ * the lock; throwing installs nothing. Returns the rows that took a vector.
*/
export async function installSegmentedVectors(engine: BrainEngine, page: SegmentedEmbedPage, target: Awaited<ReturnType<typeof embeddingWriteTarget>>,
vectors: readonly SegmentedVectorUpdate[], beforeInstall?: (tx: BrainEngine) => Promise<void>): Promise<number> {
- const updates = vectors.map(v => ({ chunk_index: v.chunk_index, chunk_text: v.chunk_text, embedding: `[${Array.from(v.vector).join(',')}]`, hash: v.hash }));
+ const updates = vectors.map(v => ({ chunk_index: v.chunk_index, chunk_text: v.chunk_text, embedding: `[${Array.from(v.vector).join(',')}]`, hash: v.hash, expected: v.expected }));
const col = quoteIdentifier(target.column.name);
return engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
@@ -166,9 +179,9 @@ export async function installSegmentedVectors(engine: BrainEngine, page: Segment
installed += (await tx.executeRaw(`UPDATE content_chunks cc SET ${col} = v.embedding${vectorCastSuffix(target.column)},
embedding_input_hash = v.hash, embedded_at = now(), embedded_text_hash = md5(cc.chunk_text), model = COALESCE($3, cc.model),
embedding_pending_since = NULL
- FROM jsonb_to_recordset($2::text::jsonb) AS v(chunk_index int, chunk_text text, embedding text, hash text), pages p
+ FROM jsonb_to_recordset($2::text::jsonb) AS v(chunk_index int, chunk_text text, embedding text, hash text, expected text), pages p
WHERE cc.page_id = $1 AND p.id = cc.page_id AND cc.chunk_index = v.chunk_index AND cc.chunk_text = v.chunk_text
- AND ${chunkGenerationFilter('p', 'cc')}
+ AND cc.embedding_input_hash IS NOT DISTINCT FROM v.expected AND ${chunkGenerationFilter('p', 'cc')}
RETURNING cc.id`, [page.id, batch, target.model])).length;
}
return installed;
diff --git a/test/helpers/synopsis-segment-hash-cases.ts b/test/helpers/synopsis-segment-hash-cases.ts
index aa74887add..30736ccbe1 100644
--- a/test/helpers/synopsis-segment-hash-cases.ts
+++ b/test/helpers/synopsis-segment-hash-cases.ts
@@ -27,6 +27,9 @@ import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page
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 { embedStalePages } from '../../src/core/embed-stale.ts';
+import { pageEmbeddingLeaseProbe } from '../../src/core/page-embedding-lease.ts';
+import { installSegmentedVectors, readSegmentedEmbedPage } from '../../src/core/page-body/segmented-embedding.ts';
import type { AppendBrain } from './append-brain.ts';
const WORDS = ['launch', 'pricing', 'roadmap', 'hiring', 'metrics', 'retention', 'design', 'latency', 'budget', 'customer'];
@@ -52,8 +55,10 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBra
const calls: GeneratePerChunkSynopsisArgs[] = [];
let segmentReads = 0;
let refuse: ((args: GeneratePerChunkSynopsisArgs) => boolean) | null = null;
+ let onSynopsis: ((args: GeneratePerChunkSynopsisArgs) => Promise<void>) | null = null;
const generateSynopsis = async (args: GeneratePerChunkSynopsisArgs): Promise<GeneratePerChunkSynopsisResult> => {
calls.push(args);
+ await onSynopsis?.(args);
if (refuse?.(args)) return { kind: 'refusal', detail: 'fixture refusal' };
return { kind: 'success', synopsis: `Synopsis of chunk ${args.chunkIndex}.` };
};
@@ -211,6 +216,80 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBra
expect(calls.length).toBe(0);
}, 300_000);
+ const unitVectors = async (n: number) => {
+ const dims = (await embeddingWriteTarget(opts.getBrain().engine)).column.dimensions;
+ return Array.from({ length: n }, () => Float32Array.from({ length: dims }, (_, j) => (j === 1 ? 1 : 0)));
+ };
+
+ test('race: a title-tier embed in flight on a stamped page with new rows when the synopsis pass starts installs first; the pass waits for the page lease and its install wins', async () => {
+ const brain = opts.getBrain();
+ await roomyCap();
+ const slug = 'notes/synopsis-race-lease';
+ const { body, count } = days(1_300_000);
+ await brain.seed(slug, page(body));
+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis' });
+ const stamped = await pageRow(slug);
+ // The state an append leaves (the page stays stamped per_chunk_synopsis, the new rows have no vector), written
+ // locally so no post-write embedding effect races the fixture.
+ await brain.seed(slug, page(body + day(count + 1)));
+ await brain.engine.executeRaw('UPDATE pages SET contextual_retrieval_mode = $2, corpus_generation = $3 WHERE id = $1', [stamped.id, stamped.mode, stamped.generation]);
+ const pending = (await chunks(slug)).filter(c => c.vector === null);
+ expect(pending.length).toBeGreaterThan(0);
+ reset();
+ let pass: Promise<unknown> | null = null;
+ let contended!: () => void;
+ const waited = new Promise<void>(resolve => { contended = resolve; });
+ pageEmbeddingLeaseProbe.contended = () => contended();
+ let titleTexts = 0;
+ try {
+ const titled = await embedStalePages(brain.engine, [slug], 'default', { embedFn: async texts => {
+ titleTexts += texts.length;
+ if (!pass) { pass = run(slug); await Promise.race([pass, waited]); }
+ return unitVectors(texts.length);
+ } });
+ expect(titled.embedded).toBe(pending.length);
+ expect(await pass).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: pending.length });
+ } finally {
+ pageEmbeddingLeaseProbe.contended = undefined;
+ }
+ expect({ titleTexts, calls: calls.length, synopsisEmbeds: brain.embedded.length })
+ .toEqual({ titleTexts: pending.length, calls: nonCode(pending).length, synopsisEmbeds: pending.length });
+ const after = await chunks(slug);
+ for (const c of after) expect(c.embedding_input_hash).not.toBe(await titleHash(c));
+ expect(after.every(c => c.vector !== null)).toBe(true);
+ reset();
+ expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: 0 });
+ expect(calls.length).toBe(0);
+ }, 300_000);
+
+ test('race: a row another writer installed after the synopsis pass read it keeps that install; the stale synopsis install is a no-op and the retry pays for that row and the windows not reached', async () => {
+ const brain = opts.getBrain();
+ await roomyCap();
+ const slug = 'notes/synopsis-race-cas';
+ await brain.seed(slug, page(days(1_300_000).body));
+ const all = await chunks(slug);
+ const target = all.filter(c => c.chunk_source !== 'fenced_code')[Math.floor(all.length / 2)]!;
+ const engine = brain.engine;
+ reset();
+ onSynopsis = async args => {
+ if (args.chunkIndex !== target.chunk_index) return;
+ onSynopsis = null;
+ const seg = (await readSegmentedEmbedPage(engine, { sourceId: 'default', slug }))!;
+ expect(await installSegmentedVectors(engine, seg, await embeddingWriteTarget(engine), [{ chunk_index: target.chunk_index, chunk_text: target.chunk_text,
+ vector: (await unitVectors(1))[0]!, hash: await titleHash(target), expected: null }])).toBe(1);
+ };
+ expect(await run(slug)).toMatchObject({ kind: 'transient_error', cause: 'db' });
+ const halted = await chunks(slug);
+ expect(halted.find(c => c.chunk_index === target.chunk_index)!.embedding_input_hash).toBe(await titleHash(target));
+ const unreached = halted.filter(c => c.vector === null);
+ reset();
+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: unreached.length + 1 });
+ expect(calls.map(call => call.chunkIndex).sort((a, b) => a - b)).toEqual([target, ...nonCode(unreached)].map(c => c.chunk_index).sort((a, b) => a - b));
+ const after = await chunks(slug);
+ for (const c of after) expect(c.embedding_input_hash).not.toBe(await titleHash(c));
+ expect(after.every(c => c.vector !== null)).toBe(true);
+ }, 300_000);
+
test('an inline page keeps the synopsisBodyHash input', async () => {
const brain = opts.getBrain();
const slug = 'notes/synopsis-inline';