Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): synthesis postprocess looks up committed outputs by uuid through a request-id index and defers on a statement timeout (#6757)

garrytan7bd759177257
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 2a276576e6..3858f94367 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -9,7 +9,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/behavior-changes.ts` — `behavior_changes` (META, after `chat_fallback_chain`): the `behavior_changes` disclosure read again (`src/core/behavior-change-notice.ts`): every change newer than the brain's baseline, labeled by release, whether or not the notice was shown; always `ok`; reads the baseline and markers without recording either, and reports which channels were shown.
- `src/commands/doctor/checks/ranking-extraction.ts` — informational BRAIN check `extraction_date_grounding`, registered after `timeline_history`: fact extraction, synthesis, atoms and takes grounded by default, all off when the setting is false, and whether the chronicle prompt is opted in. Pinned by `test/doctor-ranking-extraction.test.ts` and the doctor registry/JSON goldens.
- `src/commands/doctor/checks/vector-plan.ts` — `vector_plan` (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement `searchVector` emits for the active embedding column with a zero vector through `PostgresEngine.explainVectorSearch` (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (`pg_index.indisvalid`, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (`pg_class.reltuples` x `pg_stats.null_frac`, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to `gbrain embed --stale` above 5%. Tested in `test/e2e/vector-plan-real-column-postgres.test.ts` (empty, small, ok, unused valid index, INVALID index, guard via env and config).
-- `src/commands/doctor/checks/persistence-requests.ts` — wave checks (OPS, registered in `wave-checks.ts`); `persistence_terminal_failures` (#6650) is in [Managed sync bookkeeping](managed-sync-bookkeeping.md). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. `persistence_write_stall` (#6176, host-only) reads running requests and warns when one has held its claim longer than `persistence.max_claim_ms` (`claim-phase.ts`; an owner that predates phase recording falls back to the request's age on the database clock), naming the stuck phase, the root, the claim age, the queued writes behind it and whether the request resumes on its own, with `gbrain sources writer status --source <id> --json` as the fix. `persistence_session_timeouts` (#6278, host-only) reads `SHOW statement_timeout` through the configured URL and warns `session_timeouts_not_applied` when it is `0` while `resolveSessionTimeouts()` configured one (a transaction-mode pooler dropped the startup parameter), naming the role-level fix. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`, `test/persistence-write-stall.test.ts`, `test/persistence-session-timeouts-check.test.ts`.
+- `src/commands/doctor/checks/persistence-requests.ts` — wave checks (OPS, registered in `wave-checks.ts`); `persistence_terminal_failures` (#6650) is in [Managed sync bookkeeping](managed-sync-bookkeeping.md). `persistence_request_indexes` (#5762) reports each request index missing, INVALID or building, naming `gbrain repair request-indexes --apply`, and 3+ consecutive dream postprocess deferrals (#6757). `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. `persistence_write_stall` (#6176, host-only) reads running requests and warns when one has held its claim longer than `persistence.max_claim_ms` (`claim-phase.ts`; an owner that predates phase recording falls back to the request's age on the database clock), naming the stuck phase, the root, the claim age, the queued writes behind it and whether the request resumes on its own, with `gbrain sources writer status --source <id> --json` as the fix. `persistence_session_timeouts` (#6278, host-only) reads `SHOW statement_timeout` through the configured URL and warns `session_timeouts_not_applied` when it is `0` while `resolveSessionTimeouts()` configured one (a transaction-mode pooler dropped the startup parameter), naming the role-level fix. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`, `test/persistence-write-stall.test.ts`, `test/persistence-session-timeouts-check.test.ts`.
- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` and no recorded origin (blank `source_path` and `source_uri`) per source, via `databaseOnlyPageSql` (`persistence/unbound-pages.ts`), the SQL form of `isDatabaseOnlyPage` (#6536). A managed sync that records a page's origin, and a reconcile apply, clear the marker. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Tests: `e2e/unbound-source-postgres`, `unbound-source-6536`.
- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index 63601eaec8..bffc3eb0d1 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -4,7 +4,8 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Synthesis, patterns, consolidation and connector atom gating.
-- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. `loadCommittedSynthesisOutputs` finds each child's committed output by canonicalizing the retained `brain_put_page` input (`parseWriteRequestId` for the request id, `journaledPageSlug` for the slug) before matching request id, source, incarnation, committed put_page, slug and revision (#6616); slug discovery (`collectChildPutPageSlugs`) and postprocessing share that set. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output. `deferPublishOrThrow` defers an output or summary publish that is still pending or whose admission gave up on database contention (`publicationHold` in `persistence/accepted-pending.ts`, one stderr line per contended publish) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp; every other error fails the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`. #5575 I2: each output publishes with `derivation` from its transcript (`dream-taint.ts` `transcriptDerivation`; `meetingTranscriptsDir` in opts); a retained request replays the declaration it was admitted with. #6360: when the page moved after the child commit, a drift made only by committed local `managed_maintenance_page` requests (for example the next cycle's lint `created:` fix) over a body equal to the child's is adopted: the postprocess runs on the current snapshot under a request id that also binds that base revision (found again on replay among the later requests). Any other later write leaves the page alone as a `PostprocessConflict` (`withPostprocessConflicts`: phase `warn`, `details.postprocess_conflicts` with the read-only `gbrain get` fix); it is reported once (config `dream.synthesize.postprocess_conflicts`, 30-day memory) and does not block the cooldown stamp.
+- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. `loadCommittedSynthesisOutputs` finds each child's committed output by canonicalizing the retained `brain_put_page` input (`parseWriteRequestId` for the request id, `journaledPageSlug` for the slug) before matching request id, source, incarnation, committed put_page, slug and revision (#6616); slug discovery (`collectChildPutPageSlugs`) and postprocessing share that set. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output. `deferPublishOrThrow` defers an output or summary publish that is still pending or whose admission gave up on database contention (`publicationHold` in `persistence/accepted-pending.ts`, one stderr line per contended publish) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp; every other error fails the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`. #5575 I2: each output publishes with `derivation` from its transcript (`dream-taint.ts` `transcriptDerivation`; `meetingTranscriptsDir` in opts); a retained request replays the declaration it was admitted with. #6360: when the page moved after the child commit, a drift made only by committed local `managed_maintenance_page` requests (for example the next cycle's lint `created:` fix) over a body equal to the child's is adopted: the postprocess runs on the current snapshot under a request id that also binds that base revision (found again on replay among the later requests). Any other later write leaves the page alone as a `PostprocessConflict` (`withPostprocessConflicts`: phase `warn`, `details.postprocess_conflicts` with the read-only `gbrain get` fix); it is reported once (config `dream.synthesize.postprocess_conflicts`, 30-day memory) and does not block the cooldown stamp. #6757: the committed-outputs join (`COMMITTED_OUTPUT_REQUESTS_SQL`) compares `request_id` as a uuid within the source, served by `persistence_requests_request_id`. The phase loads it through `loadCommittedOutputsOrDefer`; a statement timeout there, or on an output's own `getWriteRequest`, defers the pass instead of failing it (`withPublishPending` with `details.postprocess_deferred`: phase warn, no cooldown stamp, no summary). Deferred and publish-pending outputs are carried by `synthesize-postprocess-deferral.ts` and finished by a later pass from the carried fields, with no child; `finishDeferredPostprocess` (run after the phase body by `runPhaseSynthesize`) finishes them when that pass returned before postprocessing.
+- `src/core/cycle/synthesize-postprocess-deferral.ts` — #6757: config row `dream.synthesize.postprocess_pending`, keyed by source and bound to its incarnation: each pending output (child request id, journaled and input slug, revision, job key, transcript path, content hash, seat, first write) and the source's consecutive deferred passes with the last read and its elapsed time. `isPostprocessReadTimeout` unwinds a cancelled cycle first, then accepts only SQLSTATE 57014 with the statement-timeout message (a user cancel is not deferred). `recordPostprocessPass` drops settled outputs, adds deferred and carried ones and resets the count on a pass that deferred nothing; `repeatedPostprocessDeferrals` lists sources at three or more for doctor `persistence_request_indexes`.
- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302: `collectChildTimelineAppends` selects the entries the child newly published with `brain_add_timeline_entry` by write receipt (`persistence_requests` committed with outcome status `ok`, joined on the call's input `request_id`), once per request id and per entry identity, so a replay or a re-append of an existing entry (`skipped`) is not a new append. On pages the child did not `put_page`, `groundTimelineAppends` quote-verifies only those entry blocks against this run's reflections: a failing entry (with its materialized marker line) leaves the timeline for `unverified_claims` (its timeline row is deleted on the import path; a managed publish projects rows from the Markdown), a near/normalized quote is repaired in place, and everything else on the page, `quote_verified_at` and stored claim sources included, is kept. Those pages are provenance-stamped, reverse-written and counted in `patterns_written`; `details.timeline_appends` counts the entries and `quote_verify.timeline_appends` the grounding. `details.appended_unverified` (`countChildTimelineAppends`, completed calls) is a deprecated alias. Segmented storage: `loadGroundingSources` reads a segmented reflection through `materializeSegmentedBody` (over `PAGE_MAX_BYTES` it is not a source, logged), and `groundTimelineAppends` reads pattern pages through `materializedSnapshot`, skipping an over-ceiling page (`segmented_skipped`). Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts` and `test/cycle-patterns-segmented.test.ts` (both engines). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`. #6297: an in-cycle run (not `--once`, not a direct `--phase patterns`, `CycleOpts.directPhases`) is skipped with `patterns_min_interval` while the partition's last COMPLETED child ended less than `dream.patterns.min_interval_hours` (default 6, 0 off) ago (`patternsCadenceSkip` in `patterns-plan.ts`; stamp `dream.patterns.last_completed_at.<source>.<incarnation>`, `.external` for the external partition), and the child gets `read_budget_bytes` from `dream.patterns.child_read_budget_kb` (default 200). Pinned by `test/cycle-patterns-cadence.serial.test.ts` and `test/cycle-patterns-read-budget.serial.test.ts`.
- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws.
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 036adb54a9..80c3094167 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -2,7 +2,7 @@
[Subsystem index](../KEY_FILES.md) · [Core Persistence](core-persistence.md) · [continued](core-persistence-continued.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (`gbrain repair stuck-recovery`) that uses them.
+The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index, dream postprocessing's request-id index), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (`gbrain repair stuck-recovery`) that uses them.
- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 31004ce4d8..6012773d82 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -128,7 +128,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 managed sync request 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), 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. |
@@ -211,7 +211,7 @@ Git-backed source and while the account differs
([`connector_account_changed`](write-refusals.md#connector-account-changed)).
<a id="request-indexes"></a>
-### Managed sync request indexes
+### Request-table indexes
A managed sync checkpoint checks that every page receipt of its run
committed. Two indexes serve that check, `persistence_requests_sync_run_open`
@@ -226,13 +226,26 @@ and is not retried ahead of other writes.
**Say to your agent:** *"My sync says checkpoint_validation_timeout. What do I run?"*
-`gbrain doctor` reports `persistence_request_indexes`: ok when both indexes are
-valid, a warning with progress while one is still building (leave it
+`gbrain doctor` reports `persistence_request_indexes`: ok when every request-table
+index is valid, a warning with progress while one is still building (leave it
running), and a warning naming `gbrain repair request-indexes --apply` when one
is missing or INVALID. After the rebuild, run the retry the refusal printed
(`gbrain sync --source <source> --no-pull --retry-failed` plus the saved
processing flags).
+The same command builds `persistence_requests_slug_intent` (the page purge's
+lookup) and `persistence_requests_request_id`, which dream synthesis uses to
+find each child's committed page. When that lookup, or a postprocess request
+read, still hits the statement timeout, the synthesis pass is deferred rather
+than failed: the phase warns `postprocessing deferred`, the pages stay
+unstamped, and the next pass finishes them without another synthesis call. After
+three deferred passes in a row the doctor check names the source, the read, how
+long it ran and the pending outputs. It names the rebuild only when an index is
+missing or INVALID; otherwise compare the elapsed time with
+`persistence_session_timeouts`.
+
+**Say to your agent:** *"Dream keeps saying postprocessing deferred. What's wrong?"*
+
<a id="request-growth"></a>
### Request-table growth
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index 8c85fcbafe..a6069058aa 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -9,16 +9,22 @@ import { resolvePrepare, resolveSessionTimeouts } from '../../../core/db.ts';
import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
import { lostCallerWrites } from '../../../core/repair/failed-writes.ts';
import { readCapacityForecast, readCapacityThresholds } from '../../../core/persistence/capacity-forecast.ts';
+import { DEFERRED_READ_LABEL, repeatedPostprocessDeferrals } from '../../../core/cycle/synthesize-postprocess-deferral.ts';
+import { PERSISTENCE_REQUEST_ID_INDEX } from '../../../core/persistence/schema.ts';
const WINDOW_DAYS = 7;
const SAMPLE = 10_000;
const HORIZON_DAYS = 3650;
/**
- * #5762: the managed sync checkpoint validation relies on two request
- * indexes that Postgres builds CONCURRENTLY. Reports each one missing, left
- * INVALID by an interrupted build, or still building (with progress), and the
- * one command that rebuilds it on a current schema.
+ * #5762: managed sync checkpoint validation, the page purge's slug lookup and
+ * dream synthesis postprocessing read the request table through indexes that
+ * Postgres builds CONCURRENTLY. Reports each one missing, left INVALID by an
+ * interrupted build, or still building (with progress), and the one command
+ * that rebuilds it on a current schema. #6757: also names a source whose
+ * synthesis postprocessing deferred three or more passes in a row on a
+ * statement timeout, with the read, its elapsed time and the pending outputs;
+ * the rebuild is named only when the request-id index is what is missing.
*/
export async function requestIndexesCheck(engine: BrainEngine): Promise<Check> {
const docs = 'docs/guides/repair.md#request-indexes';
@@ -26,14 +32,24 @@ export async function requestIndexesCheck(engine: BrainEngine): Promise<Check> {
const indexes = await readRequestIndexStates(engine);
const broken = indexes.filter(index => index.state === 'missing' || index.state === 'invalid');
const building = indexes.filter(index => index.state === 'building');
- const details = { count: broken.length, indexes, repair: 'request-indexes', command: REQUEST_INDEXES_REPAIR_COMMAND, docs };
+ const deferred = await repeatedPostprocessDeferrals(engine).catch(() => []);
+ const postprocess = deferred.map(d => ({ source_id: d.source_id, consecutive_passes: d.consecutive, read: d.last_read ?? null,
+ elapsed_ms: d.last_elapsed_ms ?? null, pending_outputs: d.pending.length, last_deferred_at: d.last_deferred_at ?? null }));
+ const details = { count: broken.length, indexes, repair: 'request-indexes', command: REQUEST_INDEXES_REPAIR_COMMAND, docs,
+ ...(postprocess.length ? { postprocess_deferred: postprocess } : {}) };
+ const deferral = postprocess.length ? ` Dream synthesis postprocessing deferred on a statement timeout ${postprocess.map(d => `${d.consecutive_passes} passes in a row on source ${d.source_id} `
+ + `(${d.read ? DEFERRED_READ_LABEL[d.read] : 'a request read'}, ${d.elapsed_ms ?? '?'} ms; ${d.pending_outputs} output(s) pending)`).join('; ')}.` : '';
if (broken.length) return { name: 'persistence_request_indexes', status: 'warn', details,
- message: `${broken.map(index => `${index.name} is ${index.state === 'invalid' ? 'INVALID' : 'missing'}`).join('; ')}: managed sync checkpoints can time out `
- + `on a large request table. Rebuild on the brain host: ${REQUEST_INDEXES_REPAIR_COMMAND}` };
+ message: `${broken.map(index => `${index.name} is ${index.state === 'invalid' ? 'INVALID' : 'missing'}`).join('; ')}: request-table reads (managed sync checkpoints, page purges, `
+ + `dream synthesis postprocessing) can time out on a large request table. Rebuild on the brain host: ${REQUEST_INDEXES_REPAIR_COMMAND}${deferral}` };
if (building.length) return { name: 'persistence_request_indexes', status: 'warn', details,
message: `Still building: ${building.map(index => `${index.name} (${index.progress?.phase ?? 'building'}${index.progress?.blocks_total
- ? `, ${index.progress.blocks_done}/${index.progress.blocks_total} blocks` : ''})`).join('; ')}. It is safe to leave running; rerun gbrain doctor to follow it.` };
- return { name: 'persistence_request_indexes', status: 'ok', message: 'Managed sync request indexes are valid.', details };
+ ? `, ${index.progress.blocks_done}/${index.progress.blocks_total} blocks` : ''})`).join('; ')}. It is safe to leave running; rerun gbrain doctor to follow it.${deferral}` };
+ if (postprocess.length) return { name: 'persistence_request_indexes', status: 'warn', details,
+ message: `Request-table indexes are valid, including ${PERSISTENCE_REQUEST_ID_INDEX.name}, so the timeout is not a missing index.${deferral} `
+ + 'The deferred outputs finish without another synthesis call on the first pass whose read completes; compare the elapsed time with the session statement_timeout '
+ + '(doctor persistence_session_timeouts).' };
+ return { name: 'persistence_request_indexes', status: 'ok', message: 'Request-table indexes are valid.', details };
} catch (error) {
return { name: 'persistence_request_indexes', status: 'warn',
message: `Request indexes could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
diff --git a/src/core/cycle/synthesize-postprocess-deferral.ts b/src/core/cycle/synthesize-postprocess-deferral.ts
new file mode 100644
index 0000000000..aaeb642182
--- /dev/null
+++ b/src/core/cycle/synthesize-postprocess-deferral.ts
@@ -0,0 +1,113 @@
+/**
+ * #6757: dream synthesis postprocessing reads the request journal twice: the
+ * committed-outputs join (`loadCommittedSynthesisOutputs`) and each output's
+ * own postprocess request (`getWriteRequest`). When either read hits the
+ * statement timeout the children have already run and been paid for, so the
+ * pass is deferred, never failed: the outputs it could not finish are recorded
+ * here, with everything their postprocess request id is derived from (the
+ * child's request id, revision and job key, the transcript path and the content
+ * hash it was synthesized from), so a later pass finishes them without
+ * re-running a child, even after the transcript grows or `jobs prune` removes
+ * the child's rows. State lives in one config row keyed by source; a pass that
+ * defers increments the source's consecutive count and a pass that does not
+ * resets it, so doctor `persistence_request_indexes` can name a repeating
+ * deferral.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { throwIfAborted } from '../abort-check.ts';
+
+export const POSTPROCESS_PENDING_KEY = 'dream.synthesize.postprocess_pending';
+/** Consecutive deferred passes after which doctor names the deferral. */
+export const POSTPROCESS_DEFERRAL_WARN_PASSES = 3;
+
+export type DeferredRead = 'committed_outputs' | 'postprocess_request';
+
+/** One child output whose postprocessing has not finished. */
+export interface PendingOutput {
+ request_id: string;
+ slug: string;
+ input_slug: string;
+ revision: string;
+ job_key: string;
+ raw_source: string;
+ transcript_hash: string;
+ seat?: string;
+ first_write_at?: string;
+}
+
+export interface SourceDeferral {
+ source_incarnation: string;
+ consecutive: number;
+ last_attempt_at: string;
+ last_deferred_at?: string;
+ last_read?: DeferredRead;
+ last_elapsed_ms?: number;
+ pending: PendingOutput[];
+}
+
+/** What a deferred pass reports in its phase result. */
+export interface PostprocessDeferral { read: DeferredRead; elapsed_ms: number; outputs: number; consecutive: number }
+
+/**
+ * A statement timeout from one of the two deferrable reads. A cancelled cycle
+ * unwinds first (an explicit cancel also raises SQLSTATE 57014), and only the
+ * server's statement-timeout message counts, so a user cancel is never
+ * deferred.
+ */
+export function isPostprocessReadTimeout(error: unknown, signal: AbortSignal | undefined): boolean {
+ throwIfAborted(signal, '[dream] synthesis postprocessing');
+ const e = error as { code?: unknown; message?: unknown; cause?: { code?: unknown; message?: unknown } } | null;
+ const code = e?.code ?? e?.cause?.code;
+ return code === '57014' && /statement timeout/i.test(`${e?.message ?? ''} ${e?.cause?.message ?? ''}`);
+}
+
+export async function readPostprocessDeferrals(engine: Pick<BrainEngine, 'getConfig'>): Promise<Record<string, SourceDeferral>> {
+ try {
+ const parsed = JSON.parse(await engine.getConfig(POSTPROCESS_PENDING_KEY) ?? '{}') as Record<string, SourceDeferral>;
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
+ } catch { return {}; }
+}
+
+/** The outputs still pending for one source incarnation (another incarnation's are moot). */
+export async function pendingOutputsFor(engine: Pick<BrainEngine, 'getConfig'>, sourceId: string, incarnation: string): Promise<PendingOutput[]> {
+ const entry = (await readPostprocessDeferrals(engine))[sourceId];
+ return entry?.source_incarnation === incarnation && Array.isArray(entry.pending) ? entry.pending : [];
+}
+
+/**
+ * Record one postprocess pass for a source: drop the outputs it finished or
+ * left alone for good, add the ones it deferred or could not publish yet
+ * (`carry`), and count consecutive deferred passes. Returns the deferral to
+ * report, or null when the pass deferred no read.
+ */
+export async function recordPostprocessPass(engine: Pick<BrainEngine, 'getConfig' | 'setConfig'>, sourceId: string, incarnation: string,
+ pass: { settled: string[]; carry?: PendingOutput[]; deferred?: { read: DeferredRead; elapsed_ms: number; pending: PendingOutput[] } }): Promise<PostprocessDeferral | null> {
+ const state = await readPostprocessDeferrals(engine);
+ const prior = state[sourceId]?.source_incarnation === incarnation ? state[sourceId] : undefined;
+ const settled = new Set(pass.settled);
+ const pending = new Map((prior?.pending ?? []).filter(p => !settled.has(p.request_id)).map(p => [p.request_id, p]));
+ for (const p of [...pass.deferred?.pending ?? [], ...pass.carry ?? []]) pending.set(p.request_id, p);
+ const now = new Date().toISOString();
+ const consecutive = pass.deferred ? (prior?.consecutive ?? 0) + 1 : 0;
+ if (!pending.size && !consecutive) {
+ if (!state[sourceId]) return null;
+ delete state[sourceId];
+ } else {
+ state[sourceId] = { source_incarnation: incarnation, consecutive, last_attempt_at: now, pending: [...pending.values()],
+ ...(pass.deferred ? { last_deferred_at: now, last_read: pass.deferred.read, last_elapsed_ms: pass.deferred.elapsed_ms } : {}) };
+ }
+ await engine.setConfig(POSTPROCESS_PENDING_KEY, JSON.stringify(state));
+ return pass.deferred ? { read: pass.deferred.read, elapsed_ms: pass.deferred.elapsed_ms, outputs: pending.size, consecutive } : null;
+}
+
+/** Sources whose postprocessing deferred at least `POSTPROCESS_DEFERRAL_WARN_PASSES` passes in a row (doctor). */
+export async function repeatedPostprocessDeferrals(engine: Pick<BrainEngine, 'getConfig'>): Promise<Array<{ source_id: string } & SourceDeferral>> {
+ return Object.entries(await readPostprocessDeferrals(engine))
+ .filter(([, entry]) => Number(entry?.consecutive) >= POSTPROCESS_DEFERRAL_WARN_PASSES)
+ .map(([source_id, entry]) => ({ source_id, ...entry }));
+}
+
+export const DEFERRED_READ_LABEL: Record<DeferredRead, string> = {
+ committed_outputs: 'the committed-outputs read',
+ postprocess_request: 'a postprocess request read',
+};
diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.ts
index 1e0724a404..05f20f2c6a 100644
--- a/src/core/cycle/synthesize-postprocess.ts
+++ b/src/core/cycle/synthesize-postprocess.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import { throwIfAborted } from '../abort-check.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
@@ -10,7 +11,7 @@ import { digest } from '../persistence/digest.ts';
import { getWriteRequest } from '../persistence/journal.ts';
import { parseWriteRequestId } from '../persistence/preconditions.ts';
import type { WriteRequest } from '../persistence/model.ts';
-import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import { writeResponse } from '../persistence/service.ts';
import type { PhaseResult } from '../cycle.ts';
import type { DiscoveredTranscript } from './transcript-discovery.ts';
@@ -18,6 +19,10 @@ import { transcriptDerivation } from './dream-taint.ts';
import { declareDerivation, readDerivationDeclaration } from '../trust/taint.ts';
import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource, type GroundingPass } from './synthesize-verify.ts';
import { attributionChecksEnabled } from './attribution-checks.ts';
+import { resolveGroundingDecide } from './grounding-decide.ts';
+import { resolveCycleDate } from './cycle-date.ts';
+import { DEFERRED_READ_LABEL, isPostprocessReadTimeout, pendingOutputsFor, readPostprocessDeferrals, recordPostprocessPass,
+ type DeferredRead, type PendingOutput, type PostprocessDeferral } from './synthesize-postprocess-deferral.ts';
interface OutputRef { slug: string; source_id: string; raw_source?: string; seat?: string; first_write_at?: Date; }
export interface RetainedOutput { job_id: number | bigint; job_key: string; input_slug: string; request: WriteRequest; }
@@ -59,30 +64,93 @@ export const journaledPageSlug = (slug: string): string => slug.toLowerCase();
* slug discovery and postprocessing so the two cannot disagree.
*/
export async function loadCommittedSynthesisOutputs(engine: BrainEngine, authority: MaintenanceAuthority, childIds: number[]): Promise<RetainedOutput[]> {
+ return committedRequestsFor(engine, authority, await retainedPutPageCalls(engine, childIds));
+}
+
+interface RetainedCall { job_id: number | bigint; job_key: string; input_slug: string; slug: string; requestId: string; revision: string; started_at?: string }
+
+async function retainedPutPageCalls(engine: BrainEngine, childIds: number[]): Promise<RetainedCall[]> {
if (!childIds.length) return [];
- const tools = await engine.executeRaw<{ job_id: number | bigint; job_key: string; input: Record<string, unknown> | null; output: Record<string, unknown> | null }>(
- `SELECT t.job_id,j.idempotency_key AS job_key,t.input,t.output
+ const tools = await engine.executeRaw<{ job_id: number | bigint; job_key: string; input: Record<string, unknown> | null; output: Record<string, unknown> | null; started_at: Date | string | null }>(
+ `SELECT t.job_id,j.idempotency_key AS job_key,t.input,t.output,t.started_at
FROM subagent_tool_executions t JOIN minion_jobs j ON j.id=t.job_id
WHERE t.job_id=ANY($1::int[]) AND t.tool_name='brain_put_page' AND t.status='complete' AND t.output->>'state'='committed'`, [childIds]);
- const calls = tools.flatMap(t => {
+ return tools.flatMap(t => {
const inputSlug = t.input?.slug;
const revision = t.output?.revision;
let requestId: string | undefined;
try { requestId = parseWriteRequestId(t.input?.request_id); } catch { return []; }
+ const startedAt = t.started_at ? new Date(t.started_at) : null;
return requestId && typeof inputSlug === 'string' && typeof revision === 'string'
- ? [{ job_id: t.job_id, job_key: t.job_key, input_slug: inputSlug, slug: journaledPageSlug(inputSlug), requestId, revision }] : [];
+ ? [{ job_id: t.job_id, job_key: t.job_key, input_slug: inputSlug, slug: journaledPageSlug(inputSlug), requestId, revision,
+ ...(startedAt && !Number.isNaN(startedAt.getTime()) ? { started_at: startedAt.toISOString() } : {}) }] : [];
});
- if (!calls.length) return [];
- const requests = await engine.executeRaw<{ request: WriteRequest }>(
- `SELECT row_to_json(p) AS request FROM persistence_requests p
- WHERE p.request_id::text=ANY($1::text[]) AND p.source_id=$2 AND p.source_incarnation=$3
+}
+
+/**
+ * #6757: the committed journal row of each retained call, looked up by request id (a uuid, as the column is) within
+ * the cycle's source, which `persistence_requests_request_id` serves; a text cast of the column defeats every index.
+ */
+export const COMMITTED_OUTPUT_REQUESTS_SQL = `SELECT row_to_json(p) AS request FROM persistence_requests p
+ WHERE p.source_id=$2 AND p.request_id=ANY($1::uuid[]) AND p.source_incarnation=$3
AND p.operation='put_page' AND p.state='committed'
- ORDER BY p.sequence DESC`, [[...new Set(calls.map(c => c.requestId))], authority.writer.sourceId, authority.writer.sourceIncarnation]);
+ ORDER BY p.sequence DESC`;
+
+async function committedRequestsFor(engine: BrainEngine, authority: MaintenanceAuthority, calls: RetainedCall[]): Promise<RetainedOutput[]> {
+ if (!calls.length) return [];
+ const requests = await engine.executeRaw<{ request: WriteRequest }>(COMMITTED_OUTPUT_REQUESTS_SQL,
+ [[...new Set(calls.map(c => c.requestId))], authority.writer.sourceId, authority.writer.sourceIncarnation]);
return requests.flatMap(({ request }) => calls
.filter(c => c.requestId === String(request.request_id) && c.slug === request.slug && c.revision === request.outcome?.revision)
.map(c => ({ job_id: c.job_id, job_key: c.job_key, input_slug: c.input_slug, request })));
}
+/** Child outputs for postprocessing, or the outputs to carry when the committed-outputs read hit the statement timeout (#6757). */
+export interface CommittedOutputs { outputs: RetainedOutput[]; deferred?: { read: DeferredRead; elapsed_ms: number; pending: PendingOutput[] } }
+
+/**
+ * #6757: `loadCommittedSynthesisOutputs` for the phase. A statement timeout on the journal join defers the pass:
+ * every retained call becomes a pending output with its transcript path and content hash, so a later pass finishes it
+ * without the job rows or the transcript's current hash. Any other error, and a cancelled cycle, propagates.
+ */
+export async function loadCommittedOutputsOrDefer(engine: BrainEngine, authority: MaintenanceAuthority, childIds: number[],
+ ctx: { jobRawSource: Map<number, string>; transcripts: Array<{ filePath: string; contentHash: string; seat?: string }>; signal?: AbortSignal }): Promise<CommittedOutputs> {
+ const calls = await retainedPutPageCalls(engine, childIds);
+ const started = Date.now();
+ try {
+ return { outputs: await committedRequestsFor(engine, authority, calls) };
+ } catch (error) {
+ if (!isPostprocessReadTimeout(error, ctx.signal)) throw error;
+ const byPath = new Map(ctx.transcripts.map(t => [t.filePath, t]));
+ const pending = calls.flatMap(c => {
+ const transcript = byPath.get(ctx.jobRawSource.get(Number(c.job_id)) ?? '');
+ return transcript ? [{ request_id: c.requestId, slug: c.slug, input_slug: c.input_slug, revision: c.revision, job_key: c.job_key,
+ raw_source: transcript.filePath, transcript_hash: transcript.contentHash, ...(transcript.seat ? { seat: transcript.seat } : {}),
+ ...(c.started_at ? { first_write_at: c.started_at } : {}) }] : [];
+ });
+ return { outputs: [], deferred: { read: 'committed_outputs', elapsed_ms: Date.now() - started, pending } };
+ }
+}
+
+/** A transcript as postprocessing reads it: the discovered one, or a carried output's file read again (#6757). */
+type TranscriptInput = Pick<DiscoveredTranscript, 'filePath' | 'contentHash' | 'content' | 'seat'>;
+interface Item { ref: OutputRef; output?: RetainedOutput; path?: string; transcript?: TranscriptInput; hash?: string }
+
+const pendingOf = (item: Item): PendingOutput[] => item.output && item.path && item.hash && typeof item.output.request.outcome?.revision === 'string'
+ ? [{ request_id: String(item.output.request.request_id), slug: item.output.request.slug, input_slug: item.output.input_slug,
+ revision: item.output.request.outcome.revision, job_key: item.output.job_key, raw_source: item.path, transcript_hash: item.hash,
+ ...(item.transcript?.seat ? { seat: item.transcript.seat } : {}), ...(item.ref.first_write_at ? { first_write_at: item.ref.first_write_at.toISOString() } : {}) }] : [];
+
+/** A carried output's transcript: the one discovered this pass at its path, else its file; null for one no longer readable. */
+function carriedTranscript(p: PendingOutput, byPath: Map<string, DiscoveredTranscript>): TranscriptInput | null | undefined {
+ const found = byPath.get(p.raw_source);
+ if (found) return found;
+ // A conversation page is discovered from the database, never read here; it stays pending until a pass discovers it.
+ if (!p.raw_source.startsWith('/')) return undefined;
+ try { return { filePath: p.raw_source, contentHash: p.transcript_hash, content: readFileSync(p.raw_source, 'utf8'), ...(p.seat ? { seat: p.seat } : {}) }; }
+ catch { return null; }
+}
+
export async function postprocessManagedSynthesis(
engine: BrainEngine,
authority: MaintenanceAuthority,
@@ -91,8 +159,8 @@ export async function postprocessManagedSynthesis(
jobRawSource: Map<number, string>,
transcripts: DiscoveredTranscript[],
opts: { cycleDate: string; quoteVerify: boolean; sinceByTranscript: Map<string, Date>; signal?: AbortSignal; grounding?: GroundingPass;
- /** The child outputs slug discovery already loaded (loadCommittedSynthesisOutputs). */
- committedOutputs?: RetainedOutput[];
+ /** The child outputs slug discovery already loaded (loadCommittedOutputsOrDefer). */
+ committedOutputs?: CommittedOutputs;
/** #5575 I2: files under it are third-party speech; their outputs publish external_untrusted. */
meetingTranscriptsDir?: string | null },
) {
@@ -101,38 +169,89 @@ export async function postprocessManagedSynthesis(
const finalizedRefs: OutputRef[] = [];
const conflicts: PostprocessConflict[] = [];
let pending = 0;
- if (!refs.length) return { writtenRefs, finalizedRefs, stats, pending, conflicts };
+ const { sourceId, sourceIncarnation } = authority.writer;
+ // #6757: outputs an earlier pass deferred are finished here, whether or not their child is in this pass.
+ const carried = await pendingOutputsFor(engine, sourceId, sourceIncarnation);
+ const settled: string[] = [], carry: PendingOutput[] = [];
+ let deferred: CommittedOutputs['deferred'];
+ if (opts.committedOutputs?.deferred) {
+ const deferral = await recordPostprocessPass(engine, sourceId, sourceIncarnation, { settled, deferred: opts.committedOutputs.deferred });
+ return { writtenRefs, finalizedRefs, stats, pending: deferral?.outputs ?? 0, conflicts, deferral };
+ }
+ if (!refs.length && !carried.length) return { writtenRefs, finalizedRefs, stats, pending, conflicts, deferral: null };
const reported = await readReportedConflicts(engine);
const supersession = opts.quoteVerify ? await attributionChecksEnabled(engine) : false; // #5425 [UC4], default off
- const outputs = opts.committedOutputs ?? await loadCommittedSynthesisOutputs(engine, authority, childIds);
+ const outputs = opts.committedOutputs?.outputs ?? await loadCommittedSynthesisOutputs(engine, authority, childIds);
const byPath = new Map(transcripts.map(t => [t.filePath, t]));
+ const items: Item[] = [...refs].sort((a, b) => (a.raw_source ?? '').localeCompare(b.raw_source ?? '')).map(ref => {
+ const output = outputs.find(o => o.request.slug === ref.slug);
+ const path = output && jobRawSource.get(Number(output.job_id));
+ const transcript = path ? byPath.get(path) : undefined;
+ return { ref, output, path, transcript, hash: transcript?.contentHash };
+ });
+ const open = carried.filter(p => !outputs.some(o => String(o.request.request_id) === p.request_id));
+ if (open.length) {
+ const started = Date.now();
+ let found: RetainedOutput[] | null = null;
+ try {
+ found = await committedRequestsFor(engine, authority, open.map(p => ({ job_id: 0, job_key: p.job_key, input_slug: p.input_slug, slug: p.slug, requestId: p.request_id, revision: p.revision })));
+ } catch (error) {
+ if (!isPostprocessReadTimeout(error, opts.signal)) throw error;
+ deferred = { read: 'committed_outputs', elapsed_ms: Date.now() - started, pending: [] };
+ pending += open.length;
+ }
+ for (const p of found ? open : []) {
+ const output = found!.find(o => String(o.request.request_id) === p.request_id);
+ const transcript = carriedTranscript(p, byPath);
+ if (transcript === undefined) { carry.push(p); pending++; continue; }
+ if (!output || !transcript) {
+ settled.push(p.request_id);
+ if (!reported.has(p.request_id)) conflicts.push({ slug: p.slug, source_id: sourceId, request_id: p.request_id,
+ message: `Deferred synthesis output ${p.slug} in source ${sourceId} ${output ? `lost its transcript ${p.raw_source}` : `has no committed journal row for child request ${p.request_id}`}, so postprocessing left it alone and did not verify or stamp it. Review the page; this output is not retried.`,
+ fix: writerStatusFix(sourceId, `Shows source ${sourceId}'s committed and pending maintenance requests, read-only.`) });
+ continue;
+ }
+ items.push({ ref: { slug: output.request.slug, source_id: sourceId, raw_source: p.raw_source, ...(p.seat ? { seat: p.seat } : {}),
+ ...(p.first_write_at ? { first_write_at: new Date(p.first_write_at) } : {}) }, output, path: p.raw_source, transcript, hash: p.transcript_hash });
+ }
+ }
+ // #6757: a statement timeout on this request's own read defers it and every output after it.
+ let readsFrom = 0;
+ const readPrior = async (index: number, requestId: string): Promise<WriteRequest | null | undefined> => {
+ const started = Date.now();
+ try { return await getWriteRequest(engine, authority.writer.principal, requestId); } catch (error) {
+ if (!isPostprocessReadTimeout(error, opts.signal)) throw error;
+ deferred = { read: 'postprocess_request', elapsed_ms: Date.now() - started, pending: items.slice(index).flatMap(pendingOf) };
+ readsFrom = index;
+ return undefined;
+ }
+ };
let grounded: GroundedSource | undefined;
- for (const ref of [...refs].sort((a, b) => (a.raw_source ?? '').localeCompare(b.raw_source ?? ''))) {
+ for (const [index, { ref, output, path, transcript, hash }] of items.entries()) {
throwIfAborted(opts.signal, '[dream] synthesis postprocessing');
if (ref.source_id !== authority.writer.sourceId) {
throw opError('source_changed', 'The synthesis output source changed.',
`Synthesis output ${ref.slug} belongs to source ${ref.source_id}, not ${authority.writer.sourceId} that this dream cycle writes, so it was not postprocessed. Check source ${authority.writer.sourceId}'s writer status, then run gbrain dream --phase synthesize --source ${authority.writer.sourceId} again.`,
{ fix: writerStatusFix(authority.writer.sourceId, `Shows source ${authority.writer.sourceId}'s maintenance writer and requests in flight, read-only.`) });
}
- const output = outputs.find(o => o.request.slug === ref.slug);
- const path = output && jobRawSource.get(Number(output.job_id));
- const transcript = path ? byPath.get(path) : undefined;
const revision = output?.request.outcome?.revision;
if (!output || !transcript || typeof revision !== 'string') {
throw opError('recovery_required', 'The synthesis output has no retained transcript and committed revision.',
`Synthesis output ${ref.slug} in source ${ref.source_id} has no retained transcript or committed put_page revision${output ? ` (child request ${output.request.request_id})` : ''}, so it cannot be verified. Inspect the writer status before running synthesis again; do not republish the page by hand.`,
{ fix: writerStatusFix(ref.source_id, `Shows source ${ref.source_id}'s committed and pending maintenance requests, read-only.`) });
}
+ const outputRequestId = String(output.request.request_id);
const finalizedRef = { ...ref, raw_source: path };
// #6360: a postprocess adopted onto a maintenance-only drift binds its base revision too.
const postprocessId = (base: string) => {
const key = digest({ kind: 'synthesis-postprocess-v1', source: authority.writer.sourceIncarnation,
- slug: ref.slug, job: output.job_key, output: output.request.id, revision, transcript: transcript.contentHash, ...(base === revision ? {} : { base }) });
+ slug: ref.slug, job: output.job_key, output: output.request.id, revision, transcript: hash, ...(base === revision ? {} : { base }) });
return `${key.slice(0, 8)}-${key.slice(8, 12)}-4${key.slice(13, 16)}-a${key.slice(17, 20)}-${key.slice(20, 32)}`;
};
let base = revision;
let requestId = postprocessId(base);
- let prior = await getWriteRequest(engine, authority.writer.principal, requestId);
+ let prior = await readPrior(index, requestId);
+ if (prior === undefined) break;
let snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>> = null;
if (!prior) {
snapshot = await engine.readPageSnapshot(ref.slug, { sourceId: ref.source_id });
@@ -143,11 +262,13 @@ export async function postprocessManagedSynthesis(
if (ours) {
base = ours.intent!.expected_revision as string;
requestId = ours.request_id;
- prior = await getWriteRequest(engine, authority.writer.principal, requestId);
+ prior = await readPrior(index, requestId);
+ if (prior === undefined) break;
} else if (snapshot && later.filter(r => r.state === 'committed').every(localMaintenance) && sameBody(output.request.intent?.content, snapshot.page, ref.slug)) {
base = snapshot.revision;
requestId = postprocessId(base);
} else {
+ settled.push(outputRequestId);
if (!reported.has(requestId)) conflicts.push({ slug: ref.slug, source_id: ref.source_id, request_id: requestId,
message: `Page ${ref.slug} in source ${ref.source_id} changed after the synthesis child committed revision ${revision}, so postprocessing left it alone and did not verify or stamp it. Review the page; this output is not retried.`,
fix: readFix(`Shows page ${ref.slug} as it is now, read-only.`, { argv: ['gbrain', 'get', '--source', ref.source_id, '--', ref.slug] }) });
@@ -157,7 +278,7 @@ export async function postprocessManagedSynthesis(
}
if (prior) {
await authorizeStoredRequest(engine, prior);
- if (prior.state === 'committed') { finalizedRefs.push(finalizedRef); continue; }
+ if (prior.state === 'committed') { settled.push(outputRequestId); finalizedRefs.push(finalizedRef); continue; }
if (['conflict', 'failed', 'cancelled'].includes(prior.state)) writeResponse(prior);
}
await authorizeStoredRequest(engine, output.request);
@@ -198,15 +319,20 @@ export async function postprocessManagedSynthesis(
await publishMaintenancePage(engine, authority, ref.slug, content, { requestId, expectedRevision: base, derivation });
} catch (error) {
deferPublishOrThrow(error, `${ref.slug} (request ${requestId})`);
+ // #6757: carried too, so the same request finishes even after the transcript grows or the child's rows are pruned.
+ carry.push(...pendingOf(items[index]!));
pending++;
continue;
}
+ settled.push(outputRequestId);
writtenRefs.push(finalizedRef);
finalizedRefs.push(finalizedRef);
await new Promise(resolve => setTimeout(resolve, 0));
}
+ if (deferred?.read === 'postprocess_request') pending += items.length - readsFrom;
if (conflicts.length) await rememberConflicts(engine, reported, conflicts);
- return { writtenRefs, finalizedRefs, stats, pending, conflicts };
+ const deferral = await recordPostprocessPass(engine, sourceId, sourceIncarnation, { settled, carry, deferred });
+ return { writtenRefs, finalizedRefs, stats, pending, conflicts, deferral };
}
async function readReportedConflicts(engine: BrainEngine): Promise<Map<string, string>> {
@@ -254,10 +380,41 @@ export const SYNTH_PUBLISH_DEFERRED = 'publish deferred (writer busy); finishes
/**
* #5854/#6051: an output publish deferred by deferPublishOrThrow is never
* counted as written: the phase warns, the cooldown stays unstamped, and the
- * next cycle resumes the same request id.
+ * next cycle resumes the same request id. #6757: so is an output whose
+ * postprocess read hit the statement timeout (`deferral`); the phase names the
+ * read, how long it ran and how many passes in a row deferred.
+ */
+export function withPublishPending(pending: number, result: PhaseResult, deferral?: PostprocessDeferral | null): PhaseResult {
+ if (!pending && !deferral) return result;
+ const read = deferral && `postprocessing deferred: ${DEFERRED_READ_LABEL[deferral.read]} hit the statement timeout after ${deferral.elapsed_ms} ms `
+ + `(${deferral.consecutive} pass(es) in a row); ${deferral.outputs} output(s) finish next cycle without another synthesis call`;
+ return { ...result, status: 'warn', summary: [result.summary, read, deferral && pending <= deferral.outputs ? null : SYNTH_PUBLISH_DEFERRED].filter(Boolean).join('; '),
+ details: { ...result.details, publish_pending: pending, ...(deferral && pending <= deferral.outputs ? {} : { publish_deferred: SYNTH_PUBLISH_DEFERRED }),
+ ...(deferral ? { postprocess_deferred: { ...deferral, doctor: 'gbrain doctor --only persistence_request_indexes --json' } } : {}) } };
+}
+
+/**
+ * #6757: a pass that returned before postprocessing (nothing new to synthesize) still finishes the outputs an earlier
+ * pass deferred; a pass that postprocessed already did. Runs after the phase body, on a real (not dry) run that did
+ * not fail or skip, only when this source has pending outputs no postprocess attempted since `startedAt`.
*/
-export function withPublishPending(pending: number, result: PhaseResult): PhaseResult {
- if (!pending) return result;
- return { ...result, status: 'warn', summary: `${result.summary}; ${SYNTH_PUBLISH_DEFERRED}`,
- details: { ...result.details, publish_pending: pending, publish_deferred: SYNTH_PUBLISH_DEFERRED } };
+export async function finishDeferredPostprocess(engine: BrainEngine,
+ opts: { dryRun: boolean; sourceId?: string; brainDir: string; deadlineAtMs?: number | null; signal?: AbortSignal; date?: string; cycleDate?: string; now?: () => Date },
+ startedAt: number, result: PhaseResult, loadConfig: (engine: BrainEngine) => Promise<{ quoteVerify: boolean; meetingTranscriptsDir: string | null }>): Promise<PhaseResult> {
+ if (opts.dryRun || result.status === 'fail' || result.status === 'skipped') return result;
+ const sourceId = opts.sourceId ?? 'default';
+ const entry = (await readPostprocessDeferrals(engine))[sourceId];
+ if (!entry?.pending?.length || Date.parse(entry.last_attempt_at) >= startedAt) return result;
+ const authority = await maintenancePreflight(engine, sourceId, opts.brainDir, { deadlineAtMs: opts.deadlineAtMs });
+ if (!authority) return result;
+ const config = await loadConfig(engine);
+ const processed = await postprocessManagedSynthesis(engine, authority, [], [], new Map(), [], {
+ cycleDate: await resolveCycleDate(engine, { explicitDate: opts.date ?? opts.cycleDate, now: opts.now }), quoteVerify: config.quoteVerify,
+ sinceByTranscript: new Map(), signal: opts.signal, grounding: config.quoteVerify ? await resolveGroundingDecide(engine) : undefined,
+ meetingTranscriptsDir: config.meetingTranscriptsDir });
+ const written = processed.writtenRefs.map(r => r.slug);
+ const resumed = written.length ? { ...result, summary: `${result.summary}; ${written.length} deferred output page(s) postprocessed`,
+ details: { ...result.details, pages_written: Number(result.details?.pages_written ?? 0) + written.length,
+ written_slugs: [...(Array.isArray(result.details?.written_slugs) ? result.details.written_slugs as string[] : []), ...written], postprocess_resumed: written } } : result;
+ return withPostprocessConflicts(processed.conflicts, withPublishPending(processed.pending, resumed, processed.deferral));
}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 438267d55f..71313be0a0 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -1,7 +1,7 @@
import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';
import { isConsumerDateGroundingOn } from '../facts/extract.ts';
import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
-import { deferPublishOrThrow, loadCommittedSynthesisOutputs, postprocessManagedSynthesis, withPostprocessConflicts, withPublishPending, type PostprocessConflict, type RetainedOutput } from './synthesize-postprocess.ts';
+import { deferPublishOrThrow, finishDeferredPostprocess, loadCommittedOutputsOrDefer, postprocessManagedSynthesis, withPostprocessConflicts, withPublishPending, type PostprocessConflict, type RetainedOutput } from './synthesize-postprocess.ts';
/**
* Synthesize phase (v0.23; #4152 two-stage cascade) — conversation-to-brain
* pipeline. Cheap-model triage gates frontier-model synthesis:
@@ -396,7 +396,8 @@ export async function runPhaseSynthesize(
// calls keep their own job:* tag — the innermost AsyncLocalStorage phase
// wins (minions/worker.ts wraps each job), and that is intentional: the
// authoritative child spend rolls up from minion_jobs token columns below.
- return withChatPhase('phase:synthesize', () => runPhaseSynthesizeInner(engine, opts));
+ const startedAt = Date.now(); // #6757: outputs an earlier pass deferred finish even when this pass returns before postprocessing
+ return withChatPhase('phase:synthesize', async () => finishDeferredPostprocess(engine, opts, startedAt, await runPhaseSynthesizeInner(engine, opts), loadSynthConfig));
}
async function runPhaseSynthesizeInner(
@@ -1138,8 +1139,8 @@ async function runPhaseSynthesizeInner(
// F6 rule-D visibility: track which children wrote pages, so a rescued/passed transcript
// whose child declined to write (task D) is distinguishable from a triage miss in telemetry.
const jobsWithPages = new Set<number>();
- const committedOutputs = maintenance ? await loadCommittedSynthesisOutputs(engine, maintenance, childIds) : undefined;
- let writtenRefs = withTranscriptSeats(await collectChildPutPageSlugs(engine, childIds, chunkInfo, cycleSourceId, jobRawSource, jobsWithPages, committedOutputs), worthProcessing);
+ const committedOutputs = maintenance ? await loadCommittedOutputsOrDefer(engine, maintenance, childIds, { jobRawSource, transcripts: worthProcessing, signal: opts.signal }) : undefined;
+ let writtenRefs = withTranscriptSeats(await collectChildPutPageSlugs(engine, childIds, chunkInfo, cycleSourceId, jobRawSource, jobsWithPages, committedOutputs?.outputs), worthProcessing);
let finalizedRefs = writtenRefs;
// Grounding gate: verify every page the children wrote (whole page when
@@ -1148,7 +1149,7 @@ async function runPhaseSynthesizeInner(
// chunks or the markdown body. Fail-open (abort still unwinds); kill
// switch: dream.synthesize.quote_verify=false.
let quoteVerifyStats: QuoteVerifyStats | null = null;
- let publishPending = 0, postprocessConflicts: PostprocessConflict[] = [];
+ let publishPending = 0, postprocessConflicts: PostprocessConflict[] = [], postprocessDeferral: Awaited<ReturnType<typeof postprocessManagedSynthesis>>['deferral'] = null;
const sinceByTranscript = await loadChildWriteEpochs(engine, childIds, jobRawSource, verifySince);
const grounding = config.quoteVerify ? await resolveGroundingDecide(engine) : undefined;
if (maintenance) {
@@ -1156,7 +1157,7 @@ async function runPhaseSynthesizeInner(
worthProcessing, { cycleDate: summaryDate, quoteVerify: config.quoteVerify, sinceByTranscript, signal: opts.signal, grounding, committedOutputs, meetingTranscriptsDir: config.meetingTranscriptsDir });
writtenRefs = processed.writtenRefs;
finalizedRefs = processed.finalizedRefs;
- [publishPending, postprocessConflicts] = [processed.pending, processed.conflicts];
+ [publishPending, postprocessConflicts, postprocessDeferral] = [processed.pending, processed.conflicts, processed.deferral];
quoteVerifyStats = config.quoteVerify ? processed.stats : null;
} else if (config.quoteVerify && writtenRefs.length > 0) {
const transcriptsForVerify = new Map<string, TranscriptForVerify>(worthProcessing.map(t => [t.filePath, { content: t.content }]));
@@ -1420,7 +1421,7 @@ async function runPhaseSynthesizeInner(
// child counters + triage pass usage). cost_usd null when unpriced.
spend: spendBlock,
},
- })));
+ }), postprocessDeferral));
} catch (e) {
return failed(makeError('InternalError', 'SYNTH_PHASE_FAIL', e instanceof Error ? (e.message || 'synthesize phase threw') : String(e),
e instanceof OperationError ? e.suggestion : undefined), e instanceof OperationError ? { error_code: e.code } : {});
diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.ts
index 0aacb5d148..84c5234ca4 100644
--- a/src/core/persistence/schema.ts
+++ b/src/core/persistence/schema.ts
@@ -26,8 +26,17 @@ export const PERSISTENCE_SYNC_RUN_INDEXES = [
export const PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_slug_intent
ON persistence_requests(source_id,slug,sequence) WHERE intent IS NOT NULL AND NOT compacted`;
export const PERSISTENCE_REQUEST_SLUG_INTENT_INDEX = { name: 'persistence_requests_slug_intent', table: 'persistence_requests', sql: PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL } as const;
+/**
+ * #6757: dream synthesis postprocessing joins each child's committed `put_page` to its journal row by request id
+ * within the cycle's source (`loadCommittedSynthesisOutputs`). The only index holding `request_id` leads with the
+ * principal, which that read does not know, so it ran as a sequential scan of the request table. Postgres builds it
+ * CONCURRENTLY in the persistence_request_id_index migration (`transaction: false`); PGLite inline.
+ */
+export const PERSISTENCE_REQUEST_ID_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_request_id
+ ON persistence_requests(source_id,request_id)`;
+export const PERSISTENCE_REQUEST_ID_INDEX = { name: 'persistence_requests_request_id', table: 'persistence_requests', sql: PERSISTENCE_REQUEST_ID_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] as const;
+export const PERSISTENCE_REQUEST_ONLINE_INDEXES = [...PERSISTENCE_SYNC_RUN_INDEXES, PERSISTENCE_REQUEST_SLUG_INTENT_INDEX, PERSISTENCE_REQUEST_ID_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`
@@ -97,7 +106,7 @@ export const PERSISTENCE_CONSUMERS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS persi
/** Indexes the Postgres blob omits because a migration builds them CONCURRENTLY. */
export 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_SLUG_INTENT_INDEX_SQL, PERSISTENCE_REQUEST_ID_INDEX_SQL,
]);
/** Durable infrastructure: never reconstruct or discard these rows during page reindexing. */
export const PERSISTENCE_SCHEMA_STATEMENTS = [
@@ -192,6 +201,7 @@ export const PERSISTENCE_SCHEMA_STATEMENTS = [
PERSISTENCE_SYNC_WATERMARK_INDEX_SQL,
PERSISTENCE_COMPACTABLE_INDEX_SQL,
PERSISTENCE_REQUEST_SLUG_INTENT_INDEX_SQL,
+ PERSISTENCE_REQUEST_ID_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/schema-migrations/v250-persistence-request-id-index.ts b/src/core/schema-migrations/v250-persistence-request-id-index.ts
new file mode 100644
index 0000000000..a83b8aa9ed
--- /dev/null
+++ b/src/core/schema-migrations/v250-persistence-request-id-index.ts
@@ -0,0 +1,25 @@
+import type { Migration } from './types.ts';
+import { PERSISTENCE_REQUEST_ID_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.
+//
+// #6757 (wave 18): dream synthesis postprocessing looks up each child's
+// committed put_page by request id within the cycle's source. No index served
+// that lookup (the unique key leads with the principal), so on a large request
+// table it ran as a sequential scan and hit the statement timeout after the
+// paid children had run. Postgres builds the index CONCURRENTLY outside a
+// transaction, after dropping an INVALID leftover (the blob omits it); PGLite
+// builds it inline. `gbrain repair request-indexes` runs the same helper on a
+// brain whose schema is already current. DDL only: no column, no backfill.
+export const v250: Migration = {
+ version: 250,
+ name: 'persistence_request_id_index',
+ idempotent: true,
+ transaction: false,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 250, PERSISTENCE_REQUEST_ID_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/test/managed-synthesis-postprocess.test.ts b/test/managed-synthesis-postprocess.test.ts
index 79ffa7f8a4..1ac5fc1649 100644
--- a/test/managed-synthesis-postprocess.test.ts
+++ b/test/managed-synthesis-postprocess.test.ts
@@ -1,6 +1,6 @@
import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -13,7 +13,11 @@ import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/
import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { clientRequestUuid } from '../src/core/persistence/preconditions.ts';
-import { journaledPageSlug } from '../src/core/cycle/synthesize-postprocess.ts';
+import { COMMITTED_OUTPUT_REQUESTS_SQL, journaledPageSlug } from '../src/core/cycle/synthesize-postprocess.ts';
+import { POSTPROCESS_PENDING_KEY } from '../src/core/cycle/synthesize-postprocess-deferral.ts';
+import { requestIndexesCheck } from '../src/commands/doctor/checks/persistence-requests.ts';
+import { PERSISTENCE_REQUEST_ID_INDEX } from '../src/core/persistence/schema.ts';
+import { buildIndexOnline } from '../src/core/schema-migrations/helpers.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, __setDecideTransportForTests } from '../src/core/ai/gateway.ts';
import { flushDecideWrites } from '../src/core/ai/decide/store.ts';
@@ -736,3 +740,140 @@ test('#6051: a storage error that is not admission contention still fails the ph
"SELECT 1 FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_maintenance_page'", [sourceId, slug])).toEqual([]);
});
}, 120_000);
+
+/** #6757: the server's statement-timeout error (or a user cancel, which shares SQLSTATE 57014) on the matching read. */
+const STATEMENT_TIMEOUT = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+function failCommittedOutputsRead(engine: BrainEngine, error: () => Error = STATEMENT_TIMEOUT) {
+ let hits = 0;
+ // Unbound: a transaction view inherits the method and must keep running on its own connection.
+ const executeRaw = engine.executeRaw as (this: unknown, ...args: unknown[]) => unknown;
+ const spy = spyOn(engine, 'executeRaw').mockImplementation((async function (this: unknown, sql: string, ...rest: unknown[]) {
+ if (sql === COMMITTED_OUTPUT_REQUESTS_SQL) { hits++; throw error(); }
+ return executeRaw.call(this, sql, ...rest);
+ }) as never);
+ return { hits: () => hits, restore: () => spy.mockRestore() };
+}
+const quietly = async <T>(fn: () => Promise<T>): Promise<T> => {
+ const write = spyOn(process.stderr, 'write').mockImplementation((() => true) as never);
+ try { return await fn(); } finally { write.mockRestore(); }
+};
+
+test('#6757: a committed-outputs read past the statement timeout defers the pass; after the transcript grows and the child rows are pruned, the next pass stamps the output without a synthesis call', async () => {
+ await fixture(async ({ engine, sourceId, root, opts, calls }) => {
+ const timeout = failCommittedOutputsRead(engine);
+ let deferred: Awaited<ReturnType<typeof runPhaseSynthesize>>;
+ try { deferred = await quietly(() => runPhaseSynthesize(engine, opts)); } finally { timeout.restore(); }
+ expect(timeout.hits()).toBe(1);
+ expect(deferred.status, JSON.stringify(deferred.error ?? deferred.summary)).toBe('warn');
+ expect(deferred.details.postprocess_deferred).toMatchObject({ read: 'committed_outputs', outputs: 1, consecutive: 1 });
+ expect(deferred.summary).toContain('postprocessing deferred: the committed-outputs read hit the statement timeout');
+ expect(deferred.details.publish_deferred).toBeUndefined();
+ expect(deferred.details.pages_written).toBe(0);
+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();
+ const slug = await outputSlug(engine, sourceId);
+ const unstamped = (await engine.readPageSnapshot(slug, { sourceId }))!.page;
+ expect(unstamped.frontmatter.dream_generated).toBeUndefined();
+ expect(unstamped.compiled_truth).toContain('"an entirely invented');
+
+ // The transcript grows (a new content hash) and `jobs prune` removes the child's rows.
+ appendFileSync(opts.inputFile, 'User: one more line added after the first synthesis.\n');
+ await engine.executeRaw("DELETE FROM subagent_tool_executions WHERE job_id IN (SELECT id FROM minion_jobs WHERE data->>'source_id'=$1)", [sourceId]);
+ await engine.executeRaw("DELETE FROM minion_jobs WHERE data->>'source_id'=$1", [sourceId]);
+ await disposePersistenceConsumer(engine);
+ // The grown transcript now triages below the threshold, so this pass submits no child at all.
+ let synthesisCalls = 0;
+ __setChatTransportForTests(async o => {
+ const triage = (o.system ?? '').startsWith('You triage a conversation transcript');
+ if (!triage) synthesisCalls++;
+ const text = triage ? JSON.stringify({ score: 0.1, content_type: 'routine', segments: [], entities: [], reasons: ['routine'] }) : JSON.stringify({ pages: [], skipped: true });
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: o.model!, providerId: 'anthropic' };
+ });
+ const spent = calls();
+ const next = await runPhaseSynthesize(engine, opts);
+ expect(next.status, JSON.stringify(next.error ?? next.summary)).toBe('ok');
+ expect(synthesisCalls).toBe(0);
+ expect(calls()).toBe(spent);
+ expect(next.details.children_submitted ?? 0).toBe(0);
+ expect(next.details.postprocess_resumed).toEqual([slug]);
+ expect(next.details.written_slugs).toEqual([slug]);
+ const stamped = (await engine.readPageSnapshot(slug, { sourceId }))!.page;
+ expect(stamped.frontmatter.dream_generated).toBe(true);
+ expect(stamped.compiled_truth).not.toContain('"an entirely invented');
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('dream_generated: true');
+ expect(JSON.parse(await engine.getConfig(POSTPROCESS_PENDING_KEY) ?? '{}')[sourceId]).toBeUndefined();
+ });
+}, 120_000);
+
+test('#6757: a postprocess request read past the statement timeout defers that output, and the next ordinary pass finishes it without a provider call', async () => {
+ await fixture(async ({ engine, sourceId, opts, calls }) => {
+ await interruptAfterChild(engine, sourceId, opts);
+ const slug = await outputSlug(engine, sourceId);
+ const spent = calls();
+ const getWriteRequest = journal.getWriteRequest;
+ let hits = 0;
+ const spy = spyOn(journal, 'getWriteRequest').mockImplementation(async (...args) => {
+ if (!hits++) throw STATEMENT_TIMEOUT();
+ return getWriteRequest(...args);
+ });
+ let deferred: Awaited<ReturnType<typeof runPhaseSynthesize>>;
+ try { deferred = await quietly(() => runPhaseSynthesize(engine, opts)); } finally { spy.mockRestore(); }
+ expect(deferred.status, JSON.stringify(deferred.error ?? deferred.summary)).toBe('warn');
+ expect(deferred.details.postprocess_deferred).toMatchObject({ read: 'postprocess_request', outputs: 1, consecutive: 1 });
+ expect(deferred.details.pages_written).toBe(0);
+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();
+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.page.frontmatter.dream_generated).toBeUndefined();
+ await disposePersistenceConsumer(engine);
+ const next = await runPhaseSynthesize(engine, opts);
+ expect(next.status, JSON.stringify(next.error ?? next.summary)).toBe('ok');
+ expect(calls()).toBe(spent);
+ expect(next.details.written_slugs).toEqual([slug]);
+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.page.frontmatter.dream_generated).toBe(true);
+ expect(JSON.parse(await engine.getConfig(POSTPROCESS_PENDING_KEY) ?? '{}')[sourceId]).toBeUndefined();
+ });
+}, 120_000);
+
+test('#6757: a user cancel on the committed-outputs read (SQLSTATE 57014, not a statement timeout) still fails the phase and defers nothing', async () => {
+ await fixture(async ({ engine, sourceId, opts }) => {
+ const cancel = failCommittedOutputsRead(engine, () => Object.assign(new Error('canceling statement due to user request'), { code: '57014' }));
+ let failed: Awaited<ReturnType<typeof runPhaseSynthesize>>;
+ try { failed = await runPhaseSynthesize(engine, opts); } finally { cancel.restore(); }
+ expect(cancel.hits()).toBe(1);
+ expect(failed.status).toBe('fail');
+ expect(failed.error?.code).toBe('SYNTH_PHASE_FAIL');
+ expect(JSON.parse(await engine.getConfig(POSTPROCESS_PENDING_KEY) ?? '{}')[sourceId]).toBeUndefined();
+ });
+}, 120_000);
+
+test('#6757: three deferred passes in a row put a line on doctor persistence_request_indexes; it names the rebuild only when the index is missing, and clears once a pass completes', async () => {
+ await fixture(async ({ engine, sourceId, opts, calls }) => {
+ const spent: number[] = [];
+ for (let pass = 1; pass <= 3; pass++) {
+ const timeout = failCommittedOutputsRead(engine);
+ let deferred: Awaited<ReturnType<typeof runPhaseSynthesize>>;
+ try { deferred = await quietly(() => runPhaseSynthesize(engine, opts)); } finally { timeout.restore(); }
+ expect(deferred.details.postprocess_deferred).toMatchObject({ read: 'committed_outputs', consecutive: pass });
+ await disposePersistenceConsumer(engine);
+ spent.push(calls());
+ if (pass === 2) expect((await requestIndexesCheck(engine)).status).toBe('ok');
+ }
+ expect(new Set(spent).size).toBe(1);
+ const valid = await requestIndexesCheck(engine);
+ expect(valid.status).toBe('warn');
+ expect(valid.message).toContain(`3 passes in a row on source ${sourceId}`);
+ expect(valid.message).toContain('the committed-outputs read');
+ expect(valid.message).toContain('1 output(s) pending');
+ expect(valid.message).not.toContain('gbrain repair request-indexes');
+ expect(valid.details).toMatchObject({ count: 0, postprocess_deferred: [expect.objectContaining({ source_id: sourceId, consecutive_passes: 3, read: 'committed_outputs', pending_outputs: 1 })] });
+ await engine.executeRaw(`DROP INDEX ${PERSISTENCE_REQUEST_ID_INDEX.name}`);
+ try {
+ const missing = await requestIndexesCheck(engine);
+ expect(missing.message).toContain(`${PERSISTENCE_REQUEST_ID_INDEX.name} is missing`);
+ expect(missing.message).toContain('gbrain repair request-indexes');
+ expect(missing.message).toContain(`3 passes in a row on source ${sourceId}`);
+ } finally { await buildIndexOnline(engine, 0, PERSISTENCE_REQUEST_ID_INDEX); }
+ const next = await runPhaseSynthesize(engine, opts);
+ expect(next.status, JSON.stringify(next.error ?? next.summary)).toBe('ok');
+ expect(calls()).toBe(spent[0]);
+ expect(await requestIndexesCheck(engine)).toMatchObject({ status: 'ok', message: 'Request-table indexes are valid.' });
+ });
+}, 180_000);
diff --git a/test/migration-persistence-request-id-index.test.ts b/test/migration-persistence-request-id-index.test.ts
new file mode 100644
index 0000000000..7e148dc6c3
--- /dev/null
+++ b/test/migration-persistence-request-id-index.test.ts
@@ -0,0 +1,148 @@
+/**
+ * #6757 (wave 18): dream synthesis postprocessing joins each child's committed
+ * put_page to its journal row by request id within the cycle's source
+ * (`COMMITTED_OUTPUT_REQUESTS_SQL`). No index served that read (the unique key
+ * leads with the principal) and the old text cast of the uuid column defeated
+ * any index, so on a large request table it was a sequential scan that hit the
+ * statement timeout after the paid children ran. The migration that builds
+ * `persistence_requests_request_id` has the v179 online-index shape; the
+ * Postgres blob omits the index, PGLite's carries it; `gbrain repair
+ * request-indexes` rebuilds a dropped or INVALID one on a current schema.
+ *
+ * The migration is found by its name, never by its number: the number is
+ * provisional until the merge slot.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+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_ID_INDEX, PERSISTENCE_REQUEST_ONLINE_INDEXES, POSTGRES_CONCURRENT_PERSISTENCE_INDEXES } from '../src/core/persistence/schema.ts';
+import { COMMITTED_OUTPUT_REQUESTS_SQL } from '../src/core/cycle/synthesize-postprocess.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';
+import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';
+import { runMigrations } from '../src/core/migrate.ts';
+import { runRepair, resolveRepairScope } from '../src/core/repair/core.ts';
+import { requestIndexesRepair } from '../src/core/repair/request-indexes.ts';
+import { requestIndexesCheck } from '../src/commands/doctor/checks/persistence-requests.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const INDEX = PERSISTENCE_REQUEST_ID_INDEX;
+const migration = MIGRATIONS.find(m => m.name === 'persistence_request_id_index');
+
+describe('#6757 the request-id index migration module', () => {
+ test('is registered once in the v179 online-index shape', () => {
+ expect(MIGRATIONS.filter(m => m.name === 'persistence_request_id_index')).toHaveLength(1);
+ expect(migration).toMatchObject({ idempotent: true, transaction: false, sql: '' });
+ expect(migration!.version).toBeGreaterThan(249);
+ expect(migration!.version).toBeLessThanOrEqual(LATEST_SCHEMA_VERSION);
+ expect(typeof migration!.handler).toBe('function');
+ });
+ test('is DDL only and leads with the columns the committed-outputs read constrains', () => {
+ expect(INDEX.sql).toMatch(/^CREATE INDEX IF NOT EXISTS persistence_requests_request_id\s+ON persistence_requests\(source_id,request_id\)$/);
+ expect(INDEX.sql).not.toMatch(/ALTER TABLE|ADD COLUMN|UPDATE /i);
+ expect(COMMITTED_OUTPUT_REQUESTS_SQL).toContain('p.request_id=ANY($1::uuid[])');
+ expect(COMMITTED_OUTPUT_REQUESTS_SQL).not.toContain('::text');
+ });
+ test('the Postgres blob omits the index (the migration builds it CONCURRENTLY); the PGLite blob carries it; repair and doctor cover it', () => {
+ expect(POSTGRES_CONCURRENT_PERSISTENCE_INDEXES.has(INDEX.sql)).toBe(true);
+ expect(SCHEMA_SQL).not.toContain(INDEX.name);
+ expect(PGLITE_SCHEMA_SQL).toContain(INDEX.name);
+ expect(PERSISTENCE_REQUEST_ONLINE_INDEXES.map(index => index.name)).toContain(INDEX.name);
+ });
+});
+
+for (const backend of testBackends()) describe(`[${backend}] #6757 the request-id index on a brain`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const ctx = () => ({ engine, config: { engine: backend }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;
+ const state = async () => (await readRequestIndexStates(engine, [INDEX]))[0]!.state;
+ const incarnation = async () => (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'"))[0]!.incarnation;
+ const seed = (rows: number) => engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,intent,authority,intent_bytes,terminal_reservation,state,outcome)
+ SELECT 'local_cli','seed',gen_random_uuid(),'put_page','default',(SELECT incarnation FROM sources WHERE id='default'),'seed-'||g,'d',jsonb_build_object('kind','put_page','n',g),'{}'::jsonb,1,64,'committed',jsonb_build_object('revision',gen_random_uuid()::text)
+ FROM generate_series(1,$1::int) g`, [rows]);
+
+ 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; closePostgres = pg.close; }
+ }, 120_000);
+ afterAll(async () => { await engine.disconnect(); await closePostgres?.(); }, 60_000);
+
+ test('a fresh brain has the index valid; the migration handler is a no-op on it', async () => {
+ expect(await state()).toBe('valid');
+ await migration!.handler!(engine);
+ expect(await state()).toBe('valid');
+ });
+
+ test('the committed-outputs read returns the committed rows of the asked source only', async () => {
+ await seed(20);
+ const rows = await engine.executeRaw<{ request_id: string }>("SELECT request_id::text FROM persistence_requests WHERE principal_id='seed' ORDER BY sequence LIMIT 3");
+ const ids = rows.map(r => r.request_id);
+ const found = await engine.executeRaw<{ request: { request_id: string } }>(COMMITTED_OUTPUT_REQUESTS_SQL, [ids, 'default', await incarnation()]);
+ expect(found.map(r => r.request.request_id).sort()).toEqual([...ids].sort());
+ expect(await engine.executeRaw(COMMITTED_OUTPUT_REQUESTS_SQL, [ids, 'other-source', await incarnation()])).toEqual([]);
+ });
+
+ test('a populated brain upgrading from the previous schema version builds it in the migration', async () => {
+ await seed(200);
+ await engine.executeRaw(`DROP INDEX ${INDEX.name}`);
+ expect(await state()).toBe('missing');
+ await engine.setConfig('version', String(migration!.version - 1));
+ const result = await runMigrations(engine);
+ expect(result.current).toBe(LATEST_SCHEMA_VERSION);
+ expect(await state()).toBe('valid');
+ }, 120_000);
+
+ test('a dropped index is named by doctor and rebuilt by gbrain repair request-indexes; a second repair is a no-op', async () => {
+ await engine.executeRaw(`DROP INDEX ${INDEX.name}`);
+ const check = await requestIndexesCheck(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(`${INDEX.name} is missing`);
+ expect(check.message).toContain('gbrain repair request-indexes');
+ const scope = await resolveRepairScope(engine);
+ const preview = await runRepair(ctx(), requestIndexesRepair, scope, { apply: false });
+ expect(preview).toMatchObject({ affected: 1, apply_command: 'gbrain repair request-indexes --apply' });
+ expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ applied: 1, complete: true });
+ expect(await state()).toBe('valid');
+ expect(await runRepair(ctx(), requestIndexesRepair, scope, { apply: true })).toMatchObject({ affected: 0, applied: 0, complete: true });
+ expect(await requestIndexesCheck(engine)).toMatchObject({ status: 'ok', message: 'Request-table indexes are valid.' });
+ }, 60_000);
+
+ if (backend === 'postgres') {
+ const explain = async (sql: string, ids: string[]) => JSON.stringify(await engine.executeRaw(`EXPLAIN (FORMAT JSON) ${sql}`, [ids, 'default', await incarnation()]));
+ const masterSql = COMMITTED_OUTPUT_REQUESTS_SQL.replace('p.request_id=ANY($1::uuid[])', 'p.request_id::text=ANY($1::text[])');
+
+ test('on a 50k-row request table the committed-outputs read is served by the index; the text-cast read it replaces seq-scans', async () => {
+ await seed(50_000);
+ await engine.executeRaw('ANALYZE persistence_requests');
+ const ids = (await engine.executeRaw<{ request_id: string }>("SELECT request_id::text FROM persistence_requests WHERE principal_id='seed' ORDER BY sequence DESC LIMIT 4")).map(r => r.request_id);
+ expect(await explain(COMMITTED_OUTPUT_REQUESTS_SQL, ids)).toContain(INDEX.name);
+ expect(await explain(masterSql, ids)).toContain('Seq Scan');
+ await engine.executeRaw(`DROP INDEX ${INDEX.name}`);
+ expect(await explain(COMMITTED_OUTPUT_REQUESTS_SQL, ids)).not.toContain(INDEX.name);
+ await migration!.handler!(engine);
+ expect(await explain(COMMITTED_OUTPUT_REQUESTS_SQL, ids)).toContain(INDEX.name);
+ }, 180_000);
+
+ test('an INVALID index (an interrupted concurrent build) is dropped and rebuilt CONCURRENTLY by repair', async () => {
+ const pg = engine as PostgresEngine;
+ await pg.executeRaw(`UPDATE pg_index SET indisvalid=false WHERE indexrelid='${INDEX.name}'::regclass`);
+ expect(await state()).toBe('invalid');
+ expect((await requestIndexesCheck(engine)).message).toContain(`${INDEX.name} is INVALID`);
+ const statements: string[] = [];
+ const reserve = pg.withReservedConnection.bind(pg);
+ pg.withReservedConnection = (async (fn: Parameters<PostgresEngine['withReservedConnection']>[0]) => reserve(conn => fn({
+ executeRaw: async (sql: string, params?: unknown[]) => { statements.push(sql); return conn.executeRaw(sql, params); },
+ }))) as PostgresEngine['withReservedConnection'];
+ try {
+ expect(await runRepair(ctx(), requestIndexesRepair, await resolveRepairScope(engine), { apply: true })).toMatchObject({ applied: 1, complete: true });
+ } finally { pg.withReservedConnection = reserve; }
+ expect(statements.filter(sql => sql.startsWith('CREATE INDEX CONCURRENTLY IF NOT EXISTS')).map(sql => sql.split(/\s+/)[6])).toEqual([INDEX.name]);
+ expect(await state()).toBe('valid');
+ }, 120_000);
+ }
+});