Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(segmented synopsis): a busy page embedding lease returns a retryable result before any provider call; the install asserts the lease is still held

garrytanab4a36465ba0
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index f9c9b44c62..448d7404ac 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -70,7 +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 { acquirePageEmbeddingLease, pageEmbeddingLeaseUnavailable } from './page-embedding-lease.ts';
import { planSegmentDerivations, segmentDerivationContextHash } from './page-body/derivations.ts';
import { embeddingInputHash, synopsisDocumentHash, type EmbeddingTier } from './embedding-input-hash.ts';
import { currentEmbeddingSignature } from './embedding.ts';
@@ -504,7 +504,9 @@ export const SYNOPSIS_DERIVATION_VERSION = 1;
* (`synopsis:<model>`) first: a held page or a refused reservation leaves the title tier in place (`budget_limited`), the
* segment `partial` and the windows already installed kept. A window whose synopsis is refused, empty or malformed
* embeds at the title tier, which a synopsis page accepts (page_fallback; the segment is settled with the fallback in
- * its receipt, so it is not paid for again until its inputs change). Vectors install through installSegmentedVectors;
+ * its receipt, so it is not paid for again until its inputs change). Each segment runs under the page's embedding lease:
+ * a lease another path holds through the wait returns a retryable result before any provider call, and a lease lost
+ * before an install (assertHeld) installs nothing and returns one too. Vectors install through installSegmentedVectors;
* the page is stamped `per_chunk_synopsis` once every segment is settled.
*/
async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promise<ReembedPageResult> {
@@ -551,7 +553,8 @@ 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 });
+ await using lease = await acquirePageEmbeddingLease(engine, page.id, { signal: args.abortSignal });
+ if (lease.busy) return { kind: 'transient_error', cause: 'db', detail: pageEmbeddingLeaseUnavailable(page.id, false).message };
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)) {
@@ -585,8 +588,11 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promi
if (built.vectors.length !== todo.length || built.vectors.some(v => !v?.length || !v.every(Number.isFinite))) {
return { kind: 'transient_error', cause: 'embed', detail: 'Embedding provider returned an incomplete or invalid batch' };
}
+ let held = true;
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), expected: c.embedding_input_hash ?? null })));
+ vector: built.vectors[i]!, hash: embeddingInputHash(built.tier === 'title' ? base : provenance, built.tier, c), expected: c.embedding_input_hash ?? null })),
+ async tx => (held = await lease.assertHeld(tx).then(() => true, () => false)));
+ if (!held) return { kind: 'transient_error', cause: 'db', detail: pageEmbeddingLeaseUnavailable(page.id, true).message };
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 be0bd7a4ab..aaee712231 100644
--- a/src/core/page-body/segmented-embedding.ts
+++ b/src/core/page-body/segmented-embedding.ts
@@ -162,15 +162,15 @@ export interface SegmentedVectorUpdate { chunk_index: number; chunk_text: string
* 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. 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.
+ * the lock; throwing or returning false 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> {
+ vectors: readonly SegmentedVectorUpdate[], beforeInstall?: (tx: BrainEngine) => Promise<void | boolean>): 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, expected: v.expected }));
const col = quoteIdentifier(target.column.name);
return engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
- await beforeInstall?.(tx);
+ if (await beforeInstall?.(tx) === false) return 0;
const current = await readSegmentedEmbedPage(tx, { id: page.id });
const now = await embeddingWriteTarget(tx);
if (!current || current.slug !== page.slug || current.title !== page.title
diff --git a/test/helpers/synopsis-segment-hash-cases.ts b/test/helpers/synopsis-segment-hash-cases.ts
index c5999cdef2..8dc56e3d5f 100644
--- a/test/helpers/synopsis-segment-hash-cases.ts
+++ b/test/helpers/synopsis-segment-hash-cases.ts
@@ -31,7 +31,7 @@ import { reservationCostUsd } from '../../src/core/budget/reservation-cost.ts';
import { chunkGenerationFilter } from '../../src/core/search/safe-chunks.ts';
import { __setChatTransportForTests, __setEmbedTransportForTests, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';
import { embedStalePages } from '../../src/core/embed-stale.ts';
-import { pageEmbeddingLeaseProbe } from '../../src/core/page-embedding-lease.ts';
+import { acquirePageEmbeddingLease, pageEmbeddingLeaseId, 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';
import { needlePage, needlePageBody, sealAtOldChunker } from './rechunk-segmented-cases.ts';
@@ -274,6 +274,62 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBra
expect(calls.length).toBe(0);
}, 300_000);
+ test('lease busy: with the page lease held elsewhere through the wait, the pass makes no provider call and returns a retryable result; once released it runs', async () => {
+ const brain = opts.getBrain();
+ await roomyCap();
+ const slug = 'notes/synopsis-lease-busy';
+ await brain.seed(slug, page(days(1_300_000).body + '\nLease busy fixture.\n'));
+ const { id } = await pageRow(slug);
+ const all = await chunks(slug);
+ let contentions = 0;
+ pageEmbeddingLeaseProbe.contended = () => { contentions++; };
+ pageEmbeddingLeaseProbe.waitBoundMs = 300;
+ reset();
+ try {
+ await using held = await acquirePageEmbeddingLease(brain.engine, id);
+ expect(held.busy).toBe(false);
+ const result = await run(slug);
+ expect(result).toMatchObject({ kind: 'transient_error', cause: 'db' });
+ expect(result.kind === 'transient_error' ? result.detail : '').toContain('Another path is embedding this page');
+ } finally {
+ pageEmbeddingLeaseProbe.contended = undefined;
+ pageEmbeddingLeaseProbe.waitBoundMs = undefined;
+ }
+ expect(contentions).toBeGreaterThan(0);
+ expect({ calls: calls.length, embedded: brain.embedded.length }).toEqual({ calls: 0, embedded: 0 });
+ expect((await chunks(slug)).every(c => c.vector === null)).toBe(true);
+ expect(await synopsisRows(id)).toEqual([]);
+ reset();
+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: all.length });
+ expect(calls.length).toBe(nonCode(all).length);
+ }, 300_000);
+
+ test('lease lost: a pass whose lease another path took over before the install installs nothing and returns a retryable result', async () => {
+ const brain = opts.getBrain();
+ await roomyCap();
+ const slug = 'notes/synopsis-lease-lost';
+ await brain.seed(slug, page(days(1_300_000).body + '\nLease lost fixture.\n'));
+ const { id } = await pageRow(slug);
+ const all = await chunks(slug);
+ reset();
+ onSynopsis = async () => {
+ onSynopsis = null;
+ expect((await brain.engine.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token = $2::uuid WHERE id = $1 RETURNING id',
+ [pageEmbeddingLeaseId(id), randomUUID()])).length).toBe(1);
+ };
+ const result = await run(slug);
+ expect(result).toMatchObject({ kind: 'transient_error', cause: 'db' });
+ expect(result.kind === 'transient_error' ? result.detail : '').toContain('lease was lost');
+ expect(calls.length).toBeGreaterThan(0);
+ expect(brain.embedded.length).toBe(calls.length);
+ expect((await chunks(slug)).every(c => c.vector === null)).toBe(true);
+ expect(await synopsisRows(id)).toEqual([]);
+ await brain.engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id = $1', [pageEmbeddingLeaseId(id)]);
+ reset();
+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: all.length });
+ expect(calls.length).toBe(nonCode(all).length);
+ }, 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();