Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Budget, defer and read a segmented page at most three times in the sweep links pass; detach its timeline entries (fix C5, C6)
garrytan86390781ebd4
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.tsindex c354575f3f..ea4dbd099e 100644--- a/src/core/page-body/read-range.ts+++ b/src/core/page-body/read-range.ts@@ -171,13 +171,14 @@ interface LoadedSegment {}/** The rows' texts and JSON metadata, one text at a time (metadata in batches). */-async function* loadSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[]): AsyncIterable<LoadedSegment> {+async function* loadSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[], stop?: () => void): AsyncIterable<LoadedSegment> {for (let at = 0; at < rows.length; at += HEAVY_BATCH) {const batch = rows.slice(at, at + HEAVY_BATCH);const meta = new Map((await engine.executeRaw<Record<string, unknown>>(`SELECT occurrence_id, entry_state, protected_regionsFROM page_body_manifest WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND staging_id IS NULL AND gen_from<=$3 AND (gen_to IS NULL OR gen_to>$3)`,[body.pageId, batch.map(r => r.occurrenceId), body.generation])).map(m => [Number(m.occurrence_id), m]));for (const row of batch) {+ stop?.();const m = meta.get(row.occurrenceId);const bytes = (await engine.readSegmentTexts(body.sourceId, [row.sha256])).get(Buffer.from(row.sha256).toString('hex'));if (!m || bytes === undefined) throw projectionStaleError(row.byteStart, 'its manifest row or text is missing');@@ -327,9 +328,12 @@ export interface TrustedSegment {pieces: ProjectedPiece[];}-/** The trusted body of `rows` (rows of `body`, in order), one segment at a time: what readBodyRange's trusted stored read cuts. */-export async function* trustedSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[]): AsyncIterable<TrustedSegment> {- for await (const seg of loadSegments(engine, body, rows)) {+/**+ * The trusted body of `rows` (rows of `body`, in order), one segment at a time: what readBodyRange's trusted stored read+ * cuts. `stop` is called before each segment text is read; it throws to end the read there.+ */+export async function* trustedSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[], stop?: () => void): AsyncIterable<TrustedSegment> {+ for await (const seg of loadSegments(engine, body, rows, stop)) {const raw = utf8.decode(seg.bytes);yield { row: seg.row, raw: seg.bytes, entryState: seg.entryState, pieces: overlaidPieces(raw, await overlaidText(engine, body, seg, raw, 'trusted')) };}diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.tsindex f49f7fb194..9c2e922bf9 100644--- a/src/core/page-body/segment-blocks.ts+++ b/src/core/page-body/segment-blocks.ts@@ -77,6 +77,16 @@ export interface BodyBlockOptions {* read. A block after a skipped run has `at` NaN.*/want?: (run: { seqs: readonly number[]; first: boolean }) => boolean;+ /** Asked before each segment is read: true ends the read with BodyReadStopped (a caller's time budget ran out). */+ stop?: () => boolean;+}++/** bodyBlocks ended before a segment read because `stop` said so; nothing after the blocks already yielded was read. */+export class BodyReadStopped extends Error {+ constructor(readonly slug: string) {+ super(`Reading page ${slug} stopped: the caller's budget ran out.`);+ this.name = 'BodyReadStopped';+ }}/** `page_body_segmented`: a run a derived pass must read whole is over BLOCK_MAX_BYTES. */@@ -139,7 +149,8 @@ export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug:start = end;return block;};- for await (const seg of trustedSegments(engine, body, rows.slice(i, j + 1))) {+ const stop = opts.stop;+ for await (const seg of trustedSegments(engine, body, rows.slice(i, j + 1), stop && (() => { if (stop()) throw new BodyReadStopped(page.slug); }))) {bodyRowWork.visits++;if (previous && freshAfterForcedCut(previous, seg, body.stale)) yield flush(seg.row.byteStart);const end = seg.row.byteStart + seg.row.byteLen;diff --git a/src/core/page-body/segment-links.ts b/src/core/page-body/segment-links.tsindex 5b4a6bbf82..1ee6d5680a 100644--- a/src/core/page-body/segment-links.ts+++ b/src/core/page-body/segment-links.ts@@ -112,10 +112,11 @@ export async function segmentedRoleText(engine: BrainEngine, page: { id: number;/*** extractPageLinks(slug, `${compiled_truth}\n${timeline}`, ...) of a segmented page, streamed; `regions` narrows the* body (the remote mention effect reads the compiled truth only). With `temporal`, also collects the body's temporal- * inputs (dated lines, narrative references, ranged relation lines) for publication.+ * inputs (dated lines, narrative references, ranged relation lines) for publication. `onBlock` sees each block once,+ * in order, so a caller can parse the same read for something else.*/export async function extractSegmentedPageLinks(engine: BrainEngine, page: SegmentedLinkPage, resolver: SlugResolver,- opts: ExtractPageLinksOptions & BodyBlockOptions & { temporal?: boolean } = {}): Promise<PageLinksResult & { temporalBody?: TemporalBody }> {+ opts: ExtractPageLinksOptions & BodyBlockOptions & { temporal?: boolean; onBlock?: (block: BodyBlock) => void } = {}): Promise<PageLinksResult & { temporalBody?: TemporalBody }> {const roleText = opts.roleText ?? await segmentedRoleText(engine, page, opts);const regexBudget = opts.regexBudget ?? new PageRegexBudget();const kept = new Map<string, BodyLinkCandidate & { seq: number }>();@@ -126,6 +127,7 @@ export async function extractSegmentedPageLinks(engine: BrainEngine, page: Segmeconst body = await extractBodyLinks(page.slug, w.text, page.type, resolver,{ ...opts, roleText, regexBudget, window: { start: w.start, end: w.end, offset: w.offset } });attendanceComplete &&= body.attendanceComplete;+ opts.onBlock?.(w.block);for (const link of body.links) {const key = candidateKey(link.candidate);const prior = kept.get(key);diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 2d02dd176e..37907df5cb 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -250,6 +250,7 @@ export async function runMaintenanceSweep(overBudget,report,skip,+ log,});}} catch (e) {@@ -303,6 +304,18 @@ interface PassCtx {skip: (reason: string, count?: number) => void;}+/**+ * Segmented pages whose links/timeline pass did not fit a sweep's budget, `source\0slug` to the page's updated_at then:+ * later sweeps in this process skip them until the page changes, so one page too large for any budget cannot take+ * every sweep's budget. `gbrain extract --stale` extracts them.+ */+const deferredSegmentedPages = new Map<string, string>();++/** Test seam: forget deferred segmented pages. */+export function _resetDeferredSegmentedPagesForTests(): void {+ deferredSegmentedPages.clear();+}+/*** Pass 2 body. Calls the SAME per-page cores as `gbrain extract* links|timeline --source db` (extract.ts:extractLinksFromDB /@@ -313,9 +326,9 @@ interface PassCtx {*/async function runLinksTimelinePass(engine: BrainEngine,- ctx: PassCtx & { cutoffIso: string },+ ctx: PassCtx & { cutoffIso: string; log: (msg: string) => void },): Promise<void> {- const { sourceId, batchLimit, cutoffIso, overBudget, report, skip } = ctx;+ const { sourceId, batchLimit, cutoffIso, overBudget, report, skip, log } = ctx;const {extractPageLinks,@@ -344,9 +357,10 @@ async function runLinksTimelinePass(// job; the sweep is a recency back-stop). The µs to_char projection is the// #1768 stamp discipline: stamp the row's READ updated_at, not now(), so an// edit between SELECT and stamp stays stale and re-sweeps.- const recent = await engine.executeRaw<{ slug: string; updated_at_iso: string }>(+ const recent = await engine.executeRaw<{ slug: string; updated_at_iso: string; body_storage: string | null; body_bytes: number | null }>(`SELECT slug,- to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso+ to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso,+ body_storage, body_bytesFROM pagesWHERE source_id = $1AND deleted_at IS NULL@@ -373,220 +387,263 @@ async function runLinksTimelinePass(type Extracted = Awaited<ReturnType<typeof extractPageLinks>>;type Snapshot = NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>;- // A segmented body is read block by block (page-body/segment-links.ts), never as one string.- const { extractSegmentedPageLinks } = await import('./page-body/segment-links.ts');- const { bodyBlocks } = await import('./page-body/segment-blocks.ts');- const linksOf = (snapshot: Snapshot, opts: Parameters<typeof extractPageLinks>[5] & { temporal?: boolean }): ReturnType<typeof extractSegmentedPageLinks> => {- const { page } = snapshot;- return isSegmentedPage(page)- ? extractSegmentedPageLinks(engine, { id: Number(page.id), slug: page.slug, source_id: sourceId, type: page.type, frontmatter: page.frontmatter }, resolver, opts)- : extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter, page.type, resolver, opts);- };- const temporalBodies = new Map<string, NonNullable<Awaited<ReturnType<typeof extractSegmentedPageLinks>>['temporalBody']>>();-- const tlBatch: TimelineBatchInput[] = [];- const processedRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];- const pageCandidates: Array<{ slug: string; candidates: Extracted['candidates'] }> = [];- const snapshots = new Map<string, Snapshot>();+ const { extractSegmentedPageLinks, segmentedRoleText } = await import('./page-body/segment-links.ts');+ const { bodyBlocks, BodyReadStopped, detachedValue } = await import('./page-body/segment-blocks.ts');- // Phase 1: per-page extraction. The per-slug getPage loop stays a loop —- // BrainEngine has no batch read-by-slug-list primitive (resolveSlugsByPaths- // is path→slug only), and the loop is bounded by batchLimit (default 20).- for (let i = 0; i < recent.length; i++) {- if (overBudget()) {- skip('budget_exhausted:links_timeline', recent.length - i);- break;- }- const slug = recent[i].slug;- const page = await engine.getPage(slug, { sourceId });- if (!page) continue;- const snapshot = await engine.readPageSnapshot(slug, { sourceId });- const segmented = isSegmentedPage(page);- if (!snapshot || segmented !== isSegmentedPage(snapshot.page)- || (!segmented && (snapshot.page.compiled_truth !== page.compiled_truth || snapshot.page.timeline !== page.timeline))- || snapshot.page.type !== page.type || JSON.stringify(snapshot.page.frontmatter) !== JSON.stringify(page.frontmatter)) continue;- snapshots.set(slug, snapshot);+ /**+ * One batch through every phase. A segmented page's reads ask `stop` before each segment, so one that does not fit+ * the budget throws BodyReadStopped between segments.+ */+ const runBatch = async (recent: Array<{ slug: string; updated_at_iso: string }>, stop?: () => boolean): Promise<void> => {+ // A segmented body is read block by block (page-body/segment-links.ts), never as one string: its role phrases once+ // for both extractions, and its timeline entries from the first extraction's blocks.+ const roleTexts = new Map<string, string>();+ const linksOf = async (snapshot: Snapshot, opts: Parameters<typeof extractPageLinks>[5] & { temporal?: boolean; onBlock?: (block: { text: string }) => void }): ReturnType<typeof extractSegmentedPageLinks> => {+ const { page } = snapshot;+ if (!isSegmentedPage(page)) return extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter, page.type, resolver, opts);+ const ref = { id: Number(page.id), slug: page.slug, source_id: sourceId, type: page.type, frontmatter: page.frontmatter };+ const roleText = roleTexts.get(page.slug) ?? await segmentedRoleText(engine, ref, { stop });+ roleTexts.set(page.slug, roleText);+ return extractSegmentedPageLinks(engine, ref, resolver, { ...opts, roleText, stop });+ };+ const temporalBodies = new Map<string, NonNullable<Awaited<ReturnType<typeof extractSegmentedPageLinks>>['temporalBody']>>();++ const tlBatch: TimelineBatchInput[] = [];+ const processedRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];+ const pageCandidates: Array<{ slug: string; candidates: Extracted['candidates'] }> = [];+ const snapshots = new Map<string, Snapshot>();++ // Phase 1: per-page extraction. The per-slug getPage loop stays a loop —+ // BrainEngine has no batch read-by-slug-list primitive (resolveSlugsByPaths+ // is path→slug only), and the loop is bounded by batchLimit (default 20).+ for (let i = 0; i < recent.length; i++) {+ if (overBudget()) {+ skip('budget_exhausted:links_timeline', recent.length - i);+ break;+ }+ const slug = recent[i].slug;+ const page = await engine.getPage(slug, { sourceId });+ if (!page) continue;+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ const segmented = isSegmentedPage(page);+ if (!snapshot || segmented !== isSegmentedPage(snapshot.page)+ || (!segmented && (snapshot.page.compiled_truth !== page.compiled_truth || snapshot.page.timeline !== page.timeline))+ || snapshot.page.type !== page.type || JSON.stringify(snapshot.page.frontmatter) !== JSON.stringify(page.frontmatter)) continue;+ snapshots.set(slug, snapshot);++ // A segmented page's entries are copied off their block (detachedValue), or each would keep its whole block alive.+ const entries: ReturnType<typeof parseTimelineEntries> = [];+ const timelineOf = (block: { text: string }) => { for (const entry of parseTimelineEntries(block.text)) entries.push(detachedValue(entry)); };+ if (linksEnabled) {+ // skipFrontmatter matches user-invoked `gbrain extract links`+ // (frontmatter backfill stays a migration-orchestrator concern).+ const extracted = await linksOf(snapshot, { skipFrontmatter: true, globalBasename, pack, temporal: segmented,+ ...(segmented && timelineEnabled ? { onBlock: timelineOf } : {}) });+ if (extracted.temporalBody) temporalBodies.set(slug, extracted.temporalBody);+ if (extracted.candidates.length > 0) {+ pageCandidates.push({ slug, candidates: extracted.candidates });+ }+ }- if (linksEnabled) {- // skipFrontmatter matches user-invoked `gbrain extract links`- // (frontmatter backfill stays a migration-orchestrator concern).- const extracted = await linksOf(snapshot, { skipFrontmatter: true, globalBasename, pack, temporal: segmented });- if (extracted.temporalBody) temporalBodies.set(slug, extracted.temporalBody);- if (extracted.candidates.length > 0) {- pageCandidates.push({ slug, candidates: extracted.candidates });+ if (timelineEnabled) {+ if (!segmented) entries.push(...parseTimelineEntries(page.compiled_truth + '\n' + page.timeline));+ else if (!linksEnabled) for await (const block of bodyBlocks(engine, snapshot.page, { stop })) timelineOf(block);+ for (const entry of entries) {+ // Same row shape as extractTimelineFromDB's batch push (extract.ts):+ // #3957 — parsed source label threaded so FS- and DB-extracted rows+ // share one dedup shape; detail '' when empty.+ tlBatch.push({+ slug,+ date: entry.date,+ source: entry.source,+ summary: entry.summary,+ detail: entry.detail || '',+ source_id: sourceId,+ });+ }}++ processedRefs.push({ slug, source_id: sourceId, extractedAt: recent[i].updated_at_iso });}- if (timelineEnabled) {- const entries = segmented ? [] : parseTimelineEntries(page.compiled_truth + '\n' + page.timeline);- if (segmented) for await (const block of bodyBlocks(engine, snapshot.page)) entries.push(...parseTimelineEntries(block.text));- for (const entry of entries) {- // Same row shape as extractTimelineFromDB's batch push (extract.ts):- // #3957 — parsed source label threaded so FS- and DB-extracted rows- // share one dedup shape; detail '' when empty.- tlBatch.push({- slug,- date: entry.date,- source: entry.source,- summary: entry.summary,- detail: entry.detail || '',- source_id: sourceId,- });+ // Phase 2: endpoint validation is scoped to the slugs the candidates+ // actually name — NOT engine.listAllPageRefs() (the full (slug, source_id)+ // map, O(all pages) per sweep; the extract command amortizes that cost over+ // a whole-brain run, a recurring bounded sweep must not). The targeted+ // lookup keeps listAllPageRefs' visibility semantics (deleted_at IS NULL),+ // so resolveCandidateSources' F10 resolution is unchanged — it just sees+ // only the rows it can possibly use. Zero candidates ⇒ zero queries.+ const linkBatch: LinkBatchInput[] = [];+ const endpointMetadata = new Map<string, { slug: string; source_id: string; type: string; knowledge_revision: string }>();+ const incomplete = new Set<string>();+ const wantedBySlug = new Map<string, WantedLinkInput[]>();+ const wantedEnabled = await isWantedPagesEnabled(engine);+ // One settings snapshot per sweep; publication refuses a page if the settings move meanwhile (it stays unstamped).+ const grammar = await readLineGrammarSettings(engine);+ const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };+ if (pageCandidates.length > 0) {+ const needed = new Set<string>();+ for (const { slug, candidates } of pageCandidates) {+ needed.add(slug);+ for (const c of candidates) {+ needed.add(c.targetSlug);+ if (c.fromSlug) needed.add(c.fromSlug);+ }+ }+ const { allSlugs, slugToSources, metadata } = await lookupRefsForSlugs(engine, [...needed]);+ for (const row of metadata) endpointMetadata.set(`${row.source_id}\0${row.slug}`, row);+ // #3478: the 'default' fallback is a federation feature — a sweep over an+ // isolated source must not push cross-source edges. Single-row fetchSource+ // (not loadAllSources) keeps the sweep's bounded-cost discipline; a missing+ // sources row fails closed to isolated.+ const { fetchSource, isSourceFederated } = await import('./sources-load.ts');+ const sourceRow = await fetchSource(engine, sourceId);+ const allowCrossSource = sourceRow !== null && isSourceFederated(sourceRow.config);+ // #3757: thread the same `link_resolution.cross_source` opt-in (#2589) and+ // configured default source (#4611) the CLI extract lanes pass. Without+ // them the sweep dropped every edge into a non-default source AND its+ // reconcile below deleted the ones `extract links --source db` created.+ const [crossSource, linkDefaultSourceId] = await Promise.all([+ isCrossSourceLinksEnabled(engine),+ resolveLinkFallbackDefault(engine),+ ]);+ let crossSourceDrops = 0;+ for (const { slug } of pageCandidates) {+ const { candidates, attendanceComplete } = await linksOf(snapshots.get(slug)!,+ { skipFrontmatter: true, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {+ const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,+ sourceId, allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId });+ return resolved.ok ? endpointMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;+ } });+ if (!attendanceComplete) {+ incomplete.add(slug);+ skip('attendance_resolution_incomplete');+ continue;+ }+ if (wantedEnabled) {+ wantedBySlug.set(slug, collectWantedLinks({ candidates, originSourceId: sourceId,+ crossSourceAllowed: allowCrossSource || crossSource, resolve: c => resolveCandidateSources(c, slug, sourceId,+ allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId }) }));+ }+ for (const c of candidates) {+ // #2589: a cross_source drop here means the target exists only in+ // other sources and cross-source links are off — counted in the+ // skip ledger exactly like the extract paths count it.+ const resolved = resolveCandidateSources(+ c, slug, sourceId, allSlugs, slugToSources, allowCrossSource,+ { crossSource, defaultSourceId: linkDefaultSourceId },+ );+ if (!resolved.ok) {+ if (resolved.reason === 'cross_source') crossSourceDrops++;+ continue;+ }+ linkBatch.push(resolvedLinkCandidate(c, slug, sourceId, resolved));+ }}+ if (crossSourceDrops > 0) skip('cross_source_link', crossSourceDrops);}- processedRefs.push({ slug, source_id: sourceId, extractedAt: recent[i].updated_at_iso });- }-- // Phase 2: endpoint validation is scoped to the slugs the candidates- // actually name — NOT engine.listAllPageRefs() (the full (slug, source_id)- // map, O(all pages) per sweep; the extract command amortizes that cost over- // a whole-brain run, a recurring bounded sweep must not). The targeted- // lookup keeps listAllPageRefs' visibility semantics (deleted_at IS NULL),- // so resolveCandidateSources' F10 resolution is unchanged — it just sees- // only the rows it can possibly use. Zero candidates ⇒ zero queries.- const linkBatch: LinkBatchInput[] = [];- const endpointMetadata = new Map<string, { slug: string; source_id: string; type: string; knowledge_revision: string }>();- const incomplete = new Set<string>();- const wantedBySlug = new Map<string, WantedLinkInput[]>();- const wantedEnabled = await isWantedPagesEnabled(engine);- // One settings snapshot per sweep; publication refuses a page if the settings move meanwhile (it stays unstamped).- const grammar = await readLineGrammarSettings(engine);- const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };- if (pageCandidates.length > 0) {- const needed = new Set<string>();- for (const { slug, candidates } of pageCandidates) {- needed.add(slug);- for (const c of candidates) {- needed.add(c.targetSlug);- if (c.fromSlug) needed.add(c.fromSlug);+ // Engine batch primitives self-retry; default auditSite labels apply+ // (BATCH_AUDIT_SITES is a closed enum owned by retry.ts).+ // A managed brain refuses raw timeline inserts (managed_writer_guard): each page publishes through the coordinator.+ const timelineUnsettled = new Set<string>();+ if (tlBatch.length > 0 && await managedPersistenceEnabled(engine)) {+ const { publishManagedPageTimeline } = await import('../commands/extract-timeline-db.ts');+ for (const slug of new Set(tlBatch.map(row => row.slug))) {+ if (overBudget()) { skip('budget_exhausted:timeline'); timelineUnsettled.add(slug); continue; }+ try {+ const added = await publishManagedPageTimeline(engine, slug, sourceId);+ if (added === 'unsettled') timelineUnsettled.add(slug);+ else report.timelineExtracted += added;+ } catch {+ skip('timeline_publish_failed');+ timelineUnsettled.add(slug);+ }}+ } else if (tlBatch.length > 0) {+ report.timelineExtracted += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(tlBatch)); // gbrain-allow-direct-insert: same extract-path rationale as addLinksBatch above [CX-P0.3]}- const { allSlugs, slugToSources, metadata } = await lookupRefsForSlugs(engine, [...needed]);- for (const row of metadata) endpointMetadata.set(`${row.source_id}\0${row.slug}`, row);- // #3478: the 'default' fallback is a federation feature — a sweep over an- // isolated source must not push cross-source edges. Single-row fetchSource- // (not loadAllSources) keeps the sweep's bounded-cost discipline; a missing- // sources row fails closed to isolated.- const { fetchSource, isSourceFederated } = await import('./sources-load.ts');- const sourceRow = await fetchSource(engine, sourceId);- const allowCrossSource = sourceRow !== null && isSourceFederated(sourceRow.config);- // #3757: thread the same `link_resolution.cross_source` opt-in (#2589) and- // configured default source (#4611) the CLI extract lanes pass. Without- // them the sweep dropped every edge into a non-default source AND its- // reconcile below deleted the ones `extract links --source db` created.- const [crossSource, linkDefaultSourceId] = await Promise.all([- isCrossSourceLinksEnabled(engine),- resolveLinkFallbackDefault(engine),- ]);- let crossSourceDrops = 0;- for (const { slug } of pageCandidates) {- const { candidates, attendanceComplete } = await linksOf(snapshots.get(slug)!,- { skipFrontmatter: true, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {- const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,- sourceId, allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId });- return resolved.ok ? endpointMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;- } });- if (!attendanceComplete) {- incomplete.add(slug);- skip('attendance_resolution_incomplete');- continue;- }- if (wantedEnabled) {- wantedBySlug.set(slug, collectWantedLinks({ candidates, originSourceId: sourceId,- crossSourceAllowed: allowCrossSource || crossSource, resolve: c => resolveCandidateSources(c, slug, sourceId,- allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId }) }));++ // #4196: reconcile removals. The sweep is the ONLY link extraction remote+ // put_page pages ever get (runAutoLink is skipped by design), so add-only+ // inserts leave a phantom edge forever once a page drops a reference.+ // Mirror runAutoLink's provenance-scoped removal (ops/pages.ts) — markdown /+ // NULL-legacy / wikilink-resolved only — minus its own-frontmatter clause:+ // the sweep extracts with skipFrontmatter, so its desired set can never+ // contain frontmatter candidates and deleting them would clobber valid+ // edges. 'manual' and 'mentions' are never touched. A page whose reconcile+ // fails (or is cut by budget) is left unstamped so the next sweep retries.+ const stampable = new Set(processedRefs.map(r => r.slug).filter(slug => !timelineUnsettled.has(slug)));+ if (linksEnabled) {+ const desiredBySlug = new Map<string, LinkBatchInput[]>(+ processedRefs.map(r => [r.slug, []]),+ );+ for (const b of linkBatch) {+ desiredBySlug.get(b.origin_slug ?? b.from_slug)?.push(b);}- for (const c of candidates) {- // #2589: a cross_source drop here means the target exists only in- // other sources and cross-source links are off — counted in the- // skip ledger exactly like the extract paths count it.- const resolved = resolveCandidateSources(- c, slug, sourceId, allSlugs, slugToSources, allowCrossSource,- { crossSource, defaultSourceId: linkDefaultSourceId },- );- if (!resolved.ok) {- if (resolved.reason === 'cross_source') crossSourceDrops++;+ for (const ref of processedRefs) {+ if (incomplete.has(ref.slug) || overBudget()) {+ if (!incomplete.has(ref.slug)) skip('budget_exhausted:link_reconcile');+ stampable.delete(ref.slug);continue;}- linkBatch.push(resolvedLinkCandidate(c, slug, sourceId, resolved));+ const desired = desiredBySlug.get(ref.slug)!;+ try {+ const snapshot = snapshots.get(ref.slug)!;+ const result = await engine.replaceDerivedLinks({ slug: ref.slug, sourceId,+ expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, desired,+ { includeFrontmatter: false, preserveExisting: true, lineGrammar: grammar,+ wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [] }, temporalBody: temporalBodies.get(ref.slug), expectedEndpoints: [...new Set(desired.flatMap(row =>+ [`${row.from_source_id}\0${row.from_slug}`, `${row.to_source_id}\0${row.to_slug}`]))].map(key => {+ const endpoint = endpointMetadata.get(key)!;+ return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };+ }) });+ report.linksRemoved += result.removed;+ report.linksExtracted += result.created;+ } catch {+ skip('link_reconcile_failed');+ stampable.delete(ref.slug);+ }}}- if (crossSourceDrops > 0) skip('cross_source_link', crossSourceDrops);- }- // Engine batch primitives self-retry; default auditSite labels apply- // (BATCH_AUDIT_SITES is a closed enum owned by retry.ts).- // A managed brain refuses raw timeline inserts (managed_writer_guard): each page publishes through the coordinator.- const timelineUnsettled = new Set<string>();- if (tlBatch.length > 0 && await managedPersistenceEnabled(engine)) {- const { publishManagedPageTimeline } = await import('../commands/extract-timeline-db.ts');- for (const slug of new Set(tlBatch.map(row => row.slug))) {- if (overBudget()) { skip('budget_exhausted:timeline'); timelineUnsettled.add(slug); continue; }- try {- const added = await publishManagedPageTimeline(engine, slug, sourceId);- if (added === 'unsettled') timelineUnsettled.add(slug);- else report.timelineExtracted += added;- } catch {- skip('timeline_publish_failed');- timelineUnsettled.add(slug);- }+ // Stamp only when BOTH kinds ran for these pages (extract.ts C3/D6:+ // links_extracted_at covers links AND timeline). Per-ref extractedAt is the+ // page's read updated_at (#1768 µs discipline; D4 — an edit between SELECT+ // and stamp stays stale).+ if (linksEnabled && timelineEnabled) {+ const toStamp = processedRefs.filter(r => stampable.has(r.slug));+ if (toStamp.length > 0) await stampExtracted(engine, toStamp);}- } else if (tlBatch.length > 0) {- report.timelineExtracted += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(tlBatch)); // gbrain-allow-direct-insert: same extract-path rationale as addLinksBatch above [CX-P0.3]- }+ };- // #4196: reconcile removals. The sweep is the ONLY link extraction remote- // put_page pages ever get (runAutoLink is skipped by design), so add-only- // inserts leave a phantom edge forever once a page drops a reference.- // Mirror runAutoLink's provenance-scoped removal (ops/pages.ts) — markdown /- // NULL-legacy / wikilink-resolved only — minus its own-frontmatter clause:- // the sweep extracts with skipFrontmatter, so its desired set can never- // contain frontmatter candidates and deleting them would clobber valid- // edges. 'manual' and 'mentions' are never touched. A page whose reconcile- // fails (or is cut by budget) is left unstamped so the next sweep retries.- const stampable = new Set(processedRefs.map(r => r.slug).filter(slug => !timelineUnsettled.has(slug)));- if (linksEnabled) {- const desiredBySlug = new Map<string, LinkBatchInput[]>(- processedRefs.map(r => [r.slug, []]),- );- for (const b of linkBatch) {- desiredBySlug.get(b.origin_slug ?? b.from_slug)?.push(b);+ // #C5: a segmented page is read several times per pass and can outlast any budget, so it never shares a batch: the+ // inline pages run first as one batch, then each segmented page alone, smallest first, while budget remains. One+ // that does not fit stops at a segment bound and is deferred (left unstamped) until its page changes, so it cannot+ // take the budget of the rest of this sweep, or of later sweeps in this process.+ const pending = recent.filter(row => {+ if (deferredSegmentedPages.get(`${sourceId}\0${row.slug}`) !== row.updated_at_iso) return true;+ skip('segmented_page_deferred');+ return false;+ });+ const inline = pending.filter(row => row.body_storage !== 'segmented');+ const segmented = pending.filter(row => row.body_storage === 'segmented').sort((a, b) => Number(a.body_bytes ?? 0) - Number(b.body_bytes ?? 0));+ if (inline.length > 0) await runBatch(inline);+ for (let i = 0; i < segmented.length; i++) {+ if (overBudget()) {+ skip('budget_exhausted:links_timeline', segmented.length - i);+ break;}- for (const ref of processedRefs) {- if (incomplete.has(ref.slug) || overBudget()) {- if (!incomplete.has(ref.slug)) skip('budget_exhausted:link_reconcile');- stampable.delete(ref.slug);- continue;- }- const desired = desiredBySlug.get(ref.slug)!;- try {- const snapshot = snapshots.get(ref.slug)!;- const result = await engine.replaceDerivedLinks({ slug: ref.slug, sourceId,- expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, desired,- { includeFrontmatter: false, preserveExisting: true, lineGrammar: grammar,- wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [] }, temporalBody: temporalBodies.get(ref.slug), expectedEndpoints: [...new Set(desired.flatMap(row =>- [`${row.from_source_id}\0${row.from_slug}`, `${row.to_source_id}\0${row.to_slug}`]))].map(key => {- const endpoint = endpointMetadata.get(key)!;- return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };- }) });- report.linksRemoved += result.removed;- report.linksExtracted += result.created;- } catch {- skip('link_reconcile_failed');- stampable.delete(ref.slug);- }+ const row = segmented[i]!;+ try {+ await runBatch([row], overBudget);+ } catch (e) {+ if (!(e instanceof BodyReadStopped)) throw e;+ deferredSegmentedPages.set(`${sourceId}\0${row.slug}`, row.updated_at_iso);+ skip('budget_deferred:segmented_page');+ log(`[sweep] links/timeline: ${row.slug} (${row.body_bytes ?? '?'} bytes, segmented) does not fit the sweep budget; deferred until it changes. \`gbrain extract --stale --source-id ${sourceId}\` extracts it.`);}}-- // Stamp only when BOTH kinds ran for these pages (extract.ts C3/D6:- // links_extracted_at covers links AND timeline). Per-ref extractedAt is the- // page's read updated_at (#1768 µs discipline; D4 — an edit between SELECT- // and stamp stays stale).- if (linksEnabled && timelineEnabled) {- const toStamp = processedRefs.filter(r => stampable.has(r.slug));- if (toStamp.length > 0) await stampExtracted(engine, toStamp);- }}/**diff --git a/test/large-pages/segmented-sweep-budget.test.ts b/test/large-pages/segmented-sweep-budget.test.tsnew file mode 100644index 0000000000..8a345a7c4f--- /dev/null+++ b/test/large-pages/segmented-sweep-budget.test.ts@@ -0,0 +1,130 @@+/**+ * Wave B PR 2 fix lane C1 (findings C5, C6): the maintenance sweep's links/timeline pass over a segmented page.+ *+ * 1. Protects (C5): a segmented page never shares a batch with the inline pages, and its reads ask the sweep budget+ * before each segment: a page that does not fit stops at a segment bound and is deferred (unstamped, skipped by+ * later sweeps in this process until it changes) while every inline page in the batch still links; a page that+ * fits is read at most three times (its role phrases, the first extraction with its timeline entries, the typed+ * extraction) instead of five. (C6) The timeline entries the pass keeps until publication are copies, so they do+ * not keep the page's blocks alive.+ * 2. Fails when: the segmented page is one unbounded sweep item processed first, so it reads its whole body several+ * times past the budget and the inline pages behind it get nothing (linksExtracted 0, budget_exhausted); or each+ * parsed entry pins its block until the batch publishes.+ * Seams: the sweep's clock (opts.now) advances only with segmentedPassWork.bytes, the bytes the segmented reads take,+ * so the budget is a byte budget here and no machine load moves it; the heap is sampled after a full collection+ * when the pass opens its publication transactions (engine.transaction), with the batch's timeline rows alive.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { runMaintenanceSweep, _resetDeferredSegmentedPagesForTests } from '../../src/core/sweep.ts';+import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const MB = 1024 * 1024;+/** Clock ms per segmented byte read: a budget of B ms lets the pass read B x BYTES_PER_MS bytes. */+const BYTES_PER_MS = 1024;++/**+ * About `bytes` of paragraphs (the first names the person page), a dated bullet after every `every` paragraphs (so every block+ * holds timeline entries), and `bullets` dated bullets in the timeline.+ */+function segmentedPage(title: string, bytes: number, bullets: number, every = 0): string {+ const paras: string[] = [];+ let size = 0;+ for (let i = 0; size < bytes; i++) {+ const p = 'Paragraph ' + i + ' notes that the widget plan moved again; the team met ' + (i === 0 ? '[[people/alice-example]]' : 'the vendor') + ' to review the ' + 'rollout '.repeat(40) + '\n\n'+ + (every && i % every === every - 1 ? '- **2024-0' + (1 + (i % 9)) + '-2' + (i % 10) + '** | Body review ' + i + '\n\n' : '');+ paras.push(p);+ size += p.length;+ }+ const timeline = Array.from({ length: bullets }, (_, i) => '- **2025-0' + (1 + (i % 9)) + '-1' + (i % 10) + '** | Review ' + i + ' of the widget plan').join('\n');+ return '---\ntype: note\ntitle: ' + title + '\n---\n' + paras.join('') + '<!-- timeline -->\n\n' + timeline + '\n';+}++const inlinePage = (i: number) => '---\ntype: note\ntitle: Inline ' + i + '\n---\nMet [[people/alice-example]] about item ' + i + '.\n';++for (const kind of testBackends()) {+ describe('sweep links/timeline over a segmented page (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let start = 0;+ const now = () => start + segmentedPassWork.bytes / BYTES_PER_MS;++ beforeAll(async () => {+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Fixture.', timeline: '', frontmatter: {} }, { sourceId: 'default' });+ }, 120_000);++ afterAll(async () => { await close(); });++ beforeEach(() => {+ _resetDeferredSegmentedPagesForTests();+ segmentedPassWork.bytes = 0;+ start = 1_000_000;+ });++ const stamped = async (slug: string) => (await engine.executeRaw<{ at: unknown }>('SELECT links_extracted_at AS at FROM pages WHERE slug=$1', [slug]))[0]?.at ?? null;+ const bodyBytes = async (slug: string) => Number((await engine.executeRaw<{ n: unknown }>('SELECT body_bytes AS n FROM pages WHERE slug=$1', [slug]))[0]!.n);++ test('a segmented page over the budget is deferred at a segment bound and the inline pages still link', async () => {+ for (let i = 0; i < 3; i++) await importFromContent(engine, 'notes/inline-' + i, inlinePage(i), { sourceId: 'default', noEmbed: true });+ expect((await importFromContent(engine, 'notes/too-large', segmentedPage('Too large', 6 * MB, 50), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const budgetMs = (2 * MB) / BYTES_PER_MS;+ const r = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs, batchLimit: 20, now });+ console.log('[segmented-sweep] ' + kind + ' over budget: ' + segmentedPassWork.bytes + ' bytes read, report ' + JSON.stringify({ linksExtracted: r.linksExtracted, skipped: r.skipped }));+ expect(r.linksExtracted).toBeGreaterThanOrEqual(3);+ for (let i = 0; i < 3; i++) expect(await stamped('notes/inline-' + i)).not.toBeNull();+ expect(r.skipped.map(s => s.reason)).toContain('budget_deferred:segmented_page');+ expect(segmentedPassWork.bytes).toBeLessThanOrEqual(budgetMs * BYTES_PER_MS + SEGMENT_MAX_BYTES);+ expect(await stamped('notes/too-large')).toBeNull();++ segmentedPassWork.bytes = 0;+ const again = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs, batchLimit: 20, now });+ expect(again.skipped.map(s => s.reason)).toContain('segmented_page_deferred');+ expect(segmentedPassWork.bytes).toBe(0);+ }, 300_000);++ test('a segmented page that fits is read at most three times, and its kept timeline entries pin no block', async () => {+ await engine.executeRaw("UPDATE pages SET links_extracted_at = now() WHERE slug <> 'notes/fits'");+ const content = segmentedPage('Fits', 20 * MB, 400, 16);+ const bodyBullets = content.split('| Body review ').length - 1;+ expect((await importFromContent(engine, 'notes/fits', content, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const bytes = await bodyBytes('notes/fits');+ let peak = 0;+ const transaction = engine.transaction.bind(engine);+ engine.transaction = (async (fn: Parameters<BrainEngine['transaction']>[0]) => {+ Bun.gc(true);+ peak = Math.max(peak, process.memoryUsage().heapUsed);+ return transaction(fn);+ }) as BrainEngine['transaction'];+ Bun.gc(true);+ const base = process.memoryUsage().heapUsed;+ let r: Awaited<ReturnType<typeof runMaintenanceSweep>>;+ try { r = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs: 1_000_000, batchLimit: 20, now }); } finally { engine.transaction = transaction; }+ const held = peak - base;+ console.log('[segmented-sweep] ' + kind + ' fits: ' + segmentedPassWork.bytes + ' bytes read for a ' + bytes + '-byte page ('+ + (segmentedPassWork.bytes / bytes).toFixed(2) + ' reads), heap held ' + (held / MB).toFixed(1) + ' MiB, report ' + JSON.stringify({ links: r!.linksExtracted, timeline: r!.timelineExtracted, skipped: r!.skipped }));+ expect(await stamped('notes/fits')).not.toBeNull();+ expect(peak).toBeGreaterThan(0);+ expect(r!.timelineExtracted).toBeGreaterThan(0);+ const rows = await engine.executeRaw<{ n: unknown }>("SELECT count(*) AS n FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.slug='notes/fits'");+ expect(Number(rows[0]!.n)).toBe(400 + bodyBullets);+ expect(segmentedPassWork.bytes).toBeLessThanOrEqual(3 * bytes);+ expect(held).toBeLessThan(bytes / 2);+ }, 600_000);+ });+}