Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): bound cancelled shared group reads; write_interrupted is a write error code; breaker names it

garrytan75b9a55cdd3d
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 41c6f5517c..a682e73ed7 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -98,7 +98,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 is held like [`preparation_stalled`](#write_interrupted-hold): the run moves past it and the rest of the source lands, `gbrain sync status` lists the hold (class `page`, safe action `retry`, [runbook row](sync-unblock-runbook.md)), and `gbrain sources retry-held` re-admits it. Only the database ending the write's own statement counts: a group's shared read the database cancels charges no member, and the charge commits with the claim's release, so a crash between them never counts it twice. 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; for a held sync file, run `gbrain sources retry-held <source>` and the same sync with its options. 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 is held like [`preparation_stalled`](#write_interrupted-hold): the run moves past it and the rest of the source lands, `gbrain sync status` lists the hold (class `page`, safe action `retry`, [runbook row](sync-unblock-runbook.md)), and `gbrain sources retry-held` re-admits it. Only the database ending the write's own statement counts: a group's shared read the database cancels is charged once, to the first member that settles with it, never to every member, so a read cancelled on every pass still ends each member `write_interrupted` at the limit; and the charge commits with the claim's release, so a crash between them never counts it twice. 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; for a held sync file, run `gbrain sources retry-held <source>` and the same sync with its options. 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/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 0f0cfbe08b..eddb1f9f3a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -892,7 +892,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable. The writer hold now counts any gbrain older than this release, v0.60.290.0 included (its withdrawal mirror leaves a large page\'s file unchanged and its search build can overlap another\'s): while one wrote in the last 7 days, new pages stay inline and doctor `segmented_storage` names the host to upgrade.', id: 'segmented_switch_on' },
{ since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text. The content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`), which the database stores and the file does not, are now set aside when a page stored in segments is compared with its file, as they are for an inline page; before, any rewrite of a marked page\'s file (a withdrawal, delete, restore or tag change) was skipped or refused as `file_database_drift`.' },
{ since: 'TBD', text: 'A page stored in segments whose facts fence is longer than a segment (so it crosses a forced cut) is now read whole by every trusted reader once its source has a withdrawal: `gbrain export`, the withdrawal mirror and Git walk, the file drift check and the derived passes join the fence\'s segments (up to 8 MiB) and apply the withdrawals to the joined fence, as withdrawal discovery and the purge rewrite already did. Before, they refused with `page_projection_stale`, so a purge committed but its withdrawal mirror failed five times and parked with the purged row still in the canonical file. A fence longer than 8 MiB is recorded as a skipped target (reason `page_body_segmented`) by the mirror and Git walk instead of parking them. A withdrawal mirror whose staging file cannot be written (an I/O error such as EIO or ENOSPC) while the canonical file is unchanged now releases its recovery record and reserved capacity, so other writes and effects on the source\'s worktree proceed and the mirror retries and parks after its attempts like any failed mirror; before, the record held every write on the worktree and the mirror retried every 30 seconds without ever parking. The mirror now renders a segmented page\'s file only when the file exists to be rewritten, the Git walk no longer renders it at all, and both renew their effect claim while they stream the file.' },
- { 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 holds the file and moves on (`gbrain sync status` lists the hold with class `page`, safe action `retry`, and the read-only `gbrain sources writer status` diagnosis), and `gbrain sources retry-held` re-admits it. A shared read of a group the database cancels charges no member, and the charge commits with the release of the claim, so a crash between them never counts an interruption twice. `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 holds the file and moves on (`gbrain sync status` lists the hold with class `page`, safe action `retry`, and the read-only `gbrain sources writer status` diagnosis), and `gbrain sources retry-held` re-admits it. A shared read of a group the database cancels is charged once, to the first member that settles with it, never to every member (so a read cancelled on every pass still ends each member `write_interrupted` at the limit); a receipt and a failed source lifecycle name `write_interrupted` instead of `storage_error`; a sync breaker trip names its `write_interrupted` receipts by that code; and the charge commits with the release of the claim, so a crash between them never counts an interruption twice. `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },
{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },
{ since: 'TBD', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v258) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included: turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },
{ since: 'TBD', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and it has since written with the upgraded gbrain: it reports the hold as information with the time it clears. Another host, or an older `serve` or worker still running on this host, keeps the warning and the `gbrain upgrade` fix.' },
diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.ts
index cbc0507286..9e6cf1d770 100644
--- a/src/core/persistence/bounded-reads.ts
+++ b/src/core/persistence/bounded-reads.ts
@@ -68,8 +68,8 @@ const SHARED_READ = Symbol('gbrain.shared-read');
/**
* Flip lane C: the failure of a read several preparations share (group-publish.ts `preparationReads`), handed to every member
* waiting on it. It ran without any member's bound, so it is no member's own statement: a bounded member never reads it as
- * its deadline, and the coordinator never charges it as the member's interruption. The SQLSTATE stays, so a transient
- * one still releases the member uncounted.
+ * its deadline, and the coordinator charges it once, to the first member that settles with it (`chargedSharedReads`); the
+ * other members waiting on the same failure are released uncounted.
*/
export function sharedReadFailure(error: unknown): unknown {
if (!(error instanceof Error)) return error;
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 5db9f205a6..7a836d2891 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -211,10 +211,15 @@ export function transientDatabaseFailure(error: unknown): boolean {
* shutting down or out of connections is not the write's doing: neither is charged, so a restart never fails a write.
*/
function writeInterruption(error: unknown): string | null {
- // A group's shared read (`sharedReadFailure`) is no member's own statement.
- if (isSharedReadFailure(error)) return null;
return String((error as {code?:string})?.code) === '57014' ? '57014' : null;
}
+/**
+ * Flip lane C: the shared-read failures (`sharedReadFailure`) already charged. A group's memoized read the database cancelled
+ * ran once, for the whole group, and every member waiting on it gets the same failure: it is charged once, to the first
+ * member that settles with it (in group order, the member that would have sent it alone), and the other members are
+ * released uncounted. A read cancelled on every pass so still reaches the limit, one member at a time, never unbounded.
+ */
+const chargedSharedReads = new WeakSet<object>();
function writeInterruptedFailure(row: WriteRequest, sqlstate: string, attempts: number, limit: number): PublicationFailure {
const fix = preparationKind(row) === 'sync'
? `The file is held and the rest of the source syncs; reduce the load, then gbrain sources retry-held ${row.source_id} and the same gbrain sync with the same options.`
@@ -232,6 +237,10 @@ function writeInterruptedFailure(row: WriteRequest, sqlstate: string, attempts:
async function interruptionCharge(engine: BrainEngine, error: unknown): Promise<{ sqlstate: string; limit: number } | null> {
const sqlstate = writeInterruption(error);
if (!sqlstate) return null;
+ if (isSharedReadFailure(error)) {
+ if (chargedSharedReads.has(error as object)) return null;
+ chargedSharedReads.add(error as object);
+ }
try {
const { switches, preparation } = await readWriteSwitchSnapshot(engine);
return switches.preparation_deadlines ? { sqlstate, limit: preparation.maxAttempts } : null;
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 8eac58e522..2aea7a044f 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -24,6 +24,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| 'persistence:interruption_charged'
// Flip lane C: on publishMutation's recovery route, after a statement-cancelled (57014) write's attempt is charged, before the request is marked recovering.
| 'persistence:recovery_interruption_charged'
+ // Flip lane C: before a group's memoized shared preparation read (group-publish.ts `preparationReads`) is sent; a hook that throws a 57014 models the database cancelling it.
+ | 'group:shared_read'
// Before each claim attempt of the consumer, a FIFO claim or a lane head's: a stalling hook keeps this process from starting
// another request or lane group meanwhile, while the requests it already holds run on.
| 'consumer:claiming'
@@ -80,6 +82,8 @@ export const EFFECT_FAULT_POINTS: Record<EffectKind, FaultPoint> = {
let installed: FaultHook | undefined;
/** Gate workers only. */
export function installFaultHook(hook: FaultHook | undefined): void { installed = hook; }
+/** Whether a hook is installed: a seam that must not delay a synchronous send in production checks it first. */
+export function faultHookInstalled(): boolean { return installed !== undefined; }
export async function faultPoint(point: FaultPoint, detail: FaultDetailInput = {}): Promise<void> {
if (!installed) return;
const { effectId, ...rest } = detail;
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 9e12aa2637..52473c8a75 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -69,7 +69,7 @@ import { readJournalLimits } from './limits.ts';
import type { JournalLimits } from './model.ts';
import { writerStamp } from './writer-versions.ts';
import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';
-import { faultPoint, type PublicationBoundary } from './fault-points.ts';
+import { faultHookInstalled, faultPoint, type PublicationBoundary } from './fault-points.ts';
import { assertMutationProtocol } from './protocol.ts';
import { writeSwitchOn } from './switches.ts';
import { importGroupReads, type ImportGroupReads } from './import-reads.ts';
@@ -171,8 +171,9 @@ export function preparationReads(engine: BrainEngine, imports?: ImportGroupReads
const reads = new Map<string, Promise<unknown>>();
const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {
let value = reads.get(id) as Promise<T> | undefined;
- // Flip lane C: a failed shared read is no member's own statement (`sharedReadFailure`): nobody is charged for it.
- if (!value) { value = read().catch(error => { throw sharedReadFailure(error); }); reads.set(id, value); value.catch(() => reads.delete(id)); }
+ // Flip lane C: a failed shared read is no member's own statement (`sharedReadFailure`): it is charged once, never to every member.
+ // The read is sent synchronously (the memo rule); only an installed hook runs the `group:shared_read` seam first.
+ if (!value) { value = (faultHookInstalled() ? faultPoint('group:shared_read').then(read) : read()).catch(error => { throw sharedReadFailure(error); }); reads.set(id, value); value.catch(() => reads.delete(id)); }
return value;
};
return new Proxy(engine, { get(target, key) {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index b4119dfa78..fe69e10359 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -147,18 +147,18 @@ export interface CursorProgress { startedAt: number; startIndex: number; lastAt:
* run stops `blocked` / `preparation_systemic`, and the next run re-freezes the entry and schedules the run's earlier
* stalled holds for a re-screen instead of holding.
*/
-export interface CursorBreaker { stalled: string[]; streak: number; tripped?: { at: string; rule: 'count' | 'consecutive'; stalled: number; streak: number; step: string | null; request_id: string } }
+export interface CursorBreaker { stalled: string[]; streak: number; interrupted?: number; tripped?: { at: string; rule: 'count' | 'consecutive'; stalled: number; streak: number; step: string | null; request_id: string; interrupted?: number } }
/** The second trip rule: this many consecutive stalled entries with no commit between them. */
export const BREAKER_STREAK = 5;
/** The breaker after this receipt: the count rule is `holdsEscalated`'s "greater than" rule over the run's screened imports, the streak rule is `BREAKER_STREAK`. */
-function breakerAfter(cursor: Cursor, done: Pick<WriteRequest, 'request_id' | 'error_detail'>, policy: Pick<SyncHoldPolicy, 'escalateCount' | 'escalatePct'>): CursorBreaker {
+function breakerAfter(cursor: Cursor, done: Pick<WriteRequest, 'request_id' | 'error_code' | 'error_detail'>, policy: Pick<SyncHoldPolicy, 'escalateCount' | 'escalatePct'>): CursorBreaker {
const prior = cursor.breaker ?? { stalled: [], streak: 0 };
if (prior.tripped || prior.stalled.includes(done.request_id)) return prior;
- const stalled = [...prior.stalled, done.request_id], streak = prior.streak + 1;
+ const stalled = [...prior.stalled, done.request_id], streak = prior.streak + 1, interrupted = (prior.interrupted ?? 0) + (done.error_code === 'write_interrupted' ? 1 : 0);
const screened = cursor.entries.slice(0, cursor.index + 1).filter(entry => entry.action === 'import').length;
const rule = holdsEscalated(policy, stalled.length, { held: stalled.length, screened }) ? 'count' : streak >= BREAKER_STREAK ? 'consecutive' : null;
const step = done.error_detail && typeof done.error_detail === 'object' && typeof (done.error_detail as Record<string, unknown>).step === 'string' ? String((done.error_detail as Record<string, unknown>).step) : null;
- return { stalled, streak, ...(rule ? { tripped: { at: new Date().toISOString(), rule, stalled: stalled.length, streak, step, request_id: done.request_id } } : {}) };
+ return { stalled, streak, interrupted, ...(rule ? { tripped: { at: new Date().toISOString(), rule, stalled: stalled.length, streak, step, request_id: done.request_id, interrupted } } : {}) };
}
/** The cursor after a committed page: a commit ends the breaker's consecutive streak. */
function committedBreaker(cursor: Cursor): Pick<Cursor, 'breaker'> {
@@ -176,15 +176,15 @@ export interface ManagedSyncBreaker {
fix: import('../agent-output.ts').Action;
}
function breakerResult(cursor: Cursor, pending: Pending, done: WriteRequest, remote: boolean): SyncResult {
- const trip = cursor.breaker!.tripped!;
- const where = trip.step ? ` at step ${trip.step}` : '';
+ const trip = cursor.breaker!.tripped!, interrupted = trip.interrupted ?? 0, prepared = trip.stalled - interrupted;
+ const causes = [prepared ? `${prepared} could not finish preparing${trip.step ? ` at step ${trip.step}` : ''}` : '', interrupted ? `${interrupted} had their statements ended by the database (write_interrupted)` : ''].filter(Boolean).join(', ');
const fix: ManagedSyncBreaker['fix'] = { argv: ['gbrain', 'sources', 'writer', 'status', '--source', cursor.sourceId, '--json'], consent: [], actor: remote ? 'host_admin' : 'agent', requires_exclusive: false,
docs: 'docs/guides/write-refusals.md#preparation_systemic', verify: { argv: ['gbrain', 'sources', 'status', cursor.sourceId, '--json'] },
- why: `${trip.stalled} write(s) of this sync could not finish preparing${where} (${trip.rule === 'consecutive' ? `${trip.streak} in a row with no page committed between them` : 'more than a source should hold'}), `
+ why: `${trip.stalled} write(s) of this sync ran out of attempts: ${causes} (${trip.rule === 'consecutive' ? `${trip.streak} in a row with no page committed between them` : 'more than a source should hold'}), `
+ 'so the run stopped instead of holding every file: the write owner, not the files, is the likely cause. Writer status (read-only) shows the owner process, its gbrain version and the step '
+ 'each stuck write reached; fix what it names or upgrade gbrain, then rerun the same sync: it re-freezes the stopped entry and re-screens the files this run held.',
- ...(remote ? { user_message: `A managed sync of source ${cursor.sourceId} stopped because ${trip.stalled} writes could not finish preparing. Please run 'gbrain sources writer status --source ${cursor.sourceId} --json' on the brain host, fix what it names, then rerun the sync.` } : {}) };
- return { ...result(cursor, 'blocked_by_failures'), failedFiles: 1, failureCodes: [{ code: PREPARATION_STALLED, count: trip.stalled }],
+ ...(remote ? { user_message: `A managed sync of source ${cursor.sourceId} stopped because ${trip.stalled} writes ran out of attempts (${causes}). Please run 'gbrain sources writer status --source ${cursor.sourceId} --json' on the brain host, fix what it names, then rerun the sync.` } : {}) };
+ return { ...result(cursor, 'blocked_by_failures'), failedFiles: 1, failureCodes: [{ code: PREPARATION_STALLED, count: prepared }, { code: 'write_interrupted', count: interrupted }].filter(code => code.count > 0),
breaker: { code: 'preparation_systemic', rule: trip.rule, stalled: trip.stalled, consecutive: trip.streak, step: trip.step, request_id: trip.request_id, fix },
...(remote ? {} : { managedWrite: writeDiagnostic(cursor, pending, done) }) };
}
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index cb7de292a5..bb520a4eff 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -20,7 +20,7 @@ export const WRITE_ERROR_CODES = [
'core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',
'timeline_rows_would_be_removed', 'purged_content', 'preparation_stalled',
'fence_unrenderable', 'page_body_segmented',
- 'write_outcome_unknown',
+ 'write_outcome_unknown', 'write_interrupted',
] as const;
export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 29a6960cd3..7a7257b2a8 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -133,6 +133,9 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
// #5575: a purged claim or page content is refused for good; the owner alone can clear its tombstone.
if (code === 'purged_content') return { reason: code, message: 'This content was purged from this source and cannot be saved again.',
suggestion: PURGED_SUGGESTION };
+ // Flip lane C: the receipt names the attempts, the limit and the SQLSTATE; the next step is the read-only writer status.
+ if (code === 'write_interrupted' && message) return { reason: code, message,
+ suggestion: 'Inspect the owner with gbrain sources writer status --source <source> --json (read-only), then submit the write again with a new request_id once the database is less loaded; a held sync file needs gbrain sources retry-held <source> and the same sync.' };
const memory = code === 'invalid_params' ? MEMORY_REFUSAL.exec(message ?? '') : null;
if (memory) return { reason: code, message: message!, suggestion: MEMORY_REFUSAL_SUGGESTION[/, extracted from that conversation page\.$/.test(message!) ? 'replaces_cross_page_derived' : memory[1]!]! };
const reason = isWriteErrorCode(code) ? code : 'storage_error';
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index d0e7fe5e3a..5682c0423b 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6303,7 +6303,7 @@
"kind": "type",
"name": "ErrorCode",
"signature": [
- "\"rate_limited\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"
+ "\"rate_limited\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"
]
},
{
@@ -6393,7 +6393,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"write_interrupted\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
@@ -6413,10 +6413,10 @@
"stack?: string | undefined",
"suggestion?: string | undefined",
"syncRefusal?: Record<string, unknown> | undefined",
- "toJSON: () => { contract_version?: 1 | undefined; withdrawn?: WithdrawnDetail | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",
+ "toJSON: () => { contract_version?: 1 | undefined; withdrawn?: WithdrawnDetail | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",
"why?: string | undefined",
"withdrawn?: WithdrawnDetail | undefined",
- "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | undefined",
+ "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | undefined",
"writeRequest?: WriteReceipt | undefined"
],
"name": "OperationError",
diff --git a/test/managed-sync-preparation-stalled-holds.test.ts b/test/managed-sync-preparation-stalled-holds.test.ts
index 5f3079844e..8346f02285 100644
--- a/test/managed-sync-preparation-stalled-holds.test.ts
+++ b/test/managed-sync-preparation-stalled-holds.test.ts
@@ -60,15 +60,16 @@ afterAll(async () => {
await closePostgres?.(); rmSync(home, { recursive: true, force: true });
});
-/** The forced probe: the owner finishes the request for one of `paths` `failed` with `preparation_stalled` at `point`. */
-function stallPaths(engine: BrainEngine, sourceId: string, paths: Set<string>, point: FaultPoint = 'consumer:prepared'): { fired: string[] } {
+/** The forced probe: the owner finishes the request for one of `paths` `failed` with `preparation_stalled` (or `codeOf` its path) at `point`. */
+function stallPaths(engine: BrainEngine, sourceId: string, paths: Set<string>, point: FaultPoint = 'consumer:prepared',
+ codeOf: (path: string) => 'preparation_stalled' | 'write_interrupted' = () => 'preparation_stalled'): { fired: string[] } {
const fired: string[] = [];
installFaultHook(async (at, detail) => {
if (at !== point || detail.sourceId !== sourceId || !detail.requestId) return;
const [row] = await engine.executeRaw<{ path: string | null }>("SELECT intent->>'path' AS path FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);
if (!row?.path || !paths.has(row.path)) return;
fired.push(row.path);
- throw new OperationError('preparation_stalled', `Preparation of ${row.path} did not finish within its attempts (forced probe).`, 'Inspect the writer with gbrain sources writer status.');
+ throw new OperationError(codeOf(row.path), `Preparation of ${row.path} did not finish within its attempts (forced probe).`, 'Inspect the writer with gbrain sources writer status.');
});
return { fired };
}
@@ -453,6 +454,29 @@ test('breaker: five consecutive stalled entries with no commit between stop the
expect(await s.holds()).toEqual([]);
}), 240_000);
+test('breaker: write_interrupted receipts trip it like stalled ones, and the trip names each code instead of calling them preparations that could not finish', () => each(async engine => {
+ const files: Record<string, string> = {};
+ for (let i = 0; i < 7; i++) files[`notes/s${i}.md`] = note(`S${i}`);
+ const s = await source(engine, files);
+ const interrupted = new Set(['notes/s1.md', 'notes/s3.md']);
+ stallPaths(engine, s.id, new Set(Object.keys(files)), 'consumer:prepared', path => interrupted.has(path) ? 'write_interrupted' : 'preparation_stalled');
+ const tripped = await s.sync();
+ expect(tripped).toMatchObject({ status: 'blocked_by_failures', breaker: { code: 'preparation_systemic', rule: 'consecutive', stalled: 5, consecutive: 5 } });
+ expect(tripped.failureCodes).toEqual([{ code: 'preparation_stalled', count: 3 }, { code: 'write_interrupted', count: 2 }]);
+ const why = tripped.breaker!.fix.why;
+ expect(why).toContain('3 could not finish preparing');
+ expect(why).toContain('2 had their statements ended by the database');
+ expect(why).not.toContain('5 write(s) of this sync could not finish preparing');
+ expect((await s.holds()).map(hold => [hold.path, hold.code]).sort()).toEqual([['notes/s0.md', 'preparation_stalled'], ['notes/s1.md', 'write_interrupted'],
+ ['notes/s2.md', 'preparation_stalled'], ['notes/s3.md', 'write_interrupted']]);
+ // Only write_interrupted receipts: the trip names that code alone.
+ const t = await source(engine, files);
+ stallPaths(engine, t.id, new Set(Object.keys(files)), 'consumer:prepared', () => 'write_interrupted');
+ const all = await t.sync();
+ expect(all.failureCodes).toEqual([{ code: 'write_interrupted', count: 5 }]);
+ expect(all.breaker!.fix.why).not.toContain('could not finish preparing');
+}), 240_000);
+
test('breaker: the count rule trips above GBRAIN_SYNC_HOLD_ESCALATE_COUNT (greater than), and a committed page resets the consecutive streak', () => each(async engine => {
await withEnv({ GBRAIN_SYNC_HOLD_ESCALATE_COUNT: '2' }, async () => {
const files: Record<string, string> = {};
diff --git a/test/persistence-write-interrupted.test.ts b/test/persistence-write-interrupted.test.ts
index 1e9c23ab6f..1d288bf605 100644
--- a/test/persistence-write-interrupted.test.ts
+++ b/test/persistence-write-interrupted.test.ts
@@ -24,7 +24,12 @@
* recovering; a crash between them (the `persistence:recovery_interruption_charged` seam) leaves a running request
* that holds its recovery record, which neither expired-owner sweep takes (`recovery IS NULL`), so the owner's
* recovery pass finishes it with the one charge. A group's shared read (preparationReads) the database cancelled is no member's own
- * statement: no member is charged, and a bounded member never reads it as its own deadline.
+ * statement: a bounded member never reads it as its own deadline, and it is charged once, to the first member that
+ * settles with it (the member that would have sent it alone), never to every member. A shared read the database
+ * cancels every time therefore ends bounded: each charged member reaches the limit and ends write_interrupted, and
+ * the last member, alone, takes the single path. write_interrupted is a write error code (a foreground receipt and a
+ * source lifecycle failure name it, never storage_error), and the sync breaker names the write_interrupted receipts
+ * it tripped on instead of reporting them as preparations that could not finish.
* 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.
@@ -54,6 +59,10 @@ import { receiptClass, resumableStop } from '../src/core/persistence/sync-stop-c
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 { importManagedFiles } from '../src/core/persistence/import-mutations.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { assertTopologyCommitted } from '../src/core/persistence/managed-sources.ts';
+import { isWriteErrorCode } from '../src/core/persistence/types.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -93,6 +102,13 @@ test('a shared read the database cancelled is no member\'s own deadline: each me
}
});
+test('write_interrupted is a write error code: a failed source lifecycle names it instead of storage_error', () => {
+ expect(isWriteErrorCode('write_interrupted')).toBe(true);
+ let thrown: unknown;
+ try { assertTopologyCommitted({ state: 'failed', write_error: 'write_interrupted', request_id: randomUUID() }); } catch (error) { thrown = error; }
+ expect(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 };
for (const backend of testBackends()) describe(`[${backend}] transient publication failures are bounded`, () => {
@@ -155,6 +171,10 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati
expect(failed.error_message).toContain('57014');
expect(failed.error_detail).toMatchObject({ origin: 'database_interruption', attempts: 2, limit: 2, 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>;
+ expect(receipt).toMatchObject({ state: 'failed', write_error: 'write_interrupted' });
+ expect(String(receipt.write_error_message)).toContain('57014');
// The source keeps moving: the next write commits.
expect(await call({ slug: `db/after-${n}`, content: page(`After ${n}`), request_id: randomUUID() })).toMatchObject({ state: 'committed' });
}, 120_000);
@@ -248,7 +268,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati
expect(claims.attempts).toEqual([0, 1]);
}, 120_000);
- test('a group\'s shared read the database cancelled charges no member: the member is released uncounted and commits', async () => {
+ test('a group\'s shared read the database cancelled is charged once: the same failure settling a member again is released uncounted', async () => {
const [shared] = await sharedReadFailures();
const slug = `db/shared-${++n}`, requestId = randomUUID();
const claims = { n: 0, attempts: [] as number[] };
@@ -260,7 +280,7 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati
});
expect(await call({ slug, content: page(`Shared ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });
expect(claims.n).toBe(4);
- expect(claims.attempts).toEqual([0, 0, 0, 0]);
+ expect(claims.attempts).toEqual([0, 1, 1, 1]);
}, 120_000);
describe('worktree-backed page', () => {
@@ -329,5 +349,32 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicati
expect(await row(requestId)).toMatchObject({ state: 'committed', preparation_attempts: 0, has_recovery: false });
expect(readFileSync(path, 'utf8')).toContain(`Next ${n}`);
}, 120_000);
+
+ test('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');
+ const dir = `shared-${++n}`;
+ mkdirSync(join(brainDir, dir), { recursive: true });
+ const files = ['a', 'b', 'c'].map(name => {
+ writeFileSync(join(brainDir, dir, `${name}.md`), page(`Shared ${n} ${name}`));
+ return { filePath: join(brainDir, dir, `${name}.md`), sourcePath: `${dir}/${name}.md` };
+ });
+ // Every shared read of a group's preparation is cancelled; a guard far above the bound stops it, so an unbounded loop
+ // ends committed instead of hanging the test.
+ const GUARD = 40;
+ let cancelled = 0;
+ installFaultHook(async point => {
+ if (point === 'group:shared_read' && cancelled < GUARD) { cancelled++; throw interruption('57014'); }
+ });
+ 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}/%`]);
+ // 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.
+ 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(settled.map(result => result.status === 'rejected' ? (result.reason as { code?: string }).code : 'ok')).toEqual(['write_interrupted', 'write_interrupted', 'write_interrupted']);
+ }), 120_000);
});
});