Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(pathological): GBRA-130 A-11/A-12/A-13/A-15 effects probes on both engines
garrytan24c0b3309228
diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex d5cff083c8..06f44cdc30 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -43,6 +43,7 @@ export const ISOLATE_SITES = {'repair.all_kinds': 'A-45','repair.content_lane_kinds': 'A-46','migration.credential_reseal': 'A-27',+ 'effects.derived_retry_budget': 'A-11',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;diff --git a/test/pathological/a11-effect-retry-budget.test.ts b/test/pathological/a11-effect-retry-budget.test.tsnew file mode 100644index 0000000000..a43de1ceaf--- /dev/null+++ b/test/pathological/a11-effect-retry-budget.test.ts@@ -0,0 +1,142 @@+/**+ * GBRA-130 A-11: a `links` or `facts-backstop` effect that failed the same way+ * every time (an oversized segmented block, a 57014 on a page with thousands of+ * mention targets, a queue refusal) was retried every 30 s forever: only Git and+ * withdrawal-mirror effects counted toward PARK_AFTER_FAILURES. The queued effect+ * wedged `writer deactivate` and shared-skills activation, and retry-effects did+ * not cover these kinds.+ *+ * Authoring gate: (1) protects "a derived effect that keeps failing reaches a+ * terminal state with its code": after five counted failures a links effect+ * completes as skipped (the edge is derived; `gbrain extract --stale` recovers it)+ * and a facts-backstop effect fails with the code, deactivate no longer lists them,+ * retry-effects re-authorizes the failed one, a run-scoped failure is never counted,+ * and a pass where most effects fail counts nothing. (2) Reverting the count in+ * effects.ts recordFailure leaves the effect queued and every item case goes red.+ * (3) No existing test fails a links or facts-backstop effect repeatedly.+ * (4) The failure is injected by wrapping the engine's transaction (no production seam).+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { OperationError, type OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import { listBlockingEffects } from '../../src/core/persistence/blocking-effects.ts';+import { deactivatePersistence } from '../../src/core/persistence/deactivation.ts';+import { retryRequestEffects } from '../../src/core/persistence/effect-retry.ts';+import { PARK_AFTER_FAILURES } from '../../src/core/persistence/effect-model.ts';+import { failLocks, passes } from './effects-fixture.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const TARGET = 'notes/target-example';+const PAGES = Array.from({ length: 6 }, (_, i) => `notes/p-${i + 1}`);+const BAD = 'notes/p-3';+const healthy = PAGES.filter(slug => slug !== BAD);+const segmented = () => new OperationError('page_body_segmented', 'A block of this page exceeds the segmented block limit.');+const timeout = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });++const put = (ctx: OperationContext, slug: string, body: string) => submitPageMutation(ctx, { operation: 'put_page',+ params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${body}\n` } });++/** Every page mentions the target; each page's request gets a links effect, BAD's also a facts-backstop effect (the shapes a remote put_page queues). */+async function seed(engine: BrainEngine, ctx: OperationContext, slugs = PAGES, facts = [BAD]) {+ await put(ctx, TARGET, 'The target.');+ for (const slug of slugs) await put(ctx, slug, `See [[${TARGET}]].`);+ await disposePersistenceConsumer(engine);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,revision,data,source_id,source_incarnation,worktree_id)+ SELECT e.request_id,k.kind,e.revision,e.data,e.source_id,e.source_incarnation,e.worktree_id FROM persistence_effects e+ JOIN persistence_requests r ON r.id=e.request_id CROSS JOIN (VALUES ('links'),('facts-backstop')) AS k(kind)+ WHERE e.kind='embedding' AND r.slug=ANY($1::text[]) AND (k.kind='links' OR r.slug=ANY($2::text[]))`, [slugs, facts]);+ });+}++type Row = { slug: string; request_id: string; kind: string; state: string; error_code: string | null; outcome: Record<string, unknown> | null; failures: number | null };+async function derived(engine: BrainEngine): Promise<Row[]> {+ return engine.executeRaw<Row>(`SELECT r.slug,r.request_id::text AS request_id,e.kind,e.state,e.error_code,e.outcome,(e.data->>'target_failures')::int AS failures+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind IN ('links','facts-backstop') ORDER BY r.slug,e.kind`);+}+const of = (rows: Row[], slug: string, kind: string) => rows.find(row => row.slug === slug && row.kind === kind)!;++async function effectBlockers(engine: BrainEngine) {+ return (await deactivatePersistence(engine, { dryRun: true })).blockers.filter(blocker => blocker.kind === 'effect');+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-11 links and facts-backstop effects have a retry budget (${backend})`, () => {+ test('A-11 item: a links and a facts-backstop effect failing every attempt reach terminal states with the code; the siblings link', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await seed(engine, ctx);+ const before = await snapshotItems(engine, 'default');+ const restore = failLocks(engine, new Set([BAD]), segmented);+ try {+ await expectUnitNotAborted(() => passes(engine, ctx.config, PARK_AFTER_FAILURES - 1));+ const counting = await derived(engine);+ expect({ state: of(counting, BAD, 'links').state, failures: of(counting, BAD, 'links').failures }).toEqual({ state: 'queued', failures: PARK_AFTER_FAILURES - 1 });+ await expectUnitNotAborted(() => passes(engine, ctx.config, 1));+ } finally { restore(); }+ const rows = await derived(engine);+ const links = of(rows, BAD, 'links');+ expect({ state: links.state, outcome: links.outcome }).toEqual({ state: 'committed', outcome: { links: 'skipped', reason: 'page_body_segmented' } });+ const facts = of(rows, BAD, 'facts-backstop');+ expectItemFailure({ key: facts.slug, code: facts.error_code ?? undefined }, { key: BAD, code: 'page_body_segmented' });+ expect(facts.state).toBe('failed');+ for (const slug of healthy) expect({ slug, ...pick(of(rows, slug, 'links')) }).toEqual({ slug, state: 'committed', links: 'committed' });+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { changed: [BAD], expectProgress: healthy, progressFields: ['links'] });+ expect(await listBlockingEffects(engine)).toEqual([]);+ expect(await effectBlockers(engine)).toEqual([]);++ // Recovery: the cause clears and retry-effects authorizes one more attempt for the failed facts-backstop effect.+ const preview = await retryRequestEffects(engine, 'default', facts.request_id, true, ctx.config);+ expect((preview.effects as Array<{ kind: string; action: string }>).filter(e => e.kind === 'facts-backstop')).toEqual([expect.objectContaining({ action: 'would_retry' })]);+ expect(of(await derived(engine), BAD, 'facts-backstop').state).toBe('failed');+ await retryRequestEffects(engine, 'default', facts.request_id, false, ctx.config);+ await passes(engine, ctx.config, 1);+ expect(of(await derived(engine), BAD, 'facts-backstop')).toMatchObject({ state: 'committed', error_code: null });+ }, { databaseUrl });+ }, 180_000);++ test('A-11 item: a statement timeout on every attempt is bounded too', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await seed(engine, ctx, PAGES.slice(0, 2), []);+ const restore = failLocks(engine, new Set([PAGES[0]]), timeout);+ try { await expectUnitNotAborted(() => passes(engine, ctx.config, PARK_AFTER_FAILURES + 1)); } finally { restore(); }+ const rows = await derived(engine);+ expect(pick(of(rows, PAGES[0], 'links'))).toEqual({ state: 'committed', links: 'skipped', reason: 'statement_timeout' });+ expect(pick(of(rows, PAGES[1], 'links'))).toEqual({ state: 'committed', links: 'committed' });+ expect(await effectBlockers(engine)).toEqual([]);+ }, { databaseUrl });+ }, 180_000);++ for (const injected of runScopedErrors()) {+ test(`A-11 run: a run-scoped failure (${injected.name}) is never counted and the effect stays queued`, async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await seed(engine, ctx, PAGES.slice(0, 1));+ const restore = failLocks(engine, new Set([PAGES[0]]), injected.error);+ try { await expectUnitNotAborted(() => passes(engine, ctx.config, PARK_AFTER_FAILURES + 2)); } finally { restore(); }+ for (const row of await derived(engine)) expect({ kind: row.kind, state: row.state, failures: row.failures }).toEqual({ kind: row.kind, state: 'queued', failures: null });+ }, { databaseUrl });+ }, 180_000);+ }++ test('A-11 breaker: a pass where every links effect fails counts none of them', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await seed(engine, ctx, PAGES, []);+ const restore = failLocks(engine, new Set(PAGES), segmented);+ try { await expectUnitNotAborted(() => passes(engine, ctx.config, PARK_AFTER_FAILURES + 1)); } finally { restore(); }+ for (const row of await derived(engine)) {+ expect({ slug: row.slug, state: row.state, error_code: row.error_code, failures: row.failures })+ .toEqual({ slug: row.slug, state: 'queued', error_code: 'item_failures_systemic', failures: null });+ }+ }, { databaseUrl });+ }, 180_000);+ });+}++function pick(row: Row) {+ const outcome = row.outcome ?? {};+ return { state: row.state, links: outcome.links, ...(outcome.reason ? { reason: outcome.reason } : {}) };+}diff --git a/test/pathological/a12-withdrawal-mirror-gate.test.ts b/test/pathological/a12-withdrawal-mirror-gate.test.tsnew file mode 100644index 0000000000..37186a69d4--- /dev/null+++ b/test/pathological/a12-withdrawal-mirror-gate.test.ts@@ -0,0 +1,164 @@+/**+ * GBRA-130 A-12: a withdrawal-mirror effect that ended `failed` (one parked+ * target, or `source_changed` when its source was archived while it was queued)+ * gated its request's Git and embedding effects forever: both claim queries and+ * the lifecycle settlement waited on `mirror.state<>'committed'`. The withdrawn+ * pages stayed vectorless, Git never committed, and the source's lifecycle refused.+ *+ * Authoring gate: (1) protects "a finished mirror releases exactly the targets it+ * committed": Git and embedding run for the mirrored pages and park every other+ * target with `withdrawal_mirror_failed` (a mirror that failed before rewriting a+ * file never lets Git commit withdrawn text), the coalesced single-file Git claim+ * honours the same list, retry-effects reruns a failed mirror and re-arms the+ * withheld targets, and a run-scoped failure reading the list parks nothing.+ * (2) Reverting the gate in effect-journal.ts leaves Git and embedding queued and+ * every item case goes red; reverting the allowlist commits withdrawn files.+ * (3) No existing test fails a mirror and then looks at its siblings.+ * (4) The failure is a real one: a directory where the mirror expects the page file.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import { getWorktreeBinding } from '../../src/core/persistence/ownership.ts';+import { retryRequestEffects } from '../../src/core/persistence/effect-retry.ts';+import { settleTopologyRequests, topologyPrincipal } from '../../src/core/persistence/topology-locks.ts';+import { checkParkedEffects } from '../../src/commands/doctor/checks/parked-effects.ts';+import { durableGitRepo, git } from '../helpers/git-publication.ts';+import { committedSinceSeed, drain, effectsOf, embeddedPages, passes, SOURCE, TARGETS, UNTOUCHED, withdrawalBrain } from './effects-fixture.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const [W1, W2, W3] = TARGETS;+const WITHHELD = 'withdrawal_mirror_failed';+/** A directory where the mirror expects page W2's file: every mirror attempt for it fails before writing anything. */+const breakFile = (root: string) => { rmSync(join(root, `${W2}.md`)); mkdirSync(join(root, `${W2}.md`)); };+const fixFile = (root: string) => { rmSync(join(root, `${W2}.md`), { recursive: true }); git(root, 'checkout', '--', `${W2}.md`); };+const actions = (result: Record<string, unknown>) => Object.fromEntries((result.effects as Array<{ kind: string; action: string }>).map(e => [e.kind, e.action]));++async function settleLifecycle(engine: BrainEngine): Promise<number> {+ const binding = (await getWorktreeBinding(engine, SOURCE, localHostId()))!;+ const principal = await topologyPrincipal(engine);+ return engine.transaction(tx => settleTopologyRequests(tx, [SOURCE], [binding.worktree_id], principal));+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-12 a failed withdrawal mirror releases only what it committed (${backend})`, () => {+ test('A-12 item: a mirror that parked one target lets Git and embedding finish the targets it committed and withholds the rest', async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, root, request, ctx }) => {+ breakFile(root);+ const before = await snapshotItems(engine, SOURCE);+ await expectUnitNotAborted(() => drain(engine, 12));+ const effects = await effectsOf(engine, request.id);+ expect({ state: effects['withdrawal-mirror'].state, parked: effects['withdrawal-mirror'].data.parked?.map((p: { slug: string }) => p.slug) })+ .toEqual({ state: 'failed', parked: [W2] });+ for (const kind of ['git', 'embedding']) {+ expect({ kind, state: effects[kind].state, error_code: effects[kind].error_code }).toEqual({ kind, state: 'failed', error_code: 'targets_parked' });+ const [parked] = effects[kind].data.parked ?? [];+ expectItemFailure(parked && { key: parked.slug, code: parked.error_code }, { key: W2, code: WITHHELD });+ }+ expect(committedSinceSeed(root).sort()).toEqual([`${W1}.md`, `${W3}.md`]);+ expect(await embeddedPages(engine)).toEqual([W1, W3]);+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { changed: [W2], expectProgress: [W1, W3], progressFields: ['chunks'] });+ expect((await snapshotItems(engine, SOURCE)).get(UNTOUCHED)).toEqual(before.get(UNTOUCHED));+ const doctor = await checkParkedEffects(engine);+ expect(doctor.message).toContain(`${W2} (${WITHHELD})`);+ expect(doctor.message).toContain(`gbrain sources writer retry-effects ${SOURCE} --request-id ${request.request_id} --dry-run`);+ expect(await expectUnitNotAborted(() => settleLifecycle(engine))).toBe(0);++ // Recovery: the file is restored, one retry-effects reruns the mirror's parked target and re-arms the withheld ones.+ fixFile(root);+ expect(actions(await retryRequestEffects(engine, SOURCE, request.request_id, true, ctx.config)))+ .toEqual({ embedding: 'would_retry', git: 'would_retry', 'withdrawal-mirror': 'would_retry' });+ await retryRequestEffects(engine, SOURCE, request.request_id, false, ctx.config);+ await drain(engine, 8);+ const after = await effectsOf(engine, request.id);+ for (const kind of ['withdrawal-mirror', 'git', 'embedding']) expect({ kind, state: after[kind].state }).toEqual({ kind, state: 'committed' });+ expect(committedSinceSeed(root).sort()).toEqual([`${W1}.md`, `${W2}.md`, `${W3}.md`]);+ expect(await embeddedPages(engine)).toEqual(TARGETS);+ });+ }, 180_000);++ test('A-12 item: a mirror that failed source_changed withholds its remaining targets; retry-effects reruns it once the source is back', async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, root, request, ctx }) => {+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [SOURCE]);+ await expectUnitNotAborted(() => drain(engine, 2, { projections: false }));+ await engine.executeRaw('UPDATE sources SET archived=false WHERE id=$1', [SOURCE]);+ const failed = await effectsOf(engine, request.id);+ expect(Object.fromEntries(Object.values(failed).map(e => [e.kind, e.state]))).toEqual({ embedding: 'failed', git: 'failed', 'withdrawal-mirror': 'failed' });+ expect(failed['withdrawal-mirror'].error_code).toBe('source_changed');+ expect(committedSinceSeed(root)).toEqual([]);+ expect(await expectUnitNotAborted(() => settleLifecycle(engine))).toBe(0);+ expect(actions(await retryRequestEffects(engine, SOURCE, request.request_id, true, ctx.config)))+ .toEqual({ embedding: 'would_retry', git: 'would_retry', 'withdrawal-mirror': 'would_retry' });+ await retryRequestEffects(engine, SOURCE, request.request_id, false, ctx.config);+ await drain(engine, 8);+ const after = await effectsOf(engine, request.id);+ for (const kind of ['withdrawal-mirror', 'git', 'embedding']) expect({ kind, state: after[kind].state }).toEqual({ kind, state: 'committed' });+ expect(committedSinceSeed(root).sort()).toEqual(TARGETS.map(slug => `${slug}.md`));+ expect(await embeddedPages(engine)).toEqual(TARGETS);+ });+ }, 180_000);++ test('A-12 item: the coalesced single-file Git claim commits a page behind a failed mirror only when the mirror committed it', async () => {+ await managedBrain(async ({ engine, ctx, root }) => {+ const put = (slug: string) => submitPageMutation(ctx, { operation: 'put_page',+ params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\nBody of ${slug}.\n` } });+ await put('notes/mirrored'); await put('notes/withheld');+ await disposePersistenceConsumer(engine);+ await passes(engine, ctx.config, 2);+ writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']);+ const git1 = await engine.executeRaw<{ id: string; request_id: string; slug: string; data: Record<string, unknown> }>(`SELECT e.id::text AS id,e.request_id::text AS request_id,r.slug,e.data+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' ORDER BY e.id`);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_effects SET state='queued',attempts=0,execution_token=NULL,claim_expires_at=NULL,error_code=NULL,outcome=NULL,+ next_attempt_at=now() WHERE kind='git'`);+ for (const row of git1) {+ const page = { slug: row.slug, page_id: row.data.page_id, revision: randomUUID() };+ const data = row.slug === 'notes/mirrored'+ ? { version: 2, targets: [page, { slug: 'notes/zz-other', page_id: 0, revision: randomUUID() }], after_slug: 'notes/zz-other', parked: [{ slug: 'notes/zz-other', error_code: 'storage_error' }] }+ : { version: 2, targets: [page], after_slug: row.slug, parked: [{ slug: row.slug, error_code: 'storage_error' }] };+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id,state,error_code)+ SELECT request_id,'withdrawal-mirror',$2::text::jsonb,source_id,source_incarnation,worktree_id,'failed','targets_parked' FROM persistence_effects WHERE id=$1`,+ [row.id, JSON.stringify(data)]);+ }+ });+ await expectUnitNotAborted(() => runPersistenceEffects(engine, ctx.config, { hostId: localHostId(), limit: 1 }));+ const after = await engine.executeRaw<{ slug: string; state: string; error_code: string | null; attempts: number; parked: Array<{ slug: string; error_code: string }> | null }>(+ `SELECT r.slug,e.state,e.error_code,e.attempts,e.data->'parked' AS parked FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE e.kind='git' ORDER BY r.slug`);+ expect(after.map(row => ({ slug: row.slug, state: row.state, attempts: Number(row.attempts) }))).toEqual([+ { slug: 'notes/mirrored', state: 'committed', attempts: 1 }, { slug: 'notes/withheld', state: 'failed', attempts: 1 }]);+ expectItemFailure(after[1].parked?.[0] && { key: after[1].parked[0].slug, code: after[1].parked[0].error_code }, { key: 'notes/withheld', code: WITHHELD });+ const log = git(root, 'log', '--name-only', '--pretty=format:');+ expect({ mirrored: log.includes('notes/mirrored.md'), withheld: log.includes('notes/withheld.md') }).toEqual({ mirrored: true, withheld: false });+ }, { databaseUrl });+ }, 180_000);++ for (const injected of runScopedErrors()) {+ test(`A-12 run: a run-scoped failure (${injected.name}) reading the mirror's committed targets parks nothing`, async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, root, request }) => {+ breakFile(root);+ const original = engine.executeRaw;+ engine.executeRaw = (async function (this: BrainEngine, sql: string, params?: unknown[]) {+ if (/kind='withdrawal-mirror' AND state='failed'/.test(sql)) throw injected.error();+ return original.call(this, sql, params);+ }) as BrainEngine['executeRaw'];+ try { await expectUnitNotAborted(() => drain(engine, 12)); } finally { engine.executeRaw = original; }+ const effects = await effectsOf(engine, request.id);+ expect(effects['withdrawal-mirror'].state).toBe('failed');+ for (const kind of ['git', 'embedding']) expect({ kind, parked: effects[kind].data.parked ?? null }).toEqual({ kind, parked: null });+ expect({ state: effects.git.state, failures: effects.git.data.target_failures ?? null }).toEqual({ state: 'queued', failures: null });+ expect(committedSinceSeed(root)).toEqual([]);+ });+ }, 180_000);+ }+ });+}diff --git a/test/pathological/a13-embedding-target-park.test.ts b/test/pathological/a13-embedding-target-park.test.tsnew file mode 100644index 0000000000..3cb095890f--- /dev/null+++ b/test/pathological/a13-embedding-target-park.test.ts@@ -0,0 +1,78 @@+/**+ * GBRA-130 A-13: a targeted (withdrawal) or scan embedding effect never set its+ * failing target, so one page whose provider call failed every time used up the+ * whole effect's retry budget: the effect failed `embedding_attempts_exhausted`+ * and every later target stayed without vectors (the withdrawal had deleted+ * their chunks). Git and mirror scans already parked one target and moved on.+ *+ * Authoring gate: (1) protects "one page the provider refuses never leaves the+ * other withdrawn pages vectorless": the failing page is parked with its code+ * after the per-page budget, the scan embeds the later targets and ends+ * `targets_parked`, retry-effects re-embeds the parked page once the provider+ * accepts it, while configuration and run-scoped failures stay effect-wide and+ * park nothing. (2) Reverting the per-target park in effects.ts fails the whole+ * effect at the first page and the item case goes red. (3) No existing test fails+ * one target of a multi-target embedding effect. (4) The provider is the effect+ * worker's embedding stub, the seam every embedding-effect test uses.+ */+import { describe, expect, test } from 'bun:test';+import { AIConfigError } from '../../src/core/ai/errors.ts';+import { retryRequestEffects } from '../../src/core/persistence/effect-retry.ts';+import { drain, effectsOf, embedAll, embeddedPages, SOURCE, TARGETS, UNTOUCHED, withdrawalBrain, type Embed } from './effects-fixture.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const [W1, W2, W3] = TARGETS;+/** The provider refuses W2's text every time (a non-retriable, non-configuration server error) and embeds every other text. */+const refusing = (error: () => unknown): Embed => async (texts, options) => {+ if (texts.some(text => text.includes(W2))) throw error();+ return embedAll(texts, options);+};+const providerRefusal = () => Object.assign(new Error('The provider could not embed this input'), { status: 500 });++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-13 an embedding scan parks the page the provider refuses (${backend})`, () => {+ test('A-13 item: the refused page is parked with its code, the later targets are embedded, and retry-effects re-embeds it', async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, request, ctx }) => {+ const before = await snapshotItems(engine, SOURCE);+ await expectUnitNotAborted(() => drain(engine, 14, { embed: refusing(providerRefusal) }));+ const { embedding, git } = await effectsOf(engine, request.id);+ expect({ state: embedding.state, error_code: embedding.error_code }).toEqual({ state: 'failed', error_code: 'targets_parked' });+ const [parked] = embedding.data.parked ?? [];+ expectItemFailure(parked && { key: parked.slug, code: parked.error_code }, { key: W2, code: 'effect_unavailable' });+ expect(embedding.data.parked).toHaveLength(1);+ expect(await embeddedPages(engine)).toEqual([W1, W3]);+ expect(git.state).toBe('committed');+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { changed: TARGETS });+ expect((await snapshotItems(engine, SOURCE)).get(UNTOUCHED)).toEqual(before.get(UNTOUCHED));++ const preview = await retryRequestEffects(engine, SOURCE, request.request_id, true, ctx.config);+ expect((preview.effects as Array<{ kind: string; action: string }>).find(e => e.kind === 'embedding')?.action).toBe('would_retry');+ await retryRequestEffects(engine, SOURCE, request.request_id, false, ctx.config);+ await drain(engine, 4);+ expect((await effectsOf(engine, request.id)).embedding).toMatchObject({ state: 'committed', error_code: null });+ expect(await embeddedPages(engine)).toEqual(TARGETS);+ });+ }, 180_000);++ test('A-13 item: a configuration error stays effect-wide and parks nothing', async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, request }) => {+ await expectUnitNotAborted(() => drain(engine, 8, { embed: refusing(() => new AIConfigError('The embedding model is not configured for this provider.')) }));+ const { embedding } = await effectsOf(engine, request.id);+ expect({ state: embedding.state, error_code: embedding.error_code, parked: embedding.data.parked ?? null })+ .toEqual({ state: 'failed', error_code: 'embedding_configuration', parked: null });+ });+ }, 180_000);++ for (const injected of runScopedErrors()) {+ test(`A-13 run: a run-scoped failure (${injected.name}) at one page parks nothing and does not move the scan past it`, async () => {+ await withdrawalBrain(databaseUrl, async ({ engine, request }) => {+ await expectUnitNotAborted(() => drain(engine, 14, { embed: refusing(injected.error) }));+ const { embedding } = await effectsOf(engine, request.id);+ expect({ parked: embedding.data.parked ?? null, error_code: embedding.error_code === 'targets_parked' ? 'targets_parked' : 'not parked' })+ .toEqual({ parked: null, error_code: 'not parked' });+ expect(await embeddedPages(engine)).toEqual([W1]);+ });+ }, 180_000);+ }+ });+}diff --git a/test/pathological/a15-deactivate-exits.test.ts b/test/pathological/a15-deactivate-exits.test.tsnew file mode 100644index 0000000000..53e946ff1d--- /dev/null+++ b/test/pathological/a15-deactivate-exits.test.ts@@ -0,0 +1,117 @@+/**+ * GBRA-130 A-15: `writer deactivate` blocked on every effect whose state was not+ * `committed`, terminal failures included, and several blockers printed exits that+ * could not clear them: retry-effects refused a failed Git effect without parked+ * targets (`source_changed` after an archive and restore) with `invalid_params`,+ * and `repair embedding-effects` re-queued a zero-norm embedding effect that fails+ * the same way by design. Activation already blocked only on queued, running or+ * recovering effects.+ *+ * Authoring gate: (1) protects "only work that can still change blocks deactivate,+ * and every exit it prints clears what it names": terminal failures are listed in+ * `failed_effects` with their code and a real exit (or none when nothing can retry+ * them), and running each printed exit removes its entry. (2) Reverting the+ * blocker predicate in deactivation.ts lists the failures as blockers again and the+ * cases go red. (3) persistence-deactivate.test.ts covers requests and leases, not+ * failed effects or their exits. (4) No seam: the failures are real or built rows.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { OperationError, type OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import { deactivatePersistence } from '../../src/core/persistence/deactivation.ts';+import { retryRequestEffects } from '../../src/core/persistence/effect-retry.ts';+import { PARK_AFTER_FAILURES } from '../../src/core/persistence/effect-model.ts';+import { failLocks, passes } from './effects-fixture.ts';+import { expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, snapshotItems } from './harness.ts';++const put = (ctx: OperationContext, slug: string, body: string) => submitPageMutation(ctx, { operation: 'put_page',+ params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${body}\n` } });++async function effectOf(engine: BrainEngine, slug: string, kind: string) {+ const [row] = await engine.executeRaw<{ id: string; request_id: string; state: string; error_code: string | null }>(`SELECT e.id::text AS id,+ r.request_id::text AS request_id,e.state,e.error_code FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE r.slug=$1 AND e.kind=$2`, [slug, kind]);+ return row;+}+async function setEffect(engine: BrainEngine, id: string, sql: string) {+ await engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(`UPDATE persistence_effects SET ${sql} WHERE id=$1`, [id]); });+}+const preview = (engine: BrainEngine) => deactivatePersistence(engine, { dryRun: true });++/** Runs one printed exit the way an agent would: the retry-effects preview's apply step, or the owner's effect worker. */+async function runExit(engine: BrainEngine, ctx: OperationContext, exit: string): Promise<void> {+ const retry = /^gbrain sources writer retry-effects (\S+) --request-id (\S+) --dry-run$/.exec(exit);+ if (retry) {+ await retryRequestEffects(engine, retry[1], retry[2], true, ctx.config);+ await retryRequestEffects(engine, retry[1], retry[2], false, ctx.config);+ await passes(engine, ctx.config, 2);+ return;+ }+ if (/^wait for the owner to drain it/.test(exit)) { await passes(engine, ctx.config, PARK_AFTER_FAILURES + 1); return; }+ throw new Error(`unrecognized exit: ${exit}`);+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-15 deactivate blocks only on work that can still change (${backend})`, () => {+ test('A-15 item: terminal effect failures are history with a real exit, and each printed exit clears its entry', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/archived', 'Its Git effect fails while the source is archived.');+ await put(ctx, 'notes/zero', 'The provider returns a zero vector for this text.');+ await disposePersistenceConsumer(engine);+ await passes(engine, ctx.config, 2);+ // A Git effect that failed source_changed while its source was archived, after the source was restored.+ const git = await effectOf(engine, 'notes/archived', 'git');+ await setEffect(engine, git.id, `state='failed',attempts=1,outcome=NULL,error_code='source_changed'`);+ const zero = await effectOf(engine, 'notes/zero', 'embedding');+ await setEffect(engine, zero.id, `state='failed',error_code='embedding_zero_norm',outcome=NULL`);+ const before = await snapshotItems(engine, 'default');++ const report = await expectUnitNotAborted(() => preview(engine));+ expect(report.blockers.filter(b => b.kind === 'effect')).toEqual([]);+ const failed = new Map((report.failed_effects ?? []).map(entry => [entry.effect_id, entry]));+ expect(failed.get(git.id)).toMatchObject({ kind: 'git', code: 'source_changed',+ exit: `gbrain sources writer retry-effects default --request-id ${git.request_id} --dry-run` });+ expect(failed.get(zero.id)).toMatchObject({ kind: 'embedding', code: 'embedding_zero_norm', exit: null });++ for (const entry of failed.values()) if (entry.exit) await runExit(engine, ctx, entry.exit);+ const after = await preview(engine);+ expect(after.blockers.filter(b => b.kind === 'effect')).toEqual([]);+ expect((after.failed_effects ?? []).map(entry => entry.effect_id)).toEqual([zero.id]);+ expect(await effectOf(engine, 'notes/archived', 'git')).toMatchObject({ state: 'committed' });+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));+ }, { databaseUrl });+ }, 180_000);++ test('A-15 item: every exit an effect blocker prints clears that blocker', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/target-example', 'The target.');+ await put(ctx, 'notes/stuck', 'See [[notes/target-example]].');+ await put(ctx, 'notes/queued', 'An embedding effect still queued.');+ await disposePersistenceConsumer(engine);+ await passes(engine, ctx.config, 2);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,revision,data,source_id,source_incarnation,worktree_id)+ SELECT e.request_id,'links',e.revision,e.data,e.source_id,e.source_incarnation,e.worktree_id FROM persistence_effects e+ JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='embedding' AND r.slug='notes/stuck'`);+ await tx.executeRaw(`UPDATE persistence_effects e SET state='queued',outcome=NULL,error_code=NULL,attempts=0 FROM persistence_requests r+ WHERE r.id=e.request_id AND e.kind='embedding' AND r.slug='notes/queued'`);+ });+ const restore = failLocks(engine, new Set(['notes/stuck']), () => new OperationError('page_body_segmented', 'A block of this page exceeds the segmented block limit.'));+ try {+ const blockers = (await preview(engine)).blockers.filter(b => b.kind === 'effect');+ expect(blockers.map(b => b.detail.split(' ')[0]).sort()).toEqual(['embedding', 'links']);+ for (const blocker of blockers) {+ await runExit(engine, ctx, blocker.exit);+ const remaining = (await preview(engine)).blockers.filter(b => b.kind === 'effect').map(b => b.id);+ expect({ exit: blocker.exit, cleared: !remaining.includes(blocker.id) }).toEqual({ exit: blocker.exit, cleared: true });+ }+ } finally { restore(); }+ }, { databaseUrl });+ }, 180_000);+ });+}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex 57423125e6..bd8b8ea1fb 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -63,4 +63,6 @@ export const CATALOGUE: Record<IsolateSite, SiteCases> = {'repair.all_kinds': { file: 'test/pathological/a45-repair-all-kinds.test.ts', item: 'item case: a kind whose plan throws', run: 'run case: a run-scoped' },'repair.content_lane_kinds': { file: 'test/pathological/a46-content-lane-kinds.test.ts', item: 'item case: fences throwing is recorded', run: 'run case: a run-scoped' },'migration.credential_reseal': { file: 'test/pathological/a27-credential-reseal.test.ts', item: 'item case: the unbuildable page is held', run: 'run case: a run-scoped' },+ 'effects.derived_retry_budget': { file: 'test/pathological/a11-effect-retry-budget.test.ts',+ item: 'A-11 item: a links and a facts-backstop effect failing every attempt', run: 'A-11 run: a run-scoped failure (' },};diff --git a/test/pathological/effects-fixture.ts b/test/pathological/effects-fixture.tsnew file mode 100644index 0000000000..da187ea2b5--- /dev/null+++ b/test/pathological/effects-fixture.ts@@ -0,0 +1,158 @@+/**+ * Effect-runner builders for the GBRA-130 effects cases (A-11, A-12, A-13): a+ * fresh engine per arm whose default source is a claimed worktree in a durable+ * Git repository, three pages that carry one world claim in their facts fence+ * (plus one untouched page), and helpers that drive the effect runner one pass+ * at a time with every effect due, an embedding stub, and the text projections+ * a withdrawal invalidates rebuilt the way the projection worker would.+ */+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { renderFactsTable } from '../../src/core/facts-fence.ts';+import { serializePageToMarkdown } from '../../src/core/markdown.ts';+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { submissionAuthority } from '../../src/core/persistence/authority.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import { localHostId, registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { admitWrite, completeWrite } from '../../src/core/persistence/journal.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { runPersistenceEffects, type EffectWorkerOptions } from '../../src/core/persistence/effects.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { durableGitRepo, git } from '../helpers/git-publication.ts';+import { withEnv } from '../helpers/with-env.ts';++export const SOURCE = 'default';+export const CLAIM = 'acme-example closed a seed round';+export const TARGETS = ['notes/w-1', 'notes/w-2', 'notes/w-3'];+export const UNTOUCHED = 'notes/untouched';+export const SIGNATURE = 'test:model:1536';+export const MODEL = 'test:model';+export const vector = () => new Float32Array(1536).fill(0.1);+export type Embed = NonNullable<EffectWorkerOptions['embedding']>['embed'];+export const embedAll: Embed = async texts => texts.map(() => vector());++export interface WithdrawalBrain {+ engine: BrainEngine; root: string; ctx: OperationContext;+ /** The forget request: journal row id (effects reference it) and public receipt id. */+ request: { id: string; request_id: string };+}++const body = (slug: string) => `# ${slug}\n\n${renderFactsTable([{ rowNum: 1, claim: CLAIM, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }])}`;++/** Seeds the pages, their files and chunks, commits them, then commits one forget request whose withdrawal queues mirror, Git and embedding effects. */+export async function withdrawalBrain(databaseUrl: string | undefined, run: (brain: WithdrawalBrain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-pathological-effects-'));+ try {+ await withEnv({ GBRAIN_HOME: join(home, 'home'), GBRAIN_AUDIT_DIR: join(home, 'audit'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ const root = join(home, 'brain'); mkdirSync(join(root, 'notes'), { recursive: true });+ try {+ await registerLocalWriter(engine, 'cli');+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [root, SOURCE]);+ const binding = await claimWorktree(engine, SOURCE, root, localHostId());+ const files: string[] = [];+ for (const slug of [...TARGETS, UNTOUCHED]) {+ const text = slug === UNTOUCHED ? 'Exact untouched bytes.' : body(slug);+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: text }, { sourceId: SOURCE });+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text }], { sourceId: SOURCE });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: SOURCE }))!;+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));+ files.push(`${slug}.md`);+ }+ durableGitRepo(root, files);+ const ctx: OperationContext = { engine, remote: false, sourceId: SOURCE, config: { engine: engine.kind, embedding_disabled: false }, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } };+ const fact = await engine.insertFact({ fact: CLAIM, source: 'synthetic', visibility: 'world' }, { source_id: SOURCE });+ const authority = await submissionAuthority(ctx, 'forget', SOURCE, binding.source_incarnation, TARGETS[0]);+ const request = await admitWrite(engine, { authority, principal: authority.principal, operation: 'forget', sourceId: SOURCE,+ sourceIncarnation: binding.source_incarnation, slug: TARGETS[0], pageId: null, requestId: randomUUID(),+ intent: { id: fact.id }, callerIntent: { id: fact.id }, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ await engine.transaction(async tx => {+ await recordFactWithdrawal(tx, fact.id, SOURCE, false, { requestId: request.id });+ await completeWrite(tx, request, 'committed', { status: 'forgotten' });+ });+ await run({ engine, root, ctx, request: { id: request.id, request_id: request.request_id } });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++/** Rebuilds and seals the text projection of every listed page whose projection the withdrawal invalidated. */+export async function rebuildProjections(engine: BrainEngine, slugs = TARGETS): Promise<void> {+ for (const slug of slugs) {+ const prepared = await readProjectionSnapshot(engine, slug, SOURCE, { allowUnsealed: true });+ if (!prepared || prepared.snapshot.page.text_projection_revision === prepared.snapshot.revision) continue;+ await installPageProjection(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: prepared.snapshot.page.compiled_truth }], { seal: true });+ }+}++/** Makes every unfinished effect due now. */+export async function due(engine: BrainEngine): Promise<void> {+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE state IN ('queued','running')");+ });+}++/**+ * Runs `passes` effect passes (limit 20 each), every effect due before each, with the given embedding stub; the+ * projections a withdrawal invalidated are rebuilt first unless `projections` is false (an archived source refuses them).+ */+export async function drain(engine: BrainEngine, passes: number, opts: { embed?: Embed; config?: GBrainConfig; projections?: boolean } = {}): Promise<void> {+ for (let i = 0; i < passes; i++) {+ await due(engine);+ if (opts.projections !== false) await rebuildProjections(engine);+ await runPersistenceEffects(engine, opts.config ?? { engine: engine.kind, embedding_disabled: false },+ { hostId: localHostId(), limit: 20, embedding: { signature: SIGNATURE, model: MODEL, embed: opts.embed ?? embedAll } });+ }+}++/** The outermost transactions' lockPageKeys throws error() whenever the keys include a listed slug; returns the restore. */+export function failLocks(engine: BrainEngine, slugs: Set<string>, error: () => unknown): () => void {+ const original = engine.transaction;+ engine.transaction = (async function (this: BrainEngine, fn: (tx: BrainEngine) => Promise<unknown>, opts?: unknown) {+ if (this !== engine) return original.call(this, fn, opts as never);+ return original.call(engine, async (tx: BrainEngine) => {+ const real = tx.lockPageKeys;+ tx.lockPageKeys = (async (keys: ReadonlyArray<{ slug: string }>, ...rest: unknown[]) => {+ if (keys.some(key => slugs.has(key.slug))) throw error();+ return (real as (...a: unknown[]) => Promise<unknown>).call(tx, keys, ...rest);+ }) as BrainEngine['lockPageKeys'];+ try { return await fn(tx); } finally { delete (tx as { lockPageKeys?: unknown }).lockPageKeys; }+ }, opts as never);+ }) as BrainEngine['transaction'];+ return () => { engine.transaction = original; };+}++/** Runs `n` effect passes of a managed brain (no embedding stub), every effect due before each. */+export async function passes(engine: BrainEngine, config: GBrainConfig, n: number): Promise<void> {+ for (let i = 0; i < n; i++) {+ await due(engine);+ await runPersistenceEffects(engine, config, { hostId: localHostId(), limit: 20 });+ }+}++export interface EffectRow { id: string; kind: string; state: string; error_code: string | null; attempts: number; data: Record<string, any>; outcome: Record<string, any> | null }++export async function effectsOf(engine: BrainEngine, requestId: string): Promise<Record<string, EffectRow>> {+ const rows = await engine.executeRaw<EffectRow>('SELECT id::text AS id,kind,state,error_code,attempts,data,outcome FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind', [requestId]);+ return Object.fromEntries(rows.map(row => [row.kind, { ...row, attempts: Number(row.attempts) }]));+}++/** Files Git has committed since the seed commit. */+export function committedSinceSeed(root: string): string[] {+ return git(root, 'log', '--name-only', '--pretty=format:', 'HEAD', '--not', git(root, 'rev-list', '--max-parents=0', 'HEAD').trim())+ .split('\n').filter(Boolean);+}++export async function embeddedPages(engine: BrainEngine): Promise<string[]> {+ const rows = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT p.slug FROM pages p JOIN content_chunks c ON c.page_id=p.id+ WHERE p.source_id=$1 AND c.embedding IS NOT NULL AND c.embedded_at IS NOT NULL ORDER BY p.slug`, [SOURCE]);+ return rows.map(row => row.slug);+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 6b437b9f9d..a9c669df7a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -220,6 +220,10 @@ test/page-purge-journal-timeout-6511.test.tstest/page-state-engine.test.tstest/pathological/a1-links-extract.test.tstest/pathological/a10-global-maintenance-stamp.test.ts+test/pathological/a11-effect-retry-budget.test.ts+test/pathological/a12-withdrawal-mirror-gate.test.ts+test/pathological/a13-embedding-target-park.test.ts+test/pathological/a15-deactivate-exits.test.tstest/pathological/a21-facts-expire-deleted.test.tstest/pathological/a22-consolidate-buckets.test.tstest/pathological/a23-patterns-grounding.test.ts