Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): bound the failed-writes preview on large request tables (#8707)
garrytan924b96aa284b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 00e93d0379..ed558078ce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**`gbrain repair failed-writes` now previews a brain with a large write journal in about a second instead of timing out.** On Postgres, the preview of refused writes read the request table once per refused write, and one of those reads walked the table from that write to its end. With hundreds of refused writes and a journal of over a million requests, the preview ran for minutes and the server's statement timeout ended it with a bare `internal_error`, so the operator had no way to see or recover the lost writes. The preview now classes every refused write in a few set reads: on a synthetic journal of 1.5 million requests with over 800 refused writes it took 1.2 seconds (it took 265 seconds before), with the same classes and the same preview hash. When a preview read does still run past the timeout, it refuses `repair_preview_timeout` with a fix instead of `internal_error`, and nothing is saved.++### Itemized changes++- `src/core/repair/failed-writes.ts`: recovered fact requests are read once for all refused writes instead of inside the candidate read; replay attempts are read for every refused write together (`request_id = ANY`); later requests of the same page and the file check are read per page, not per write. The listing, classes, residuals and preview hash are unchanged.+- New refusal `repair_preview_timeout`. When the request indexes the preview reads are missing or INVALID, its fix is `gbrain repair request-indexes --apply`; when they are valid, it tells the brain host to run the same preview once with a longer statement timeout.+- Schema migration v291 builds two request-table indexes online (`persistence_requests_replay_id` on the request id, `persistence_requests_slug_sequence` on source, slug and sequence). They join the indexes `gbrain repair request-indexes` and doctor's `persistence_request_indexes` check report. Without them the preview is still bounded, only slower. PGLite and repo-less brains get them unchanged.+- The request-index states doctor and `gbrain repair request-indexes` print now come back in the order the indexes are declared on Postgres as well as PGLite.+- `test/repair-failed-writes-bounded-8707.test.ts` (PGLite and Postgres) seeds a journal with refused writes of every class and checks that the preview's request-table reads stay flat as refused writes grow, that each write gets its class, and that a read ended at the statement timeout refuses `repair_preview_timeout` and saves nothing.+## [0.60.589.0] - 2026-11-06**gbrain can now wake an agent's conversation when a job it started finishes, through Wakeshift. It's off until the brain owner turns it on.**diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex ad2ee2b9b5..ec3faefe12 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4032,6 +4032,16 @@ Reasons: `rename_source_changed`.|---|---|---|---|---|---|---|| A renamed file imported, but removing the page of its old name failed unexpectedly, so that page was kept and may be a duplicate. | An unexpected error is deterministic, so a blocking marker would stop the source on every run; the rename is held instead and the rest of the source keeps syncing. | Ask the user before a full sync of the source (gbrain sync --source <source> --full --no-pull), which removes pages whose file is gone, or remove the old page with gbrain delete. | agent | `repeat the read that failed` | 1 | no |+### repair_preview_timeout++<a id="repair_preview_timeout"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A `gbrain repair failed-writes` preview read ran past the database statement timeout, so the preview stopped; nothing was saved, no approval checkpoint was written and no page changed. | The preview classes every refused caller write against the write journal (replay attempts, later requests of the same page, recovered fact requests) in a few set reads. They use the `persistence_requests_replay_id` and `persistence_requests_slug_sequence` indexes; when either is missing or INVALID, or the journal is large enough that a set read outlasts the timeout, the server ends the read. | Build the request indexes with gbrain repair request-indexes --apply, then run the same preview again; if it stops again with the indexes valid, run it once with a longer statement timeout on the brain host. Run: gbrain repair request-indexes --json | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/troubleshooting.md#repair-preview-timeout](../../docs/guides/troubleshooting.md#repair-preview-timeout)+### request_already_submitted<a id="request_already_submitted"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex c2930d41f8..48add4eeda 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -145,7 +145,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| --- | --- | --- | --- || `timeline` | `timeline_history` | Re-saves each page with its current body through a revision-bound `put_page`. The save writes each database-only timeline entry back into the page as a bullet preceded by `<!-- gbrain:materialized v1 <hash> -->`. | `kept_unrenderable_rows`: entries that would change if written as a bullet (for example an empty source). They stay in the database. || `visibility` | `derived_visibility` | Stamps an explicit `visibility` on extracted atoms and synthesized concepts. An atom takes its origin page's visibility; transcript atoms and atoms whose origin is gone become `private`; a concept takes the strictest visibility of its input atoms. A concept input found only through an atom's `concepts:` list counts as private. Atoms are repaired before concepts. It never loosens an explicit value: `private` stays `private`, and `world` can only become `private`. A missing value is stamped with the origin's value, which is `world` when the origin page is public. | `concepts_without_lineage`: concepts whose inputs cannot be found. They stay as they are, and remote readers already treat a missing visibility as private. `atoms_origin_gone_to_private` counts atoms made private because their origin page no longer exists. |-| `request-indexes` | `persistence_request_indexes` | Creates a missing request-table index (the managed sync checkpoint pair, the purge slug index, the dream postprocess request-id index, the write claims' foreground-commit index), or drops an INVALID one (left by an interrupted concurrent build) and rebuilds it, on a brain whose schema version is already current. Postgres builds each index `CONCURRENTLY`, one at a time, so writes continue; PGLite builds inline. It changes no user data, takes no journal admission and runs brain-wide (`--source` does not narrow it). See [managed sync request indexes](#request-indexes). | `building`: an index another session is still building; it is never dropped. |+| `request-indexes` | `persistence_request_indexes` | Creates a missing request-table index (the managed sync checkpoint pair, the purge slug index, the dream postprocess request-id index, the write claims' foreground-commit index, the failed-writes replay and page-sequence indexes), or drops an INVALID one (left by an interrupted concurrent build) and rebuilds it, on a brain whose schema version is already current. Postgres builds each index `CONCURRENTLY`, one at a time, so writes continue; PGLite builds inline. It changes no user data, takes no journal admission and runs brain-wide (`--source` does not narrow it). See [managed sync request indexes](#request-indexes). | `building`: an index another session is still building; it is never dropped. || `connector-fences` | none (a `connector_fence_below_timeline` refusal names it) | Moves a facts or takes fence that sits below the timeline sentinel of a Google or GitHub page into the page body through a revision-bound `put_page`, so the connector's next re-render carries the fence instead of refusing. Then re-attempt the held item with `gbrain sources retry-held <source>`. | `kept_ambiguous_pages`: pages whose fences are duplicated, unbalanced or unparseable. Move the fence by hand: read the page, place the fence above the `<!-- timeline -->` line, and save it with the current `expected_revision`. || `take-supersession` | none | Rebuilds `takes.superseded_by` for supersession chains written before the pointer moved onto the old fence row (#5886). Each struck take is linked to the row that replaced it only from evidence: a committed `takes_supersede` receipt, a stored `superseded_by`, or a row carrying the old `superseded by #<own row>` pointer with exactly one possible predecessor. The pointer is written onto the old row (`<source>; superseded by #N`) and stale self-pointers are dropped through a revision-bound `put_page`; a page whose fence is already right but whose stored pointers differ is reprojected without a page write. See [take supersession](#take-supersession). | `ambiguous_pages` / `ambiguous_rows`: pages where a new row has two or more possible predecessors, or where evidence conflicts. The preview lists each with its candidates and the manual edit; nothing on them changes. `unparsed_pages`: pages whose takes fence does not parse cleanly. || `accepted-takes` | none | Explicit-only, preview-bound. Restores takes that accepting a held strike-through or kind change removed on v0.60.253.0 (`gbrain trust confirm tp<id>` ran a `takes_remove` instead of applying the change). It restores only what the records prove: the accepted proposal, the `takes_remove` receipt bound to it, the page version that receipt archived (the row the accept should have applied) and the reservation row still holding its number. `--apply --expect <hash>` republishes each page with that row through a revision-bound `put_page`. See [accepted takes](#accepted-takes). | `version_missing` (the archived version was pruned), `row_number_in_use` (the number holds a take again), `page_missing`, `fence_unreadable`. A grade or resolution the database alone held is not in any record and is not restored. |@@ -267,7 +267,9 @@ reads to find the newest foreground commit of a worktree (without it theclaims after a restart can overrun their claim phase on a large request table,so the write queue grows and sync never commits), and`persistence_requests_request_id`, which dream synthesis uses to-find each child's committed page. When that lookup, or a postprocess request+find each child's committed page, and (#8707) `persistence_requests_replay_id`+and `persistence_requests_slug_sequence`, which `gbrain repair failed-writes`+reads to find replay attempts and the later requests of a page. When that lookup, or a postprocess requestread, still hits the statement timeout, the synthesis pass is deferred ratherthan failed: the phase warns `postprocessing deferred`, the pages stayunstamped, and the next pass finishes them without another synthesis call. After@@ -2599,7 +2601,11 @@ receipt alone: an unpinned `remember` (`unpinned_target`) and a `put_page`whose page changed after the revision the caller read (`revision_superseded`, whichthe preview classes `superseded`). Thepreview changes no page content, but it records an approval checkpoint for its-replay set, which `--apply --expect <hash>` reads.+replay set, which `--apply --expect <hash>` reads. The preview reads the write+journal in a few set reads whatever the number of refused writes (#8707); a read+the database ends at its statement timeout stops it with+[`repair_preview_timeout`](troubleshooting.md#repair-preview-timeout) and a fix,+nothing saved.**Say to your agent:** *"Preview which refused writes gbrain can replay, showme the list, then apply after I agree."* The agent runs `gbrain repairdiff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 413829e041..e54f9e5dc6 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -79,6 +79,7 @@| [`gbrain sync` refused `managed_sync_flag_refused`](write-refusals.md#managed_sync_flag_refused) | rerun the same command without the flag `detail` names (`--skip-failed` or `--include-gitignored`); fix a failed file and rerun the plain sync (`--retry-failed` is a deprecated alias), or commit an ignored file | agent | none | `gbrain sources status --json` || [Sync with the deprecated `--retry-failed` alias says failures "belong to a run with different sync options"](#retry-other-options) | run the command printed on each line: `resumable (replay …)` or `resumable (fresh discovery …)` reruns under the failed run's options, `safely orphaned` previews `gbrain repair managed-sync-orphans --source <id>` (apply with its hash), `unresolved` names what has to finish first | agent; the repair apply after the user agrees | the repair retires bookkeeping rows only | `gbrain sync status --source <id> --json` || [Managed sync blocked with `checkpoint_validation_timeout`](#checkpoint-validation-timeout) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …` | brain host | none | `gbrain doctor --only persistence_request_indexes --json` |+| [`gbrain repair failed-writes` preview stopped with `repair_preview_timeout`](#repair-preview-timeout) | follow the refusal's `fix`: `gbrain repair request-indexes --apply` when it names an index, then the same preview | agent (indexes); brain host (a longer timeout) | none | `gbrain doctor --only persistence_request_indexes --json` || Writes fail with `connection_inherited_read_only` (SQLSTATE 25006) | [reset the pooler's server connections, stop session-level `SET`, check role defaults](write-refusals.md#connection_inherited_read_only) | brain host | none | `gbrain doctor --json` || [Doctor warns `persistence_session_timeouts` (`session_timeouts_not_applied`)](#session-timeouts-not-applied) | `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` on the database, or accept it: preparation reads carry their own bound | brain host | none (a role default; `destructive` only in that it changes a server setting) | `gbrain doctor --only persistence_session_timeouts --json` || `gbrain init` or `gbrain upgrade` stops with `schema_lock_blocked` naming a pid (or, before #5227, sat in `wait_event_type=Lock` with no output) | let the named session finish, or with the user's agreement end it on the database host: `SELECT pg_terminate_backend(<pid>)`; then rerun the same command ([ENGINES.md](../ENGINES.md#schema-lock-blocked)) | brain host, after the user agrees | `destructive` when it ends another session | the rerun completes; `gbrain doctor --json` shows the schema at head |@@ -131,6 +132,8 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.+<a id="repair-preview-timeout"></a>**The `gbrain repair failed-writes` preview stopped with `repair_preview_timeout`?** One of its reads of the write journal ran past the database statement timeout, so nothing was saved, no approval checkpoint was written and no page changed. The preview reads the journal in a few set reads (replay attempts by request id, later requests of each page, recovered fact requests) through `persistence_requests_replay_id` and `persistence_requests_slug_sequence`. When the refusal names one of them as missing, INVALID or still building, run `gbrain repair request-indexes --apply` (online, no user data changes), check with `gbrain doctor --only persistence_request_indexes --json`, and run the same preview again. When both indexes are valid, run the preview once on the brain host with a longer statement timeout for that command (`GBRAIN_STATEMENT_TIMEOUT=15min`; behind a transaction-mode pooler that setting is dropped, so raise the role's default as in [session timeouts](#session-timeouts-not-applied)). Older releases ended this preview with a bare `internal_error` on a large request table (#8707).+<a id="pglite-aborted"></a>**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](../ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](../INSTALL.md#pglite-crashes-at-startup-runtimeerror-aborted).<a id="embedding-dimensions"></a>**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch (`migrate embeddings` re-embeds through the provider: effect `paid`, ask the user first). You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings (effects: `credentials` and `paid`, since every page is embedded through the provider; it needs the brain's writer lock, so stop a running `gbrain serve` first; pages and facts are kept), or pass `--no-embedding` up front to make keyless explicit. `gbrain config get embedding_disabled` reports whether embedding is off and which plane says so (the config file and the database setting; `true` on either turns it off); `gbrain config set embedding_disabled true|false` and `gbrain config unset embedding_disabled` change both, and the `init --force --embedding-model` enable path clears both. See [`docs/integrations/embedding-providers.md`](../integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](../operations/headless-install.md) for Docker/CI sequencing.diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 999f15865e..ede72b1f56 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -668,6 +668,12 @@ export const CODES = {rename_held: { class: 'caller', summary: "A renamed file is held because the page it was renamed from changed after the rename was recorded.", reasons: ['rename_source_changed'], why: "Moving the page now could carry the newer edit to the wrong file, so the rename waits for an explicit re-bind.", suggestion: 'Preview the frontmatter repair with --include-ambiguous to re-bind the rename to the current page, and approve it.' },rename_identity_unreadable: { class: 'caller', summary: "A renamed file is held because the database refused to compare its title or frontmatter id (SQLSTATE 22021/22P05), so sync could not tell whether it is the page it replaces.", why: "Which page a file is cannot be decided without comparing its identity; the old page keeps its id, links, facts and timeline and the rest of the source keeps syncing.", suggestion: 'Remove the NUL byte or broken Unicode character from the file title and id, commit, and sync again; the pair is decided again when the file changes.' },rename_reconcile_failed: { class: 'caller', summary: "A renamed file imported, but removing the page of its old name failed unexpectedly, so that page was kept and may be a duplicate.", why: "An unexpected error is deterministic, so a blocking marker would stop the source on every run; the rename is held instead and the rest of the source keeps syncing.", suggestion: 'Ask the user before a full sync of the source (gbrain sync --source <source> --full --no-pull), which removes pages whose file is gone, or remove the old page with gbrain delete.' },+ repair_preview_timeout: { class: 'caller', retryable: false, actor: 'agent',+ summary: "A `gbrain repair failed-writes` preview read ran past the database statement timeout, so the preview stopped; nothing was saved, no approval checkpoint was written and no page changed.",+ why: "The preview classes every refused caller write against the write journal (replay attempts, later requests of the same page, recovered fact requests) in a few set reads. They use the `persistence_requests_replay_id` and `persistence_requests_slug_sequence` indexes; when either is missing or INVALID, or the journal is large enough that a set read outlasts the timeout, the server ends the read.",+ docs: 'docs/guides/troubleshooting.md#repair-preview-timeout',+ suggestion: 'Build the request indexes with gbrain repair request-indexes --apply, then run the same preview again; if it stops again with the indexes valid, run it once with a longer statement timeout on the brain host.',+ fix: { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'agent', why: 'Previews the request-table indexes without changing anything; the refusal names the ones the preview needs when they are not valid.', requires_exclusive: false } },request_already_submitted: { class: 'caller', summary: "This optimizer publication request has already been submitted." },request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.tsindex 0cb0d7aa6d..018711cfaa 100644--- a/src/core/persistence/checkpoint-validation.ts+++ b/src/core/persistence/checkpoint-validation.ts@@ -163,10 +163,11 @@ export async function readRequestIndexStates(engine: Pick<BrainEngine, 'executeR}const rows = await engine.executeRaw<{ name: string; valid: boolean | null; phase: string | null; blocks_done: string | null; blocks_total: string | null }>(`SELECT n.name, i.indisvalid AS valid, p.phase, p.blocks_done::text, p.blocks_total::text- FROM unnest($1::text[]) AS n(name)+ FROM unnest($1::text[]) WITH ORDINALITY AS n(name, position)LEFT JOIN pg_index i ON i.indexrelid = to_regclass(n.name)LEFT JOIN LATERAL (SELECT phase, blocks_done, blocks_total FROM pg_stat_progress_create_index p- WHERE p.relid = i.indrelid AND p.index_relid IN (i.indexrelid, 0) LIMIT 1) p ON true`, [names]);+ WHERE p.relid = i.indrelid AND p.index_relid IN (i.indexrelid, 0) LIMIT 1) p ON true+ ORDER BY n.position`, [names]);return rows.map(row => row.valid === null ? { name: row.name, state: 'missing' }: row.valid ? { name: row.name, state: 'valid' }: row.phase !== null ? { name: row.name, state: 'building', progress: { phase: row.phase, blocks_done: Number(row.blocks_done ?? 0), blocks_total: Number(row.blocks_total ?? 0) } }diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.tsindex 8d75434591..66be38d174 100644--- a/src/core/persistence/schema.ts+++ b/src/core/persistence/schema.ts@@ -46,9 +46,23 @@ export const PERSISTENCE_REQUEST_ID_INDEX = { name: 'persistence_requests_requesexport const PERSISTENCE_FOREGROUND_COMMITTED_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_foreground_committedON persistence_requests(worktree_id,sequence) WHERE state='committed' AND NOT COALESCE(intent->>'kind','') LIKE 'managed_sync_%'`;export const PERSISTENCE_FOREGROUND_COMMITTED_INDEX = { name: 'persistence_requests_foreground_committed', table: 'persistence_requests', sql: PERSISTENCE_FOREGROUND_COMMITTED_INDEX_SQL } as const;+/**+ * #8707: `gbrain repair failed-writes` finds a refused write's replay attempts by request id alone (the id is derived+ * from the refused request, so neither the principal nor the source is known), and finds the later requests of its page+ * (supersession, recovered fact requests) by source, slug and sequence over every receipt, compacted ones included,+ * which the partial slug index above does not hold. Without these each lookup was a sequential scan of the request+ * table, and the preview ran several per refused write. Postgres builds them CONCURRENTLY in the+ * persistence_request_replay_indexes migration (`transaction: false`); PGLite inline.+ */+export const PERSISTENCE_REQUEST_REPLAY_ID_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_replay_id+ ON persistence_requests(request_id)`;+export const PERSISTENCE_REQUEST_REPLAY_ID_INDEX = { name: 'persistence_requests_replay_id', table: 'persistence_requests', sql: PERSISTENCE_REQUEST_REPLAY_ID_INDEX_SQL } as const;+export const PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_slug_sequence+ ON persistence_requests(source_id,slug,sequence)`;+export const PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX = { name: 'persistence_requests_slug_sequence', table: 'persistence_requests', sql: PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX_SQL } as const;/** Every request-table index built online (a migration, then `gbrain repair request-indexes` and doctor `persistence_request_indexes`). */export const PERSISTENCE_REQUEST_ONLINE_INDEXES = [...PERSISTENCE_SYNC_RUN_INDEXES, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX, PERSISTENCE_REQUEST_ID_INDEX,- PERSISTENCE_FOREGROUND_COMMITTED_INDEX] as const;+ PERSISTENCE_FOREGROUND_COMMITTED_INDEX, PERSISTENCE_REQUEST_REPLAY_ID_INDEX, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX] as const;/*** #6317: the movement watermark (the newest committed receipt of a worktree)* that `writer movement`, `data_moving` and doctor `managed_sync_not_moving`@@ -120,6 +134,7 @@ export const PERSISTENCE_CONSUMERS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS persiexport const POSTGRES_CONCURRENT_PERSISTENCE_INDEXES: ReadonlySet<string> = new Set([PERSISTENCE_DATABASE_PENDING_INDEX_SQL, PERSISTENCE_SYNC_RUN_OPEN_INDEX_SQL, PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL, PERSISTENCE_SYNC_WATERMARK_INDEX_SQL, PERSISTENCE_COMPACTABLE_INDEX_SQL,PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL, PERSISTENCE_REQUEST_ID_INDEX_SQL, PERSISTENCE_FOREGROUND_COMMITTED_INDEX_SQL,+ PERSISTENCE_REQUEST_REPLAY_ID_INDEX_SQL, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX_SQL,]);/** Durable infrastructure: never reconstruct or discard these rows during page reindexing. */export const PERSISTENCE_SCHEMA_STATEMENTS = [@@ -216,6 +231,8 @@ export const PERSISTENCE_SCHEMA_STATEMENTS = [PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL,PERSISTENCE_REQUEST_ID_INDEX_SQL,PERSISTENCE_FOREGROUND_COMMITTED_INDEX_SQL,+ PERSISTENCE_REQUEST_REPLAY_ID_INDEX_SQL,+ PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX_SQL,`CREATE INDEX IF NOT EXISTS persistence_requests_principal ON persistence_requests(principal_kind,principal_id,sequence DESC)`,`CREATE TABLE IF NOT EXISTS persistence_effects (id bigserial PRIMARY KEY,diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 4b42497248..4331a8ba24 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1697,6 +1697,10 @@ CREATE INDEX IF NOT EXISTS persistence_requests_request_idON persistence_requests(source_id,request_id);CREATE INDEX IF NOT EXISTS persistence_requests_foreground_committedON persistence_requests(worktree_id,sequence) WHERE state='committed' AND NOT COALESCE(intent->>'kind','') LIKE 'managed_sync_%';+CREATE INDEX IF NOT EXISTS persistence_requests_replay_id+ ON persistence_requests(request_id);+CREATE INDEX IF NOT EXISTS persistence_requests_slug_sequence+ ON persistence_requests(source_id,slug,sequence);CREATE INDEX IF NOT EXISTS persistence_requests_principal ON persistence_requests(principal_kind,principal_id,sequence DESC);CREATE TABLE IF NOT EXISTS persistence_effects (id bigserial PRIMARY KEY,diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex 23bea8ed74..c131c14173 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -61,6 +61,10 @@ import { readFactsBackstopJobPage } from '../persistence/effect-facts.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { dispositionOf, PAGE_REMOVAL_OPERATIONS, supersessionOrderSql, supersessionSql } from '../persistence/terminal-classify.ts';+import { isStatementTimeout } from '../persistence/bounded-reads.ts';+import { readRequestIndexStates } from '../persistence/checkpoint-validation.ts';+import { PERSISTENCE_REQUEST_REPLAY_ID_INDEX, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX } from '../persistence/schema.ts';+import { StatementDeadlineError } from '../statement-deadline.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';const REPLAYABLE = ['put_page', 'add_timeline_entry', 'remember'];@@ -176,16 +180,21 @@ async function failedWrites(engine: BrainEngine, sourceIds: string[], opts: { idELSE r.operation || COALESCE(':' || (r.intent->>'kind'), '') END AS producerFROM persistence_requests rWHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL}${facts ? ` OR ${FACTS_MOVED_REFUSAL}` : ''})- ${facts ? `AND NOT ${FACTS_RECOVERED}` : ''}${id ? 'AND r.id=$3::uuid' : ''}ORDER BY r.sequence`, id ? [sourceIds, REPLAYABLE, id] : [sourceIds, REPLAYABLE]);if (id) return rows;+ // #8707: the recovery check reads only the refused fact requests, in one statement. Correlated into the selection above it+ // ran for every candidate, and the planner walked the request table from each candidate's sequence to the end.+ const factIds = rows.filter(row => row.operation === 'extract_facts').map(row => row.id);+ const recovered = new Set(factIds.length ? (await engine.executeRaw<{ id: string }>(+ `SELECT r.id::text FROM persistence_requests r WHERE r.id = ANY($1::uuid[]) AND ${FACTS_RECOVERED}`, [factIds])).map(row => row.id) : []);+ const live = rows.filter(row => !recovered.has(row.id));// #6429: a replay this command submitted that was refused source_changed is itself a conflict row; the original// write stays the candidate (its attempts are read through replayAttempt), so the attempt rows are not listed twice.const replays = new Set<string>();- const requestIds = new Set(rows.map(row => row.request_id));- for (const row of rows) for (let attempt = 0; requestIds.has(replayId(row.id, attempt)); attempt++) replays.add(replayId(row.id, attempt));- return rows.filter(row => !replays.has(row.request_id));+ const requestIds = new Set(live.map(row => row.request_id));+ for (const row of live) for (let attempt = 0; requestIds.has(replayId(row.id, attempt)); attempt++) replays.add(replayId(row.id, attempt));+ return live.filter(row => !replays.has(row.request_id));}/**@@ -307,14 +316,29 @@ async function replayAttempt(engine: BrainEngine, failedId: string): Promise<{ i}}-/** The newest replay attempt that ended without committing, or null. */-async function lastFailedAttempt(engine: BrainEngine, failedId: string): Promise<WriteRequest | null> {- let last: WriteRequest | null = null;- for (let attempt = 0; ; attempt++) {- const [prior] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [replayId(failedId, attempt)]);- if (!prior || prior.state === 'committed' || !isTerminal(prior)) return last;- last = prior;+/**+ * #8707: each refused write's replay attempts, walked as `replayAttempt` walks them, with one read per attempt number across+ * every write: `committed` when the walk stopped at a committed attempt, `lastFailed` the newest attempt before the stop+ * that ended without committing.+ */+async function replayWalks(engine: BrainEngine, failedIds: string[]): Promise<Map<string, { committed: boolean; lastFailed: WriteRequest | null }>> {+ const walks = new Map<string, { committed: boolean; lastFailed: WriteRequest | null }>();+ const last = new Map<string, WriteRequest>();+ let pending = failedIds;+ for (let attempt = 0; pending.length; attempt++) {+ const found = new Map<string, WriteRequest>();+ for (const row of await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id = ANY($1::uuid[])', [pending.map(id => replayId(id, attempt))])) {+ if (!found.has(String(row.request_id))) found.set(String(row.request_id), row);+ }+ const next: string[] = [];+ for (const id of pending) {+ const prior = found.get(replayId(id, attempt));+ if (!prior || prior.state === 'committed' || !isTerminal(prior)) walks.set(id, { committed: prior?.state === 'committed', lastFailed: last.get(id) ?? null });+ else { last.set(id, prior); next.push(id); }+ }+ pending = next;}+ return walks;}/** W4.11: the reconcile step for a page whose file and database differ. */@@ -341,31 +365,51 @@ async function stillDrifted(engine: BrainEngine, write: FailedWrite): Promise<bo}}-/** Why a caller write must not be replayed now, or `replay`. */-async function disposition(engine: BrainEngine, write: FailedWrite): Promise<{ class: Disposition; detail?: string }> {- if ((await replayAttempt(engine, write.id)).prior?.state === 'committed') return { class: 'already_written', detail: 'replayed by gbrain repair failed-writes' };- const drifted = await lastFailedAttempt(engine, write.id);- if (drifted?.error_code === 'source_changed') {- const [written] = await engine.executeRaw<{ later: boolean }>(- 'SELECT updated_at > $3::timestamptz AS later FROM pages WHERE source_id=$1 AND slug=$2', [write.source_id, write.slug, drifted.updated_at]);- if (!written?.later && await stillDrifted(engine, write)) return { class: 'file_database_drift', detail: driftDetail(write.source_id, write.slug) };- }- const replace = write.operation === 'put_page';- const [later] = await engine.executeRaw<{ state: string; operation: string; same_intent: boolean }>(- `SELECT c.state, c.operation, c.digest=r.digest AS same_intent FROM persistence_requests r JOIN persistence_requests c ON ${supersessionSql('r', 'c')}- WHERE r.id=$1::uuid ORDER BY ${supersessionOrderSql('r', 'c')} LIMIT 1`, [write.id]);- const found = dispositionOf(later);- if (found === 'already_written') return { class: 'already_written' };- if (found === 'duplicate') return { class: 'duplicate', detail: `a later request with the same intent is ${later!.state}` };- if (found === 'superseded') return { class: 'superseded', detail: `a later ${later!.operation} of this page is ${later!.state}` };- const read = write.intent.expected_revision;- if (replace && typeof read === 'string' && read !== await pageRevision(engine, write.source_id, write.slug)) {- return { class: 'superseded', detail: 'the page changed after the revision the caller read' };+type Verdict = { class: Disposition; detail?: string };++/**+ * Why each caller write must not be replayed now, or `replay`. #8707: the request-table reads (replay attempts, later+ * requests of the page) are made once for all the writes, never once per write, and the file check runs once per page.+ */+async function dispositions(engine: BrainEngine, writes: FailedWrite[]): Promise<Map<string, Verdict>> {+ const verdicts = new Map<string, Verdict>();+ const walks = await replayWalks(engine, writes.map(write => write.id));+ const drift = new Map<string, Promise<boolean>>();+ const open: FailedWrite[] = [];+ for (const write of writes) {+ const walk = walks.get(write.id)!;+ if (walk.committed) { verdicts.set(write.id, { class: 'already_written', detail: 'replayed by gbrain repair failed-writes' }); continue; }+ const drifted = walk.lastFailed;+ if (drifted?.error_code === 'source_changed') {+ const [written] = await engine.executeRaw<{ later: boolean }>(+ 'SELECT updated_at > $3::timestamptz AS later FROM pages WHERE source_id=$1 AND slug=$2', [write.source_id, write.slug, drifted.updated_at]);+ const page = `${write.source_id}\0${write.slug}`;+ if (!written?.later && !drift.has(page)) drift.set(page, stillDrifted(engine, write));+ if (!written?.later && await drift.get(page)) { verdicts.set(write.id, { class: 'file_database_drift', detail: driftDetail(write.source_id, write.slug) }); continue; }+ }+ open.push(write);}- if (write.operation === 'remember' && typeof write.intent.entity_slug !== 'string') {- return { class: 'unpinned_target', detail: 'the fact was saved unattributed; replaying would infer its subject again' };+ const later = new Map(open.length ? (await engine.executeRaw<{ id: string; state: string; operation: string; same_intent: boolean }>(+ `SELECT DISTINCT ON (r.id) r.id::text, c.state, c.operation, c.digest=r.digest AS same_intent FROM persistence_requests r JOIN persistence_requests c ON ${supersessionSql('r', 'c')}+ WHERE r.id = ANY($1::uuid[]) ORDER BY r.id, ${supersessionOrderSql('r', 'c')}`, [open.map(write => write.id)])).map(row => [row.id, row]) : []);+ for (const write of open) {+ const row = later.get(write.id);+ const found = dispositionOf(row);+ const read = write.intent.expected_revision;+ if (found === 'already_written') verdicts.set(write.id, { class: 'already_written' });+ else if (found === 'duplicate') verdicts.set(write.id, { class: 'duplicate', detail: `a later request with the same intent is ${row!.state}` });+ else if (found === 'superseded') verdicts.set(write.id, { class: 'superseded', detail: `a later ${row!.operation} of this page is ${row!.state}` });+ else if (write.operation === 'put_page' && typeof read === 'string' && read !== await pageRevision(engine, write.source_id, write.slug)) {+ verdicts.set(write.id, { class: 'superseded', detail: 'the page changed after the revision the caller read' });+ } else if (write.operation === 'remember' && typeof write.intent.entity_slug !== 'string') {+ verdicts.set(write.id, { class: 'unpinned_target', detail: 'the fact was saved unattributed; replaying would infer its subject again' });+ } else verdicts.set(write.id, { class: 'replay' });}- return { class: 'replay' };+ return verdicts;+}++async function disposition(engine: BrainEngine, write: FailedWrite): Promise<Verdict> {+ return (await dispositions(engine, [write])).get(write.id)!;}function item(write: ApprovedWrite, hash: string, last: boolean): FailedWriteItem {@@ -373,41 +417,76 @@ function item(write: ApprovedWrite, hash: string, last: boolean): FailedWriteItechars: typeof write.intent.content === 'string' ? write.intent.content.length : 0, action: `replay:${write.operation}`, failed: write, hash, last };}+/**+ * #8707: a preview read the server ended at its statement timeout (or a statement deadline refused) becomes a refusal+ * with the next step instead of `internal_error`. Nothing was saved: the approval checkpoint is written only after every+ * candidate is classed. When an index the preview reads is not valid, building it is the fix.+ */+async function previewTimeoutRefusal(engine: BrainEngine, error: unknown, scope: RepairScope): Promise<unknown> {+ if (!isStatementTimeout(error) && !(error instanceof StatementDeadlineError)) return error;+ const command = previewCommand(scope);+ const argv = ['gbrain', 'repair', 'failed-writes', ...(scope.source_ids.length === 1 ? ['--source', scope.source_ids[0]!] : []), '--json'];+ const unbuilt = (await readRequestIndexStates(engine, [PERSISTENCE_REQUEST_REPLAY_ID_INDEX, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX]).catch(() => []))+ .filter(index => index.state !== 'valid').map(index => `${index.name} (${index.state})`);+ const refusal = new OperationError('repair_preview_timeout',+ 'The failed-writes preview stopped: a read of the write journal ran past the database statement timeout. Nothing was saved and no page changed.',+ unbuilt.length ? `Build the request indexes the preview reads (${unbuilt.join(', ')}) with gbrain repair request-indexes --apply, then run ${command} again.`+ : `Run ${command} again; if it stops again, raise the statement timeout for that one command on the brain host.`,+ 'docs/guides/troubleshooting.md#repair-preview-timeout');+ refusal.retryable = false;+ refusal.why = unbuilt.length+ ? `Without ${unbuilt.join(' and ')} a lookup of the preview reads the whole request table.`+ : 'Every preview read is a set read over the request table; on this brain one of them took longer than the statement timeout allows.';+ refusal.fix = unbuilt.length+ ? { argv: ['gbrain', 'repair', 'request-indexes', '--apply'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Builds the missing or INVALID request-table indexes online; it changes no user data.',+ verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_request_indexes', '--json'] }, docs: 'docs/guides/repair.md#request-indexes' }+ : { argv, consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Re-runs the read-only preview.',+ user_message: `The preview of refused writes did not finish within the database statement timeout. On the brain host, run ${command} with a longer timeout for that one command (GBRAIN_STATEMENT_TIMEOUT=15min; behind a transaction-mode pooler that setting is dropped, so raise the role's default instead).`,+ verify: { argv }, docs: 'docs/guides/troubleshooting.md#repair-preview-timeout' };+ return refusal;+}+export const failedWritesRepair: RepairHandler = {kind: 'failed-writes',embeds: false,async plan(engine, scope, after, opts): Promise<RepairPlan> {const command = previewCommand(scope);if (!opts?.apply) {- const rows = await failedWrites(engine, scope.source_ids, { facts: true });- const extractions = await factExtractions(engine, scope.source_ids, rows);- const residuals: Record<string, number> = {};- const listing: NonNullable<RepairPlan['listing']> = [];- const producers = new Map<string, string>();- const replay: ApprovedWrite[] = [];- for (const write of rows) {- const label = `${write.source_id}:${write.slug} ${write.operation} (${write.state} ${write.created_at}, request ${write.id})`;- if (write.producer) {- residuals[`producer_owned:${write.producer}`] = (residuals[`producer_owned:${write.producer}`] ?? 0) + 1;- const facts = write.operation === 'extract_facts';- const run = facts ? await factsRecovery(engine, write, extractions) : producerCommand(write.producer, write.source_id);- producers.set(`${write.producer} in ${write.source_id}`, facts ? 'each listed request names the command that recovers its facts' : run);- listing.push({ item: label, class: 'producer_owned', detail: facts ? run : `re-run: ${run}` });- continue;+ try {+ const rows = await failedWrites(engine, scope.source_ids, { facts: true });+ const extractions = await factExtractions(engine, scope.source_ids, rows);+ const verdicts = await dispositions(engine, rows.filter(write => !write.producer));+ const residuals: Record<string, number> = {};+ const listing: NonNullable<RepairPlan['listing']> = [];+ const producers = new Map<string, string>();+ const replay: ApprovedWrite[] = [];+ for (const write of rows) {+ const label = `${write.source_id}:${write.slug} ${write.operation} (${write.state} ${write.created_at}, request ${write.id})`;+ if (write.producer) {+ residuals[`producer_owned:${write.producer}`] = (residuals[`producer_owned:${write.producer}`] ?? 0) + 1;+ const facts = write.operation === 'extract_facts';+ const run = facts ? await factsRecovery(engine, write, extractions) : producerCommand(write.producer, write.source_id);+ producers.set(`${write.producer} in ${write.source_id}`, facts ? 'each listed request names the command that recovers its facts' : run);+ listing.push({ item: label, class: 'producer_owned', detail: facts ? run : `re-run: ${run}` });+ continue;+ }+ const verdict = verdicts.get(write.id)!;+ if (verdict.class === 'replay') replay.push({ ...write, revision: await pageRevision(engine, write.source_id, write.slug), selection: scope.source_ids });+ else residuals[verdict.class] = (residuals[verdict.class] ?? 0) + 1;+ listing.push({ item: label, class: verdict.class, ...(verdict.detail ? { detail: verdict.detail } : {}) });}- const verdict = await disposition(engine, write);- if (verdict.class === 'replay') replay.push({ ...write, revision: await pageRevision(engine, write.source_id, write.slug), selection: scope.source_ids });- else residuals[verdict.class] = (residuals[verdict.class] ?? 0) + 1;- listing.push({ item: label, class: verdict.class, ...(verdict.detail ? { detail: verdict.detail } : {}) });+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);+ const hash = previewHash({ kind: 'failed-writes-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids },+ replay: replay.map(write => ({ id: write.id, digest: write.digest, revision: write.revision })) });+ if (replay.length) await saveApprovedSet<ApprovedWrite>(engine, { command: 'failed-writes', hash }, replay);+ return { items: replay.map((write, index) => item(write, hash, index === replay.length - 1)), preview_hash: hash, residuals, listing,+ warnings: [...[...producers].map(([what, run]) => `${what}: produced by gbrain itself, not replayed here; ${run}`),+ ...(replay.length ? [`This preview recorded an approval checkpoint for its replay set (preview ${hash.slice(0, 12)}), which --apply --expect reads; no page content changed.`] : [])] };+ } catch (error) {+ throw await previewTimeoutRefusal(engine, error, scope);}- const sources = await engine.executeRaw<{ id: string; incarnation: string }>(- 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);- const hash = previewHash({ kind: 'failed-writes-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids },- replay: replay.map(write => ({ id: write.id, digest: write.digest, revision: write.revision })) });- if (replay.length) await saveApprovedSet<ApprovedWrite>(engine, { command: 'failed-writes', hash }, replay);- return { items: replay.map((write, index) => item(write, hash, index === replay.length - 1)), preview_hash: hash, residuals, listing,- warnings: [...[...producers].map(([what, run]) => `${what}: produced by gbrain itself, not replayed here; ${run}`),- ...(replay.length ? [`This preview recorded an approval checkpoint for its replay set (preview ${hash.slice(0, 12)}), which --apply --expect reads; no page content changed.`] : [])] };}if (!opts.expect) {throw new OperationError('invalid_params', 'gbrain repair failed-writes --apply replays only the set a preview printed.',diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex c794939689..e9b5222f7a 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 290;+export const LATEST_SCHEMA_VERSION = 291;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 9f437a9af7..27cc526a32 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -291,6 +291,7 @@ import { v287 } from './v287-multi-page-recovery-record.ts';import { v288 } from './v288-decide-proposals-claim-pair-index.ts';import { v289 } from './v289-page-change-reasons.ts';import { v290 } from './v290-wake-subscriptions.ts';+import { v291 } from './v291-persistence-request-replay-indexes.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -580,4 +581,5 @@ export const MIGRATIONS: Migration[] = [v288,v289,v290,+ v291,];diff --git a/src/core/schema-migrations/v291-persistence-request-replay-indexes.ts b/src/core/schema-migrations/v291-persistence-request-replay-indexes.tsnew file mode 100644index 0000000000..3556ac0df1--- /dev/null+++ b/src/core/schema-migrations/v291-persistence-request-replay-indexes.ts@@ -0,0 +1,25 @@+import type { Migration } from './types.ts';+import { PERSISTENCE_REQUEST_REPLAY_ID_INDEX, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX } from '../persistence/schema.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #8707: the failed-writes repair finds a refused write's replay attempts by+// request id alone and the later requests of its page by source, slug and+// sequence. Neither had an index, so on a large request table each lookup was+// a sequential scan and the preview could not finish. Postgres builds both+// CONCURRENTLY outside a transaction, after dropping an INVALID leftover (the+// blob omits them); PGLite builds them inline. `gbrain repair request-indexes`+// runs the same helper on a brain whose schema is already current. DDL only.+export const v291: Migration = {+ version: 291,+ name: 'persistence_request_replay_indexes',+ idempotent: true,+ transaction: false,+ sql: '',+ handler: async engine => {+ await buildIndexOnline(engine, 291, PERSISTENCE_REQUEST_REPLAY_ID_INDEX, { notice: migrationNotice });+ await buildIndexOnline(engine, 291, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX, { notice: migrationNotice });+ },+};diff --git a/test/e2e/persistence-request-indexes-postgres.test.ts b/test/e2e/persistence-request-indexes-postgres.test.tsindex 0a62d8c5ac..3ef63eb5bc 100644--- a/test/e2e/persistence-request-indexes-postgres.test.ts+++ b/test/e2e/persistence-request-indexes-postgres.test.ts@@ -107,23 +107,23 @@ test('#5762 the Postgres blob never builds the indexes; v179 builds them concurrtry { await v179.handler!(engine); } finally { engine.withReservedConnection = reserve; }expect(statements.filter(sql => sql.startsWith('CREATE INDEX CONCURRENTLY IF NOT EXISTS')).map(sql => sql.split(/\s+/)[6])).toEqual(NAMES);expect(statements.filter(sql => /^(SET|RESET)\b/i.test(sql))).toEqual([]);- expect(await states()).toEqual(['valid', 'valid', 'valid', 'valid', 'valid']);+ expect(await states()).toEqual(['valid', 'valid', 'valid', 'valid', 'valid', 'valid', 'valid']);}), 120_000);test('#5762 gbrain repair request-indexes rebuilds a dropped and an INVALID index on a current schema; a second run is a no-op', async () => withEnv(env, async () => {await engine.executeRaw('DROP INDEX persistence_requests_sync_run_open');await engine.executeRaw("UPDATE pg_index SET indisvalid=false WHERE indexrelid='persistence_requests_sync_run_committed'::regclass");- expect(await readRequestIndexStates(engine)).toEqual([{ name: NAMES[0], state: 'missing' }, { name: NAMES[1], state: 'invalid' }, { name: ALL_NAMES[2], state: 'valid' }, { name: ALL_NAMES[3], state: 'valid' }, { name: ALL_NAMES[4], state: 'valid' }]);+ expect(await readRequestIndexStates(engine)).toEqual([{ name: NAMES[0], state: 'missing' }, { name: NAMES[1], state: 'invalid' }, { name: ALL_NAMES[2], state: 'valid' }, { name: ALL_NAMES[3], state: 'valid' }, { name: ALL_NAMES[4], state: 'valid' }, { name: ALL_NAMES[5], state: 'valid' }, { name: ALL_NAMES[6], state: 'valid' }]);const doctor = await requestIndexesCheck(engine);expect(doctor).toMatchObject({ name: 'persistence_request_indexes', status: 'warn', details: { count: 2, command: 'gbrain repair request-indexes --apply' } });expect(doctor.message).toContain('persistence_requests_sync_run_committed is INVALID');const scope = await resolveRepairScope(engine);const preview = await runRepair(ctx(), requestIndexesRepair, scope, { apply: false });expect(preview).toMatchObject({ affected: 2, cost: { lifetime_ids: 0 }, apply_command: 'gbrain repair request-indexes --apply' });- expect(await states()).toEqual(['missing', 'invalid', 'valid', 'valid', 'valid']);+ expect(await states()).toEqual(['missing', 'invalid', 'valid', 'valid', 'valid', 'valid', 'valid']);const applied = await runRepair(ctx(), requestIndexesRepair, scope, { apply: true });expect(applied).toMatchObject({ applied: 2, complete: true });- expect(await states()).toEqual(['valid', 'valid', 'valid', 'valid', 'valid']);+ expect(await states()).toEqual(['valid', 'valid', 'valid', 'valid', 'valid', 'valid', 'valid']);expect((await requestIndexesCheck(engine)).status).toBe('ok');expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ affected: 0, applied: 0, complete: true });}), 120_000);@@ -142,7 +142,7 @@ test('#5762 a build that leaves the index INVALID (a concurrent caller failed fitry { await expect(buildIndexOnline(engine, 0, index)).rejects.toThrow(`Index ${index.name} is not valid after its concurrent build`); }finally { engine.withReservedConnection = reserve; }expect(await buildIndexOnline(engine, 0, index)).toBe('rebuilt');- expect(await states()).toEqual(['valid', 'valid', 'valid', 'valid', 'valid']);+ expect(await states()).toEqual(['valid', 'valid', 'valid', 'valid', 'valid', 'valid', 'valid']);}), 60_000);test('#5762 recovery journey: a checkpoint timeout with a dropped index is fixed by the two printed commands', async () => withEnv(env, async () => {diff --git a/test/e2e/repair-failed-writes-bounded-8707-postgres.test.ts b/test/e2e/repair-failed-writes-bounded-8707-postgres.test.tsnew file mode 100644index 0000000000..5bcb7ce08c--- /dev/null+++ b/test/e2e/repair-failed-writes-bounded-8707-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-failed-writes-bounded-8707.test.ts'));diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.tsindex 44d99518be..f694bcf9eb 100644--- a/test/fix-wave-4-integration.test.ts+++ b/test/fix-wave-4-integration.test.ts@@ -77,8 +77,8 @@ test('X1: an upgrade from v178 builds the request indexes; managed working-treeawait engine.executeRaw('DROP INDEX IF EXISTS persistence_requests_sync_run_committed');await engine.setConfig('version', '178');expect(await runMigrations(engine)).toEqual({ applied: LATEST_VERSION - 178, current: LATEST_VERSION });- // #6511/#6757/#7649: the online-built set is the checkpoint pair, the purge slug index, the request-id index and the claims' foreground-commit index.- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid']);+ // #6511/#6757/#7649: the online-built set is the checkpoint pair, the purge slug index, the request-id index, the claims' foreground-commit index and the failed-writes replay-id and slug-sequence indexes (#8707).+ expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid', 'valid', 'valid']);expect((await requestIndexesCheck(engine)).status).toBe('ok');const id = `x1-${randomUUID().slice(0, 8)}`, root = join(home, id);@@ -230,7 +230,7 @@ test('X11: the remediation run reaches every new repair kind, runs the free onesconst byKind = Object.fromEntries(run.repairs.map((r: { kind: string }) => [r.kind, r]));expect(byKind['request-indexes']).toMatchObject({ status: 'completed' });expect(byKind['orphan-bindings']).toMatchObject({ status: 'completed' });- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid']);+ expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid', 'valid', 'valid']);expect(await engine.executeRaw("SELECT 1 FROM persistence_source_bindings WHERE source_id='x11-orphan'")).toEqual([]);const replanned = (await planRepairSteps(engine, { noEmbed: true })).map(step => step.kind);expect(replanned).not.toContain('request-indexes');diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 027afe01e2..fec9e3a81f 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -1535,9 +1535,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex f8bae2723b..722a825b30 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -1535,9 +1535,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex c7e2cb48e8..8e479e6910 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -1531,9 +1531,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex a958e1e6ae..65bbed1975 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -1073,9 +1073,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex b32a99536f..d35e63c36a 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -1073,9 +1073,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex e84bd8b167..3f7a1cd9fc 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -1072,9 +1072,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex a53fcdcefc..624cb33ca3 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -1539,9 +1539,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 0000e9004f..88c8ef9c67 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -1539,9 +1539,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex b09bcb6053..29aa872b38 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -1535,9 +1535,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 4200b55924..ad9c1ff7a8 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1486,6 +1486,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 63aece8918..9ad48ef803 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1583,6 +1583,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"@@ -6569,6 +6577,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 17a3ca383e..bd96e1bad2 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1575,6 +1575,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"@@ -6562,6 +6570,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 1b7efad691..414f980d8a 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1363,6 +1363,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 31504a7570..4343f8ca3c 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1419,6 +1419,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 0a6f87c019..8cf0a72730 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1411,6 +1411,14 @@{"name": "persistence_requests_foreground_committed","state": "valid"+ },+ {+ "name": "persistence_requests_replay_id",+ "state": "valid"+ },+ {+ "name": "persistence_requests_slug_sequence",+ "state": "valid"}],"repair": "request-indexes"diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 38d98a6b10..0592b7face 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 285,+ "count": 286,"gaps": [17,18,@@ -44,7 +44,9 @@"PERSISTENCE_EFFECT_PARKED_INDEX_SQL": "0107863883415378d7c0dce7a0cbd5311c2c5a59fc0f81917cc8b767fd235cf2","PERSISTENCE_FOREGROUND_COMMITTED_INDEX": "cb6bb9f8e9bcfd2524a04d05e5da865e92c69442bbcd438d8191d311f76d0663","PERSISTENCE_REQUEST_ID_INDEX": "2c5325e86cf395f617d93a39a45593931639cd8b14fd513b6d9e7d125f16c78f",+ "PERSISTENCE_REQUEST_REPLAY_ID_INDEX": "b9ee7e914c0a8370a9aee053c68d78cdd83a20ffe30c5513d81acf04a3a91761","PERSISTENCE_REQUEST_SLUG_INTENT_INDEX": "5f2e4a3dde452e610fe7eaae949642c00d7c61a363b1cd344d7f0917db233aa5",+ "PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX": "4759eaf319a6ad8d99aae7648acb6556745ed7cba051175273e2f46927c77d52","PERSISTENCE_SYNC_RUN_INDEXES": "e1b12613c5fd2facb850e6857b0bddcf49b2478ec258fa226fe15e71e55df9c1","PERSISTENCE_SYNC_WATERMARK_INDEX": "93523954a30e8483717f07ec97a3e0cd062b15d8a60cc759281054b06c23bb40","PINNED_FUNCTION_NAMES": "aa10ffdebfc6025cbd0235255d01682f16026426ce2383fcd0db57f024e356f1",@@ -94,7 +96,7 @@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 290,+ "latest": 291,"records": [{"handler": {@@ -2288,8 +2290,8 @@"idempotent": true,"name": "durable_concurrent_persistence","sql": {- "length": 15532,- "sha256": "d18cf500d26ac27f68e4cdeb71e9c23220c33505b6b08100377e91fcdf1a82a8"+ "length": 15743,+ "sha256": "c6a64dd7451000894ce425095a465e8c403cd45f989e8f5419109a8360d51484"},"sqlFor": "absent","transaction": "absent",@@ -4700,6 +4702,36 @@"transaction": "absent","verify": "absent","version": 290+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "PERSISTENCE_REQUEST_REPLAY_ID_INDEX",+ "PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX",+ "PLANNER_REPAIR_TABLES",+ "analyzeAfterIndexBuild",+ "analyzeDeferred",+ "analyzeYieldingToVacuum",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "lockTableForAnalyze",+ "migrationNotice",+ "quietMigrationNotices",+ "tableRows"+ ],+ "sha256": "8b1e45df596f4bc7afcace9328cb586f6020cce7819fee175cd315982e8b8a25"+ },+ "idempotent": true,+ "name": "persistence_request_replay_indexes",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": false,+ "verify": "absent",+ "version": 291}],"versions": [@@ -4987,7 +5019,8 @@287,288,289,- 290+ 290,+ 291]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex ba3f7b86f9..6a9406d01b 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -1535,9 +1535,11 @@"persistence_requests_principal": "CREATE INDEX persistence_requests_principal ON public.persistence_requests USING btree (principal_kind, principal_id, sequence DESC)","persistence_requests_principal_kind_principal_id_request_id_key": "CREATE UNIQUE INDEX persistence_requests_principal_kind_principal_id_request_id_key ON public.persistence_requests USING btree (principal_kind, principal_id, request_id)","persistence_requests_recovery": "CREATE INDEX persistence_requests_recovery ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (recovery IS NOT NULL)",+ "persistence_requests_replay_id": "CREATE INDEX persistence_requests_replay_id ON public.persistence_requests USING btree (request_id)","persistence_requests_request_id": "CREATE INDEX persistence_requests_request_id ON public.persistence_requests USING btree (source_id, request_id)","persistence_requests_sequence_key": "CREATE UNIQUE INDEX persistence_requests_sequence_key ON public.persistence_requests USING btree (sequence)","persistence_requests_slug_intent": "CREATE INDEX persistence_requests_slug_intent ON public.persistence_requests USING btree (source_id, slug, sequence) WHERE ((intent IS NOT NULL) AND (NOT compacted))",+ "persistence_requests_slug_sequence": "CREATE INDEX persistence_requests_slug_sequence ON public.persistence_requests USING btree (source_id, slug, sequence)","persistence_requests_sync_run_committed": "CREATE INDEX persistence_requests_sync_run_committed ON public.persistence_requests USING btree (source_id, ((intent ->> 'runId'::text)), ((intent ->> 'index'::text))) WHERE ((state = 'committed'::text) AND (intent ? 'runId'::text))","persistence_requests_sync_run_open": "CREATE INDEX persistence_requests_sync_run_open ON public.persistence_requests USING btree (worktree_id, ((intent ->> 'runId'::text))) WHERE ((state <> 'committed'::text) AND ((intent ->> 'kind'::text) = ANY (ARRAY['managed_sync_import'::text, 'managed_sync_delete'::text])))","persistence_requests_sync_watermark": "CREATE INDEX persistence_requests_sync_watermark ON public.persistence_requests USING btree (worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))",diff --git a/test/migration-persistence-request-slug-index.test.ts b/test/migration-persistence-request-slug-index.test.tsindex bc88c63948..d9c266fe89 100644--- a/test/migration-persistence-request-slug-index.test.ts+++ b/test/migration-persistence-request-slug-index.test.ts@@ -19,7 +19,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { PostgresEngine } from '../src/core/postgres-engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { readRequestIndexStates } from '../src/core/persistence/checkpoint-validation.ts';-import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX, POSTGRES_CONCURRENT_PERSISTENCE_INDEXES } from '../src/core/persistence/schema.ts';+import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX, POSTGRES_CONCURRENT_PERSISTENCE_INDEXES } from '../src/core/persistence/schema.ts';import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.generated.ts';import { SCHEMA_SQL } from '../src/core/schema-embedded.generated.ts';import { MIGRATIONS } from '../src/core/schema-migrations/registry.generated.ts';@@ -98,9 +98,12 @@ for (const backend of testBackends()) describe(`[${backend}] #6511 the slug indeawait engine.executeRaw('ANALYZE persistence_requests');expect(await explain('seed-7')).toContain(INDEX.name);await engine.executeRaw(`DROP INDEX ${INDEX.name}`);+ // #8707: the failed-writes (source, slug, sequence) index also holds these rows; without either slug index the lookup scans the table.+ await engine.executeRaw(`DROP INDEX ${PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX.name}`);expect(await explain('seed-7')).toContain('Seq Scan');await migration!.handler!(engine);expect(await explain('seed-7')).toContain(INDEX.name);+ await engine.executeRaw(PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX.sql);}, 120_000);test('an INVALID index (an interrupted concurrent build) is dropped and rebuilt; the build is CONCURRENTLY outside a transaction and sets nothing on the session', async () => {diff --git a/test/persistence-request-indexes.test.ts b/test/persistence-request-indexes.test.tsindex b84ada9a91..f3ee07e577 100644--- a/test/persistence-request-indexes.test.ts+++ b/test/persistence-request-indexes.test.ts@@ -46,8 +46,8 @@ test('#5762 gbrain repair request-indexes rebuilds a dropped index inline on PGLconst scope = await resolveRepairScope(engine);expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: false })).toMatchObject({ affected: 1, sample: [`(brain):${NAMES[1]}`], cost: { lifetime_ids: 0, embedding_pages: 0 } });expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ applied: 1, complete: true });- // #6511/#6757/#7649: the online-built set is the checkpoint pair, the purge slug, request-id and foreground-commit indexes.- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid']);+ // #6511/#6757/#7649/#8707: the online-built set is the checkpoint pair, the purge slug, request-id and foreground-commit indexes, and the failed-writes replay-id and slug-sequence indexes.+ expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid', 'valid', 'valid']);expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ affected: 0, applied: 0 });}, 60_000);diff --git a/test/persistence-sync-checkpoint-validation.test.ts b/test/persistence-sync-checkpoint-validation.test.tsindex 8df3514492..31f2b8ad55 100644--- a/test/persistence-sync-checkpoint-validation.test.ts+++ b/test/persistence-sync-checkpoint-validation.test.ts@@ -311,13 +311,14 @@ test('#5762 the hint names one of three index states and keeps the saved process});test('#5762 a dropped index reads as missing and the hint then names the rebuild command', async () => each(async engine => {- // #6511, #6757 and #7649 added the purge slug, request-id and foreground-commit indexes to the online-built set; the default read lists them after the checkpoint pair.- expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid']);+ // #6511, #6757, #7649 and #8707 added the purge slug, request-id, foreground-commit, replay-id and slug-sequence indexes to the online-built set; the default read lists them after the checkpoint pair.+ expect((await readRequestIndexStates(engine)).map(index => index.state)).toEqual(['valid', 'valid', 'valid', 'valid', 'valid', 'valid', 'valid']);await engine.executeRaw('DROP INDEX persistence_requests_sync_run_committed');try {expect(await readRequestIndexStates(engine)).toEqual([{ name: 'persistence_requests_sync_run_open', state: 'valid' },{ name: 'persistence_requests_sync_run_committed', state: 'missing' }, { name: 'persistence_requests_slug_intent', state: 'valid' },- { name: 'persistence_requests_request_id', state: 'valid' }, { name: 'persistence_requests_foreground_committed', state: 'valid' }]);+ { name: 'persistence_requests_request_id', state: 'valid' }, { name: 'persistence_requests_foreground_committed', state: 'valid' },+ { name: 'persistence_requests_replay_id', state: 'valid' }, { name: 'persistence_requests_slug_sequence', state: 'valid' }]);} finally {const { PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL } = await import('../src/core/persistence/schema.ts');await engine.executeRaw(PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL);diff --git a/test/repair-failed-writes-bounded-8707.test.ts b/test/repair-failed-writes-bounded-8707.test.tsnew file mode 100644index 0000000000..408f111e35--- /dev/null+++ b/test/repair-failed-writes-bounded-8707.test.ts@@ -0,0 +1,161 @@+/**+ * #8707: `gbrain repair failed-writes` previews stay bounded on a large request table, with the same classes as before.+ *+ * The preview used to read the request table once per refused write, several times over (replay attempts by request id,+ * the later requests of the page, a correlated fact-recovery check the planner ran for every candidate), so on a large+ * brain one statement outlasted the statement timeout and the preview died with `internal_error`. The test pins that+ * the preview's request-table statements do not grow with the number of refused writes, that each class it lists is+ * the one the per-row rules give, and that a statement the server ends at its timeout comes back as the+ * `repair_preview_timeout` refusal with a fix, nothing saved. Runs on PGLite and, through test/e2e, Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { digest } from '../src/core/persistence/digest.ts';+import { FACTS_ENTITY_MOVED_MESSAGES } from '../src/core/persistence/verb-errors.ts';+import { PERSISTENCE_REQUEST_REPLAY_ID_INDEX, PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX } from '../src/core/persistence/schema.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const logger = { info() {}, warn() {}, error() {} };+const replayId = (failedId: string, attempt: number) => {+ const h = digest(['failed-writes-replay-v1', failedId, attempt]);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+};++/** Counts the statements that read the request table, through the engine the repair runner is given. */+function counting(engine: BrainEngine): { engine: BrainEngine; reads: () => number } {+ let reads = 0;+ const view = new Proxy(engine, { get(target, key) {+ const value = Reflect.get(target, key, target);+ if (key !== 'executeRaw') return typeof value === 'function' ? value.bind(target) : value;+ return (sql: string, ...rest: unknown[]) => { if (sql.includes('persistence_requests')) reads++; return (value as Function).call(target, sql, ...rest); };+ } }) as BrainEngine;+ return { engine: view, reads: () => reads };+}++async function receipt(engine: BrainEngine, sourceId: string, incarnation: string, row: { operation: string; slug: string; state: string; digest?: string;+ intent?: Record<string, unknown> | null; outcome?: Record<string, unknown>; error_code?: string; error_message?: string; request_id?: string; compacted?: boolean }): Promise<string> {+ const [inserted] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,+ authority,state,intent_bytes,terminal_reservation,outcome,error_code,error_message,compacted)+ VALUES('local_cli','cli',$1::uuid,$2,$3,$4::uuid,$5,$6,$7::text::jsonb,'{}'::jsonb,$8,100,100,$9::text::jsonb,$10,$11,$12) RETURNING id::text`,+ [row.request_id ?? randomUUID(), row.operation, sourceId, incarnation, row.slug, row.digest ?? randomUUID(), row.intent === null ? null : JSON.stringify(row.intent ?? {}),+ row.state, row.outcome ? JSON.stringify(row.outcome) : null, row.error_code ?? null, row.error_message ?? null, row.compacted ?? false]);+ return inserted!.id;+}++/** A source with a committed history and every preview class among its refused writes; `extra` more plain refused remembers. */+async function seed(engine: BrainEngine, extra: number): Promise<{ sourceId: string; expected: Map<string, string> }> {+ const sourceId = `b8707-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,NULL)', [sourceId]);+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const add = (row: Parameters<typeof receipt>[3]) => receipt(engine, sourceId, incarnation, row);+ const refused = { state: 'conflict', error_code: 'source_changed', error_message: 'refused' };+ const expected = new Map<string, string>();+ for (let i = 0; i < 30; i++) await add({ operation: 'put_page', slug: `people/history-${i}`, state: 'committed', intent: i % 3 ? { kind: 'managed_sync_import' } : null, compacted: i % 3 === 0 });+ expected.set(await add({ operation: 'remember', slug: 'people/alice-example', ...refused, intent: { entity_slug: 'people/alice-example', claim: 'a' } }), 'replay');+ const same = randomUUID();+ expected.set(await add({ operation: 'remember', slug: 'people/alice-example', ...refused, digest: same, intent: { entity_slug: 'people/alice-example', claim: 'b' } }), 'already_written');+ await add({ operation: 'remember', slug: 'people/alice-example', state: 'committed', digest: same, intent: { entity_slug: 'people/alice-example', claim: 'b' } });+ const twin = randomUUID();+ expected.set(await add({ operation: 'remember', slug: 'people/bob-example', ...refused, digest: twin, intent: { entity_slug: 'people/bob-example', claim: 'c' } }), 'duplicate');+ expected.set(await add({ operation: 'remember', slug: 'people/bob-example', state: 'failed', error_code: 'writer_coordinator_required', digest: twin,+ intent: { entity_slug: 'people/bob-example', claim: 'c' } }), 'replay');+ expected.set(await add({ operation: 'remember', slug: 'people/carol-example', ...refused, intent: { claim: 'unpinned' } }), 'unpinned_target');+ const replayed = await add({ operation: 'add_timeline_entry', slug: 'people/carol-example', state: 'failed', error_code: 'writer_coordinator_required', intent: { slug: 'people/carol-example', summary: 's' } });+ await add({ operation: 'add_timeline_entry', slug: 'people/carol-example', state: 'conflict', error_code: 'source_changed', request_id: replayId(replayed, 0), intent: { slug: 'people/carol-example', summary: 's' } });+ await add({ operation: 'add_timeline_entry', slug: 'people/carol-example', state: 'committed', request_id: replayId(replayed, 1), intent: { slug: 'people/carol-example', summary: 's' } });+ expected.set(replayed, 'already_written');+ expected.set(await add({ operation: 'put_page', slug: 'people/dana-example', ...refused, intent: { slug: 'people/dana-example', content: 'x' } }), 'superseded');+ await add({ operation: 'delete_page', slug: 'people/dana-example', state: 'committed', intent: { slug: 'people/dana-example' }, compacted: true });+ const moved = { state: 'conflict', error_code: 'revision_conflict', error_message: FACTS_ENTITY_MOVED_MESSAGES[0] };+ const recovered = await add({ operation: 'extract_facts', slug: 'people/erin-example', ...moved, intent: { kind: 'managed_facts_entity', inputDigest: 'd1', batchKey: '0' } });+ await add({ operation: 'extract_facts', slug: 'people/erin-example', state: 'committed', intent: null, compacted: true, outcome: { input_digest: 'd1', batch_key: '1' } });+ expected.set(recovered, 'not_listed');+ expected.set(await add({ operation: 'extract_facts', slug: 'people/erin-example', ...moved, intent: { kind: 'managed_facts_entity', inputDigest: 'd2', batchKey: '0' } }), 'producer_owned');+ for (let i = 0; i < extra; i++) {+ expected.set(await add({ operation: 'remember', slug: `people/extra-${i % 7}`, ...refused, intent: { entity_slug: `people/extra-${i % 7}`, claim: `e${i}` } }), 'replay');+ await add({ operation: 'put_page', slug: `people/history-${i}`, state: 'committed', intent: { kind: 'managed_sync_import' } });+ }+ return { sourceId, expected };+}++async function preview(engine: BrainEngine, sourceId: string) {+ const scope = await resolveRepairScope(engine, sourceId);+ return (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+}++for (const backend of testBackends()) describe(`[${backend}] #8707 the failed-writes preview on a large request table`, () => {+ let engine: BrainEngine;+ let databaseUrl: string | undefined;+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; databaseUrl = pg.databaseUrl; closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => { await engine.disconnect(); await closePostgres?.(); }, 60_000);++ test('request-table reads do not grow with the refused writes, and each write gets the class its rules give', async () => {+ const reads: number[] = [];+ for (const extra of [5, 60]) {+ const { sourceId, expected } = await seed(engine, extra);+ const view = counting(engine);+ const result = await preview(view.engine, sourceId);+ reads.push(view.reads());+ const listed = new Map((result.listing ?? []).map(entry => [/request ([0-9a-f-]{36})\)/.exec(entry.item)![1]!, entry.class]));+ for (const [id, klass] of expected) expect([id, listed.get(id) ?? 'not_listed']).toEqual([id, klass]);+ expect(listed.size).toBe([...expected.values()].filter(klass => klass !== 'not_listed').length);+ expect(result.residuals).toMatchObject({ already_written: 2, duplicate: 1, unpinned_target: 1, superseded: 1 });+ }+ expect(reads[1]).toBe(reads[0]);+ }, 120_000);++ test('a preview read the server ends at its timeout is a repair_preview_timeout refusal with a fix; nothing is saved', async () => {+ const { sourceId } = await seed(engine, 3);+ const checkpoints = async () => Number((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM op_checkpoints WHERE op='repair-approval'"))[0]!.n);+ const before = await checkpoints();+ const refused = async (target: BrainEngine) => {+ const error = await preview(target, sourceId).then(() => null, (caught: unknown) => caught);+ expect(error).toBeInstanceOf(OperationError);+ const refusal = error as OperationError;+ expect(refusal.code).toBe('repair_preview_timeout');+ expect(refusal.retryable).toBe(false);+ expect(refusal.message).toContain('Nothing was saved');+ return refusal;+ };+ if (backend === 'postgres') {+ // A real server timeout: another session holds the request table, and the preview's connection has a 1 s statement timeout.+ const timed = await withEnv({ GBRAIN_STATEMENT_TIMEOUT: '1s' }, async () => { const e = new PostgresEngine(); await e.connect({ database_url: databaseUrl!, poolSize: 1 }); return e; });+ try {+ const refusal = await engine.transaction(async tx => {+ await tx.executeRaw('LOCK TABLE persistence_requests IN ACCESS EXCLUSIVE MODE');+ return refused(timed);+ });+ expect(refusal.fix).toMatchObject({ actor: 'host_admin', argv: ['gbrain', 'repair', 'failed-writes', '--source', sourceId, '--json'] });+ } finally { await timed.disconnect(); }+ } else {+ const timeout = new Proxy(engine, { get(target, key) {+ const value = Reflect.get(target, key, target);+ if (key !== 'executeRaw') return typeof value === 'function' ? value.bind(target) : value;+ return (sql: string, ...rest: unknown[]) => sql.includes('request_id = ANY')+ ? Promise.reject(Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' }))+ : (value as Function).call(target, sql, ...rest);+ } }) as BrainEngine;+ expect((await refused(timeout)).fix).toMatchObject({ actor: 'host_admin', argv: ['gbrain', 'repair', 'failed-writes', '--source', sourceId, '--json'] });+ await engine.executeRaw(`DROP INDEX ${PERSISTENCE_REQUEST_REPLAY_ID_INDEX.name}`);+ try {+ const refusal = await refused(timeout);+ expect(refusal.fix).toMatchObject({ actor: 'agent', argv: ['gbrain', 'repair', 'request-indexes', '--apply'] });+ expect(refusal.suggestion).toContain(`${PERSISTENCE_REQUEST_REPLAY_ID_INDEX.name} (missing)`);+ expect(refusal.suggestion).not.toContain(PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX.name);+ } finally { await engine.executeRaw(PERSISTENCE_REQUEST_REPLAY_ID_INDEX.sql); }+ }+ expect(await checkpoints()).toBe(before);+ }, 120_000);+});