Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): preserve fence publication on cache mirror errors
garrytan9638c3c2d4e3
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex 45a04ed16a..e2b69e4b1c 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -63,7 +63,7 @@ import type { TaintInput, WriteTrust } from '../trust/tier.ts';import { gitChildEnv } from '../git-env.ts';import { urlCloneReadOnly } from '../url-clone.ts';import { bodyUnread } from '../page-body/page-shape.ts';-import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';+import { bestEffortStoredBodyMirror, fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';/** Resolved source binding for the entity page. */export interface FenceTarget {@@ -580,7 +580,9 @@ export async function writeFactsToFence(const result = await maintenanceTransaction(engine, async tx => {if (fileBefore === null ? existsSync(filePath) : !existsSync(filePath) || readFileSync(filePath, 'utf-8') !== fileBefore) return null;- if (stored && !await withPageTierKept(tx, target, () => mirrorFileBody(tx, target.sourceId, target.slug, tmpBody, stored))) return null;+ if (stored && !await bestEffortStoredBodyMirror(tx, target.sourceId, target.slug, stored,+ savepoint => withPageTierKept(savepoint, target, () => mirrorFileBody(savepoint, target.sourceId, target.slug, tmpBody, stored)),+ err => console.warn(`[facts.fence] FACTS_PAGE_MIRROR_FAILED: ${target.slug} (source ${target.sourceId}): ${err instanceof Error ? err.message : String(err)}; page cache stale until gbrain sync --source ${target.sourceId}`))) return null;if (!stored && await readStoredBody(tx, target.sourceId, target.slug, true)) return null;const inserted = await insertFenceRows(tx, target.sourceId, enriched, facts, derivation);if (fileBefore === null ? existsSync(filePath) : !existsSync(filePath) || readFileSync(filePath, 'utf-8') !== fileBefore) {diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.tsindex 521953d373..e8c013c143 100644--- a/src/core/facts/file-body-guard.ts+++ b/src/core/facts/file-body-guard.ts@@ -16,6 +16,7 @@ import { sanitizeText } from '../batch-rows.ts';import { parseMarkdown, parseMarkdownHead } from '../markdown.ts';import { contentHash, contentHashFrontmatterAndTags } from '../utils.ts';import { stableJson } from '../persistence/digest.ts';+import { classifyItemFailure } from '../item-failure.ts';export interface StoredBody {compiled_truth: string | null;@@ -51,6 +52,27 @@ export async function readStoredBody(engine: BrainEngine, sourceId: string, slugreturn row ?? null;}+async function storedBodyUnchanged(tx: BrainEngine, sourceId: string, slug: string, expected: StoredBody): Promise<boolean> {+ const current = await readStoredBody(tx, sourceId, slug, true);+ return current !== null && current.compiled_truth === expected.compiled_truth && current.timeline === expected.timeline;+}++/**+ * Keep the preimage lock in the publication transaction while isolating a best-effort cache mirror in a savepoint.+ * False holds publication on drift. An unexpected mirror failure rolls back only the cache attempt and reports it;+ * publication may continue under the retained lock. Run-scoped failures still abort the publication transaction.+ */+export async function bestEffortStoredBodyMirror(tx: BrainEngine, sourceId: string, slug: string, expected: StoredBody,+ mirror: (savepoint: BrainEngine) => Promise<boolean>, onFailure: (err: unknown) => void): Promise<boolean> {+ if (!await storedBodyUnchanged(tx, sourceId, slug, expected)) return false;+ try { return await tx.transaction(mirror); }+ catch (err) {+ if (classifyItemFailure(err).scope === 'run') throw err;+ onFailure(err);+ return true;+ }+}+/*** Inside `tx`: lock the page, and when its stored body is still `expected` (the body the caller compared before* planning), keep it in page_versions and store `next`. The row keeps its content_hash unless `hash` is given.@@ -58,8 +80,7 @@ export async function readStoredBody(engine: BrainEngine, sourceId: string, slug*/export async function replaceStoredBody(tx: BrainEngine, sourceId: string, slug: string, next: { compiled_truth: string; timeline: string },expected: StoredBody, hash?: string): Promise<boolean> {- const current = await readStoredBody(tx, sourceId, slug, true);- if (!current || current.compiled_truth !== expected.compiled_truth || current.timeline !== expected.timeline) return false;+ if (!await storedBodyUnchanged(tx, sourceId, slug, expected)) return false;const page = await tx.getPage(slug, { sourceId });if (!page) return false;await tx.createVersion(slug, { sourceId });diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex b289370f7c..af11556e2e 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -27,7 +27,7 @@ import { maintenanceTransaction } from '../persistence/attribution.ts';import { markBeliefCommits } from '../belief/append.ts';import { classifyItemFailure } from '../item-failure.ts';import { withdrawnFact } from './withdrawal-overlay.ts';-import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';+import { bestEffortStoredBodyMirror, fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';export interface ForgetFactResult {/** True iff the row was found AND a forget was applied (fence or DB). */@@ -310,7 +310,11 @@ export async function forgetFactInFence(if (!segmented) {const written = await maintenanceTransaction(engine, async tx => {if (!existsSync(filePath) || readFileSync(filePath, 'utf-8') !== body) return false;- if (stored ? !await mirrorFileBody(tx, row.source_id, slug, tmpBody, stored) : await readStoredBody(tx, row.source_id, slug, true)) return false;+ if (stored ? !await bestEffortStoredBodyMirror(tx, row.source_id, slug, stored,+ savepoint => mirrorFileBody(savepoint, row.source_id, slug, tmpBody, stored), err => {+ mirrorWarning = `FACTS_PAGE_MIRROR_FAILED: ${slug} (source ${row.source_id}): ${err instanceof Error ? err.message : String(err)}; page cache stale until gbrain sync --source ${row.source_id}`;+ console.warn(`[facts.forget] ${mirrorWarning}`);+ }) : await readStoredBody(tx, row.source_id, slug, true)) return false;if (!existsSync(filePath) || readFileSync(filePath, 'utf-8') !== body) throw new WithdrawalFileChanged();assertSourceFilesystemActive();renameSync(tmpPath, filePath);@@ -323,7 +327,7 @@ export async function forgetFactInFence(rmSync(tmpPath, { force: true });return held('during');}- return { ok: true, path: 'fence', reason };+ return { ok: true, path: 'fence', reason, ...(mirrorWarning ? { warning: mirrorWarning } : {}) };}renameSync(tmpPath, filePath);diff --git a/test/pathological/facts-mirror-failures.test.ts b/test/pathological/facts-mirror-failures.test.tsnew file mode 100644index 0000000000..3d5b14bcad--- /dev/null+++ b/test/pathological/facts-mirror-failures.test.ts@@ -0,0 +1,102 @@+/**+ * B-21 / D-2 / D-3: a failed cache mirror does not discard an otherwise safe fence publication.+ * Protects: file/fact publication survives unexpected mirror failures, including real SQL errors and errors after+ * a body update; the failed mirror and its history roll back. Drift still holds publication, and run errors throw.+ * Fails when: the mirror shares the publication transaction without a savepoint, or its failure bypasses drift checks.+ * Existing B-21 coverage pins the warning and inserted count on PGLite, not rollback, file bytes or Postgres recovery.+ * Seams: transaction-preserving engine proxy injects refreshPageBody failures; real isolated PGLite/Postgres engines.+ */+import { describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { forgetFactInFence } from '../../src/core/facts/forget.ts';+import { parseFactsFence } from '../../src/core/facts-fence.ts';+import { CLAIM, EDIT, SLUG, withFactsBrain } from './facts-overwrite-fixture.ts';+import { pathologicalArms, runScopedErrors } from './harness.ts';++function brokenMirror(engine: BrainEngine, fail: (tx: BrainEngine, args: Parameters<BrainEngine['refreshPageBody']>) => Promise<never>, afterInsert?: () => Promise<void>): BrainEngine {+ const wrap = (base: BrainEngine): BrainEngine => new Proxy(base, { get(target, prop) {+ if (prop === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>, opts?: Parameters<BrainEngine['transaction']>[1]) =>+ target.transaction(tx => run(wrap(tx)), opts);+ if (prop === 'refreshPageBody') return (...args: Parameters<BrainEngine['refreshPageBody']>) => fail(target, args);+ if (prop === 'insertFacts' && afterInsert) return async (...args: Parameters<BrainEngine['insertFacts']>) => {+ const result = await target.insertFacts(...args);+ await afterInsert();+ return result;+ };+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+ return wrap(engine);+}++for (const { backend, databaseUrl } of pathologicalArms()) describe(`best-effort facts mirror (${backend})`, () => {+ if (backend === 'postgres') test('the preimage row lock survives rollback of the failed mirror savepoint', async () => {+ await withFactsBrain(databaseUrl, async b => {+ const before = await b.body();+ let checked = false;+ const broken = brokenMirror(b.engine, async () => { throw new Error('mirror write failed'); }, async () => {+ checked = true;+ await expect(b.engine.transaction(async other => {+ await other.executeRaw("SET LOCAL lock_timeout = '100ms'");+ await other.executeRaw("UPDATE pages SET compiled_truth = compiled_truth || $2 WHERE source_id = 'default' AND slug = $1", [SLUG, EDIT]);+ })).rejects.toMatchObject({ code: '55P03' });+ });+ expect((await b.append(broken)).inserted).toBe(1);+ expect(checked).toBe(true);+ expect(await b.body()).toBe(before);+ expect(parseFactsFence(b.bytes()).facts.map(f => f.claim)).toEqual([CLAIM]);+ });+ }, 180_000);++ for (const writer of ['append', 'forget'] as const) {+ for (const failure of ['before', 'after', 'sql'] as const) test(`${writer}: ${failure} mirror failure keeps the canonical fence and fact publication`, async () => {+ await withFactsBrain(databaseUrl, async b => {+ const id = writer === 'forget' ? (await b.append()).ids[0]! : null;+ const before = { body: await b.body(), versions: await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id') };+ const broken = brokenMirror(b.engine, async (tx, args) => {+ if (failure === 'after') await tx.refreshPageBody(...args);+ if (failure === 'sql') await tx.executeRaw("SELECT 'mirror write failed'::integer");+ throw new Error('mirror write failed');+ });+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ if (writer === 'append') expect(await b.append(broken)).toMatchObject({ inserted: 1 });+ else expect(await forgetFactInFence(broken, id!)).toMatchObject({ ok: true, path: 'fence' });+ expect(parseFactsFence(b.bytes()).facts.map(f => ({ claim: f.claim, active: f.active })))+ .toEqual([{ claim: CLAIM, active: writer === 'append' }]);+ expect(await b.engine.executeRaw('SELECT fact FROM facts WHERE expired_at IS NULL'))+ .toEqual(writer === 'append' ? [{ fact: CLAIM }] : []);+ expect(await b.body()).toBe(before.body);+ expect(await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id')).toEqual(before.versions);+ expect(warn.mock.calls.some(c => String(c[0]).includes('FACTS_PAGE_MIRROR_FAILED') && String(c[0]).includes('mirror write failed'))).toBe(true);+ } finally { warn.mockRestore(); }+ });+ }, 180_000);++ test(`${writer}: an editor save during a failed mirror still holds publication`, async () => {+ await withFactsBrain(databaseUrl, async b => {+ const id = writer === 'forget' ? (await b.append()).ids[0]! : null;+ const before = { file: b.bytes(), body: await b.body(), versions: await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id') };+ const broken = brokenMirror(b.engine, async () => { b.fileEdit(); throw new Error('mirror write failed'); });+ const result = writer === 'append' ? await b.append(broken) : await forgetFactInFence(broken, id!);+ expect(result.warning).toContain(`${SLUG} (file_database_drift`);+ expect(result).toMatchObject(writer === 'append' ? { inserted: 0, legacyFallback: true } : { ok: true, path: 'legacy_db' });+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: before.file + EDIT, body: before.body });+ expect(await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id')).toEqual(before.versions);+ expect(await b.engine.executeRaw('SELECT fact FROM facts WHERE expired_at IS NULL')).toEqual([]);+ });+ }, 180_000);++ test(`${writer}: run-scoped mirror failures still throw without publishing`, async () => {+ for (const fault of runScopedErrors()) await withFactsBrain(databaseUrl, async b => {+ const id = writer === 'forget' ? (await b.append()).ids[0]! : null;+ const before = { file: b.bytes(), body: await b.body(), versions: await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id') };+ const broken = brokenMirror(b.engine, async () => { throw fault.error(); });+ await expect(writer === 'append' ? b.append(broken) : forgetFactInFence(broken, id!)).rejects.toThrow();+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: before.file, body: before.body });+ expect(await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id')).toEqual(before.versions);+ expect(await b.engine.executeRaw('SELECT fact FROM facts WHERE expired_at IS NULL')).toEqual([]);+ });+ }, 180_000);+ }+});