Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

doctor: failed or empty reads and unclassified candidates are health unknown, not a verdict (#7145)

garrytan84de6d1698f3
diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.ts
index 85e8aab982..7eb36c98f1 100644
--- a/src/commands/doctor/checks/content-quality.ts
+++ b/src/commands/doctor/checks/content-quality.ts
@@ -14,6 +14,7 @@ import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { agentFix, checkError, doctorVerify, withSkippedSegmented } from '../check-fix.ts';
import { scanDeadline } from '../budget.ts';
+import { boundUnknownDetails } from '../bounded-unknown.ts';
/** Oversized pages `oversized_pages` lists before it reports a floor. */
const OVERSIZED_LIST_LIMIT = 100;
@@ -448,6 +449,9 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {
checks.push({
name: 'frontmatter_integrity',
status: 'warn',
+ // #7145: a partial walk is a floor with health unknown past it, readable without parsing the message.
+ details: { count: report.total, partial: report.partial, exact: !report.partial,
+ ...(report.partial ? { ...boundUnknownDetails('time'), limit: fmTimeoutMs } : {}) },
message:
`${report.total} frontmatter issue(s)` +
(report.partial ? ` (PARTIAL SCAN — timeout after ${fmTimeoutMs / 1000}s)` : '') +
diff --git a/src/commands/doctor/checks/conversation-coverage.ts b/src/commands/doctor/checks/conversation-coverage.ts
index da9a0be82d..f9f9c730b5 100644
--- a/src/commands/doctor/checks/conversation-coverage.ts
+++ b/src/commands/doctor/checks/conversation-coverage.ts
@@ -14,6 +14,9 @@ import { ALLOWED_TYPES, isConversationFactsEligiblePage, requireParseableConvers
import type { Check } from '../../doctor.ts';
import { checkError } from '../check-fix.ts';
+/** Newest pages read per conversation type. */
+const TYPE_SAMPLE = 50;
+
export async function computeConversationFormatCoverageCheck(
engine: BrainEngine,
): Promise<Check> {
@@ -28,8 +31,10 @@ export async function computeConversationFormatCoverageCheck(
const sample: import('../../../core/types.ts').Page[] = [];
// #5330: sample only pages the extractor would claim.
const strict = await requireParseableConversationFlag(engine);
+ let capped = false;
for (const t of allowedTypes) {
- const slice = await engine.listPages({ limit: 50, type: t as import('../../../core/types.ts').PageType });
+ const slice = await engine.listPages({ limit: TYPE_SAMPLE, type: t as import('../../../core/types.ts').PageType });
+ if (slice.length >= TYPE_SAMPLE) capped = true;
sample.push(...slice.filter(page => isConversationFactsEligiblePage(page, allowedTypes, strict)));
}
if (sample.length === 0) {
@@ -66,6 +71,9 @@ export async function computeConversationFormatCoverageCheck(
if (result.phase === 'no_match') unmatched++;
}
const candidates = sample.length - summaryOnly - oversized;
+ // #7145: a sample is named as one, in the text and in details.
+ const sampleNote = capped ? ` (a sample of up to ${TYPE_SAMPLE} pages per conversation type)` : '';
+ const details = { sampled: sample.length, exact: !capped, ...(capped ? { bound: 'sample', limit: TYPE_SAMPLE } : {}) };
const unmatchedPct = candidates > 0 ? (unmatched / candidates) * 100 : 0;
const breakdown = Object.entries(hitsByPattern)
.sort(([, a], [, b]) => b - a)
@@ -76,15 +84,17 @@ export async function computeConversationFormatCoverageCheck(
name,
status: 'warn',
message:
- `${unmatched}/${candidates} transcript-bearing conversation pages (${unmatchedPct.toFixed(1)}%) match NO built-in pattern. ` +
+ `${unmatched}/${candidates} transcript-bearing conversation pages${sampleNote} (${unmatchedPct.toFixed(1)}%) match NO built-in pattern. ` +
`Breakdown: ${breakdown}. ` +
`Investigate: gbrain conversation-parser scan <slug>`,
+ details,
};
}
return {
name,
status: 'ok',
- message: `${sample.length} pages: ${breakdown}`,
+ message: `${sample.length} pages${sampleNote}: ${breakdown}`,
+ details,
};
} catch (err) {
return checkError(name, 'check conversation format coverage', err);
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 2e17e8f2aa..0ea4462d4f 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -253,6 +253,12 @@ function estimatedOrphanRatioCheck(est: OrphanEstimate, cutoff: number, srcId: s
const pct = (est.ratio * 100).toFixed(0);
const deep = ['gbrain', 'doctor', '--tier', 'deep', '--only', 'orphan_ratio', ...(srcId ? ['--source', srcId] : []), '--json'];
const details = { exact: false, estimated: true, ...est, full_scan_max_pages: cutoff, config_key: ORPHAN_FULL_SCAN_KEY, exact_command: deep.join(' ') };
+ // #7145: a sample with no linkable page estimated nothing; 0/0 is not 0%.
+ if (est.sample_linkable === 0) {
+ return { name: 'orphan_ratio', status: 'warn', details: { ...details, health: 'unknown', reason: 'empty_sample' },
+ message: `Orphan ratio unknown${srcId ? ` in source '${srcId}'` : ''}: the ${est.sample_pages}-page sample of ${est.live_pages} live pages held no linkable page. Exact figure: ${deep.join(' ')}.`,
+ fix: agentFix(deep, 'Read-only: the exact orphan ratio from the full scan.', 'orphan_ratio') };
+ }
const message = `Orphan ratio about ${pct}%${srcId ? ` in source '${srcId}'` : ''} (estimated: ${est.sample_orphans}/${est.sample_linkable} linkable pages in a `
+ `${est.sample_pages}-page sample of ${est.live_pages} live pages; the full scan runs above ${cutoff} pages only with --tier deep: ${deep.join(' ')}).`;
if (est.ratio <= 0.5) return { name: 'orphan_ratio', status: 'ok', message, details };
diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.ts
index a2501da087..6b90998ca6 100644
--- a/src/commands/doctor/checks/queue-jobs.ts
+++ b/src/commands/doctor/checks/queue-jobs.ts
@@ -8,6 +8,7 @@ import type { BrainEngine } from '../../../core/engine.ts';
import { resolveEnvNumber } from '../../../core/env-number.ts';
import type { Check } from '../../doctor.ts';
import { checkError, doctorVerify } from '../check-fix.ts';
+import { boundUnknownDetails } from '../bounded-unknown.ts';
import { queueWorkerAlive, runWaitingJobsFix } from '../../../core/minions/no-worker.ts';
/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */
@@ -574,7 +575,8 @@ export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Pro
EXTRACT(EPOCH FROM min(created_at)) * 1000 AS birth_epoch_ms
FROM minion_jobs
WHERE queue LIKE 'dream-inline-%'
- GROUP BY queue`,
+ GROUP BY queue
+ ORDER BY queue`,
);
// Live cycle locks with their acquisition time, for ownership correlation.
// Liveness matches db-lock's own model: an unexpired TTL, OR a lapsed TTL
@@ -675,6 +677,17 @@ export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Pro
flaggedWaiting += candidateWaiting[i];
}
const flagged = recoverable.length + legacyUnowned.length + ownerPending.length;
+ // #7145: candidates past the classification cap were not checked, so none flagged among the first is not clear.
+ if (flagged === 0 && truncatedCandidates > 0) {
+ return {
+ name: 'orphaned_private_queue',
+ status: 'warn',
+ message: `Orphaned private queues unknown: ${truncatedCandidates} candidate queue(s) were left unclassified past the ${CLASSIFY_CAP} classified per run (no setting); `
+ + `none of the ${CLASSIFY_CAP} classified is provably orphaned (${suppressedByLiveLock + suppressedByLiveLease} possibly owned by a live cycle).`,
+ details: { paused_jobs: pausedTotal, suppressed_by_live_lock: suppressedByLiveLock, suppressed_by_live_lease: suppressedByLiveLease,
+ unclassified_candidates: truncatedCandidates, ...boundUnknownDetails('rows'), limit: CLASSIFY_CAP },
+ };
+ }
if (flagged === 0) {
const suppressed = suppressedByLiveLock + suppressedByLiveLease;
return {
@@ -682,16 +695,14 @@ export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Pro
status: 'ok',
// Truncation must stay visible on the ok path too: 100 live + 50
// never-classified candidates is NOT a clean bill of health.
- message: suppressed > 0 || truncatedCandidates > 0
- ? `No provably-orphaned private queues (${suppressed} possibly owned by a live cycle` +
- (truncatedCandidates > 0 ? `, ${truncatedCandidates} unclassified — re-run doctor to page through them` : '') + `)`
+ message: suppressed > 0
+ ? `No provably-orphaned private queues (${suppressed} possibly owned by a live cycle)`
: 'No orphaned private queues',
- ...(pausedTotal > 0 || suppressed > 0 || truncatedCandidates > 0
+ ...(pausedTotal > 0 || suppressed > 0
? { details: {
paused_jobs: pausedTotal,
suppressed_by_live_lock: suppressedByLiveLock,
suppressed_by_live_lease: suppressedByLiveLease,
- ...(truncatedCandidates > 0 ? { unclassified_candidates: truncatedCandidates } : {}),
} }
: {}),
};
@@ -721,7 +732,8 @@ export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Pro
status: 'fail',
message:
`Orphaned private dream queue(s): ${[...recoverable, ...legacyUnowned, ...ownerPending].join('; ')}. ` +
- `A supervisor restart cannot consume these parent-owned queues. ${remediation.join(' ')}`,
+ `A supervisor restart cannot consume these parent-owned queues. ${remediation.join(' ')}`
+ + (truncatedCandidates > 0 ? ` ${truncatedCandidates} more candidate queue(s) past the ${CLASSIFY_CAP} classified per run were not checked.` : ''),
details: {
orphaned_private_queues: flagged,
recoverable_queues: recoverable.length,
diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.ts
index 22d4d2c935..b0508e4ccc 100644
--- a/src/core/onboard/checks.ts
+++ b/src/core/onboard/checks.ts
@@ -30,6 +30,7 @@ import { loadConfig } from '../config.ts';
import { MIN_ENTITY_PAGES_FOR_COVERAGE } from '../types.ts';
import { ORPHANED_ALIAS_COUNTS_SQL, SOFT_DELETED_ALIAS_COUNT_SQL } from '../repair/aliases.ts';
import { repairPreviewCommand } from '../repair/registry.ts';
+import { isUndefinedTableError } from '../utils.ts';
/** Shared shape returned by all four checks. */
export interface OnboardCheckResult {
@@ -161,7 +162,7 @@ async function sampleVisibleEntityCoverage(
sampleClause: string,
feature: CoverageFeature,
filter: EntityTypeFilter,
-): Promise<EntityCoverageSample> {
+): Promise<EntityCoverageSample | { error: string }> {
try {
const sql = visibleEntityCoverageSql(feature, filter, sampleClause);
const result = await engine.executeRaw(sql.text, sql.params);
@@ -175,11 +176,17 @@ async function sampleVisibleEntityCoverage(
// impossible percentages or feed a negative value into sqrt().
const matched = Math.min(sampleSize, finiteCount(row.matched));
return { matched, sampleSize };
- } catch {
- return { matched: 0, sampleSize: 0 };
+ } catch (error) {
+ return { error: redactConnectionInfo(error instanceof Error ? error.message : String(error)) };
}
}
+/** #7145: a coverage read that failed or sampled no row measured nothing, so it is not "0% coverage". */
+function unmeasuredCoverage(name: string, sample: EntityCoverageSample | { error: string }): OnboardCheckResult {
+ const why = 'error' in sample ? `the coverage read failed (${sample.error})` : 'the sampled read returned no entity page';
+ return { check: { name, status: 'warn', message: `Coverage unknown: ${why}; rerun doctor.`, details: { health: 'unknown', reason: 'error' in sample ? 'error' : 'empty_sample' } }, remediations: [] };
+}
+
function coverageWithConfidence(sample: EntityCoverageSample): { coverage: number; ci: number } {
const rawCoverage = sample.sampleSize > 0 ? sample.matched / sample.sampleSize : 0;
const coverage = Math.min(1, Math.max(0, rawCoverage));
@@ -341,6 +348,7 @@ export async function checkEntityLinkCoverage(
LINK_COVERAGE_FEATURE,
entityTypes.filter,
);
+ if ('error' in sample || sample.sampleSize === 0) return unmeasuredCoverage('entity_link_coverage', sample);
const { coverage, ci } = coverageWithConfidence(sample);
const pct = Math.round(coverage * 100);
@@ -422,6 +430,7 @@ export async function checkTimelineCoverage(
TIMELINE_COVERAGE_FEATURE,
entityTypes.filter,
);
+ if ('error' in sample || sample.sampleSize === 0) return unmeasuredCoverage('timeline_coverage', sample);
const { coverage, ci } = coverageWithConfidence(sample);
const pct = Math.round(coverage * 100);
const ciPct = (ci * 100).toFixed(1);
@@ -746,7 +755,13 @@ export async function checkDanglingAliases(
orphaned = await engine.executeRaw(ORPHANED_ALIAS_COUNTS_SQL);
const [row] = await engine.executeRaw<typeof soft>(SOFT_DELETED_ALIAS_COUNT_SQL);
if (row) soft = row;
- } catch { /* pre-v105 brain or unreadable alias tables: nothing to report */ }
+ } catch (error) {
+ // #7145: only a pre-v105 brain (no alias tables) has nothing to report; any other failure is unknown, not clear.
+ if (!isUndefinedTableError(error)) {
+ return { check: { name: 'dangling_aliases', status: 'warn', details: { health: 'unknown' },
+ message: `Dangling aliases unknown: the alias read failed (${redactConnectionInfo(error instanceof Error ? error.message : String(error))}); rerun doctor.` }, remediations: [] };
+ }
+ }
const slugAliases = orphaned.reduce((sum, row) => sum + Number(row.slug_redirects), 0) + Number(soft.slug_redirects);
const pageAliases = orphaned.reduce((sum, row) => sum + Number(row.page_aliases), 0) + Number(soft.page_aliases);
const n = slugAliases + pageAliases;
diff --git a/test/doctor-unknown-reads-7145.test.ts b/test/doctor-unknown-reads-7145.test.ts
new file mode 100644
index 0000000000..80ba98ef34
--- /dev/null
+++ b/test/doctor-unknown-reads-7145.test.ts
@@ -0,0 +1,96 @@
+/**
+ * #7145: a doctor read that failed, sampled nothing, or stopped at its bound measured nothing, so it reports health
+ * unknown (warn) instead of a known verdict: coverage, dangling aliases, the estimated orphan ratio. A sample is named
+ * as one (conversation_format_coverage), and a partial frontmatter walk carries its bound in details. PGLite in-memory.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { checkDanglingAliases, checkEntityLinkCoverage, checkTimelineCoverage } from '../src/core/onboard/checks.ts';
+import { orphanRatioEntry } from '../src/commands/doctor/checks/graph-health.ts';
+import { computeConversationFormatCoverageCheck } from '../src/commands/doctor/checks/conversation-coverage.ts';
+import { frontmatterEntry } from '../src/commands/doctor/checks/content-quality.ts';
+import { buildQuarantineMarker } from '../src/core/quarantine.ts';
+import { MIN_ENTITY_PAGES_FOR_COVERAGE } from '../src/core/types.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const progress = new Proxy({}, { get: () => () => undefined });
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+/** The engine with every statement matching `match` failing the way a cancelled statement does. */
+function failing(match: RegExp): BrainEngine {
+ return new Proxy(engine, { get(target, key) {
+ const value = Reflect.get(target, key);
+ if (key !== 'executeRaw') return typeof value === 'function' ? value.bind(target) : value;
+ return (sql: string, params?: unknown[]) => match.test(sql)
+ ? Promise.reject(Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' }))
+ : target.executeRaw(sql, params);
+ } }) as BrainEngine;
+}
+
+describe('#7145 unknown reads', () => {
+ test('coverage whose read failed is unknown, not 0% with a remediation', async () => {
+ for (let n = 1; n <= MIN_ENTITY_PAGES_FOR_COVERAGE; n++) {
+ await engine.putPage(`people/example-${n}`, { type: 'person', title: `Example ${n}`, compiled_truth: 'A synthetic entity.', timeline: '' });
+ }
+ const broken = failing(/sample_size/);
+ for (const run of [checkEntityLinkCoverage, checkTimelineCoverage]) {
+ const result = await run(broken);
+ expect(result.check).toMatchObject({ status: 'warn', details: { health: 'unknown', reason: 'error' } });
+ expect(result.check.message).toContain('Coverage unknown');
+ expect(result.remediations).toEqual([]);
+ }
+ });
+
+ test('dangling_aliases whose read failed is unknown, not clear', async () => {
+ const result = await checkDanglingAliases(failing(/slug_aliases|page_aliases|slug_redirects/));
+ expect(result.check).toMatchObject({ name: 'dangling_aliases', status: 'warn', details: { health: 'unknown' } });
+ expect(result.check.message).toContain('Dangling aliases unknown');
+ });
+
+ test('an estimated orphan ratio whose sample held no linkable page is unknown, not 0%', async () => {
+ const source = 'orphan-src';
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES($1,$1)", [source]);
+ for (const n of [1, 2]) {
+ await engine.putPage(`people/hidden-${n}`, { type: 'person', title: `Hidden ${n}`, compiled_truth: 'Quarantined.', timeline: '',
+ frontmatter: { quarantine: buildQuarantineMarker('junk_pattern', 'synthetic fixture') } }, { sourceId: source });
+ }
+ await engine.setConfig('doctor.orphan_ratio.full_scan_max_pages', '1');
+ try {
+ const [check] = await orphanRatioEntry.run({ engine, progress, tier: 'standard', orphanRatioSourceId: source } as never) as Array<Record<string, any>>;
+ expect(check).toMatchObject({ name: 'orphan_ratio', status: 'warn', details: { health: 'unknown', reason: 'empty_sample', sample_linkable: 0 } });
+ expect(check.message).toContain('Orphan ratio unknown');
+ } finally { await engine.unsetConfig('doctor.orphan_ratio.full_scan_max_pages'); }
+ });
+
+ test('conversation_format_coverage names a capped sample as one', async () => {
+ await engine.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth)
+ SELECT 'conversations/example-' || i, 'conversation', 'Example ' || i, 'Alice: hello' || chr(10) || 'Bob: hi' FROM generate_series(1, 50) i`);
+ const check = await computeConversationFormatCoverageCheck(engine);
+ expect(check.details).toMatchObject({ exact: false, bound: 'sample', limit: 50 });
+ expect(check.message).toContain('a sample of up to 50 pages per conversation type');
+ });
+
+ test('a partial frontmatter walk carries its time bound in details', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-7145-fm-'));
+ try {
+ for (let n = 0; n < 400; n++) {
+ mkdirSync(join(dir, `d${n % 20}`), { recursive: true });
+ writeFileSync(join(dir, `d${n % 20}`, `note-${n}.md`), '---\ntitle: [unclosed\n---\nBody.\n');
+ }
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('fm-src','fm-src',$1)", [dir]);
+ await withEnv({ GBRAIN_DOCTOR_FM_TIMEOUT_MS: '1' }, async () => {
+ const [check] = (await frontmatterEntry.run({ engine, progress, args: [] } as never) as Array<Record<string, any>>).filter(c => c.name === 'frontmatter_integrity');
+ expect(check).toMatchObject({ status: 'warn', details: { partial: true, exact: false, health: 'unknown', reason: 'bound', bound: 'time' } });
+ });
+ } finally {
+ await engine.executeRaw("DELETE FROM sources WHERE id = 'fm-src'");
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.ts
index 6b4e9deced..1e29aad4c3 100644
--- a/test/doctor-wedged-queue.test.ts
+++ b/test/doctor-wedged-queue.test.ts
@@ -471,8 +471,8 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-only
it('ok-path truncation honesty: 100 live + 1 never-classified is NOT a clean bill of health', async () => {
// First 100 candidates classify 'live' (future lease + fresh updated_at);
- // the 101st never gets classified. Status stays ok but the message and
- // details must still surface the unclassified remainder.
+ // the 101st never gets classified. #7145: that is health unknown (warn),
+ // and the message and details still surface the unclassified remainder.
await base.executeRaw(
`INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_lease_until)
SELECT '{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-live-' || i, 'waiting',
@@ -480,7 +480,8 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-only
FROM generate_series(1, 101) AS i`,
);
const check = await computeOrphanedPrivateQueueCheck(pgLike);
- expect(check.status).toBe('ok');
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ health: 'unknown', reason: 'bound', bound: 'rows', limit: 100 });
expect(check.message).toContain('unclassified');
expect((check.details as any).unclassified_candidates).toBe(1);
expect((check.details as any).suppressed_by_live_lease).toBe(100);