Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(retention): one expired source's failed delete no longer aborts the unmanaged sweep (GBRA-130 A-50)
garrytanee52d904afd9
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex a809f15e42..ae36528c48 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plus `oauthClientCount` — OAuth clients whose `source_id` references it. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). FK-RESTRICT lifecycle: `clientsReferencingSource(engine, sourceId)` lists ALL physical OAuth-client rows referencing a source via `oauth_clients.source_id` — the FK is PHYSICAL (ON DELETE RESTRICT ignores `deleted_at`), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged `deleted`; pre-migration brains without `deleted_at` fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. `formatClientReferentsBlock` renders the shared refusal `sources remove`/`sources purge` print (naming each client — `[revoked, retained]` for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator. `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`; `purgeExpiredSources` SKIPS client-referenced sources via a physical `NOT EXISTS` (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting; an archive with a missing or epoch `archived_at`/`archive_expires_at` is never treated as expired and is reported in `blocked`. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. `get_page`/`delete_page`/`restore_page` (`src/core/ops/pages.ts`) accept an explicit per-call `source_id` that is honored or rejected loudly, never silently dropped: `get_page` resolves it through the caller's read grant (`'__all__'` spans every source for trusted local callers, the granted sources for remote callers), while `delete_page`/`restore_page` reject `'__all__'`, target exactly one source, and — for every caller other than trusted local CLI (`ctx.remote === false`) — accept only the caller's write authority (`ctx.auth.sourceId`, falling back to `ctx.sourceId` for legacy tokens and unauthenticated transports; the federated read grant `allowedSources` confers no delete/restore access), echoing the targeted `source_id` in the response. Pinned by `test/pages-source-scoping-4329.test.ts`. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.+- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plus `oauthClientCount` — OAuth clients whose `source_id` references it. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). FK-RESTRICT lifecycle: `clientsReferencingSource(engine, sourceId)` lists ALL physical OAuth-client rows referencing a source via `oauth_clients.source_id` — the FK is PHYSICAL (ON DELETE RESTRICT ignores `deleted_at`), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged `deleted`; pre-migration brains without `deleted_at` fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. `formatClientReferentsBlock` renders the shared refusal `sources remove`/`sources purge` print (naming each client — `[revoked, retained]` for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator. `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`; `purgeExpiredSources` SKIPS client-referenced sources via a physical `NOT EXISTS` (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting; an archive with a missing or epoch `archived_at`/`archive_expires_at` is never treated as expired and is reported in `blocked`. On an unmanaged brain any other failure of one source's delete is classified (ItemRun site `retention.expired_sources`): an item-scoped one (a statement timeout on a large cascade, a lock timeout) is reported in `blocked` with its `code` and a rendered `fix` (`tell_user_to_run gbrain sources purge <id> --confirm-destructive`) and the sweep continues; a run-scoped one, or a sweep where most sources fail, re-raises (`test/pathological/a50-unmanaged-expired-sources.test.ts`). Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. `get_page`/`delete_page`/`restore_page` (`src/core/ops/pages.ts`) accept an explicit per-call `source_id` that is honored or rejected loudly, never silently dropped: `get_page` resolves it through the caller's read grant (`'__all__'` spans every source for trusted local callers, the granted sources for remote callers), while `delete_page`/`restore_page` reject `'__all__'`, target exactly one source, and — for every caller other than trusted local CLI (`ctx.remote === false`) — accept only the caller's write authority (`ctx.auth.sourceId`, falling back to `ctx.sourceId` for legacy tokens and unauthenticated transports; the federated read grant `allowedSources` confers no delete/restore access), echoing the targeted `source_id` in the response. Pinned by `test/pages-source-scoping-4329.test.ts`. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.- `src/core/env-trust.ts` — Trust boundary for environment variables Bun auto-loaded from the cwd `.env` family. `CWD_DOTENV_FILES` (the eight names Bun auto-loads across NODE_ENV values), `splitDotenvLines` (Bun's line grammar: `\n`, `\r\n` AND a bare `\r` terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), `dotenvValuesForKey(key, dir)` (value set across all assignments; the #427 `DATABASE_URL` value-match guard in config.ts, which re-exports both), `cwdDotenvAssignsKey(key, dir | assignments)` (KEY-PRESENCE predicate; an empty assignment counts) and `parseCwdDotenv(dir)` → `DotenvAssignment[]` (one read the two preflight consumers share). The assignment RHS is matched as `([^\r\n]*)`, never `.*$`. Protection is one predicate, `isCwdDotenvProtectedKey(key)`: `CWD_DOTENV_PROTECTED_KEYS` (code-loading / exec-target / root- and endpoint-redirect incl. `GBRAIN_DATABASE_URL` (key-presence; the #427 config.ts VALUE guard is separate and covers only bare `DATABASE_URL`), `GBRAIN_DIRECT_DATABASE_URL`, `GBRAIN_REMOTE_MCP_URL`, `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_OAUTH_RELAY_URL` / posture-widening `GBRAIN_*`, plus the re-run marker `GBRAIN_CWD_ENV_QUARANTINED`; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS `CWD_DOTENV_PROTECTED_PREFIXES` (`LD_`, `DYLD_`, `GIT_`, `BUN_`, `NPM_CONFIG_`, `npm_config_`, `BASH_FUNC_`) and `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS` (NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/ksh `ENV` deliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified. `quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })` iterates the keys the cwd .env files ASSIGN, deletes each protected one present in `env`, prints ONE stderr line (`formatQuarantineWarning`, composed from the exported `CWD_DOTENV_REMEDIATION` that guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicit `env` see Bun's startup snapshot, which is why `cli-preflight.ts` re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by `test/env-trust.test.ts`; the GBRAIN list is guarded against rot by the structural `test/env-trust-protected-keys.test.ts` (every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose name matches `_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix or `GBRAIN_ALLOW_` prefix must be on the list or carry a `cwd-dotenv-ok: <why>` annotation).diff --git a/src/core/destructive-guard.ts b/src/core/destructive-guard.tsindex 593073ddd5..0166cace81 100644--- a/src/core/destructive-guard.ts+++ b/src/core/destructive-guard.ts@@ -24,6 +24,8 @@ import { defaultCloneDir } from './sources-ops.ts';import { gbrainPath } from './config.ts';import { isMissingSchemaObject } from './utils.ts';import { deleteSourceRow, EXPIRED_ARCHIVE_SQL, UNVERIFIED_ARCHIVE_SQL, unverifiedArchiveReason } from './source-delete.ts';+import { ItemRun } from './item-failure.ts';+import { cliRenderContext, renderAction, type RenderedAction } from './agent-output.ts';// ── Types ───────────────────────────────────────────────────@@ -447,7 +449,14 @@ export interface PurgeExpiredResult {* every client is revoked-and-purged or re-scoped. Blocked is a policy* outcome, not an error: the sweep reports it and moves on.*/- blocked: Array<{ id: string; reason: string }>;+ blocked: Array<{+ id: string;+ reason: string;+ /** GBRA-130 A-50 (unmanaged): the classified code of a delete that failed for this source alone (statement_timeout, lock_timeout, ...). */+ code?: string;+ /** With `code`: the manual purge of this source, for the user to run (`next: tell_user_to_run`). */+ fix?: RenderedAction;+ }>;}/**@@ -459,8 +468,12 @@ export interface PurgeExpiredResult {* aborted the whole statement, wedging the nightly purge forever. The sweep is* now per-source: each DELETE re-checks the expiry predicate (no* select-then-delete race with a concurrent restore), ONLY the FK-restriction- * error class (SQLSTATE 23503) is treated as blocked-and-reported, and every- * other error re-raises. (Supersedes #4238's set-based NOT-EXISTS variant at+ * error class (SQLSTATE 23503) is treated as blocked-and-reported.+ * GBRA-130 A-50: any other failure of one source's delete is classified+ * (classifyItemFailure via ItemRun): an item-scoped one (a statement timeout on+ * a large source's cascade, a lock timeout) is reported in `blocked` with its+ * code and the manual purge as its fix, and the sweep continues; a run-scoped+ * one, or a sweep where most sources fail, re-raises. (Supersedes #4238's set-based NOT-EXISTS variant at* merge: the 23503 catch covers ANY current or future RESTRICT FK — including* soft-deleted oauth_clients, since the FK is physical — not just the one* table an EXISTS prefilter names, and the structured {purged, blocked}@@ -491,6 +504,7 @@ export async function purgeExpiredSources(const purged: string[] = [];const blocked: PurgeExpiredResult['blocked'] = await unverifiedArchives(engine);const cloneRoot = gbrainPath('clones');+ const items = new ItemRun('retention.expired_sources');for (const candidate of candidates) {const { id } = candidate;try {@@ -527,6 +541,7 @@ export async function purgeExpiredSources(}// 0 rows = restored/already gone between SELECT and DELETE; neither// purged nor blocked.+ items.succeed();} catch (err) {// SQLSTATE 23503 foreign_key_violation — same detection idiom as// oauth-provider.ts's delete path for this exact FK.@@ -539,7 +554,13 @@ export async function purgeExpiredSources(});continue;}- throw err;+ const failure = items.fail(id, err);+ blocked.push({+ id, code: failure.code,+ reason: `its delete failed (${failure.message}); the next retention sweep retries it`,+ fix: renderAction({ argv: ['gbrain', 'sources', 'purge', id, '--confirm-destructive'], consent: ['destructive'], actor: 'user', requires_exclusive: false,+ why: 'Purges this expired archived source by hand, outside the nightly sweep.' }, cliRenderContext()),+ });}}return { purged, blocked };diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex ba25c7fca8..d1d68c2a1e 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -29,6 +29,7 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';export const ISOLATE_SITES = {'backfill.rows': 'A-47','purge.recorded_tombstones': 'A-49',+ 'retention.expired_sources': 'A-50',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;diff --git a/test/destructive-guard.test.ts b/test/destructive-guard.test.tsindex 30425e05cd..9b4066a895 100644--- a/test/destructive-guard.test.ts+++ b/test/destructive-guard.test.ts@@ -557,17 +557,24 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {expect(result.blocked).toEqual([]);});+ // GBRA-130 A-50: a non-FK error is never read as FK-blocked. One source's own failure (57014) is blocked with its+ // classified code and the manual purge, and the sweep continues; a run-scoped error (lost connection) still re-raises.+ const nonFkStub = (code: string, message: string) => ({+ async executeRaw(sql: string): Promise<Array<{ id: string }>> {+ if (sql.includes('archive_expires_at IS NULL')) return []; // #5452 unverified-archive listing: none here+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as never]; // #6482: one well-formed unmanaged row+ if (sql.trimStart().startsWith('SELECT')) return [{ id: 'boom' }];+ throw Object.assign(new Error(message), { code }); // NOT the FK class+ },+ }) as never;+test('gbrain#4115 — a NON-FK error re-raises instead of reading as blocked (review gap G8)', async () => {- const stub = {- async executeRaw(sql: string): Promise<Array<{ id: string }>> {- if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as never]; // #6482: one well-formed unmanaged row- if (sql.trimStart().startsWith('SELECT')) return [{ id: 'boom' }];- const err = new Error('canceling statement due to statement timeout') as Error & { code: string };- err.code = '57014'; // query_canceled — NOT the FK class- throw err;- },- } as never;- await expect(purgeExpiredSources(stub)).rejects.toThrow('statement timeout');+ await expect(purgeExpiredSources(nonFkStub('08006', 'Connection terminated unexpectedly'))).rejects.toThrow('Connection terminated');+ const { purged, blocked } = await purgeExpiredSources(nonFkStub('57014', 'canceling statement due to statement timeout'));+ expect(purged).toEqual([]);+ expect(blocked.map(b => [b.id, b.code, b.fix?.next, b.fix?.command])).toEqual([['boom', 'statement_timeout', 'tell_user_to_run', 'gbrain sources purge boom --confirm-destructive']]);+ expect(blocked[0]!.reason).toContain('statement timeout');+ expect(blocked[0]!.reason).not.toContain('foreign key');});test('gbrain#4115 — a source restored between SELECT and DELETE is neither purged nor blocked (review gap G8)', async () => {diff --git a/test/pathological/a50-unmanaged-expired-sources.test.ts b/test/pathological/a50-unmanaged-expired-sources.test.tsnew file mode 100644index 0000000000..07750b2043--- /dev/null+++ b/test/pathological/a50-unmanaged-expired-sources.test.ts@@ -0,0 +1,119 @@+/**+ * A-50 (GBRA-130, hardening: the failure is fault-injected): one expired+ * archived source that cannot be deleted never stops an unmanaged brain's+ * retention sweep (src/core/destructive-guard.ts purgeExpiredSources).+ *+ * Protects: a source whose cascade delete fails with an item-scoped error (a+ * statement timeout on a large source, a lock timeout) is reported in+ * `blocked` with its typed code and the manual purge as a fix+ * (`tell_user_to_run gbrain sources purge <id> --confirm-destructive`), and the+ * sweep goes on to the next source, so the purge phase's page purge and GC+ * still run. A run-scoped failure (lost connection, failed transaction) still+ * stops the sweep. Nothing is persisted, so the next sweep retries the source.+ * Fails when: a non-FK error rethrows and aborts the sweep (the catch keeps+ * only SQLSTATE 23503), or a run-scoped error is swallowed as blocked.+ * Seams: none in production; failures come from a BEFORE DELETE trigger, run-scoped+ * errors from an engine wrapper. PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { purgeExpiredSources, softDeleteSource } from '../../src/core/destructive-guard.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++/** Expired archived sources (the poison one sorts first) plus a live source, each with two pages. */+async function seed(engine: BrainEngine): Promise<{ poison: string; healthy: string[]; live: string }> {+ const tag = randomUUID().slice(0, 6);+ const [poison, healthy1, healthy2, live] = [`a-${tag}-poison`, `b-${tag}-expired`, `c-${tag}-expired`, `d-${tag}-live`];+ for (const id of [poison, healthy1, healthy2, live]) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [id]);+ for (const slug of ['notes/one', 'notes/two']) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}`, timeline: '' }, { sourceId: id });+ }+ for (const id of [poison, healthy1, healthy2]) await softDeleteSource(engine, id);+ await engine.executeRaw(`UPDATE sources SET archive_expires_at = now() - interval '1 hour' WHERE id IN ($1, $2, $3)`, [poison, healthy1, healthy2]);+ return { poison, healthy: [healthy1, healthy2], live };+}++async function refuseDelete(engine: BrainEngine, id: string, state: string): Promise<void> {+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION probe_refuse_source_delete() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN IF OLD.id = TG_ARGV[0] THEN RAISE EXCEPTION 'probe refuses deleting source %', OLD.id USING ERRCODE = '${state}'; END IF; RETURN OLD; END $fn$`);+ await engine.executeRaw('DROP TRIGGER IF EXISTS probe_refuse_source_delete ON sources');+ await engine.executeRaw(`CREATE TRIGGER probe_refuse_source_delete BEFORE DELETE ON sources FOR EACH ROW EXECUTE FUNCTION probe_refuse_source_delete('${id}')`);+}++const sourceIds = async (engine: BrainEngine, ids: string[]) =>+ (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = ANY($1::text[]) ORDER BY id', [ids])).map(r => r.id);++/** The engine whose first source DELETE throws `error`. */+function failingFirstSourceDelete(engine: BrainEngine, error: unknown): BrainEngine {+ let thrown = false;+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => {+ if (!thrown && sql.includes('DELETE FROM sources')) { thrown = true; return Promise.reject(error); }+ return target.executeRaw(sql, params);+ };+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-50 unmanaged expired-source sweep (${backend})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | null = null;++ beforeAll(async () => {+ if (databaseUrl) ({ engine, close: closePostgres } = await isolatedPersistencePostgres(databaseUrl));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 180_000);++ afterAll(async () => {+ if (closePostgres) await closePostgres();+ else await engine.disconnect();+ });++ test('item: a source whose delete times out is blocked with its code and the manual purge; the other expired sources purge', async () => {+ const { poison, healthy, live } = await seed(engine);+ await refuseDelete(engine, poison, '57014');+ const [poisonBefore, liveBefore] = [await snapshotItems(engine, poison), await snapshotItems(engine, live)];+ const result = await expectUnitNotAborted(() => purgeExpiredSources(engine));+ expect(result.purged).toEqual(healthy);+ const blocked = result.blocked.find(b => b.id === poison);+ expectItemFailure(blocked ? { key: blocked.id, code: blocked.code, fix: blocked.fix } : undefined,+ { key: poison, code: 'statement_timeout', fix: new RegExp(`"next":"tell_user_to_run".*"command":"gbrain sources purge ${poison} --confirm-destructive"|"command":"gbrain sources purge ${poison} --confirm-destructive".*"next":"tell_user_to_run"`) });+ expect(await sourceIds(engine, [poison, ...healthy, live])).toEqual([poison, live]);+ expectOthersUnchanged(poisonBefore, await snapshotItems(engine, poison));+ expectOthersUnchanged(liveBefore, await snapshotItems(engine, live));+ for (const id of healthy) expect((await snapshotItems(engine, id)).size).toBe(0);++ await engine.executeRaw('DROP TRIGGER probe_refuse_source_delete ON sources');+ const retried = await expectUnitNotAborted(() => purgeExpiredSources(engine));+ expect({ purged: retried.purged, blocked: retried.blocked.filter(b => b.id === poison) }).toEqual({ purged: [poison], blocked: [] });+ });++ test('item: a lock timeout is blocked the same way and retried on the next sweep', async () => {+ const { poison, healthy } = await seed(engine);+ await refuseDelete(engine, poison, '55P03');+ const result = await expectUnitNotAborted(() => purgeExpiredSources(engine));+ expect(result.purged).toEqual(healthy);+ expect(result.blocked.find(b => b.id === poison)).toMatchObject({ code: 'lock_timeout' });+ await engine.executeRaw('DROP TRIGGER probe_refuse_source_delete ON sources');+ expect((await purgeExpiredSources(engine)).purged).toEqual([poison]);+ });++ for (const { name, error } of runScopedErrors()) {+ test(`run: a run-scoped failure (${name}) deleting a source stops the sweep`, async () => {+ const { poison, healthy, live } = await seed(engine);+ const injected = error();+ const thrown = await purgeExpiredSources(failingFirstSourceDelete(engine, injected)).catch(e => e);+ expect(thrown).toBe(injected);+ expect(await sourceIds(engine, [poison, ...healthy, live])).toEqual([poison, ...healthy, live].sort());+ await purgeExpiredSources(engine);+ });+ }+ });+}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex 0aea87c218..25060b1610 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -24,4 +24,7 @@ export const CATALOGUE: Record<IsolateSite, SiteCases> = {'purge.recorded_tombstones': { file: 'test/pathological/a49-unmanaged-purge-tombstones.test.ts',item: 'item: a tombstone whose delete is refused is reported and kept; the other tombstones and the bulk delete still purge',run: 'run: a run-scoped failure (' },+ 'retention.expired_sources': { file: 'test/pathological/a50-unmanaged-expired-sources.test.ts',+ item: 'item: a source whose delete times out is blocked with its code and the manual purge; the other expired sources purge',+ run: 'run: a run-scoped failure (' },};diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 5ffd38ed72..80c2f55ba6 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -220,6 +220,7 @@ test/page-purge-journal-timeout-6511.test.tstest/page-state-engine.test.tstest/pathological/a47-backfill-poison-row.test.tstest/pathological/a49-unmanaged-purge-tombstones.test.ts+test/pathological/a50-unmanaged-expired-sources.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.ts