Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract_facts): one refused deleted-page expiry no longer fails the phase (GBRA-130 A-21)

garrytan18f65780a7aa
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 0844041c40..6305a33ae3 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -70,6 +70,7 @@ import { resolveManagedFactsEmbedding } from '../persistence/facts-maintenance.t
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';
import { opError, OperationError } from '../ops/contract.ts';
+import { ItemRun } from '../item-failure.ts';
import {
resolveSupersededByRow,
supersessionChainOf,
@@ -897,7 +898,7 @@ export async function runExtractFacts(
// Managed: one receipted request per page, rechecked under its key, so a
// concurrent restore is either seen as restored or waited for, never
// expired underneath it.
- const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, managedAuthority) : await maintenanceTransaction(engine, expireDeleted);
+ const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, managedAuthority, result.warnings) : await maintenanceTransaction(engine, expireDeleted);
result.factsExpiredForDeletedPages = expired.length;
}
@@ -1112,8 +1113,12 @@ export async function runExtractFacts(
return result;
}
+/**
+ * A refused page never stops the expiry or the reconcile after it (GBRA-130 A-21): it is a
+ * FACTS_EXPIRE_FAILED warning retried by the next run; a page the refusal breaker holds back is skipped.
+ */
async function expireDeletedPagesManaged(engine: BrainEngine, sourceId: string,
- managedAuthority: () => Promise<MaintenanceAuthority | null>): Promise<Array<{ id: number }>> {
+ managedAuthority: () => Promise<MaintenanceAuthority | null>, warnings: string[]): Promise<Array<{ id: number }>> {
const pages = await engine.executeRaw<{ slug: string }>(
`SELECT DISTINCT f.source_markdown_slug AS slug FROM facts f
WHERE f.source_id = $1 AND f.row_num IS NOT NULL AND f.expired_at IS NULL
@@ -1121,9 +1126,20 @@ async function expireDeletedPagesManaged(engine: BrainEngine, sourceId: string,
[sourceId],
);
const expired: Array<{ id: number }> = [];
+ const run = new ItemRun('extract_facts.expire_deleted');
for (const { slug } of pages) {
const authority = (await managedAuthority())!;
- expired.push(...(await expireDeletedPageFactsManaged(engine, authority, slug)).map(id => ({ id })));
+ try {
+ expired.push(...(await expireDeletedPageFactsManaged(engine, authority, slug)).map(id => ({ id })));
+ run.succeed();
+ } catch (error) {
+ if (error instanceof OperationError && error.detail === 'refusal_breaker') {
+ warnings.push(`FACTS_EXPIRE_SKIPPED: ${slug}: ${error.code}: the same expiry was refused repeatedly; it is tried again once the page changes or the oldest refusal is 24 hours old`);
+ continue;
+ }
+ const failure = run.fail(slug, error);
+ warnings.push(`FACTS_EXPIRE_FAILED: ${slug}: ${failure.code}: ${failure.message.slice(0, 200)} (retried by the next extract_facts run${failure.requestId ? `; gbrain write-request -- ${failure.requestId} names the refusal` : ''})`);
+ }
}
return expired;
}
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index 639ecfed21..bb68dd579b 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -27,6 +27,7 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';
/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */
export const ISOLATE_SITES = {
+ 'extract_facts.expire_deleted': 'A-21',
'maintain.cycle_sources': 'A-41',
} as const satisfies Record<string, string>;
diff --git a/test/pathological/a21-facts-expire-deleted.test.ts b/test/pathological/a21-facts-expire-deleted.test.ts
new file mode 100644
index 0000000000..094f3d5e42
--- /dev/null
+++ b/test/pathological/a21-facts-expire-deleted.test.ts
@@ -0,0 +1,121 @@
+/**
+ * GBRA-130 A-21: managed extract_facts expires the facts of soft-deleted pages
+ * before it reconciles anything. One deleted page whose expiry request is
+ * refused (a terminal storage failure replayed through the receipt, a
+ * source_changed refusal) used to throw out of the whole phase every run, so
+ * no page of the source ever reconciled again. Now that page is reported as
+ * `FACTS_EXPIRE_FAILED: <slug>: <code>`, the other deleted pages expire and
+ * the reconcile runs; run-scoped errors still stop the phase.
+ *
+ * Authoring gate: (1) protects per-page isolation of the deleted-page expiry;
+ * (2) fails when expireDeletedPagesManaged loses its per-page catch or treats a
+ * lost connection as one page's problem; (3) test/managed-facts-writers.test.ts
+ * covers only the happy path; (4) no production seam: the refusal is a real
+ * database trigger that rejects the expiry for one page.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+import { FACTS_FENCE, managedSource, PERSON, type ManagedSource } from './managed-fixture.ts';
+
+const ROW = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2020-01-01 | | chat | |`;
+
+/** Rejects every expiry of `slug`'s fact rows, the way a terminal storage failure refuses one page's write. */
+async function refuseExpiry(engine: BrainEngine, slug: string): Promise<void> {
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION patho_refuse_expiry() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN IF NEW.expired_at IS NOT NULL AND OLD.expired_at IS NULL AND NEW.source_markdown_slug = '${slug}' THEN
+ RAISE EXCEPTION 'expiry refused for %', NEW.source_markdown_slug USING ERRCODE = '23514'; END IF; RETURN NEW; END $$`);
+ await engine.executeRaw('DROP TRIGGER IF EXISTS patho_refuse_expiry ON facts');
+ await engine.executeRaw('CREATE TRIGGER patho_refuse_expiry BEFORE UPDATE ON facts FOR EACH ROW EXECUTE FUNCTION patho_refuse_expiry()');
+}
+const allowExpiry = (engine: BrainEngine) => engine.executeRaw('DROP TRIGGER IF EXISTS patho_refuse_expiry ON facts');
+
+async function active(engine: BrainEngine, sourceId: string, slug: string): Promise<string[]> {
+ return (await engine.executeRaw<{ fact: string }>(
+ 'SELECT fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL ORDER BY row_num', [sourceId, slug])).map(r => r.fact);
+}
+
+/** Two soft-deleted pages with active fence facts, plus one live page whose fact index drifted from its fence. */
+async function seedDeleted(s: ManagedSource, deleted = ['people/alice-example', 'people/bob-example']): Promise<void> {
+ for (const slug of deleted) {
+ await s.put(slug, PERSON(slug, FACTS_FENCE(ROW(1, `${slug} founded acme-example`))));
+ await s.engine.softDeletePage(slug, { sourceId: s.sourceId });
+ }
+ await s.put('people/carol-example', PERSON('Carol Example', FACTS_FENCE(ROW(1, 'Carol plays chess'))));
+ await s.engine.executeRaw('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [s.sourceId, 'people/carol-example']);
+}
+
+const failures = (warnings: string[]) => warnings.filter(w => w.startsWith('FACTS_EXPIRE_FAILED: ')).map(w => {
+ const [, key, code] = w.match(/^FACTS_EXPIRE_FAILED: ([^:]+): ([a-z_]+)/) ?? [];
+ return { key, code, fix: w };
+});
+
+describe('A-21 managed extract_facts isolates one deleted page whose expiry is refused', () => {
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] a refused deleted-page expiry is reported and the other pages still expire and reconcile`, async () => {
+ await managedSource(databaseUrl, seedDeleted, async ({ engine, sourceId }) => {
+ await refuseExpiry(engine, 'people/alice-example');
+ const before = await snapshotItems(engine, sourceId);
+ const result = await expectUnitNotAborted(() => runExtractFacts(engine, { sourceId }));
+ expect(failures(result.warnings)).toHaveLength(1);
+ expectItemFailure(failures(result.warnings)[0], { key: 'people/alice-example', code: 'storage_error', fix: /retried by the next extract_facts run/ });
+ expect(await active(engine, sourceId, 'people/alice-example')).toEqual(['people/alice-example founded acme-example']);
+ expect(await active(engine, sourceId, 'people/bob-example')).toEqual([]);
+ expect(result.factsExpiredForDeletedPages).toBe(1);
+ expect(await active(engine, sourceId, 'people/carol-example')).toEqual(['Carol plays chess']);
+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId));
+ });
+ }, 120_000);
+
+ test(`[${backend}] a deleted page whose expiry the refusal breaker holds back is skipped, not failed`, async () => {
+ await managedSource(databaseUrl, seedDeleted, async ({ engine, sourceId }) => {
+ await refuseExpiry(engine, 'people/alice-example');
+ for (let run = 0; run < 3; run++) await runExtractFacts(engine, { sourceId });
+ const result = await expectUnitNotAborted(() => runExtractFacts(engine, { sourceId }));
+ expect(failures(result.warnings)).toEqual([]);
+ expect(result.warnings.filter(w => w.startsWith('FACTS_EXPIRE_SKIPPED: people/alice-example: storage_error'))).toHaveLength(1);
+ expect(await active(engine, sourceId, 'people/alice-example')).toHaveLength(1);
+ });
+ }, 180_000);
+
+ test(`[${backend}] once the refusal clears, the next run expires the page`, async () => {
+ await managedSource(databaseUrl, seedDeleted, async ({ engine, sourceId }) => {
+ await refuseExpiry(engine, 'people/alice-example');
+ expect(failures((await runExtractFacts(engine, { sourceId })).warnings)).toHaveLength(1);
+ await allowExpiry(engine);
+ const result = await runExtractFacts(engine, { sourceId });
+ expect(failures(result.warnings)).toEqual([]);
+ expect(await active(engine, sourceId, 'people/alice-example')).toEqual([]);
+ });
+ }, 120_000);
+
+ test(`[${backend}] most deleted pages refused trips the breaker instead of reporting each one`, async () => {
+ const deleted = ['a', 'b', 'c', 'd', 'e'].map(x => `people/${x}-example`);
+ await managedSource(databaseUrl, s => seedDeleted(s, deleted), async ({ engine, sourceId }) => {
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION patho_refuse_expiry() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN IF NEW.expired_at IS NOT NULL AND OLD.expired_at IS NULL THEN RAISE EXCEPTION 'expiry refused' USING ERRCODE = '23514'; END IF; RETURN NEW; END $$`);
+ await engine.executeRaw('CREATE TRIGGER patho_refuse_expiry BEFORE UPDATE ON facts FOR EACH ROW EXECUTE FUNCTION patho_refuse_expiry()');
+ await expect(runExtractFacts(engine, { sourceId })).rejects.toMatchObject({ code: 'item_failures_systemic' });
+ });
+ }, 120_000);
+
+ for (const { name, error } of runScopedErrors()) {
+ test(`[${backend}] a run-scoped error during a deleted-page expiry still stops extract_facts (${name})`, async () => {
+ await managedSource(databaseUrl, seedDeleted, async ({ engine, sourceId }) => {
+ const injected = error();
+ const read = engine.readPageSnapshot.bind(engine);
+ engine.readPageSnapshot = (async (slug: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) => {
+ if (opts?.includeDeleted && slug.endsWith('-example') && slug !== 'people/carol-example') throw injected;
+ return read(slug, opts);
+ }) as BrainEngine['readPageSnapshot'];
+ await expect(runExtractFacts(engine, { sourceId })).rejects.toBe(injected);
+ engine.readPageSnapshot = read;
+ expect(await active(engine, sourceId, 'people/alice-example')).toHaveLength(1);
+ expect(await active(engine, sourceId, 'people/bob-example')).toHaveLength(1);
+ expect(await active(engine, sourceId, 'people/carol-example')).toEqual([]);
+ });
+ }, 120_000);
+ }
+ }
+});
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
index 5366abc0f2..98c91aef66 100644
--- a/test/pathological/catalogue.ts
+++ b/test/pathological/catalogue.ts
@@ -18,6 +18,9 @@ export interface SiteCases {
}
export const CATALOGUE: Record<IsolateSite, SiteCases> = {
+ 'extract_facts.expire_deleted': { file: 'test/pathological/a21-facts-expire-deleted.test.ts',
+ item: 'a refused deleted-page expiry is reported and the other pages still expire and reconcile',
+ run: 'a run-scoped error during a deleted-page expiry still stops extract_facts' },
'maintain.cycle_sources': { file: 'test/pathological/a41-maintain-sources.test.ts',
item: 'a source whose cycle throws is blocked with its code and the next source still cycles',
run: "a run-scoped error in one source's cycle still stops maintain" },
diff --git a/test/pathological/managed-fixture.ts b/test/pathological/managed-fixture.ts
new file mode 100644
index 0000000000..a6d4396795
--- /dev/null
+++ b/test/pathological/managed-fixture.ts
@@ -0,0 +1,60 @@
+/**
+ * Managed-brain builder for the cycle-phase pathological cases (GBRA-130
+ * A-21, A-22): a fresh engine per arm, one source whose worktree this host
+ * owns, seeded through ordinary page writes while persistence is off, then
+ * switched to managed mode so the phase under test publishes through the
+ * coordinator exactly as it does in production.
+ */
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+export interface ManagedSource { engine: BrainEngine; sourceId: string; root: string; put(slug: string, content: string): Promise<void> }
+
+export async function managedSource(databaseUrl: string | undefined, seed: (s: ManagedSource) => Promise<void>, run: (s: ManagedSource) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-pathological-managed-'));
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `patho-${randomUUID().slice(0, 8)}`;
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await claimWorktree(engine, sourceId, root);
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ const source: ManagedSource = { engine, sourceId, root, put: async (slug, content) => {
+ const prior = await engine.readPageSnapshot(slug, { sourceId });
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(),
+ ...(prior ? { expected_revision: prior.revision } : {}) } });
+ } };
+ await seed(source);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await run(source);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await close();
+ }
+ });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}
+
+export const FACTS_FENCE = (rows: string) => `## Facts
+
+<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${rows}
+<!--- gbrain:facts:end -->
+`;
+export const PERSON = (title: string, body = '', extra = '') => `---\ntitle: ${title}\ntype: person\n${extra}---\n# ${title}\n\n${body}`;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 1e811693b6..260061c706 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -218,6 +218,7 @@ test/page-prepare-shared-origin-6517.test.ts
test/page-purge-batch-sweep-6884.test.ts
test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
+test/pathological/a21-facts-expire-deleted.test.ts
test/pathological/a41-maintain-sources.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts