Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

persistence: write_interrupted is a resumable connection fault in managed sync (fault table, runbook, public category)

garrytanc68a5397f86d
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 8193a644f7..0b230c8b21 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -138,6 +138,7 @@ Every hold and error has three fields, from one table
| `sync_incomplete` | page | retry | no | never: an unfinished cursor resumes with the same command |
| `connection_lost` | connection | retry | no | three reruns in a row end connection_lost (the database is unreachable from this host) |
| `database_contention` | connection | retry | no | three reruns in a row stop on it |
+| `write_interrupted` | connection | retry | no | a rerun ends write_interrupted on the same entry again: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner |
| `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle |
| `write_capacity_backpressure` | connection | retry | no | reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day |
| `capacity_paused` | connection | retry | no | reason lifetime_ids (only the host raise resumes it), or the same pause after the raise |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 416dc9e535..652c3fd3e7 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -97,7 +97,7 @@ of making a duplicate.
| <a id="purge_lookup_timeout"></a>`purge_lookup_timeout` | `purge_lookup_timeout` | A page purge (`gbrain delete <slug> --purge`) ran one of the journal lookups that still execute inside its publication transaction (the lookup of stored intents for the slug, the re-check of requests admitted after its preparation scan or pending at that scan, the locking read of the requests to redact) and that statement hit the transaction's 5-second statement budget on a large `persistence_requests` table. The request failed terminally instead of being released as `database_contention` and claimed again: nothing of the page was removed or tombstoned, nothing in the journal was redacted, and later writes to the source move again. Do not assume the requested content was erased. The substring search for the page's claims no longer runs here: it runs at preparation in bounded keyset chunks under the preparation budget, and a sweep that outruns that budget twice ends [`preparation_stalled`](#preparation_stalled) instead. A committed purge's receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`); `complete: false` means a cap was hit (the 10,000-match cap or the tail bound) and some requests were not tested. | If the receipt says the slug index `persistence_requests_slug_intent` is missing or INVALID, run `gbrain repair request-indexes --apply` (the `persistence_request_slug_intent_index` migration builds it online; the index serves the slug lookup, not the substring sweep), then submit the purge again with a new `request_id`. Otherwise submit it again with a new `request_id` (a retry with the same id returns this failure); if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. |
| <a id="purge_mirror_unwritable"></a>`purge_mirror_unwritable` | `purge_mirror_unwritable` | A fact or page purge appends a text-free `intent` line to the purge mirror (`<brain home>/.gbrain/purge-events.jsonl`) and fsyncs it before it commits, so a later restore of an older backup can replay the purge. The mirror could not be written (a directory in its place, a read-only home, a full disk), so the purge was refused: nothing was removed, tombstoned or redacted. Do not assume the requested content was erased. | Make the mirror a writable regular file owned by the brain's user (mode 0600), then run the purge again with a new `request_id`. |
| <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The write's owner could not finish *preparing* it. Every write has a preparation budget (`persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other managed kind, 120 s each; `remember`, `put_page` and `edit_page` keep 30 s), the owner releases the claim at the budget and tries again, and a request cut off `persistence.max_preparation_attempts` times (default 2; a process killed mid-preparation counts too) is finished `failed` with this code instead of being claimed again and holding the rest of its root. The receipt names the last recorded step and what it was waiting on (`git`, `fs`, `db`, `pool` or `unknown`); while the write was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. A **managed sync member** (an import, delete or rename of a file) is also **held**: the sync turns the failed receipt into a `preparation_stalled` hold and carries on, so the file is not imported until it is retried. The file is fine; this is the write owner stalling (a database or pool wait, a hung step), never a frontmatter or fence problem, so no repair applies. The hold's `message` names the request and the step; a held deletion keeps its page. A stalled hold re-screens by itself only when the gbrain version changes; a run that stalls many files in a row stops with [`preparation_systemic`](#preparation_systemic) instead of holding them all. A **foreground write** (`put_page`, `edit_page`, `remember`) or a **maintenance write** (fact-fence adoption, maintenance page writes) gets the terminal receipt only. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`, `put_page` and `edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause, the owner process and its gbrain version), fix what it names (restart or upgrade an owner that predates deadlines, free the pool, let the lock holder finish), then for a sync hold run `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options (the hold's `fix.then.then` and `retry-held` print it, for example `gbrain sync --source <source> --no-pull --no-embed`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
-| <a id="write_interrupted"></a>`write_interrupted` | `write_interrupted` | The database ended this managed write's own statements (SQLSTATE `57014`, a statement timeout or cancel) at preparation or inside its publication transaction, and the request reached `persistence.max_preparation_attempts` (default 2) counted attempts, so the owner finished it `failed` instead of preparing it again. Nothing was published: a worktree-backed write's canonical file is restored before the failure is recorded. Each interruption throws the preparation away, so it counts with the preparations cut off at their deadline ([`preparation_stalled`](#preparation_stalled)); before, a write the database ended every time (a large page publishing under the 5-second statement bound on a loaded host) was released as `database_contention` and prepared again, its whole body streamed again, without limit. Contention with other transactions (`55P03` lock timeout, `40001` serialization failure, `40P01` deadlock) is still released as `database_contention` uncounted, and a dropped connection or a database that is restarting or out of connections is never counted. The receipt's message and owner-only `error_detail` name the attempts, the limit and the SQLSTATE (`sqlstate`, public). A managed sync member re-freezes in place under a fresh request, at most three times in a row per run. With `persistence.preparation_deadlines` off nothing is counted, as before. | Run `gbrain sources writer status --source <source> --json` (read-only: the owner, its pool, what its writes wait on), then submit the write again with a new `request_id` once the database is less loaded; a managed sync freezes the file again on its next run. If the same write ends this way again, report its request id with `gbrain doctor --json`. Do not raise `persistence.max_preparation_attempts` to get past it. |
+| <a id="write_interrupted"></a>`write_interrupted` | `write_interrupted` | The database ended this managed write's own statements (SQLSTATE `57014`, a statement timeout or cancel) at preparation or inside its publication transaction, and the request reached `persistence.max_preparation_attempts` (default 2) counted attempts, so the owner finished it `failed` instead of preparing it again. Nothing was published: a worktree-backed write's canonical file is restored before the failure is recorded. Each interruption throws the preparation away, so it counts with the preparations cut off at their deadline ([`preparation_stalled`](#preparation_stalled)); before, a write the database ended every time (a large page publishing under the 5-second statement bound on a loaded host) was released as `database_contention` and prepared again, its whole body streamed again, without limit. Contention with other transactions (`55P03` lock timeout, `40001` serialization failure, `40P01` deadlock) is still released as `database_contention` uncounted, and a dropped connection or a database that is restarting or out of connections is never counted. The receipt's message and owner-only `error_detail` name the attempts, the limit and the SQLSTATE (`sqlstate`, public). A managed sync member re-freezes in place under a fresh request, at most three times in a row per run; a run that stops on it is resumable (`gbrain sync status` class `connection`, safe action `retry`, [runbook row](sync-unblock-runbook.md)). With `persistence.preparation_deadlines` off nothing is counted, as before. | Run `gbrain sources writer status --source <source> --json` (read-only: the owner, its pool, what its writes wait on), then submit the write again with a new `request_id` once the database is less loaded; a managed sync freezes the file again on its next run. If the same write ends this way again, report its request id with `gbrain doctor --json`. Do not raise `persistence.max_preparation_attempts` to get past it. |
| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. |
| <a id="page_body_segmented"></a>`page_body_segmented` | `page_body_segmented` (a memory verb: `invalid_params` with `write_error: page_body_segmented`) | The target page stores its body in segments (a page over 1 MiB written while `pages.segmented_storage` was on), and this write needs the whole body as one string: `remember` against an entity page over 24 MiB (named, or inferred from the fact), and the other whole-body writers listed under [page_body_segmented](windowed-reads.md#page_body_segmented). It refused before changing anything and is not retryable. | For `remember`, save the claim without an entity (`infer_entity: false`); remembering it with `entity` once that page accepts fact rows replaces that copy. Otherwise edit the page's file and sync it, or read it with `get_page` `body: "auto"`. |
| <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. Before v0.60.218.0 the planner could reuse a leftover fence row (one with no database owner) whose visibility differed from the legacy fact's. On a managed brain the publisher refused that page here every cycle, so no private fact was published as world. An unmanaged brain had no such check: it fenced the fact into the leftover row, and the same cycle's reconcile copied that row's visibility into the fact, so a private fact could become world. The current planner never reuses a leftover row for a fact with a different visibility unless the fact is private, and re-renders a reused row from the fact. To count what an older build left in the writer table, run the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. |
diff --git a/llms-full.txt b/llms-full.txt
index a1ba0f4bdc..e23768bdf0 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7524,6 +7524,7 @@ Every hold and error has three fields, from one table
| `sync_incomplete` | page | retry | no | never: an unfinished cursor resumes with the same command |
| `connection_lost` | connection | retry | no | three reruns in a row end connection_lost (the database is unreachable from this host) |
| `database_contention` | connection | retry | no | three reruns in a row stop on it |
+| `write_interrupted` | connection | retry | no | a rerun ends write_interrupted on the same entry again: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner |
| `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle |
| `write_capacity_backpressure` | connection | retry | no | reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day |
| `capacity_paused` | connection | retry | no | reason lifetime_ids (only the host raise resumes it), or the same pause after the raise |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 033d1b9a9d..ca2941068d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -883,7 +883,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.287.0', text: 'The managed purge (autopilot purge phase, the purge job and `gbrain pages purge-deleted`) submits only while the writer has outstanding-request room (a background run stops at `persistence.capacity.background_pause_pct` of the cap). The rest is reported as `write_capacity_deferred` and counted in `capacity_deferred` (cycle: `purged_pages_capacity_deferred`, phase status warn) and is submitted by the next run, where it used to fail each page with `queue_capacity` (`managed_purge_failed`) and count each failure toward parking it.' },
{ since: '0.60.288.0', text: 'On a managed brain `gbrain sync --dry-run --json` adds a `convergence` object: a read-only shadow of the level-triggered sync (#6712 PR 4a) that classifies every path of the source the way the coming pass will (matched, import, held, drift and the other classes, each tagged with who acts: none, owner or repair), with predicted file_drift decisions after a read-only screen, `legacy_unverified` counts, deletes with the mass-delete valve verdict and up to 20 sample paths per class. `--redact-paths` turns the sample paths into sha256 prefixes and drops slugs, so the counts can be shared. `gbrain sync status --detail --json` adds the same object (`convergence`, `dry_run: true`) and `convergence_read`; a plain `sync status` skips that heavy read. Nothing is written or admitted, existing keys keep their meaning, and sync behaves exactly as before.' },
// Flip lane C (segmented storage switch-on): transient publication failures are bounded.
- { since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync re-freezes the file in place. `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },
+ { since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync re-freezes the file in place, and a run that stops on it is resumable (`gbrain sync status` shows class `connection`, safe action `retry`, no person needed; a rerun on the same entry ending it again names the read-only `gbrain sources writer status`). `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 2a187e817d..e0dae810a0 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -42,7 +42,7 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
canonical_file_missing: 'file_missing',
parser_regression: 'defect', outside_fence: 'defect', preparation_systemic: 'defect', drain_stalled: 'defect',
cancelled: 'superseded', knock_on: 'superseded', run_replaced: 'superseded', knock_on_exhausted: 'superseded', cursor_incarnation_retired: 'superseded',
- preparation_stalled: 'transient', sync_incomplete: 'transient', connection_lost: 'transient', database_contention: 'transient', write_capacity: 'transient',
+ preparation_stalled: 'transient', sync_incomplete: 'transient', connection_lost: 'transient', database_contention: 'transient', write_interrupted: 'transient', write_capacity: 'transient',
write_capacity_backpressure: 'transient', capacity_paused: 'transient', sync_drain_lease_held: 'transient', graduation_in_progress: 'transient',
storage_error: 'storage', recovery_required: 'storage',
permission_denied: 'permission',
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 369c6efe8e..a381e85b42 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -103,6 +103,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// Connection class: transport only; the cursor and manifest stand.
{ code: 'connection_lost', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row end connection_lost (the database is unreachable from this host)' },
{ code: 'database_contention', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row stop on it' },
+ // The database ended a write's statements (SQLSTATE 57014) persistence.max_preparation_attempts times; the run re-freezes the entry in place.
+ { code: 'write_interrupted', class: 'connection', safe_actions: ['retry'], needs_human: false,
+ escalate: 'a rerun ends write_interrupted on the same entry again: gbrain sources writer status --source <source> --json (read-only) names the load on the write owner' },
{ code: 'write_capacity', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'writer status shows the cap held by requests that never settle' },
// #6696 (A5): a background sync paused near a cumulative cap; interactive writes keep the rest and the pause lifts as capacity returns.
{ code: 'write_capacity_backpressure', class: 'connection', safe_actions: ['retry'], needs_human: false,
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index e0c030b413..4d8aa1ae16 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -285,6 +285,7 @@ function route(input: TerminalInput): Partial_ {
why: 'The page changed after the caller read it. Read the current revision and resubmit against it with a new request id.',
verify: { argv: failuresArgv(source) } } };
}
+ if (code === 'write_interrupted') return fromTable('transport', code, origin, syncRetry(source, 'The database ended this write\'s statements until its preparation limit; a sync re-freezes the entry under a new request.'));
if (FAULT_CODES.has(code)) return fromTable('sync_fault', code, origin, faultAction(code, input), null, input.error_message);
const entry = (CODES as Record<string, { class: string } | undefined>)[code];
if (!entry) return diagnosis(input, code, origin, `The write ended with code ${code}, which this build does not know.`);
diff --git a/test/persistence-write-interrupted.test.ts b/test/persistence-write-interrupted.test.ts
index c87d887e44..abb048642a 100644
--- a/test/persistence-write-interrupted.test.ts
+++ b/test/persistence-write-interrupted.test.ts
@@ -15,13 +15,17 @@
* loaded host is prepared again, its whole body streamed again, without limit), or when contention or a connection loss is counted.
* 3. Existing coverage: page-purge-journal-timeout-6511.test.ts bounds the purge's own lookups only;
* persistence-preparation-deadline tests bound preparation deadlines, never a publication's interruptions.
+ * A managed sync member that ends `write_interrupted` is a transient connection-class fault (SYNC_FAULT_TABLE): the
+ * run re-freezes it in place under a fresh request (STOPS_PER_ENTRY times in a row), then stops resumable with
+ * `retry` and an escalation naming the read-only `gbrain sources writer status`, never "Unknown code" for a person.
* 4. Semantic injection: installFaultHook on the publication's before_commit seam (inside the publication transaction),
* throwing an error carrying the SQLSTATE, for every publication of the claims the test names. Counts claims, never
* time. Runs on PGLite and, with DATABASE_URL, on Postgres.
*/
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -31,6 +35,12 @@ 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 { resetWriteSwitches } from '../src/core/persistence/switches.ts';
+import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';
+import { performManagedSync, STOPS_PER_ENTRY } from '../src/core/persistence/sync-run.ts';
+import { readSyncStatus, unblockSync } from '../src/core/persistence/sync-status.ts';
+import { receiptClass, resumableStop } from '../src/core/persistence/sync-stop-class.ts';
+import { classifyRecordedFault } from '../src/core/persistence/terminal-classify.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -39,6 +49,19 @@ import { withEnv } from './helpers/with-env.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 page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;
+const WRITER_STATUS = 'gbrain sources writer status';
+
+test('write_interrupted is a transient connection fault whose escalation names the read-only writer status', () => {
+ expect(classifySyncFault({ code: 'write_interrupted' })).toEqual({ class: 'connection', safe_actions: ['retry'], needs_human: false });
+ expect(classifyRecordedFault({ source_id: 'notes', code: 'write_interrupted', slug: 'a' })).toMatchObject({ category: 'transport', public_category: 'transient',
+ class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: expect.stringContaining(WRITER_STATUS) });
+ const receipt = { request_id: randomUUID(), source_id: 'notes', slug: 'a', operation: 'put_page', state: 'failed', error_code: 'write_interrupted',
+ error_message: 'The database ended this write\'s statements 2 time(s).', error_detail: { origin: 'database_interruption', sqlstate: '57014', attempts: 2, limit: 2 },
+ recovery: null, blocked_reason: null, compacted: false, publication_started: false, intent: { kind: 'managed_sync_import' } } as unknown as WriteRequest;
+ expect(receiptClass(receipt)).toBe('transport');
+ expect(resumableStop(receipt)).toBe(true);
+});
+
type Row = { state: string; error_code: string | null; error_message: string | null; error_detail: Record<string, unknown> | null; preparation_attempts: number; has_recovery: boolean };
for (const backend of testBackends()) describe(`[${backend}] transient publication failures are bounded`, () => {
@@ -123,6 +146,49 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati
expect(await row(requestId)).toMatchObject({ state: 'committed' });
}, 120_000);
+ test('a managed sync entry that ends write_interrupted is re-frozen in place, then stops resumable with a retry', async () => withEnv({ GBRAIN_HOME: home,
+ GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
+ const id = `wi-${randomUUID().slice(0, 8)}`, root = join(home, id);
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ mkdirSync(root); git('init', '-q');
+ for (const name of ['a', 'b']) writeFileSync(join(root, `${name}.md`), page(`Sync ${name}`));
+ git('add', '.'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content');
+ 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,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=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>();
+ installFaultHook(async (point, detail) => {
+ if (detail.sourceId !== id || !detail.requestId) return;
+ if (point === 'consumer:preparing') {
+ const [request] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE request_id=$1::uuid', [detail.requestId]);
+ if (request?.slug === 'a') pageA.add(detail.requestId);
+ }
+ if (point === 'publication:before_commit' && pageA.has(detail.requestId)) throw interruption('57014');
+ });
+ const result = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ installFaultHook(undefined);
+ expect(result).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'write_interrupted', count: 1 }] });
+ const requests = await 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(requests).toEqual(Array.from({ length: STOPS_PER_ENTRY + 1 }, () => ({ state: 'failed', error_code: 'write_interrupted', preparation_attempts: 2 })));
+ expect(await engine.readPageSnapshot('a', { sourceId: id })).toBeNull();
+ const status = await readSyncStatus(engine, id);
+ expect(status.last_error).toMatchObject({ code: 'write_interrupted', category: 'transport', public_category: 'transient', class: 'connection',
+ safe_actions: ['retry'], needs_human: false });
+ expect(status).toMatchObject({ state: 'resumable', needs_human: false });
+ expect(status.next?.argv?.slice(0, 2)).toEqual(['gbrain', 'sync']);
+ expect(status.next?.user_message).toBeUndefined();
+ expect((await unblockSync(engine, id, { apply: false })).refused).toEqual([]);
+ // The cause gone, the same sync converges.
+ expect((await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true })).status).not.toBe('blocked_by_failures');
+ expect(await engine.readPageSnapshot('a', { sourceId: id })).not.toBeNull();
+ expect(await engine.readPageSnapshot('b', { sourceId: id })).not.toBeNull();
+ }), 300_000);
+
describe('worktree-backed page', () => {
let brainDir: string;
const sourceId = `wt-${randomUUID().slice(0, 8)}`;