Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: gate projection statistics refresh by changed pages

time-attack1b9f46fd13d9
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 23b76e48fe..c6857b2b95 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -1206,7 +1206,7 @@ export async function runImport(
}
}
- if (imported > 0 && !opts.managedBookmark) await refreshProjectionStatistics(engine);
+ if (imported > 0 && !opts.managedBookmark) await refreshProjectionStatistics(engine, imported);
return {
imported, skipped, errors, chunksCreated, failures,
...(resealSummary ? { resealed: resealSummary } : {}), ...fenceTally.fields(),
diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.ts
index 1892af46ff..580da1ab1e 100644
--- a/src/commands/reindex-code.ts
+++ b/src/commands/reindex-code.ts
@@ -344,7 +344,7 @@ export async function runReindexCode(
}
}
- if (reindexed > 0) await refreshProjectionStatistics(engine);
+ if (reindexed > 0) await refreshProjectionStatistics(engine, reindexed);
if (budgetExhausted) {
// Partial-progress result: surfaces what got reindexed before the cap
// fired. The CLI wrapper translates this into a clear user-facing
diff --git a/src/commands/reindex.ts b/src/commands/reindex.ts
index de3efa7b56..0000b5a956 100644
--- a/src/commands/reindex.ts
+++ b/src/commands/reindex.ts
@@ -514,7 +514,7 @@ export async function runReindex(engine: BrainEngine, args: string[], runOpts: R
reporter.finish();
if (stopped) return reportBudgetStop(engine, stopped, { pending, type, json: !!opts.json, reindexed, skipped, failed, workers });
- if (reindexed > 0) await refreshProjectionStatistics(engine);
+ if (reindexed > 0) await refreshProjectionStatistics(engine, reindexed);
const pendingAfter = await countPending(engine, type, !!opts.noEmbed);
if (failed > 0) setCliExitVerdict(1);
@@ -550,7 +550,7 @@ export async function runReindex(engine: BrainEngine, args: string[], runOpts: R
* kept (a rerun continues with the rest); exit 1 with the spend and the rerun.
*/
async function reportBudgetStop(engine: BrainEngine, e: BudgetExhausted, r: { pending: number; type: string | null; json: boolean; reindexed: number; skipped: number; failed: number; workers?: number }): Promise<ReindexResult> {
- if (r.reindexed > 0) await refreshProjectionStatistics(engine);
+ if (r.reindexed > 0) await refreshProjectionStatistics(engine, r.reindexed);
const pendingAfter = await countPending(engine, r.type, false);
setCliExitVerdict(1);
const message = `stopped at the $${e.cap.toFixed(2)} cost cap after spending $${e.spent.toFixed(4)} (${e.message}). ${pendingAfter} page(s) still pending, and pages re-chunked after the cap wait for gbrain embed --stale; ask the user before running again with a higher --max-usd.`;
@@ -597,7 +597,7 @@ async function reindexManaged(engine: BrainEngine, opts: ReindexOpts, type: stri
if (run.stopped) stopped.push(run.stopped.message);
unsupported += Object.values(run.residuals).reduce((sum, count) => sum + count, 0);
}
- if (pending > 0) await refreshProjectionStatistics(engine);
+ if (pending > 0) await refreshProjectionStatistics(engine, pending);
const pendingAfter = await countPending(engine, type, !!opts.noEmbed);
const reindexed = Math.max(0, pending - pendingAfter);
if (stopped.length) setCliExitVerdict(1);
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index ede39293e3..3141928757 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -31,7 +31,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
const finish = async (result: SyncResult, refresh = false): Promise<SyncResult> => {
assertSyncDispatchActive();
if (refresh && (result.pagesAffected.length > 0 || result.deleted > 0)) {
- await refreshProjectionStatistics(engine);
+ await refreshProjectionStatistics(engine, result.pagesAffected.length + result.deleted);
}
if (refresh && !opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);
return result;
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 832cd854de..e880ebe975 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -1109,7 +1109,8 @@ async function cursorMovedAdmission(engine: BrainEngine, key: string, admitting:
*/
async function finishCheckpoint(engine: BrainEngine, key: string, cursor: Cursor, company: boolean, assertActive: () => void): Promise<SyncResult> {
await clearManagedSyncFailureAfterSuccess(engine, key);
- if (cursor.counts.added + cursor.counts.modified + cursor.counts.deleted > 0) await refreshProjectionStatistics(engine);
+ const changed = cursor.counts.added + cursor.counts.modified + cursor.counts.deleted;
+ if (changed > 0) await refreshProjectionStatistics(engine, changed);
assertActive();
const scheduled = company ? [] : await readGitHoldRetryPaths(engine, cursor.sourceId, cursor.incarnation);
assertActive();
diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.ts
index 899761980a..bf964da70c 100644
--- a/src/core/search/projection-statistics.ts
+++ b/src/core/search/projection-statistics.ts
@@ -1,5 +1,5 @@
import type { BrainEngine } from '../engine.ts';
-import { beginFullAnalyze, plannerAutoAnalyzeEnabled } from '../planner-stats.ts';
+import { beginFullAnalyze, maybeRefreshPlannerStats, plannerAutoAnalyzeEnabled, plannerStatsThreshold } from '../planner-stats.ts';
export const PROJECTION_STATISTICS_NAME = 'pages_text_projection_current_stats';
@@ -39,8 +39,22 @@ export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'exec
}
}
-export async function refreshProjectionStatistics(engine: BrainEngine): Promise<boolean> {
+/**
+ * Refreshes the projection statistics after a write pass that changed `changedPages` pages (omitted: always).
+ * A pass that changed fewer pages than the planner-statistics threshold (max(500, 10% of pages), autovacuum's
+ * scale) leaves collected statistics alone: the current-page fraction barely moves, and the narrow ANALYZE cost
+ * 170 ms per one-page sync at 50k pages on Postgres and a full ANALYZE of every table on PGLite. PGLite still
+ * analyzes any hot table its row deltas mark stale.
+ */
+export async function refreshProjectionStatistics(engine: BrainEngine, changedPages = Infinity): Promise<boolean> {
try {
+ if (Number.isFinite(changedPages)) {
+ const [pages] = await engine.executeRaw<{ reltuples: number }>("SELECT reltuples::float8 AS reltuples FROM pg_class WHERE oid = 'pages'::regclass");
+ if (changedPages < plannerStatsThreshold(Number(pages?.reltuples ?? -1)) && await verifyProjectionStatistics(engine).then(() => true, () => false)) {
+ await maybeRefreshPlannerStats(engine, 'import', { throttle: false });
+ return true;
+ }
+ }
const [role] = await engine.executeRaw<{ can_analyze: boolean }>(
`SELECT pg_has_role(current_user, p.relowner, 'USAGE') OR r.rolsuper AS can_analyze
FROM pg_class p CROSS JOIN pg_roles r
diff --git a/test/projection-statistics.test.ts b/test/projection-statistics.test.ts
index 86c948113a..84a3b3e0d3 100644
--- a/test/projection-statistics.test.ts
+++ b/test/projection-statistics.test.ts
@@ -69,6 +69,34 @@ describe('current projection planner estimates', () => {
});
});
+describe('projection statistics refresh after a write pass', () => {
+ const planRows = async (db: PGlite) => (await db.query<{ 'QUERY PLAN': Array<{ Plan: { 'Plan Rows': number } }> }>(
+ `EXPLAIN (FORMAT JSON) SELECT * FROM pages p WHERE ${currentTextProjectionFilter('p')}`)).rows[0]['QUERY PLAN'][0].Plan['Plan Rows'];
+
+ test('a pass below max(500, 10% of pages) keeps collected statistics; a larger pass or uncollected statistics refresh', async () => {
+ const db = new PGlite();
+ try {
+ const engine = fixtureEngine(db);
+ await db.exec(`CREATE TABLE pages (id integer PRIMARY KEY, text_projection_revision uuid, knowledge_revision uuid);
+ INSERT INTO pages SELECT i, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001' FROM generate_series(1, 10000) i;`);
+ await db.exec(PROJECTION_STATISTICS_SQL);
+ expect(await planRows(db)).toBe(10000);
+ await db.query('UPDATE pages SET text_projection_revision = NULL WHERE id <= 999');
+ const stale = await planRows(db);
+ expect(stale).toBeGreaterThan(9001);
+ expect(await refreshProjectionStatistics(engine, 999)).toBe(true);
+ expect(await planRows(db)).toBe(stale);
+ expect(await refreshProjectionStatistics(engine, 1000)).toBe(true);
+ expect(await planRows(db)).toBe(9001);
+ await db.exec(`DROP STATISTICS pages_text_projection_current_stats;
+ CREATE STATISTICS pages_text_projection_current_stats ON ((text_projection_revision = knowledge_revision)) FROM pages;`);
+ await expect(verifyProjectionStatistics(engine)).rejects.toThrow('not been collected');
+ expect(await refreshProjectionStatistics(engine, 1)).toBe(true);
+ await verifyProjectionStatistics(engine);
+ } finally { await db.close(); }
+ }, 30_000);
+});
+
describe('projection statistics migration postconditions', () => {
test('empty initialization and later population both collect valid statistics', async () => {
const db = new PGlite();