Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: restore replay re-hides derived rows (#3), restores pre-v249 archives (#4), matches pages by content hash or lifetime (#33)

garrytanc5e6235d4844
diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.ts
index d9671ebbcb..e7fb125694 100644
--- a/src/core/backup/snapshot.ts
+++ b/src/core/backup/snapshot.ts
@@ -15,7 +15,7 @@ import { quarantineRestoredExecution, rebaseRestorePath, relativeBackupPath, typ
import { quarantineSharedSkillRestore, validateSharedSkillRestoreMode, type SharedSkillRestore, type SharedSkillRestoreOptions } from '../shared-skills/restore.ts';
import { isPhysicalRootMetadata } from '../persistence/physical-root-record.ts';
import { protectNewBackupPath } from './private-path.ts';
-import { PURGE_MIRROR_FILE, readPurgeMirror, replayPurgesInRestore, type PurgeReplayState, type ReplayRecord } from '../belief/purge-mirror.ts';
+import { PURGE_MIRROR_FILE, readPurgeMirror, replayPurgesInRestore, type PurgeReplayResult } from '../belief/purge-mirror.ts';
interface SourceInventory { id: string; local_path: string | null; managed_relative_path: string | null }
interface BackupMetadata {
@@ -228,7 +228,7 @@ function metadataOf(manifest: ArchiveManifest): BackupMetadata {
* `<original_root>/.gbrain/purge-events.jsonl`); the restore replays the purges recorded there after the archive.
*/
export async function restorePgliteBackup(options: { archive: string; into: string; purgeMirror?: string } & SharedSkillRestoreOptions): Promise<{ root: string; quarantined_jobs: number;
- reconnect_required: string[]; shared_skills: SharedSkillRestore | null; purge_replay: { state: PurgeReplayState; replays: ReplayRecord[] } }> {
+ reconnect_required: string[]; shared_skills: SharedSkillRestore | null; purge_replay: PurgeReplayResult }> {
const mode = validateSharedSkillRestoreMode(options);
const root = checkedRoot(options.into);
if (!existsSync(dirname(root))) throw new AgentInstallError('parent_missing', 'Restore parent directory must already exist.');
@@ -272,7 +272,7 @@ export async function restorePgliteBackup(options: { archive: string; into: stri
let quarantined = 0;
let execution: RestoreQuarantine;
let sharedSkills: SharedSkillRestore | null = null;
- let purgeReplay: { state: PurgeReplayState; replays: ReplayRecord[] } = { state: 'none', replays: [] };
+ let purgeReplay: PurgeReplayResult = { state: 'none', replays: [] };
await engine.transaction(async tx => {
sharedSkills = await quarantineSharedSkillRestore(tx, restoreId, options);
await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.ts
index 7d4b8abfc6..4fcf4d9fdc 100644
--- a/src/core/belief/purge-mirror.ts
+++ b/src/core/belief/purge-mirror.ts
@@ -28,7 +28,8 @@ import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
import { COVERAGE_KEY, factKey, pageKey, slugRef } from './keys.ts';
import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
-import { bumpPurgeEpoch, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers } from './purge.ts';
+import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, pageLifetimesOf, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers } from './purge.ts';
+import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from '../facts/derivation-inputs.ts';
export const PURGE_MIRROR_FILE = 'purge-events.jsonl';
@@ -78,11 +79,16 @@ const RANK: Record<PurgeReplayState, number> = { none: 0, complete: 1, partial:
export const replayState = (records: readonly ReplayRecord[]): PurgeReplayState =>
records.reduce<PurgeReplayState>((worst, r) => RANK[r.outcome] > RANK[worst] ? r.outcome : worst, 'none');
-/** One replayed purge inside the restore transaction. No other process can reach the restored database, so it takes no page keys. */
-async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent): Promise<ReplayOutcome> {
- const src = intent.source_id, actor = 'restore_replay';
+/**
+ * One replayed purge inside the restore transaction. No other process can reach the restored database, so it takes no page keys.
+ * `ledger` is false for an archive older than the ledger (schema before v249): tombstones and row removal replay, the ledger passes do not.
+ * Rows derived from the purged ones are hidden again and, with a ledger, get their `derived.hidden`; a walk that cannot run
+ * (no derivation table) or hits its bound makes the replay `partial`.
+ */
+async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent, ledger: boolean): Promise<ReplayOutcome> {
+ const src = intent.source_id, actor = 'restore_replay', publicationId = randomUUID();
await tx.executeRaw("SELECT set_config('gbrain.write_sources', $1, true)", [JSON.stringify([src])]);
- await bumpPurgeEpoch(tx, src);
+ if (ledger) await bumpPurgeEpoch(tx, src);
for (const f of intent.facts) {
await tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason) VALUES ($1,$2,$3,$4,$5::uuid,$6,'restore replay')
ON CONFLICT DO NOTHING`, [src, f.visibility, f.subject, f.fact_hash, intent.request, actor]);
@@ -99,18 +105,23 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent): Promise<Re
const fps = [...new Set([...intent.facts.map(f => f.fact_hash), ...intent.takes])];
let claims: string[] = [];
let lifetimes = intent.lifetimes;
- let restoredPage: { id: number; slug: string } | null = null;
+ let inputs: DerivationRef[] = [];
+ let removeRows = async () => {};
if (intent.scope === 'page' && intent.slug) {
- const [page] = await tx.executeRaw<{ id: number; slug: string }>(`SELECT p.id, p.slug FROM pages p WHERE p.source_id = $1
- AND (p.slug = $2 OR p.content_hash = ANY($3::text[])) ORDER BY (p.slug = $2) DESC LIMIT 1`, [src, intent.slug, intent.content_hashes ?? []]);
+ const [page] = await tx.executeRaw<{ id: number; slug: string }>(`SELECT p.id, p.slug FROM pages p WHERE p.source_id = $1 AND (p.content_hash = ANY($2::text[])
+ ${ledger ? 'OR p.id IN (SELECT l.page_id FROM belief_page_lifetimes l WHERE l.source_id = $1 AND l.page_lifetime = ANY($3::uuid[]))' : 'OR $3::uuid[] IS NULL'})
+ ORDER BY (p.slug = $4) DESC, p.id LIMIT 1`, [src, intent.content_hashes ?? [], intent.lifetimes, intent.slug]);
if (page) {
- restoredPage = { id: Number(page.id), slug: page.slug };
- const own = await tx.executeRaw<{ page_lifetime: string }>(`SELECT page_lifetime::text AS page_lifetime FROM belief_page_lifetimes WHERE source_id = $1
- AND (page_id = $2 OR (slug = $3 AND ended_at IS NULL))`, [src, restoredPage.id, restoredPage.slug]);
- lifetimes = [...new Set([...lifetimes, ...own.map(r => r.page_lifetime)])];
- claims = (await pagePurgeClaims(tx, { sourceId: src, slug: restoredPage.slug, pageId: restoredPage.id, lifetimes })).claims;
- await tx.executeRaw('DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [src, restoredPage.slug]);
- await tx.deletePage(restoredPage.slug, { sourceId: src });
+ const restored = { id: Number(page.id), slug: page.slug };
+ if (ledger) lifetimes = [...new Set([...lifetimes, ...await pageLifetimesOf(tx, src, restored.slug, restored.id)])];
+ claims = (await pagePurgeClaims(tx, { sourceId: src, slug: restored.slug, pageId: restored.id, lifetimes: ledger ? lifetimes : [] })).claims;
+ const owned = await tx.executeRaw<{ t: string; id: number }>(`SELECT 'facts' AS t, id FROM facts WHERE source_id = $1 AND source_markdown_slug = $2
+ UNION ALL SELECT 'takes', id FROM takes WHERE page_id = $3`, [src, restored.slug, restored.id]);
+ inputs = [{ table: 'pages', id: restored.id }, ...owned.map(r => ({ table: r.t, id: Number(r.id) }))];
+ removeRows = async () => {
+ await tx.executeRaw('DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [src, restored.slug]);
+ await tx.deletePage(restored.slug, { sourceId: src });
+ };
}
} else {
const scope = intent.facts[0] ?? { fact_hash: '', visibility: 'world', subject: '*' };
@@ -119,7 +130,8 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent): Promise<Re
const takes = await tx.executeRaw<{ id: number; claim: string; page_id: number }>(`SELECT k.id, k.claim, k.page_id FROM takes k JOIN pages p ON p.id = k.page_id
WHERE p.source_id = $1 AND gbrain_fact_fingerprint(k.claim) = $2 AND ($3 = '*' OR p.slug = $3)`, [src, scope.fact_hash, scope.subject]);
claims = [...new Set([...rows.map(r => r.fact), ...takes.map(t => t.claim)])];
- if (claims.length) {
+ inputs = [...rows.map(r => ({ table: 'facts', id: Number(r.id) })), ...takes.map(t => ({ table: 'takes', id: Number(t.id) }))];
+ if (claims.length) removeRows = async () => {
const { rewritePageBodies, redactPageVersions } = await import('../facts/purge.ts');
const pages = await tx.executeRaw<{ slug: string; page_id: number; revision: string }>(`SELECT slug, id AS page_id, knowledge_revision::text AS revision FROM pages
WHERE source_id = $1 AND (slug = ANY($2::text[]) OR id = ANY($3::int[]))`, [src, rows.map(r => r.slug).filter(Boolean), takes.map(t => Number(t.page_id))]);
@@ -127,15 +139,25 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent): Promise<Re
await tx.executeRaw('DELETE FROM facts WHERE id = ANY($1::bigint[])', [rows.map(r => Number(r.id))]);
await rewritePageBodies(tx, src, pages.map(p => ({ ...p, page_id: Number(p.page_id) })));
for (const claim of claims) await redactPageVersions(tx, src, claim, pages.map(p => Number(p.page_id)));
- }
+ };
}
+ const walkable = (await tx.executeRaw<{ present: boolean }>("SELECT to_regclass('derivation_inputs') IS NOT NULL AS present"))[0]?.present === true;
+ const purgedHere = new Set(inputs.map(r => `${r.table}:${r.id}`));
+ const walk = walkable && inputs.length ? await derivedRowsFrom(tx, inputs) : { rows: [], truncated: false };
+ const derivedRows = walk.rows.filter(r => !purgedHere.has(`${r.table}:${r.id}`));
+ const targets = ledger ? await derivedBeliefTargets(tx, src, derivedRows) : [];
+ await hideDerivedRows(tx, derivedRows, { sourceId: src, requestId: intent.request, reason: 'restore replay' });
+ await removeRows();
+ const outcome: ReplayOutcome = (claims.length || replayFault === 'always_complete') && walkable && !walk.truncated ? 'complete' : 'partial';
+ if (!ledger) return outcome;
await redactPurgedKeys(tx, { sourceId: src, claimFps: fps, lifetimes });
if (claims.length) {
await redactCarryingFields(tx, { sourceId: src, request: intent.request, claims });
await registerLiveCarriers(tx, { sourceId: src, request: intent.request, claims });
}
- const outcome: ReplayOutcome = claims.length || replayFault === 'always_complete' ? 'complete' : 'partial';
- await appendBeliefEvents(tx, [await replayDraft(tx, intent, lifetimes, outcome)], { publicationId: randomUUID(), origin: 'live', purgesPossible: true });
+ await appendDerivedHidden(tx, { sourceId: src, request: intent.request, publicationId, op: 'restore_replay', targets, truncated: walk.truncated,
+ cause: { cause: 'restore_replay' } });
+ await appendBeliefEvents(tx, [await replayDraft(tx, intent, lifetimes, outcome)], { publicationId, origin: 'live', purgesPossible: true });
return outcome;
}
@@ -155,13 +177,17 @@ async function replayDraft(tx: BrainEngine, intent: PurgeMirrorIntent, lifetimes
subjectKey: known?.subject_key ?? factKey(slugRef(intent.source_incarnation, f.subject), f.fact_hash, f.visibility) };
}
+export interface PurgeReplayResult { state: PurgeReplayState; replays: ReplayRecord[]; ledger?: 'absent' }
+
/**
* Replays the purges newer than `archivedAt` for the restored database's sources (matching incarnation), in
* recorded order, then appends `coverage.restored` naming the archive time and the outcome on every source with
- * coverage. `lines` null means no mirror could be read: `purge_replay: 'unavailable'`.
+ * coverage. `lines` null means no mirror could be read: `purge_replay: 'unavailable'`. An archive older than the
+ * ledger (no `belief_events`) replays tombstones and row removal only and reports `ledger: 'absent'`.
*/
export async function replayPurgesInRestore(tx: BrainEngine, input: { lines: PurgeMirrorLine[] | null; archivedAt: string; restoreId: string }):
- Promise<{ state: PurgeReplayState; replays: ReplayRecord[] }> {
+ Promise<PurgeReplayResult> {
+ const ledger = (await tx.executeRaw<{ present: boolean }>("SELECT to_regclass('belief_events') IS NOT NULL AS present"))[0]?.present === true;
const sources = await tx.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources ORDER BY id');
const replays: ReplayRecord[] = [];
if (input.lines) {
@@ -173,11 +199,12 @@ export async function replayPurgesInRestore(tx: BrainEngine, input: { lines: Pur
if (seen.has(intent.request)) continue;
seen.add(intent.request);
if (replayFault === 'skip_replay') continue;
- const outcome = committed.has(intent.request) || replayFault === 'replay_uncommitted' ? await replayOne(tx, intent) : 'unverified';
+ const outcome = committed.has(intent.request) || replayFault === 'replay_uncommitted' ? await replayOne(tx, intent, ledger) : 'unverified';
replays.push({ request: intent.request, request_id: intent.request_id, scope: intent.scope, outcome });
}
}
const state: PurgeReplayState = input.lines ? replayState(replays) : 'unavailable';
+ if (!ledger) return { state, replays, ledger: 'absent' };
for (const source of sources) {
const [covered] = await tx.executeRaw<{ id: number }>(`SELECT id FROM belief_events WHERE source_id = $1 AND source_incarnation = $2::uuid AND subject_kind = 'coverage'
LIMIT 1`, [source.id, source.incarnation]);
diff --git a/test/belief-ledger-restore.test.ts b/test/belief-ledger-restore.test.ts
index e72dcd835a..7304826d92 100644
--- a/test/belief-ledger-restore.test.ts
+++ b/test/belief-ledger-restore.test.ts
@@ -8,7 +8,7 @@
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import postgres from '#postgres';
import { __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';
@@ -19,10 +19,14 @@ import { operations } from '../src/core/operations.ts';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { __setPurgeRedactionFaultForTests } from '../src/core/belief/purge.ts';
+import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { beliefBrain, beliefEngineCase, beliefPage, openFileBeliefBrain, withFileBeliefBrain, type BeliefBrain, type FileBeliefBrain } from './helpers/belief-ledger.ts';
import { testBackends } from './helpers/test-backends.ts';
-afterEach(() => { __setPurgeReplayFaultForTests(null); __setBeliefEmitterFaultForTests(null); });
+afterEach(() => { __setPurgeReplayFaultForTests(null); __setBeliefEmitterFaultForTests(null); __setPurgeRedactionFaultForTests(null); });
const X = 'Door code is 4417';
const SOURCE = 'belief-restore';
@@ -48,6 +52,16 @@ async function carriers(b: BeliefBrain, claim: string): Promise<string[]> {
return found;
}
+/** What the restored brain's facts, pages and versions still say about `claim` (an archive with no ledger tables). */
+async function carriersWithoutLedger(b: BeliefBrain, claim: string): Promise<string[]> {
+ const needle = claim.toLowerCase();
+ const found: string[] = [];
+ for (const [store, sql] of [['facts', 'SELECT fact AS t FROM facts'], ['pages', "SELECT compiled_truth || COALESCE(timeline,'') AS t FROM pages"]] as const) {
+ if ((await b.engine.executeRaw<{ t: string }>(sql)).some(r => r.t?.toLowerCase().includes(needle))) found.push(store);
+ }
+ return found;
+}
+
async function backupAndRestore(fb: FileBeliefBrain, between: () => Promise<void>, opts: { purgeMirror?: string } = {}) {
const archive = join(fb.home, `archive-${randomUUID().slice(0, 8)}.gbrain-backup`);
const archived = await fb.open(b => ledgerRows(b.engine));
@@ -59,6 +73,29 @@ async function backupAndRestore(fb: FileBeliefBrain, between: () => Promise<void
return { archived, result, restored, receipt: JSON.parse(readFileSync(join(into, 'restore-receipt.json'), 'utf8')), close };
}
+const Y = 'Acme front door is secured by a four digit code';
+const DERIVED_SLUG = 'notes/acme-summary-example';
+
+/** Page with X, a summary page whose fact Y was derived from X (derivation_inputs). */
+async function seedDerived(b: BeliefBrain): Promise<void> {
+ await b.put('companies/acme-example', beliefPage({ prose: 'Acme.' }));
+ await b.put('companies/acme-example', beliefPage({ facts: [X] }));
+ await b.put(DERIVED_SLUG, beliefPage({ prose: 'Summary.' }));
+ await b.put(DERIVED_SLUG, beliefPage({ facts: [Y] }));
+ const [x] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2', [b.sourceId, X]);
+ const [y] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2', [b.sourceId, Y]);
+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId],
+ () => recordDerivationInputs(tx, { table: 'facts', id: y!.id, sourceId: b.sourceId }, [{ table: 'facts', id: x!.id }]), TEST_WRITE_ATTRIBUTION));
+}
+
+/** Y's live state and the derived.hidden events a replay appended. */
+async function derivedState(engine: BrainEngine, sourceId: string) {
+ const [y] = await engine.executeRaw<{ expired: boolean }>('SELECT expired_at IS NOT NULL AS expired FROM facts WHERE source_id = $1 AND fact = $2', [sourceId, Y]);
+ const hidden = await engine.executeRaw<{ slug: string; op: string }>(`SELECT slug, cause->>'op' AS op FROM belief_events WHERE source_id = $1 AND event_type = 'derived.hidden'
+ AND cause->>'op' = 'restore_replay'`, [sourceId]);
+ return { expired: y?.expired ?? null, hidden: hidden.map(h => [h.slug, h.op]) };
+}
+
/** Runs a brain scenario to completion (teardown included, so withEnv scopes never overlap) and returns what it reported. */
async function collect<T>(run: (report: (value: T) => void) => Promise<void>): Promise<T> {
let out: T | undefined;
@@ -75,7 +112,7 @@ async function forced<T>(scenario: () => Promise<T>, check: (value: T) => void,
let failed = false;
try { check(value); } catch { failed = true; }
expect(failed).toBe(true);
- } finally { __setPurgeReplayFaultForTests(null); __setBeliefEmitterFaultForTests(null); }
+ } finally { __setPurgeReplayFaultForTests(null); __setBeliefEmitterFaultForTests(null); __setPurgeRedactionFaultForTests(null); }
}
const replayFault = (fault: PurgeReplayFault) => () => __setPurgeReplayFaultForTests(fault);
@@ -192,6 +229,63 @@ describe('belief ledger restore (pglite archive)', () => {
cleanup: { events: [['page', 'page.expired', false, null]], tombstones: 0, redacted: 0, mirror: false }, state: 'none', restoredRedacted: 0 }),
() => __setBeliefEmitterFaultForTests(drafts => drafts.map(d => d.eventType === 'page.expired' ? { ...d, eventType: 'page.purged', purged: true } : d)));
}, 300_000);
+ test('#3: a replayed purge hides its derived rows again and appends derived.hidden', async () => {
+ const scenario = () => collect<Record<string, unknown>>(resolve => withFileBeliefBrain(SOURCE, async fb => {
+ await fb.open(seedDerived);
+ const restored = await backupAndRestore(fb, () => fb.open(async b => { await purgeFact(b, X); }));
+ const out = { outcomes: restored.result.purge_replay.replays.map(r => r.outcome), ...await derivedState(restored.restored.engine, SOURCE) };
+ await restored.close();
+ resolve(out);
+ }));
+ await forced(scenario, (r: any) => expect(r).toEqual({ outcomes: ['complete'], expired: true, hidden: [[DERIVED_SLUG, 'restore_replay']] }),
+ () => __setPurgeRedactionFaultForTests('skip_derived_hidden'));
+ }, 300_000);
+
+ test('#4: an archive from before the ledger (v248) restores and replays tombstones and row removal', async () => {
+ const r = await collect<Record<string, unknown>>(resolve => withFileBeliefBrain(SOURCE, async fb => {
+ await fb.open(async b => {
+ await b.put('companies/acme-example', beliefPage({ prose: 'Acme.' }));
+ await b.put('companies/acme-example', beliefPage({ facts: [X, 'Acme sells widgets'] }));
+ });
+ const archive = join(fb.home, 'old.gbrain-backup');
+ await fb.open(async b => {
+ await b.engine.executeRaw('DROP TABLE belief_events, belief_page_lifetimes, belief_commit_marks, belief_retier_manifest, belief_redactions');
+ await b.engine.executeRaw('ALTER TABLE sources DROP COLUMN purge_epoch');
+ await b.engine.setConfig('version', '248');
+ });
+ await createPgliteBackup({ root: fb.home, output: archive });
+ await fb.open(async b => { await b.engine.initSchema(); await purgeFact(b, X); });
+ const into = join(fb.home, 'restored-old');
+ const result = await restorePgliteBackup({ archive, into });
+ const { brain, close } = await openFileBeliefBrain(join(into, '.gbrain', 'brain.pglite'), SOURCE, join(into, 'content'));
+ try {
+ resolve({ purge_replay: { ...result.purge_replay, replays: result.purge_replay.replays.map(x => x.outcome) }, left: await carriersWithoutLedger(brain, X),
+ tombstones: (await brain.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_purges WHERE source_id = $1', [SOURCE]))[0]!.n });
+ } finally { await close(); }
+ }));
+ expect(r).toEqual({ purge_replay: { state: 'complete', replays: ['complete'], ledger: 'absent' }, left: [], tombstones: 1 });
+ }, 300_000);
+
+ test('#33: a page-scope replay never deletes an unrelated page that held the slug in the archive', async () => {
+ const r = await collect<Record<string, unknown>>(resolve => withFileBeliefBrain(SOURCE, async fb => {
+ const slug = 'notes/shared-slug-example';
+ await fb.open(async b => { await b.put(slug, beliefPage({ prose: 'Page B, unrelated.' })); });
+ const restored = await backupAndRestore(fb, () => fb.open(async b => {
+ renameSync(join(b.root, `${slug}.md`), join(b.root, 'notes/b-moved-example.md'));
+ await b.engine.executeRaw(`UPDATE pages SET slug = 'notes/b-moved-example', source_path = $3 WHERE source_id = $1 AND slug = $2`,
+ [SOURCE, slug, join(b.root, 'notes/b-moved-example.md')]);
+ await b.put(slug, beliefPage({ prose: 'Page A.' }));
+ await b.put(slug, beliefPage({ facts: [X] }));
+ const snapshot = await b.engine.readPageSnapshot(slug, { sourceId: SOURCE, includeDeleted: true });
+ await deleteOp.handler(b.ctx, { slug, purge: true, expected_revision: snapshot!.revision, request_id: randomUUID() });
+ }));
+ const out = { outcomes: restored.result.purge_replay.replays.map(x => [x.scope, x.outcome]),
+ pages: (await restored.restored.engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id = $1 ORDER BY slug', [SOURCE])).map(p => p.slug) };
+ await restored.close();
+ resolve(out);
+ }));
+ expect(r).toEqual({ outcomes: [['page', 'partial']], pages: ['notes/shared-slug-example'] });
+ }, 300_000);
});
for (const engineCase of testBackends().map(beliefEngineCase)) {
@@ -219,6 +313,33 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, 240_000);
if (engineCase.name !== 'postgres') return;
+ test('#3 (postgres): replayPurgesFromDatabase hides the purge\'s derived rows again and appends derived.hidden', async () => {
+ const scenario = () => collect<Record<string, unknown>>(resolve => beliefBrain(async b => {
+ await seedDerived(b);
+ const url = new URL(engineCase.databaseUrl!);
+ const [{ db }] = await b.engine.executeRaw<{ db: string }>('SELECT current_database() AS db');
+ const clone = `gbrain_test_restore_${randomUUID().replace(/-/g, "").slice(0, 16)}`;
+ const admin = postgres(engineCase.databaseUrl!, { max: 1, prepare: false });
+ await disposePersistenceConsumer(b.engine);
+ await admin.unsafe(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${db}' AND pid <> pg_backend_pid()`);
+ await admin.unsafe(`CREATE DATABASE ${clone} TEMPLATE ${db}`);
+ const archivedAt = new Date().toISOString();
+ const restored = new PostgresEngine();
+ try {
+ await purgeFact(b, X);
+ url.pathname = `/${clone}`;
+ await restored.connect({ database_url: url.toString(), poolSize: 2 });
+ const replay = await replayPurgesFromDatabase(restored, b.engine, archivedAt);
+ resolve({ outcomes: replay.replays.map(x => x.outcome), ...await derivedState(restored, b.sourceId) });
+ } finally {
+ await restored.disconnect();
+ await admin.unsafe(`DROP DATABASE IF EXISTS ${clone} WITH (FORCE)`);
+ await admin.end();
+ }
+ }, { databaseUrl: engineCase.databaseUrl }));
+ await forced(scenario, (r: any) => expect(r).toEqual({ outcomes: ['complete'], expired: true, hidden: [[DERIVED_SLUG, 'restore_replay']] }),
+ () => __setPurgeRedactionFaultForTests('skip_derived_hidden'));
+ }, 300_000);
test('probe 11 (postgres): replayPurgesFromDatabase replays the pre-restore database\'s later purges into a clone taken at the archive time', async () => {
const scenario = () => collect<Record<string, unknown>>(resolve => beliefBrain(async b => {
await b.put('companies/acme-example', beliefPage({ prose: 'Acme.' }));