Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync,persistence): admit-ahead fits the writer's outstanding limit; JIT off for two reads; receipt health on live publications

garrytand00f4d035407
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 8b6c26c439..e50b5357f8 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2202 ratchet +2: pre-publication withdrawal validation;
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
src/core/pglite-engine.ts 2998 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move)
-src/core/postgres-engine.ts 2946 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts)
+src/core/postgres-engine.ts 2948 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff)
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
src/core/types.ts 2239 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index b6fb2b48ef..146d7ee78d 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -778,6 +778,11 @@ export function receiptFor(row: WriteRequest, facts?: WriteHealthFacts, now = Da
}
const healthQueries = new WeakMap<BrainEngine, Promise<unknown>>();
+/**
+ * #6275: a head needs recovery only when it is recovering, or holds a recovery record without a live claim; a
+ * publication in progress keeps its ordinary before-image record, and the requests behind it are only waiting.
+ */
+const STUCK_RECOVERY = (r: string) => `(${r}.state='recovering' OR (${r}.recovery IS NOT NULL AND (${r}.state<>'running' OR ${r}.claim_expires_at<now())))`;
/**
* Receipt health facts per root. #5984: a queued request waits on any earlier unfinished request of its root;
* a claimed one (a lane, a group follower, or a foreground write claimed ahead of queued sync rows) waits only
@@ -802,14 +807,14 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]
LEFT JOIN LATERAL (
(SELECT r.sequence,(SELECT s.sequence FROM persistence_requests s WHERE s.worktree_id=w.id
AND (s.state IN ('running','recovering') OR s.recovery IS NOT NULL) ORDER BY s.sequence LIMIT 1) AS started_sequence,
- r.recovery IS NOT NULL AS recovering,
+ ${STUCK_RECOVERY('r')} AS recovering,
r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
WHERE r.worktree_id=w.id AND (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL)
ORDER BY r.sequence LIMIT 1)
UNION ALL
(SELECT r.sequence,(SELECT s.sequence FROM persistence_requests s WHERE s.worktree_id IS NULL AND s.source_incarnation=r.source_incarnation
AND s.state IN ('running','recovering') ORDER BY s.sequence LIMIT 1) AS started_sequence,
- r.recovery IS NOT NULL AS recovering,
+ ${STUCK_RECOVERY('r')} AS recovering,
r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
WHERE r.worktree_id IS NULL AND r.source_incarnation=CASE WHEN roots.root LIKE 'db:%' THEN substring(roots.root FROM 4)::uuid END
AND r.state IN ('queued','running','recovering') ORDER BY r.sequence LIMIT 1)
diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.ts
index 1a5f9c5abe..132e63cc80 100644
--- a/src/core/persistence/page-advisories.ts
+++ b/src/core/persistence/page-advisories.ts
@@ -23,8 +23,13 @@ const LINE_GRAMMAR_FINDINGS_MAX = 5;
async function similarPagesAdvisory(engine: BrainEngine, row: WriteRequest, page: ParsedPage): Promise<Record<string, unknown> | undefined> {
if (!['put_page', 'capture'].includes(row.operation) || row.page_id != null || row.slug.startsWith('wiki/agents/')
|| page.frontmatter?.dream_generated === true || (page.type as string) === 'extract_receipt' || isQuarantined(page.frontmatter)) return undefined;
- const found = await findSimilarPages(engine, { sourceId: row.source_id, slug: row.slug, title: page.title ?? '',
- excludePrivate: row.authority.excludePrivate ?? row.authority.remote });
+ // #6276: off by default, so the default path sends no statement; on Postgres the check runs with JIT off (its
+ // correlated visibility subplans cross the JIT cost threshold on larger brains and compile on every call).
+ if (!/^(true|1|yes|on)$/i.test((await engine.getConfig('put_page.similar_pages').catch(() => null))?.trim() ?? '')) return undefined;
+ const input = { sourceId: row.source_id, slug: row.slug, title: page.title ?? '', excludePrivate: row.authority.excludePrivate ?? row.authority.remote };
+ const found = engine.kind === 'postgres'
+ ? await engine.transaction(async tx => { await tx.executeRaw('SET LOCAL jit = off'); return findSimilarPages(tx, input); })
+ : await findSimilarPages(engine, input);
if (!found?.candidates.length) return undefined;
const first = found.candidates[0];
return {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 074a8ec365..45323cc6ad 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -28,7 +28,8 @@ import { writeFailureDiagnostic } from './verb-errors.ts';
import { extractManagedStaleLinks } from './links-maintenance.ts';
import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint } from './checkpoint-validation.ts';
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
-import type { WriteRequest } from './model.ts';
+import { principalKey, type WriteRequest } from './model.ts';
+import { readJournalLimits } from './limits.ts';
import { assertManagedSyncAllowed } from './worktree-refresh.ts';
import type { GBrainConfig } from '../config.ts';
import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';
@@ -681,6 +682,14 @@ function laneRunOf(cursor: Cursor, bulk: BulkPass): string | null {
* while foreground writes are recent (one was queued on the worktree in the last minute), or when the next
* entry is not groupable (renames, holds, waivers, the checkpoint and overtaken entries stay on the single path).
*/
+/** Requests the sync writer may still admit before its principal or the brain reaches the outstanding-request limit, less a reserve of 10. */
+async function admissionRoom(engine: BrainEngine, cursor: Cursor): Promise<number> {
+ const [limits, counters] = await Promise.all([readJournalLimits(engine),
+ engine.executeRaw<{ key: string; outstanding: string }>('SELECT key,outstanding_count::text AS outstanding FROM persistence_counters WHERE key=ANY($1::text[])',
+ [['brain', principalKey(cursor.authority.writer.principal)]])]);
+ const used = (key: string) => Number(counters.find(row => row.key === key)?.outstanding ?? 0);
+ return Math.min(limits.principalOutstanding - used(principalKey(cursor.authority.writer.principal)), limits.brainOutstanding - used('brain')) - 10;
+}
async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, freezeAt: FreezeAt,
assertActive: () => void): Promise<Cursor> {
if (!bulk.settings.enabled || !cursor.group?.length) return cursor;
@@ -707,14 +716,19 @@ async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk
if (foreground) bulk.foregroundAt = performance.now();
}
if (!bulk.foregroundFirst && bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_RECENT_MS) break;
+ // The admission must fit the writer's outstanding-request capacity (a refused admission would end admit-ahead):
+ // the groups admitted at once take only the room left after the cursor's next group and the agent's own writes.
+ const room = await admissionRoom(engine, current) - bulk.settings.size;
// The window's free slots are frozen and then admitted and saved in one transaction, up to a lane count of
// groups at a time, so lanes start on the first ones while the rest are frozen.
const formed: Pending[][] = [];
let next = start;
while (window.length + formed.length < depth && formed.length < Math.max(1, depth / 2) && next < current.entries.length) {
const base: Cursor = { ...current, index: next - 1 };
+ const size = Math.min(groupSize(base, bulk), room - formed.flat().length);
+ if (size < 1) break;
// A freeze refusal here is left for the single path to raise in order, after the publishing groups.
- const frozen = await freezeFollowers(engine, base, config, groupSize(base, bulk), freezeAt(base)).catch(() => []);
+ const frozen = await freezeFollowers(engine, base, config, size, freezeAt(base)).catch(() => []);
if (!frozen.length) break;
const after = (formed.at(-1) ?? window.at(-1) ?? current.group!).at(-1)!.requestId;
formed.push(frozen.map(member => ({ ...member, intent: { ...member.intent, group: frozen[0]!.requestId, after, ...(lane ? { lane } : {}) } })));
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 1c0d45af9c..765cfc9bb8 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -720,8 +720,10 @@ export class PostgresEngine implements BrainEngine {
}
async readPageSnapshot(slug: string, opts?: PageSnapshotOptions): Promise<PageSnapshot | null> {
+ // #6276: the remote alias-resolving read's visibility subplans cross the JIT thresholds on larger brains; run it with JIT off.
return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx =>
- readCanonicalPageSnapshot(async (query, params) => Array.from(await tx.unsafe(query, params as never, { prepare: true })) as never, slug, opts));
+ readCanonicalPageSnapshot(async (query, params) => Array.from(await tx.unsafe(query, params as never, { prepare: true })) as never, slug, opts),
+ opts?.resolveAlias && opts.excludePrivate ? { alwaysTransaction: true, jitOff: true } : undefined);
}
async lockPageKeys(keys: readonly PageKey[]): Promise<void> {
diff --git a/test/e2e/jit-off-reads-postgres.test.ts b/test/e2e/jit-off-reads-postgres.test.ts
new file mode 100644
index 0000000000..a9fe07d329
--- /dev/null
+++ b/test/e2e/jit-off-reads-postgres.test.ts
@@ -0,0 +1,68 @@
+/**
+ * #6276: two statements whose correlated visibility subplans cross Postgres' JIT cost thresholds on larger
+ * brains run with JIT off: the remote alias-resolving page read (`get_page`/`fetch`) and put_page's
+ * similar-pages advisory, which is not issued at all while `put_page.similar_pages` is off (the default).
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { managedBrain } from '../helpers/managed-brain.ts';
+
+const url = process.env.DATABASE_URL;
+const put = (ctx: Parameters<typeof submitPageMutation>[0], slug: string, title: string) => submitPageMutation(ctx, { operation: 'put_page',
+ params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${title}\n---\n\nBody of ${slug}.\n` } });
+
+/** Records `current_setting('jit')` on the statement's own connection just before each statement matching `match` runs. */
+function watchJit(match: RegExp): { seen: string[]; restore: () => void } {
+ const seen: string[] = [];
+ const proto = PostgresEngine.prototype as unknown as { executeRaw: BrainEngine['executeRaw']; transaction: BrainEngine['transaction'] };
+ const execute = proto.executeRaw, transaction = proto.transaction;
+ proto.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[], opts?: unknown) {
+ if (match.test(sql)) seen.push(((await execute.call(this, "SELECT current_setting('jit') AS jit", [])) as Array<{ jit: string }>)[0]!.jit);
+ return execute.call(this, sql, params, opts as never);
+ } as BrainEngine['executeRaw'];
+ // The page read runs through the transaction handle's `unsafe`, not executeRaw: watch it there.
+ proto.transaction = async function (this: BrainEngine, fn: (tx: BrainEngine) => Promise<unknown>) {
+ return transaction.call(this, async (tx: BrainEngine) => {
+ const sql = (tx as unknown as { sql: { unsafe: (q: string, p?: unknown, o?: unknown) => Promise<unknown> } & Record<string, unknown> }).sql;
+ const unsafe = sql.unsafe;
+ sql.unsafe = async (q: string, p?: unknown, o?: unknown) => {
+ if (match.test(q)) seen.push(((await unsafe.call(sql, "SELECT current_setting('jit') AS jit")) as Array<{ jit: string }>)[0]!.jit);
+ return unsafe.call(sql, q, p, o);
+ };
+ try { return await fn(tx); } finally { sql.unsafe = unsafe; }
+ });
+ } as BrainEngine['transaction'];
+ return { seen, restore: () => { proto.executeRaw = execute; proto.transaction = transaction; } };
+}
+
+describe.skipIf(!url)('JIT off for statements past the JIT cost thresholds (#6276)', () => {
+ test('the similar-pages advisory is not issued while off, and runs with JIT off when on', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const watch = watchJit(/WITH hits AS/);
+ try {
+ await put(ctx, 'companies/acme-example', 'Acme Example');
+ expect(watch.seen).toEqual([]);
+ await engine.setConfig('put_page.similar_pages', 'true');
+ const written = await put(ctx, 'companies/acme-example-2', 'Acme Example') as Record<string, any>;
+ expect((written.outcome ?? written).similar_pages.candidates).toContainEqual(expect.objectContaining({ slug: 'companies/acme-example' }));
+ expect(watch.seen.length).toBeGreaterThan(0);
+ expect(watch.seen.every(jit => jit === 'off')).toBe(true);
+ } finally { watch.restore(); }
+ }, { databaseUrl: url });
+ }, 180_000);
+
+ test('the remote alias-resolving page read runs with JIT off; other reads keep the server setting', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'notes/jit-example', 'JIT example');
+ const watch = watchJit(/WITH chosen AS/);
+ try {
+ expect((await engine.readPageSnapshot('notes/jit-example', { sourceId: 'default', resolveAlias: true, excludePrivate: true }))?.page.slug).toBe('notes/jit-example');
+ expect(watch.seen).toEqual(['off']);
+ expect(((await engine.executeRaw("SELECT current_setting('jit') AS jit", [])) as Array<{ jit: string }>)[0]!.jit).toBe('on');
+ } finally { watch.restore(); }
+ }, { databaseUrl: url });
+ }, 180_000);
+});
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index 030d64dcb5..bbc29f0550 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -222,6 +222,33 @@ test('lanes publish several groups at once and every page still commits, attribu
expect(cursor!.n).toBe(0);
}), 300_000);
+test('admit-ahead fits the writer\'s outstanding-request limit instead of stopping when a batch would exceed it', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ // Eight lanes keep sixteen groups of four admitted ahead; the principal may hold only 40 outstanding requests.
+ await engine.setConfig('persistence.limits.principal_outstanding', '40');
+ try {
+ const f = await fixture(engine, notes(160));
+ const admitted: number[] = []; // the source's queued and running requests at each cursor step
+ installFaultHook(async (point, detail) => {
+ if (point !== 'sync:mid_checkpoint' || detail.sourceId !== f.id) return;
+ const [row] = await engine!.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [f.id]);
+ admitted.push(row!.n);
+ });
+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 8 });
+ installFaultHook(undefined);
+ expect(result.drain).toMatchObject({ outcome: 'synced' });
+ expect((await imports(engine, f.id)).every(row => row.state === 'committed')).toBe(true);
+ // Groups kept being admitted ahead through the whole run: between the first admission and the last commits,
+ // the sync never ran out of admitted requests (an admission over the limit used to stop admit-ahead until the window drained).
+ const first = admitted.findIndex(n => n > 0), last = admitted.length - 1 - [...admitted].reverse().findIndex(n => n > 0);
+ expect(admitted.slice(first, last + 1).filter(n => n === 0)).toEqual([]);
+ expect(Math.max(...admitted)).toBeLessThanOrEqual(40);
+ } finally {
+ installFaultHook(undefined);
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.principal_outstanding'");
+ }
+}), 300_000);
+
test('a failed page under lanes stops the run: earlier pages commit, nothing after it publishes', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
if (!engine) return;
const f = await fixture(engine, notes(60, i => i === 30 ? '---\ntitle: Conflict\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' : null));
diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.ts
index 9898690141..86379b72c2 100644
--- a/test/persistence-diagnostics.test.ts
+++ b/test/persistence-diagnostics.test.ts
@@ -181,3 +181,39 @@ test('#5984 4.5: health never reports an overtaking claimed write as waiting, no
await engine.executeRaw("UPDATE persistence_requests SET state='cancelled',completed_at=now() WHERE id=$1::uuid", [laterSync.id]);
}
});
+
+test('#6275: a publication in progress with its before-image record is not recovery; a recovering head or a lost claim is', async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, sourceId: 'default',
+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await initializeLocalPersistence(ctx);
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.limits.%'");
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const admit = async (slug: string) => {
+ const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, slug);
+ return admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug, requestId: randomUUID(), callerIntent: {}, intent: { content: slug } });
+ };
+ const head = await admit('inbox/publishing-head'), behind = await admit('inbox/waiting-behind');
+ const worktree = randomUUID();
+ await engine.executeRaw("INSERT INTO persistence_worktrees(id,owner_host_id,state) VALUES($1,$2,'active')", [worktree, randomUUID()]);
+ await engine.executeRaw('UPDATE persistence_requests SET worktree_id=$2 WHERE id=ANY($1::uuid[])', [[head.id, behind.id], worktree]);
+ const health = async () => {
+ const rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [[head.id, behind.id]]);
+ const facts = await writeHealthFacts(engine, rows);
+ return Object.fromEntries(rows.map(row => [row.slug, { recovery: facts.get(row.id)!.recovery_required, earlier: facts.get(row.id)!.earlier_write }]));
+ };
+ // The head publishes under a live claim with its ordinary recovery record (the file's before-image).
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',
+ recovery='{"version":1}'::jsonb WHERE id=$1::uuid`, [head.id, randomUUID()]);
+ expect(await health()).toEqual({ 'inbox/publishing-head': { recovery: false, earlier: false }, 'inbox/waiting-behind': { recovery: false, earlier: true } });
+ // Its claim lapsed with the record still there: recovery is required.
+ await engine.executeRaw("UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE id=$1::uuid", [head.id]);
+ expect((await health())['inbox/waiting-behind']!.recovery).toBe(true);
+ // A recovering head is recovery too.
+ await engine.executeRaw("UPDATE persistence_requests SET state='recovering',claim_expires_at=now()+interval '30 seconds' WHERE id=$1::uuid", [head.id]);
+ expect((await health())['inbox/waiting-behind']!.recovery).toBe(true);
+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled',recovery=NULL,execution_token=NULL,completed_at=now() WHERE id=ANY($1::uuid[])", [[head.id, behind.id]]);
+ }
+});