Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

extract: refresh PGLite planner stats during the database timeline walk

garrytan5b062e6ae2cb
diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.ts
index 1584d71c0a..53f000cb86 100644
--- a/src/commands/extract-timeline-db.ts
+++ b/src/commands/extract-timeline-db.ts
@@ -30,6 +30,7 @@ import { digest } from '../core/persistence/digest.ts';
import type { PreparedMutation } from '../core/persistence/coordinator.ts';
import { OperationError } from '../core/ops/contract.ts';
import { createProgress } from '../core/progress.ts';
+import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../core/planner-stats.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import { filterRefsSince } from './extract.ts';
@@ -113,6 +114,11 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD
const managed = !opts.dryRun && await managedPersistenceEnabled(engine);
const dryRunSeen = opts.dryRun ? new Set<string>() : null;
const batch: TimelineBatchInput[] = [];
+ // PGLite has no autovacuum: a walk that grows timeline_entries from empty
+ // re-plans its per-page reads against stale statistics and slows with
+ // every row, so it refreshes them on the bulk-import cadence.
+ const analyzeEvery = opts.dryRun ? 0 : await importAnalyzeEveryPages(engine);
+ let walked = 0;
async function flush() {
if (batch.length === 0) return;
@@ -129,6 +135,10 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD
}
for (const { slug, source_id } of refs) {
+ if (analyzeEvery > 0 && ++walked % analyzeEvery === 0) {
+ await flush();
+ await maybeRefreshPlannerStats(engine, 'extract', { throttle: false }).catch(() => undefined);
+ }
if (managed) {
try {
const outcome = await publishPageTimeline(engine, await authorityFor(source_id), slug, source_id, opts);
diff --git a/src/core/planner-stats.ts b/src/core/planner-stats.ts
index 95b49abe50..e6a14585be 100644
--- a/src/core/planner-stats.ts
+++ b/src/core/planner-stats.ts
@@ -13,8 +13,8 @@
* modification committed between that read and the publication stays pending.
*
* Call sites: the PGLite engine's planner-sensitive reads (first relevant
- * read, `planner.first_read_budget_ms`), bulk import and managed sync every
- * `import.analyze_every_pages` pages, the cycle after its freshness phases,
+ * read, `planner.first_read_budget_ms`), bulk import, managed sync and the
+ * database timeline walk every `import.analyze_every_pages` pages, the cycle after its freshness phases,
* the resident consumer's idle tick, and `refreshProjectionStatistics` (full
* ANALYZE, then watermarks for every table). `planner.auto_analyze=false`
* (env GBRAIN_PLANNER_AUTO_ANALYZE) disables all of them; doctor
@@ -31,7 +31,7 @@ export const DEFAULT_FIRST_READ_BUDGET_MS = 2000;
export const DEFAULT_IMPORT_ANALYZE_EVERY_PAGES = 500;
export const PLANNER_STATS_REPAIR_COMMAND = 'gbrain repair planner-stats --apply';
-export type PlannerRefreshReason = 'first_read' | 'import' | 'managed_sync' | 'cycle' | 'idle' | 'repair';
+export type PlannerRefreshReason = 'first_read' | 'import' | 'managed_sync' | 'extract' | 'cycle' | 'idle' | 'repair';
export interface PlannerTableState {
table: PlannerStatsTable;
diff --git a/test/extract-timeline-db-planner-stats.test.ts b/test/extract-timeline-db-planner-stats.test.ts
new file mode 100644
index 0000000000..24e2acd229
--- /dev/null
+++ b/test/extract-timeline-db-planner-stats.test.ts
@@ -0,0 +1,60 @@
+/**
+ * `gbrain extract timeline --source db` on PGLite refreshes planner statistics
+ * every `import.analyze_every_pages` pages while it fills timeline_entries.
+ *
+ * Protects: the PGLite scale tier at 20k pages. The walk starts with an empty
+ * timeline_entries and PGLite has no autovacuum, so without a refresh every
+ * per-page read plans against the empty table and slows with each row: the
+ * walk took 157 s at 10k pages and 655 s at 20k on the scale nightly, and
+ * 34 s at 4k locally against 2.8 s with the refresh.
+ * Fails when: the walk stops calling maybeRefreshPlannerStats, so
+ * timeline_entries ends the walk with no pg_stats rows.
+ * Why new: test/planner-stats-import.slow.test.ts covers import and managed
+ * sync; nothing covered the database extract walk.
+ * Seam: planner-stats __testing.hooks.onAnalyzed (observes, changes nothing).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';
+import { __testing } from '../src/core/planner-stats.ts';
+
+const PAGES = 300;
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (let i = 0; i < PAGES; i++) {
+ await engine.putPage(`notes/timeline-${i}`, {
+ type: 'note', title: `Timeline ${i}`, compiled_truth: `Note ${i}.`, frontmatter: {},
+ timeline: `- **2025-01-${String(1 + (i % 28)).padStart(2, '0')}** | Event ${i}\n- **2026-02-${String(1 + (i % 28)).padStart(2, '0')}** | Follow-up ${i}`,
+ });
+ }
+}, 120_000);
+
+afterAll(async () => {
+ __testing.hooks.onAnalyzed = undefined;
+ await engine.disconnect();
+});
+
+describe('database timeline walk keeps PGLite planner statistics fresh', () => {
+ test('timeline_entries is analyzed during the walk, at the page cadence', async () => {
+ await engine.setConfig('import.analyze_every_pages', '100');
+ const analyzed: Array<{ table: string; rows: number }> = [];
+ __testing.hooks.onAnalyzed = async (eng, event) => {
+ if (event.reason !== 'extract') return;
+ const [{ n }] = await eng.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM timeline_entries');
+ analyzed.push({ table: event.table, rows: n });
+ };
+
+ const result = await extractTimelineFromDB(engine, { dryRun: false, jsonMode: true, quiet: true });
+
+ expect(result.created).toBe(PAGES * 2);
+ // The check before page 300 sees 299 pages' rows (598), the first count over the max(500, 10%) threshold.
+ expect(analyzed.filter(a => a.table === 'timeline_entries').map(a => a.rows)).toEqual([(PAGES - 1) * 2]);
+ const [{ n }] = await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM pg_stats WHERE schemaname = 'public' AND tablename = 'timeline_entries'");
+ expect(n).toBeGreaterThan(0);
+ }, 120_000);
+});