Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages: contextual re-embed skips segmented pages honestly

garrytan1a9d367384f8
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index 5791a54b63..c3e6a15420 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts` and `cycle/budget-meter.ts`.
-- `src/core/contextual-retrieval-service.ts` — captures the complete originating projection before synopsis/embedding providers, then installs vectors with UPDATE-only CAS and stamps mode/generation in the same guarded transaction. Stored corpus generation participates in `page-state/projections.ts` indexing context even when the mode and canonical revision stay unchanged. New vectors receive the captured provider model; text, chunk identity, metadata and retrieval seal remain intact. Source contextual policy is rechecked before publication. Superseded preparation returns the existing retryable database result. Empty/disabled-mode stamps compare identity, seal, context and raw chunk inventory under the guard; unsealed nonempty chunks never reach a provider. `test/embedding-completion-atomic.serial.test.ts` covers real service/edit/rechunk/context interleavings and ordinary retrieval on both engines.
+- `src/core/contextual-retrieval-service.ts` — captures the complete originating projection before synopsis/embedding providers, then installs vectors with UPDATE-only CAS and stamps mode/generation in the same guarded transaction. Stored corpus generation participates in `page-state/projections.ts` indexing context even when the mode and canonical revision stay unchanged. New vectors receive the captured provider model; text, chunk identity, metadata and retrieval seal remain intact. Source contextual policy is rechecked before publication. Superseded preparation returns the existing retryable database result. Empty/disabled-mode stamps compare identity, seal, context and raw chunk inventory under the guard; unsealed nonempty chunks never reach a provider. A segmented page is skipped as `page_body_segmented` with nothing stamped, and the `contextual_reindex_per_chunk` job result names it in `skip_reason` (Wave B PR 2; per-segment synopses are PR 4; `test/large-pages/contextual-reembed-segmented.test.ts`). `test/embedding-completion-atomic.serial.test.ts` covers real service/edit/rechunk/context interleavings and ordinary retrieval on both engines.
- `src/core/embed-backfill-submit.ts` — Automatic per-source embed-backfill submitter with a true discriminated result union: `submitted` requires `jobId` plus an explicit spend-bypass payload, `cooldown` requires a reason plus a numeric remaining duration or explicit `null` for active work, `spend_capped` requires cap/spend payloads, and `no_worker_surface` requires the refused engine kind. It queries cooldown/spend state only after the shared admission classification accepts a worker-backed engine, preserving Postgres behavior while guaranteeing PGLite/unknown refusal before config, schema, or SQL access; callers handle every status exhaustively.
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index 89e4c23dd3..7f98af30a8 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -65,7 +65,7 @@ import { installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshot
import { reconcileContextualEmbeddingInputs } from './page-state/contextual-proof.ts';
import { digest } from './persistence/digest.ts';
import { isLargePageBytes } from './page-size-policy.ts';
-import { pageBodyBytes } from './page-body/page-shape.ts';
+import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';
/**
* v3 = chunks embed with optional contextual retrieval wrapper. The
@@ -228,7 +228,7 @@ export type ReembedPageResult =
}
| {
kind: 'skipped';
- reason: 'mode_none' | 'no_chunks' | 'page_missing' | 'soft_deleted' | 'budget_limited';
+ reason: 'mode_none' | 'no_chunks' | 'page_missing' | 'soft_deleted' | 'budget_limited' | 'page_body_segmented';
}
| {
kind: 'page_fallback';
@@ -310,6 +310,9 @@ export async function reembedPageWithContextualRetrieval(
if (initial.deleted_at != null) {
return { kind: 'skipped', reason: 'soft_deleted' };
}
+ // Wave B: a segmented page's vectors come from its stale chunk rows (page-body/segmented-embedding.ts); its contextual
+ // synopsis per segment is spec 8.6. Nothing is stamped: its vectors were not rebuilt under this mode.
+ if (isSegmentedPage(initial)) return { kind: 'skipped', reason: 'page_body_segmented' };
const prepared = await readProjectionSnapshot(args.engine, args.pageSlug, args.sourceId, { allowUnsealed: true });
if (!prepared) return { kind: 'skipped', reason: 'page_missing' };
diff --git a/src/core/minions/handlers/contextual-reindex-per-chunk.ts b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
index 99c36104cb..600548baf6 100644
--- a/src/core/minions/handlers/contextual-reindex-per-chunk.ts
+++ b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
@@ -129,7 +129,7 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerO
return async function contextualReindexHandler(
ctx: MinionJobContext,
- ): Promise<{ ok: true; mode_applied: string; chunks_embedded: number }> {
+ ): Promise<{ ok: true; mode_applied: string; chunks_embedded: number; skip_reason?: string }> {
const data = parseJobData(ctx.data);
// Load page row to derive the authoritative source_id (D27 P2-1).
@@ -281,7 +281,7 @@ function abortError(): Error {
function classifyResult(
pageSlug: string,
result: ReembedPageResult,
-): { ok: true; mode_applied: string; chunks_embedded: number } {
+): { ok: true; mode_applied: string; chunks_embedded: number; skip_reason?: string } {
switch (result.kind) {
case 'success':
return {
@@ -299,7 +299,7 @@ function classifyResult(
chunks_embedded: result.chunks_embedded,
};
case 'skipped':
- return { ok: true, mode_applied: 'skipped', chunks_embedded: 0 };
+ return { ok: true, mode_applied: 'skipped', chunks_embedded: 0, skip_reason: result.reason };
case 'transient_error':
// Throw so Minion retries. The queue's backoff policy handles
// rate-limit + network blips.
diff --git a/test/large-pages/contextual-reembed-segmented.test.ts b/test/large-pages/contextual-reembed-segmented.test.ts
new file mode 100644
index 0000000000..48baaf54a0
--- /dev/null
+++ b/test/large-pages/contextual-reembed-segmented.test.ts
@@ -0,0 +1,64 @@
+/**
+ * Wave B: contextual re-embed (`reembedPageWithContextualRetrieval`, the
+ * `contextual_reindex_per_chunk` handler) on a segmented page.
+ *
+ * 1. Protects: a segmented page is skipped with the reason
+ * `page_body_segmented` (its contextual synopsis per segment is spec 8.6,
+ * PR 4; its vectors come from the segmented embedding path), its mode
+ * stamp and chunk vectors are left as they are, and the handler's job
+ * result names the reason. A page that does not exist is still
+ * `page_missing`.
+ * 2. Fails when: a segmented page is reported as missing (the projection
+ * snapshot is null for it), or the skip stamps a mode its vectors were
+ * never rebuilt for.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-retrieval-service.ts';
+import { makeContextualReindexHandler } from '../../src/core/minions/handlers/contextual-reindex-per-chunk.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) await engine.disconnect();
+ await closePostgres?.();
+});
+
+test('a segmented page is skipped as page_body_segmented, its mode and vectors untouched', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await importFromContent(engine, 'notes/contextual', conversationPage(2 * 1024 * 1024, { seed: 91 }), { noEmbed: true });
+ const page = await segmentedPageRow(engine, 'notes/contextual');
+ expect(page.body_storage).toBe('segmented');
+ const state = async () => engine.executeRaw<{ mode: string | null; generation: string | null; embedded: number }>(
+ `SELECT p.contextual_retrieval_mode AS mode, p.corpus_generation AS generation,
+ (SELECT count(*)::int FROM content_chunks c WHERE c.page_id = p.id AND c.embedded_at IS NOT NULL) AS embedded FROM pages p WHERE p.id = $1`, [page.id]);
+ const before = await state();
+
+ for (const globalMode of ['title', 'per_chunk_synopsis', 'none'] as const) {
+ expect(await reembedPageWithContextualRetrieval({ engine, pageSlug: 'notes/contextual', sourceId: 'default', globalMode }))
+ .toEqual({ kind: 'skipped', reason: 'page_body_segmented' });
+ }
+ expect(await state()).toEqual(before);
+ expect(await reembedPageWithContextualRetrieval({ engine, pageSlug: 'notes/absent', sourceId: 'default', globalMode: 'title' }))
+ .toEqual({ kind: 'skipped', reason: 'page_missing' });
+
+ const [job] = await engine.executeRaw<{ id: number }>("INSERT INTO minion_jobs (name, submission_authority) VALUES ('test-contextual-segmented', '{}'::jsonb) RETURNING id");
+ const handler = makeContextualReindexHandler({ engine });
+ expect(await handler({ id: job!.id, data: { page_slug: 'notes/contextual', expected_source_id: 'default' }, signal: new AbortController().signal } as never))
+ .toEqual({ ok: true, mode_applied: 'skipped', chunks_embedded: 0, skip_reason: 'page_body_segmented' });
+ }
+}), 300_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 16a55a8e21..ff4adda669 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -64,6 +64,7 @@ test/import-revision-concurrency.test.ts
test/keyword-statement-timeout-knob-6495.test.ts
test/lane-apply-pipelining.test.ts
test/large-pages/chunk-visibility.test.ts
+test/large-pages/contextual-reembed-segmented.test.ts
test/large-pages/managed-streamed-import.test.ts
test/large-pages/managed-sync-segmented-rename.test.ts
test/large-pages/oversized-backfill-segmented.test.ts