Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): yield to the event loop after each managed stale-extraction page

garrytan398bd696d3a3
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index 2eaa42a5bc..cf88af951c 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -4,6 +4,7 @@ import { isQuarantined } from '../quarantine.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
import { preparationConfigView } from './config-snapshot.ts';
import { withCoordinatedWrite } from './context.ts';
+import { yieldToEventLoop } from './journal.ts';
import { maintenanceAttribution } from './attribution.ts';
import { storedCanonicalTimeline, unrecordedCanonicalTimeline } from './canonical-projections.ts';
import { runMentionPass, type MentionPassResult } from '../mentions/pass.ts';
@@ -100,6 +101,9 @@ export const MANAGED_LINK_EXTRACTION_WIDTH = 4;
* coordinated transaction, insert-only. This is the one managed extraction
* path: sync, `extract --stale` (every caller of extractStaleFromDB) and the
* PGLite owner delegation all run it, in the process that owns the brain.
+ * Each page yields to the event loop when it finishes: PGLite statements
+ * resolve as one microtask chain, so a long drain would otherwise hold every
+ * timer and in-process request until its last page.
*/
export async function extractManagedStaleLinks(engine: BrainEngine,
opts: { sourceId?: string; slugs?: readonly string[]; maxPages?: number; timeBudgetMs?: number; signal?: AbortSignal; mentions?: boolean } = {}): Promise<ManagedLinkExtraction> {
@@ -174,6 +178,7 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
try {
await derive(slug, sourceId, stamp, read);
run.succeed();
+ await yieldToEventLoop();
} catch (error) {
try { failed.push({ ...run.fail(`${sourceId}:${slug}`, error), slug, source_id: sourceId, revision: read.revision }); } catch (stopped) {
if (stopped !== error && !opts.sourceId) tripped.set(sourceId, stopped as OperationError);
diff --git a/test/links-extraction-yield.test.ts b/test/links-extraction-yield.test.ts
new file mode 100644
index 0000000000..a88e1cb91b
--- /dev/null
+++ b/test/links-extraction-yield.test.ts
@@ -0,0 +1,78 @@
+/**
+ * GBRA-133: managed stale link extraction gives the event loop a turn after
+ * every page. PGLite statements resolve as one microtask chain, so a sync's
+ * end-of-run extraction over thousands of pages otherwise held every timer
+ * (and every in-process search) until the last page published.
+ * Protects: a timer queued during the drain runs before each worker starts
+ * its next page, so no more pages than the extraction width (1 on PGLite)
+ * start within one event-loop turn.
+ * Fails when: the per-page loop in extractManagedStaleLinks stops yielding,
+ * so every PGLite page starts at the same heartbeat count.
+ * Seams: the engine's readPageSnapshot is observed (it still runs on the
+ * receiver, a transaction included) to learn when each page's derivation starts. PGLite, and Postgres with DATABASE_URL.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { extractManagedStaleLinks, MANAGED_LINK_EXTRACTION_WIDTH } from '../src/core/persistence/links-maintenance.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-links-yield-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+const PAGES = 8;
+
+for (const [index, backend] of backends.entries()) {
+ test(`${backend}: a managed stale extraction starts no more pages per event-loop turn than its width`, async () => {
+ const engine = engines[index]!;
+ await engine.putPage('topics/hub', { type: 'concept', title: 'hub', compiled_truth: 'The hub.', frontmatter: {} });
+ for (let i = 0; i < PAGES; i++) {
+ await engine.putPage(`notes/n${i}`, { type: 'note', title: `n${i}`, compiled_truth: `Note ${i} links [[topics/hub]].`, frontmatter: {} });
+ }
+ await engine.executeRaw(`UPDATE pages SET links_extracted_at = NULL`);
+
+ let beats = 0; let live = true;
+ const beat = () => { beats++; if (live) setTimeout(beat, 0); };
+ setTimeout(beat, 0);
+ const seen = new Map<string, number>();
+ const read = engine.readPageSnapshot;
+ engine.readPageSnapshot = function (this: BrainEngine, slug, opts) {
+ if (slug.startsWith('notes/') && !seen.has(slug)) seen.set(slug, beats);
+ return read.call(this, slug, opts);
+ };
+ try {
+ const result = await extractManagedStaleLinks(engine, { mentions: false });
+ expect(result.pages).toBe(PAGES + 1);
+ } finally {
+ live = false;
+ delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot;
+ }
+
+ expect(seen.size).toBe(PAGES);
+ const startedPerTurn = new Map<number, number>();
+ for (const count of seen.values()) startedPerTurn.set(count, (startedPerTurn.get(count) ?? 0) + 1);
+ const width = engine.kind === 'postgres' ? MANAGED_LINK_EXTRACTION_WIDTH : 1;
+ expect(Math.max(...startedPerTurn.values())).toBeLessThanOrEqual(width);
+ }, 60_000);
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 4461f258c6..46b31fba88 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -184,6 +184,7 @@ test/large-pages/v252-master-reader-compat.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts
test/links-attendance-blocked.test.ts
+test/links-extraction-yield.test.ts
test/managed-cycle-pull-upstream.test.ts
test/managed-facts-withdrawal-recovery-6506.test.ts
test/managed-facts-withdrawn-skip-6506.test.ts