Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(persistence): lp-b/lp-c transient retry budget and publication ceiling cases; write-interrupted on the transient budget
garrytan910ae846f093
diff --git a/test/pathological/lp-b-transient-retry-budget.test.ts b/test/pathological/lp-b-transient-retry-budget.test.tsnew file mode 100644index 0000000000..04beb00f3f--- /dev/null+++ b/test/pathological/lp-b-transient-retry-budget.test.ts@@ -0,0 +1,240 @@+/**+ * Large-pages hardening (b): a managed write's transient interruptions have their own retry budget.+ *+ * 1. Protects: a statement the database ended with SQLSTATE 57014 (a statement timeout or cancel under load) is load,+ * not a property of the write. It is counted in `transient_interruptions` against `persistence.max_transient_retries`+ * (default 5), never in `preparation_attempts`, and each one schedules the next claim at `next_attempt_at` with a+ * bounded exponential backoff (1 s, 2 s, 4 s, 8 s, then 15 s); a claim never takes the row before it. The interruption+ * after the last retry ends the request `failed`/`write_interrupted` (the receipt names the interruptions, the retry+ * limit, the key, the cause and the SQLSTATE), so the loop is bounded. Preparations cut off at their deadline keep the+ * content-class `persistence.max_preparation_attempts` budget, and contention (55P03, 40001, 40P01) or a lost+ * connection (CONNECTION_CLOSED, 57P01) is never counted. `persistence.preparation_deadlines false` turns the counting+ * and the backoff off with the deadlines.+ * 2. Fails when: a 57014 charges `preparation_attempts` (v0.60.299.0: two statement cancels, at preparation or at+ * publication, end a request `write_interrupted` for good), when the backoff is a sleep holding the claim instead of+ * the request's own schedule, when the transient budget is unbounded, or when contention starts being counted.+ * 3. Existing coverage: test/persistence-write-interrupted.test.ts pins the charge's atomicity with the claim release,+ * the shared group read charged once, the sync hold and the recovery route; it bounded 57014 by+ * `max_preparation_attempts` until this change.+ * 4. Semantic injection: installFaultHook throws an error carrying the SQLSTATE at `consumer:preparing` (preparation) or+ * `publication:before_commit` (inside the publication transaction) for the claims a test names. At+ * `persistence:interruption_charged` (after the charge commits) the hook reads the scheduled delay+ * (`next_attempt_at - updated_at`, both the charging transaction's now()) and then brings the row's next attempt+ * forward, so the test counts claims, never wall time. A guard far above every bound stops injecting, so an unbounded+ * loop ends committed (and fails the claim-count assertion) instead of hanging. PGLite always; Postgres with DATABASE_URL.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';+import { hasClaimableWrite } from '../../src/core/persistence/journal.ts';+import { readHeadBlockers } from '../../src/core/persistence/head-blocker.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import * as budget from '../../src/core/persistence/preparation-budget.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const op = (name: string) => operations.find(o => o.name === name)!;+const interruption = (code: string) => Object.assign(new Error(code === '57014' ? 'canceling statement due to statement timeout' : `database interruption ${code}`), { code });+const deadlineCut = () => Object.assign(new Error('preparation budget reached (probe)'), { code: 'preparation_deadline' });+const page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;+/** Far above every bound: an unbounded loop stops being interrupted here and commits, failing the claim count. */+const GUARD = 30;+const BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];+const TRANSIENT_KEY = 'persistence.max_transient_retries';++test('persistence.max_transient_retries is a validated preparation-budget key (0 to 20, default 5)', () => {+ expect((budget.PREPARATION_BUDGET_CONFIG_KEYS as readonly string[]).includes(TRANSIENT_KEY)).toBe(true);+ expect(budget.validatePreparationConfigValue(TRANSIENT_KEY, '0')).toBeNull();+ expect(budget.validatePreparationConfigValue(TRANSIENT_KEY, '20')).toBeNull();+ expect(budget.validatePreparationConfigValue(TRANSIENT_KEY, '21')).toMatchObject({ message: expect.stringContaining('from 0 to 20'), example: '5' });+ expect(budget.validatePreparationConfigValue(TRANSIENT_KEY, '-1')?.message).toContain('whole number');+ expect((budget.resolvePreparationPolicy(new Map([[TRANSIENT_KEY, '99']])) as unknown as Record<string, number>).transientRetries).toBe(5);+});++type Row = { state: string; error_code: string | null; error_message: string | null; error_detail: Record<string, unknown> | null;+ preparation_attempts: number; transient_interruptions?: number; next_attempt_at?: string | null };++for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}] lp-b: transient interruptions have their own bounded retry budget`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const home = mkdtempSync(join(tmpdir(), `gbrain-lp-b-${backend}-`));+ let n = 0;+ const context = (): OperationContext => ({ engine, config: { engine: backend, embedding_disabled: true } as never,+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' });+ const call = (params: Record<string, unknown>) => withEnv({ GBRAIN_HOME: home },+ () => op('put_page').handler(context(), { wait_ms: 30_000, ...params })) as Promise<Record<string, any>>;+ // Read whole (to_jsonb), so a column this build added reads as absent on a build without it instead of failing the read.+ const row = async (requestId: string): Promise<Row> => (await engine.executeRaw<{ j: Row | string }>(+ 'SELECT to_jsonb(r) AS j FROM persistence_requests r WHERE request_id=$1::uuid', [requestId])).map(r => typeof r.j === 'string' ? JSON.parse(r.j) as Row : r.j)[0]!;++ /**+ * `at` names where claim k (1-based, counted at consumer:preparing) is interrupted, or null to let it run. Records each+ * claim's counters as it began, and each charged interruption's scheduled delay, then brings that attempt forward.+ */+ function inject(requestId: string, at: (claim: number) => { point: 'consumer:preparing' | 'publication:before_commit'; error: () => Error } | null) {+ const seen = { claims: 0, transient: [] as number[], preparation: [] as number[], delays: [] as number[] };+ installFaultHook(async (point, detail) => {+ if (detail.requestId !== requestId) return;+ if (point === 'consumer:preparing') {+ seen.claims++;+ const current = await row(requestId);+ seen.transient.push(current.transient_interruptions ?? 0);+ seen.preparation.push(current.preparation_attempts);+ }+ if (point === 'persistence:interruption_charged') {+ const [charged] = await engine.executeRaw<{ state: string; delay_ms: number | string | null }>(`SELECT state,+ round(extract(epoch FROM (next_attempt_at-updated_at))*1000) AS delay_ms FROM persistence_requests WHERE request_id=$1::uuid`, [requestId]).catch(() => []);+ if (charged?.state === 'queued' && charged.delay_ms !== null) seen.delays.push(Number(charged.delay_ms));+ await engine.executeRaw("UPDATE persistence_requests SET next_attempt_at=now() WHERE request_id=$1::uuid AND state='queued'", [requestId]).catch(() => undefined);+ return;+ }+ const fault = seen.claims <= GUARD ? at(seen.claims) : null;+ if (fault && fault.point === point) throw fault.error();+ });+ return seen;+ }++ beforeAll(async () => {+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ else { const pg = await isolatedPersistencePostgres(databaseUrl!); engine = pg.engine; closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine); await engine.disconnect(); await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+ }, 60_000);+ afterEach(async () => {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("DELETE FROM config WHERE key IN ('persistence.max_transient_retries','persistence.max_preparation_attempts','persistence.preparation_deadlines')");+ resetWriteSwitches();+ });++ test('a write whose preparation hits 57014 three times, more than max_preparation_attempts (2), is retried with backoff and commits', async () => {+ const slug = `db/prep-cancel-${++n}`, requestId = randomUUID();+ const seen = inject(requestId, claim => claim <= 3 ? { point: 'consumer:preparing', error: () => interruption('57014') } : null);+ expect(await call({ slug, content: page(`Prep cancel ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(seen.claims).toBe(4);+ expect(seen.transient).toEqual([0, 1, 2, 3]);+ expect(seen.preparation).toEqual([0, 0, 0, 0]);+ expect(seen.delays).toEqual(BACKOFF_MS.slice(0, 3));+ expect(await row(requestId)).toMatchObject({ state: 'committed', preparation_attempts: 0 });+ }, 180_000);++ test('a write cancelled at every publication ends write_interrupted after exactly max_transient_retries (5) retries, with the backoff scheduled on the request', async () => {+ const slug = `db/always-${++n}`, requestId = randomUUID();+ const seen = inject(requestId, () => ({ point: 'publication:before_commit', error: () => interruption('57014') }));+ const outcome = await call({ slug, content: page(`Always ${n}`), request_id: requestId }).catch(error => error as { code?: string });+ installFaultHook(undefined);+ expect(seen.claims).toBe(6);+ expect((outcome as { code?: string }).code).toBe('write_interrupted');+ expect(seen.transient).toEqual([0, 1, 2, 3, 4, 5]);+ expect(seen.preparation).toEqual([0, 0, 0, 0, 0, 0]);+ // Bounded exponential: each delay doubles up to the 15 s ceiling and is the request's next_attempt_at, not a held claim.+ expect(seen.delays).toEqual(BACKOFF_MS);+ const failed = await row(requestId);+ expect(failed).toMatchObject({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 0, transient_interruptions: 6 });+ expect(failed.error_detail).toMatchObject({ origin: 'database_interruption', cause: 'statement_cancel', sqlstate: '57014', attempts: 6, limit: 5,+ limit_key: TRANSIENT_KEY });+ expect(failed.error_message).toContain('6 time(s)');+ expect(failed.error_message).toContain(`${TRANSIENT_KEY} (5)`);+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).toBeNull();+ const receipt = await withEnv({ GBRAIN_HOME: home }, () => op('get_write_request').handler(context(), { request_id: requestId })) as Record<string, unknown>;+ expect(receipt).toMatchObject({ state: 'failed', write_error: 'write_interrupted' });+ // The source keeps moving.+ expect(await call({ slug: `db/after-${n}`, content: page(`After ${n}`), request_id: randomUUID() })).toMatchObject({ state: 'committed' });+ }, 180_000);++ test('the backoff holds no claim: until next_attempt_at the row is not claimable and its head blocker says transient_backoff; then it is claimed and commits', async () => {+ const slug = `db/held-off-${++n}`, requestId = randomUUID();+ const observed: { blocker?: unknown; claimable?: boolean; reclaimedAfterBackoff?: boolean } = {};+ let claims = 0;+ installFaultHook(async (point, detail) => {+ if (detail.requestId !== requestId) return;+ if (point === 'consumer:preparing' && ++claims === 2) {+ // The second claim's own statement time is at or after the scheduled attempt.+ const [due] = await engine.executeRaw<{ due: boolean }>('SELECT updated_at>=next_attempt_at AS due FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ observed.reclaimedAfterBackoff = due?.due === true;+ }+ if (point === 'publication:before_commit' && claims === 1) throw interruption('57014');+ if (point === 'persistence:interruption_charged') {+ const [queued] = await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ const hostId = localHostId();+ observed.claimable = await hasClaimableWrite(engine, hostId);+ const read = (await readHeadBlockers(engine, [queued!.id], hostId)).get(queued!.id);+ observed.blocker = read?.status === 'blocked' ? read.blocker : read;+ }+ });+ expect(await call({ slug, content: page(`Held off ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(claims).toBe(2);+ expect(observed.claimable).toBe(false);+ expect(observed.blocker).toMatchObject({ predicate: 'transient_backoff', ids: [requestId], intervention: false });+ expect(observed.reclaimedAfterBackoff).toBe(true);+ }, 180_000);++ test('the cap follows persistence.max_transient_retries: 1 retry ends the write at its second interruption', async () => {+ await engine.setConfig(TRANSIENT_KEY, '1');+ resetWriteSwitches();+ const slug = `db/cap-${++n}`, requestId = randomUUID();+ const seen = inject(requestId, () => ({ point: 'publication:before_commit', error: () => interruption('57014') }));+ const outcome = await call({ slug, content: page(`Cap ${n}`), request_id: requestId }).catch(error => error as { code?: string });+ installFaultHook(undefined);+ expect(seen.claims).toBe(2);+ expect((outcome as { code?: string }).code).toBe('write_interrupted');+ expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'write_interrupted', transient_interruptions: 2,+ error_detail: expect.objectContaining({ attempts: 2, limit: 1 }) });+ }, 180_000);++ test('statement cancels never spend the content budget: a deadline cut-off plus three 57014s still commits', async () => {+ const slug = `db/mixed-${++n}`, requestId = randomUUID();+ const seen = inject(requestId, claim => claim === 1 ? { point: 'consumer:preparing', error: deadlineCut }+ : claim <= 4 ? { point: 'publication:before_commit', error: () => interruption('57014') } : null);+ expect(await call({ slug, content: page(`Mixed ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(seen.claims).toBe(5);+ expect(seen.preparation).toEqual([0, 1, 1, 1, 1]);+ expect(seen.transient).toEqual([0, 0, 1, 2, 3]);+ }, 180_000);++ test('content-class counting is unchanged: deadline cut-offs end the write preparation_stalled at max_preparation_attempts, with no transient charge', async () => {+ const slug = `db/deadline-${++n}`, requestId = randomUUID();+ const seen = inject(requestId, () => ({ point: 'consumer:preparing', error: deadlineCut }));+ const outcome = await call({ slug, content: page(`Deadline ${n}`), request_id: requestId }).catch(error => error as { code?: string });+ installFaultHook(undefined);+ expect(seen.claims).toBe(2);+ expect((outcome as { code?: string }).code).toBe('preparation_stalled');+ expect(seen.transient).toEqual([0, 0]);+ expect(seen.delays).toEqual([]);+ expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'preparation_stalled', preparation_attempts: 2, transient_interruptions: 0 });+ }, 180_000);++ for (const code of ['55P03', '40001', '40P01', 'CONNECTION_CLOSED', '57P01']) test(`contention or a lost connection (${code}) is never counted: past both limits the write commits with no backoff`, async () => {+ const slug = `db/contention-${++n}`, requestId = randomUUID();+ const seen = inject(requestId, claim => claim <= 6 ? { point: 'publication:before_commit', error: () => interruption(code) } : null);+ expect(await call({ slug, content: page(`Contention ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(seen.claims).toBe(7);+ expect(seen.transient).toEqual([0, 0, 0, 0, 0, 0, 0]);+ expect(seen.preparation).toEqual([0, 0, 0, 0, 0, 0, 0]);+ expect(seen.delays).toEqual([]);+ expect(await row(requestId)).toMatchObject({ state: 'committed', next_attempt_at: null });+ }, 180_000);++ test('persistence.preparation_deadlines false turns the counting and the backoff off with the deadlines (the pre-#6278 uncounted release)', async () => {+ await engine.setConfig('persistence.preparation_deadlines', 'false');+ resetWriteSwitches();+ const slug = `db/switch-off-${++n}`, requestId = randomUUID();+ const seen = inject(requestId, claim => claim <= 7 ? { point: 'publication:before_commit', error: () => interruption('57014') } : null);+ expect(await call({ slug, content: page(`Switch off ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(seen.claims).toBe(8);+ expect(seen.transient).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);+ expect(seen.delays).toEqual([]);+ }, 180_000);+});diff --git a/test/pathological/lp-c-publication-ceiling-retry.test.ts b/test/pathological/lp-c-publication-ceiling-retry.test.tsnew file mode 100644index 0000000000..4d5e2741be--- /dev/null+++ b/test/pathological/lp-c-publication-ceiling-retry.test.ts@@ -0,0 +1,183 @@+/**+ * Large-pages hardening (c): a publication cancelled at the publication ceiling counts against the transient retry budget.+ *+ * 1. Protects: `boundPublication` cancels a publication that runs past `persistence.publication_ceiling_ms` and its+ * grace. That cancellation (whatever error the cancelled publish then rejects with: a discarded connection, an+ * AbortError, a 57014) is a transient interruption (transient-retry.ts): it is counted in `transient_interruptions`+ * against `persistence.max_transient_retries` and schedules the next claim with the backoff, so a write whose+ * publication overruns the ceiling every time ends `failed`/`write_interrupted` (cause `publication_ceiling`) after+ * the cap instead of being prepared and published again without limit. A single overrun re-prepares and commits. Both+ * publication arms: a database-only page (finishUnpublishedFailure) and a worktree-backed page (the recovery route,+ * which restores the canonical file first; on Postgres the retried publish there surfaces as a bare AbortError).+ * 2. Fails when: the cancelled publication is released as `database_contention` uncounted (v0.60.299.0: the error is a+ * discarded connection, which is never counted), so the claim count grows past the cap; or when the recovery route+ * fails it `storage_error` at once.+ * 3. Existing coverage: test/persistence-publication-deadline.test.ts pins that the ceiling marks, cancels and reports a+ * publication and that a cancelled one commits nothing; it never bounds how often a write is published again.+ * 4. Semantic injection: `_setPublicationTimingForTest` sets a 300 ms ceiling and 50 ms grace; installFaultHook parks the+ * publication at `publication:before_commit` (inside its transaction) past the cancellation and then rejects it as the+ * discarded connection does (`PublicationDeadlineError`, CONNECTION_CLOSED). PGLite cannot cancel a running+ * transaction (its signal is checked only before BEGIN), so the parked body's own rejection stands in for the+ * discard there; on Postgres the signal also discards the connection. The charged hook brings each backoff forward.+ * A guard stops the overruns far above the cap, so an unbounded loop ends committed. PGLite always; Postgres with DATABASE_URL.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import * as publicationDeadline from '../../src/core/persistence/publication-deadline.ts';+import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const op = (name: string) => operations.find(o => o.name === name)!;+const page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;+const CEILING_MS = 300, GRACE_MS = 50;+/** Parked past the ceiling and its grace, when the owner has cancelled the publication. */+const PARK_MS = CEILING_MS + GRACE_MS + 200;+const GUARD = 14;+const discarded = () => Object.assign(new Error('publication_deadline: the publish transaction passed the ceiling and its connection was discarded (CONNECTION_CLOSED)'),+ { name: 'PublicationDeadlineError', code: 'CONNECTION_CLOSED' });+// Optional, so the file still loads (and fails on its assertions, not its import) against a build without the seam.+const setTiming = (timing: { ceilingMs: number; graceMs: number } | undefined) =>+ (publicationDeadline as { _setPublicationTimingForTest?: (t: typeof timing) => void })._setPublicationTimingForTest?.(timing);++type Row = { state: string; error_code: string | null; error_message: string | null; error_detail: Record<string, unknown> | null;+ preparation_attempts: number; transient_interruptions?: number; recovery: unknown };++for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}] lp-c: a publication cancelled at the ceiling is a counted transient interruption`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const home = mkdtempSync(join(tmpdir(), `gbrain-lp-c-${backend}-`));+ let n = 0;+ const context = (sourceId: string): OperationContext => ({ engine, config: { engine: backend, embedding_disabled: true } as never,+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId });+ const call = (params: Record<string, unknown>, sourceId = 'default') => withEnv({ GBRAIN_HOME: home },+ () => op('put_page').handler(context(sourceId), { wait_ms: 30_000, ...params })) as Promise<Record<string, any>>;+ const row = async (requestId: string): Promise<Row> => (await engine.executeRaw<{ j: Row | string }>(+ 'SELECT to_jsonb(r) AS j FROM persistence_requests r WHERE request_id=$1::uuid', [requestId])).map(r => typeof r.j === 'string' ? JSON.parse(r.j) as Row : r.j)[0]!;++ /** Every publication of claims `overruns(k)` parks past the ceiling and then fails as a discarded connection. */+ function overrun(requestId: string, overruns: (claim: number) => boolean) {+ const seen = { claims: 0, transient: [] as number[], preparation: [] as number[] };+ installFaultHook(async (point, detail) => {+ if (detail.requestId !== requestId) return;+ if (point === 'consumer:preparing') {+ seen.claims++;+ const current = await row(requestId);+ seen.transient.push(current.transient_interruptions ?? 0);+ seen.preparation.push(current.preparation_attempts);+ return;+ }+ if (point === 'persistence:interruption_charged' || point === 'persistence:recovery_interruption_charged') {+ await engine.executeRaw('UPDATE persistence_requests SET next_attempt_at=now() WHERE request_id=$1::uuid', [requestId]).catch(() => undefined);+ return;+ }+ if (point === 'publication:before_commit' && seen.claims <= GUARD && overruns(seen.claims)) {+ await new Promise(resolve => setTimeout(resolve, PARK_MS));+ throw discarded();+ }+ });+ return seen;+ }++ beforeAll(async () => {+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ else { const pg = await isolatedPersistencePostgres(databaseUrl!); engine = pg.engine; closePostgres = pg.close; }+ setTiming({ ceilingMs: CEILING_MS, graceMs: GRACE_MS });+ }, 120_000);+ afterAll(async () => {+ setTiming(undefined);+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine); await engine.disconnect(); await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+ }, 60_000);+ afterEach(async () => {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("DELETE FROM config WHERE key IN ('persistence.max_transient_retries')");+ resetWriteSwitches();+ });++ test('a publication that overruns the ceiling every time ends write_interrupted after exactly max_transient_retries (5) retries', async () => {+ const slug = `db/overrun-${++n}`, requestId = randomUUID();+ const seen = overrun(requestId, () => true);+ const outcome = await call({ slug, content: page(`Overrun ${n}`), request_id: requestId }).catch(error => error as { code?: string });+ installFaultHook(undefined);+ expect(seen.claims).toBe(6);+ expect((outcome as { code?: string }).code).toBe('write_interrupted');+ expect(seen.transient).toEqual([0, 1, 2, 3, 4, 5]);+ expect(seen.preparation).toEqual([0, 0, 0, 0, 0, 0]);+ const failed = await row(requestId);+ expect(failed).toMatchObject({ state: 'failed', error_code: 'write_interrupted', transient_interruptions: 6, preparation_attempts: 0 });+ expect(failed.error_detail).toMatchObject({ origin: 'database_interruption', cause: 'publication_ceiling', attempts: 6, limit: 5 });+ expect(failed.error_message).toContain('persistence.publication_ceiling_ms');+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).toBeNull();+ }, 180_000);++ test('a single overrun is counted once, re-prepares and commits', async () => {+ const slug = `db/overrun-once-${++n}`, requestId = randomUUID();+ const seen = overrun(requestId, claim => claim === 1);+ expect(await call({ slug, content: page(`Once ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(seen.claims).toBe(2);+ expect(seen.transient).toEqual([0, 1]);+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).not.toBeNull();+ }, 180_000);++ describe('worktree-backed page (the recovery route)', () => {+ let brainDir: string;+ const sourceId = `lpc-${randomUUID().slice(0, 8)}`;+ beforeAll(async () => {+ brainDir = mkdtempSync(join(home, 'brain-'));+ await disposePersistenceConsumer(engine);+ 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, brainDir]);+ await withEnv({ GBRAIN_HOME: home }, () => claimWorktree(engine, sourceId, brainDir));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ _resetWriteThroughCacheForTest();+ });+ afterAll(async () => { await disposePersistenceConsumer(engine); _resetWriteThroughCacheForTest(); });++ test('an overrun on every publication ends write_interrupted after the cap with the canonical file restored', async () => {+ await engine.setConfig('persistence.max_transient_retries', '2');+ resetWriteSwitches();+ const slug = `wt/overrun-${++n}`;+ expect(await call({ slug, content: page(`Prior ${n}`), request_id: randomUUID() }, sourceId)).toMatchObject({ state: 'committed', write_through: { written: true } });+ const path = join(brainDir, `${slug}.md`);+ const bytes = readFileSync(path);+ const before = await engine.readPageSnapshot(slug, { sourceId });+ const requestId = randomUUID();+ const seen = overrun(requestId, () => true);+ const outcome = await call({ slug, content: page(`Next ${n}`), request_id: requestId, expected_revision: before!.revision }, sourceId).catch(error => error as { code?: string });+ installFaultHook(undefined);+ expect(seen.claims).toBe(3);+ expect((outcome as { code?: string }).code).toBe('write_interrupted');+ expect(seen.transient).toEqual([0, 1, 2]);+ expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'write_interrupted', transient_interruptions: 3, recovery: null,+ error_detail: expect.objectContaining({ cause: 'publication_ceiling', attempts: 3, limit: 2 }) });+ expect(readFileSync(path).equals(bytes)).toBe(true);+ expect(await engine.readPageSnapshot(slug, { sourceId })).toEqual(before);+ }, 180_000);++ test('a single overrun is retried, never a terminal storage_error (on Postgres the retried publish surfaces as a bare AbortError), and commits', async () => {+ const slug = `wt/overrun-once-${++n}`;+ expect(await call({ slug, content: page(`Prior ${n}`), request_id: randomUUID() }, sourceId)).toMatchObject({ state: 'committed' });+ const before = await engine.readPageSnapshot(slug, { sourceId });+ const requestId = randomUUID();+ const seen = overrun(requestId, claim => claim === 1);+ expect(await call({ slug, content: page(`Next ${n}`), request_id: requestId, expected_revision: before!.revision }, sourceId)).toMatchObject({ state: 'committed' });+ expect(seen.claims).toBe(2);+ expect(seen.transient).toEqual([0, 1]);+ expect(readFileSync(join(brainDir, `${slug}.md`), 'utf8')).toContain(`Next ${n}`);+ }, 180_000);+ });+});diff --git a/test/persistence-write-interrupted.test.ts b/test/persistence-write-interrupted.test.tsindex 1d288bf605..eac7c784fb 100644--- a/test/persistence-write-interrupted.test.ts+++ b/test/persistence-write-interrupted.test.ts@@ -2,10 +2,12 @@* Flip lane C (4): a write whose statements the database keeps ending is failed after a bound, not prepared forever.** 1. Protects: a statement the database ended while it stayed up (57014, a statement timeout or cancel of this write's- * own work) is charged to the request's preparation_attempts like a preparation cut off at its deadline; at- * persistence.max_preparation_attempts the request ends `failed`/`write_interrupted` (the receipt names the- * attempts, the limit and the SQLSTATE) instead of being released as `database_contention` and prepared again. A- * single interruption still re-prepares and commits. Contention with other transactions (55P03 lock timeout, 40P01+ * own work) is charged to the request's transient budget (transient_interruptions; since large-pages hardening (b)+ * it no longer spends preparation_attempts); past persistence.max_transient_retries the request ends+ * `failed`/`write_interrupted` (the receipt names the interruptions, the retry limit and the SQLSTATE) instead of+ * being released as `database_contention` and prepared again. A single interruption still re-prepares and commits.+ * These cases set the retry limit low; test/pathological/lp-b-transient-retry-budget.test.ts pins the default (5)+ * and the backoff. Contention with other transactions (55P03 lock timeout, 40P01* deadlock) and a dropped connection or restarting database (CONNECTION_CLOSED, 57P01) are never counted, so a* Postgres restart never fails a write.* Both publication arms: a database-only page (released or failed in place) and a worktree-backed page (the@@ -109,7 +111,8 @@ test('write_interrupted is a write error code: a failed source lifecycle names iexpect(thrown).toMatchObject({ code: 'write_interrupted', writeError: 'write_interrupted', writeRequest: { state: 'failed' } });});-type Row = { state: string; error_code: string | null; error_message: string | null; error_detail: Record<string, unknown> | null; preparation_attempts: number; has_recovery: boolean };+type Row = { state: string; error_code: string | null; error_message: string | null; error_detail: Record<string, unknown> | null; preparation_attempts: number;+ transient_interruptions: number; has_recovery: boolean };for (const backend of testBackends()) describe(`[${backend}] transient publication failures are bounded`, () => {let engine: BrainEngine;@@ -120,13 +123,13 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatilogger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId });const call = (params: Record<string, unknown>, sourceId = 'default') => withEnv({ GBRAIN_HOME: home },() => op('put_page').handler(context(sourceId), { wait_ms: 20_000, ...params })) as Promise<Record<string, any>>;- const row = async (requestId: string): Promise<Row> => (await engine.executeRaw<Row>(`SELECT state,error_code,error_message,error_detail,preparation_attempts,+ const row = async (requestId: string): Promise<Row> => (await engine.executeRaw<Row>(`SELECT state,error_code,error_message,error_detail,preparation_attempts,transient_interruptions,recovery IS NOT NULL AS has_recovery FROM persistence_requests WHERE request_id=$1::uuid`, [requestId]))[0]!;/*** Every publication of the request's claims numbered in `failing` (1-based, counted at `consumer:preparing`) throws* `error()` at its before_commit seam, inside the publication transaction. Returns the claim count and the request's- * preparation_attempts as each claim began (a commit resets the counter, so it is read while the request runs).+ * transient_interruptions as each claim began (read while the request runs).*/function interrupt(requestId: string, failing: (claim: number) => boolean, error: () => Error) {const claims = { n: 0, attempts: [] as number[] };@@ -134,7 +137,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiif (detail.requestId !== requestId) return;if (point === 'consumer:preparing') {claims.n++;- claims.attempts.push((await row(requestId)).preparation_attempts);+ claims.attempts.push((await row(requestId)).transient_interruptions);return;}if (point === 'publication:before_commit' && failing(claims.n)) throw error();@@ -154,11 +157,15 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiafterEach(async () => {installFaultHook(undefined);await disposePersistenceConsumer(engine);- await engine.executeRaw("DELETE FROM config WHERE key='persistence.max_preparation_attempts'");+ await engine.executeRaw("DELETE FROM config WHERE key IN ('persistence.max_preparation_attempts','persistence.max_transient_retries')");resetWriteSwitches();});- test('a write cancelled at every publication ends write_interrupted after exactly max_preparation_attempts preparations', async () => {+ /** A low retry limit keeps these cases to a few claims; the default and the backoff are lp-b's. */+ const retries = async (limit: number) => { await engine.setConfig('persistence.max_transient_retries', String(limit)); resetWriteSwitches(); };++ test('a write cancelled at every publication ends write_interrupted after exactly max_transient_retries retries', async () => {+ await retries(1);const slug = `db/interrupted-${++n}`, requestId = randomUUID();const claims = interrupt(requestId, () => true, () => interruption('57014'));const outcome = await call({ slug, content: page(`Interrupted ${n}`), request_id: requestId }).catch(error => error as { code?: string });@@ -166,10 +173,10 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiexpect(claims.n).toBe(2);expect((outcome as { code?: string }).code).toBe('write_interrupted');const failed = await row(requestId);- expect(failed).toMatchObject({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 2, has_recovery: false });+ expect(failed).toMatchObject({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 0, transient_interruptions: 2, has_recovery: false });expect(failed.error_message).toContain('2 time(s)');expect(failed.error_message).toContain('57014');- expect(failed.error_detail).toMatchObject({ origin: 'database_interruption', attempts: 2, limit: 2, sqlstate: '57014' });+ expect(failed.error_detail).toMatchObject({ origin: 'database_interruption', attempts: 2, limit: 1, sqlstate: '57014' });expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).toBeNull();// The receipt names the code and its diagnostic, like every other write error.const receipt = await withEnv({ GBRAIN_HOME: home }, () => op('get_write_request').handler(context(), { request_id: requestId })) as Record<string, unknown>;@@ -209,6 +216,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiawait engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);await claimWorktree(engine, id, root);await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await retries(1);// Every publication of a request for page `a` of this source has its statement cancelled. The request's page is read// as it is claimed (outside any transaction: PGLite has one connection, which the publication holds).const pageA = new Set<string>();@@ -226,9 +234,9 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiexpect(await engine.readPageSnapshot('b', { sourceId: id })).not.toBeNull();expect(await engine.readPageSnapshot('a', { sourceId: id })).toBeNull();// One request for `a`, never re-frozen in place: its two preparations, then the hold.- const requests = async () => engine.executeRaw<{ state: string; error_code: string | null; preparation_attempts: number }>(- "SELECT state,error_code,preparation_attempts FROM persistence_requests WHERE source_id=$1 AND slug='a' ORDER BY sequence", [id]);- expect(await requests()).toEqual([{ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 2 }]);+ const requests = async () => engine.executeRaw<{ state: string; error_code: string | null; preparation_attempts: number; transient_interruptions: number }>(+ "SELECT state,error_code,preparation_attempts,transient_interruptions FROM persistence_requests WHERE source_id=$1 AND slug='a' ORDER BY sequence", [id]);+ expect(await requests()).toEqual([{ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 0, transient_interruptions: 2 }]);const writerStatus = ['gbrain', 'sources', 'writer', 'status', '--source', id, '--json'];const held = await readSyncStatus(engine, id);expect(held.last_error).toBeNull();@@ -254,7 +262,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiif (detail.requestId !== requestId) return;if (point === 'consumer:preparing') {claims.n++;- claims.attempts.push((await row(requestId)).preparation_attempts);+ claims.attempts.push((await row(requestId)).transient_interruptions);if (claims.n === 1) throw interruption('57014');}// The owner dies here: nothing after the seam runs, and the claim it held lapses.@@ -275,7 +283,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiinstallFaultHook(async (point, detail) => {if (detail.requestId !== requestId || point !== 'consumer:preparing') return;claims.n++;- claims.attempts.push((await row(requestId)).preparation_attempts);+ claims.attempts.push((await row(requestId)).transient_interruptions);if (claims.n <= 3) throw shared;});expect(await call({ slug, content: page(`Shared ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });@@ -297,22 +305,21 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati});afterAll(async () => { await disposePersistenceConsumer(engine); _resetWriteThroughCacheForTest(); });- test('the limit follows max_preparation_attempts, and the recovery route restores the canonical file before the failure', async () => {+ test('the limit follows max_transient_retries, and the recovery route restores the canonical file before the failure', async () => {const slug = `wt/interrupted-${++n}`;expect(await call({ slug, content: page(`Prior ${n}`), request_id: randomUUID() }, sourceId)).toMatchObject({ state: 'committed', write_through: { written: true } });const path = join(brainDir, `${slug}.md`);const bytes = readFileSync(path);const before = await engine.readPageSnapshot(slug, { sourceId });- await engine.setConfig('persistence.max_preparation_attempts', '3');- resetWriteSwitches();+ await retries(2);const requestId = randomUUID();const claims = interrupt(requestId, () => true, () => interruption('57014'));const outcome = await call({ slug, content: page(`Next ${n}`), request_id: requestId, expected_revision: before!.revision }, sourceId).catch(error => error as { code?: string });installFaultHook(undefined);expect(claims.n).toBe(3);expect((outcome as { code?: string }).code).toBe('write_interrupted');- expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 3, has_recovery: false,- error_detail: expect.objectContaining({ attempts: 3, limit: 3, sqlstate: '57014' }) });+ expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 0, transient_interruptions: 3, has_recovery: false,+ error_detail: expect.objectContaining({ attempts: 3, limit: 2, sqlstate: '57014' }) });expect(existsSync(path)).toBe(true);expect(readFileSync(path).equals(bytes)).toBe(true);expect(await engine.readPageSnapshot(slug, { sourceId })).toEqual(before);@@ -331,7 +338,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiif (detail.requestId !== requestId) return;if (point === 'consumer:preparing') {claims.n++;- claims.attempts.push((await row(requestId)).preparation_attempts);+ claims.attempts.push((await row(requestId)).transient_interruptions);}if (point === 'publication:before_commit' && claims.n === 1) throw interruption('57014');// The owner dies here: the charge has committed, the request is not marked recovering, and its claim lapses.@@ -339,7 +346,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati});const pending = call({ slug, content: page(`Next ${n}`), request_id: requestId, expected_revision: before!.revision }, sourceId).catch(error => error as { code?: string });while (!crashed) await new Promise(resolve => setTimeout(resolve, 20));- expect(crashed).toMatchObject({ state: 'running', preparation_attempts: 1, has_recovery: true });+ expect(crashed).toMatchObject({ state: 'running', preparation_attempts: 0, transient_interruptions: 1, has_recovery: true });await engine.executeRaw("UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE request_id=$1::uuid AND state='running'", [requestId]);expect(await pending).toMatchObject({ state: 'committed' });expect(claims.n).toBe(2);@@ -353,6 +360,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatitest('a group\'s shared read the database cancels every time ends bounded: each cancelled read is charged to one member, and every member ends write_interrupted', async () => withEnv({ GBRAIN_HOME: home,OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {await registerLocalWriter(engine, 'cli');+ await retries(1);const dir = `shared-${++n}`;mkdirSync(join(brainDir, dir), { recursive: true });const files = ['a', 'b', 'c'].map(name => {@@ -368,12 +376,12 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati});const settled = await importManagedFiles(engine, files, { sourceId, noEmbed: true });installFaultHook(undefined);- const rows = await engine.executeRaw<{ slug: string; state: string; error_code: string | null; preparation_attempts: number }>(- `SELECT slug,state,error_code,preparation_attempts FROM persistence_requests WHERE source_id=$1 AND slug LIKE $2 ORDER BY slug`, [sourceId, `${dir}/%`]);+ const rows = await engine.executeRaw<{ slug: string; state: string; error_code: string | null; transient_interruptions: number }>(+ `SELECT slug,state,error_code,transient_interruptions FROM persistence_requests WHERE source_id=$1 AND slug LIKE $2 ORDER BY slug`, [sourceId, `${dir}/%`]);// Each cancelled read is charged to exactly one member (the first that settles with it), so the reads stop once every- // member has used its max_preparation_attempts (2): 3 members x 2.+ // member has used its max_transient_retries (1) and been interrupted once more: 3 members x 2.expect(cancelled).toBe(3 * 2);- expect(rows).toEqual(['a', 'b', 'c'].map(name => ({ slug: `${dir}/${name}`, state: 'failed', error_code: 'write_interrupted', preparation_attempts: 2 })));+ expect(rows).toEqual(['a', 'b', 'c'].map(name => ({ slug: `${dir}/${name}`, state: 'failed', error_code: 'write_interrupted', transient_interruptions: 2 })));expect(settled.map(result => result.status === 'rejected' ? (result.reason as { code?: string }).code : 'ok')).toEqual(['write_interrupted', 'write_interrupted', 'write_interrupted']);}), 120_000);});