Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
doctor maintenance_write_drift: read receipts older than the window under a time bound and report unchecked candidates as unknown (#7145)
garrytan716d169044d0
diff --git a/src/commands/doctor/checks/maintenance-drift.ts b/src/commands/doctor/checks/maintenance-drift.tsindex ce3053b554..3072336f59 100644--- a/src/commands/doctor/checks/maintenance-drift.ts+++ b/src/commands/doctor/checks/maintenance-drift.ts@@ -6,11 +6,15 @@ import { auditConflictsCommand, FILE_DRIFT_MESSAGE, fileDriftRepairCommand, liveimport { existingLocalHostId } from '../../../core/persistence/identity.ts';import { isKeepDbSlug } from '../../../core/storage-config.ts';import { keepDbReceiptCost, readKeepDbPolicy } from '../../../core/repair/keep-db-policy.ts';+import { isStatementTimeout } from '../../../core/persistence/bounded-reads.ts';+import { boundUnknownDetails } from '../bounded-unknown.ts';/** Newest request sequences scanned for drift conflicts (one range read of the unique sequence index). */const WINDOW = 20_000;/** Distinct slugs checked live per source; the rest are reported as unchecked. */const LIVE_LIMIT = 100;+/** #7145: time the read of drift receipts older than the window may take before the check reports them unread. */+const OLDER_READ_MS = 3_000;/*** #6643 (B3): pages whose canonical file differs from the database right now,@@ -38,33 +42,57 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?const rows = [];const policies = [];const suppressed: SuppressedWrite[] = [];+ let unchecked = 0;+ const olderUnread: string[] = [];+ const receiptFilter = `r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3`;for (const sourceId of sources) {suppressed.push(...await listSuppressedWrites(engine, sourceId));- const candidates = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests r- WHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3- ORDER BY r.slug LIMIT ${LIVE_LIMIT + 1}`, [sourceId, floor, FILE_DRIFT_MESSAGE]);+ const recent = await engine.executeRaw<{ slug: string; total: number }>(`SELECT slug, count(*) OVER ()::int AS total FROM (+ SELECT DISTINCT r.slug FROM persistence_requests r WHERE r.sequence > $2::bigint AND ${receiptFilter}) d+ ORDER BY slug LIMIT ${LIVE_LIMIT}`, [sourceId, floor, FILE_DRIFT_MESSAGE]);+ // #7145: a drifted page stops adding receipts, so its only receipts can sit below the window; read them under a time bound.+ let older: Array<{ slug: string }> = [];+ if (floor !== '0') {+ try {+ older = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests r WHERE r.sequence <= $2::bigint AND ${receiptFilter}+ ORDER BY r.slug LIMIT ${LIVE_LIMIT + 1}`, [sourceId, floor, FILE_DRIFT_MESSAGE], { timeoutMs: OLDER_READ_MS });+ } catch (error) {+ if (!isStatementTimeout(error)) throw error;+ olderUnread.push(sourceId);+ }+ }+ const candidates = new Set([...recent.map(row => row.slug), ...older.map(row => row.slug)]);+ const candidateCount = Math.max(candidates.size, recent[0]?.total ?? 0) + (older.length > LIVE_LIMIT ? 1 : 0);const skipped = Object.keys(skips).filter(key => key.startsWith(`${sourceId}:`)).map(key => key.slice(sourceId.length + 1));const drifted = new Set<string>();let unknown = 0;- for (const slug of [...new Set([...candidates.slice(0, LIVE_LIMIT).map(row => row.slug), ...skipped])].slice(0, LIVE_LIMIT)) {- const live = await liveFileDrift(engine, sourceId, slug);- if (live.still_present === true) drifted.add(slug);- else if (live.still_present === null) unknown++;+ const live = [...new Set([...candidates, ...skipped])];+ for (const slug of live.slice(0, LIVE_LIMIT)) {+ const state = await liveFileDrift(engine, sourceId, slug);+ if (state.still_present === true) drifted.add(slug);+ else if (state.still_present === null) unknown++;}- const unchecked = Math.max(0, candidates.length - LIVE_LIMIT);- if (drifted.size || skipped.length || unknown) rows.push({ source_id: sourceId, drifted: drifted.size, sample: [...drifted].slice(0, 5),- concept_skips: skipped.length, unknown, unchecked });+ const sourceUnchecked = Math.max(0, candidateCount - LIVE_LIMIT, live.length - LIVE_LIMIT);+ unchecked += sourceUnchecked;+ if (drifted.size || skipped.length || unknown || sourceUnchecked) rows.push({ source_id: sourceId, drifted: drifted.size, sample: [...drifted].slice(0, 5),+ concept_skips: skipped.length, unknown, unchecked: sourceUnchecked });try {const policy = await readKeepDbPolicy(engine, sourceId, hostId);const matched = policy ? [...drifted].filter(slug => isKeepDbSlug(slug, policy.keep_db)).length : 0;- if (policy) policies.push({ ...policy, matched, unchecked, receipt_cost: keepDbReceiptCost(matched) });+ if (policy) policies.push({ ...policy, matched, unchecked: sourceUnchecked, receipt_cost: keepDbReceiptCost(matched) });} catch (error) {policies.push({ source_id: sourceId, error: error instanceof Error ? error.message : String(error) });}}const count = rows.reduce((sum, row) => sum + row.drifted, 0);const skipCount = rows.reduce((sum, row) => sum + row.concept_skips, 0);- const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, suppressed, ...(policies.length ? { keep_db_policy: policies } : {}) };+ const bounded = unchecked > 0 || olderUnread.length > 0;+ const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, suppressed, ...(policies.length ? { keep_db_policy: policies } : {}),+ ...(bounded ? { exact: false, unchecked, live_limit: LIVE_LIMIT, older_unread_sources: olderUnread, older_read_ms: OLDER_READ_MS } : {}) };+ const auditSource = rows.find(row => row.unchecked)?.source_id ?? olderUnread[0] ?? sources[0];+ const boundNote = !bounded ? '' : ` Not every candidate was checked: ${[unchecked ? `${unchecked} slug(s) past the ${LIVE_LIMIT} checked live per source` : '',+ olderUnread.length ? `receipts older than the newest ${WINDOW} request sequences in ${olderUnread.join(', ')} were not read within ${OLDER_READ_MS} ms` : ''].filter(Boolean).join('; ')} (no setting). `+ + `Page through every slug with its live state: ${auditConflictsCommand(auditSource ?? '<id>')} --window 1000000.`;const policyNote = policies.map(policy => 'error' in policy ? ` storage.keep_db of ${policy.source_id} could not be read: ${policy.error}`: ` storage.keep_db of ${policy.source_id} (${policy.keep_db.join(', ')}) matches ${policy.matched} of them${policy.unchecked ? ` (${policy.unchecked} more not checked here)` : ''}; `+ `the owner host's managed sync reconciles those whose file is clean and committed with the database copy, one request each (${policy.receipt_cost.lifetime_ids} lifetime id(s), ${policy.receipt_cost.receipt_bytes} receipt bytes).`).join('');@@ -72,9 +100,15 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?return { name: 'maintenance_write_drift', status: 'warn', details,message: `${suppressed.length} maintenance write(s) are held back after repeated identical refusals (#6696), so they stop adding receipts: `+ `${suppressed.slice(0, 5).map(row => `${row.source_id}:${row.slug} ${row.error_code} x${row.refusals}${row.cause ? ` (${row.cause})` : ''} -> ${row.exit}`).join('; ')}. `- + 'Each is tried again once its page, planner or write changes, or after a day.',+ + `Each is tried again once its page, planner or write changes, or after a day.${boundNote}`,fix: agentFix(['gbrain', 'write-request', '--', suppressed[0]!.last_request_id], 'Read-only: the last refused attempt and what it names.', 'maintenance_write_drift', { docs }) };}+ if (!count && !skipCount && bounded) {+ return { name: 'maintenance_write_drift', status: 'warn', details: { ...details, ...boundUnknownDetails(unchecked ? 'rows' : 'time'), limit: unchecked ? LIVE_LIMIT : OLDER_READ_MS },+ message: `Maintenance write drift unknown: no page checked has a canonical file that differs from the database, but the check stopped at its bound.${boundNote}`,+ fix: agentFix(['gbrain', 'sources', 'reconcile', auditSource!, '--brain', 'host', '--audit', '--conflicts', '--window', '1000000', '--json'],+ 'Read-only: pages through the conflict receipts grouped by slug, with whether each file still differs.', 'maintenance_write_drift', { docs }) };+ }if (!count && !skipCount) {const unknown = rows.reduce((sum, row) => sum + row.unknown, 0);return { name: 'maintenance_write_drift', status: 'ok', details,@@ -83,9 +117,9 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?}const first = rows.find(row => row.drifted || row.concept_skips)!.source_id;return { name: 'maintenance_write_drift', status: 'warn', details,- message: `${count} page(s) have a canonical file that differs from the database, so every coordinated write to them refuses source_changed `+ message: `${bounded ? 'At least ' : ''}${count} page(s) have a canonical file that differs from the database, so every coordinated write to them refuses source_changed `+ `(${rows.filter(row => row.drifted || row.concept_skips).map(row => `${row.source_id}: ${row.drifted} drifted, ${row.concept_skips} concept skip(s)`).join('; ')}). `- + `Maintenance now skips them before spending or admitting anything. List them: ${auditConflictsCommand(first)}; preview the resolution: ${fileDriftRepairCommand(first)} (or --prefer database), then apply with the --expect hash it prints.${policyNote}`,+ + `Maintenance now skips them before spending or admitting anything. List them: ${auditConflictsCommand(first)}; preview the resolution: ${fileDriftRepairCommand(first)} (or --prefer database), then apply with the --expect hash it prints.${policyNote}${boundNote}`,fix: agentFix(['gbrain', 'sources', 'reconcile', first, '--brain', 'host', '--audit', '--conflicts', '--json'],'Read-only: lists the conflict receipts grouped by slug, whether each file still differs, its drift class and producer.', 'maintenance_write_drift', { docs }) };} catch (error) {diff --git a/test/maintenance-file-drift-6643.test.ts b/test/maintenance-file-drift-6643.test.tsindex 0a3ff6812c..0f72586d66 100644--- a/test/maintenance-file-drift-6643.test.ts+++ b/test/maintenance-file-drift-6643.test.ts@@ -313,6 +313,41 @@ for (const backend of testBackends()) describe(`#6643 maintenance file drift (${expect((await liveFileDrift(engine, sourceId, 'notes/two')).still_present).toBe(true);await expect(apply()).rejects.toMatchObject({ code: 'preview_changed' });}), 240_000);++ /** #7145: moves the request sequence past the doctor window, so every receipt written so far is older than it. */+ const pastWindow = async (ctx: OperationContext, slug: string) => {+ await engine.executeRaw(`SELECT setval(pg_get_serial_sequence('persistence_requests','sequence'), (SELECT max(sequence) FROM persistence_requests) + 30000)`);+ await put(ctx, slug, '---\ntype: note\ntitle: Later\n---\nA later write.\n');+ };++ test('#7145: a drifted page whose only receipt is older than the doctor window is still reported', () => fixture(async ({ root, sourceId, ctx }) => {+ await put(ctx, 'notes/alpha', '---\ntype: note\ntitle: Alpha\n---\nAlpha.\n');+ drift(root, 'notes/alpha', text => `${text}\nEdited in the file only.\n`);+ await refusedWrite(ctx, 'notes/alpha', 'One.');+ await pastWindow(ctx, 'notes/later');+ const doctor = await maintenanceWriteDriftCheck(engine, [sourceId]);+ expect(doctor).toMatchObject({ name: 'maintenance_write_drift', status: 'warn', details: { count: 1 } });+ expect(doctor.details!.sources).toEqual([expect.objectContaining({ source_id: sourceId, drifted: 1, unchecked: 0 })]);+ }), 240_000);++ test('#7145: candidates past the live-check limit make a clear result unknown, not ok', () => fixture(async ({ root, sourceId, ctx }) => {+ await put(ctx, 'notes/alpha', '---\ntype: note\ntitle: Alpha\n---\nAlpha.\n');+ const original = readFileSync(join(root, 'notes/alpha.md'), 'utf8');+ drift(root, 'notes/alpha', text => `${text}\nEdited in the file only.\n`);+ await refusedWrite(ctx, 'notes/alpha', 'One.');+ writeFileSync(join(root, 'notes/alpha.md'), original);+ await engine.executeRaw(`INSERT INTO persistence_requests (principal_kind, principal_id, request_id, operation, source_id, source_incarnation, slug, digest, authority,+ state, intent_bytes, terminal_reservation, error_code, error_message)+ SELECT r.principal_kind, r.principal_id, gen_random_uuid(), r.operation, r.source_id, r.source_incarnation, 'notes/zz-' || lpad(n::text, 3, '0'), r.digest, r.authority,+ r.state, r.intent_bytes, r.terminal_reservation, r.error_code, r.error_message+ FROM persistence_requests r, generate_series(1, 105) n WHERE r.source_id=$1 AND r.state='conflict' AND r.slug='notes/alpha'`, [sourceId]);+ const doctor = await maintenanceWriteDriftCheck(engine, [sourceId]);+ expect(doctor).toMatchObject({ name: 'maintenance_write_drift', status: 'warn',+ details: { count: 0, exact: false, health: 'unknown', reason: 'bound', bound: 'rows', limit: 100 } });+ expect(doctor.details!.unchecked).toBeGreaterThan(0);+ expect(doctor.message).toContain('Maintenance write drift unknown');+ expect(doctor.message).toContain('--window 1000000');+ }), 240_000);});describe('#6643 file-drift pure rules', () => {