Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres): gbrain ANALYZE never waits on (and cancels) a running autovacuum (#7083)
garrytanacbd2220a9c4
diff --git a/docs/guides/planner-stats.md b/docs/guides/planner-stats.mdindex a6de94d3cd..eb5a343ce9 100644--- a/docs/guides/planner-stats.md+++ b/docs/guides/planner-stats.md@@ -65,12 +65,35 @@ On Postgres nothing collects an existing index's statistics automatically:autovacuum analyzes a table only after 10% of its rows change, so a quietbrain keeps the gap. Doctor warns, and an operator runs`gbrain repair planner-stats --apply` on the brain host (one whole-table-ANALYZE per table, 60 s statement and 2 s lock timeout).+ANALYZE per table, 60 s statement timeout, deferred while another session+holds the table).On Postgres, `planner_stats_stale` reads `pg_stat_user_tables` and warns onlywhen a table is over the same threshold and neither ANALYZE nor autoanalyze ran-in the last hour; the repair runs each ANALYZE with a 60 s statement and 2 s-lock timeout.+in the last hour; the repair runs each ANALYZE with a 60 s statement timeout.++### ANALYZE never waits on a vacuum (Postgres)++ANALYZE takes the same table lock as VACUUM and autovacuum, and Postgres+cancels an autovacuum once another session has waited `deadlock_timeout`+(1 s by default) for that lock. On a large `content_chunks` an ANALYZE after+every embed drain could cancel every autovacuum of the table before it+finished, leaving millions of dead rows in every index (#7083). So every+ANALYZE gbrain runs on Postgres on its own (the import, sync, reindex and+embed refreshes, the search guard, `gbrain repair planner-stats --apply`+and migrations) first locks the table with `NOWAIT`: when a vacuum, another+ANALYZE or an index build holds it, the ANALYZE is deferred with a warning+(the repair reports the table `deferred`) and never waits. The embed+drain's chunk refresh also skips a drain that changed fewer than 50 + 10% of+the table's chunks once the chunk statistics exist; autovacuum's own analyze+covers what small drains add up to.++`planner_stats_stale` also warns when a hot table of at least 100,000 rows+holds more dead rows than autovacuum's vacuum threshold and no vacuum has+completed on it for 24 hours: something keeps cancelling its autovacuum.+Look for `canceling autovacuum task` in the server log and the statement+logged next to it; once nothing cancels it, autovacuum finishes on its own,+or the database operator runs `VACUUM (VERBOSE) <table>` in a quiet window.Postgres can also lose the statistics outright: `pg_upgrade` carries none andresets the modification counters, so autovacuum never collects them againdiff --git a/src/commands/doctor/checks/keyword-plan.ts b/src/commands/doctor/checks/keyword-plan.tsindex 97bec866b2..a53d1f08e3 100644--- a/src/commands/doctor/checks/keyword-plan.ts+++ b/src/commands/doctor/checks/keyword-plan.ts@@ -129,7 +129,7 @@ export async function keywordPlanCheck(engine: BrainEngine, probe: KeywordPlanPr}const canary = await probe.canary();if (!canary) {- return { name, status: 'ok', message: `Skipped: the planner has no statistics for content_chunks.search_vector yet (run ANALYZE content_chunks on the brain host, or let the next sync refresh them); the keyword bound is ${knob}.${recorded}`,+ return { name, status: 'ok', message: `Skipped: the planner has no statistics for content_chunks.search_vector yet (autovacuum's analyze collects them; to do it now, run ANALYZE content_chunks(search_vector) on the brain host while no vacuum is running on the table: an ANALYZE that waits on an autovacuum cancels it); the keyword bound is ${knob}.${recorded}`,details: { ...base, outcome: 'skipped', reason: 'no_statistics' } };}const percent = `${(canary.share * 100).toFixed(1)}%`;diff --git a/src/commands/doctor/checks/planner-stats.ts b/src/commands/doctor/checks/planner-stats.tsindex b8974420e7..e07052b1e5 100644--- a/src/commands/doctor/checks/planner-stats.ts+++ b/src/commands/doctor/checks/planner-stats.ts@@ -24,9 +24,13 @@* built. PGLite's next maintenance pass analyzes the table; on Postgres* autovacuum waits for 10% of the rows to change, so the operator runs the* repair.+ *+ * Postgres also warns when autovacuum is starved on a hot table (`readVacuumStarvation`, #7083): its dead rows passed+ * the vacuum threshold and no vacuum completed for a day, because something keeps cancelling it. That stops the+ * autovacuum's analyze as well; the fix is the database operator's.*/import { plannerAutoAnalyzeEnabled, PLANNER_STATS_REPAIR_COMMAND, readExpressionIndexesWithoutStats, readPlannerTableStates,- type ExpressionIndexGap } from '../../../core/planner-stats.ts';+ readVacuumStarvation, VACUUM_STARVATION_HOURS, type ExpressionIndexGap, type VacuumStarvation } from '../../../core/planner-stats.ts';import { canAnalyzePages, missingSearchStatistics } from '../../../core/search/projection-statistics.ts';import type { Check } from '../../doctor.ts';import { doctorVerify } from '../check-fix.ts';@@ -47,10 +51,11 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {const stale = tables.filter(t => t.stale);const missing = await missingSearchStatistics(engine);const gaps = await readExpressionIndexesWithoutStats(engine);+ const starved = await readVacuumStarvation(engine);const details = { engine: engine.kind, auto_analyze: autoAnalyze, checked: tables.map(t => t.table), stale, missing_search_statistics: missing,- expression_indexes_without_statistics: gaps, fix: PLANNER_STATS_REPAIR_COMMAND };- const expression = expressionIndexText(gaps, engine.kind, autoAnalyze);- if (stale.length === 0 && missing.length === 0 && gaps.length === 0) {+ expression_indexes_without_statistics: gaps, vacuum_starved: starved, fix: PLANNER_STATS_REPAIR_COMMAND };+ const expression = [expressionIndexText(gaps, engine.kind, autoAnalyze), starvationText(starved)].filter(Boolean).join(' ');+ if (stale.length === 0 && missing.length === 0 && gaps.length === 0 && starved.length === 0) {checks.push({ name: 'planner_stats_stale', status: 'ok', message: `Planner statistics are fresh on ${tables.length} hot tables.`, details });return checks;}@@ -65,6 +70,13 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {verify: doctorVerify('planner_stats_stale'), requires_exclusive: false } });return checks;}+ if (stale.length === 0 && gaps.length === 0) {+ const why = starvationText(starved);+ checks.push({ name: 'planner_stats_stale', status: 'warn', message: why, details,+ fix: { argv: ['psql', '-c', `VACUUM (VERBOSE) ${starved.map(s => s.table).join(', ')}`], consent: [], actor: 'host_admin', why,+ verify: doctorVerify('planner_stats_stale'), requires_exclusive: false } });+ return checks;+ }if (stale.length === 0) {checks.push({ name: 'planner_stats_stale', status: 'warn', message: `${expression} Fix on the brain host: ${PLANNER_STATS_REPAIR_COMMAND}.`, details });return checks;@@ -85,6 +97,17 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {return checks;}+/** The starved-autovacuum sentence (#7083): which tables, their dead rows, and what the operator looks for. */+function starvationText(starved: VacuumStarvation[]): string {+ if (starved.length === 0) return '';+ const listed = starved.map(s => `${s.table} (${s.dead_rows} dead rows, vacuum threshold ${s.threshold}, last completed vacuum ${s.vacuumed_at ?? 'never recorded'}${s.vacuum_running ? ', an autovacuum is running now' : ''})`).join(', ');+ return `Autovacuum is starved: ${listed}. No vacuum completed on ${starved.length === 1 ? 'it' : 'them'} in ${VACUUM_STARVATION_HOURS} h although the dead rows passed the threshold, `+ + 'so something keeps cancelling it: Postgres cancels an autovacuum whenever another session waits a second for its lock (an ANALYZE, an index build, a LOCK). '+ + 'Dead rows stay in every index until a vacuum finishes, and the autovacuum\'s analyze never runs. gbrain\'s own ANALYZE no longer waits on a vacuum; '+ + 'look for "canceling autovacuum task" in the server log and the statement logged beside it. Once nothing cancels it, autovacuum finishes on its own, '+ + 'or the database operator runs VACUUM (VERBOSE) on the table in a quiet window.';+}+/** The expression-index sentence: its own reason, never a row delta, and who runs the ANALYZE on this engine. */function expressionIndexText(gaps: ExpressionIndexGap[], kind: string, autoAnalyze: boolean | null): string {if (gaps.length === 0) return '';diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 33af9272d3..7f2f21712c 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -733,7 +733,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promislet drainError: { err: unknown } | undefined;const drain = (async () => {try {- await withChunkStatisticsRefresh(engine, () => !opts.dryRun && result.embedded > 0 && !isAborted(drainSignal), () => embedAll(engine, !!opts.stale, !!opts.dryRun, result, opts.onProgress, opts.sourceId, {+ await withChunkStatisticsRefresh(engine, () => opts.dryRun || isAborted(drainSignal) ? 0 : result.embedded, () => embedAll(engine, !!opts.stale, !!opts.dryRun, result, opts.onProgress, opts.sourceId, {batchSize: opts.batchSize,priority: opts.priority,catchUp: opts.catchUp,diff --git a/src/core/analyze-lock.ts b/src/core/analyze-lock.tsnew file mode 100644index 0000000000..d74dcc2459--- /dev/null+++ b/src/core/analyze-lock.ts@@ -0,0 +1,25 @@+import type { BrainEngine } from './engine.ts';++/** SQLSTATE lock_not_available: a NOWAIT lock request met a conflicting lock. */+const LOCK_NOT_AVAILABLE = '55P03';++/**+ * #7083: ANALYZE takes SHARE UPDATE EXCLUSIVE, the lock a running VACUUM or autovacuum holds. Postgres cancels a+ * (non-wraparound) autovacuum once another session has waited `deadlock_timeout` (1 s by default) for a lock it holds,+ * so an ANALYZE that waits (the refresh's 2 s lock timeout, or none at all) cancels the autovacuum it meets. Run after+ * every embed drain on a 10M-chunk content_chunks, that cancelled every autovacuum of the table before it finished.+ *+ * Every ANALYZE gbrain runs on Postgres on its own takes the table's lock first, inside its transaction, with NOWAIT:+ * a lock that is not free at once (a vacuum, another ANALYZE, an index build) fails with 55P03 and the caller defers+ * its ANALYZE (`analyzeDeferred`) instead of waiting. A request that never waits never signals a vacuum, and the+ * ANALYZE that follows reuses the lock this transaction holds. PGLite has no autovacuum and takes no lock here.+ */+export async function lockTableForAnalyze(tx: Pick<BrainEngine, 'executeRaw' | 'kind'>, table: string): Promise<void> {+ if (tx.kind !== 'postgres') return;+ await tx.executeRaw(`LOCK TABLE ${table} IN SHARE UPDATE EXCLUSIVE MODE NOWAIT`);+}++/** Whether `error` is `lockTableForAnalyze`'s refusal: another session holds the table, so the ANALYZE is deferred. */+export function analyzeDeferred(error: unknown): boolean {+ return !!error && typeof error === 'object' && (error as { code?: unknown }).code === LOCK_NOT_AVAILABLE;+}diff --git a/src/core/planner-stats.ts b/src/core/planner-stats.tsindex a8de4a871b..974922da77 100644--- a/src/core/planner-stats.ts+++ b/src/core/planner-stats.ts@@ -27,6 +27,7 @@* and an operator runs `gbrain repair planner-stats --apply`.*/import type { BrainEngine } from './engine.ts';+import { lockTableForAnalyze } from './analyze-lock.ts';import { PLANNER_STATS_TABLES, type PlannerStatsTable } from './planner-stats-schema.ts';export const PLANNER_STATS_MIN_PENDING = 500;@@ -192,7 +193,11 @@ export async function readPlannerTableStates(engine: BrainEngine): Promise<Plannreturn engine.kind === 'pglite' ? readPlannerStatsState(engine) : readPostgresPlannerStats(engine);}-/** `gbrain repair planner-stats --apply`: one bounded ANALYZE on the brain host (Postgres: 60 s statement, 2 s lock timeout). */+/**+ * `gbrain repair planner-stats --apply`: one bounded ANALYZE on the brain host (Postgres: 60 s statement; a table+ * another session holds, such as a running autovacuum, throws `lockTableForAnalyze`'s 55P03 at once instead of+ * waiting and cancelling the vacuum, #7083).+ */export async function repairPlannerTable(engine: BrainEngine, table: PlannerStatsTable): Promise<void> {if (!PLANNER_STATS_TABLES.includes(table)) throw new Error(`Not a planner statistics table: ${table}`);if (engine.kind === 'pglite') {@@ -202,10 +207,47 @@ export async function repairPlannerTable(engine: BrainEngine, table: PlannerStatawait engine.transaction(async tx => {await tx.executeRaw("SET LOCAL statement_timeout = '60s'");await tx.executeRaw("SET LOCAL lock_timeout = '2s'");+ await lockTableForAnalyze(tx, table);await tx.executeRaw(`ANALYZE ${table}`);});}+/** Below this many rows a hot table's vacuum finishes in seconds, so its dead rows are never reported as starved. */+export const VACUUM_STARVATION_MIN_ROWS = 100_000;+/** A hot table past autovacuum's vacuum threshold with no completed vacuum for this long is starved. */+export const VACUUM_STARVATION_HOURS = 24;++/** A hot Postgres table whose dead rows passed autovacuum's vacuum threshold while no vacuum completed for a day. */+export interface VacuumStarvation { table: PlannerStatsTable; dead_rows: number; threshold: number; vacuumed_at: string | null; vacuum_running: boolean }++/**+ * #7083 (Postgres; [] on PGLite): hot tables of at least VACUUM_STARVATION_MIN_ROWS rows holding more dead rows than+ * autovacuum's vacuum threshold (`autovacuum_vacuum_threshold` + `autovacuum_vacuum_scale_factor` x rows, the server+ * settings) whose last completed VACUUM or autovacuum is over VACUUM_STARVATION_HOURS old or unrecorded. Postgres+ * cancels an autovacuum whenever another session waits a second for a lock it holds (an ANALYZE, an index build, a+ * LOCK), so a table one of them keeps meeting is never vacuumed, and its dead rows stay in every index.+ * `vacuum_running`: an autovacuum worker holds a lock on the table now (pg_locks, which every role can read).+ */+export async function readVacuumStarvation(engine: BrainEngine): Promise<VacuumStarvation[]> {+ if (engine.kind !== 'postgres') return [];+ const rows = await engine.executeRaw<{ table_name: PlannerStatsTable; dead_rows: string | number; threshold: number;+ vacuumed_at: string | Date | null; vacuum_running: boolean }>(+ `SELECT s.relname AS table_name, s.n_dead_tup AS dead_rows, v.threshold,+ GREATEST(s.last_vacuum, s.last_autovacuum) AS vacuumed_at,+ EXISTS (SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid+ WHERE l.relation = s.relid AND l.granted AND a.backend_type = 'autovacuum worker') AS vacuum_running+ FROM pg_stat_user_tables s JOIN pg_class c ON c.oid = s.relid+ CROSS JOIN LATERAL (SELECT current_setting('autovacuum_vacuum_threshold')::float8+ + current_setting('autovacuum_vacuum_scale_factor')::float8 * GREATEST(c.reltuples, 0) AS threshold) v+ WHERE s.schemaname = current_schema() AND s.relname = ANY($1::text[])+ AND c.reltuples >= $2 AND s.n_dead_tup > v.threshold+ AND COALESCE(GREATEST(s.last_vacuum, s.last_autovacuum) < now() - make_interval(hours => $3::int), true)+ ORDER BY array_position($1::text[], s.relname::text)`,+ [[...PLANNER_STATS_TABLES], VACUUM_STARVATION_MIN_ROWS, VACUUM_STARVATION_HOURS]);+ return rows.map(row => ({ table: row.table_name, dead_rows: Number(row.dead_rows), threshold: Math.round(Number(row.threshold)),+ vacuumed_at: row.vacuumed_at == null ? null : new Date(row.vacuumed_at).toISOString(), vacuum_running: !!row.vacuum_running }));+}+async function readWatermarks(engine: BrainEngine, tables: readonly PlannerStatsTable[]): Promise<Map<PlannerStatsTable, number>> {const rows = await engine.executeRaw<{ table_name: PlannerStatsTable; watermark: string | number }>(`SELECT t.table_name, COALESCE((SELECT max(d.id) FROM planner_stats_deltas d WHERE d.table_name = t.table_name), 0) AS watermarkdiff --git a/src/core/repair/planner-stats.ts b/src/core/repair/planner-stats.tsindex b7ac310216..58bd11a5fe 100644--- a/src/core/repair/planner-stats.ts+++ b/src/core/repair/planner-stats.ts@@ -17,6 +17,7 @@* it. On Postgres this repair is the recovery (autovacuum waits for 10% of the* rows to change), run by an operator.*/+import { analyzeDeferred } from '../analyze-lock.ts';import { PLANNER_STATS_TABLES, type PlannerStatsTable } from '../planner-stats-schema.ts';import { readExpressionIndexesWithoutStats, readPlannerTableStates, repairPlannerTable } from '../planner-stats.ts';import { missingSearchStatistics, refreshProjectionStatistics } from '../search/projection-statistics.ts';@@ -49,7 +50,12 @@ export const plannerStatsRepair: RepairHandler = {async apply(ctx, item) {if (item.slug === SEARCH_STATISTICS_ITEM) return refreshProjectionStatistics(ctx.engine);if (!PLANNER_STATS_TABLES.includes(item.slug as PlannerStatsTable)) return false;- await repairPlannerTable(ctx.engine, item.slug as PlannerStatsTable);+ try {+ await repairPlannerTable(ctx.engine, item.slug as PlannerStatsTable);+ } catch (error) {+ if (!analyzeDeferred(error)) throw error;+ return { applied: false, outcome: 'deferred', reason: `another session (a vacuum, an ANALYZE or an index build) holds ${item.slug}; the repair never waits on it, so it cannot cancel an autovacuum (#7083). Rerun the repair once that session finishes.` };+ }return true;},};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 87c3328b84..4711e7702e 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -314,7 +314,7 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'], approval: 'unbound',summary: 'ANALYZE the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale (F4b), '+ 'so search and graph reads stop planning as slow nested loops. PGLite also resets each table\'s pending row count; Postgres runs each '- + 'ANALYZE with a 60 s statement and 2 s lock timeout. No journal admission and no user data changes. Brain-wide.',+ + 'ANALYZE with a 60 s statement timeout and defers a table another session holds (a running vacuum) instead of waiting on it. No journal admission and no user data changes. Brain-wide.',},'managed-sync-orphans': {handler: managedSyncOrphansRepair, embeds: 'none', checks: ['sync_failures'], explicit_only: true, preview_bound: true,diff --git a/src/core/schema-migrations/helpers.ts b/src/core/schema-migrations/helpers.tsindex 300c9d7a17..a0e81679fc 100644--- a/src/core/schema-migrations/helpers.ts+++ b/src/core/schema-migrations/helpers.ts@@ -6,6 +6,7 @@* (ESM import cycle -> TDZ at module load, including in the compiled binary).*/import type { BrainEngine } from '../engine.ts';+import { analyzeDeferred, lockTableForAnalyze } from '../analyze-lock.ts';/*** When true, per-migration explanatory notices (e.g. the v123/v124 "here is@@ -130,27 +131,43 @@ async function tableRows(engine: BrainEngine, table: string): Promise<number> {/** The hot tables `gbrain repair planner-stats` analyzes (PLANNER_STATS_TABLES; this leaf does not import planner-stats). */const PLANNER_REPAIR_TABLES = new Set(['pages', 'links', 'facts', 'takes', 'content_chunks', 'timeline_entries']);+/**+ * #7083: one migration ANALYZE in its own transaction that never waits on the table's lock (`lockTableForAnalyze`):+ * a vacuum, ANALYZE or index build holding the table defers it (returns false) instead of cancelling an autovacuum,+ * which on a large table restarts its whole heap scan. `statementTimeoutMs` bounds it on Postgres; other errors throw.+ */+export async function analyzeYieldingToVacuum(engine: BrainEngine, table: string, columns = '', statementTimeoutMs?: number): Promise<boolean> {+ try {+ await engine.transaction(async tx => {+ if (engine.kind === 'postgres' && statementTimeoutMs) await tx.executeRaw(`SET LOCAL statement_timeout = '${statementTimeoutMs}ms'`);+ await lockTableForAnalyze(tx, table);+ await tx.executeRaw(`ANALYZE ${table}${columns ? `(${columns})` : ''}`);+ });+ return true;+ } catch (error) {+ if (analyzeDeferred(error)) return false;+ throw error;+ }+}+/*** lhf wave 2 item 6: a new index on an expression has no planner statistics until* its table is analyzed, and PGLite runs no autovacuum (a 50-name `entity names`* batch after v240 on a 55k-page PGLite brain: 5.4 s, 1.2 s after ANALYZE pages).* Best effort: one whole-table ANALYZE (a column list collects no index- * statistics), Postgres bounded by a 60 s statement and 2 s lock timeout. A- * failure prints the command that finishes the job and never fails the build of- * a valid index; doctor `planner_stats_stale` keeps reporting the index.+ * statistics), Postgres bounded by a 60 s statement and deferred, never waiting,+ * while another session holds the table (#7083). A failure or deferral prints the+ * command that finishes the job and never fails the build of a valid index;+ * doctor `planner_stats_stale` keeps reporting the index.*/export async function analyzeAfterIndexBuild(engine: BrainEngine, index: { name: string; table: string }): Promise<boolean> {+ const fix = PLANNER_REPAIR_TABLES.has(index.table) ? 'gbrain repair planner-stats --apply' : `ANALYZE ${index.table} as the table owner`;try {- await engine.transaction(async tx => {- if (engine.kind === 'postgres') {- await tx.executeRaw("SET LOCAL statement_timeout = '60s'");- await tx.executeRaw("SET LOCAL lock_timeout = '2s'");- }- await tx.executeRaw(`ANALYZE ${index.table}`);- });- return true;+ if (await analyzeYieldingToVacuum(engine, index.table, '', 60_000)) return true;+ console.warn(` [warn] ${index.name} is built and valid, but ANALYZE ${index.table} was deferred: another session (a vacuum, an ANALYZE `+ + `or an index build) holds the table, and a migration never waits on it. The planner has no statistics for the index yet. Once it finishes, run on the brain host: ${fix}`);+ return false;} catch (err) {- const fix = PLANNER_REPAIR_TABLES.has(index.table) ? 'gbrain repair planner-stats --apply' : `ANALYZE ${index.table} as the table owner`;console.warn(` [warn] ${index.name} is built and valid, but ANALYZE ${index.table} failed `+ `(${err instanceof Error ? err.message : String(err)}); the planner has no statistics for it yet. Run on the brain host: ${fix}`);return false;diff --git a/src/core/schema-migrations/v248-segmented-page-storage.ts b/src/core/schema-migrations/v248-segmented-page-storage.tsindex 381d3604a3..c02f4349ae 100644--- a/src/core/schema-migrations/v248-segmented-page-storage.ts+++ b/src/core/schema-migrations/v248-segmented-page-storage.ts@@ -1,7 +1,7 @@import type { Migration } from './types.ts';import { PAGE_BODY_SCHEMA_SQL, PAGE_GENERATION_BUMP_FN_SQL } from '../page-body/schema.ts';import { PAGE_SEARCH_VECTOR_TRIGGER_SQL } from '../page-state/projection-schema.ts';-import { buildIndexOnline, migrationNotice } from './helpers.ts';+import { analyzeYieldingToVacuum, buildIndexOnline, migrationNotice } from './helpers.ts';// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.@@ -109,8 +109,13 @@ export const v248: Migration = {await buildIndexOnline(engine, 248, CONTENT_CHUNKS_OCCURRENCE_INDEX, { notice: migrationNotice });// Search's visibility predicate reads the generation columns; without their statistics Postgres prices it at 0.5%// and vector search sorts every candidate instead of walking its HNSW index (projection-statistics.ts).+ // #7083: an ANALYZE that waited on a running autovacuum cancelled it; a deferred one is left to the search guard and doctor.if (engine.kind === 'postgres') {- await engine.runMigration(248, 'ANALYZE pages(body_generation); ANALYZE content_chunks(body_generation, retired_generation);');+ for (const [table, columns] of [['pages', 'body_generation'], ['content_chunks', 'body_generation, retired_generation']] as const) {+ if (await analyzeYieldingToVacuum(engine, table, columns)) continue;+ migrationNotice(` ANALYZE ${table}(${columns}) deferred: another session (a vacuum, an ANALYZE or an index build) holds ${table}. `+ + 'The search statistics refresh and doctor planner_stats_stale pick it up; no migration step waits on it.');+ }}},};diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.tsindex 4f1c83a1b5..0ee9ab9d1f 100644--- a/src/core/search/projection-statistics.ts+++ b/src/core/search/projection-statistics.ts@@ -1,4 +1,5 @@import type { BrainEngine } from '../engine.ts';+import { analyzeDeferred, lockTableForAnalyze } from '../analyze-lock.ts';import { beginFullAnalyze, maybeRefreshPlannerStats, plannerAutoAnalyzeEnabled } from '../planner-stats.ts';export const PROJECTION_STATISTICS_NAME = 'pages_text_projection_current_stats';@@ -79,36 +80,58 @@ export const CHUNK_STATISTICS_SQL = `ANALYZE content_chunks(${SEARCH_STATISTICS_*/export const SEARCH_PAGE_STATISTICS_SQL = `ANALYZE pages(${SEARCH_STATISTICS_COLUMNS.pages.join(', ')})`;-const CHUNK_STATISTICS_WARNING = `[search] Chunk planner statistics could not be refreshed (a lock or the 30 s bound). Vector search may skip its index until autovacuum analyzes content_chunks; run ${CHUNK_STATISTICS_SQL} as the table owner to fix it now.`;+const CHUNK_STATISTICS_WARNING = `[search] Chunk planner statistics could not be refreshed (the 30 s bound or a missing privilege). Vector search may skip its index until autovacuum analyzes content_chunks; run ${CHUNK_STATISTICS_SQL} as the table owner to fix it now.`;+const CHUNK_STATISTICS_DEFERRED = '[search] Chunk planner statistics refresh deferred: another session (a vacuum, an ANALYZE or an index build) holds content_chunks, and this refresh never waits on it (#7083). Autovacuum analyzes the table, and the next import, sync or embed drain refreshes it again.';/**- * The chunk ANALYZE inside a caller's bounded Postgres transaction, behind a- * savepoint: a concurrent index build holding the table's lock (2 s lock- * timeout) costs this step alone, never the caller's page statistics. A role- * that does not own the table gets Postgres's skip warning, not an error.+ * The chunk ANALYZE inside a caller's bounded Postgres transaction, in a nested+ * transaction (a savepoint the driver rolls back, so a failed statement never+ * aborts the caller's transaction): a vacuum, ANALYZE or index build holding+ * the table's lock defers this step alone (`lockTableForAnalyze`, which never+ * waits, so it never cancels an autovacuum), never the caller's page+ * statistics. A role that does not own the table gets Postgres's skip warning,+ * not an error.*/async function analyzeChunkColumns(tx: BrainEngine): Promise<boolean> {- await tx.executeRaw('SAVEPOINT chunk_statistics');try {- await tx.executeRaw(CHUNK_STATISTICS_SQL);- await tx.executeRaw('RELEASE SAVEPOINT chunk_statistics');+ await tx.transaction(async step => {+ await lockTableForAnalyze(step, 'content_chunks');+ await step.executeRaw(CHUNK_STATISTICS_SQL);+ });return true;- } catch {- await tx.executeRaw('ROLLBACK TO SAVEPOINT chunk_statistics');- console.warn(CHUNK_STATISTICS_WARNING);+ } catch (error) {+ console.warn(analyzeDeferred(error) ? CHUNK_STATISTICS_DEFERRED : CHUNK_STATISTICS_WARNING);return false;}}+/**+ * #7083: whether a drain that changed `changedRows` chunks can leave the chunk statistics alone: content_chunks was+ * sampled with rows, its `SEARCH_STATISTICS_COLUMNS` statistics exist, and the drain changed fewer than 50 + 10% of+ * its sampled rows (autovacuum's analyze threshold, as `statisticsStillCurrent` for pages). Such a drain barely moves+ * them, and autovacuum's own analyze covers what small drains add up to. Without this, every import's embed drain on+ * a 10M-chunk table ran a 2-6 s ANALYZE.+ */+async function chunkStatisticsStillCurrent(engine: BrainEngine, changedRows: number): Promise<boolean> {+ if (!Number.isFinite(changedRows)) return false;+ const [state] = await engine.executeRaw<{ reltuples: number }>(`SELECT reltuples::float8 AS reltuples FROM pg_class WHERE oid = 'content_chunks'::regclass`);+ const rows = Number(state?.reltuples ?? -1);+ if (rows <= 0 || changedRows >= 50 + 0.1 * rows) return false;+ return !(await missingSearchStatistics(engine)).some(column => column.startsWith('content_chunks.'));+}+/*** Postgres only (PGLite's planner-stats deltas own its chunk statistics): one- * bounded narrow ANALYZE of content_chunks after an embed drain, which moves- * content_chunks.model on every row it embeds. Import, sync and reindex get- * the same step inside refreshProjectionStatistics.+ * bounded narrow ANALYZE of content_chunks after an embed drain that changed+ * `changedRows` chunks (omitted: always), which moves content_chunks.model on+ * every row it embeds. A drain `chunkStatisticsStillCurrent` vouches for+ * skips it. Import, sync and reindex get the same step inside+ * refreshProjectionStatistics.*/-export async function refreshChunkStatistics(engine: BrainEngine): Promise<boolean> {+export async function refreshChunkStatistics(engine: BrainEngine, changedRows = Infinity): Promise<boolean> {if (engine.kind !== 'postgres') return false;try {+ if (await chunkStatisticsStillCurrent(engine, changedRows)) return true;return await engine.transaction(async tx => {await tx.executeRaw("SET LOCAL statement_timeout = '30s'");await tx.executeRaw("SET LOCAL lock_timeout = '2s'");@@ -120,10 +143,11 @@ export async function refreshChunkStatistics(engine: BrainEngine): Promise<boole}}-/** Runs an embed drain, then refreshes the chunk statistics once when `changed()` says it embedded something (a drain moves content_chunks.model on every row it embeds). */-export async function withChunkStatisticsRefresh<T>(engine: BrainEngine, changed: () => boolean, drain: () => Promise<T>): Promise<T> {+/** Runs an embed drain, then refreshes the chunk statistics once for the `changed()` chunks it embedded (none: no refresh; a drain moves content_chunks.model on every row it embeds). */+export async function withChunkStatisticsRefresh<T>(engine: BrainEngine, changed: () => number, drain: () => Promise<T>): Promise<T> {const out = await drain();- if (changed()) await refreshChunkStatistics(engine);+ const rows = changed();+ if (rows > 0) await refreshChunkStatistics(engine, rows);return out;}@@ -247,6 +271,7 @@ export async function refreshProjectionStatistics(engine: BrainEngine, changedPaif (engine.kind === 'postgres') {await tx.executeRaw("SET LOCAL statement_timeout = '30s'");await tx.executeRaw("SET LOCAL lock_timeout = '2s'");+ await lockTableForAnalyze(tx, 'pages');}// PGLite has no autovacuum, so nothing else ever collects planner statistics there. Without them the// planner sees empty tables and runs search's graph joins as pages-by-pages nested loops (about 50 s@@ -260,8 +285,10 @@ export async function refreshProjectionStatistics(engine: BrainEngine, changedPaawait verifyProjectionStatistics(tx);});return true;- } catch {- console.warn('[search] Projection planner statistics could not be refreshed. Run ANALYZE pages(text_projection_revision, knowledge_revision) as the table owner; completed page writes were retained.');+ } catch (error) {+ console.warn(analyzeDeferred(error)+ ? '[search] Projection planner statistics refresh deferred: another session (a vacuum, an ANALYZE or an index build) holds pages, and this refresh never waits on it (#7083). Completed page writes were retained; the next import or sync refreshes them.'+ : '[search] Projection planner statistics could not be refreshed. Run ANALYZE pages(text_projection_revision, knowledge_revision) as the table owner; completed page writes were retained.');return false;}}diff --git a/test/e2e/analyze-yields-to-autovacuum-postgres.test.ts b/test/e2e/analyze-yields-to-autovacuum-postgres.test.tsnew file mode 100644index 0000000000..368d30f5db--- /dev/null+++ b/test/e2e/analyze-yields-to-autovacuum-postgres.test.ts@@ -0,0 +1,140 @@+/**+ * #7083: gbrain's ANALYZEs never cancel an autovacuum. ANALYZE takes SHARE UPDATE EXCLUSIVE, which a running+ * autovacuum holds, and Postgres cancels a (non-wraparound) autovacuum once another session has waited+ * deadlock_timeout (1 s) for it. The chunk refresh after every embed drain waited up to its 2 s lock timeout, so on a+ * 10M-chunk content_chunks every autovacuum of the table was cancelled before it finished.+ *+ * Runs in a dedicated database. It makes autovacuum vacuum content_chunks slowly (cost delay 100 ms per page, naptime+ * 1 s for the duration of the test, restored in afterAll), then, while that autovacuum holds the table, runs every+ * ANALYZE path gbrain owns on Postgres: each returns at once without waiting, and the same autovacuum is still+ * vacuuming content_chunks after deadlock_timeout has passed. Before the fix the first refresh cancelled it.+ * It also pins the drain rate limit (a small drain on a sampled table leaves the statistics alone) and doctor's+ * starved-autovacuum signal.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { refreshChunkStatistics, refreshProjectionStatistics } from '../../src/core/search/projection-statistics.ts';+import { readVacuumStarvation, repairPlannerTable } from '../../src/core/planner-stats.ts';+import { analyzeDeferred } from '../../src/core/analyze-lock.ts';+import { analyzeAfterIndexBuild, analyzeYieldingToVacuum } from '../../src/core/schema-migrations/helpers.ts';+import { plannerStatsEntry } from '../../src/commands/doctor/checks/planner-stats.ts';+import type { DoctorContext } from '../../src/commands/doctor/context.ts';+import { hasDatabase } from './helpers.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const PAGES = 3_000;+const CHUNKS_PER_PAGE = 40;+const adminUrl = process.env.GBRAIN_PGBOUNCER_DIRECT_URL ?? process.env.DATABASE_URL ?? '';+const dbName = `gbrain_test_analyze_yield_${randomUUID().replaceAll('-', '')}`;+let admin: ReturnType<typeof postgres> | undefined;+let engine: PostgresEngine;+let naptime: string | undefined;++let chunksOid = 0;++/** The transactions that wrote content_chunks' pg_statistic rows: they change exactly when an ANALYZE samples the table. */+async function chunkStatisticsXmin(): Promise<string> {+ const [row] = await engine.executeRaw<{ x: string }>(`SELECT string_agg(xmin::text, ',' ORDER BY staattnum) AS x FROM pg_statistic WHERE starelid = 'content_chunks'::regclass`);+ return String(row?.x);+}++/** The autovacuum worker vacuuming content_chunks in this database, if any (the test role is a superuser, so it sees relid). */+async function vacuumingPid(): Promise<number | null> {+ const [row] = await admin!.unsafe(`SELECT p.pid FROM pg_stat_progress_vacuum p JOIN pg_stat_activity a ON a.pid = p.pid+ WHERE p.datname = $1 AND a.backend_type = 'autovacuum worker' AND p.relid = $2::oid`, [dbName, chunksOid]);+ return row ? Number(row.pid) : null;+}++(hasDatabase() ? describe : describe.skip)('ANALYZE yields to a running autovacuum (Postgres, #7083)', () => {+ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ admin = postgres(adminUrl, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${dbName}`);+ const url = new URL(adminUrl);+ url.pathname = `/${dbName}`;+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });+ engine = new PostgresEngine();+ await engine.connect({ database_url: url.toString(), poolSize: 3 });+ await engine.initSchema();+ for (const table of ['content_chunks', 'pages']) await engine.executeRaw(`ALTER TABLE ${table} SET (autovacuum_enabled = off, toast.autovacuum_enabled = off)`);+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)+ SELECT 'notes/yield-' || i, 'default', 'note', 'Yield ' || i, 'fixture', '00000000-0000-4000-8000-000000000001'::uuid,+ '00000000-0000-4000-8000-000000000001'::uuid, 4+ FROM generate_series(1, ${PAGES}) i`);+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash)+ SELECT p.id, c, 'chunk ' || p.id || '/' || c, 'compiled_truth', 'openai:text-embedding-3-small', md5('chunk ' || p.id || '/' || c)+ FROM pages p CROSS JOIN generate_series(0, ${CHUNKS_PER_PAGE - 1}) c`);+ const [oid] = await engine.executeRaw<{ oid: number }>(`SELECT 'content_chunks'::regclass::oid::int8 AS oid`);+ chunksOid = Number(oid!.oid);+ const [setting] = await admin.unsafe(`SELECT setting FROM pg_settings WHERE name = 'autovacuum_naptime'`);+ naptime = String(setting!.setting);+ }, 180_000);++ afterAll(async () => {+ await engine?.disconnect();+ resetGateway();+ if (admin) {+ await admin.unsafe('ALTER SYSTEM RESET autovacuum_naptime').catch(() => undefined);+ await admin.unsafe('SELECT pg_reload_conf()').catch(() => undefined);+ await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);+ await admin.end();+ }+ }, 60_000);++ test('an embed drain that changed few chunks of a sampled table leaves the chunk statistics alone', async () => {+ expect(await refreshProjectionStatistics(engine)).toBe(true);+ const sampled = await chunkStatisticsXmin();+ expect(sampled).not.toBe('undefined');+ expect(await refreshChunkStatistics(engine, 10)).toBe(true);+ expect(await chunkStatisticsXmin()).toBe(sampled);+ expect(await refreshChunkStatistics(engine, 50 + 0.1 * PAGES * CHUNKS_PER_PAGE)).toBe(true);+ expect(await chunkStatisticsXmin()).not.toBe(sampled);+ }, 60_000);++ test('doctor reports a hot table whose autovacuum never completes', async () => {+ await engine.executeRaw(`DELETE FROM content_chunks WHERE chunk_index >= ${CHUNKS_PER_PAGE - 12}`);+ let starved = await readVacuumStarvation(engine);+ for (let i = 0; i < 40 && !starved.length; i++) { await Bun.sleep(250); starved = await readVacuumStarvation(engine); }+ expect(starved.map(s => s.table)).toEqual(['content_chunks']);+ expect(starved[0]!.vacuumed_at).toBeNull();+ expect(starved[0]!.dead_rows).toBeGreaterThan(starved[0]!.threshold);+ const [check] = await plannerStatsEntry.run({ engine, progress: { heartbeat: () => {} } } as unknown as DoctorContext);+ expect(check!.status).toBe('warn');+ expect(check!.message).toContain('Autovacuum is starved: content_chunks');+ }, 60_000);++ test('every ANALYZE gbrain runs defers at once while an autovacuum holds content_chunks, and the autovacuum is not cancelled', async () => {+ const [deadlock] = await admin!.unsafe(`SELECT setting::int AS ms FROM pg_settings WHERE name = 'deadlock_timeout'`);+ const deadlockMs = Number(deadlock!.ms);+ // A slow autovacuum of content_chunks only: 100 ms per page visited, no analyze.+ await engine.executeRaw(`ALTER TABLE content_chunks SET (autovacuum_enabled = on, autovacuum_vacuum_threshold = 0, autovacuum_vacuum_scale_factor = 0,+ autovacuum_vacuum_insert_threshold = -1, autovacuum_analyze_threshold = 2000000000, autovacuum_vacuum_cost_delay = 100, autovacuum_vacuum_cost_limit = 1)`);+ await admin!.unsafe(`ALTER SYSTEM SET autovacuum_naptime = '1s'`);+ await admin!.unsafe('SELECT pg_reload_conf()');+ let pid: number | null = null;+ for (let i = 0; i < 240 && pid === null; i++) { await Bun.sleep(250); pid = await vacuumingPid(); }+ expect(pid, `precondition: autovacuum never started on content_chunks (naptime was ${naptime})`).not.toBeNull();+ expect((await readVacuumStarvation(engine))[0]?.vacuum_running).toBe(true);++ const timed = async <T>(run: () => Promise<T>): Promise<[T, number]> => { const t = performance.now(); const out = await run(); return [out, performance.now() - t]; };+ const [chunks, chunkMs] = await timed(() => refreshChunkStatistics(engine));+ expect(chunks).toBe(false);+ // The page step still refreshes; only the chunk step behind its savepoint is deferred.+ const [projection, projectionMs] = await timed(() => refreshProjectionStatistics(engine));+ expect(projection).toBe(true);+ const [repair, repairMs] = await timed(() => repairPlannerTable(engine, 'content_chunks').then(() => null, (error: unknown) => error));+ expect(analyzeDeferred(repair)).toBe(true);+ const [migration, migrationMs] = await timed(() => analyzeYieldingToVacuum(engine, 'content_chunks', 'body_generation'));+ expect(migration).toBe(false);+ const [index, indexMs] = await timed(() => analyzeAfterIndexBuild(engine, { name: 'idx_fixture', table: 'content_chunks' }));+ expect(index).toBe(false);+ for (const ms of [chunkMs, projectionMs, repairMs, migrationMs, indexMs]) expect(ms).toBeLessThan(deadlockMs);++ // Past deadlock_timeout, the same autovacuum is still vacuuming the table: nothing waited on it, so nothing cancelled it.+ await Bun.sleep(deadlockMs * 2);+ expect(await vacuumingPid()).toBe(pid);+ }, 180_000);+});