Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): orphan-children kind with torn-TOAST probe, doctor names it, storage_corrupt classifier hint for XX000 (#5216 #4738)
garrytan70afd929ab66
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 06fd5edf14..fb3857bfa1 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -525,6 +525,7 @@ names — reasons may be added, never renamed or removed). All 16:| `db_missing` | 3D000 — the named database does not exist || `schema_missing` | 42P01/42703 — pending migrations (`gbrain apply-migrations --yes`; excluded from the db-repair marker on the MCP mid-operation path, where it usually means code skew) || `pgvector_missing` | the vector extension is absent — auto tier creates it |+| `storage_corrupt` | XX001/XX002, or an XX000 such as `unexpected chunk number … for toast value` or `tuple concurrently deleted` — stored data is damaged; db-repair stops at manual and names the first step, `gbrain repair orphan-children` (preview, includes the torn-TOAST probe; [orphan children](guides/repair.md#orphan-children)) || `unknown` | unclassified — redacted error + `gbrain doctor` |The classifier lives in `src/core/pg-access-classify.ts`; remediation copy hasdiff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 8853a8c8f6..4f793414da 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -6,6 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.+- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 0bc562de15..3eaa6ac19c 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -119,6 +119,7 @@ should also check `results[].complete`.| `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. Releases before this one left the binding behind on `gbrain sources remove` and `gbrain sources purge`, so the re-added source read as claimed and every `gbrain sync --source <id>` failed with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. || `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). || `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |+| `orphan-children` | `child_table_orphans` (also a `storage_corrupt` error) | Explicit-only. Deletes rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page row no longer exists, and clears dangling `links.origin_page_id` and `files.page_id` references, each in one statement that rechecks the orphan condition. See [orphan children](#orphan-children). | `torn_pages`: page rows whose stored body cannot be read (torn TOAST). The preview names them; the repair never changes them. || `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |gbrain repair google-file-modes --apply # explicit-only: runs only when namedgbrain repair --all --apply # every automatic kind in order@@ -314,6 +315,29 @@ Do not delete binding rows by hand: the repair rechecks, in the samestatement, that the binding is still orphaned and that no pending writerequest uses it.+### Orphan children++**Say to your agent:** *"gbrain fails with `unexpected chunk number` or+`tuple concurrently deleted`, or doctor warns `child_table_orphans`. Fix it."*++These errors (SQLSTATE XX000) mean stored data is damaged, usually after a+crash or a full disk. Child rows can outlive their page row, and a page body+can be torn, so every command that reads it fails. Preview first; it changes+nothing:++```bash+gbrain repair orphan-children # orphan child rows per table, plus torn_pages+gbrain repair orphan-children --apply # deletes the orphan rows, clears dangling references+gbrain doctor # child_table_orphans is ok+```++The preview also reads every page body and lists the rows it cannot read+(`torn_pages`, with page id, source and slug). The repair never changes those+rows. Recover them from a backup, or create a fresh brain and sync it again+from its source files. Until then, a write that names the revision of a page+the upgrade could not backfill is refused with `revision_backfill_pending`;+`gbrain apply-migrations --yes` resumes that backfill and prints its progress.+### Timeline history scan coverageDoctor's `timeline_history` check classifies at most 2,000 pages or 10diff --git a/src/commands/db-repair.ts b/src/commands/db-repair.tsindex bdfef4a286..26075d341e 100644--- a/src/commands/db-repair.ts+++ b/src/commands/db-repair.ts@@ -313,6 +313,7 @@ function tierOf(reason: PgAccessReason): 'auto' | 'rewrite' | 'manual' {case 'db_missing':case 'no_url':case 'env_shadowed':+ case 'storage_corrupt':case 'unknown':return 'manual';default: {@@ -776,6 +777,7 @@ async function applyLadder(case 'db_missing':case 'no_url':case 'env_shadowed':+ case 'storage_corrupt':case 'unknown':return manualStop();diff --git a/src/commands/doctor/checks/core-health.ts b/src/commands/doctor/checks/core-health.tsindex 37c5b403b1..0c913a82a9 100644--- a/src/commands/doctor/checks/core-health.ts+++ b/src/commands/doctor/checks/core-health.ts@@ -13,6 +13,7 @@ import { checkLinkSourceCheck } from '../../../core/link-source-check-repair.ts'import { loadConfig } from '../../../core/config.ts';import type { ProgressReporter } from '../../../core/progress.ts';import type { Check } from '../../doctor.ts';+import { PAGE_CHILD_FK_TARGETS, orphanPredicate } from '../../../core/repair/orphan-children.ts';/*** Doctor check: takes.weight grid integrity (v0.32 — EXP-2).@@ -467,8 +468,8 @@ export async function takesWeightGridCheck(engine: BrainEngine): Promise<Check>** All ten FK-to-pages tables declare `ON DELETE CASCADE` in the live schema* (verified via `pg_constraint` snapshot in the issue body), so finding any- * orphan row is by definition unexpected. The check ships paste-ready- * cleanup SQL when orphans surface.+ * orphan row is by definition unexpected. The check names+ * `gbrain repair orphan-children` (the target list lives there).** Excluded: `files.page_id` and `links.origin_page_id` — both declared as* `ON DELETE SET NULL`, so a NULL value is a valid state (file/link survives@@ -479,48 +480,25 @@ export async function takesWeightGridCheck(engine: BrainEngine): Promise<Check>* directly without driving the full `runDoctor` pipeline.*/export async function childTableOrphansCheck(engine: BrainEngine): Promise<Check> {- // (table, fk_column, allow_null). When allow_null=true, NULL is a valid- // state (FK was declared ON DELETE SET NULL); the orphan predicate filters- // out NULL values. When false, NULL is impossible by NOT NULL constraint;- // any value not in pages.id is an orphan.- const targets: Array<{ table: string; col: string; allowNull: boolean }> = [- { table: 'content_chunks', col: 'page_id', allowNull: false },- { table: 'page_versions', col: 'page_id', allowNull: false },- { table: 'tags', col: 'page_id', allowNull: false },- { table: 'takes', col: 'page_id', allowNull: false },- { table: 'raw_data', col: 'page_id', allowNull: false },- { table: 'timeline_entries', col: 'page_id', allowNull: false },- { table: 'links', col: 'from_page_id', allowNull: false },- { table: 'links', col: 'to_page_id', allowNull: false },- { table: 'links', col: 'origin_page_id', allowNull: true },- { table: 'files', col: 'page_id', allowNull: true },- ];let totalOrphans = 0;const breakdown: string[] = [];- const cleanupSql: string[] = [];const errors: string[] = [];- for (const { table, col, allowNull } of targets) {+ for (const target of PAGE_CHILD_FK_TARGETS) {try {- // NOT IN subquery is portable across postgres + PGLite. The `pages.id`- // subquery covers every existing parent row.- const nullFilter = allowNull ? `${col} IS NOT NULL AND ` : '';const rows = await engine.executeRaw<{ n: string | number }>(- `SELECT COUNT(*)::int AS n FROM ${table} WHERE ${nullFilter}${col} NOT IN (SELECT id FROM pages)`,+ `SELECT COUNT(*)::int AS n FROM ${target.table} WHERE ${orphanPredicate(target)}`,);const n = Number(rows[0]?.n ?? 0);if (n > 0) {totalOrphans += n;- breakdown.push(`${table}.${col}=${n}`);- cleanupSql.push(- `DELETE FROM ${table} WHERE ${nullFilter}${col} NOT IN (SELECT id FROM pages);`,- );+ breakdown.push(`${target.table}.${target.col}=${n}`);}} catch (e) {// Table or column may not exist on older schemas — skip and continue.// Aggregate the errors so doctor surfaces "could not check N tables"// when a real failure shape appears (network, lock, syntax).const msg = e instanceof Error ? e.message : String(e);- errors.push(`${table}.${col}: ${msg.slice(0, 80)}`);+ errors.push(`${target.table}.${target.col}: ${msg.slice(0, 80)}`);}}if (totalOrphans === 0 && errors.length === 0) {@@ -537,12 +515,17 @@ export async function childTableOrphansCheck(engine: BrainEngine): Promise<Checkmessage: `Could not check ${errors.length}/10 FK-child tables (older schema or transient error): ${errors.slice(0, 3).join('; ')}`,};}+ const docs = 'docs/guides/repair.md#orphan-children';return {name: 'child_table_orphans',status: 'warn',message:`${totalOrphans} orphan row(s) in FK-child tables (${breakdown.join(', ')}). ` +- `Cleanup: ${cleanupSql.join(' ')}`,+ `Preview: gbrain repair orphan-children — apply: gbrain repair orphan-children --apply. See ${docs}.`,+ details: {+ code: 'child_table_orphans', cause: `child rows reference ${totalOrphans} missing page row(s), usually after storage damage`,+ fix: { kind: 'run_command', argv: ['gbrain', 'repair', 'orphan-children'] }, docs, repair: 'orphan-children', orphans: breakdown,+ },};}diff --git a/src/core/pg-access-classify.ts b/src/core/pg-access-classify.tsindex 2566a7f7b6..f411887bd6 100644--- a/src/core/pg-access-classify.ts+++ b/src/core/pg-access-classify.ts@@ -67,6 +67,7 @@ export type PgAccessReason =| 'db_missing' // 3D000 database does not exist| 'schema_missing' // 42P01 / 42703 missing relation or column| 'pgvector_missing' // vector extension absent+ | 'storage_corrupt' // XX000/XX001/XX002: torn TOAST value, catalog/tuple damage (#5216, #4738)| 'unknown';export type PgAccessFix =@@ -165,6 +166,16 @@ interface ReasonRow {* second person, never preachy.*/const REASON_ROWS: ReadonlyArray<ReasonRow> = [+ {+ reason: 'storage_corrupt',+ transient: false,+ codes: ['XX001', 'XX002'],+ patterns: [/unexpected chunk number/i, /missing chunk number/i, /tuple concurrently (deleted|updated)/i, /invalid page in block/i,+ /could not read block/i, /compressed data is corrupt/i, /found xmin .* from before relfrozenxid/i],+ remediation: 'Stored data looks damaged (SQLSTATE XX000: a torn TOAST value or a damaged row). First preview orphaned child rows and torn page bodies: '+ + 'gbrain repair orphan-children. See docs/guides/repair.md#orphan-children for recovery of the rows it names.',+ fix: { kind: 'run_command', argv: ['gbrain', 'repair', 'orphan-children'] },+ },{reason: 'pgvector_missing',transient: false,diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 79ec677b0a..04061ac7e0 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'orphan-children'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/orphan-children.ts b/src/core/repair/orphan-children.tsnew file mode 100644index 0000000000..7e98360824--- /dev/null+++ b/src/core/repair/orphan-children.ts@@ -0,0 +1,89 @@+/**+ * `gbrain repair orphan-children` (#5216, #4738): remove child rows whose+ * page no longer exists, and find page rows whose stored body cannot be read+ * (a torn TOAST value). Both show up on brains with storage damage: doctor's+ * `child_table_orphans` used to print cleanup SQL no gbrain command could run,+ * and a torn body fails every operation that reads it with SQLSTATE XX000.+ *+ * Each item is one (table, column) pair. Applying it deletes the orphans, or+ * clears the reference for the two ON DELETE SET NULL columns, in one+ * statement that rechecks the orphan predicate. The torn-TOAST probe reads+ * every page body, one batch at a time and then row by row inside a failing+ * batch, and reports the torn pages as a residual with their ids; it never+ * changes them. Brain-wide, bookkeeping only, no journal admission.+ */+import type { BrainEngine } from '../engine.ts';+import type { RepairHandler, RepairItem } from './core.ts';++/** FK children of pages. `allowNull`: the FK is ON DELETE SET NULL, so NULL is valid and an orphan is cleared, not deleted. */+export const PAGE_CHILD_FK_TARGETS: ReadonlyArray<{ table: string; col: string; allowNull: boolean }> = [+ { table: 'content_chunks', col: 'page_id', allowNull: false },+ { table: 'page_versions', col: 'page_id', allowNull: false },+ { table: 'tags', col: 'page_id', allowNull: false },+ { table: 'takes', col: 'page_id', allowNull: false },+ { table: 'raw_data', col: 'page_id', allowNull: false },+ { table: 'timeline_entries', col: 'page_id', allowNull: false },+ { table: 'links', col: 'from_page_id', allowNull: false },+ { table: 'links', col: 'to_page_id', allowNull: false },+ { table: 'links', col: 'origin_page_id', allowNull: true },+ { table: 'files', col: 'page_id', allowNull: true },+];++export function orphanPredicate(target: { col: string; allowNull: boolean }): string {+ return `${target.allowNull ? `${target.col} IS NOT NULL AND ` : ''}${target.col} NOT IN (SELECT id FROM pages)`;+}++const PROBE_BATCH = 500;+const PROBE_SQL = `SELECT id, length(compiled_truth) + length(COALESCE(timeline, '')) + length(COALESCE(frontmatter::text, '')) AS n+ FROM pages WHERE id = ANY($1::bigint[])`;++/** Page ids whose body, timeline or frontmatter cannot be read back. */+export async function probeTornPages(engine: Pick<BrainEngine, 'executeRaw'>): Promise<number[]> {+ const torn: number[] = [];+ let cursor = 0;+ for (;;) {+ const ids = (await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE id > $1 ORDER BY id LIMIT $2', [cursor, PROBE_BATCH])).map(r => Number(r.id));+ if (ids.length === 0) return torn;+ try { await engine.executeRaw(PROBE_SQL, [ids]); }+ catch {+ for (const id of ids) {+ try { await engine.executeRaw(PROBE_SQL, [[id]]); } catch { torn.push(id); }+ }+ }+ cursor = ids[ids.length - 1]!;+ }+}++export const orphanChildrenRepair: RepairHandler = {+ kind: 'orphan-children',+ publication: 'projection',+ embeds: false,+ async plan(engine) {+ const items: RepairItem[] = [];+ for (const [index, target] of PAGE_CHILD_FK_TARGETS.entries()) {+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${target.table} WHERE ${orphanPredicate(target)}`);+ const n = Number(row?.n ?? 0);+ if (n > 0) items.push({ cursor: { phase: 0, id: index + 1 }, source_id: 'brain', slug: `${target.table}.${target.col}`, chars: 0,+ action: target.allowNull ? `clear_${n}_orphan_reference(s)` : `delete_${n}_orphan_row(s)`, change: { from: String(n), to: target.allowNull ? 'null' : 'deleted' } });+ }+ const torn = await probeTornPages(engine);+ const warnings: string[] = [];+ if (torn.length > 0) {+ const named = await engine.executeRaw<{ id: number; source_id: string; slug: string }>(+ 'SELECT id, source_id, slug FROM pages WHERE id = ANY($1::bigint[]) ORDER BY id LIMIT 20', [torn]);+ warnings.push(`${torn.length} page row(s) have a stored body that cannot be read (torn TOAST, SQLSTATE XX000): `+ + `${named.map(p => `#${p.id} ${p.source_id}:${p.slug}`).join(', ')}${torn.length > 20 ? ', …' : ''}. `+ + 'This repair does not change them. Restore the brain from a backup, or re-create it and sync from its source files; see docs/guides/repair.md#orphan-children.');+ }+ const residuals: Record<string, number> = torn.length ? { torn_pages: torn.length } : {};+ return { items, residuals, ...(warnings.length ? { warnings } : {}) };+ },+ async apply(ctx, item) {+ const target = PAGE_CHILD_FK_TARGETS[item.cursor.id - 1];+ if (!target || item.slug !== `${target.table}.${target.col}`) return false;+ const rows = await ctx.engine.executeRaw<{ n: number }>(target.allowNull+ ? `WITH cleared AS (UPDATE ${target.table} SET ${target.col} = NULL WHERE ${orphanPredicate(target)} RETURNING 1) SELECT count(*)::int AS n FROM cleared`+ : `WITH removed AS (DELETE FROM ${target.table} WHERE ${orphanPredicate(target)} RETURNING 1) SELECT count(*)::int AS n FROM removed`);+ return Number(rows[0]?.n ?? 0) > 0;+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 0db950fd6c..9b3e7a52db 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -34,6 +34,7 @@ import { embeddingEffectsRepair } from './embedding-effects.ts';import { googleFileModesRepair } from './google-file-modes.ts';import { staleAtomsRepair } from './stale-atoms.ts';import { extractorFactsRepair } from './extractor-facts.ts';+import { orphanChildrenRepair } from './orphan-children.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -115,6 +116,12 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'without that evidence. Preview-bound: --apply --expect <hash> restores exactly the previewed set; a fact that changed since reports '+ 'changed_since_preview and stays expired. Superseded, withdrawn and duplicated facts are never restored. Database-only; no page is rewritten.',},+ 'orphan-children': {+ handler: orphanChildrenRepair, embeds: 'none', checks: ['child_table_orphans'], explicit_only: true,+ summary: 'Delete rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page no longer exists, and clear dangling '+ + 'links.origin_page_id and files.page_id references (#5216, #4738). The preview also probes every page body and reports torn TOAST rows '+ + '(SQLSTATE XX000) as torn_pages without changing them. Bookkeeping only; no journal admission. Brain-wide; runs only when named.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --git a/test/doctor-child-orphans.test.ts b/test/doctor-child-orphans.test.tsindex 4c15486750..ecf4a2380d 100644--- a/test/doctor-child-orphans.test.ts+++ b/test/doctor-child-orphans.test.ts@@ -32,7 +32,7 @@ describe('childTableOrphansCheck (#1063)', () => {expect(result.message).toContain('10 tables checked');});- test('one orphan in content_chunks → status:warn with paste-ready cleanup SQL', async () => {+ test('one orphan in content_chunks → status:warn naming the repair command (#5216: no raw SQL)', async () => {const engine = makeMockEngine(async (sql: string) => {if (sql.includes('content_chunks')) return [{ n: 5 }];return [{ n: 0 }];@@ -41,10 +41,13 @@ describe('childTableOrphansCheck (#1063)', () => {expect(result.status).toBe('warn');expect(result.message).toContain('5 orphan row(s)');expect(result.message).toContain('content_chunks.page_id=5');- expect(result.message).toContain('DELETE FROM content_chunks WHERE page_id NOT IN (SELECT id FROM pages)');+ expect(result.message).not.toContain('DELETE FROM');+ expect(result.message).toContain('gbrain repair orphan-children --apply');+ expect(result.details).toMatchObject({ code: 'child_table_orphans', fix: { kind: 'run_command', argv: ['gbrain', 'repair', 'orphan-children'] },+ docs: 'docs/guides/repair.md#orphan-children' });});- test('orphans in multiple tables → aggregated breakdown + multi-line cleanup', async () => {+ test('orphans in multiple tables → aggregated breakdown + one repair command', async () => {const engine = makeMockEngine(async (sql: string) => {if (sql.includes('content_chunks')) return [{ n: 234 }];if (sql.includes('page_versions')) return [{ n: 12 }];@@ -57,9 +60,8 @@ describe('childTableOrphansCheck (#1063)', () => {expect(result.message).toContain('content_chunks.page_id=234');expect(result.message).toContain('page_versions.page_id=12');expect(result.message).toContain('tags.page_id=3');- expect(result.message).toContain('DELETE FROM content_chunks');- expect(result.message).toContain('DELETE FROM page_versions');- expect(result.message).toContain('DELETE FROM tags');+ expect(result.message).toContain('Preview: gbrain repair orphan-children');+ expect(result.details?.orphans).toEqual(['content_chunks.page_id=234', 'page_versions.page_id=12', 'tags.page_id=3']);});test('nullable FK (files.page_id, links.origin_page_id) filters IS NOT NULL', async () => {diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 6552fe9a2b..32392074ec 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -191,7 +191,7 @@ for (const backend of testBackends()) {const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };- const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts' };+ const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts', 'orphan-children': 'gbrain repair orphan-children' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --git a/test/pg-access-storage-corrupt-5216.test.ts b/test/pg-access-storage-corrupt-5216.test.tsnew file mode 100644index 0000000000..1622f0bad6--- /dev/null+++ b/test/pg-access-storage-corrupt-5216.test.ts@@ -0,0 +1,28 @@+/**+ * #5216 / #4738: storage damage (a torn TOAST value, "tuple concurrently+ * deleted") used to surface as a bare XX000 with no recovery hint. The+ * classifier names it `storage_corrupt` and points at the repair preview;+ * other internal errors stay unclassified.+ */+import { expect, test } from 'bun:test';+import { classifyPgAccessError } from '../src/core/pg-access-classify.ts';+import { REPAIR_KINDS } from '../src/core/repair/core.ts';++const xx000 = (message: string) => Object.assign(new Error(message), { code: 'XX000' });++test.each([+ 'unexpected chunk number 21 (expected 1) for toast value 141869 in pg_toast_16808',+ 'missing chunk number 0 for toast value 99 in pg_toast_2619',+ 'tuple concurrently deleted',+])('%s → storage_corrupt with the orphan-children preview as the fix', (message) => {+ const d = classifyPgAccessError(xx000(message));+ expect(d.reason).toBe('storage_corrupt');+ expect(d.transient).toBe(false);+ expect(d.fix).toEqual({ kind: 'run_command', argv: ['gbrain', 'repair', 'orphan-children'] });+ expect(d.remediation).toContain('docs/guides/repair.md#orphan-children');+ expect(REPAIR_KINDS).toContain('orphan-children');+});++test('an unrelated internal error is not called storage damage', () => {+ expect(classifyPgAccessError(xx000('cache lookup failed for type 12345')).reason).toBe('unknown');+});diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex a42e5f6229..ffa9d217d6 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts'];+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'orphan-children'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-orphan-children-5216.test.ts b/test/repair-orphan-children-5216.test.tsnew file mode 100644index 0000000000..d6d790dd90--- /dev/null+++ b/test/repair-orphan-children-5216.test.ts@@ -0,0 +1,68 @@+/**+ * #5216 / #4738: doctor's child_table_orphans used to print cleanup SQL that+ * no gbrain command could run. `gbrain repair orphan-children` previews and+ * removes orphaned child rows (clearing the two ON DELETE SET NULL+ * references), and its preview probes every page body for torn TOAST values.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';+import { orphanChildrenRepair } from '../src/core/repair/orphan-children.ts';+import { childTableOrphansCheck } from '../src/commands/doctor/checks/core-health.ts';++let engine: PGLiteEngine;+const ctx = () => ({ engine, config: { engine: 'pglite' }, remote: false, logger: console } as unknown as OperationContext);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const slug of ['notes/kept-example', 'notes/removed-example']) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` }, { sourceId: 'default' });+ }+ const ids = Object.fromEntries((await engine.executeRaw<{ slug: string; id: number }>('SELECT slug, id FROM pages')).map(r => [r.slug, r.id]));+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, origin_page_id) VALUES ($1, $1, 'mention', $2)`,+ [ids['notes/kept-example'], ids['notes/removed-example']]);+ // Recreate storage damage: child rows of a page whose row is gone without the cascade.+ await engine.executeRaw('SET session_replication_role = replica');+ await engine.executeRaw('DELETE FROM pages WHERE id = $1', [ids['notes/removed-example']]);+ await engine.executeRaw(`INSERT INTO tags (page_id, tag) VALUES ($1, 'orphan-tag')`, [ids['notes/removed-example']]);+ await engine.executeRaw('SET session_replication_role = DEFAULT');+}, 60_000);+afterAll(async () => { await engine.disconnect(); });++test('preview lists orphan groups, apply removes them and clears dangling references, doctor goes ok', async () => {+ const before = await childTableOrphansCheck(engine);+ expect(before.status).toBe('warn');+ expect(before.message).toContain('gbrain repair orphan-children');+ const scope = await resolveRepairScope(engine);+ await expect(runRepair(ctx(), orphanChildrenRepair, scope, { apply: false })).rejects.toThrow();+ const preview = await runRepair(ctx(), orphanChildrenRepair, scope, { apply: false, explicit: true });+ expect(preview.sample).toEqual(['brain:tags.page_id', 'brain:links.origin_page_id']);+ expect(preview.residuals).toEqual({});+ const applied = await runRepair(ctx(), orphanChildrenRepair, scope, { apply: true, explicit: true });+ expect(applied.applied).toBe(2);+ expect(await engine.executeRaw("SELECT tag FROM tags WHERE tag = 'orphan-tag'")).toEqual([]);+ const [link] = await engine.executeRaw<{ origin_page_id: number | null }>('SELECT origin_page_id FROM links');+ expect(link!.origin_page_id).toBeNull();+ expect((await childTableOrphansCheck(engine)).status).toBe('ok');+});++test('the preview probes page bodies and reports a torn one by id and slug without changing it', async () => {+ const [{ id }] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'notes/kept-example'");+ const torn = new Proxy(engine, { get(target, prop, receiver) {+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => {+ if (sql.includes('length(compiled_truth)') && JSON.stringify(params).includes(String(id))) {+ return Promise.reject(Object.assign(new Error('unexpected chunk number 21 (expected 1) for toast value 141869 in pg_toast_16808'), { code: 'XX000' }));+ }+ return target.executeRaw(sql, params as never);+ };+ return Reflect.get(target, prop, receiver);+ } }) as PGLiteEngine;+ const plan = await orphanChildrenRepair.plan(torn, await resolveRepairScope(engine), null);+ expect(plan.residuals).toEqual({ torn_pages: 1 });+ expect(plan.warnings?.[0]).toContain(`#${id} default:notes/kept-example`);+ expect(plan.warnings?.[0]).toContain('docs/guides/repair.md#orphan-children');+ expect(await engine.getPage('notes/kept-example', { sourceId: 'default' })).not.toBeNull();+});