Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): segmented storage switch-on blockers, GC index (Wave B PR 2, lane G)
garrytan61531c632571
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 823fff6205..03550eebfd 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -173,14 +173,14 @@ describes bounded candidate recovery and incomplete-result metadata.On Postgres the same refresh also analyzes the page columns every searchfilter reads (`deleted_at`, `source_id`, `type`, `slug`) and-`content_chunks(model, modality, page_id, body_generation, retired_generation)`, and an embed drain that embedded+`content_chunks(model, modality, page_id, body_generation)`, and an embed drain that embeddedanything analyzes those chunk columns once at its end (each ANALYZE bounded bya 30 s statement and 2 s lock timeout). Without those statistics the vectorcandidate statement sorts every eligible chunk instead of walking the HNSWindex, and at 1M chunks and above that sort runs past the 8 s vector budget,so hybrid search falls back to keyword-only results until autovacuumanalyzes the tables. If a refresh is skipped (a lock, or a role that does not-own the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)` and+own the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation)` and`ANALYZE pages` as the table owner.### Vector index sizingdiff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex d431d7e4c7..ec18f79c66 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).-- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain. `chunkWriteInvalidations(pageId, chunks)` yields one guarded `chunker_version = -1` invalidation per row batch of a chunk replacement (`batch-rows.ts` `jsonRowBatches`); the caller stops at the first that returns a row. Wave B: `chunkVisibleFilter(p, c)` (current projection plus `chunkGenerationFilter`: a row of the page's live body generation; every inline row passes) is the search-facing chunk predicate, `chunkGenerationProbe(c)` the same without a joined page, and `chunkManifestJoin` / `chunkDocumentOrder` give segmented rows document order (manifest byte_start, local_ordinal); `scripts/check-chunk-visibility.ts` requires one of them or a reason on every `content_chunks` reader (rules in its header).+- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain. `chunkWriteInvalidations(pageId, chunks)` yields one guarded `chunker_version = -1` invalidation per row batch of a chunk replacement (`batch-rows.ts` `jsonRowBatches`); the caller stops at the first that returns a row. Wave B: `chunkVisibleFilter(p, c)` (current projection plus a row at or below the page's body generation; sealed pages hold no retired rows, and no subplan keeps vector search on HNSW) is the search predicate; `chunkGenerationFilter(p, c)` serves generation readers (an inline row of a non-segmented page, or a row whose occurrence has a live manifest row, hiding rows a deferred retirement or demotion left; `p` needs `body_storage`), `chunkGenerationProbe(c)` the same without a joined page, and `chunkManifestJoin` / `chunkDocumentOrder` give segmented rows document order (manifest byte_start, local_ordinal); `scripts/check-chunk-visibility.ts` requires one of them or a reason on every `content_chunks` reader (rules in its header).- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.- `src/core/link-ranking-policy.ts` — the link-type ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer.diff --git a/docs/eval/hnsw-scale-bench.md b/docs/eval/hnsw-scale-bench.mdindex 17bf13ae9d..e85281fc0a 100644--- a/docs/eval/hnsw-scale-bench.md+++ b/docs/eval/hnsw-scale-bench.md@@ -15,7 +15,7 @@ neighbours. The deeper scan has these effects:- **Unscoped searches** return identical results.**Fix 2: statistics follow bulk writes.** Import, sync, reindex and embed drains now analyze-`content_chunks(model, modality, page_id, body_generation, retired_generation)` and the page columns search filters read. Without those+`content_chunks(model, modality, page_id, body_generation)` and the page columns search filters read. Without thosestatistics, the pooled statement sorted every eligible chunk instead of walking the index. At 1M to 2Mchunks that ran past the 8 s budget on 44% to 100% of 50%-scoped searches. In the post-import statisticsstate, 1M and 2M chunks now plan on HNSW with no incomplete results.@@ -190,7 +190,7 @@ decimals in every cell. The topic-coherent gap is not a scan budget.`ANALYZE pages(text_projection_revision, knowledge_revision)` only. That is what import, sync, reindex andprojection recovery end with. On Postgres it now runs two steps:1. `ANALYZE pages(text_projection_revision, knowledge_revision, deleted_at, source_id, type, slug, body_generation)`.-2. `ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)`, in the same transaction (30 s statement and 2 s lock+2. `ANALYZE content_chunks(model, modality, page_id, body_generation)`, in the same transaction (30 s statement and 2 s locktimeouts) behind a savepoint, so a concurrent index build only skips this step, with a warning thatnames the command.diff --git a/docs/guides/planner-stats.md b/docs/guides/planner-stats.mdindex a4d5b8d04d..11937692bf 100644--- a/docs/guides/planner-stats.md+++ b/docs/guides/planner-stats.md@@ -53,7 +53,7 @@ until 10% of a table changes. Without the page columns search filters read,search plans as nested loops over every page (50-60 s per search at 5,000pages instead of 0.5 s). gbrain guards this two ways, both through the samerefresh as import and sync (`ANALYZE pages(...)` and-`ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)`, 30 s bounded):+`ANALYZE content_chunks(model, modality, page_id, body_generation)`, 30 s bounded):- The first search of each process checks in the background and collects themwhen the database role owns the tables. The search does not wait for it.diff --git a/llms-full.txt b/llms-full.txtindex 766153c72f..400d7ed1c5 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5412,14 +5412,14 @@ describes bounded candidate recovery and incomplete-result metadata.On Postgres the same refresh also analyzes the page columns every searchfilter reads (`deleted_at`, `source_id`, `type`, `slug`) and-`content_chunks(model, modality, page_id, body_generation, retired_generation)`, and an embed drain that embedded+`content_chunks(model, modality, page_id, body_generation)`, and an embed drain that embeddedanything analyzes those chunk columns once at its end (each ANALYZE bounded bya 30 s statement and 2 s lock timeout). Without those statistics the vectorcandidate statement sorts every eligible chunk instead of walking the HNSWindex, and at 1M chunks and above that sort runs past the 8 s vector budget,so hybrid search falls back to keyword-only results until autovacuumanalyzes the tables. If a refresh is skipped (a lock, or a role that does not-own the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)` and+own the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation)` and`ANALYZE pages` as the table owner.### Vector index sizingdiff --git a/scripts/bench-large-pages.ts b/scripts/bench-large-pages.tsindex 16798c3af3..3f00d0de34 100644--- a/scripts/bench-large-pages.ts+++ b/scripts/bench-large-pages.ts@@ -86,7 +86,7 @@ async function pageRows(engine: BrainEngine) {texts: await count(engine, 'SELECT count(DISTINCT sha256) AS n FROM page_body_manifest WHERE page_id=$1 AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2)', [id, generation]),manifest: await count(engine, 'SELECT count(*) AS n FROM page_body_manifest WHERE page_id=$1 AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2)', [id, generation]),manifestAtGeneration: await count(engine, 'SELECT count(*) AS n FROM page_body_manifest WHERE page_id=$1 AND gen_from=$2', [id, generation]),- chunks: await count(engine, 'SELECT count(*) AS n FROM content_chunks WHERE page_id=$1 AND retired_generation IS NULL', [id]),+ chunks: await count(engine, 'SELECT count(*) AS n FROM content_chunks WHERE page_id=$1', [id]),chunksAtGeneration: await count(engine, 'SELECT count(*) AS n FROM content_chunks WHERE page_id=$1 AND body_generation=$2', [id, generation]),};}diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 901e94570e..5580cca40c 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -1048,7 +1048,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReqSELECT * FROM unnest(${requests.map(r => r.page_id)}::int[], ${requests.map(r => r.from_index)}::int[],${requests.map(r => r.to_index)}::int[], ${requests.map(r => r.priority)}::int[]) AS r(page_id, lo, hi, prio)), auth AS (- SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation,+ SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_storage, p.body_generation,(COALESCE(p.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}) AS sealed,(SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prioFROM pages pdiff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.tsindex 9d36c5e895..7055ec9c40 100644--- a/src/core/engine-sql/page-body.ts+++ b/src/core/engine-sql/page-body.ts@@ -9,9 +9,12 @@* while a non-terminal persistence request's `intent.body_ref` names it.* - Manifest rows are staged before the chunk rows of their occurrences: a* staged chunk row no live staging's manifest row owns is garbage.- * - A writer that dedupes onto an existing text stages its manifest row in the- * same transaction as the text insert, so the FK lock protects the text from- * a concurrent sweep (insert-reference-before-GC).+ * - Insert-reference-before-GC: staging a text that already exists refreshes+ * its `created_at` under the row lock (a concurrent sweep skips the locked+ * row, then sees it inside the grace window), and the text sweep keeps every+ * text touched since the oldest live staging of its source opened, so a+ * text a preparation staged or deduped onto stays until its manifest row+ * references it, however long publication waits.** Statement sizes stay bounded whatever the page size: texts by* STAGE_BATCH_BYTES per engine, manifest and chunk rows by `jsonRowBatches`@@ -60,19 +63,24 @@ export async function stageSegmentTexts(exec: SqlExecutor, sourceId: string, texconst maxRows = Math.floor(exec.capabilities.maxBindParamsPerStatement / 5);let inserted = 0;let batch: SqlFragment[] = [];+ let batchShas = new Set<string>();let batchBytes = 0;const flush = async () => {if (batch.length === 0) return;- const { affectedRows } = await exec.run(sqlFragment`INSERT INTO page_segment_texts (source_id, sha256, byte_len, line_count, body)- VALUES ${joinFragments(batch, ', ')} ON CONFLICT (source_id, sha256) DO NOTHING`);- inserted += affectedRows;+ const { rows } = await exec.run<{ inserted: boolean }>(sqlFragment`INSERT INTO page_segment_texts (source_id, sha256, byte_len, line_count, body)+ VALUES ${joinFragments(batch, ', ')} ON CONFLICT (source_id, sha256) DO UPDATE SET created_at = now() RETURNING (xmax = 0) AS inserted`);+ inserted += rows.filter(row => row.inserted).length;batch = [];+ batchShas = new Set();batchBytes = 0;await yieldTurn();};for (const text of texts) {+ const sha = hex(text.sha256);+ if (batchShas.has(sha)) continue;if (batch.length > 0 && (batchBytes + text.body.byteLength > maxBytes || batch.length >= maxRows)) await flush();- batch.push(sqlFragment`(${sourceId}, decode(${hex(text.sha256)}, 'hex'), ${text.body.byteLength}::int, ${text.lineCount}::int,+ batchShas.add(sha);+ batch.push(sqlFragment`(${sourceId}, decode(${sha}, 'hex'), ${text.body.byteLength}::int, ${text.lineCount}::int,${Buffer.from(text.body.buffer, text.body.byteOffset, text.body.byteLength)}::bytea)`);batchBytes += text.body.byteLength;}@@ -177,6 +185,17 @@ export async function stageSegmentChunks(exec: SqlExecutor, pageId: number, gene// Lock-census: COMPLIANT — key is the page id, unique brain-wide.await tx.run(sqlFragment`SELECT pg_advisory_xact_lock(hashtextextended('gbrain:page-body-chunks:' || ${pageId}::text, 0))`);}+ // A preparation stages above the live generation and a projection at it, on a segmented page. Rows for a generation the+ // page has passed, or reached as an inline page, belong to a write that cannot publish. Read after the key-share lock:+ // a demotion holds the row FOR UPDATE (lockPageKeys) until it commits, so this read sees it.+ const { rows: pages } = await tx.run<{ body_generation: unknown; body_storage: string; slug: string }>(sqlFragment`+ SELECT body_generation, body_storage, slug FROM pages WHERE id = ${pageId}`);+ const live = Number(pages[0]?.body_generation);+ if (!pages[0] || generation < live || (generation === live && pages[0].body_storage !== 'segmented')) {+ throw opError('revision_changed', `Page ${pages[0]?.slug ?? pageId} moved to body generation ${pages[0] ? live : 'none'} while chunks for generation ${generation} were staged.`,+ 'Another write published first. Read the page again and repeat this write against its current revision.',+ { legacy_error: 'invalid_params', detail: JSON.stringify({ staged_generation: generation, current_generation: pages[0] ? live : null }) });+ }// chunk-visibility-ok: chunk_index is never reused, so the next index is past every row, staged and retired includedconst { rows } = await tx.run<{ next: unknown }>(sqlFragment`SELECT COALESCE(MAX(chunk_index), -1) + 1 AS next FROM content_chunks WHERE page_id = ${pageId}`);const first = Number(rows[0]?.next ?? 0);@@ -276,7 +295,7 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInputconst newLive = sqlFragment`(SELECT s.occurrence_id FROM page_body_manifest s WHERE s.page_id = ${input.pageId}AND (s.staging_id = ${input.stagingId}::uuidOR (s.staging_id IS NULL AND s.gen_to IS NULL AND NOT (s.occurrence_id = ANY(${[...input.closeOccurrences]}::bigint[])))))`;- const retire = sqlFragment`c.page_id = ${input.pageId} AND c.retired_generation IS NULL AND (+ const retire = sqlFragment`c.page_id = ${input.pageId} AND ((c.occurrence_id = ANY(${[...input.retireChunkOccurrences]}::bigint[]) AND c.body_generation <= ${input.expectedGeneration}::bigint)OR (${input.retireInlineChunks === true}::boolean AND c.body_generation IS NULL)OR (c.body_generation = ${input.newGeneration}::bigint AND c.occurrence_id NOT IN ${newLive}))`;@@ -286,8 +305,8 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInputconst retireDeferred = toRetire > input.retireMaxRows;await tx.run(sqlFragment`UPDATE page_body_manifest SET gen_to = ${input.newGeneration}::bigintWHERE page_id = ${input.pageId} AND gen_to IS NULL AND staging_id IS NULL AND occurrence_id = ANY(${[...input.closeOccurrences]}::bigint[])`);- // Retired rows are deleted, not marked: GC would delete a marked row at once (retired_generation <= the live generation),- // nothing reads one (vector reuse runs during preparation, against live rows), and marking rewrote each row's HNSW entry.+ // Retired rows are deleted, not marked (marking rewrote each row's HNSW entry). Their occurrences are closed above, so a+ // deferred retirement's rows are invisible to every reader (chunkGenerationFilter) before the projection job deletes them.const retired = retireDeferred || toRetire === 0 ? 0 : (await tx.run(sqlFragment`DELETE FROM content_chunks c WHERE ${retire}`)).affectedRows;await tx.run(sqlFragment`UPDATE page_body_manifest SET staging_id = NULL WHERE page_id = ${input.pageId} AND staging_id = ${input.stagingId}::uuid`);const m = metaParams(input.meta);@@ -332,11 +351,15 @@ export async function setBodyStagingState(exec: SqlExecutor, id: string, state:/*** Garbage collection (spec 3.5). Roots: each segmented page's live generation,* every generation a page_versions row references, and staged rows of live- * stagings (`liveStagingIds`). Deletes chunk rows marked retired at or below- * the live generation (the flip deletes the rows it retires, so none are- * marked today), staged chunk rows no live staging owns, manifest rows outside every root, and unreferenced- * texts older than the grace window (a text a concurrent writer is- * referencing is row-locked by its FK check and skipped). With+ * stagings (`liveStagingIds`). Deletes staged chunk rows (above the page's+ * generation) no live staging owns, manifest rows outside every root, and+ * unreferenced texts older than the grace window and older than every live+ * staging of their source (a text a concurrent writer is referencing is+ * row-locked by its FK check or its refresh and skipped). A page-scoped sweep+ * (`pageId`) considers only the texts its own manifest deletes released, so+ * its cost is the page's, not the source's; the source-wide sweep collects the+ * rest. Rows of retired occurrences are deleted by the flip or, deferred, by+ * the projection job; until then no reader sees them. With* `expireStagings`, stagings past a deadline (and not request-held) become* `expired`, every non-live staging loses its parts, and terminal stagings* (committed, aborted, expired) are deleted once BODY_STAGING_HARD_MS has@@ -368,24 +391,30 @@ export async function sweepSegments(exec: SqlExecutor, opts: SegmentSweepOptionsAND ${stagingScope} AND s.id::text NOT IN ${liveStagingIds}`);}const { affectedRows: retiredChunksDeleted } = await exec.run(sqlFragment`DELETE FROM content_chunks c USING pages p- WHERE c.page_id = p.id AND ${pageScope} AND (- (c.retired_generation IS NOT NULL AND c.retired_generation <= p.body_generation)- OR (c.body_generation > p.body_generation AND NOT EXISTS (SELECT 1 FROM page_body_manifest m- WHERE m.page_id = c.page_id AND m.occurrence_id = c.occurrence_id AND m.staging_id::text IN ${liveStagingIds})))`);- const { affectedRows: stagedRowsDeleted } = await exec.run(sqlFragment`DELETE FROM page_body_manifest m USING pages p- WHERE m.page_id = p.id AND ${pageScope} AND m.staging_id IS NOT NULL AND m.staging_id::text NOT IN ${liveStagingIds}`);- const { affectedRows: closedRowsDeleted } = await exec.run(sqlFragment`DELETE FROM page_body_manifest m USING pages p+ WHERE c.page_id = p.id AND ${pageScope} AND c.body_generation IS NOT NULL AND c.body_generation > p.body_generation+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m+ WHERE m.page_id = c.page_id AND m.occurrence_id = c.occurrence_id AND m.staging_id::text IN ${liveStagingIds})`);+ const released = new Set<string>();+ const returning = opts.pageId !== undefined ? sqlFragment`RETURNING encode(m.sha256, 'hex') AS sha` : sqlFragment``;+ const { rows: stagedRows, affectedRows: stagedRowsDeleted } = await exec.run<{ sha: string }>(sqlFragment`DELETE FROM page_body_manifest m USING pages p+ WHERE m.page_id = p.id AND ${pageScope} AND m.staging_id IS NOT NULL AND m.staging_id::text NOT IN ${liveStagingIds} ${returning}`);+ const { rows: closedRows, affectedRows: closedRowsDeleted } = await exec.run<{ sha: string }>(sqlFragment`DELETE FROM page_body_manifest m USING pages pWHERE m.page_id = p.id AND ${pageScope} AND m.staging_id IS NULLAND NOT (p.body_storage = 'segmented' AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation))AND NOT EXISTS (SELECT 1 FROM page_versions v WHERE v.page_id = m.page_id AND v.body_generation >= m.gen_from- AND (m.gen_to IS NULL OR v.body_generation < m.gen_to))`);+ AND (m.gen_to IS NULL OR v.body_generation < m.gen_to)) ${returning}`);+ for (const row of [...stagedRows, ...closedRows]) released.add(row.sha);const graceMs = opts.graceMs ?? SEGMENT_TEXT_GC_GRACE_MS;- const textScope = opts.sourceId !== undefined ? sqlFragment`AND t.source_id = ${opts.sourceId}`- : opts.pageId !== undefined ? sqlFragment`AND t.source_id = (SELECT source_id FROM pages WHERE id = ${opts.pageId}::int)` : sqlFragment``;- const { affectedRows: textsDeleted } = await exec.run(sqlFragment`DELETE FROM page_segment_texts d+ const textScope = opts.pageId !== undefined+ ? sqlFragment`AND t.source_id = (SELECT source_id FROM pages WHERE id = ${opts.pageId}::int)+ AND t.sha256 = ANY(SELECT decode(h, 'hex') FROM unnest(${[...released]}::text[]) AS h)`+ : opts.sourceId !== undefined ? sqlFragment`AND t.source_id = ${opts.sourceId}` : sqlFragment``;+ const textsDeleted = opts.pageId !== undefined && released.size === 0 ? 0 : (await exec.run(sqlFragment`DELETE FROM page_segment_texts dWHERE (d.source_id, d.sha256) IN (SELECT t.source_id, t.sha256 FROM page_segment_texts tWHERE t.created_at < ${now} - (${graceMs}::bigint * interval '1 millisecond') ${textScope}AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id = t.source_id AND m.sha256 = t.sha256)- FOR UPDATE SKIP LOCKED)`);+ AND NOT EXISTS (SELECT 1 FROM page_body_stagings s WHERE s.source_id = t.source_id AND s.created_at <= t.created_at+ AND s.id::text IN ${liveStagingIds})+ FOR UPDATE SKIP LOCKED)`)).affectedRows;return { retiredChunksDeleted, manifestRowsDeleted: stagedRowsDeleted + closedRowsDeleted, textsDeleted, stagingsExpired };}diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.tsindex 6295c1bba3..d0f811952b 100644--- a/src/core/page-body/ingest.ts+++ b/src/core/page-body/ingest.ts@@ -340,7 +340,7 @@ export async function occurrencesWithoutChunks(engine: Pick<BrainEngine, 'executif (!rows.length) return [];const chunked = new Set((await engine.executeRaw<{ occurrence_id: number }>(`SELECT DISTINCT occurrence_id FROM content_chunks-- chunk-visibility-ok: write path; the generation predicate is explicit, at the generation the caller diffed against- WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND body_generation<=$3 AND retired_generation IS NULL`,+ WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND body_generation<=$3`,[pageId, rows.map(row => row.occurrenceId), generation])).map(row => Number(row.occurrence_id)));return rows.filter(row => !chunked.has(row.occurrenceId));}diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.tsindex a1f1c115e4..9c6709ad93 100644--- a/src/core/page-body/projection.ts+++ b/src/core/page-body/projection.ts@@ -43,11 +43,11 @@ async function retireStaleChunks(engine: Pick<BrainEngine, 'executeRaw' | 'kind'for (;;) {const rows = await engine.executeRaw<{ id: number }>(`DELETE FROM content_chunks cWHERE c.id IN (SELECT s.id FROM content_chunks s -- chunk-visibility-ok: retirement selects the rows the live generation does not hold- WHERE s.page_id=$1 AND s.retired_generation IS NULL+ WHERE s.page_id=$1AND (s.body_generation IS NULLOR (s.body_generation<=$2 AND NOT (s.occurrence_id=ANY($3::bigint[])))OR (s.body_generation<=$2 AND EXISTS (SELECT 1 FROM content_chunks n WHERE n.page_id=s.page_id AND n.occurrence_id=s.occurrence_id- AND n.retired_generation IS NULL AND n.body_generation>s.body_generation AND n.body_generation<=$2)))+ AND n.body_generation>s.body_generation AND n.body_generation<=$2)))LIMIT $4)RETURNING c.id`, [pageId, generation, live, DEFAULT_FLIP_RETIRE_MAX_ROWS]);retired += rows.length;diff --git a/src/core/page-body/segment-chunks.ts b/src/core/page-body/segment-chunks.tsindex c4a2dc9f0a..77deb9cfff 100644--- a/src/core/page-body/segment-chunks.ts+++ b/src/core/page-body/segment-chunks.ts@@ -61,7 +61,6 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segm}const maxTokens = opts.maxChunkTokens ?? resolveMaxChunkTokens();const raw = Buffer.from(segment.bytes).toString('utf8');- const segEnd = segment.byteStart + segment.bytes.length;const pieces: string[] = [];const map: MappedPart[] = [];const factsTexts: string[] = [];@@ -83,7 +82,7 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segmconst source = segment.region === 'truth' ? 'compiled_truth' : 'timeline';const chunks: SegmentChunk[] = [];const push = (c: Omit<SegmentChunk, 'local_ordinal'>) => chunks.push({ ...c, local_ordinal: chunks.length });- const wholeSegment = { raw_byte_start: segment.byteStart, raw_byte_end: segEnd };+ const wholeSegment = { raw_byte_start: 0, raw_byte_end: segment.bytes.length };if (projection.trim()) {for (const c of chunkProjectedText(projection, { maxTokens, spans: true })) {@@ -96,8 +95,8 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segmchunk_source: source,projected_byte_start: c.byte_start,projected_byte_end: c.byte_end,- raw_byte_start: segment.byteStart + rawAt(map, c.byte_start, false),- raw_byte_end: segment.byteStart + rawAt(map, c.byte_end, true),+ raw_byte_start: rawAt(map, c.byte_start, false),+ raw_byte_end: rawAt(map, c.byte_end, true),});}if (segment.region === 'truth') {diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.tsindex da88a38461..504545e53b 100644--- a/src/core/page-body/segmented-embedding.ts+++ b/src/core/page-body/segmented-embedding.ts@@ -16,7 +16,7 @@ import { embeddingInputHash, plainEmbeddingTier } from '../embedding-input-hash.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 { chunkGenerationFilter, currentTextProjectionFilter } from '../search/safe-chunks.ts';import { buildSegmentedProjection } from './projection.ts';import { isSegmentedPage } from './page-shape.ts';import type { BodyStorage } from './types.ts';@@ -81,7 +81,7 @@ export async function countSegmentedEmbedRows(engine: Pick<BrainEngine, 'executeconst [row] = await engine.executeRaw<{ total: number; stale: number }>(`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_id- WHERE cc.page_id = $1 AND ${chunkVisibleFilter('p', 'cc')}`, [pageId]);+ WHERE cc.page_id = $1 AND ${currentTextProjectionFilter('p')} AND ${chunkGenerationFilter('p', 'cc')}`, [pageId]);return { total: Number(row?.total ?? 0), stale: Number(row?.stale ?? 0) };}@@ -97,7 +97,8 @@ export async function listSegmentedStaleRows(engine: Pick<BrainEngine, 'executeR`SELECT cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks cc JOIN pages p ON p.id = cc.page_idWHERE 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')}+ AND ($4::bigint[] IS NULL OR cc.occurrence_id = ANY($4::bigint[]))+ AND ${currentTextProjectionFilter('p')} AND ${chunkGenerationFilter('p', 'cc')}ORDER BY cc.chunk_index DESC LIMIT $3`,[pageId, opts.beforeChunkIndex, opts.limit, opts.occurrenceIds ? [...opts.occurrenceIds] : null, opts.includeEmbedded ?? false]);}diff --git a/src/core/page-body/types.ts b/src/core/page-body/types.tsindex 01145e5b5e..582af8dddd 100644--- a/src/core/page-body/types.ts+++ b/src/core/page-body/types.ts@@ -68,7 +68,7 @@ export interface SegmentChunkInput extends Omit<ChunkInput, 'chunk_index'> {occurrence_id: number;/** Order of the chunk inside its occurrence; document order is (manifest byte_start, local_ordinal). */local_ordinal: number;- /** Stored-stream span (generation-bound). */+ /** Stored span relative to the occurrence's segment (add the manifest row's byte_start), so it survives a shift. */raw_byte_start: number;raw_byte_end: number;}diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.tsindex b0d5d7f5b0..2ceba1c5ab 100644--- a/src/core/persistence/segmented-apply.ts+++ b/src/core/persistence/segmented-apply.ts@@ -148,7 +148,10 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyI* (the caller's inline write fills it in the same transaction). The live* manifest rows close at the next generation, so versions that pin earlier* generations keep theirs; the page's segmented chunk rows are deleted here,- * before the inline write stages its chunks.+ * before the inline write stages its chunks. The write holds the page row FOR+ * UPDATE (lockPageKeys), so a chunk batch in flight (FOR KEY SHARE) commits+ * before this delete, and a later batch of a racing preparation refuses+ * (stageSegmentChunks: an inline page at the generation it targets).*/export async function demoteSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<void> {await tx.executeRaw(`UPDATE page_body_manifest SET gen_to=(SELECT body_generation+1 FROM pages WHERE id=$1)diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex c4cac01d35..6dec3293b6 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -346,9 +346,10 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- content_chunks columns, so fresh and upgraded brains share their ordinals.-- v244: projected_byte_start / projected_byte_end (a prose chunk's UTF-8-- span in its source's read projection) are added the same way.- -- v248: occurrence_id, local_ordinal, raw_byte_start/end, body_generation and- -- retired_generation (segmented-page chunks; NULL for inline pages) and- -- content_chunks_occurrence_idx are added the same way.+ -- v248: occurrence_id, local_ordinal, raw_byte_start/end and body_generation+ -- (segmented-page chunks; NULL for inline pages) and+ -- content_chunks_occurrence_idx are added the same way (v248's+ -- retired_generation is dropped by v249, which adds content_chunks_generation_idx).-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 284286cf7d..762ad27cf7 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 248;+export const LATEST_SCHEMA_VERSION = 249;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 6c14de5c01..cc3d1bb9a3 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -249,6 +249,7 @@ import { v245 } from './v245-page-search-vector-bounded-timeline.ts';import { v246 } from './v246-page-embedding-budget.ts';import { v247 } from './v247-page-extraction-state.ts';import { v248 } from './v248-segmented-page-storage.ts';+import { v249 } from './v249-segmented-chunk-gc-index.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -496,4 +497,5 @@ export const MIGRATIONS: Migration[] = [v246,v247,v248,+ v249,];diff --git a/src/core/schema-migrations/v248-segmented-page-storage.ts b/src/core/schema-migrations/v248-segmented-page-storage.tsindex 381d3604a3..8c90d73338 100644--- a/src/core/schema-migrations/v248-segmented-page-storage.ts+++ b/src/core/schema-migrations/v248-segmented-page-storage.ts@@ -110,7 +110,7 @@ export const v248: Migration = {// Search's visibility predicate reads the generation columns; without their statistics Postgres prices it at 0.5%// and vector search sorts every candidate instead of walking its HNSW index (projection-statistics.ts).if (engine.kind === 'postgres') {- await engine.runMigration(248, 'ANALYZE pages(body_generation); ANALYZE content_chunks(body_generation, retired_generation);');+ await engine.runMigration(248, 'ANALYZE pages(body_generation); ANALYZE content_chunks(body_generation);');}},};diff --git a/src/core/schema-migrations/v249-segmented-chunk-gc-index.ts b/src/core/schema-migrations/v249-segmented-chunk-gc-index.tsnew file mode 100644index 0000000000..717f1f390f--- /dev/null+++ b/src/core/schema-migrations/v249-segmented-chunk-gc-index.ts@@ -0,0 +1,33 @@+import type { Migration } from './types.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Segmented page storage (v248), follow-up:+// - content_chunks.retired_generation is dropped. Nothing writes it: the flip+// and the projection delete the rows they retire, and a row awaiting a+// deferred retirement is hidden by its occurrence's closed manifest range+// (chunkGenerationFilter), so the predicates that read it were always true.+// - content_chunks_generation_idx serves segment GC's staged-chunk delete+// (`c.body_generation IS NOT NULL AND c.body_generation > p.body_generation`,+// engine-sql/page-body.ts sweepSegments), which the resident maintenance+// worker runs about once a minute: without it every tick scanned the whole+// table, inline chunks included. Partial, so inline chunks (body_generation+// NULL) are not in it; built online (CONCURRENTLY on Postgres).+export const CONTENT_CHUNKS_GENERATION_INDEX = {+ name: 'content_chunks_generation_idx',+ table: 'content_chunks',+ sql: 'CREATE INDEX IF NOT EXISTS content_chunks_generation_idx ON content_chunks (page_id, body_generation) WHERE body_generation IS NOT NULL',+};++export const v249: Migration = {+ version: 249,+ name: 'segmented_chunk_gc_index',+ idempotent: true,+ transaction: false,+ sql: 'ALTER TABLE content_chunks DROP COLUMN IF EXISTS retired_generation;',+ handler: async engine => {+ await buildIndexOnline(engine, 249, CONTENT_CHUNKS_GENERATION_INDEX, { notice: migrationNotice });+ },+};diff --git a/src/core/search/keyword-chunk-match.ts b/src/core/search/keyword-chunk-match.tsindex bfbd698180..162c0ff7fe 100644--- a/src/core/search/keyword-chunk-match.ts+++ b/src/core/search/keyword-chunk-match.ts@@ -22,7 +22,7 @@ export function buildKeywordChunkMatch(ftsLang: string, excludePrivate: booleanreturn {// chunk-visibility-ok: the outer search statement applies buildVisibilityClause(..., { chunkAlias: 'cc' }) to the generation columns this subquery projectsfrom: `(- SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type, body_generation, retired_generation+ SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type, body_generation, occurrence_idFROM content_chunksWHERE search_vector @@ ${tsq} AND modality = 'text'OFFSET 0diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.tsindex 02a8df7e62..4f1c83a1b5 100644--- a/src/core/search/projection-statistics.ts+++ b/src/core/search/projection-statistics.ts@@ -56,7 +56,7 @@ export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'exec*/export const SEARCH_STATISTICS_COLUMNS = {pages: ['text_projection_revision', 'knowledge_revision', 'deleted_at', 'source_id', 'type', 'slug', 'body_generation'],- content_chunks: ['model', 'modality', 'page_id', 'body_generation', 'retired_generation'],+ content_chunks: ['model', 'modality', 'page_id', 'body_generation'],} as const;/**diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.tsindex 40756d5c4b..a96efe9058 100644--- a/src/core/search/safe-chunks.ts+++ b/src/core/search/safe-chunks.ts@@ -45,25 +45,36 @@ export function currentTextProjectionFilter(alias: string): string {}/**- * Wave B: the chunk row belongs to its page's live body generation. Staged rows- * (`body_generation` above the page's) and retired rows are invisible; every- * inline-page row (`body_generation IS NULL`) passes. Row predicate, no join.+ * Wave B: the chunk row belongs to its page's live body: an inline row+ * (`body_generation IS NULL`) of a page that is not segmented, or a segmented+ * row at or below the page's generation whose occurrence has a live manifest+ * row. Staged rows (above the page's generation), rows of retired occurrences+ * (closed by a flip or a demotion, deleted later when the flip deferred their+ * retirement) and rows of a preparation that never published are invisible+ * whether or not they were deleted yet. The manifest probe is one primary-key+ * lookup per segmented row; `page` must expose `body_storage` and `body_generation`.*/export function chunkGenerationFilter(page: string, chunk: string): string {- return `(${chunk}.body_generation IS NULL+ return `((${chunk}.body_generation IS NULL AND ${page}.body_storage <> 'segmented')OR (${chunk}.body_generation <= ${page}.body_generation- AND (${chunk}.retired_generation IS NULL OR ${chunk}.retired_generation > ${page}.body_generation)))`;+ AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = ${chunk}.page_id AND lm.occurrence_id = ${chunk}.occurrence_id+ AND lm.staging_id IS NULL AND lm.gen_from <= ${page}.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > ${page}.body_generation))))`;}-/** `chunkGenerationFilter` for a statement that has no page row joined: inline rows pass without the page lookup. */+/** `chunkGenerationFilter` for a statement that has no page row joined. */export function chunkGenerationProbe(chunk: string): string {- return `(${chunk}.body_generation IS NULL- OR EXISTS (SELECT 1 FROM pages gp WHERE gp.id = ${chunk}.page_id AND ${chunkGenerationFilter('gp', chunk)}))`;+ return `EXISTS (SELECT 1 FROM pages gp WHERE gp.id = ${chunk}.page_id AND ${chunkGenerationFilter('gp', chunk)})`;}-/** Search-facing chunk visibility: the current text projection and the live body generation. */+/**+ * Search-facing chunk visibility: the current text projection and the live body generation. A sealed page holds no+ * rows of a retired occurrence (the flip deletes them in its transaction, or leaves the page unsealed until the+ * projection job has), so the row predicate needs no manifest probe, whose per-row cost moved vector search off its+ * HNSW plan (test/e2e/vector-chunk-statistics-postgres.test.ts).+ */export function chunkVisibleFilter(page: string, chunk: string): string {- return `(${currentTextProjectionFilter(page)} AND ${chunkGenerationFilter(page, chunk)})`;+ return `(${currentTextProjectionFilter(page)}+ AND (${chunk}.body_generation IS NULL OR ${chunk}.body_generation <= ${page}.body_generation))`;}/**diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.tsindex e57993fdc7..6525534775 100644--- a/src/core/search/title-statement.ts+++ b/src/core/search/title-statement.ts@@ -107,7 +107,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undconst sql = `WITH top_pages AS (SELECT p.slug, p.id AS page_id, p.title, p.type, p.source_id,- p.effective_date, p.effective_date_source, p.updated_at, p.body_generation,+ p.effective_date, p.effective_date_source, p.updated_at, p.body_storage, p.body_generation,(lower(btrim(p.title, ' "''' || chr(160))) = $2) AS exact_title,${rankSql} * ${sourceFactorCase} AS scoreFROM pages pdiff --git a/src/schema.sql b/src/schema.sqlindex 8fdcf388f2..092f137dcd 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -342,9 +342,10 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- content_chunks columns, so fresh and upgraded brains share their ordinals.-- v244: projected_byte_start / projected_byte_end (a prose chunk's UTF-8-- span in its source's read projection) are added the same way.- -- v248: occurrence_id, local_ordinal, raw_byte_start/end, body_generation and- -- retired_generation (segmented-page chunks; NULL for inline pages) and- -- content_chunks_occurrence_idx are added the same way.+ -- v248: occurrence_id, local_ordinal, raw_byte_start/end and body_generation+ -- (segmented-page chunks; NULL for inline pages) and+ -- content_chunks_occurrence_idx are added the same way (v248's+ -- retired_generation is dropped by v249, which adds content_chunks_generation_idx).-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,diff --git a/test/e2e/keyword-arm-ranking-postgres.test.ts b/test/e2e/keyword-arm-ranking-postgres.test.tsindex e143171395..00d2662727 100644--- a/test/e2e/keyword-arm-ranking-postgres.test.ts+++ b/test/e2e/keyword-arm-ranking-postgres.test.ts@@ -64,7 +64,7 @@ describe('keyword arm plan (postgres)', () => {test(`\`${query}\` with excludePrivate runs the full-text match inside the OFFSET 0 subquery`, async () => {const { sql, params, rows } = await capturedKeywordStatement(query, true);expect(rows).toBeGreaterThan(0);- expect(sql).toMatch(/FROM \(\s*SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type, body_generation, retired_generation\s+FROM content_chunks\s+WHERE search_vector @@ websearch_to_tsquery\('[a-z_]+', \$1\) AND modality = 'text'\s+OFFSET 0\s*\) cc\s+JOIN pages p/);+ expect(sql).toMatch(/FROM \(\s*SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type, body_generation, occurrence_id\s+FROM content_chunks\s+WHERE search_vector @@ websearch_to_tsquery\('[a-z_]+', \$1\) AND modality = 'text'\s+OFFSET 0\s*\) cc\s+JOIN pages p/);expect(sql).not.toMatch(/cc\.search_vector @@/);const plan = (await engine.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN ${sql}`, params)).map((r) => r['QUERY PLAN']).join('\n');expect(plan).toContain('content_chunks');diff --git a/test/e2e/segmented-storage-statistics-postgres.test.ts b/test/e2e/segmented-storage-statistics-postgres.test.tsindex 511dd0415e..841e38ab9d 100644--- a/test/e2e/segmented-storage-statistics-postgres.test.ts+++ b/test/e2e/segmented-storage-statistics-postgres.test.ts@@ -1,7 +1,7 @@/*** Wave B: migration v248 leaves the search statistics complete on an upgraded* Postgres brain. Search's chunk visibility predicate reads- * pages.body_generation and content_chunks.body_generation/retired_generation;+ * pages.body_generation and content_chunks.body_generation;* columns added by ALTER TABLE have no pg_stats rows until ANALYZE, and* without them vector search drops its HNSW plan* (test/e2e/vector-chunk-statistics-postgres.test.ts).@@ -15,7 +15,7 @@ import { missingSearchStatistics } from '../../src/core/search/projection-statisimport { v248 } from '../../src/core/schema-migrations/v248-segmented-page-storage.ts';const d = hasDatabase() ? describe : describe.skip;-const GENERATION_COLUMNS = ['pages.body_generation', 'content_chunks.body_generation', 'content_chunks.retired_generation'];+const GENERATION_COLUMNS = ['pages.body_generation', 'content_chunks.body_generation'];d('v248 search statistics on Postgres', () => {beforeAll(async () => {@@ -29,7 +29,7 @@ d('v248 search statistics on Postgres', () => {await engine.executeRaw(`DELETE FROM pg_statistic s USING pg_attribute aWHERE a.attrelid = s.starelid AND a.attnum = s.staattnumAND ((a.attrelid = 'pages'::regclass AND a.attname = 'body_generation')- OR (a.attrelid = 'content_chunks'::regclass AND a.attname IN ('body_generation', 'retired_generation')))`);+ OR (a.attrelid = 'content_chunks'::regclass AND a.attname = 'body_generation'))`);await engine.executeRaw("UPDATE pg_class SET reltuples = 5000 WHERE oid IN ('pages'::regclass, 'content_chunks'::regclass)");}, 60_000);afterAll(async () => { await teardownDB(); });diff --git a/test/engine-sql-page-body.test.ts b/test/engine-sql-page-body.test.tsindex 7252152fc7..19a9901dfe 100644--- a/test/engine-sql-page-body.test.ts+++ b/test/engine-sql-page-body.test.ts@@ -32,8 +32,8 @@ async function pageRow(pageId: number) {}async function chunkRows(pageId: number) {- return engine.executeRaw<{ chunk_index: number; occurrence_id: number | null; body_generation: number | null; retired_generation: number | null; chunk_text: string }>(- `SELECT chunk_index, occurrence_id::int AS occurrence_id, body_generation::int AS body_generation, retired_generation::int AS retired_generation, chunk_text+ return engine.executeRaw<{ chunk_index: number; occurrence_id: number | null; body_generation: number | null; chunk_text: string }>(+ `SELECT chunk_index, occurrence_id::int AS occurrence_id, body_generation::int AS body_generation, chunk_textFROM content_chunks WHERE page_id = $1 ORDER BY chunk_index`, [pageId]);}@@ -146,7 +146,7 @@ describe('manifest and flip', () => {{ closeOccurrences: page.occurrences, retireChunkOccurrences: page.occurrences, retireMaxRows: 2 })));expect(deferred).toEqual({ retiredChunks: 0, retireDeferred: true });const rows = await chunkRows(page.pageId);- expect(rows.filter(r => r.body_generation === 1).every(r => r.retired_generation === null)).toBe(true);+ expect(rows.filter(r => r.body_generation === 1).map(r => r.occurrence_id).sort()).toEqual([...page.occurrences].sort());expect((await pageRow(page.pageId)).body_generation).toBe(2);const next = [segmentText('# A3\na\n')];@@ -155,7 +155,7 @@ describe('manifest and flip', () => {{ closeOccurrences: staged.occurrences, retireChunkOccurrences: [...page.occurrences, ...staged.occurrences], retireMaxRows: 6 }));expect(retired).toEqual({ retiredChunks: 6, retireDeferred: false });const after = await chunkRows(page.pageId);- expect(after.map(r => [r.occurrence_id, r.retired_generation])).toEqual(staged3.occurrences.map(occurrence => [occurrence, null]));+ expect(after.map(r => r.occurrence_id)).toEqual(staged3.occurrences);});test('two preparers at one generation: the loser\'s staged chunk rows are deleted with the winner\'s flip', async () => {@@ -167,7 +167,7 @@ describe('manifest and flip', () => {{ closeOccurrences: page.occurrences, retireChunkOccurrences: page.occurrences }));expect(result).toEqual({ retiredChunks: 2, retireDeferred: false });const rows = await chunkRows(page.pageId);- expect(rows.map(r => [r.occurrence_id, r.retired_generation])).toEqual([[winner.occurrences[0]!, null]]);+ expect(rows.map(r => r.occurrence_id)).toEqual([winner.occurrences[0]!]);expect((await engine.readManifest(page.pageId)).map(r => r.occurrenceId)).toEqual(winner.occurrences);});@@ -180,7 +180,7 @@ describe('manifest and flip', () => {const result = await engine.flipBodyGeneration(flipInput(pageId, 0, staged.stagingId, t, { retireInlineChunks: true }));expect(result).toEqual({ retiredChunks: 1, retireDeferred: false });const rows = await chunkRows(pageId);- expect(rows.map(r => [r.chunk_index, r.body_generation, r.retired_generation])).toEqual([[1, 1, null]]);+ expect(rows.map(r => [r.chunk_index, r.body_generation])).toEqual([[1, 1]]);const page = await pageRow(pageId);expect([page.body_storage, page.compiled_truth, page.timeline, page.body_generation]).toEqual(['segmented', null, null, 1]);});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 82f1cbcc57..930b2e4e48 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -954,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",@@ -1632,8 +1633,7 @@"30 local_ordinal integer/int4 NULL","31 raw_byte_start bigint/int8 NULL","32 raw_byte_end bigint/int8 NULL",- "33 body_generation bigint/int8 NULL",- "34 retired_generation bigint/int8 NULL"+ "33 body_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 7c88a44e13..60a478a750 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -954,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",@@ -1632,8 +1633,7 @@"30 local_ordinal integer/int4 NULL","31 raw_byte_start bigint/int8 NULL","32 raw_byte_end bigint/int8 NULL",- "33 body_generation bigint/int8 NULL",- "34 retired_generation bigint/int8 NULL"+ "33 body_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 603bf7eecf..581c17f53c 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -954,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",@@ -1628,8 +1629,7 @@"30 local_ordinal integer/int4 NULL","31 raw_byte_start bigint/int8 NULL","32 raw_byte_end bigint/int8 NULL",- "33 body_generation bigint/int8 NULL",- "34 retired_generation bigint/int8 NULL"+ "33 body_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 71cee22581..23c1cbd2c5 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -955,6 +955,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",@@ -1633,8 +1634,7 @@"30 local_ordinal integer/int4 NULL","31 raw_byte_start bigint/int8 NULL","32 raw_byte_end bigint/int8 NULL",- "33 body_generation bigint/int8 NULL",- "34 retired_generation bigint/int8 NULL"+ "33 body_generation bigint/int8 NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 8a70a15c5f..04f0eaebd0 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -955,6 +955,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",@@ -1633,8 +1634,7 @@"30 local_ordinal integer/int4 NULL","31 raw_byte_start bigint/int8 NULL","32 raw_byte_end bigint/int8 NULL",- "33 body_generation bigint/int8 NULL",- "34 retired_generation bigint/int8 NULL"+ "33 body_generation bigint/int8 NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex ad3d22f791..292e7a40c2 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -955,6 +955,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",@@ -1629,8 +1630,7 @@"30 local_ordinal integer/int4 NULL","31 raw_byte_start bigint/int8 NULL","32 raw_byte_end bigint/int8 NULL",- "33 body_generation bigint/int8 NULL",- "34 retired_generation bigint/int8 NULL"+ "33 body_generation bigint/int8 NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex f2d10a1b02..d95de00131 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 243,+ "count": 244,"gaps": [17,18,@@ -11,6 +11,7 @@"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0","BOUNDED_TIMELINE_CHECKPOINT": "385c4da3e28732343148795d6e9a86670813a7a7cfa1e52f8a5bb494680a3c0d","CHECKPOINT": "3c6ff909363c4ba1c9d730e748654ab90aa07549ddf4bf36b8f93c5f4ea3680b",+ "CONTENT_CHUNKS_GENERATION_INDEX": "c434b3a4acdad499cf3b9f170d9f9967b8e3e8218c829db99f3ecba3b53c8b5d","CONTENT_CHUNKS_OCCURRENCE_INDEX": "7b692ba777b30399ab5a3b100eb40b3b9d1b3fb2322dc4dc808ba8a4d667912c","FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c","FACT_PURGES_SUBJECT_INDEX": "f4fba07082f2e26da3fa51b0b689f3fe78a3d09afd20c1924dbc2fbe6b1560f1",@@ -57,7 +58,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 248,+ "latest": 249,"records": [{"handler": {@@ -3776,7 +3777,7 @@"migrationNotice","quietMigrationNotices"],- "sha256": "f534fe8c1c2a21a072644ff97155d6298e87245cf293fbf25b94c0713f6f4a66"+ "sha256": "2fb35d2d13c92c07dfd2f002db579956d1fea8869a908210f6668911fa6ddd89"},"idempotent": true,"name": "segmented_page_storage",@@ -3797,6 +3798,29 @@"transaction": false,"verify": "absent","version": 248+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "CONTENT_CHUNKS_GENERATION_INDEX",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "migrationNotice",+ "quietMigrationNotices"+ ],+ "sha256": "04311e56cedf0fa4c64828548231ceda89ed68f6e2038d7ece7a907d3e3c413f"+ },+ "idempotent": true,+ "name": "segmented_chunk_gc_index",+ "sql": {+ "length": 68,+ "sha256": "004ba9dd1ed2cdc010622bc58689e5bf912d937212ec3b8b83307d9f6824e1c9"+ },+ "sqlFor": "absent",+ "transaction": false,+ "verify": "absent",+ "version": 249}],"versions": [@@ -4042,7 +4066,8 @@245,246,247,- 248+ 248,+ 249]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 9e979ffa19..f583ed6fcd 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -954,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_generation_idx": "CREATE INDEX content_chunks_generation_idx ON public.content_chunks USING btree (page_id, body_generation) WHERE (body_generation IS NOT NULL)","content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)",@@ -1632,8 +1633,7 @@"30 local_ordinal integer/int4 NULL","31 raw_byte_start bigint/int8 NULL","32 raw_byte_end bigint/int8 NULL",- "33 body_generation bigint/int8 NULL",- "34 retired_generation bigint/int8 NULL"+ "33 body_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex d226b48336..dd1f89c8e8 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -33,8 +33,8 @@{"lane": "pool","params": [],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE 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')",- "textSha256": "72fc9180f5f7ce6a316c0022dfa993e39cdd7c6e6be65815f5fd69ce74d46682"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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')",+ "textSha256": "364d46feaba0272a76622f1b3a06ce9d06af491748c4983689e0b3dc15f4fa8f"}],"signature+includeNullSignature": [@@ -49,8 +49,8 @@"params": ["string"],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE 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 OR p.embedding_signature IS NULL OR p.embedding_signature <> $1) 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')",- "textSha256": "bea74a86af17ff193a99597f7b54c89d6963f82d2ab451e438008894a221ea01"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1) 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')",+ "textSha256": "f981130d0cfc273d84f0765edd8dac854ca41f771e2a79a750ced186b410ef1e"}],"signature+sourceId": [@@ -66,8 +66,8 @@"string","string"],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE 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 OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) 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') AND p.source_id = $2",- "textSha256": "ed7eb47065da6a0065ed0a1879f5dd34b5844ccac708c7f18eefa0bb4f4bca2c"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) 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') AND p.source_id = $2",+ "textSha256": "2223d700a8bf30585b9a816f717220c6b66fa0a78c87c28fe3f5d4ba1313a682"}]},@@ -98,8 +98,8 @@"string","string"],- "sql": "SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks FROM ( SELECT count(*) AS n, max(cc.chunk_index) AS max_index, bool_or(cc.body_generation IS NOT NULL) AS segmented FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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)))) GROUP BY cc.page_id ) t",- "textSha256": "c27d5c843e714448bfc731469bde76e859efae4d143d9f03d17b38dd80573d71"+ "sql": "SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks FROM ( SELECT count(*) AS n, max(cc.chunk_index) AS max_index, bool_or(cc.body_generation IS NOT NULL) AS segmented FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) GROUP BY cc.page_id ) t",+ "textSha256": "c29af72128a53d14d0d77ce09564344c7df8b84404c24ef22980a0181983359b"},{"lane": "pool",@@ -109,8 +109,8 @@"number","number"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "9ffec5c95730a9b938458ddd232c1908a3b4141e8011b63bdd5646af1537f798"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND cc.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "dfe772afa8fb395d035e32b1483c97558a7121379ee8818703d5bcdffea2717b"}],"sourceIds+excludePrivate": [@@ -126,8 +126,8 @@"string","array<string>"],- "sql": "SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks FROM ( SELECT count(*) AS n, max(cc.chunk_index) AS max_index, bool_or(cc.body_generation IS NOT NULL) AS segmented FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 p.chunker_version >= 4 GROUP BY cc.page_id ) t",- "textSha256": "8d92f85ecb53d999f9c06185348c5e6039891fc535bfdc5765faa927d83a4ccc"+ "sql": "SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks FROM ( SELECT count(*) AS n, max(cc.chunk_index) AS max_index, bool_or(cc.body_generation IS NOT NULL) AS segmented FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND p.chunker_version >= 4 GROUP BY cc.page_id ) t",+ "textSha256": "84e412640a83aa1625ba2e885e63b55272adf5ef6f166d2d7f687ef3d84d5b8c"},{"lane": "pool",@@ -137,8 +137,8 @@"number","number"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 p.chunker_version >= 4 AND cc.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "583b4a5a29b83fa0ce61bf78fb5edf661b931efc9b27b77a6da96bdd459687e2"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND p.chunker_version >= 4 AND cc.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "c50ec7ff7d0abd055b95eb8330537853fdc5f6636915ea977fd90507710c7eb5"}]},@@ -156,8 +156,8 @@"array<string>","number"],- "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($7::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $8 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",- "textSha256": "64aa9e142a90edbb495f64db0e2075740779bf7568da6bd32ecc15fb1cb7dd31"+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_storage, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND ((cc.body_generation IS NULL AND a.body_storage <> 'segmented') OR (cc.body_generation <= a.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= a.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > a.body_generation)))) AND cc.chunk_source = ANY($7::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $8 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND ((c2.body_generation IS NULL AND a.body_storage <> 'segmented') OR (c2.body_generation <= a.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = c2.page_id AND lm.occurrence_id = c2.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= a.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > a.body_generation))))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",+ "textSha256": "f876a92a73c341ef0b426136036f578ca3defd6a8288bc6344d050de1d0c5621"}],"scopedPrivateSafe": [@@ -174,8 +174,8 @@"array<string>","number"],- "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND p.chunker_version >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",- "textSha256": "4c57a54e1bc0845f89172e2e853c4cc7017a8301e026d48409e37585a162893a"+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_storage, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND p.chunker_version >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND ((cc.body_generation IS NULL AND a.body_storage <> 'segmented') OR (cc.body_generation <= a.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= a.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > a.body_generation)))) AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND ((c2.body_generation IS NULL AND a.body_storage <> 'segmented') OR (c2.body_generation <= a.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = c2.page_id AND lm.occurrence_id = c2.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= a.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > a.body_generation))))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",+ "textSha256": "b6c77830c75664f1f7651aba42322991d47b6de34e80884f7d3889aeedd3080c"}]},@@ -193,8 +193,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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)))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "de7ae4f65eaf49c0155218ea144912fef438e7bff158f30cd69735c0fa1ab842"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "50b5504e4acfcff7895290a159757f56e42252349975c3d87e427d61290ab446"}],"excludePrivate": [@@ -210,8 +210,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 p.chunker_version >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "2f7945ccfbbcdab7d706f431084e30e391762317a376440ee40862d383d6ca9b"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND p.chunker_version >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "4004a958873903d05650b011ae77db9db3f3a9b515c8567ac111b5aa0158bc58"}],"includeEmbedding": [@@ -227,8 +227,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null , cc.\"embedding\" AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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)))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "cd87807ada79ced2ee3e26e7bfc8ab0559a6f80437d323cb8bdbb8c56f6ff414"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null , cc.\"embedding\" AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "f25b0af8fc1b229c537e242c5eddfa3d9254c2dc44b338901b4edf8510f68c01"}],"includeUnsealed": [@@ -244,8 +244,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 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))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "6408a79073afbcd2ae068c86216f96bf1079308a8d9235581786433d596a63f3"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "8dbfad8ab65f27148efa3f52af807931b400b0a8a03a25feefd9a0a2372ccace"}],"requireSafeChunks": [@@ -261,8 +261,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 p.chunker_version >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "d17e7a0e15884ff4fa1c4ea28cd5230740f82e38626bbb60df65014036300e1c"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND p.chunker_version >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "41ce26c59b8099481552ac41ad14890c771fde32556df938ec6cbb95b8af984c"}],"sourceIds": [@@ -278,8 +278,8 @@"string","array<string>"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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)))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",- "textSha256": "2cf03b8dc230619cd7ad5a9ac11b1d3306b973e89627d84408c803452166053e"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "1d6acb2f10cc903eae3af683074ab9616b8113db68ed99a4433cbe997f63401d"}]},@@ -290,8 +290,8 @@"params": ["string"],- "sql": "SELECT cc.* FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 p.slug = $1 ORDER BY cc.chunk_index",- "textSha256": "897164893af24138f37b51ef61ca0600647ff6b13b4f0101ce110e178fb01f09"+ "sql": "SELECT cc.* FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND p.slug = $1 ORDER BY cc.chunk_index",+ "textSha256": "f4117c83ef5df061c6d44baff7af14a9a7dc16b468560a1338f3141c24b546d7"}],"sourceId+includeUnsealed": [@@ -301,8 +301,8 @@"string","string"],- "sql": "SELECT cc.* 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.slug = $1 AND p.source_id = $2 ORDER BY cc.chunk_index",- "textSha256": "ab3935a8dead2d558acf4767af5e6a8bee1f3ec71dfedfb1b1cf82a3d4317c3e"+ "sql": "SELECT cc.* FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.slug = $1 AND p.source_id = $2 ORDER BY cc.chunk_index",+ "textSha256": "adc49284828f9118caaf5395e3e2d1d3db288dd4c387fa4f27a16a70fbe95c83"}]},@@ -313,8 +313,8 @@"params": ["array<number>"],- "sql": "SELECT cc.id, vector_send(cc.\"embedding_voyage\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding_voyage\" IS NOT NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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))))",- "textSha256": "a23ecb0b4221ed9ee3ae4c9a5a4e58e8fe5df5f454d015ac4e715cc796b3889d"+ "sql": "SELECT cc.id, vector_send(cc.\"embedding_voyage\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding_voyage\" IS NOT NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation))",+ "textSha256": "67cbaa36ba5cf2f6528734247df1db73005371251b757ef6fc5a5efdcd756dc3"}],"default": [@@ -323,8 +323,8 @@"params": ["array<number>"],- "sql": "SELECT cc.id, vector_send(cc.\"embedding\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding\" IS NOT NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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))))",- "textSha256": "899d57095ec8c255e6e5175bfdd546fcfbbffac3b235f40116e5e845ec8c928b"+ "sql": "SELECT cc.id, vector_send(cc.\"embedding\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding\" IS NOT NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation))",+ "textSha256": "7e78d658816597146af750ec180ac76fb8f819e5e636ef50a93d2cf2ca76d532"}]},@@ -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 <> '' 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"+ "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 AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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 AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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": "19a968efbb91cff8f1f0fab46d7e0e15a0ce1b533e8f1ea39a1ed524a0c89e94"}],"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 <> '' 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"+ "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 AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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 AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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": "1e8153643b4495c6800096c412f4c53fca3f3d645d8c435407c93a4ed1925645"}]},@@ -551,8 +551,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at 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') 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.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",- "textSha256": "3098f5d265a6f1cf3e6f9dc91a68c3c19c1e00b4b0ff84bcec4f5efc08ac0919"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at 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') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",+ "textSha256": "a41e226d810b74525060ad936914de93d6804badc46e0644770a8bd18991ecc3"}],"sourceId": [@@ -570,8 +570,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 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') 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.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",- "textSha256": "62b87452bcd52effbcc44cd2167ce4c7ff9729c204c0fc9c585789650f79d0fb"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 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') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",+ "textSha256": "dee70bea35251fcb642d0f4b369ed207bd025becd2131a24bbaa3fa202a35c50"}],"updated_desc": [@@ -586,8 +586,8 @@"params": ["number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at 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') 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))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",- "textSha256": "da46de54a47d6bbdc155f72c47b812e48d1d9b78f1baf4db267ffd2d7eca2ff4"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at 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') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",+ "textSha256": "2060e059f461a956597a2035b6c7c08f7401e16d069c012e5bf1f7346c6b3f6c"}],"updated_desc+cursor": [@@ -608,8 +608,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at 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') 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 ( p.updated_at < $1::timestamptz OR (p.updated_at = $2::timestamptz AND p.id > $3) OR (p.updated_at = $4::timestamptz AND p.id = $5 AND cc.chunk_index > $6) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $7",- "textSha256": "6801846f3611cd0d015651a3c60151b2a03a7bc33097ad3b4c1db1774454abcc"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at 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') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $1::timestamptz OR (p.updated_at = $2::timestamptz AND p.id > $3) OR (p.updated_at = $4::timestamptz AND p.id = $5 AND cc.chunk_index > $6) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $7",+ "textSha256": "bcbb4c6e7c3227d0f3e34bee28e5f2004233194685cabb7376dfa53d020a396c"}],"updated_desc+sourceId": [@@ -625,8 +625,8 @@"string","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 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') 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))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",- "textSha256": "4b3e7be6b2d68a6adb7daef9cf3a9f0f636157dc6d8f441f60412ec864c3ed80"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 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') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",+ "textSha256": "d9dc727d9dfb4c3f4d209704f69b08eba3a03ba85b046f6e8ae3cfe3ddd5595e"}],"updated_desc+sourceId+cursor": [@@ -648,8 +648,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 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') 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 ( p.updated_at < $2::timestamptz OR (p.updated_at = $3::timestamptz AND p.id > $4) OR (p.updated_at = $5::timestamptz AND p.id = $6 AND cc.chunk_index > $7) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $8",- "textSha256": "5efa6b07f9d7ed7a59552bc5698e4e4d8faff347762015dd1491517474673649"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 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') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $2::timestamptz OR (p.updated_at = $3::timestamptz AND p.id > $4) OR (p.updated_at = $5::timestamptz AND p.id = $6 AND cc.chunk_index > $7) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $8",+ "textSha256": "b603cf513a4145b8638be743a1ce107692fa9c6bf995524aa30c63d650f119e1"}]},@@ -666,8 +666,8 @@"params": ["number"],- "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT 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, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE 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)))) s GROUP BY s.state",- "textSha256": "d747198df5c4ed086cc774f7ac81461f5d576c8adf37e37d97e72491daa328d8"+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT 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 AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation))))) s GROUP BY s.state",+ "textSha256": "5d9d1c9bedc77e5af44f0ab330a0e3c15a670341bfd55f6c7269ea5f44997b80"},{"lane": "pool",@@ -695,8 +695,8 @@"number","array<string>"],- "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT 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, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE 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 p.source_id = ANY($2::text[])) s GROUP BY s.state",- "textSha256": "bc6f020b1cd852a8feca47e968b2520ce8040382b08874200543936c2a98c607"+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT 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 AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[])) s GROUP BY s.state",+ "textSha256": "567c13023ca4f921061804c280d572a55dac61142d915c6bb48c0acbdc727713"},{"lane": "pool",@@ -757,8 +757,8 @@{"lane": "pool","params": [],- "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE 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')",- "textSha256": "7def567d09677a18a09f063043c393c9c8f7aa66bc5981866e65174914a81138"+ "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > 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')",+ "textSha256": "6b90c75b7ee5221cf0bbdab5ecaf31504172286e69501d9fe1547d2e58a3ad9d"}],"signature": [@@ -773,8 +773,8 @@"params": ["string"],- "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE 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 OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) 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')",- "textSha256": "a590a7f68a81dd3d520770d26707790ce2a365a529bbb8b8aa2d8225e84f9efd"+ "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) 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')",+ "textSha256": "a6db634edced27d38165b7232a396fd91c49e8f71b24c596d36c26ece1810d66"}]},diff --git a/test/fixtures/goldens/sql-text/cjk-search.json b/test/fixtures/goldens/sql-text/cjk-search.jsonindex e5feaf7fca..9060abc121 100644--- a/test/fixtures/goldens/sql-text/cjk-search.json+++ b/test/fixtures/goldens/sql-text/cjk-search.json@@ -59,8 +59,8 @@"number","number"],- "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",- "textSha256": "3d0622c80f2290ca631148a81df192c733fb226465b163c91b34b9a0816b4899"+ "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",+ "textSha256": "19f4c98c6cbcd6e50e16ef9824423c39334cb4b68bc4e057d850dd1c1422a7e0"},{"event": "commit",@@ -125,8 +125,8 @@"number","number"],- "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND cc.chunk_source = 'compiled_truth' AND p.type = $10 AND p.source_id = ANY($11::text[]) AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $12 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $13 OFFSET $14",- "textSha256": "7d86a89584c4be40109f304d309195d4f7d9aa45df079fe391ba05555f089b5d"+ "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND cc.chunk_source = 'compiled_truth' AND p.type = $10 AND p.source_id = ANY($11::text[]) AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $12 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $13 OFFSET $14",+ "textSha256": "31ac33411b3a569999e4b1c643d88d381c4ecad49c56dcd772335baebc27fb55"},{"event": "commit",@@ -175,8 +175,8 @@"number","number"],- "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 OFFSET $11",- "textSha256": "381368cdd0079fd647f6603f9bdbd7a1a18378d19774c82d1ddd5ce43ff49446"+ "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 OFFSET $11",+ "textSha256": "80fa25aa4c73070ddeaf034ab33184847d1b8a91203b9743a959013532e9f5ed"},{"event": "commit",@@ -224,8 +224,8 @@"number","number"],- "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND p.source_id = $10 AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE 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 NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",- "textSha256": "cff744e2ef5eb761a32372bd31a9839ee0838549781224a2c1f6d5cff32f14cf"+ "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND p.source_id = $10 AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR cc.body_generation <= p.body_generation)) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",+ "textSha256": "c1851c6f30af59f523fa02f8badedc034c39b866dadd9798fffa1c452fa2895b"},{"event": "commit",diff --git a/test/helpers/engine-sql-rollback-cases.ts b/test/helpers/engine-sql-rollback-cases.tsindex 5ff4993fdb..78d0e7f352 100644--- a/test/helpers/engine-sql-rollback-cases.ts+++ b/test/helpers/engine-sql-rollback-cases.ts@@ -447,7 +447,7 @@ export const ROLLBACK_CASES: RollbackCase[] = [[hexOf(ORPHAN_TEXT.sha256)]);},async write(tx) {- expect((await tx.sweepSegments({ pageId: await segmentedPageId(tx, SEGMENTED_SLUG) })).textsDeleted).toBeGreaterThanOrEqual(1);+ expect((await tx.sweepSegments({ sourceId: 'default' })).textsDeleted).toBeGreaterThanOrEqual(1);},observe: engine => segmentTextExists(engine, ORPHAN_TEXT),},diff --git a/test/helpers/segmented-chunks-fixture.ts b/test/helpers/segmented-chunks-fixture.tsindex a25fc1e914..77cbe520dc 100644--- a/test/helpers/segmented-chunks-fixture.ts+++ b/test/helpers/segmented-chunks-fixture.ts@@ -3,7 +3,8 @@* and chunk rows (raw SQL, no segmenter or flip), so chunk-visibility,* vector-reuse and version tests can put rows in exactly the generation* states they probe: live, staged (body_generation above the page's) and- * retired. The page is sealed as an inline page first, then its body columns+ * retired (rows of an occurrence whose manifest row is closed, not yet deleted:+ * a deferred retirement, whose page stays unsealed until they are). The page is sealed as an inline page first, then its body columns* are cleared the way a segmented row stores them (NULL bodies, body_bytes).*/import { createHash } from 'node:crypto';@@ -17,7 +18,6 @@ export interface FixtureChunk {chunkIndex?: number;/** First generation the row is part of; defaults to the occurrence's genFrom. */generation?: number;- retiredGeneration?: number | null;/** A unit vector seed: the row gets a vector with 1 at this dimension. */vector?: number;}@@ -48,6 +48,8 @@ export async function segmentPage(engine: BrainEngine, slug: string, opts: {title?: string;bodyBytes?: number;sourceId?: string;+ /** Leave the text projection unsealed, as a flip that deferred its retirement does (default sealed). */+ unsealed?: boolean;}): Promise<SegmentedFixture> {const sourceId = opts.sourceId ?? 'default';await engine.putPage(slug, { type: 'note', title: opts.title ?? slug, compiled_truth: 'Segmented fixture.', timeline: '', frontmatter: {} }, { sourceId });@@ -76,15 +78,15 @@ export async function segmentPage(engine: BrainEngine, slug: string, opts: {nextIndex = Math.max(nextIndex, chunkIndex) + 1;const vector = chunk.vector === undefined ? null : `[${(await unitVector(engine, chunk.vector)).join(',')}]`;const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, token_count,- occurrence_id, local_ordinal, body_generation, retired_generation, ${col.name}, model, embedded_at, embedded_text_hash)- VALUES ($1, $2, $3, 'compiled_truth', $4, $5, $6, $7, $8, $9::vector, $10, $11, $12) RETURNING id`,+ occurrence_id, local_ordinal, body_generation, ${col.name}, model, embedded_at, embedded_text_hash)+ VALUES ($1, $2, $3, 'compiled_truth', $4, $5, $6, $7, $8::vector, $9, $10, $11) RETURNING id`,[pageId, chunkIndex, chunk.text, Math.ceil(chunk.text.length / 4), occ.id, ordinal, chunk.generation ?? occ.genFrom,- chunk.retiredGeneration ?? null, vector, col.embeddingModel, vector ? new Date() : null,+ vector, col.embeddingModel, vector ? new Date() : null,vector ? createHash('md5').update(chunk.text).digest('hex') : null]);chunkIds.set(chunk.text, Number(row!.id));}}// Clearing the body and replacing the rows unseals the projection; the fixture's rows are the projection.- await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE id = $1', [pageId]);+ if (!opts.unsealed) await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE id = $1', [pageId]);return { pageId, chunkIds };}diff --git a/test/helpers/segmented-page-checks.ts b/test/helpers/segmented-page-checks.tsindex d1e6acba8a..c5f870a1d4 100644--- a/test/helpers/segmented-page-checks.ts+++ b/test/helpers/segmented-page-checks.ts@@ -5,6 +5,7 @@*/import type { BrainEngine } from '../../src/core/engine.ts';import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';+import { chunkGenerationFilter } from '../../src/core/search/safe-chunks.ts';import { contentHash } from '../../src/core/utils.ts';export interface SegmentedPageRow { id: number; body_storage: string; body_generation: number; content_hash: string; title: string; type: string;@@ -25,11 +26,11 @@ export async function reconstructedPage(engine: BrainEngine, slug: string, sourcreturn { page, body, hash: contentHash({ title: page.title, type: page.type, compiled_truth: body.compiled_truth, timeline: body.timeline, frontmatter: page.frontmatter, tags }) };}-/** Chunk rows of the live generation (not retired, not staged past the page's generation). */+/** Chunk rows of the live body (chunkGenerationFilter: not retired, not staged past the page's generation). */export async function visibleChunks(engine: BrainEngine, pageId: number): Promise<Array<{ occurrence_id: number | null; embedded: boolean }>> {const rows = await engine.executeRaw<{ occurrence_id: number | string | null; embedded: boolean }>(`SELECT c.occurrence_id, c.embedding IS NOT NULL AS embeddedFROM content_chunks c JOIN pages p ON p.id=c.page_id- WHERE c.page_id=$1 AND c.retired_generation IS NULL AND (c.body_generation IS NULL OR c.body_generation<=p.body_generation)`, [pageId]);+ WHERE c.page_id=$1 AND ${chunkGenerationFilter('p', 'c')}`, [pageId]);return rows.map(row => ({ occurrence_id: row.occurrence_id === null ? null : Number(row.occurrence_id), embedded: row.embedded }));}diff --git a/test/large-pages/chunk-visibility.test.ts b/test/large-pages/chunk-visibility.test.tsindex 67c2a8a5d7..438e54d28a 100644--- a/test/large-pages/chunk-visibility.test.ts+++ b/test/large-pages/chunk-visibility.test.ts@@ -2,9 +2,11 @@* Wave B chunk visibility (spec 4.2).** 1. Protects: a segmented page's staged rows (body_generation above the- * page's, an unpublished write) and retired rows (an old body) never reach- * keyword search, vector search, get_chunks, chunk windows or the embed- * sweep's stale selection; inline pages' rows are unaffected; get_chunks+ * page's, an unpublished write) and retired rows (an old body whose+ * deferred retirement has not deleted them yet; the page stays unsealed)+ * never reach keyword search, vector search, get_chunks, chunk windows or+ * the embed sweep's stale selection, and generation readers of the+ * unsealed page see only its live rows; inline pages' rows are unaffected; get_chunks* returns a segmented page in document order (manifest byte_start,* local_ordinal), paging by position.* 2. Fails when: a reader drops `chunkVisibleFilter` / `chunkGenerationFilter`@@ -21,6 +23,7 @@ import { segmentPage, unitVector, type SegmentedFixture } from '../helpers/segmeimport { testBackends } from '../helpers/test-backends.ts';const SLUG = 'notes/segmented-log';+const RETIRING = 'notes/segmented-retiring';const LIVE = ['zebrafish opening of the log', 'second live passage', 'later appended passage about herons'];for (const kind of testBackends()) {@@ -28,6 +31,7 @@ for (const kind of testBackends()) {let engine: BrainEngine;let close: () => Promise<void>;let fixture: SegmentedFixture;+ let retiring: SegmentedFixture;beforeAll(async () => {if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));@@ -47,18 +51,27 @@ for (const kind of testBackends()) {occurrences: [{ id: 20, byteStart: 4096, genFrom: 1, chunks: [{ text: LIVE[2]!, vector: 7, chunkIndex: 0 }] },{ id: 10, byteStart: 0, genFrom: 1, chunks: [{ text: LIVE[0]!, vector: 7, chunkIndex: 1 }, { text: LIVE[1]!, vector: 7, chunkIndex: 2 }] },- { id: 30, byteStart: 8192, genFrom: 1, genTo: 2, chunks: [{ text: 'retired quokka passage', vector: 9, retiredGeneration: 2 }] },{ id: 40, byteStart: 8192, genFrom: 3, chunks: [{ text: 'staged wombat passage', vector: 9 }, { text: 'staged stale wombat tail' }] },- { id: 50, byteStart: 12288, genFrom: 1, genTo: 2, chunks: [{ text: 'retired stale quokka tail', retiredGeneration: 2 }] },{ id: 60, byteStart: 12288, genFrom: 2, chunks: [{ text: 'live stale heron tail' }] },],});+ // A flip to generation 2 that deferred its retirement: occurrences 30 and 50 are closed, their rows not yet deleted.+ retiring = await segmentPage(engine, RETIRING, {+ generation: 2,+ unsealed: true,+ occurrences: [+ { id: 70, byteStart: 0, genFrom: 1, chunks: [{ text: 'kept passage of the retiring page', vector: 7 }] },+ { id: 30, byteStart: 4096, genFrom: 1, genTo: 2, chunks: [{ text: 'retired quokka passage', vector: 9 }] },+ { id: 50, byteStart: 8192, genFrom: 1, genTo: 2, chunks: [{ text: 'retired stale quokka tail' }] },+ { id: 80, byteStart: 4096, genFrom: 2, chunks: [{ text: 'new passage of the retiring page', vector: 7 }] },+ ],+ });}, 120_000);afterAll(async () => { await close?.(); });const liveIds = () => [...LIVE, 'live stale heron tail'].map(t => fixture.chunkIds.get(t)!);- const hiddenIds = () => ['retired quokka passage', 'staged wombat passage', 'staged stale wombat tail', 'retired stale quokka tail']- .map(t => fixture.chunkIds.get(t)!);+ const hiddenIds = () => [...['staged wombat passage', 'staged stale wombat tail'].map(t => fixture.chunkIds.get(t)!),+ ...['retired quokka passage', 'retired stale quokka tail'].map(t => retiring.chunkIds.get(t)!)];test('keyword search sees live rows only', async () => {expect((await engine.searchKeyword('zebrafish')).map(r => r.slug).sort()).toEqual(['notes/inline', SLUG]);@@ -104,6 +117,13 @@ for (const kind of testBackends()) {const stale = await engine.listStaleChunks({ batchSize: 100 });const texts = stale.filter(r => r.slug === SLUG).map(r => r.chunk_text);expect(texts).toEqual(['live stale heron tail']);+ expect(stale.filter(r => r.slug === RETIRING)).toEqual([]);+ });++ test('generation readers of a page awaiting its deferred retirement see its live rows only', async () => {+ expect((await engine.getChunks(RETIRING, { includeUnsealed: true })).map(c => c.chunk_text))+ .toEqual(['kept passage of the retiring page', 'new passage of the retiring page']);+ expect(await engine.getChunks(RETIRING)).toEqual([]);});});}diff --git a/test/large-pages/flip-crash.serial.test.ts b/test/large-pages/flip-crash.serial.test.tsindex 6e8a838eb8..9a8b0bcfc4 100644--- a/test/large-pages/flip-crash.serial.test.ts+++ b/test/large-pages/flip-crash.serial.test.ts@@ -113,7 +113,7 @@ describe('create: a crash after the projection staged its chunks', () => {expect(await searchHits(NEEDLE, 'notes/fresh')).toBe(1);const perOccurrence = async () => engine.executeRaw<{ occurrence_id: number; n: number }>(- `SELECT occurrence_id, count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND retired_generation IS NULL GROUP BY occurrence_id ORDER BY occurrence_id`, [sealed.id]);+ `SELECT occurrence_id, count(*)::int AS n FROM content_chunks WHERE page_id=$1 GROUP BY occurrence_id ORDER BY occurrence_id`, [sealed.id]);const once = await perOccurrence();await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation, slug, revision, reason)SELECT s.incarnation, $1, p.knowledge_revision, 'canonical_change' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.slug=$1`, ['notes/fresh']);@@ -139,7 +139,7 @@ describe('replace of a page whose projection never ran', () => {const bare = await engine.executeRaw(`SELECT m.occurrence_id FROM page_body_manifest m WHERE m.page_id=$1 AND m.staging_id IS NULLAND m.gen_from <= $2 AND (m.gen_to IS NULL OR m.gen_to > $2)AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=m.page_id AND c.occurrence_id=m.occurrence_id- AND c.body_generation <= $2 AND (c.retired_generation IS NULL OR c.retired_generation > $2))`, [sealed.id, sealed.body_generation]);+ AND c.body_generation <= $2)`, [sealed.id, sealed.body_generation]);expect(bare).toEqual([]);expect(await searchHits(NEEDLE, 'notes/unchunked')).toBe(1);}, 180_000);diff --git a/test/large-pages/segment-chunks.test.ts b/test/large-pages/segment-chunks.test.tsindex 05fa3672c3..418d19eafa 100644--- a/test/large-pages/segment-chunks.test.ts+++ b/test/large-pages/segment-chunks.test.ts@@ -74,19 +74,18 @@ describe('prepareSegmentChunks', () => {for (const seg of segs) {const chunks = await prepareSegmentChunks(seg, { fenceTrust: trustOf(body), fenceBudget: budget });const projection = Buffer.from(joinedProjection(bytes, [seg]), 'utf8');- const segEnd = seg.byteStart + seg.bytes.length;expect(chunks.map(c => c.local_ordinal)).toEqual(chunks.map((_, i) => i));const order = chunks.map(kindOf).join(',');expect(order).toMatch(/^(prose,)*prose(,code)*(,low)*$/);for (const c of chunks) {- expect(c.raw_byte_start).toBeGreaterThanOrEqual(seg.byteStart);- expect(c.raw_byte_end).toBeLessThanOrEqual(segEnd);+ expect(c.raw_byte_start).toBeGreaterThanOrEqual(0);+ expect(c.raw_byte_end).toBeLessThanOrEqual(seg.bytes.length);expect(c.raw_byte_end).toBeGreaterThan(c.raw_byte_start);if (kindOf(c) !== 'prose') continue;expect(c.projected_byte_end!).toBeLessThanOrEqual(projection.length);expect(squash(projection.subarray(c.projected_byte_start!, c.projected_byte_end!).toString('utf8'))).toBe(squash(c.chunk_text));- if (!overlaps(seg, c.raw_byte_start, c.raw_byte_end)) {- expect(squash(bytes.subarray(c.raw_byte_start, c.raw_byte_end).toString('utf8'))).toBe(squash(c.chunk_text));+ if (!overlaps(seg, seg.byteStart + c.raw_byte_start, seg.byteStart + c.raw_byte_end)) {+ expect(squash(bytes.subarray(seg.byteStart + c.raw_byte_start, seg.byteStart + c.raw_byte_end).toString('utf8'))).toBe(squash(c.chunk_text));checkedRaw++;}}diff --git a/test/large-pages/segmented-embedding.test.ts b/test/large-pages/segmented-embedding.test.tsindex fa5004ec4d..4964c64b7b 100644--- a/test/large-pages/segmented-embedding.test.ts+++ b/test/large-pages/segmented-embedding.test.ts@@ -58,7 +58,7 @@ for (const kind of testBackends()) {occurrences: [{ id: 10, byteStart: 0, genFrom: 1, chunks: [{ text: 'first live row' }, { text: 'second live row' }] },{ id: 20, byteStart: 4096, genFrom: 2, chunks: [{ text: 'appended row' }] },- { id: 30, byteStart: 4096, genFrom: 1, genTo: 2, chunks: [{ text: 'retired row', retiredGeneration: 2 }] },+ { id: 30, byteStart: 4096, genFrom: 1, genTo: 2, chunks: [{ text: 'retired row' }] },{ id: 40, byteStart: 8192, genFrom: 3, chunks: [{ text: 'staged row' }] },],});diff --git a/test/large-pages/segmented-storage-visibility.test.ts b/test/large-pages/segmented-storage-visibility.test.tsnew file mode 100644index 0000000000..c4ebf155d2--- /dev/null+++ b/test/large-pages/segmented-storage-visibility.test.ts@@ -0,0 +1,296 @@+/**+ * Wave B segmented storage: visibility and GC under races (PR 2 switch-on blockers).+ *+ * 1. Protects: a demoted page never shows a racing preparation's chunks, and+ * the preparation cannot stage more after the demotion; rows of retired+ * occurrences a deferred retirement left behind are invisible to every+ * generation reader (embed queue, unsealed chunk reads) before they are+ * deleted; a text a preparation staged or deduped onto survives a sweep+ * until publication references it; a page-scoped sweep collects only the+ * texts its page released; chunks of a shifted occurrence keep stored+ * spans that hold their text in the new body; segment GC's staged-chunk+ * delete reads an index, not the whole chunk table; v249 drops+ * content_chunks.retired_generation, which no reader still names.+ * 2. Fails when: visibility trusts body_generation alone, stageSegmentChunks+ * skips the page's current generation and storage, text staging leaves a+ * deduped text unlocked and its grace unrefreshed, the text sweep ignores+ * live stagings, a page sweep scans its source's texts, raw spans are+ * absolute body offsets, content_chunks_generation_idx is missing, or+ * v249 leaves retired_generation behind or a chunk reader still names it.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';+import { stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';+import * as pageBodySql from '../../src/core/engine-sql/page-body.ts';+import type { SqlExecutor } from '../../src/core/engine-sql/executor.ts';+import { sqlFragment, type SqlFragment } from '../../src/core/engine-sql/fragment.ts';+import { chunk, publishSegmentedPage, segmentText } from '../helpers/page-body-fixtures.ts';+import { cpuMsAsync } from '../helpers/cpu-time.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { v249 } from '../../src/core/schema-migrations/v249-segmented-chunk-gc-index.ts';++/** ~1.4 MB of sections, each its own segment. */+function sections(tag: string, n = 60): string {+ const parts: string[] = [];+ for (let i = 0; i < n; i++) parts.push(`## Section ${tag}${i}\n\n` + `Paragraph ${i} of ${tag} about widgets and gadgets number ${i}. `.repeat(400) + '\n\n');+ return parts.join('');+}+const page = (body: string) => `---\ntitle: Visibility\ntype: note\n---\n\n${body}`;+const squash = (s: string) => s.replace(/\s+/g, '');+const CHUNKING = { quarantined: false, corpusGeneration: null, tier: 'none' } as const;++for (const kind of testBackends()) {+ describe(`segmented storage visibility and GC (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ 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();+ }+ }, 120_000);+ afterAll(async () => { await close?.(); });+ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw('DELETE FROM page_body_stagings');+ await engine.executeRaw('DELETE FROM page_segment_texts');+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('pages.flip_retire_max_rows', '20000');+ });++ async function stage(slug: string, content: string) {+ const existing = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseMarkdown(content, `${slug}.md`);+ const staged = await stageSegmentedImport(engine, { slug, sourceId: 'default', existing,+ page: { title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags },+ policy: await readPageBodyPolicy(engine), chunking: CHUNKING, baseRevision: null });+ const apply = () => engine.transaction(tx => staged.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown' },+ { mode: 'none', corpusGeneration: null }));+ return { staged, apply };+ }++ async function generationReaderTexts(slug: string): Promise<string[]> {+ return (await engine.getChunks(slug, { sourceId: 'default', includeUnsealed: true })).map(c => c.chunk_text);+ }++ test('a demoted page shows none of a racing preparation\'s chunks, and the preparation stages no more', async () => {+ const slug = 'notes/demoted-race';+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });+ const { id } = await segmentedPageRow(engine, slug);+ const { staged } = await stage(slug, page('## Intro\n\nA quixotic new first paragraph.\n\n' + sections('a')));+ expect(await engine.searchKeyword('quixotic')).toEqual([]);+ const occurrence = (await engine.readManifest(id, { stagingId: staged.prepared.stagingId }))[0]!.occurrenceId;+ await importFromContent(engine, slug, page('Short replacement body.\n'), { sourceId: 'default', noEmbed: true });+ const demoted = await segmentedPageRow(engine, slug);+ expect([demoted.body_storage, demoted.body_generation]).toEqual(['inline', staged.prepared.newGeneration]);++ const refused = await engine.stageSegmentChunks(id, staged.prepared.newGeneration, [chunk(occurrence, 0, 'UNPUBLISHED quixotic staged text')])+ .then(() => null, (e: unknown) => e);+ expect((refused as { canonical?: string } | null)?.canonical).toBe('revision_changed');++ expect(await engine.searchKeyword('quixotic')).toEqual([]);+ expect(await generationReaderTexts(slug)).toEqual(['Short replacement body.']);++ // A row that bypassed the guard stays invisible to generation readers: its occurrence closed with the demotion.+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, occurrence_id, local_ordinal, body_generation)+ VALUES ($1, 100000, 'UNPUBLISHED quixotic staged text', 'compiled_truth', $2, 0, $3)`, [id, occurrence, staged.prepared.newGeneration]);+ expect(await generationReaderTexts(slug)).toEqual(['Short replacement body.']);+ expect((await engine.listStaleChunks({ batchSize: 1000 })).map(r => r.chunk_text)).not.toContain('UNPUBLISHED quixotic staged text');+ }, 180_000);++ test.skipIf(kind !== 'postgres')('a demotion waits for a chunk batch in flight and deletes its rows (the page row lock the guard relies on)', async () => {+ const slug = 'notes/demoted-in-flight';+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });+ const { id } = await segmentedPageRow(engine, slug);+ const { staged } = await stage(slug, page('## Intro\n\nA new first paragraph.\n\n' + sections('a')));+ const occurrence = (await engine.readManifest(id, { stagingId: staged.prepared.stagingId }))[0]!.occurrenceId;+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let locked!: () => void;+ const holding = new Promise<void>(resolve => { locked = resolve; });+ const batch = engine.transaction(async tx => {+ await tx.executeRaw("SELECT pg_advisory_xact_lock(hashtextextended('gbrain:page-body-chunks:' || $1::text, 0))", [id]);+ await tx.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, occurrence_id, local_ordinal, body_generation)+ VALUES ($1, 100000, 'in-flight lollapalooza staged text', 'compiled_truth', $2, 0, $3)`, [id, occurrence, staged.prepared.newGeneration]);+ locked();+ await gate;+ });+ await holding;+ let demoted = false;+ const demotion = importFromContent(engine, slug, page('Short replacement body.\n'), { sourceId: 'default', noEmbed: true }).then(() => { demoted = true; });+ await new Promise(resolve => setTimeout(resolve, 1000));+ const waited = !demoted;+ release();+ await batch;+ await demotion;+ expect(waited).toBe(true);+ expect(await engine.searchKeyword('lollapalooza')).toEqual([]);+ const [left] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND occurrence_id IS NOT NULL', [id]);+ expect(Number(left!.n)).toBe(0);+ }, 180_000);++ test('a deferred retirement hides the old body\'s rows from generation readers before they are deleted', async () => {+ const slug = 'notes/deferred-retire';+ await importFromContent(engine, slug, page(sections('a')), { sourceId: 'default', noEmbed: true });+ const { id } = await segmentedPageRow(engine, slug);+ await engine.setConfig('pages.flip_retire_max_rows', '5');+ const { staged, apply } = await stage(slug, page(sections('b')));+ expect((await apply()).retireDeferred).toBe(true);+ const [old] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND body_generation < $2`,+ [id, staged.prepared.newGeneration]);+ expect(Number(old!.n)).toBeGreaterThan(5);+ const texts = await generationReaderTexts(slug);+ expect(texts.length).toBeGreaterThan(0);+ expect(texts.filter(text => text.includes(' of a about '))).toEqual([]);+ const stale = (await engine.listStaleChunks({ batchSize: 100_000 })).map(r => r.chunk_text);+ expect(stale.filter(text => text.includes(' of a about '))).toEqual([]);+ expect(stale.some(text => text.includes(' of b about '))).toBe(true);+ }, 180_000);++ test('a create published after its texts aged past the grace window and a sweep ran still publishes', async () => {+ const slug = 'notes/slow-publication';+ const { staged, apply } = await stage(slug, page(sections('c')));+ await engine.executeRaw(`UPDATE page_segment_texts SET created_at = now() - interval '2 hours'`);+ await engine.executeRaw(`UPDATE page_body_stagings SET created_at = now() - interval '3 hours' WHERE id = $1`, [staged.prepared.stagingId]);+ await engine.sweepSegments({ sourceId: 'default' });+ await apply();+ const body = await materializeSegmentedBody(engine, (await segmentedPageRow(engine, slug)).id, 'default');+ expect(body.compiled_truth).toBe(parseMarkdown(page(sections('c')), `${slug}.md`).compiled_truth);+ }, 180_000);++ test('a create that dedupes onto old orphan texts keeps them through a sweep before it publishes', async () => {+ const content = page(sections('d'));+ await importFromContent(engine, 'notes/orphaned', content, { sourceId: 'default', noEmbed: true });+ expect((await segmentedPageRow(engine, 'notes/orphaned')).body_storage).toBe('segmented');+ await engine.executeRaw(`DELETE FROM pages WHERE slug = 'notes/orphaned'`);+ await engine.executeRaw(`UPDATE page_segment_texts SET created_at = now() - interval '2 hours'`);+ const [orphans] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_segment_texts');+ expect(Number(orphans!.n)).toBeGreaterThan(3);+ const { apply } = await stage('notes/dedupe', content);+ await engine.sweepSegments({ sourceId: 'default' });+ await apply();+ const body = await materializeSegmentedBody(engine, (await segmentedPageRow(engine, 'notes/dedupe')).id, 'default');+ expect(body.compiled_truth).toBe(parseMarkdown(content, 'notes/dedupe.md').compiled_truth);+ }, 180_000);++ test('a page-scoped sweep collects the texts its page released and leaves the rest of the source', async () => {+ const slug = 'notes/page-sweep';+ await importFromContent(engine, slug, page(sections('e')), { sourceId: 'default', noEmbed: true });+ const { id } = await segmentedPageRow(engine, slug);+ const orphan = Buffer.from('an orphan text another page released\n');+ const orphanSha = createHash('sha256').update(orphan).digest();+ await engine.stageSegmentTexts('default', [{ sha256: orphanSha, body: orphan, lineCount: 1 }]);+ const released = await engine.readManifest(id);+ expect(released.length).toBeGreaterThan(3);+ await importFromContent(engine, slug, page(sections('f')), { sourceId: 'default', noEmbed: true });+ await engine.executeRaw('DELETE FROM page_versions WHERE page_id = $1', [id]);+ await engine.executeRaw(`UPDATE page_segment_texts SET created_at = now() - interval '2 hours'`);+ const swept = await engine.sweepSegments({ pageId: id });+ expect(swept.textsDeleted).toBe(new Set(released.map(row => Buffer.from(row.sha256).toString('hex'))).size);+ expect((await engine.readSegmentTexts('default', [orphanSha])).size).toBe(1);+ expect((await engine.sweepSegments({ sourceId: 'default' })).textsDeleted).toBe(1);+ }, 180_000);++ test.skipIf(kind !== 'pglite')('a page-scoped sweep costs the same in a source ten times larger', async () => {+ const seeded = async (texts: number) => {+ const sourceId = `sweep-${texts}`;+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING', [sourceId]);+ const { pageId } = await publishSegmentedPage(engine, `notes/sweep-${texts}`, [segmentText('# Page\nbody\n')], { sourceId });+ for (let start = 0; start < texts; start += 2000) {+ await engine.stageSegmentTexts(sourceId, Array.from({ length: Math.min(2000, texts - start) }, (_, i) => segmentText(`text ${start + i} of ${sourceId}\n`)));+ }+ return pageId;+ };+ const small = await seeded(1000);+ const large = await seeded(10_000);+ const best = async (pageId: number) => {+ let ms = Infinity;+ for (let k = 0; k < 3; k++) ms = Math.min(ms, await cpuMsAsync(async () => { for (let n = 0; n < 300; n++) await engine.sweepSegments({ pageId }); }));+ return ms;+ };+ await best(small);+ await best(large);+ const ratios: number[] = [];+ for (let round = 0; round < 3; round++) ratios.push(await best(large) / await best(small));+ expect(ratios.sort((a, b) => a - b)[1]!).toBeLessThan(1.5);+ }, 180_000);++ test('chunks of a shifted occurrence keep stored spans that hold their text in the new body', async () => {+ const slug = 'notes/shifted-spans';+ await importFromContent(engine, slug, page(sections('g')), { sourceId: 'default', noEmbed: true });+ const { id } = await segmentedPageRow(engine, slug);+ await importFromContent(engine, slug, page('## Intro\n\nA new first paragraph.\n\n' + sections('g')), { sourceId: 'default', noEmbed: true });+ const row = await segmentedPageRow(engine, slug);+ const body = Buffer.from((await materializeSegmentedBody(engine, id, 'default')).compiled_truth, 'utf8');+ const chunks = await engine.executeRaw<{ chunk_text: string; byte_start: number; raw_byte_start: number; raw_byte_end: number; shifted: boolean }>(`+ SELECT c.chunk_text, m.byte_start::int AS byte_start, c.raw_byte_start::int AS raw_byte_start, c.raw_byte_end::int AS raw_byte_end,+ (c.body_generation < m.gen_from) AS shifted+ FROM content_chunks c JOIN page_body_manifest m ON m.page_id = c.page_id AND m.occurrence_id = c.occurrence_id+ AND m.staging_id IS NULL AND m.gen_to IS NULL+ WHERE c.page_id = $1 AND c.projected_byte_start IS NOT NULL AND m.region = 'truth'`, [id]);+ const shifted = chunks.filter(c => c.shifted);+ expect(row.body_generation).toBe(2);+ expect(shifted.length).toBeGreaterThan(10);+ for (const c of chunks) {+ expect(squash(body.subarray(c.byte_start + c.raw_byte_start, c.byte_start + c.raw_byte_end).toString('utf8'))).toBe(squash(c.chunk_text));+ }+ }, 180_000);++ test('v249 drops retired_generation from a v248 brain and builds the GC index; no chunk reader names the column', async () => {+ const columns = async () => (await engine.executeRaw<{ attname: string }>(+ "SELECT attname FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attnum > 0 AND NOT attisdropped")).map(r => r.attname);+ expect(await columns()).not.toContain('retired_generation');+ await importFromContent(engine, 'notes/upgraded', page(sections('u')), { sourceId: 'default', noEmbed: true });+ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN retired_generation BIGINT');+ await engine.executeRaw('DROP INDEX content_chunks_generation_idx');+ await engine.executeRaw(v249.sql);+ await v249.handler!(engine);+ expect(await columns()).not.toContain('retired_generation');+ const [index] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname = 'content_chunks_generation_idx'");+ expect(index?.indexdef).toContain('WHERE (body_generation IS NOT NULL)');+ for (const excludePrivate of [false, true]) {+ expect((await engine.searchKeyword('widgets', { limit: 5, excludePrivate, requireSafeChunks: false })).length).toBeGreaterThan(0);+ expect((await engine.getChunks('notes/upgraded', { sourceId: 'default', excludePrivate, requireSafeChunks: false })).length).toBeGreaterThan(0);+ }+ expect((await generationReaderTexts('notes/upgraded')).length).toBeGreaterThan(0);+ }, 120_000);++ test('the unscoped staged-chunk GC reads content_chunks through an index, never a full scan', async () => {+ for (let p = 0; p < 40; p++) {+ await engine.putPage(`notes/inline-${p}`, { type: 'note', title: `Inline ${p}`, compiled_truth: `inline ${p}`, timeline: '', frontmatter: {} });+ }+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source)+ SELECT p.id, g, 'inline chunk ' || g, 'compiled_truth' FROM pages p CROSS JOIN generate_series(1, 500) g WHERE p.slug LIKE 'notes/inline-%'`);+ await importFromContent(engine, 'notes/gc-plan', page(sections('h')), { sourceId: 'default', noEmbed: true });+ await engine.executeRaw('ANALYZE content_chunks');+ await engine.executeRaw('ANALYZE pages');+ const exec = (engine as unknown as { engineSql: SqlExecutor }).engineSql;+ const plans: string[] = [];+ const explaining = Object.assign(Object.create(exec) as SqlExecutor, {+ run: async (fragment: SqlFragment) => {+ const { rows } = await exec.run<Record<string, string>>(sqlFragment`EXPLAIN ${fragment}`);+ plans.push(rows.map(r => Object.values(r)[0]).join('\n'));+ return { rows: [], affectedRows: 0 };+ },+ });+ await pageBodySql.sweepSegments(explaining, { expireStagings: true });+ const chunkGc = plans.find(plan => /Delete on content_chunks/.test(plan));+ expect(chunkGc).toBeDefined();+ expect(chunkGc).not.toMatch(/Seq Scan on content_chunks/);+ expect(chunkGc).toMatch(/content_chunks_generation_idx/);+ }, 180_000);+ });+}diff --git a/test/large-pages/segmented-versions.test.ts b/test/large-pages/segmented-versions.test.tsindex c016a27876..6d0da78ef9 100644--- a/test/large-pages/segmented-versions.test.ts+++ b/test/large-pages/segmented-versions.test.ts@@ -60,8 +60,8 @@ for (const kind of testBackends()) {bodyBytes: 2 * KB,occurrences: [{ id: 1, byteStart: 0, genFrom: 1, byteLen: KB, chunks: [{ text: 'opening passage' }] },- { id: 2, byteStart: KB, genFrom: 1, genTo: 2, byteLen: 8 * KB, chunks: [{ text: 'first tail', retiredGeneration: 2 }] },- { id: 3, byteStart: KB, genFrom: 2, genTo: 3, byteLen: 8 * KB, chunks: [{ text: 'second tail', retiredGeneration: 3 }] },+ { id: 2, byteStart: KB, genFrom: 1, genTo: 2, byteLen: 8 * KB, chunks: [{ text: 'first tail' }] },+ { id: 3, byteStart: KB, genFrom: 2, genTo: 3, byteLen: 8 * KB, chunks: [{ text: 'second tail' }] },{ id: 4, byteStart: KB, genFrom: 3, byteLen: KB, chunks: [{ text: 'third tail' }] },],}));diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 163998e07a..7996f70449 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -72,6 +72,7 @@ test/large-pages/segmented-derived-work.test.tstest/large-pages/segmented-embedding-paths.test.tstest/large-pages/segmented-embedding.test.tstest/large-pages/segmented-shrink-below-ceiling.test.ts+test/large-pages/segmented-storage-visibility.test.tstest/large-pages/segmented-versions.test.tstest/link-cross-source.test.tstest/link-preparation-shared-index.test.tsdiff --git a/test/search-statistics-guard.test.ts b/test/search-statistics-guard.test.tsindex 9ba445f2c7..3efd14c87a 100644--- a/test/search-statistics-guard.test.ts+++ b/test/search-statistics-guard.test.ts@@ -44,7 +44,7 @@ describe('missing search planner statistics on Postgres', () => {engine = postgresLike(db);await db.exec(`CREATE TABLE pages (id integer PRIMARY KEY, source_id text, type text, slug text, deleted_at timestamptz,text_projection_revision uuid, knowledge_revision uuid, body_generation bigint NOT NULL DEFAULT 0);- CREATE TABLE content_chunks (id integer PRIMARY KEY, page_id integer, model text, modality text, body_generation bigint, retired_generation bigint);+ CREATE TABLE content_chunks (id integer PRIMARY KEY, page_id integer, model text, modality text, body_generation bigint);CREATE TABLE planner_probe_unused (id integer);INSERT INTO pages SELECT i, 'src-' || (i % 8), 'note', 'note-' || i, NULL,'00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001' FROM generate_series(1, 2000) i;@@ -62,7 +62,7 @@ describe('missing search planner statistics on Postgres', () => {try {await empty.exec(`CREATE TABLE pages (id integer, source_id text, type text, slug text, deleted_at timestamptz,text_projection_revision uuid, knowledge_revision uuid, body_generation bigint NOT NULL DEFAULT 0);- CREATE TABLE content_chunks (id integer, page_id integer, model text, modality text, body_generation bigint, retired_generation bigint);`);+ CREATE TABLE content_chunks (id integer, page_id integer, model text, modality text, body_generation bigint);`);await empty.exec(PROJECTION_STATISTICS_SQL);expect(await missingSearchStatistics(postgresLike(empty))).toEqual([]);} finally { await empty.close(); }