Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): conversation_outcomes_stale and missing_recorded_files stopped at their row bound report health unknown (#7145)

garrytanc3dfe45cf30a
diff --git a/src/commands/doctor/checks/conversation-outcomes.ts b/src/commands/doctor/checks/conversation-outcomes.ts
index 52cb60d42f..2d9b6a2c85 100644
--- a/src/commands/doctor/checks/conversation-outcomes.ts
+++ b/src/commands/doctor/checks/conversation-outcomes.ts
@@ -14,6 +14,7 @@
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
+import { boundUnknownDetails } from '../bounded-unknown.ts';
import { CONVERSATION_EXTRACTOR_VERSION, NON_EXTRACTABLE_AUDIT_SOURCE, outcomeExtractorVersion, TERMINAL_AUDIT_SOURCE } from '../../../core/facts/audit-sources.ts';
export const OUTCOME_SCAN_CAP = 5000;
@@ -34,6 +35,12 @@ export async function conversationOutcomesStaleCheck(engine: BrainEngine, source
const details = { extractor_version: CONVERSATION_EXTRACTOR_VERSION, scanned: scanned.length, capped,
stale: stale.length, unstamped, sample, docs: 'docs/guides/repair.md#conversation-labels' };
const atLeast = capped ? 'at least ' : '';
+ // #7145: stale outcomes are the old rows, which this newest-first cap reaches last: none found under it is unknown, not clear.
+ if (!stale.length && capped) {
+ return { name, status: 'warn', details: { ...details, ...boundUnknownDetails('rows'), limit: OUTCOME_SCAN_CAP },
+ message: `Stale conversation extraction outcomes unknown: only the newest ${OUTCOME_SCAN_CAP} outcome rows were read (OUTCOME_SCAN_CAP, no setting), `
+ + `and outcomes older than those, where a stale extractor version would be, were not. None of the rows read predates extractor version ${CONVERSATION_EXTRACTOR_VERSION}.` };
+ }
if (!stale.length) {
return { name, status: 'ok', details,
message: `No conversation extraction outcome predates extractor version ${CONVERSATION_EXTRACTOR_VERSION}`
diff --git a/src/commands/doctor/checks/missing-recorded-files.ts b/src/commands/doctor/checks/missing-recorded-files.ts
index 9cb2b0a0df..6abaf223ab 100644
--- a/src/commands/doctor/checks/missing-recorded-files.ts
+++ b/src/commands/doctor/checks/missing-recorded-files.ts
@@ -13,6 +13,7 @@ import type { Check } from '../../doctor.ts';
import { checkError, doctorVerify } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { scanMissingRecordedFiles, type MissingRecordedFiles } from '../../../core/persistence/detached-pages.ts';
+import { boundUnknownDetails } from '../bounded-unknown.ts';
const DOCS = 'docs/storage-tiering.md#restoring-a-page-whose-file-is-gone';
@@ -35,15 +36,24 @@ async function runMissingRecordedFiles(ctx: DoctorContext): Promise<Check[]> {
message: 'Not applicable: no source is a classic checkout on this host (managed sources are checked by ghost_pages).' });
return checks;
}
+ const truncated = scans.filter(scan => scan.truncated).map(scan => scan.source_id);
+ const limit = scans[0]?.limit;
+ // #7145: a source read only up to MISSING_FILES_SCAN_LIMIT pages is not clear past it.
+ if (!count && truncated.length) {
+ checks.push({ name: 'missing_recorded_files', status: 'warn', details: { ...details, ...boundUnknownDetails('rows'), limit },
+ message: `Unknown: the scan stops at ${limit} live pages per source (MISSING_FILES_SCAN_LIMIT, no setting) and ${truncated.join(', ')} ${truncated.length === 1 ? 'has' : 'have'} more, `
+ + `so pages past it were not checked. None of the ${scans.reduce((sum, scan) => sum + scan.inspected, 0)} page(s) inspected records a file missing from its checkout.` });
+ return checks;
+ }
if (!count) {
checks.push({ name: 'missing_recorded_files', status: 'ok', details,
- message: `Every live page's recorded file is in its checkout (${scans.reduce((sum, scan) => sum + scan.inspected, 0)} page(s) inspected${scans.some(scan => scan.truncated) ? '; bounded, more not checked' : ''}).` });
+ message: `Every live page's recorded file is in its checkout (${scans.reduce((sum, scan) => sum + scan.inspected, 0)} page(s) inspected).` });
return checks;
}
const first = found[0]!;
const sample = first.pages[0]!;
- checks.push({ name: 'missing_recorded_files', status: 'warn', details,
- message: `${count} live page(s) record a canonical file that is not in their checkout, so the next gbrain sync --full soft-deletes them `
+ checks.push({ name: 'missing_recorded_files', status: 'warn', details: { ...details, exact: !truncated.length },
+ message: `${truncated.length ? 'At least ' : ''}${count} live page(s) record a canonical file that is not in their checkout, so the next gbrain sync --full soft-deletes them `
+ `(${found.map(scan => `${scan.source_id}: ${scan.pages.length}`).join('; ')}; e.g. ${found.flatMap(scan => scan.pages.slice(0, 3).map(page => `${scan.source_id}:${page.slug} (${page.source_path})`)).slice(0, 5).join(', ')}). `
+ 'A page restored after its file left the checkout is the usual cause. To keep one with its file, put the file back, commit it and run gbrain sync; '
+ `to keep it database-only, run gbrain delete ${sample.slug} --source-id ${first.source_id}, then gbrain restore ${sample.slug} --source-id ${first.source_id} --detach. A page whose file you removed on purpose needs nothing.`,
diff --git a/src/core/persistence/detached-pages.ts b/src/core/persistence/detached-pages.ts
index 2e6f9e43ec..f831ea193d 100644
--- a/src/core/persistence/detached-pages.ts
+++ b/src/core/persistence/detached-pages.ts
@@ -97,8 +97,11 @@ export async function detachRestoredPage(tx: SqlEngine, row: Pick<WriteRequest,
/** Live pages of a source read per scan; past it the result says `truncated`. */
export const MISSING_FILES_SCAN_LIMIT = 50_000;
+let scanLimit = MISSING_FILES_SCAN_LIMIT;
+/** Tests only: a smaller per-source scan limit (null restores the default). */
+export function __setMissingFilesScanLimitForTests(limit: number | null): void { scanLimit = limit ?? MISSING_FILES_SCAN_LIMIT; }
-export interface MissingRecordedFiles { source_id: string; pages: Array<{ slug: string; source_path: string }>; inspected: number; truncated: boolean }
+export interface MissingRecordedFiles { source_id: string; pages: Array<{ slug: string; source_path: string }>; inspected: number; truncated: boolean; limit: number }
/**
* #6609: the live pages of a classic source (a `local_path` checkout on this
@@ -115,10 +118,10 @@ export async function scanMissingRecordedFiles(engine: BrainEngine, sourceId: st
const strategy = source.strategy ?? 'markdown';
const rows = await engine.executeRaw<{ slug: string; source_path: string }>(
`SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND NULLIF(btrim(source_path), '') IS NOT NULL
- ORDER BY id LIMIT ${MISSING_FILES_SCAN_LIMIT + 1}`, [sourceId]);
- const truncated = rows.length > MISSING_FILES_SCAN_LIMIT;
- const inspected = rows.slice(0, MISSING_FILES_SCAN_LIMIT).filter(row => isSyncable(row.source_path, { strategy }));
- const result: MissingRecordedFiles = { source_id: sourceId, pages: [], inspected: inspected.length, truncated };
+ ORDER BY id LIMIT ${scanLimit + 1}`, [sourceId]);
+ const truncated = rows.length > scanLimit;
+ const inspected = rows.slice(0, scanLimit).filter(row => isSyncable(row.source_path, { strategy }));
+ const result: MissingRecordedFiles = { source_id: sourceId, pages: [], inspected: inspected.length, truncated, limit: scanLimit };
if (!inspected.length) return result;
const { collectSyncableFiles } = await import('../../commands/import.ts');
const mode = await scannerSlugRootMode(engine, sourceId, root);
diff --git a/test/doctor-bound-unknown-7145.test.ts b/test/doctor-bound-unknown-7145.test.ts
index 413459c167..5d71ad66e6 100644
--- a/test/doctor-bound-unknown-7145.test.ts
+++ b/test/doctor-bound-unknown-7145.test.ts
@@ -10,6 +10,12 @@ import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { findMisroutedPages } from '../src/core/multi-source-drift.ts';
import { multiSourceDriftCheck } from '../src/commands/doctor/schema-pack-checks.ts';
+import { conversationOutcomesStaleCheck, OUTCOME_SCAN_CAP } from '../src/commands/doctor/checks/conversation-outcomes.ts';
+import { missingRecordedFilesEntry } from '../src/commands/doctor/checks/missing-recorded-files.ts';
+import { __setMissingFilesScanLimitForTests } from '../src/core/persistence/detached-pages.ts';
+import { CONVERSATION_EXTRACTOR_VERSION, TERMINAL_AUDIT_SOURCE } from '../src/core/facts/audit-sources.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
const dirs: string[] = [];
const tmp = (label: string) => {
@@ -63,3 +69,50 @@ describe('multi_source_drift stopped at its bound is unknown', () => {
expect(check.message).toContain('notes/alice-example');
});
});
+
+describe('conversation_outcomes_stale and missing_recorded_files stopped at their row bound are unknown', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+ afterAll(async () => {
+ __setMissingFilesScanLimitForTests(null);
+ await engine.disconnect();
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ });
+
+ test('conversation_outcomes_stale: no stale outcome among the newest capped rows is unknown, not clear', async () => {
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('src-conv','src-conv')");
+ await engine.executeRaw(`INSERT INTO facts(source_id, source, fact, context, source_markdown_slug, kind)
+ SELECT 'src-conv', $1, 'EXTRACTION_COMPLETE', 'synthetic; extractor_version=' || $2::int, 'conversations/c-' || g, 'fact' FROM generate_series(1, $3::int) g`,
+ [TERMINAL_AUDIT_SOURCE, CONVERSATION_EXTRACTOR_VERSION, OUTCOME_SCAN_CAP + 1]);
+ const check = await conversationOutcomesStaleCheck(engine, ['src-conv']);
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ health: 'unknown', reason: 'bound', bound: 'rows', limit: OUTCOME_SCAN_CAP, exact: false, capped: true });
+ expect(check.message).toContain(`only the newest ${OUTCOME_SCAN_CAP} outcome rows were read`);
+ }, 60_000);
+
+ test('missing_recorded_files: a source read only up to the scan limit is unknown when clean, and a found page is a floor', async () => {
+ const dir = tmp('checkout');
+ mkdirSync(join(dir, 'notes'));
+ writeFileSync(join(dir, 'notes', 'kept.md'), '# kept\n');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('src-files','src-files',$1)", [dir]);
+ for (const path of ['notes/kept.md', 'blobs/b-1.bin', 'blobs/b-2.bin']) {
+ await engine.executeRaw("INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, source_path) VALUES('src-files', $1, 'note', 't', '', '', '{}'::jsonb, $2)",
+ [path.replace(/\.[a-z]+$/, ''), path]);
+ }
+ __setMissingFilesScanLimitForTests(2);
+ const run = async () => ((await missingRecordedFilesEntry.run({ engine, sourceIds: ['src-files'] } as unknown as DoctorContext)) as Check[])[0]!;
+ const clean = await run();
+ expect(clean.status).toBe('warn');
+ expect(clean.details).toMatchObject({ health: 'unknown', reason: 'bound', bound: 'rows', limit: 2, exact: false });
+ expect(clean.message).toContain('the scan stops at 2 live pages per source');
+ await engine.executeRaw("UPDATE pages SET source_path='notes/gone.md' WHERE source_id='src-files' AND slug='blobs/b-1'");
+ const found = await run();
+ expect(found.status).toBe('warn');
+ expect(found.details).toMatchObject({ count: 1, exact: false });
+ expect(found.message).toStartWith('At least 1 live page(s)');
+ }, 60_000);
+});