Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract): a page over the block bound no longer fails extract --stale; the link phase and mention pass report it and finish the rest (#7357)
garrytana37bcd225ab7
diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 6dc7267cbc..5a07eab41b 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -39,6 +39,7 @@*/import { readFileSync, existsSync } from 'fs';+import { classifyItemFailure } from '../core/item-failure.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { ATTENDANCE_REPAIR_HELP, isAttendanceRepairRequest } from './extract-attendance-repair.ts';import { join, relative, dirname } from 'path';@@ -2214,6 +2215,7 @@ export async function extractStaleFromDB(// from a genuinely missing target.let skippedCrossSource = 0, skippedChanged = 0, skippedConcurrentWrite = 0;const unknownSource: UnknownSourceSkip[] = [];+ const contentFailures: string[] = [];const wantedEnabled = await isWantedPagesEnabled(engine);const plannerTick = await plannerStatsForLinkDrain(engine, async () => totalStale);@@ -2258,9 +2260,16 @@ export async function extractStaleFromDB(page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId });return !resolved.ok ? undefined : targetSlug === page.slug && resolved.toSourceId === page.source_id ? snapshot.page.type : targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type;} };- const extracted: Awaited<ReturnType<typeof extractSegmentedPageLinks>> = fullContent === null- ? await extractSegmentedPageLinks(engine, { ...withoutBody(snapshot.page), id: Number(snapshot.page.id), slug: page.slug, source_id: page.source_id }, resolver, { ...pageLinkOpts, temporal: true })- : await extractPageLinks(page.slug, fullContent, snapshot.page.frontmatter, snapshot.page.type, resolver, pageLinkOpts);+ // #7357: a page whose own content the reader refuses (a run over the block bound) is reported and stays stale; the sweep goes on.+ const extracted: Awaited<ReturnType<typeof extractSegmentedPageLinks>> | null = await (fullContent === null+ ? extractSegmentedPageLinks(engine, { ...withoutBody(snapshot.page), id: Number(snapshot.page.id), slug: page.slug, source_id: page.source_id }, resolver, { ...pageLinkOpts, temporal: true })+ : extractPageLinks(page.slug, fullContent, snapshot.page.frontmatter, snapshot.page.type, resolver, pageLinkOpts)).catch((error: unknown) => {+ const f = classifyItemFailure(error);+ if (f.scope !== 'item' || f.class !== 'content') throw error;+ contentFailures.push(`${page.source_id}:${page.slug}: ${f.code}: ${f.message.slice(0, 500)}`);+ return null;+ });+ if (!extracted) continue;if (!extracted.attendanceComplete) {skippedAttendanceIncomplete++;attendanceBlocked.push({ slug: page.slug, source_id: page.source_id, revision: snapshot.revision });@@ -2354,6 +2363,7 @@ export async function extractStaleFromDB(if (skippedChanged) log(settingsChangedSkipLine(skippedChanged));if (skippedConcurrentWrite) log(concurrentWriteSkipLine(skippedConcurrentWrite));if (unknownSource.length) log(unknownSourceSkipLine(unknownSource));+ if (contentFailures.length) log(`${contentFailures.length} page(s) failed link extraction and stay stale; the other pages were derived:\n ${contentFailures.slice(0, 20).join('\n ')}`);if (skippedMissingTarget > 0) {log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);}@@ -2372,10 +2382,11 @@ export async function extractStaleFromDB(...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skipped_changed: skippedChanged } : {}),...(skippedConcurrentWrite ? { skipped_concurrent_write: skippedConcurrentWrite } : {}),...(unknownSource.length ? { skipped_unknown_source: unknownSource.length, unknown_source_pages: unknownSource.slice(0, 20) } : {}), ...mentionJsonFields(mentions), ...counts,+ ...(contentFailures.length ? { failed: contentFailures.length, failures: contentFailures.slice(0, 20) } : {}),}) + '\n');}return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,- ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}), ...(unknownSource.length ? { skippedUnknownSource: unknownSource.length } : {}), mentions };+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}), ...(unknownSource.length ? { skippedUnknownSource: unknownSource.length } : {}), ...(contentFailures.length ? { linkFailed: contentFailures.length } : {}), mentions };}/**diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.tsindex 79e58bc5aa..e16e2337be 100644--- a/src/core/mentions/pass.ts+++ b/src/core/mentions/pass.ts@@ -56,6 +56,7 @@ import {type FindMentionsOpts, type Gazetteer, type GazetteerEntry, type GazetteerEntryKey, type Mention,} from '../by-mention.ts';import { bodyBlocks } from '../page-body/segment-blocks.ts';+import { classifyItemFailure } from '../item-failure.ts';import { linkableTypesFor, loadSourcePack, parseNameList, readMentionPolicy, type MentionPolicy, type PackTypes } from './policy.ts';import { deriveEntityAliases, type DerivedAlias } from './aliases.ts';import { normalizeAliasList } from '../search/alias-normalize.ts';@@ -87,8 +88,16 @@ export interface MentionPassResult {remaining: number;state: MentionState;error?: string;+ /** Pages whose own content the scanner refused (a run it must read whole is over its bound); they stay due and the pass goes on. */+ failed?: number;+ failures?: MentionPageFailure[];}+export interface MentionPageFailure { slug: string; source_id: string; code: string; message: string }++/** The failed pages a pass lists; `failed` still counts every one. */+export const MENTION_FAILURE_REPORT_LIMIT = 20;+export interface MentionPassOpts {sourceId?: string;/** Epoch ms; the pass stops between batches after it. Absent = run to completion. */@@ -461,15 +470,29 @@ async function reconcileSource(engine: BrainEngine, sourceId: string, gazetteer:if (!pages.length) return;after = pages[pages.length - 1]!.id;const found = new Map<number, Mention[]>();- for (const p of pages) found.set(Number(p.id), await pageMentions(engine, p, gazetteer,- { fromSlug: p.slug, fromSourceId: p.source_id, allowCrossSource, ignoreNames: parseNameList(p.mention_ignore) }));- await opts.beforePublish?.(pages.map(p => Number(p.id)));+ const readable: DuePage[] = [];+ for (const p of pages) {+ try {+ found.set(Number(p.id), await pageMentions(engine, p, gazetteer,+ { fromSlug: p.slug, fromSourceId: p.source_id, allowCrossSource, ignoreNames: parseNameList(p.mention_ignore) }));+ readable.push(p);+ } catch (error) {+ const failure = classifyItemFailure(error);+ if (failure.scope !== 'item' || failure.class !== 'content') throw error;+ result.failed = (result.failed ?? 0) + 1;+ if ((result.failures ??= []).length < MENTION_FAILURE_REPORT_LIMIT) {+ result.failures.push({ slug: p.slug, source_id: p.source_id, code: failure.code, message: failure.message.slice(0, 500) });+ }+ }+ }+ if (!readable.length) continue;+ await opts.beforePublish?.(readable.map(p => Number(p.id)));const outcome = await engine.transaction(async tx => {if (!sameGenerations(generations, await readGenerations(tx, genSources, true))) return null;const current = new Map((await tx.executeRaw<{ id: number; revision: string }>(`SELECT id, knowledge_revision::text AS revision FROM pages WHERE id = ANY($1::int[]) AND deleted_at IS NULL FOR SHARE`,- [pages.map(p => p.id)])).map(r => [Number(r.id), r.revision]));- const fresh = pages.filter(p => current.get(Number(p.id)) === p.revision);+ [readable.map(p => p.id)])).map(r => [Number(r.id), r.revision]));+ const fresh = readable.filter(p => current.get(Number(p.id)) === p.revision);if (!fresh.length) return { fresh: 0, created: 0, removed: 0 };const rows = await tx.executeRaw<{ id: number; from_page_id: number; to_slug: string; to_source_id: string; plain: boolean }>(`SELECT l.id, l.from_page_id, t.slug AS to_slug, t.source_id AS to_source_id,@@ -500,9 +523,9 @@ async function reconcileSource(engine: BrainEngine, sourceId: string, gazetteer:[sourceId, fresh.map(p => p.id), fresh.map(p => p.revision), MENTION_EXTRACTOR_VERSION, generations.get(sourceId) ?? '0']);return { fresh: fresh.length, created, removed: drop.length };});- if (!outcome) { result.skipped += pages.length; return; }+ if (!outcome) { result.skipped += readable.length; return; }result.pages += outcome.fresh;- result.skipped += pages.length - outcome.fresh;+ result.skipped += readable.length - outcome.fresh;result.created += outcome.created;result.removed += outcome.removed;}diff --git a/src/core/mentions/stale.ts b/src/core/mentions/stale.tsindex 634b88c78b..b78cdc97da 100644--- a/src/core/mentions/stale.ts+++ b/src/core/mentions/stale.ts@@ -57,15 +57,18 @@ export function formatMentionSummary(r: MentionPassResult): string | null {return r.removed ? `Mentions: linking is off (auto_link or mentions.auto_link); removed ${r.removed} mention link(s).` : null;}if (!r.pages && !r.removed && !r.remaining && !r.aliasPages) return null;+ const failed = r.failed ?? 0;return `Mentions: ${r.created} link(s) added, ${r.removed} removed from ${r.pages} page(s)` +(r.aliasPages ? `; derived names refreshed on ${r.aliasPages} entity page(s)` : '') +- (r.remaining ? `; ${r.remaining} page(s) still due — re-run 'gbrain extract --stale' (or pass --catch-up) to continue.` : '.');+ (r.remaining > failed ? `; ${r.remaining} page(s) still due — re-run 'gbrain extract --stale' (or pass --catch-up) to continue.` : '.') ++ (failed ? `\n${failed} page(s) could not be scanned for mentions and stay due until they change; the other pages were scanned${failed > (r.failures?.length ?? 0) ? ` (first ${r.failures?.length ?? 0} listed)` : ''}:` ++ (r.failures ?? []).map(f => `\n ${f.source_id}:${f.slug}: ${f.code}: ${f.message}`).join('') : '');}export function mentionJsonFields(r: MentionPassResult): Record<string, unknown> {return {mention_pages: r.pages, mention_links_created: r.created, mention_links_removed: r.removed,mention_alias_pages: r.aliasPages, mention_due_remaining: r.remaining, mention_state: r.state,- ...(r.error ? { mention_error: r.error } : {}),+ ...(r.error ? { mention_error: r.error } : {}), ...(r.failed ? { mention_failed: r.failed, mention_failures: r.failures ?? [] } : {}),};}diff --git a/test/extract-stale-over-bound-page-7357.test.ts b/test/extract-stale-over-bound-page-7357.test.tsnew file mode 100644index 0000000000..d4db3565a3--- /dev/null+++ b/test/extract-stale-over-bound-page-7357.test.ts@@ -0,0 +1,83 @@+/**+ * #7357: one page whose body holds a run longer than the block bound (a line or fence over 8 MiB) used to fail+ * `gbrain extract --stale` with page_body_segmented, managed or not, after the link phase spent its half of the budget:+ * the mention pass read the page block by block and the refusal escaped the run, so no later page was scanned and the+ * run exited 1 every time. Now the link phase and the mention pass each report that page, leave it stale and due, and+ * finish the other pages.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { BLOCK_MAX_BYTES } from '../src/core/page-body/segment-blocks.ts';+import { countMentionDuePages } from '../src/core/mentions/pass.ts';+import { formatMentionSummary } from '../src/core/mentions/stale.ts';+import { formatManagedStaleExtraction, runManagedStaleExtraction } from '../src/core/persistence/links-maintenance.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { mentionBrain, mentionLinks, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';++const MB = 1024 * 1024;+const ARCHIVE = 'notes/archive';++/** A note whose code fence runs past BLOCK_MAX_BYTES: segmented on import, and every block reader refuses it. */+function longFence(bytes: number): string {+ const body = Array.from({ length: Math.ceil(bytes / 32) }, (_, i) => 'code line ' + String(i).padStart(10, '0') + ' x = 1;\n').join('');+ return '---\ntitle: Archive\ntype: note\n---\nAlice Example pasted this.\n\n\`\`\`ts\n' + body + '\`\`\`\n\nAfter the fence.\n';+}++async function fixture(engine: BrainEngine): Promise<void> {+ await engine.setConfig('schema_pack', 'gbrain-base-v2');+ await engine.setConfig('pages.segmented_storage', 'on');+ await page(engine, 'people/alice-example', 'person', 'Alice Example', 'Alice Example fixture.');+ await page(engine, 'notes/meeting', 'note', 'Meeting', 'Met Alice Example about the plan.');+ expect((await importFromContent(engine, ARCHIVE, longFence(BLOCK_MAX_BYTES + 2 * MB), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ expect((await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [ARCHIVE]))[0]!.body_storage).toBe('segmented');+}++const linkStale = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ stale: boolean }>(+ 'SELECT links_extracted_at IS NULL AS stale FROM pages WHERE slug=$1', [slug]))[0]!.stale;++describe('extract --stale with an over-bound page (#7357), unmanaged', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = await mentionBrain(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => { await resetMentionBrain(engine); await fixture(engine); }, 300_000);++ test('the sweep finishes the other pages, and the page is reported, left stale and still due', async () => {+ const r = await sweep(engine);+ expect(r.linkFailed).toBe(1);+ expect(await linkStale(engine, ARCHIVE)).toBe(true);+ expect(await linkStale(engine, 'notes/meeting')).toBe(false);+ expect(await mentionLinks(engine)).toContain('notes/meeting -> people/alice-example');+ expect(r.mentions?.failed).toBe(1);+ expect(r.mentions?.failures).toEqual([expect.objectContaining({ slug: ARCHIVE, source_id: 'default', code: 'page_body_segmented' })]);+ expect(await countMentionDuePages(engine)).toBe(1);+ const again = await sweep(engine);+ expect(again.linkFailed).toBe(1);+ expect(again.mentions?.failed).toBe(1);+ }, 600_000);++ test('the report names the page and its code, and does not tell the user a re-run will finish it', async () => {+ const r = await sweep(engine);+ const line = formatMentionSummary(r.mentions!)!;+ expect(line).toContain(`default:${ARCHIVE}: page_body_segmented`);+ expect(line).toContain('1 page(s) could not be scanned for mentions and stay due until they change');+ expect(line).not.toContain('re-run');+ }, 600_000);+});++describe('extract --stale with an over-bound page (#7357), managed', () => {+ test('the managed run finishes the other pages and reports the page from both phases', async () => {+ await managedBrain(async ({ engine }) => {+ const r = await runManagedStaleExtraction(engine, { catchUp: true, counts: false });+ expect(r.failed).toBe(1);+ expect(r.failures?.[0]).toMatchObject({ slug: ARCHIVE, code: 'page_body_segmented' });+ expect(await linkStale(engine, ARCHIVE)).toBe(true);+ expect(await mentionLinks(engine)).toContain('notes/meeting -> people/alice-example');+ expect(r.mentions?.failures).toEqual([expect.objectContaining({ slug: ARCHIVE, code: 'page_body_segmented' })]);+ expect(await countMentionDuePages(engine)).toBe(1);+ const json = JSON.parse(formatManagedStaleExtraction(r, false, true)) as Record<string, unknown>;+ expect(json).toMatchObject({ failed: 1, mention_failed: 1 });+ }, { setup: ({ engine }) => fixture(engine) });+ }, 600_000);+});