Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(links): managed link extraction derives four pages at once on Postgres, with one config read per run (#5984)

garrytan52bac1ffb6d3
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index 5d7edafc38..7b3b0e1836 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -2,6 +2,7 @@ import type { BrainEngine } from '../engine.ts';
import { LINK_EXTRACTOR_VERSION_TS } from '../link-extraction.ts';
import { isQuarantined } from '../quarantine.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
+import { preparationConfigView } from './config-snapshot.ts';
import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
import { unrecordedCanonicalTimeline } from './canonical-projections.ts';
@@ -40,6 +41,9 @@ export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryR
(result.remaining ? ` ${result.remaining} page(s) remain stale.` : '') + (mentionLine ? `\n${mentionLine}` : '');
}
+/** #5984: pages a managed link extraction derives at once on Postgres. */
+export const MANAGED_LINK_EXTRACTION_WIDTH = 4;
+
/**
* Derive markdown links with put_page's contract: the page's own derived edges
* are replaced by what its current text supports, other producers' edges stay.
@@ -71,12 +75,14 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
const maxPages = opts.maxPages ?? Infinity;
const done = new Set<string>();
const attribution = await maintenanceAttribution(engine);
+ // #5984: every page's link preparation reads the same config; one read answers them for this run.
+ const settings = await preparationConfigView(engine);
const derive = async (slug: string, sourceId: string, stamp?: string) => {
opts.signal?.throwIfAborted();
done.add(`${sourceId}\0${slug}`);
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
if (!snapshot || isQuarantined(snapshot.page.frontmatter)) return;
- const prepared = await prepareAutomaticLinks(engine, slug, snapshot.page, sourceId);
+ const prepared = await prepareAutomaticLinks(settings, slug, snapshot.page, sourceId);
const outcome = await engine.transaction(async tx => withCoordinatedWrite(tx, [sourceId], async () => {
await tx.lockPageKeys(prepared.pageKeys);
const current = await tx.readPageSnapshot(slug, { sourceId });
@@ -100,20 +106,29 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
result.removed += outcome.removed;
result.timeline += outcome.timeline;
};
- const budget = () => result.pages + result.skipped < maxPages && Date.now() < deadline;
- if (opts.slugs?.length && opts.sourceId) {
- for (const slug of new Set(opts.slugs)) { if (!budget()) break; await derive(slug, opts.sourceId); }
- }
+ let started = 0;
+ const budget = () => started < maxPages && Date.now() < deadline;
+ // #5984: on Postgres several pages derive at once, each in its own transaction (page guards lock in sorted
+ // order, so they cannot deadlock); a page's links depend only on committed pages. The first failure stops the rest.
+ const width = engine.kind === 'postgres' ? MANAGED_LINK_EXTRACTION_WIDTH : 1;
+ const each = async <T>(items: readonly T[], run: (item: T) => Promise<void>) => {
+ let next = 0, failed = false;
+ await Promise.all(Array.from({ length: Math.min(width, items.length) }, async () => {
+ while (!failed && next < items.length && budget()) {
+ const item = items[next++]!;
+ started++;
+ try { await run(item); } catch (error) { failed = true; throw error; }
+ }
+ }));
+ };
+ if (opts.slugs?.length && opts.sourceId) await each([...new Set(opts.slugs)], slug => derive(slug, opts.sourceId!));
let afterPageId = 0;
while (budget()) {
const rows = await engine.listStalePagesForExtraction({ batchSize: 25, afterPageId, sourceId: opts.sourceId, versionTs });
if (!rows.length) break;
- for (const row of rows) {
- if (!budget()) break;
- afterPageId = row.id;
- if (done.has(`${row.source_id}\0${row.slug}`)) continue;
- await derive(row.slug, row.source_id, row.updated_at.getTime() >= Date.parse(versionTs) ? row.updated_at_iso : versionTs);
- }
+ afterPageId = rows[rows.length - 1]!.id;
+ await each(rows.filter(row => !done.has(`${row.source_id}\0${row.slug}`)),
+ row => derive(row.slug, row.source_id, row.updated_at.getTime() >= Date.parse(versionTs) ? row.updated_at_iso : versionTs));
}
result.remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs });
if (withMentions) {
diff --git a/test/e2e/w5-persistence-postgres.test.ts b/test/e2e/w5-persistence-postgres.test.ts
index 6c5ae120f8..2e7d58ad90 100644
--- a/test/e2e/w5-persistence-postgres.test.ts
+++ b/test/e2e/w5-persistence-postgres.test.ts
@@ -6,7 +6,7 @@
import { describe, test } from 'bun:test';
import {
capacityWarnsAndRefusalNamesTheKey, compactionSkipsUnfinishedReceipts, failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark,
- managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, scanParksOneTargetAndContinues, singleTargetParksAndRetries, staleExtractionWithheldWhenItCannotRun,
+ managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, managedStaleSweepManyPages, scanParksOneTargetAndContinues, singleTargetParksAndRetries, staleExtractionWithheldWhenItCannotRun,
} from '../helpers/w5-scenarios.ts';
const url = process.env.DATABASE_URL;
@@ -18,6 +18,7 @@ describe.skipIf(!url)('Postgres managed capacity, parking and stale extraction',
test('configured retention compacts past unfinished receipts', () => compactionSkipsUnfinishedReceipts(url), 240_000);
test('capacity warning and refusal hint', () => capacityWarnsAndRefusalNamesTheKey(url), 180_000);
test('managed extract --stale is coordinated', () => managedStaleSweep(url), 180_000);
+ test('managed extract --stale derives several pages at once', () => managedStaleSweepManyPages(url), 180_000);
test('managed extract --stale keeps normalized timeline rows single', () => managedStaleSweepKeepsNormalizedTimeline(url), 180_000);
test('extract.stale withheld when it cannot run', () => staleExtractionWithheldWhenItCannotRun(url), 180_000);
});
diff --git a/test/extract-stale-managed.test.ts b/test/extract-stale-managed.test.ts
index 44dccaff86..7f5c82b9a7 100644
--- a/test/extract-stale-managed.test.ts
+++ b/test/extract-stale-managed.test.ts
@@ -5,9 +5,10 @@
* withheld when the sweep cannot run. Postgres arm: test/e2e/w5-persistence-postgres.test.ts.
*/
import { expect, test } from 'bun:test';
-import { managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, staleExtractionWithheldWhenItCannotRun } from './helpers/w5-scenarios.ts';
+import { managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, managedStaleSweepManyPages, staleExtractionWithheldWhenItCannotRun } from './helpers/w5-scenarios.ts';
test('managed extract --stale publishes through the coordinator and clears the recommendation', () => managedStaleSweep(), 120_000);
+test('managed extract --stale stamps every page and resolves every link', () => managedStaleSweepManyPages(), 120_000);
test('managed extract --stale does not duplicate a stored row that differs only by whitespace', () => managedStaleSweepKeepsNormalizedTimeline(), 120_000);
test('extract.stale is withheld while the sweep cannot run', () => staleExtractionWithheldWhenItCannotRun(), 120_000);
diff --git a/test/helpers/w5-scenarios.ts b/test/helpers/w5-scenarios.ts
index 35a4e07fe9..70ae937747 100644
--- a/test/helpers/w5-scenarios.ts
+++ b/test/helpers/w5-scenarios.ts
@@ -224,6 +224,35 @@ export async function managedStaleSweep(databaseUrl?: string) {
}, { databaseUrl });
}
+/** #5984: on Postgres a managed extraction derives several pages at once; every page is stamped and every link resolves either way. */
+export async function managedStaleSweepManyPages(databaseUrl?: string) {
+ await managedBrain(async ({ engine, ctx }) => {
+ await engine.setConfig('auto_link', 'false');
+ const count = 12;
+ for (let i = 0; i < count; i++) await put(ctx, `notes/n${i}`, `Links [[notes/n${(i + 1) % count}]] and [[notes/hub]].`);
+ await put(ctx, 'notes/hub', 'The hub.');
+ await disposePersistenceConsumer(engine);
+ let open = 0, most = 0;
+ const transaction = engine.transaction;
+ engine.transaction = (async function (this: BrainEngine, fn: Parameters<BrainEngine['transaction']>[0]) {
+ if (this !== engine) return transaction.call(this, fn);
+ open++; most = Math.max(most, open);
+ try { return await transaction.call(this, fn); } finally { open--; }
+ }) as BrainEngine['transaction'];
+ try {
+ const { extractManagedStaleLinks, MANAGED_LINK_EXTRACTION_WIDTH } = await import('../../src/core/persistence/links-maintenance.ts');
+ const result = await extractManagedStaleLinks(engine, { sourceId: 'default', mentions: false, slugs: Array.from({ length: count }, (_, i) => `notes/n${i}`) });
+ expect(result).toMatchObject({ pages: count + 1, skipped: 0, remaining: 0 });
+ expect(most).toBe(engine.kind === 'postgres' ? MANAGED_LINK_EXTRACTION_WIDTH : 1);
+ } finally { engine.transaction = transaction; }
+ const links = await engine.executeRaw<{ f: string; t: string }>(`SELECT f.slug AS f, t.slug AS t FROM links l JOIN pages f ON f.id=l.from_page_id
+ JOIN pages t ON t.id=l.to_page_id ORDER BY 1, 2`);
+ expect(links).toEqual(Array.from({ length: 12 }, (_, i) => [{ f: `notes/n${i}`, t: 'notes/hub' }, { f: `notes/n${i}`, t: `notes/n${(i + 1) % 12}` }]).flat()
+ .sort((a, b) => a.f < b.f ? -1 : a.f > b.f ? 1 : a.t < b.t ? -1 : 1));
+ expect(await stale(engine)).toBe(0);
+ }, { databaseUrl });
+}
+
/** A stored row that differs from its bullet only by whitespace is the same entry to the coordinator; stale extraction must not add a twin. */
export async function managedStaleSweepKeepsNormalizedTimeline(databaseUrl?: string) {
await managedBrain(async ({ engine, ctx }) => {