Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embedding): chunk size-skipped pages with no chunks, roll back a failed backfill's hold, name held pages that waited (#7174, #7184, #7185)

garrytan178a6378cbb7
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index c315df6c79..242212d438 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -319,8 +319,8 @@ src/core/output/writer.ts WriteTxImpl.setCompiledTruth field INLINE
src/core/output/writer.ts WriteTxImpl.setFrontmatterField call:putPage INLINE
src/core/output/writer.ts WriteTxImpl.setFrontmatterField field INLINE
src/core/oversized-backfill.ts PAGE_BYTES_SQL sql SEGW
-src/core/oversized-backfill.ts reindexPage call:serializeMarkdown SEGW
-src/core/oversized-backfill.ts reindexPage field SEGW
+src/core/oversized-backfill.ts rewritePage call:serializeMarkdown SEGW
+src/core/oversized-backfill.ts rewritePage field SEGW
src/core/page-body/body-digests.ts fileBodyDigests field NONE scan.timeline is the scanned file's timeline byte ranges and digests.timeline a SHA-256, not a page body; each region is hashed piece by piece
src/core/page-body/body-scan.ts scanMarkdownString field NONE not a stored body: scans an incoming markdown string for the segmenter
src/core/page-body/content-hash-stream.ts ContentHashStream.fromState field NONE not a stored body: resumes the streaming content hash over incoming text
diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.ts
index b84c92d53a..6c866f1b60 100644
--- a/src/commands/doctor/checks/content-quality.ts
+++ b/src/commands/doctor/checks/content-quality.ts
@@ -67,10 +67,13 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
[bytesBlock],
);
// Pages an older gbrain stored chunkless for size that now fit under the block: the free backfill re-indexes them.
- const [skipped] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages p
+ // chunk-visibility-ok: counts pages with no chunk row at all (any generation), the chunk safety net's own test
+ const [skipped] = await engine.executeRaw<{ n: number; chunkless: number }>(`SELECT COUNT(*)::int AS n,
+ COUNT(*) FILTER (WHERE NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id))::int AS chunkless FROM pages p
WHERE p.deleted_at IS NULL AND p.frontmatter->'embed_skip'->>'reason' = 'oversized'
AND (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, ''))) <= $1`, [bytesBlock]);
const backfillable = Number(skipped?.n ?? 0);
+ const chunklessMarked = Number(skipped?.chunkless ?? 0);
// Decision #10: a segmented page's body columns are NULL, so both size scans above pass it by.
const [segmented] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages p WHERE p.deleted_at IS NULL AND p.body_storage = 'segmented'`).catch(() => []);
const oversizedCheck = (check: Check) => checks.push(withSkippedSegmented(check, Number(segmented?.n ?? 0)));
@@ -78,8 +81,11 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
oversizedCheck({
name: 'oversized_pages',
status: 'warn',
- message: `${backfillable} page(s) were stored without chunks by an older gbrain because of their size, and now fit under the ${bytesBlock}-byte bytes_block. `
- + 'They are invisible to search until re-indexed. Fix: gbrain reindex --oversized (free, CPU only; pages over 1 MiB then wait for embedding approval).',
+ // #7184: a marked page keeps its chunks once healed or rewritten, so say how many are truly invisible.
+ message: `${backfillable} page(s) still carry the size-skip marker an older gbrain wrote, and now fit under the ${bytesBlock}-byte bytes_block: `
+ + `${chunklessMarked} have no chunks, so not even keyword search finds them, and ${backfillable - chunklessMarked} are keyword-only with no vectors. `
+ + 'A page whose rewrite fails (an invalid fence, for example) keeps the marker until its content is repaired. Fix: gbrain reindex --oversized (free, CPU only; pages over 1 MiB then wait for embedding approval).',
+ details: { marked: backfillable, chunkless: chunklessMarked },
fix: agentFix(['gbrain', 'reindex', '--oversized'], 'Re-chunks the size-skipped pages so keyword search finds them; it calls no paid provider and holds large pages for embedding approval.',
'oversized_pages', { docs: 'docs/guides/memory-boundaries.md#large-pages-upgrade' }),
});
diff --git a/src/core/embedding-state.ts b/src/core/embedding-state.ts
index c643f9ce50..205aefb786 100644
--- a/src/core/embedding-state.ts
+++ b/src/core/embedding-state.ts
@@ -9,7 +9,7 @@
* `chunklessPageState`, next to `staleChunkWhere`) and both engines delegate
* to it. Precedence for a chunk: deleted page, quarantined page, stored
* vector, embed job predicate, else embed_skip. For a chunkless live page:
- * quarantined, embed_skip, healable body, else empty.
+ * quarantined, healable body, else empty.
*
* - `embedded`: a chunk on a live, unquarantined page whose active column
* holds a vector (vectors retained on an embed_skip page count: vector
@@ -19,8 +19,7 @@
* `gbrain embed --stale` drains it. On a brain keyless by choice keyword
* search is the configured retrieval and reads these chunks, so they are
* not counted as unsearchable there.
- * - `keyword_only`: a chunk with no vector on a live `embed_skip` page, or an
- * `embed_skip` page with no chunk rows. By design (#4306: never purged; its
+ * - `keyword_only`: a chunk with no vector on a live `embed_skip` page. By design (#4306: never purged; its
* text feeds keyword search). The import gate sets the marker for a body
* over the effective `content_sanity.bytes_block`, so removing the marker
* alone is undone on the next import; the exits are splitting the page or
@@ -33,9 +32,11 @@
* - `deleted_page_chunks`: chunks on a soft-deleted page. The purge lifecycle
* (`gbrain pages purge-deleted`, the autopilot purge phase, 72 h) removes
* them; past that window they are overdue.
- * - `chunkless_healable`: a live page with body text, no markers and no chunk
- * rows (`listChunklessPagesWithContent`'s predicate): `gbrain embed --stale`
- * chunks it before embedding.
+ * - `chunkless_healable`: a live, unquarantined page with body text and no
+ * chunk rows (`listChunklessPagesWithContent`'s predicate): `gbrain embed
+ * --stale` chunks it before embedding. An `embed_skip` page is included
+ * (#7174): writes keep its chunks (#6722), so none means keyword search
+ * cannot find it; it is chunked and still gets no vectors.
*
* Unstamped pending chunks (`embedding_pending_since` NULL: written by a binary
* older than the v221 stamp) carry no age; the summary reports their count,
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 3d31990089..3cb6e91e78 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -800,9 +800,11 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {
}
/**
- * Shared chunkless-page-with-content predicate. Excludes quarantined +
- * embed_skip pages — both are intentionally chunkless by design, not drift
- * the safety net should repair.
+ * Shared chunkless-page-with-content predicate. Excludes quarantined pages,
+ * which are chunkless by design. An embed_skip page is not: every write keeps
+ * its chunks for keyword search (#6722), so one with none (an older gbrain's
+ * size skip, or a backfill rewrite that never landed) is drift the safety net
+ * chunks; its chunks get no vectors (#7174).
*/
function chunklessPagesWhere(opts?: { sourceId?: string }): SqlFragment {
const conds: SqlFragment[] = [
@@ -812,7 +814,6 @@ function chunklessPagesWhere(opts?: { sourceId?: string }): SqlFragment {
// something to heal even with compiled_truth = ''. A segmented page's
// body columns are NULL; its body_bytes says it has one.
sqlFragment`(p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0))`,
- sqlFragment`${trustedSql(EMBED_SKIP_FILTER_FRAGMENT)}`,
sqlFragment`${trustedSql(QUARANTINE_FILTER_FRAGMENT)}`,
sqlFragment`NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)`,
];
@@ -870,11 +871,10 @@ function chunkEmbeddingState(column: string): SqlFragment {
ELSE 'keyword_only' END`;
}
-/** A live page with no chunk row: gated (quarantine, embed_skip), healable (`chunklessPagesWhere`), else empty. */
+/** A live page with no chunk row: quarantined, healable with a body (`chunklessPagesWhere`, embed_skip included: #7174), else empty. */
function chunklessPageState(): SqlFragment {
return sqlFragment`CASE
WHEN NOT ${trustedSql(QUARANTINE_FILTER_FRAGMENT)} THEN 'quarantined'
- WHEN NOT ${trustedSql(EMBED_SKIP_FILTER_FRAGMENT)} THEN 'keyword_only'
WHEN ${chunklessPagesWhere()} THEN 'chunkless_healable'
ELSE 'empty' END`;
}
@@ -964,7 +964,6 @@ export async function readEmbeddingStateCounts(exec: ScopedRead, column: string,
for (const state of EMBEDDING_STATES) counts[state] ??= 0;
return { ...base, basis: 'exact', counts, omitted: [], eligible_embedded: eligibleEmbedded, deleted_overdue: deletedOverdue };
}
- add('keyword_only', embedSkip.chunkless ?? 0);
const quarantined = await exec.run(sqlFragment`
SELECT COALESCE(sum(GREATEST((SELECT count(*) FROM content_chunks cc WHERE cc.page_id = p.id), 1)), 0)::bigint AS n
FROM pages p
diff --git a/src/core/held-embedding.ts b/src/core/held-embedding.ts
index e6f4198fa3..305c27e3b5 100644
--- a/src/core/held-embedding.ts
+++ b/src/core/held-embedding.ts
@@ -140,7 +140,15 @@ export async function budgetLimitedField(engine: BrainEngine, sourceId: string,
export async function budgetLimitedFinding(engine: BrainEngine, signature: string | null): Promise<{ message: string; fix: Action; details: Record<string, unknown> } | null> {
const found = await budgetLimitedReport(engine, { signature });
if (!found) return null;
- return { message: found.line, fix: found.fix, details: { ...found.report } };
+ // #7174: a hold nobody decided on stays put by design, so its age is what tells the operator it is waiting on them.
+ const [age] = await engine.executeRaw<{ stale: number; oldest: Date | string | null }>(
+ `SELECT count(*) FILTER (WHERE b.updated_at < now() - interval '1 day')::int AS stale, min(b.updated_at) AS oldest
+ FROM page_embedding_budget b JOIN pages p ON p.id = b.page_id
+ WHERE ${budgetRowAppliesFilter('b', 'p')} AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);
+ const stale = Number(age?.stale ?? 0);
+ const oldest = age?.oldest ? new Date(age.oldest).toISOString() : null;
+ const waited = stale ? ` ${stale} of them have waited more than a day (oldest unchanged since ${oldest}); nothing embeds them until the user approves or declines.` : '';
+ return { message: `${found.line}${waited}`, fix: found.fix, details: { ...found.report, waiting_over_day: stale, oldest_updated_at: oldest } };
}
type HeldListing = {
diff --git a/src/core/oversized-backfill.ts b/src/core/oversized-backfill.ts
index b27a980038..65a688e5d0 100644
--- a/src/core/oversized-backfill.ts
+++ b/src/core/oversized-backfill.ts
@@ -105,11 +105,26 @@ async function reindexPage(engine: BrainEngine, page: Candidate, managed: boolea
if (!snapshot || snapshot.page.id !== page.id) return;
const fm = { ...((snapshot.page.frontmatter ?? {}) as Record<string, unknown>) };
if ((fm[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason !== 'oversized') return;
+ let prior: { state: string; reason: string | null } | null | undefined;
if (!overBlock) {
delete fm[EMBED_SKIP_KEY];
if ((fm[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete fm[CONTENT_FLAG_KEY];
- if (isLargePageBytes(page.bytes)) await holdPageEmbedding(engine, page.id, BACKFILL_HOLD_REASON);
+ if (isLargePageBytes(page.bytes)) {
+ [prior = null] = await engine.executeRaw<{ state: string; reason: string | null }>('SELECT state, reason FROM page_embedding_budget WHERE page_id = $1', [page.id]);
+ await holdPageEmbedding(engine, page.id, BACKFILL_HOLD_REASON);
+ }
+ }
+ try {
+ await rewritePage(engine, page, snapshot, fm, managed);
+ } catch (error) {
+ // #7185: a rewrite that did not land keeps the marker, so the hold placed for it would wait on nothing; put the row back.
+ if (prior === null) await engine.executeRaw('DELETE FROM page_embedding_budget WHERE page_id = $1', [page.id]);
+ else if (prior) await engine.executeRaw('UPDATE page_embedding_budget SET state = $2, reason = $3, updated_at = now() WHERE page_id = $1', [page.id, prior.state, prior.reason]);
+ throw error;
}
+}
+
+async function rewritePage(engine: BrainEngine, page: Candidate, snapshot: NonNullable<Awaited<ReturnType<typeof materializedSnapshot>>>, fm: Record<string, unknown>, managed: boolean): Promise<void> {
const markdown = serializeMarkdown(fm, snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? '', {
type: (snapshot.page.type as PageType) ?? 'note', title: snapshot.page.title ?? '', tags: snapshot.tags,
});
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
index 17e5a7678c..22e5f91cfb 100644
--- a/src/core/page-embedding-budget.ts
+++ b/src/core/page-embedding-budget.ts
@@ -188,7 +188,8 @@ export function estimatePageEmbedUsd(chars: number, signature: string | null | u
/** Held and capped pages with their stale chunk counts (`gbrain embed --held`); `limit: null` lists every one. */
export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeRaw'>, opts: { state?: 'held' | 'capped'; sourceId?: string; limit?: number | null } = {}): Promise<PageBudgetReport[]> {
const params: unknown[] = [opts.limit === undefined ? 1000 : opts.limit];
- const filters = [budgetRowAppliesFilter('b', 'p'), 'p.deleted_at IS NULL'];
+ // #7185: an embed_skip page is never embedded, so a hold on one (a backfill rewrite that did not land) is not approvable work.
+ const filters = [budgetRowAppliesFilter('b', 'p'), 'p.deleted_at IS NULL', `NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`];
if (opts.state) filters.push(`b.state = $${params.push(opts.state)}`);
if (opts.sourceId) filters.push(`p.source_id = $${params.push(opts.sourceId)}`);
const pending = `(CASE WHEN p.body_storage = 'segmented' THEN cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)} IS NULL ELSE cc.embedded_at IS NULL END)`;
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index 3cc1a33425..d6b601c87d 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -1171,9 +1171,9 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {
// Chunkless-page safety net (embed --stale detection gap): a page with
// non-empty content but zero content_chunks rows (e.g. a putPage-only
- // write) must be found on BOTH engines identically, and quarantined /
- // embed_skip pages (intentionally chunkless by design) must be excluded
- // identically on both. Isolated under a dedicated source.
+ // write) must be found on BOTH engines identically, quarantined pages
+ // (chunkless by design) excluded and a chunkless embed_skip page with a
+ // body included (#7174) identically on both. Isolated under a dedicated source.
test('chunkless-page-with-content detection: Postgres ↔ PGLite parity', async () => {
const SRC = 'chunkless-parity';
for (const eng of [pgEngine, pgliteEngine]) {
@@ -1193,20 +1193,20 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {
type: 'note', title: 'Quarantined', compiled_truth: 'junk content',
frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'parity fixture', assessed_at: new Date().toISOString() } },
}, { sourceId: SRC });
- // cp/skipped: chunkless BY DESIGN — must be excluded.
+ // cp/skipped: embed_skip with no chunk rows — included (#7174: writes keep its chunks since #6722).
await eng.putPage('cp/skipped', {
type: 'note', title: 'Skipped', compiled_truth: 'x'.repeat(500),
frontmatter: { embed_skip: { reason: 'oversized', bytes: 500, assessed_at: new Date().toISOString() } },
}, { sourceId: SRC });
}
- expect(await pgEngine.countChunklessPagesWithContent({ sourceId: SRC })).toBe(1);
- expect(await pgliteEngine.countChunklessPagesWithContent({ sourceId: SRC })).toBe(1);
+ expect(await pgEngine.countChunklessPagesWithContent({ sourceId: SRC })).toBe(2);
+ expect(await pgliteEngine.countChunklessPagesWithContent({ sourceId: SRC })).toBe(2);
const pgRows = await pgEngine.listChunklessPagesWithContent({ sourceId: SRC });
const pgliteRows = await pgliteEngine.listChunklessPagesWithContent({ sourceId: SRC });
- expect(pgRows.map(r => r.slug)).toEqual(['cp/stub']);
- expect(pgliteRows.map(r => r.slug)).toEqual(['cp/stub']);
+ expect(pgRows.map(r => r.slug)).toEqual(['cp/stub', 'cp/skipped']);
+ expect(pgliteRows.map(r => r.slug)).toEqual(['cp/stub', 'cp/skipped']);
expect(pgRows[0].compiled_truth).toBe('stub content, never chunked');
expect(pgliteRows[0].compiled_truth).toBe(pgRows[0].compiled_truth);
diff --git a/test/embed-stale-chunkless-pages.serial.test.ts b/test/embed-stale-chunkless-pages.serial.test.ts
index 67dfa4f709..8cf81b176a 100644
--- a/test/embed-stale-chunkless-pages.serial.test.ts
+++ b/test/embed-stale-chunkless-pages.serial.test.ts
@@ -12,9 +12,9 @@ import { installFixtureChunks } from './helpers/page-projection.ts';
*
* Two layers tested here:
* 1. The detection primitive itself (`countChunklessPagesWithContent` /
- * `listChunklessPagesWithContent`) — including that quarantined and
- * `embed_skip` pages are excluded, since BOTH are intentionally
- * chunkless by design (content-quality gate), not drift to repair.
+ * `listChunklessPagesWithContent`) — including that quarantined pages
+ * are excluded (chunkless by design) while a chunkless `embed_skip` page
+ * with a body is included (#7174: writes keep its chunks since #6722).
* 2. The end-to-end `embed --stale` wiring — a chunkless page gets
* chunked AND embedded in the SAME pass, while pre-existing stale
* chunks and intentionally-chunkless pages are unaffected.
@@ -123,7 +123,7 @@ describe('countChunklessPagesWithContent / listChunklessPagesWithContent', () =>
expect(await engine.countChunklessPagesWithContent()).toBe(0);
});
- test('excludes embed_skip pages (intentionally chunkless by design)', async () => {
+ test('includes a chunkless embed_skip page with a body (#7174: keyword search cannot see it)', async () => {
await engine.putPage('oversized/page', {
type: 'note',
title: 'Oversized',
@@ -131,7 +131,8 @@ describe('countChunklessPagesWithContent / listChunklessPagesWithContent', () =>
frontmatter: { [EMBED_SKIP_KEY]: buildEmbedSkipMarker(1000) },
});
- expect(await engine.countChunklessPagesWithContent()).toBe(0);
+ expect(await engine.countChunklessPagesWithContent()).toBe(1);
+ expect((await engine.listChunklessPagesWithContent()).map(page => page.slug)).toEqual(['oversized/page']);
});
});
@@ -213,7 +214,7 @@ describe('embed --stale chunkless-page safety net (end-to-end)', () => {
expect(after.page.text_projection_revision).toBe(after.revision);
});
- test('quarantined and embed_skip pages stay chunkless — the safety net does not touch them', async () => {
+ test('a quarantined page stays chunkless; a chunkless embed_skip page is chunked for keyword search and gets no vector (#7174)', async () => {
await engine.putPage('junk/quarantined', {
type: 'note',
title: 'Junk',
@@ -229,9 +230,12 @@ describe('embed --stale chunkless-page safety net (end-to-end)', () => {
const result = await runEmbedCore(engine, { stale: true, quiet: true });
- expect(result.chunkless_pages_healed).toBe(0);
+ expect(result.chunkless_pages_healed).toBe(1);
expect(await engine.getChunks('junk/quarantined')).toEqual([]);
- expect(await engine.getChunks('oversized/skipped')).toEqual([]);
+ const [skipped] = await engine.executeRaw<{ chunks: number; vectors: number }>(`SELECT count(*)::int AS chunks, count(cc.embedding)::int AS vectors
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = 'oversized/skipped'`);
+ expect(skipped).toEqual({ chunks: 1, vectors: 0 });
+ expect((await engine.searchKeyword('x'.repeat(1000), { limit: 5 })).map(hit => hit.slug)).toContain('oversized/skipped');
});
test('dry-run reports the would-be-healed count without writing any chunks', async () => {
diff --git a/test/embedding-state.test.ts b/test/embedding-state.test.ts
index 3eb4c0777c..08108aab7e 100644
--- a/test/embedding-state.test.ts
+++ b/test/embedding-state.test.ts
@@ -73,7 +73,8 @@ async function seedEveryState(): Promise<void> {
await chunks(await page('notes/deleted-old', { deletedHoursAgo: 100 }), [{}, { vector: true }]);
}
-const EVERY_STATE = { embedded: 2, pending: 2, keyword_only: 2, quarantined: 3, empty: 1, deleted_page_chunks: 3, chunkless_healable: 1 };
+// #7174: notes/fund-a-oversized-bare (embed_skip, body, no chunk rows) is chunkless_healable: writes keep an embed_skip page's chunks (#6722).
+const EVERY_STATE = { embedded: 2, pending: 2, keyword_only: 1, quarantined: 3, empty: 1, deleted_page_chunks: 3, chunkless_healable: 2 };
describe('embedding state classifier (full mode)', () => {
test('every state on the legacy column, exact', async () => {
@@ -84,7 +85,7 @@ describe('embedding state classifier (full mode)', () => {
expect(s.active_column).toBe('embedding');
expect(s.counts).toEqual(EVERY_STATE);
expect(Object.keys(s.counts).sort()).toEqual([...EMBEDDING_STATES].sort());
- expect(s.unsearchable).toBe(2 + 3 + 1 + 1);
+ expect(s.unsearchable).toBe(2 + 3 + 1 + 2);
expect(s.unsearchable_complete).toBe(true);
expect(s.deleted_page_chunks).toEqual({ within_window: 1, past_window: 2, window_hours: 72 });
// The default bytes_block is the 24 MiB page ceiling (large pages Wave A); these markers predate it.
@@ -137,7 +138,7 @@ describe('embedding state classifier (full mode)', () => {
const s = await readEmbeddingState(engine, { mode: 'full' });
expect(s.reason).toBe('embeddings_disabled');
expect(s.counts.pending).toBe(2);
- expect(s.unsearchable).toBe(3 + 1 + 1);
+ expect(s.unsearchable).toBe(3 + 1 + 2);
});
});
@@ -148,7 +149,7 @@ describe('embedding state classifier (ops mode)', () => {
expect(s.status).toBe('known');
expect(s.basis).toBe('estimated');
expect(s.covering_index).toBe('content_chunks_stale_idx');
- expect(s.counts).toMatchObject({ pending: 2, keyword_only: 2, quarantined: 3, deleted_page_chunks: 3 });
+ expect(s.counts).toMatchObject({ pending: 2, keyword_only: 1, quarantined: 3, deleted_page_chunks: 3 });
expect(s.counts.empty).toBeUndefined();
expect(s.counts.chunkless_healable).toBeUndefined();
expect(typeof s.counts.embedded).toBe('number');
@@ -182,12 +183,12 @@ describe('embedding state rows and fixes', () => {
await seedEveryState();
const rows = await engine.listEmbeddingStateRows({ states: ['keyword_only', 'quarantined', 'empty', 'chunkless_healable', 'deleted_page_chunks'], limit: 50, purgeWindowHours: 72 });
expect(rows.map(r => `${r.state} ${r.slug} ${r.chunks}`)).toEqual([
+ 'chunkless_healable notes/fund-a-oversized-bare 0',
'chunkless_healable notes/stub-with-body 0',
'deleted_page_chunks notes/deleted-old 2',
'deleted_page_chunks notes/deleted-recent 1',
'empty notes/empty-stub 0',
'keyword_only notes/fund-a-oversized 1',
- 'keyword_only notes/fund-a-oversized-bare 0',
'quarantined notes/junk-hidden 0',
'quarantined notes/junk-legacy 2',
]);
diff --git a/test/held-embedding-visibility-7174.test.ts b/test/held-embedding-visibility-7174.test.ts
new file mode 100644
index 0000000000..0dc39a24cf
--- /dev/null
+++ b/test/held-embedding-visibility-7174.test.ts
@@ -0,0 +1,38 @@
+/**
+ * #7174: pages held from embedding stay findable and visible.
+ *
+ * - Doctor `partial_embedding` says how many held or capped pages have waited more than a day
+ * (their budget row unchanged) and since when, so a hold nobody decided on is not silent.
+ *
+ * Hermetic PGLite through the same seed the held-embedding CLI tests use.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { seedHeldPage } from './helpers/held-embedding-fixture.ts';
+import { budgetLimitedFinding } from '../src/core/held-embedding.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+describe('doctor partial_embedding names holds nobody decided on', () => {
+ test('a hold unchanged for two days is counted with its date; a fresh one is not', async () => {
+ await seedHeldPage(engine, 'archive/old-example', 'default', 2);
+ await seedHeldPage(engine, 'archive/new-example', 'default', 2);
+ await engine.executeRaw("UPDATE page_embedding_budget SET updated_at = now() - interval '2 days' WHERE page_id = (SELECT id FROM pages WHERE slug = 'archive/old-example')");
+ const [row] = await engine.executeRaw<{ at: Date }>("SELECT b.updated_at AS at FROM page_embedding_budget b JOIN pages p ON p.id = b.page_id WHERE p.slug = 'archive/old-example'");
+ const at = new Date(row!.at).toISOString();
+ const found = await budgetLimitedFinding(engine, null);
+ expect(found?.details).toMatchObject({ held: 2, waiting_over_day: 1, oldest_updated_at: at });
+ expect(found?.message).toContain(` 1 of them have waited more than a day (oldest unchanged since ${at})`);
+ }, 60_000);
+
+ test('only fresh holds: no waited clause', async () => {
+ await seedHeldPage(engine, 'archive/new-example', 'default', 2);
+ const found = await budgetLimitedFinding(engine, null);
+ expect(found?.details).toMatchObject({ held: 1, waiting_over_day: 0 });
+ expect(found?.message).not.toContain('waited more than a day');
+ }, 60_000);
+});
diff --git a/test/oversized-backfill-failed-rewrite-7185.serial.test.ts b/test/oversized-backfill-failed-rewrite-7185.serial.test.ts
new file mode 100644
index 0000000000..6820c67728
--- /dev/null
+++ b/test/oversized-backfill-failed-rewrite-7185.serial.test.ts
@@ -0,0 +1,134 @@
+/**
+ * #7174 / #7184 / #7185: a size-skipped page whose backfill rewrite fails.
+ *
+ * The shape seen on a large brain: an older gbrain stored a large page with the
+ * gate's `embed_skip: oversized` marker and no chunks; `reindex --oversized`
+ * held it for embedding approval and then failed to rewrite it (in the field, a
+ * repeated facts fence the managed owner refuses; here, an uncoordinated local
+ * edit, which the owner refuses the same way). The page stayed
+ * held behind a marker nothing removes, with no chunks, so not even keyword
+ * search found it, and doctor said nothing was held.
+ *
+ * Now: the failed rewrite puts the budget row back, the chunk safety net
+ * (`embed --stale`, the cycle's embed phase) chunks the page for keyword
+ * search with no vector and no provider call, `embed --held` lists no hold on
+ * a marked page, and doctor `oversized_pages` counts the marked pages with and
+ * without chunks.
+ *
+ * Serial: installs the process-global embedding transport seam.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { buildEmbedSkipMarker, EMBED_SKIP_KEY } from '../src/core/embed-skip.ts';
+import { runOversizedBackfill, BACKFILL_HOLD_REASON } from '../src/core/oversized-backfill.ts';
+import { holdPageEmbedding, listBudgetLimitedPages } from '../src/core/page-embedding-budget.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { buildChecks } from '../src/commands/doctor.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+
+const DIMS = 1536;
+const NEEDLE = 'zebracornflowerneedle';
+const F = '<!--- gbrain:facts:begin -->', FE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const fact = (n: number) => `| ${n} | acme-example ships quarterly | fact | 1.0 | private | medium | 2026-01-01 | | chat | |`;
+const facts = (n: number) => `${F}\n${FH}\n${fact(n)}\n${FE}`;
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+let engine: PGLiteEngine;
+let providerCalls = 0;
+let home: string;
+
+function body(bytes: number): string {
+ const line = 'alice-example and bob-example talked about acme-example plans today.\n';
+ const half = line.repeat(Math.floor(bytes / 2 / line.length));
+ return `${half}The secret word is ${NEEDLE}.\n${half}`;
+}
+
+/** An older gbrain's size skip: the gate's markers and no chunk rows; the body repeats a facts fence, so a rewrite today is refused. */
+async function seedFencedSizeSkipped(slug: string, bytes: number): Promise<number> {
+ await engine.putPage(slug, { type: 'note', title: 'Long conversation', compiled_truth: `${facts(1)}\n\n${facts(2)}\n\n${body(bytes)}`, timeline: '',
+ frontmatter: { [EMBED_SKIP_KEY]: buildEmbedSkipMarker(bytes), content_flag: { reason: 'oversized' } } });
+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);
+ return Number(row!.id);
+}
+
+const budget = (pageId: number) => engine.executeRaw<{ state: string; reason: string | null }>('SELECT state, reason FROM page_embedding_budget WHERE page_id = $1', [pageId]);
+const keywordHits = async () => (await engine.searchKeyword(NEEDLE, { limit: 10 })).map(hit => hit.slug);
+const chunkState = async (pageId: number) => (await engine.executeRaw<{ chunks: number; vectors: number }>(
+ 'SELECT count(*)::int AS chunks, count(embedding)::int AS vectors FROM content_chunks WHERE page_id = $1', [pageId]))[0];
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' } });
+ __setEmbedTransportForTests((async (input: { values: string[] }) => {
+ providerCalls++;
+ return { embeddings: input.values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: input.values.length * 4 } };
+ }) as never);
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: DIMS } as never);
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); providerCalls = 0; home = mkdtempSync(join(tmpdir(), 'backfill-7185-')); });
+
+const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, HOME: home, GBRAIN_AUDIT_DIR: home }, fn).finally(() => rmSync(home, { recursive: true, force: true }));
+
+describe('a size-skipped page whose backfill rewrite fails', () => {
+ test('a managed rewrite the owner refuses leaves no hold behind; an existing row is restored', () => managedBrain(async ({ engine: brain, root }) => {
+ await brain.setConfig('pages.segmented_storage', 'off');
+ await performManagedSync(brain, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true } as never);
+ const ids = await brain.executeRaw<{ id: number; slug: string }>("SELECT id, slug FROM pages WHERE slug LIKE 'chats/%' ORDER BY slug");
+ expect(ids.map(row => row.slug)).toEqual(['chats/capped-example', 'chats/fenced-example']);
+ await brain.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const { id } of ids) {
+ await brain.executeRaw("UPDATE pages SET frontmatter = frontmatter || jsonb_build_object('embed_skip', jsonb_build_object('reason', 'oversized', 'bytes', 1500000)) WHERE id = $1", [id]);
+ await brain.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [id]);
+ }
+ await brain.executeRaw("INSERT INTO page_embedding_budget (page_id, state, reason) VALUES ($1, 'capped', 'cap_reached')", [Number(ids[0]!.id)]);
+ await brain.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ // Both canonical files carry a local edit the owner did not coordinate, so it refuses each rewrite.
+ for (const name of ['capped-example', 'fenced-example']) appendFileSync(join(root, 'chats', `${name}.md`), '\nA local edit.\n');
+
+ const receipt = await runOversizedBackfill(brain);
+ expect(receipt.failed.map(f => f.slug).sort()).toEqual(['chats/capped-example', 'chats/fenced-example']);
+ expect(receipt).toMatchObject({ reindexed: 0, held_for_approval: 0, remaining: 2 });
+ const rows = await brain.executeRaw<{ slug: string; state: string; reason: string }>('SELECT p.slug, b.state, b.reason FROM page_embedding_budget b JOIN pages p ON p.id = b.page_id ORDER BY p.slug');
+ expect(rows).toEqual([{ slug: 'chats/capped-example', state: 'capped', reason: 'cap_reached' }]);
+ }, { setup: ({ root }) => {
+ git(root, 'init', '-q');
+ mkdirSync(join(root, 'chats'));
+ for (const name of ['capped-example', 'fenced-example']) writeFileSync(join(root, 'chats', `${name}.md`), `---\ntype: note\ntitle: Long conversation\n---\n\n${body(1_500_000)}`);
+ git(root, 'add', '-A');
+ git(root, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'seed');
+ } }), 240_000);
+
+ test('the chunk safety net makes it keyword-searchable with no vector; doctor counts it; embed --held lists no hold on a marked page', () => inHome(async () => {
+ const pageId = await seedFencedSizeSkipped('chats/fenced-example', 1_500_000);
+ await holdPageEmbedding(engine, pageId, BACKFILL_HOLD_REASON);
+ expect(await keywordHits()).toEqual([]);
+
+ const before = (await buildChecks(engine, [])).find(c => c.name === 'oversized_pages');
+ expect(before).toMatchObject({ status: 'warn', details: { marked: 1, chunkless: 1 } });
+ expect(before!.message).toContain('1 have no chunks, so not even keyword search finds them, and 0 are keyword-only');
+ expect(await listBudgetLimitedPages(engine)).toEqual([]);
+
+ const result = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(result.chunkless_pages_healed).toBe(1);
+ expect(await keywordHits()).toEqual(['chats/fenced-example']);
+ const after = await chunkState(pageId);
+ expect(after!.chunks).toBeGreaterThan(100);
+ expect(after!.vectors).toBe(0);
+ expect(providerCalls).toBe(0);
+
+ const healed = (await buildChecks(engine, [])).find(c => c.name === 'oversized_pages');
+ expect(healed).toMatchObject({ status: 'warn', details: { marked: 1, chunkless: 0 } });
+ }), 120_000);
+});