Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract): rewrite the lost-write watermark implementation (#6954)
time-attack2fd5b926f931
diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex edfd31a3cd..a12214dc0d 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -53,7 +53,7 @@ import { effectiveLinkExtractorWatermark, linkExtractorWatermarkFor } from '../cimport { concurrentWriteSkipLine, replaceDerivedLinksBatchOrReplay, replaceDerivedLinksDeferringConflicts, settingsChangedSkipLine, unknownSourceSkipLine, type DerivedLinkBatchItem, type UnknownSourceSkip } from '../core/derived-links.ts';import { pageSnapshotKey } from '../core/page-snapshot-batch.ts';import type { PageSnapshot } from '../core/page-state/types.ts';-import { ExtractBatchWriteError, batchFailure, timelineSnapshotRefs, withoutFailedRefs, extractionWrite, type ExtractBatchFailure } from '../core/extract-watermark.ts';+import { LostWrites, extractionWrite, timelineSnapshotRefs } from '../core/extract-watermark.ts';export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';export { extractMarkdownLinks } from '../core/link-extraction.ts';import {@@ -805,7 +805,7 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Prreturn result;}- const failures: ExtractBatchFailure[] = [];+ const lost = new LostWrites();// Full walk path: CLI `gbrain extract` or first-run.//// #3957 review (D4): snapshot the walked pages' updated_at BEFORE the walk@@ -819,18 +819,16 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): PrstampRefs = refsWithSnapshotStamps(walkRefs, await snapshotStampTimes(engine, walkRefs));}if (opts.mode === 'links' || opts.mode === 'all') {- const r = await extractLinksFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet);+ const r = await extractLinksFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet, lost);result.links_created = r.created;result.pages_processed = r.pages;- failures.push(...r.failures);const processed = new Set(r.processed);stampRefs = stampRefs.filter(ref => processed.has(ref.slug));}if (opts.mode === 'timeline' || opts.mode === 'all') {- const r = await extractTimelineFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet);+ const r = await extractTimelineFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet, lost);result.timeline_entries_created = r.created;result.pages_processed = Math.max(result.pages_processed, r.pages);- failures.push(...r.failures);const processed = new Set(r.processed);stampRefs = stampRefs.filter(ref => processed.has(ref.slug));}@@ -844,14 +842,14 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr// source id + the row's pre-read updated_at (D4); files with no pages row// at snapshot time are skipped (nothing to stamp — they stay visible to// `extract --stale` once synced).- stampRefs = withoutFailedRefs(stampRefs, failures);+ stampRefs = lost.stampable(stampRefs);if (!dryRun && opts.mode === 'all' && !isAborted(opts.signal)) {for (let i = 0; i < stampRefs.length; i += BATCH_SIZE) {await stampExtracted(engine, stampRefs.slice(i, i + BATCH_SIZE));}}- if (failures.length) throw new ExtractBatchWriteError(failures);+ lost.throwIfAny();return result;}@@ -1354,7 +1352,7 @@ async function extractForSlugs(// Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).quiet: boolean = false,): Promise<{ links_created: number; timeline_created: number; pages: number }> {- const failures: ExtractBatchFailure[] = [];+ const lost = new LostWrites();const stdoutQuiet = jsonMode || quiet;// Build the full slug set for link resolution (fast: just readdir, no file reads)const allFiles = walkMarkdownFiles(brainDir);@@ -1407,7 +1405,7 @@ async function extractForSlugs(try {return await replacePageFileLinks(engine, slug, sourceId ?? 'default', links, includeFrontmatter, owner) ?? 0;} catch (e) {- failures.push(batchFailure('links', links.length, [{ slug, source_id: sourceId ?? 'default' }], e));+ lost.record('links', links.length, [{ slug, source_id: sourceId ?? 'default' }], e);const msg = e instanceof Error ? e.message : String(e);if (jsonMode) {process.stderr.write(JSON.stringify({ event: 'batch_error', size: links.length, error: msg }) + '\n');@@ -1425,7 +1423,7 @@ async function extractForSlugs(try {timelineCreated += await addProjectedTimelineBatch(engine, snapshot, { auditSite: 'extract.timeline_inc' });} catch (e) {- failures.push(batchFailure('timeline', snapshot.length, timelineSnapshotRefs(snapshot), e));+ lost.record('timeline', snapshot.length, timelineSnapshotRefs(snapshot), e);const msg = e instanceof Error ? e.message : String(e);if (jsonMode) {process.stderr.write(JSON.stringify({ event: 'batch_error', size: snapshot.length, error: msg }) + '\n');@@ -1494,7 +1492,7 @@ async function extractForSlugs(pagesProcessed++;if (!dryRun) processedRefs.push({ slug, source_id: sourceId ?? 'default' });} catch (error) {- if ((error as { code?: unknown })?.code === 'extract_write_lost') failures.push(...(error as ExtractBatchWriteError).failures);+ lost.absorb(error);}progress.tick(1);},@@ -1508,7 +1506,7 @@ async function extractForSlugs(// with the pre-read updated_at snapshot (D4) — refs the snapshot never// saw (row created mid-run) are skipped and stay stale.if (!dryRun && mode === 'all') {- await stampExtracted(engine, refsWithSnapshotStamps(withoutFailedRefs(processedRefs, failures), stampSnapshot));+ await stampExtracted(engine, refsWithSnapshotStamps(lost.stampable(processedRefs), stampSnapshot));}progress.finish();@@ -1517,7 +1515,7 @@ async function extractForSlugs(console.log(`Incremental extract: ${label} ${linksCreated} link(s), ${timelineCreated} timeline entries from ${pagesProcessed}/${slugs.length} page(s)`);}- if (failures.length) throw new ExtractBatchWriteError(failures);+ lost.throwIfAny();return { links_created: linksCreated, timeline_created: timelineCreated, pages: pagesProcessed };}@@ -1530,7 +1528,8 @@ async function extractLinksFromDir(sourceId?: string,// Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).quiet: boolean = false,-): Promise<{ created: number; pages: number; processed: string[]; failures: ExtractBatchFailure[] }> {+ lost: LostWrites = new LostWrites(),+): Promise<{ created: number; pages: number; processed: string[] }> {const stdoutQuiet = jsonMode || quiet;const files = walkMarkdownFiles(brainDir);const allSlugs = new Set(files.map(f => pathToSlug(f.relPath)));@@ -1546,7 +1545,6 @@ async function extractLinksFromDir(const pageTypes = loadFsPageTypes(files, pack);const ownership = dryRun ? undefined : await fileLinkOwnership(engine, sourceId ?? 'default');const processed: string[] = [];- const failures: ExtractBatchFailure[] = [];// Progress stream on stderr (separate from the action-events --json writes// to stdout, which tests grep for). Rate-gated; respects global --quiet /@@ -1568,7 +1566,6 @@ async function extractLinksFromDir(// #1972: bail before this file on abort; each page's links are replaced in its own transaction.if (isAborted(signal)) return;if (quarantined.has(pathToSlug(file.relPath))) return;- let writing = false;try {const slug = pathToSlug(file.relPath);const snapshot = ownership && (ownership.metadata.get(`${sourceId ?? 'default'}\0${slug}`)?.type === 'meeting' || ownership.origins.has(slug))@@ -1576,16 +1573,16 @@ async function extractLinksFromDir(const content = readFileSync(file.path, 'utf-8');const links = await extractLinksFromFile(content, file.relPath, allSlugs, { globalBasename, pack, pageTypes });if (ownership) {- writing = true;- let written: number | null | undefined;- if (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug)) {- if (!snapshot) throw new Error('Link extraction origin is missing');- written = await replaceFileLinks(engine, slug, sourceId ?? 'default', links, false, snapshot, ownership, content, { pack, globalBasename });- if (written === null) return;- }- // A file with no page row yet has nothing to reconcile; it is not processed.- written ??= await replacePageFileLinks(engine, slug, sourceId ?? 'default', links, false, ownership);- if (written === null) return;+ const written = await extractionWrite('links', links.length, [{ slug, source_id: sourceId ?? 'default' }], async () => {+ if (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug)) {+ if (!snapshot) throw new Error('Link extraction origin is missing');+ const replaced = await replaceFileLinks(engine, slug, sourceId ?? 'default', links, false, snapshot, ownership, content, { pack, globalBasename });+ if (replaced !== undefined) return replaced;+ }+ // A file with no page row yet has nothing to reconcile; it is not processed.+ return replacePageFileLinks(engine, slug, sourceId ?? 'default', links, false, ownership);+ });+ if (written == null) return;created += written;} else for (const link of links) {const key = `${link.from_slug}::${link.to_slug}::${link.link_type}`;@@ -1596,7 +1593,7 @@ async function extractLinksFromDir(}processed.push(slug);} catch (error) {- if (writing) failures.push(batchFailure('links', 0, [{ slug: pathToSlug(file.relPath), source_id: sourceId ?? 'default' }], error));+ lost.absorb(error);}progress.tick(1);},@@ -1607,7 +1604,7 @@ async function extractLinksFromDir(const label = dryRun ? '(dry run) would create' : 'created';console.log(`Links: ${label} ${created} from ${files.length} pages`);}- return { created, pages: files.length, processed, failures };+ return { created, pages: files.length, processed };}async function extractTimelineFromDir(@@ -1620,9 +1617,9 @@ async function extractTimelineFromDir(sourceId?: string,// Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).quiet: boolean = false,-): Promise<{ created: number; pages: number; processed: string[]; failures: ExtractBatchFailure[] }> {+ lost: LostWrites = new LostWrites(),+): Promise<{ created: number; pages: number; processed: string[] }> {const processed: string[] = [];- const failures: ExtractBatchFailure[] = [];const stdoutQuiet = jsonMode || quiet;const files = walkMarkdownFiles(brainDir);const quarantined = await quarantinedSlugs(engine, sourceId ?? 'default');@@ -1642,7 +1639,7 @@ async function extractTimelineFromDir(try {created += await addProjectedTimelineBatch(engine, snapshot, { auditSite: 'extract.timeline_fs' });} catch (e) {- failures.push(batchFailure('timeline', snapshot.length, timelineSnapshotRefs(snapshot), e));+ lost.record('timeline', snapshot.length, timelineSnapshotRefs(snapshot), e);const msg = e instanceof Error ? e.message : String(e);if (jsonMode) {process.stderr.write(JSON.stringify({ event: 'batch_error', size: snapshot.length, error: msg }) + '\n');@@ -1689,7 +1686,7 @@ async function extractTimelineFromDir(const label = dryRun ? '(dry run) would create' : 'created';console.log(`Timeline: ${label} ${created} entries from ${files.length} pages`);}- return { created, pages: files.length, processed, failures };+ return { created, pages: files.length, processed };}// --- Sync integration hooks ---diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 1e643b38f7..5b8af25fdf 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1379,7 +1379,7 @@ async function runPhaseExtract(sourceId?: string,): Promise<PhaseResult> {try {- const { runExtractCore } = await import('../commands/extract.ts');+ const [{ runExtractCore }, { ExtractBatchWriteError }] = await Promise.all([import('../commands/extract.ts'), import('./extract-watermark.ts')]);const { resolveIncludeFrontmatter } = await import('./extract-frontmatter.ts');// Shared resolver (file plane wins, then DB plane, fail-closed) so this// cycle, sync's inline extract, the extract_stale minion and maintain all@@ -1399,7 +1399,7 @@ async function runPhaseExtract(}// Incremental path: if sync told us which slugs changed, only extract those.// On a 54K-page brain this turns a 10-minute full walk into a sub-second pass.- // PR #6954: a lost link/timeline write leaves its pages unstamped (still due), so the stale drain below retries them; warn, like A-1.+ // #6954: a lost link/timeline write leaves its pages due; the stale drain below retries them and the phase warns.let lostWrites: string | null = null;const result = await runExtractCore(engine, {mode: 'all',@@ -1410,7 +1410,7 @@ async function runPhaseExtract(signal,sourceId,includeFrontmatter, // honored on the incremental (slugs) path only- }).catch((e: unknown) => { if ((e as { code?: unknown } | null)?.code !== 'extract_write_lost') throw e; lostWrites = `; ${(e as Error).message}`; return null; });+ }).catch((error: unknown) => { if (!(error instanceof ExtractBatchWriteError)) throw error; lostWrites = `; ${error.message}`; return null; });const linksCreated = result?.links_created ?? 0;const timelineCreated = result?.timeline_entries_created ?? 0;const incremental = changedSlugs !== undefined;diff --git a/src/core/extract-watermark.ts b/src/core/extract-watermark.tsindex 1b2cd71cdb..003ed725ef 100644--- a/src/core/extract-watermark.ts+++ b/src/core/extract-watermark.ts@@ -1,76 +1,97 @@/**- * #6954: a link or timeline write that extraction loses (after the engine's- * own retries) must leave its pages due. These helpers carry the pages of a- * failed write to the watermark stamp, so pages whose rows were dropped are- * never stamped `links_extracted_at`, and `ExtractBatchWriteError`- * (`extract_write_lost`) reports the loss after the safe pages were stamped.+ * #6954: extraction stamps `links_extracted_at` only for pages whose link and+ * timeline rows all landed. A write the engine gives up on is recorded here+ * with the pages it covered; the stamp skips those pages, so they stay due for+ * `extract --stale` and the cycle's stale drain, and the run then fails with+ * `extract_write_lost` after the other pages were stamped.*/import type { TimelineBatchInput } from './engine.ts';-export type PageRef = { slug: string; source_id: string };-export function pageRefKey(r: PageRef): string { return `${r.source_id}\0${r.slug}`; }++export interface PageRef { slug: string; source_id: string }+export interface ExtractBatchFailure {- /** Which write was lost: a link batch or a timeline batch. */kind: 'links' | 'timeline';- /** Rows in the lost write. */+ /** Rows the lost write carried. */rows: number;- /** Deduplicated pages the lost write represented (row endpoints plus emitting pages). */+ /** Each page the lost write covered, once. */refs: PageRef[];error: unknown;}-/**- * One or more link/timeline writes failed after the engine's own- * retries. Thrown AFTER safe pages were stamped; the affected pages (left- * unstamped) stay due: the CLI exits 1, the extract job retries, and the cycle- * extract phase reports `warn` and lets its stale drain retry them.- */+const refKey = (ref: PageRef): string => JSON.stringify([ref.source_id, ref.slug]);++function distinctRefs(refs: Iterable<PageRef>): PageRef[] {+ const byKey = new Map<string, PageRef>();+ for (const ref of refs) {+ const key = refKey(ref);+ if (!byKey.has(key)) byKey.set(key, { slug: ref.slug, source_id: ref.source_id });+ }+ return [...byKey.values()];+}++function lostWriteMessage(failures: ExtractBatchFailure[]): string {+ const refs = distinctRefs(failures.flatMap(f => f.refs));+ const rows = failures.reduce((total, f) => total + f.rows, 0);+ const kinds = [...new Set(failures.map(f => f.kind))].join('/');+ const sources = [...new Set(refs.map(r => r.source_id))];+ const cause = failures[0]?.error;+ const retry = sources.length === 1 ? `gbrain extract --stale --source-id ${sources[0]}` : 'gbrain extract --stale';+ return `extract: ${failures.length} ${kinds} write(s) failed (${rows} row(s)) across ${refs.length} page(s); `+ + `those pages were left unstamped and remain due (first error: ${cause instanceof Error ? cause.message : String(cause)}). `+ + `Retry them with: ${retry}`;+}++/** The run lost one or more writes; thrown after every other page was stamped. */export class ExtractBatchWriteError extends Error {readonly code = 'extract_write_lost';readonly failures: ExtractBatchFailure[];constructor(failures: ExtractBatchFailure[]) {- const rows = failures.reduce((n, f) => n + f.rows, 0);- const pages = new Set(failures.flatMap(f => f.refs.map(pageRefKey))).size;- const kinds = [...new Set(failures.map(f => f.kind))].join('/');- const first = failures[0]?.error;- const sources = [...new Set(failures.flatMap(f => f.refs.map(r => r.source_id)))];- const firstMsg = first instanceof Error ? first.message : String(first);- super(- `extract: ${failures.length} ${kinds} write(s) failed (${rows} row(s)) across ${pages} page(s); ` +- `those pages were not stamped and remain due (first error: ${firstMsg}). ` +- `Retry them with: gbrain extract --stale${sources.length === 1 ? ` --source-id ${sources[0]}` : ''}`,- );+ super(lostWriteMessage(failures));this.name = 'ExtractBatchWriteError';this.failures = failures;}}-export function batchFailure(- kind: ExtractBatchFailure['kind'],- rows: number,- refs: Iterable<PageRef>,- error: unknown,-): ExtractBatchFailure {- const byKey = new Map<string, PageRef>();- for (const r of refs) byKey.set(pageRefKey(r), { slug: r.slug, source_id: r.source_id });- return { kind, rows, refs: [...byKey.values()], error };+export function batchFailure(kind: ExtractBatchFailure['kind'], rows: number, refs: Iterable<PageRef>, error: unknown): ExtractBatchFailure {+ return { kind, rows, refs: distinctRefs(refs), error };}export function timelineSnapshotRefs(rows: TimelineBatchInput[]): PageRef[] {- return rows.map(r => ({ slug: r.slug, source_id: r.source_id ?? 'default' }));+ return rows.map(row => ({ slug: row.slug, source_id: row.source_id ?? 'default' }));}-/** Drop every ref that appears in any failed write. */+/** The refs no lost write covered, in their original order. */export function withoutFailedRefs<T extends PageRef>(refs: T[], failures: ExtractBatchFailure[]): T[] {if (failures.length === 0) return refs;- const failed = new Set(failures.flatMap(f => f.refs.map(pageRefKey)));- return refs.filter(r => !failed.has(pageRefKey(r)));+ const lost = new Set(failures.flatMap(f => f.refs.map(refKey)));+ return refs.filter(ref => !lost.has(refKey(ref)));}-/** Annotate a failing native write without changing its transaction/retry policy. */+/** Runs one write; a failure becomes an `ExtractBatchWriteError` naming its pages (an existing one passes through). */export async function extractionWrite<T>(kind: ExtractBatchFailure['kind'], rows: number, refs: PageRef[], write: () => Promise<T>): Promise<T> {- try { return await write(); }- catch (error) {- if ((error as { code?: unknown })?.code === 'extract_write_lost') throw error;- throw new ExtractBatchWriteError([batchFailure(kind, rows, refs, error)]);+ try {+ return await write();+ } catch (error) {+ throw error instanceof ExtractBatchWriteError ? error : new ExtractBatchWriteError([batchFailure(kind, rows, refs, error)]);+ }+}++/** The lost writes of one extraction run. */+export class LostWrites {+ readonly failures: ExtractBatchFailure[] = [];+ record(kind: ExtractBatchFailure['kind'], rows: number, refs: Iterable<PageRef>, error: unknown): void {+ this.failures.push(batchFailure(kind, rows, refs, error));+ }+ /** Keeps the failures of an `ExtractBatchWriteError`; false for any other error. */+ absorb(error: unknown): boolean {+ if (!(error instanceof ExtractBatchWriteError)) return false;+ this.failures.push(...error.failures);+ return true;+ }+ stampable<T extends PageRef>(refs: T[]): T[] {+ return withoutFailedRefs(refs, this.failures);+ }+ throwIfAny(): void {+ if (this.failures.length > 0) throw new ExtractBatchWriteError(this.failures);}}