Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B review fixes: segmented embedding paths
garrytan82f7a4f081ee
diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 9811088b4b..00b79660f7 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -51,7 +51,7 @@ export { resolveEmbedConcurrency, _resetEmbedConcurrencyClampWarningForTest } frimport { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';import { heldEmbedArgv, meterPageBatch, spendGrant } from '../core/page-embedding-budget.ts';-import { countSegmentedEmbedRows, embedSegmentedPage, readSegmentedEmbedPage, type SegmentedEmbedPage } from '../core/page-body/segmented-embedding.ts';+import { countSegmentedEmbedRows, embedSegmentedPage, readSealedSegmentedEmbedPage, readSegmentedEmbedPage, type SegmentedEmbedPage } from '../core/page-body/segmented-embedding.ts';import {restampIfDemotedToTitleTier,embedBatchWithBackoff,@@ -1066,22 +1066,22 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf}/**- * Wave B: embed a segmented page's vector-less live rows by keyset- * (`embedSegmentedPage`), never through its body or a whole-page chunk read.- * A dry run only counts those rows.+ * Wave B: embed a segmented page's vector-less live rows (all of them with `all`)+ * by keyset (`embedSegmentedPage`), never through its body or a whole-page+ * chunk read. A dry run only counts those rows.*/async function embedSegmented(engine: BrainEngine, page: SegmentedEmbedPage, result: EmbedResult,- opts: { dryRun: boolean; signal?: AbortSignal; signature?: string; approvedCapUsd?: number }): Promise<void> {+ opts: { dryRun: boolean; signal?: AbortSignal; signature?: string; approvedCapUsd?: number; all?: boolean }): Promise<void> {if (opts.dryRun) {const counts = await countSegmentedEmbedRows(engine, page.id);result.total_chunks += counts.total;- result.would_embed += counts.stale;+ result.would_embed += opts.all ? counts.total : counts.stale;result.pages_processed++;return;}try {const done = await embedSegmentedPage(engine, page, { embedFn: (texts, o) => embedBatchWithBackoff(texts, o),- signal: opts.signal, signature: opts.signature, approvedCapUsd: opts.approvedCapUsd });+ signal: opts.signal, signature: opts.signature, approvedCapUsd: opts.approvedCapUsd, all: opts.all });result.embedded += done.embedded;const stamp = done.complete ? await resolveProvenanceStamp(engine, opts.signature) : undefined;if (stamp) await stampIfPageProvenanceComplete(engine, page.slug, page.source_id, stamp);@@ -1108,7 +1108,7 @@ async function embedPage(if (!initial) {throw new Error(`Page not found: ${slug}`);}- const segmented = await readSegmentedEmbedPage(engine, { sourceId: initial.page.source_id, slug });+ const segmented = await readSealedSegmentedEmbedPage(engine, initial.page, !dryRun);if (segmented) {if (isEmbedSkipped(initial.page.frontmatter)) { if (!quiet) serr(` ${slug}: skipped (frontmatter.embed_skip set); its chunks stay keyword-searchable`); return; }await embedSegmented(engine, segmented, result, { dryRun, signal, signature: currentEmbeddingSignature() ?? undefined, approvedCapUsd: approvedPageCapUsd });@@ -1371,8 +1371,8 @@ async function embedAll(// target the correct (source_id, slug) row, not the 'default' source.const pageSourceId = page.source_id;const pageOpts = pageSourceId ? { sourceId: pageSourceId } : undefined;- const segmented = await observed(pacer, () => readSegmentedEmbedPage(engine, { id: page.id }));- if (segmented) { await embedSegmented(engine, segmented, result, { dryRun, signal, signature }); return; }+ const segmented = await observed(pacer, () => readSealedSegmentedEmbedPage(engine, page, !dryRun));+ if (segmented) { await embedSegmented(engine, segmented, result, { dryRun, signal, signature, all: true }); return; }const prepared = await observed(pacer, () => readProjectionSnapshot(engine, page.slug, pageSourceId, { requireLiveSource: !dryRun }));if (!prepared) {if (!dryRun) recordFailure(result, 1, page.slug, EMBED_UNAVAILABLE_MESSAGE);diff --git a/src/core/embedding-readiness.ts b/src/core/embedding-readiness.tsindex 594b7d0f46..e3d9d8ba8c 100644--- a/src/core/embedding-readiness.ts+++ b/src/core/embedding-readiness.ts@@ -5,6 +5,9 @@ import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';import { isMultimodalEnabled } from './sync.ts';import { buildSegmentedProjection } from './page-body/projection.ts';+/** A segmented page with a body: its projection (`buildSegmentedProjection`) owes chunk rows even when it has none yet. */+const SEGMENTED_BODY = `(p.body_storage = 'segmented' AND p.body_bytes > 0)`;+export async function countArchivedEmbeddingWork(engine: BrainEngine, opts: { sourceId?: string; signature?: string; includeNullSignature?: boolean; includeUnsealed?: boolean } = {}, activeColumn?: string | null): Promise<number> {const column = activeColumn === undefined ? (await resolveActiveEmbeddingColumnFromEngine(engine)).name : activeColumn;const vector = column === null ? 'NULL::vector' : `c.${quoteIdentifier(column)}`;@@ -16,7 +19,7 @@ export async function countArchivedEmbeddingWork(engine: BrainEngine, opts: { soOR EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND (${vector} IS NULLOR c.embedded_text_hash <> md5(c.chunk_text)OR ($2::text IS NOT NULL AND (p.embedding_signature <> $2 OR ($3::boolean AND p.embedding_signature IS NULL)))))- OR ((p.compiled_truth <> '' OR p.timeline <> '') AND ${QUARANTINE_FILTER_FRAGMENT}+ OR ((p.compiled_truth <> '' OR p.timeline <> '' OR ${SEGMENTED_BODY}) AND ${QUARANTINE_FILTER_FRAGMENT}AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)))`,[opts.sourceId ?? null, opts.signature ?? null, opts.includeNullSignature ?? false, opts.includeUnsealed ?? false]);if (!Number.isSafeInteger(row?.n) || row.n < 0) throw new Error('Cannot determine archived embedding work.');@@ -32,16 +35,16 @@ async function pendingProjectionWhere(engine: BrainEngine, opts: ProjectionScopeif (opts.stale) {const column = quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine)).name);params.push(opts.stale.signature ?? null, opts.stale.includeNullSignature ?? false);- eligible = `AND EXISTS(SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND (+ eligible = `AND (${SEGMENTED_BODY} OR EXISTS(SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND (c.${column} IS NULL OR c.embedded_text_hash <> md5(c.chunk_text)- OR ($3::text IS NOT NULL AND (p.embedding_signature <> $3 OR ($4::boolean AND p.embedding_signature IS NULL)))))`;+ OR ($3::text IS NOT NULL AND (p.embedding_signature <> $3 OR ($4::boolean AND p.embedding_signature IS NULL))))))`;}const where = `p.deleted_at IS NULLAND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revisionAND ($1::text IS NULL OR p.source_id=$1)${opts.activeSourcesOnly ? 'AND NOT s.archived' : ''}- AND (NOT $2::boolean OR EXISTS(SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)) ${eligible}`;+ AND (NOT $2::boolean OR ${SEGMENTED_BODY} OR EXISTS(SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)) ${eligible}`;return { where, params };}diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 662339a283..901e94570e 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -750,8 +750,9 @@ function chunklessPagesWhere(opts?: { sourceId?: string }): SqlFragment {sqlFragment`p.deleted_at IS NULL`,// healChunklessPages chunks BOTH compiled_truth and timeline (mirrors// embedPage) — a timeline-only page (rare but schema-legal) has- // something to heal even with compiled_truth = ''.- sqlFragment`(p.compiled_truth <> '' OR p.timeline <> '')`,+ // something to heal even with compiled_truth = ''. A segmented page's+ // body columns are NULL; its body_bytes says it has one.+ sqlFragment`(p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0))`,sqlFragment`${trustedSql(EMBED_SKIP_FILTER_FRAGMENT)}`,sqlFragment`${trustedSql(QUARANTINE_FILTER_FRAGMENT)}`,sqlFragment`NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)`,diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex db1befdb8f..f06909ff29 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -644,10 +644,10 @@ export async function importFromContent(// it reuses inside its publication transaction, under the page guard, from// the chunks it is about to replace; only the chunks left without a vector// reach the provider.- // A large page commits with NULL vectors; the stale sweep embeds it under the- // per-page cap and the sampled junk check, so no provider call holds the write.+ // A large or segmented page (the hysteresis band too) commits with NULL vectors; the stale+ // sweep embeds it under the per-page cap and the sampled junk check, so no provider call holds the write.const noEmbed = opts.noEmbed || isEmbedSkipped(parsed.frontmatter);- const largePage = isLargePageBytes(bodyBytes);+ const largePage = isLargePageBytes(bodyBytes) || segmented !== null;const postCommitEmbedding = largePage ? undefined : opts.onPostCommitEmbedding;const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !postCommitEmbedding && chunks.length > 0 && bodyStorageOf(existing) !== 'segmented'&& !(opts.prepare && modeRequiresSynopsis(effectiveCRMode)) && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`);diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.tsindex 8549218d2d..da88a38461 100644--- a/src/core/page-body/segmented-embedding.ts+++ b/src/core/page-body/segmented-embedding.ts@@ -17,6 +17,9 @@ import { meterPageBatch, spendGrant } from '../page-embedding-budget.ts';import { embeddingInputContext, embeddingWriteTarget } from '../page-state/projections.ts';import { quoteIdentifier, vectorCastSuffix } from '../search/embedding-column.ts';import { chunkGenerationFilter, chunkVisibleFilter, currentTextProjectionFilter } from '../search/safe-chunks.ts';+import { buildSegmentedProjection } from './projection.ts';+import { isSegmentedPage } from './page-shape.ts';+import type { BodyStorage } from './types.ts';/** Stale rows read and embedded per provider round trip. */export const SEGMENTED_EMBED_BATCH_ROWS = 500;@@ -56,26 +59,47 @@ export async function readSegmentedEmbedPage(engine: Pick<BrainEngine, 'executeRreturn row ? { ...row, id: Number(row.id), body_storage: 'segmented', body_bytes: Number(row.body_bytes) } : null;}-/** A dry run's counts: the page's live rows and those not yet embedded. */+/**+ * `readSegmentedEmbedPage` for a page row; with `build`, a live segmented page+ * in a live source that is not sealed gets its projection built first (a+ * create whose post-commit projection never ran or failed has no chunk rows+ * to embed). Null for an inline page or one still not sealed.+ */+export async function readSealedSegmentedEmbedPage(engine: BrainEngine,+ page: { slug: string; source_id: string; body_storage?: BodyStorage | null }, build: boolean): Promise<SegmentedEmbedPage | null> {+ const ref = { sourceId: page.source_id, slug: page.slug };+ const sealed = await readSegmentedEmbedPage(engine, ref);+ if (sealed || !build || !isSegmentedPage(page)) return sealed;+ const [unsealed] = await engine.executeRaw(`SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.source_id = $1 AND p.slug = $2 AND p.body_storage = 'segmented' AND p.deleted_at IS NULL AND NOT s.archived`, [ref.sourceId, ref.slug]);+ return unsealed && (await buildSegmentedProjection(engine, ref)).sealed ? readSegmentedEmbedPage(engine, ref) : null;+}++/** A dry run's counts: the page's live rows and those without a vector in the write column. */export async function countSegmentedEmbedRows(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<{ total: number; stale: number }> {+ const col = quoteIdentifier((await embeddingWriteTarget(engine)).column.name);const [row] = await engine.executeRaw<{ total: number; stale: number }>(- `SELECT count(*)::int AS total, count(*) FILTER (WHERE cc.embedded_at IS NULL)::int AS stale+ `SELECT count(*)::int AS total, count(*) FILTER (WHERE cc.${col} IS NULL)::int AS staleFROM content_chunks cc JOIN pages p ON p.id = cc.page_idWHERE cc.page_id = $1 AND ${chunkVisibleFilter('p', 'cc')}`, [pageId]);return { total: Number(row?.total ?? 0), stale: Number(row?.stale ?? 0) };}-/** Vector-less live rows of a segmented page after `afterChunkIndex`, in chunk_index order; `occurrenceIds` limits them to the occurrences a write added. */+/**+ * Vector-less live rows of a segmented page below `beforeChunkIndex` (null: from the newest), newest first, so a+ * per-page cap spends on the newest rows; `occurrenceIds` limits them to the occurrences a write added,+ * `includeEmbedded` takes rows that already hold a vector too (`gbrain embed --all`).+ */export async function listSegmentedStaleRows(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, column: string,- opts: { afterChunkIndex: number; limit: number; occurrenceIds?: readonly number[] }): Promise<SegmentedStaleRow[]> {+ opts: { beforeChunkIndex: number | null; limit: number; occurrenceIds?: readonly number[]; includeEmbedded?: boolean }): Promise<SegmentedStaleRow[]> {const col = quoteIdentifier(column);return engine.executeRaw<SegmentedStaleRow>(`SELECT cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks cc JOIN pages p ON p.id = cc.page_id- WHERE cc.page_id = $1 AND cc.${col} IS NULL AND cc.chunk_index > $2+ WHERE cc.page_id = $1 AND ($5::boolean OR cc.${col} IS NULL) AND ($2::int IS NULL OR cc.chunk_index < $2::int)AND ($4::bigint[] IS NULL OR cc.occurrence_id = ANY($4::bigint[])) AND ${chunkVisibleFilter('p', 'cc')}- ORDER BY cc.chunk_index LIMIT $3`,- [pageId, opts.afterChunkIndex, opts.limit, opts.occurrenceIds ? [...opts.occurrenceIds] : null]);+ ORDER BY cc.chunk_index DESC LIMIT $3`,+ [pageId, opts.beforeChunkIndex, opts.limit, opts.occurrenceIds ? [...opts.occurrenceIds] : null, opts.includeEmbedded ?? false]);}/**@@ -126,25 +150,28 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb/*** Embed every vector-less live row of a segmented page (or only the rows of- * `occurrenceIds`, the occurrences an append added), one keyset batch at a- * time, until the rows run out (`complete`), the budget holds the page or- * leaves no room (`stopped: 'budget'`), or the page moved under an install- * (`stopped: 'page_moved'`).+ * `occurrenceIds`, the occurrences an append added; every live row with+ * `all`), newest first, one keyset batch at a time, until the rows run out+ * (`complete`), the budget holds the page or leaves no room (`stopped:+ * 'budget'`), or the page moved under an install (`stopped: 'page_moved'`).+ * An approval (`approvedCapUsd`) raises the page's cap once per run: later+ * batches keep the approval's lifted hold but spend under the cap it set.*/export async function embedSegmentedPage(engine: BrainEngine, page: SegmentedEmbedPage,- opts: SegmentedEmbedOpts & { occurrenceIds?: readonly number[]; batchRows?: number }): Promise<{ embedded: number; complete: boolean; stopped?: 'budget' | 'page_moved' }> {+ opts: SegmentedEmbedOpts & { occurrenceIds?: readonly number[]; batchRows?: number; all?: boolean }): Promise<{ embedded: number; complete: boolean; stopped?: 'budget' | 'page_moved' }> {const column = (await embeddingWriteTarget(engine)).column.name;const limit = opts.batchRows ?? SEGMENTED_EMBED_BATCH_ROWS;let embedded = 0;- for (let after = -1; ;) {+ for (let before: number | null = null; ;) {opts.signal?.throwIfAborted();- const rows = await listSegmentedStaleRows(engine, page.id, column, { afterChunkIndex: after, limit, occurrenceIds: opts.occurrenceIds });+ const rows = await listSegmentedStaleRows(engine, page.id, column, { beforeChunkIndex: before, limit, occurrenceIds: opts.occurrenceIds, includeEmbedded: opts.all });if (rows.length === 0) return { embedded, complete: true };- const installed = await embedSegmentedRows(engine, page, rows, opts);+ const approvedCapUsd = opts.approvedCapUsd === undefined || before === null ? opts.approvedCapUsd : 0;+ const installed = await embedSegmentedRows(engine, page, rows, { ...opts, approvedCapUsd });if (installed === null) return { embedded, complete: false, stopped: 'budget' };embedded += installed;if (installed === 0) return { embedded, complete: false, stopped: 'page_moved' };if (installed < rows.length) return { embedded, complete: false, stopped: 'budget' };- after = rows[rows.length - 1]!.chunk_index;+ before = rows[rows.length - 1]!.chunk_index;}}diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex e9ab6095ab..1c8c2152cc 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -40,6 +40,8 @@ import { PAGE_INLINE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';import { isEmbedSkipped } from './embed-skip.ts';import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';import { chunkGenerationFilter } from './search/safe-chunks.ts';+import { quoteIdentifier } from './search/embedding-column.ts';+import { embeddingWriteTarget } from './page-state/projections.ts';export const PAGE_EMBED_CAP_KEY = 'embed.max_usd_per_page';export const DEFAULT_PAGE_EMBED_CAP_USD = 2;@@ -195,9 +197,10 @@ export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeRconst filters = [`b.state <> 'open'`, 'p.deleted_at IS NULL'];if (opts.state) filters.push(`b.state = $${params.push(opts.state)}`);if (opts.sourceId) filters.push(`p.source_id = $${params.push(opts.sourceId)}`);+ const pending = `(cc.embedded_at IS NULL OR cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)} IS NULL)`;const rows = await engine.executeRaw<PageBudgetReport>(`SELECT p.slug, p.source_id, b.state, b.reason, b.spent_usd, b.cap_usd,- (SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL AND ${chunkGenerationFilter('p', 'cc')}) AS pending_chunks,- (SELECT COALESCE(sum(length(cc.chunk_text)), 0)::bigint FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL AND ${chunkGenerationFilter('p', 'cc')}) AS pending_chars+ (SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND ${pending} AND ${chunkGenerationFilter('p', 'cc')}) AS pending_chunks,+ (SELECT COALESCE(sum(length(cc.chunk_text)), 0)::bigint FROM content_chunks cc WHERE cc.page_id = p.id AND ${pending} AND ${chunkGenerationFilter('p', 'cc')}) AS pending_charsFROM page_embedding_budget b JOIN pages p ON p.id = b.page_idWHERE ${filters.join(' AND ')} ORDER BY b.updated_at DESC, p.id LIMIT $1`, params);return rows.map(row => ({ ...row, spent_usd: Number(row.spent_usd), cap_usd: row.cap_usd === null ? null : Number(row.cap_usd), pending_chunks: Number(row.pending_chunks), pending_chars: Number(row.pending_chars) }));@@ -267,8 +270,8 @@ export async function heldEmbedArgv(engine: BrainEngine, args: readonly string[]/*** #6722: what a write left a page's embedding in, for write, sync and* remember receipts. Null for an ordinary page (embedded with the write, or by- * the post-write job). `deferred`: over the inline threshold, embedded after- * the commit under the per-page cap. `partial`: the cap stopped it with chunks+ * the post-write job). `deferred`: over the inline threshold or stored+ * segmented, embedded after the commit under the per-page cap. `partial`: the cap stopped it with chunks* left keyword-only. `held`: it waits for the user's approval. `skipped`: an* embed_skip marker (`oversized` when the gate set it because the page is over* the operator's bytes_block). Every such page is chunked and keyword-searchable.@@ -276,13 +279,13 @@ export async function heldEmbedArgv(engine: BrainEngine, args: readonly string[]export interface PageSizeState { embedding: 'deferred' | 'partial' | 'held' | 'skipped'; reason: string; bytes: number }export function pageSizeState(bytes: number, frontmatter: Record<string, unknown> | null | undefined,- budget?: { state: PageBudgetState; reason: string | null } | null): PageSizeState | null {+ budget?: { state: PageBudgetState; reason: string | null } | null, segmented = false): PageSizeState | null {if (isEmbedSkipped(frontmatter)) {return { embedding: 'skipped', reason: (frontmatter!.embed_skip as { reason?: unknown } | null)?.reason === 'oversized' ? 'oversized' : 'operator_marker', bytes };}if (budget?.state === 'held') return { embedding: 'held', reason: budget.reason ?? 'awaiting_approval', bytes };if (budget?.state === 'capped') return { embedding: 'partial', reason: 'spend_cap', bytes };- return isLargePageBytes(bytes) ? { embedding: 'deferred', reason: 'large_page', bytes } : null;+ return isLargePageBytes(bytes) || segmented ? { embedding: 'deferred', reason: 'large_page', bytes } : null;}/**@@ -292,14 +295,14 @@ export function pageSizeState(bytes: number, frontmatter: Record<string, unknownexport async function readPageSizeStates(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slugs: readonly string[] | null): Promise<Array<{ slug: string } & PageSizeState>> {if (slugs?.length === 0) return [];const bytes = `(CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END)`;- const rows = await engine.executeRaw<{ slug: string; bytes: number; frontmatter: Record<string, unknown> | null; state: PageBudgetState | null; reason: string | null }>(- `SELECT p.slug, ${bytes}::bigint AS bytes, p.frontmatter, b.state, b.reason+ const rows = await engine.executeRaw<{ slug: string; bytes: number; segmented: boolean; frontmatter: Record<string, unknown> | null; state: PageBudgetState | null; reason: string | null }>(+ `SELECT p.slug, ${bytes}::bigint AS bytes, p.body_storage = 'segmented' AS segmented, p.frontmatter, b.state, b.reasonFROM pages p LEFT JOIN page_embedding_budget b ON b.page_id = p.idWHERE p.source_id = $1 AND p.deleted_at IS NULL${slugs ? ' AND p.slug = ANY($3::text[])' : ''}- AND (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip' OR ${bytes} > $2 OR b.page_id IS NOT NULL) ORDER BY p.slug`,+ AND (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip' OR ${bytes} > $2 OR p.body_storage = 'segmented' OR b.page_id IS NOT NULL) ORDER BY p.slug`,slugs ? [sourceId, PAGE_INLINE_MAX_BYTES, [...slugs]] : [sourceId, PAGE_INLINE_MAX_BYTES]);return rows.flatMap(row => {- const state = pageSizeState(Number(row.bytes), row.frontmatter, row.state ? { state: row.state, reason: row.reason } : null);+ const state = pageSizeState(Number(row.bytes), row.frontmatter, row.state ? { state: row.state, reason: row.reason } : null, row.segmented === true);return state ? [{ slug: row.slug, ...state }] : [];});}@@ -309,7 +312,7 @@ export async function sizeStateField(engine: Pick<BrainEngine, 'executeRaw'>, sopage: { body_storage?: BodyStorage | null; body_bytes?: number | null; compiled_truth?: string | null; timeline?: string | null; frontmatter?: Record<string, unknown> | null } | null | undefined): Promise<{ size_state?: PageSizeState }> {if (!page) return {};const bytes = pageBodyBytes(page);- if (!isLargePageBytes(bytes) && !isEmbedSkipped(page.frontmatter)) return {};+ if (!isLargePageBytes(bytes) && !isSegmentedPage(page) && !isEmbedSkipped(page.frontmatter)) return {};const [state] = await readPageSizeStates(engine, sourceId, [slug]);return state ? { size_state: { embedding: state.embedding, reason: state.reason, bytes: state.bytes } } : {};}diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex 3bcc2895b3..365b7919a4 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -7,8 +7,8 @@{"lane": "pool","params": [],- "sql": "SELECT count(*)::int AS count FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)",- "textSha256": "694dfd23cceb5cb7dcc1db8120a5921cb371b6d28403f473d15d2bac857abae6"+ "sql": "SELECT count(*)::int AS count FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)",+ "textSha256": "73a9c5e1e659d1825cbdd2179ea97221d4e99d1210a7887df33369cf680685e1"}],"sourceId": [@@ -17,8 +17,8 @@"params": ["string"],- "sql": "SELECT count(*)::int AS count FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = $1",- "textSha256": "57905ac779cfdac6d37abd91220a1fe2d49ed9f7c173d78e941680360e6508a1"+ "sql": "SELECT count(*)::int AS count FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = $1",+ "textSha256": "0671c721eec68517434e13d5a6f319288301476f24d798acf6bd36d39954c20f"}]},@@ -481,8 +481,8 @@"number","number"],- "sql": "SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = $1 AND p.id > $2 ORDER BY p.id LIMIT $3",- "textSha256": "5ab7aba0751ee5bc5f4836de31e89ea5f11344e7b850a67c801e6ce3f1c29dee"+ "sql": "SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = $1 AND p.id > $2 ORDER BY p.id LIMIT $3",+ "textSha256": "d0a4b3657d06c033511703c55e92e8f99291a7786ddadb79c1c5282a1db50358"}],"default": [@@ -491,8 +491,8 @@"params": ["number"],- "sql": "SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ORDER BY p.id LIMIT $1",- "textSha256": "075b222a373875f730b5663cacfc3740675e622b2ae5ea455e0f9bf13e0ca701"+ "sql": "SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline FROM pages p WHERE p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ORDER BY p.id LIMIT $1",+ "textSha256": "4fcbfbee9104e6de6930d7685e488ac2ed01dfd7283da57be1b6e4f04790e519"}]},@@ -511,8 +511,8 @@"array<string>","number"],- "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ) r WHERE r.state = ANY($2::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $3",- "textSha256": "1e7d563076ef0bb20f4327efff466a44cb5c98696c620f3f20d00bf55b1d4782"+ "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ) r WHERE r.state = ANY($2::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $3",+ "textSha256": "5447893d211b446588a71f42b6a882ed7af173774042e8cbb9adbe3e25e0f3d7"}],"sourceIds": [@@ -531,8 +531,8 @@"array<string>","number"],- "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND p.source_id = ANY($2::text[]) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($3::text[]) ) r WHERE r.state = ANY($4::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $5",- "textSha256": "69218d0c6798a19f396c66a58539e1276fcab3c6c38757f8622795da5ff8e9f8"+ "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND p.source_id = ANY($2::text[]) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($3::text[]) ) r WHERE r.state = ANY($4::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $5",+ "textSha256": "7ea7ddd474536a5f7def73ec3b373518fcebf6022c7a44b096314772a241ac93"}]},@@ -678,8 +678,8 @@{"lane": "pool","params": [],- "sql": "SELECT s.state, count(*)::bigint AS n FROM (SELECT CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END AS state FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)) s GROUP BY s.state",- "textSha256": "b2d51df28315e0a7e6a7398d11744d4ffec51b3b539698b822782de61e7cf0de"+ "sql": "SELECT s.state, count(*)::bigint AS n FROM (SELECT CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END AS state FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)) s GROUP BY s.state",+ "textSha256": "743d6c76815a5e22d7c1af99c4dfa0f0f8b24d1802ad7518f32ce6d732536abf"}],"full+sourceIds": [@@ -711,8 +711,8 @@"params": ["array<string>"],- "sql": "SELECT s.state, count(*)::bigint AS n FROM (SELECT CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END AS state FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($1::text[])) s GROUP BY s.state",- "textSha256": "0d349e62d3ec1f08e76c1c2c38ad677566a42717f1bc965c293210eb2807b452"+ "sql": "SELECT s.state, count(*)::bigint AS n FROM (SELECT CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END AS state FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($1::text[])) s GROUP BY s.state",+ "textSha256": "5d63653e31d242c2b9ca44d8b4a8b08766b788d8f47ce85962aaacfb441daeca"}],"ops": [diff --git a/test/large-pages/segmented-embedding-paths.test.ts b/test/large-pages/segmented-embedding-paths.test.tsnew file mode 100644index 0000000000..6624904964--- /dev/null+++ b/test/large-pages/segmented-embedding-paths.test.ts@@ -0,0 +1,188 @@+/**+ * Wave B segmented embedding paths: the per-page budget across keyset+ * batches, `embed --all` and the stale counts, writes in the hysteresis+ * band, and a segmented create whose post-commit projection never ran.+ *+ * 1. Protects: an approval (`--max-usd N`) raises a segmented page's cap once+ * per run, and a binding cap spends on the newest rows; `embed --all`+ * re-embeds a segmented page's live rows as it does an inline page's; the+ * dry-run count and the held report read the write column; a segmented+ * write under the inline threshold reports deferred embedding; an+ * unsealed segmented create with no chunk rows is rebuilt by projection+ * recovery, `embed <slug>` and `embed --all`, and counts as chunkless.+ * 2. Fails when: each keyset batch re-applies the approval, batches walk+ * oldest first, `--all` embeds only vector-less rows, counts key on+ * embedded_at, a band write reports no deferral, or the unsealed page is+ * invisible to the recovery paths.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { runEmbedCore } from '../../src/commands/embed.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { prepareEmbeddingProjections } from '../../src/core/embedding-readiness.ts';+import { countSegmentedEmbedRows, embedSegmentedPage, readSegmentedEmbedPage } from '../../src/core/page-body/segmented-embedding.ts';+import { estimatePageEmbedUsd, holdPageEmbedding, listBudgetLimitedPages, PAGE_EMBED_CAP_KEY, readPageSizeStates } from '../../src/core/page-embedding-budget.ts';+import { SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, SEGMENTED_PROMOTE_ABOVE_BYTES } from '../../src/core/page-body/limits.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';+import { conversationPage } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentPage, unitVector } from '../helpers/segmented-chunks-fixture.ts';+import { segmentedPageRow, visibleChunks } from '../helpers/segmented-page-checks.ts';+import { testBackends } from '../helpers/test-backends.ts';++const SLUG = 'notes/segmented-paths';+const ROW_TEXT = (i: number) => `Row ${i}: an ordinary paragraph about herons wading in the marsh at dawn, `.padEnd(350, 'and the reeds bend in the wind. ');+const ROW_USD = estimatePageEmbedUsd(ROW_TEXT(0).length, null);++for (const kind of testBackends()) {+ describe(`segmented embedding paths (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let dims: number;+ const embedFn = async (texts: string[]) => {+ const v = Float32Array.from(await unitVector(engine, 3));+ return texts.map(() => v);+ };++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ dims = (await resolveActiveEmbeddingColumnFromEngine(engine)).dimensions;+ }, 120_000);+ afterAll(async () => { resetGateway(); await close?.(); });+ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw('DELETE FROM page_segment_texts');+ await engine.executeRaw('DELETE FROM page_embedding_budget');+ await engine.executeRaw(`DELETE FROM config WHERE key = $1`, [PAGE_EMBED_CAP_KEY]);+ await engine.setConfig('pages.segmented_storage', 'on');+ resetGateway();+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({+ embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))),+ usage: { tokens: values.length },+ })) as never);+ });+ afterEach(() => { __setEmbedTransportForTests(null); installFaultHook(undefined); });++ const vectoredRows = async (slug = SLUG) => (await engine.executeRaw<{ chunk_index: number }>(+ `SELECT cc.chunk_index FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.slug = $1 AND cc.embedding IS NOT NULL ORDER BY cc.chunk_index`, [slug])).map(r => Number(r.chunk_index));++ /** A large (metered) segmented page of six vector-less rows, chunk_index 0..5. */+ const sixRowPage = () => segmentPage(engine, SLUG, { generation: 1, bodyBytes: 4 * 1024 * 1024,+ occurrences: [{ id: 1, byteStart: 0, genFrom: 1, chunks: [0, 1, 2, 3, 4, 5].map(i => ({ text: ROW_TEXT(i), chunkIndex: i })) }] });++ test('an approval raises the cap once per run: later keyset batches spend under it, newest rows first', async () => {+ await engine.setConfig(PAGE_EMBED_CAP_KEY, '0.000000001');+ const { pageId } = await sixRowPage();+ const page = (await readSegmentedEmbedPage(engine, { sourceId: 'default', slug: SLUG }))!;+ expect(await embedSegmentedPage(engine, page, { embedFn, batchRows: 2, approvedCapUsd: 2.5 * ROW_USD }))+ .toEqual({ embedded: 2, complete: false, stopped: 'budget' });+ expect(await vectoredRows()).toEqual([4, 5]);+ const [budget] = await engine.executeRaw<{ cap_usd: number }>('SELECT cap_usd FROM page_embedding_budget WHERE page_id = $1', [pageId]);+ expect(Number(budget!.cap_usd)).toBeCloseTo(2.5 * ROW_USD, 12);+ });++ test('a binding per-page cap without approval spends on the newest rows', async () => {+ await engine.setConfig(PAGE_EMBED_CAP_KEY, String(2.5 * ROW_USD));+ await sixRowPage();+ const page = (await readSegmentedEmbedPage(engine, { sourceId: 'default', slug: SLUG }))!;+ expect(await embedSegmentedPage(engine, page, { embedFn, batchRows: 2 })).toEqual({ embedded: 2, complete: false, stopped: 'budget' });+ expect(await vectoredRows()).toEqual([4, 5]);+ });++ /** A small segmented page whose three live rows all hold a vector. */+ const embeddedPage = (bodyBytes?: number) => segmentPage(engine, SLUG, { generation: 1, bodyBytes,+ occurrences: [{ id: 1, byteStart: 0, genFrom: 1, chunks: [0, 1, 2].map(i => ({ text: ROW_TEXT(i), chunkIndex: i, vector: 1 })) }] });++ test('embed --all dry run counts every live row of a segmented page, as it does an inline page\'s', async () => {+ await embeddedPage();+ const dry = await runEmbedCore(engine, { all: true, dryRun: true, quiet: true });+ expect({ total: dry.total_chunks, would: dry.would_embed }).toEqual({ total: 3, would: 3 });+ });++ test('embed --all re-embeds every live row of a segmented page', async () => {+ await embeddedPage();+ const run = await runEmbedCore(engine, { all: true, quiet: true });+ expect({ embedded: run.embedded, failures: run.failures }).toEqual({ embedded: 3, failures: 0 });+ const rows = await engine.executeRaw<{ first: number }>(`SELECT (cc.embedding::text::jsonb ->> 0)::float8 AS first FROM content_chunks cc+ JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1`, [SLUG]);+ expect(rows.map(r => Number(r.first))).toEqual([1, 1, 1]);+ });++ test('the segmented dry-run count reads the write column, not embedded_at', async () => {+ const { pageId } = await embeddedPage();+ await engine.executeRaw('UPDATE content_chunks SET embedding = NULL WHERE page_id = $1', [pageId]);+ expect(await countSegmentedEmbedRows(engine, pageId)).toEqual({ total: 3, stale: 3 });+ });++ test('the held report counts rows without a vector in the write column, not only those without embedded_at', async () => {+ const { pageId } = await embeddedPage(4 * 1024 * 1024);+ await engine.executeRaw('UPDATE content_chunks SET embedding = NULL WHERE page_id = $1', [pageId]);+ await holdPageEmbedding(engine, pageId, 'awaiting_approval');+ expect(await listBudgetLimitedPages(engine)).toEqual([expect.objectContaining({ slug: SLUG, state: 'held', pending_chunks: 3 })]);+ });++ test('a segmented write in the hysteresis band defers its embedding like a large page', async () => {+ const sized = (bytes: number) => conversationPage(bytes, { seed: 5 });+ await importFromContent(engine, 'notes/band', sized(SEGMENTED_PROMOTE_ABOVE_BYTES + 128 * 1024), { sourceId: 'default', noEmbed: true });+ const band = await importFromContent(engine, 'notes/band', sized(SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES + 128 * 1024), { sourceId: 'default' });+ expect((await segmentedPageRow(engine, 'notes/band')).body_storage).toBe('segmented');+ expect(band.embedding_deferred).toBe(true);+ expect(await readPageSizeStates(engine, 'default', ['notes/band'])).toEqual([expect.objectContaining({ slug: 'notes/band', embedding: 'deferred' })]);+ }, 240_000);++ describe('a segmented create whose post-commit projection never ran', () => {+ const UNSEALED = 'notes/unsealed';+ beforeEach(async () => {+ installFaultHook(point => { if (point === 'segmented:projection_staged') throw new Error('projection died'); });+ await importFromContent(engine, UNSEALED, conversationPage(SEGMENTED_PROMOTE_ABOVE_BYTES + 128 * 1024, { seed: 9 }), { sourceId: 'default', noEmbed: true });+ installFaultHook(undefined);+ const page = await segmentedPageRow(engine, UNSEALED);+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [page.id]);+ expect(page.body_storage).toBe('segmented');+ expect(page.text_projection_revision).not.toBe(page.knowledge_revision);+ }, 240_000);++ const expectSealedWithChunks = async () => {+ const page = await segmentedPageRow(engine, UNSEALED);+ expect(page.text_projection_revision).toBe(page.knowledge_revision);+ expect((await visibleChunks(engine, page.id)).length).toBeGreaterThan(0);+ };++ test('it counts as a chunkless page with content', async () => {+ expect(await engine.countChunklessPagesWithContent()).toBe(1);+ });++ test('embed --stale projection recovery rebuilds it', async () => {+ const readiness = await prepareEmbeddingProjections(engine, { existingChunksOnly: true, activeSourcesOnly: true, stale: {}, repair: true });+ expect(readiness).toEqual({ rebuilt: 1, blocked: 0 });+ await expectSealedWithChunks();+ }, 120_000);++ test('embed <slug> builds its projection and embeds it', async () => {+ const run = await runEmbedCore(engine, { slugs: [UNSEALED], quiet: true });+ expect(run.failures).toBe(0);+ expect(run.embedded).toBeGreaterThan(0);+ await expectSealedWithChunks();+ }, 120_000);++ test('embed --all builds its projection and embeds it', async () => {+ const run = await runEmbedCore(engine, { all: true, quiet: true });+ expect(run.failures).toBe(0);+ expect(run.embedded).toBeGreaterThan(0);+ await expectSealedWithChunks();+ }, 120_000);+ });+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 803b52b54d..e801c8ff4f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -67,6 +67,7 @@ test/large-pages/chunk-visibility.test.tstest/large-pages/managed-streamed-import.test.tstest/large-pages/segment-vector-reuse.test.tstest/large-pages/segmented-body-unreachable.test.ts+test/large-pages/segmented-embedding-paths.test.tstest/large-pages/segmented-embedding.test.tstest/large-pages/segmented-versions.test.tstest/link-cross-source.test.ts