Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): facts absorb waits the job deadline and logs pending writes as accepted (#6778)

garrytan87aa674fb1b4
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 0b984c4067..b4b30bf00a 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -7,6 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/embedding-identity.ts` — `embedding_identity_unqualified` (#6113, BRAIN, right after `embedding_env_override`): warns when the DB `config` row `embedding_model` has no provider prefix (managed fact extraction reads only that row and `config set` refuses it). The fix is the read-only `gbrain migrate embeddings --to <provider:model> --dry-run`, filled from `loadConfig()`'s provider-qualified `embedding_model`, or `<PROVIDER_MODEL>` plus an `inputs` entry when none is configured; `details.target_differs` flags a configured model with another name (applying it switches models). Applying re-embeds active facts (paid, user's call). The free relabel is parked (TODOS). Test: `test/doctor-embedding-identity-unqualified.test.ts`.
- `src/commands/doctor/checks/embedding-state.ts` — `embedding_state` (#6696 B3, BRAIN, `tier: 'ops'`, `opsPglite: 'not_applicable'`, after `embeddings`): `readEmbeddingState` in `ops` mode on the ops tier, `full` otherwise. Warns only on chunks of pages soft-deleted past the 72 h purge window (`deleted_page_chunks_overdue`, fix `pages purge-deleted`) and, on a keyed brain, live pages with body text but no chunks (`chunkless_pages_healable`, fix `embed --stale`); the pending backlog stays `embeddings`' warning and quarantined pages `quarantined_pages`'. keyword_only, deleted chunks inside the window and a keyless brain are `infoCheck`; ops without a covering index warns with `details.health: 'unknown'` (`embedding_state_unknown`). Test: `test/doctor-embedding-state.test.ts`.
+- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`.
- `src/commands/doctor/checks/persistence-consumers.ts` — #6317 (B3, T1c): doctor `two_consumers_on_host` (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a `put` or a row younger than 30 s, is listed in `details`) and `consumers_without_heartbeat` (a `claim_phase.owner` pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured `agentFix` (`gbrain sources writer status --json`) and `doctorVerify`; with `persistence.single_consumer` off the overlap is reported as the configured behavior. `serve_build_drift` (#6696 C6, its own `serveBuildDriftEntry`, one `listHostConsumers` read, ok on PGLite with no read) compares the live resident rows (not this process) with this binary's `VERSION` through `compareWriterVersions` (an unparsable version counts as older): an older row warns "serve is running an older build than this checkout; restart serve and workers" with `details { count, this_version, owner, older, newer }` and a `fix` (actor `user`, `doctorVerify`) whose argv is the installed serve service's restart (`systemctl --user restart gbrain-serve.service` when `systemdUnitPath` exists on Linux, `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when `launchdPlistPath` exists on macOS; `serveBuildDriftCheck`'s `ServiceHost` argument injects platform, home and uid) or else `kill <pid>`; a newer row is reported in an ok message; no rows names `consumers_without_heartbeat` for a pre-heartbeat serve. Registered in `DOCTOR_CHECK_REGISTRY` (the consumer entry, then `serveBuildDriftEntry`) before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`. Tests: `test/doctor-serve-build-drift.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index b2b287f614..36322ac61f 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Managed facts extraction: the entity-intent preparer and publisher, conversation facts batches and the unmanaged derived index. The extraction pipeline itself is in [Google and Loops (continued)](google-and-loops-continued.md) (`src/core/facts/backstop.ts`) and [Core Services (2/3)](core-services-2.md) (`src/core/facts/extract.ts`).
-- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres).
+- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). Each `ManagedFactsSession` carries one `MaintenanceWriteWait` (`maintenance-wait.ts`) built from the caller's `FactsBackstopCtx.deadlineAtMs` (the facts-absorb job passes its deadline; other callers get the 30 s base) and its abort signal: `collectManagedFacts` waits that long for each accepted request through `awaitWrite`, a cancelled job stops waiting at once, and a request still nonterminal after the wait leaves as `write_pending` with its receipt (#6778, `test/facts-absorb-publish-wait-6778.test.ts`). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres).
- `src/core/facts/same-page-shadow.ts` — #6333 the shadow counter both fact writers share. `samePageRewording(engine, sourceId, fact, embedding)` re-reads the entity's nearest live same-visibility candidate (`listSupersessionCandidates`, the pool and filters of `decideSingleFact`'s cosine pass) and answers whether `wouldDedupSamePage` (capture-dedup.ts: same lane, same `source_session`, same visibility, cosine ≥ 0.85, no diverging guard token) would have called the fact a rewording; `warnSamePageShadow` is the one stderr spelling (`[facts-backstop] #6333 shadow: …; both kept`). `facts-prepare.ts` calls it for every candidate `decideSingleFact` did not match and counts `would_dedup_same_page` on the entity outcome, the completion outcome, `ManagedFactsResult` and the `extract_facts` result; the count is frozen in the receipt, so a replay reports it and does not recount. Nothing is dropped; this is the managed mirror of the unmanaged backstop's counter (`backstop.ts`), which never fired on a managed brain. Tests: `test/backstop-same-page-shadow-managed-6333.test.ts` (PGLite and Postgres), `test/backstop-same-page-shadow-6333.test.ts` (unmanaged).
- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.
- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure or three failed batches block it; all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `replaceConversationFacts` deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the entry numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index a2b75a3522..b8870328a0 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -90,7 +90,7 @@ of making a duplicate.
| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried with `gbrain sync --source <source> --no-pull --retry-failed`; an ignored file syncs once it is committed and not ignored. `gbrain sync status --source <source> --json` shows the source's failures and holds. |
-| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
+| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. Two outcomes are not refusals and are logged under their own reasons, which doctor never counts toward its threshold: `write_pending_accepted`, a facts write that was accepted and whose receipt is still queued, running or recovering when the job stopped waiting (the job waits up to 30 s, bounded by its deadline; the write commits later), and `write_deferred_unadmitted`, a canonical writer that was busy before anything was admitted (`writer_lock_unavailable`, no receipt; the job retries). Doctor warns about deferrals only when they persist (see the check's `gbrain sources writer status` fix). The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
| <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |
diff --git a/src/commands/doctor/checks/knowledge-health.ts b/src/commands/doctor/checks/knowledge-health.ts
index 744d24c8ba..1a2e79defd 100644
--- a/src/commands/doctor/checks/knowledge-health.ts
+++ b/src/commands/doctor/checks/knowledge-health.ts
@@ -251,13 +251,17 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
});
}
} else {
+ // #6778: an accepted write still committing and a retry after writer contention before admission are not
+ // failures, so they never count toward the threshold; contention that persists warns on its own.
+ const { WRITE_PENDING_ACCEPTED, WRITE_DEFERRED_UNADMITTED } = await import('../../../core/facts/absorb-log.ts');
+ const notFailures = [WRITE_PENDING_ACCEPTED, WRITE_DEFERRED_UNADMITTED];
// Group per source so the breakdown is operator-friendly.
const bySource = new Map<string, Array<{ reason: string; n: number }>>();
let anyOverThreshold = false;
for (const r of rows) {
const n = typeof r.n === 'number' ? r.n : parseInt(r.n, 10);
if (!Number.isFinite(n)) continue;
- if (n >= threshold) anyOverThreshold = true;
+ if (n >= threshold && !notFailures.includes(r.reason)) anyOverThreshold = true;
if (!bySource.has(r.source_id)) bySource.set(r.source_id, []);
bySource.get(r.source_id)!.push({ reason: r.reason, n });
}
@@ -266,14 +270,32 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
`${sid}: ${reasons.map(x => `${x.n} ${x.reason}`).join(', ')}`,
)
.join(' | ');
+ const reasons = new Set(rows.map(r => r.reason));
+ const notes = [
+ reasons.has(WRITE_PENDING_ACCEPTED) ? `${WRITE_PENDING_ACCEPTED} rows are accepted facts writes still committing when the job stopped waiting; they are not failures.` : '',
+ reasons.has(WRITE_DEFERRED_UNADMITTED) ? `${WRITE_DEFERRED_UNADMITTED} rows found the canonical writer busy before anything was admitted; the job retries.` : '',
+ ].filter(Boolean).join(' ');
+ const contention = reasons.has(WRITE_DEFERRED_UNADMITTED) ? await persistentWriterContention(engine, WRITE_DEFERRED_UNADMITTED) : [];
+ const contended = contention.map(c =>
+ `source ${c.source_id}: ${c.n} facts write(s) deferred before admission with no later completed facts-absorb job, oldest ${new Date(c.oldest).toISOString()}`).join('; ');
checks.push({
name: 'facts_extraction_health',
- status: anyOverThreshold ? 'warn' : 'ok',
- message: anyOverThreshold
- ? `Facts:absorb failures over the threshold (${threshold}) in the last 24h: ${summary}. ` +
- `Run \`gbrain recall --since 24h --json\` to inspect what landed; ` +
- `tune the gate via \`gbrain config set facts.absorb_warn_threshold N\`.`
- : `Facts:absorb activity in last 24h (under threshold ${threshold}): ${summary}.`,
+ status: anyOverThreshold || contention.length ? 'warn' : 'ok',
+ message: [
+ anyOverThreshold
+ ? `Facts:absorb failures over the threshold (${threshold}) in the last 24h: ${summary}. ` +
+ `Run \`gbrain recall --since 24h --json\` to inspect what landed; ` +
+ `tune the gate via \`gbrain config set facts.absorb_warn_threshold N\`.`
+ : `Facts:absorb activity in last 24h (under threshold ${threshold}): ${summary}.`,
+ notes,
+ contended ? `Writer contention persists (${contended}). Check the canonical writer with \`gbrain sources writer status --source ${contention[0].source_id} --json\`.` : '',
+ ].filter(Boolean).join(' '),
+ ...(contention.length ? {
+ details: { persistent_writer_contention: contention.map(c => ({ source_id: c.source_id, deferred: c.n, oldest: new Date(c.oldest).toISOString() })) },
+ fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', contention[0].source_id, '--json'],
+ `Read-only: names source ${contention[0].source_id}'s canonical owner, the write holding it and every write waiting behind it, so the contention can be traced to its holder.`,
+ 'facts_extraction_health'),
+ } : {}),
});
}
const note = await conversationPipelineNote(engine);
@@ -306,6 +328,33 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
return checks;
}
+/**
+ * #6778: per source, the facts writes deferred before admission (writer_lock_unavailable) in the last 24 h that no
+ * facts-absorb job for the same page completed after, when they persist: more than 10, or the oldest over an hour old.
+ */
+async function persistentWriterContention(engine: ReturnType<typeof connectedEngine>, reason: string) {
+ try {
+ return await engine.executeRaw<{ source_id: string; n: number; oldest: string | Date }>(
+ `SELECT l.source_id, COUNT(*)::int AS n, MIN(l.created_at) AS oldest
+ FROM ingest_log l
+ WHERE l.source_type = 'facts:absorb'
+ AND l.created_at >= now() - INTERVAL '24 hours'
+ AND split_part(l.summary, ':', 1) = $1
+ AND NOT EXISTS (
+ SELECT 1 FROM minion_jobs j
+ WHERE j.name = 'facts-absorb' AND j.status = 'completed' AND j.finished_at >= l.created_at
+ AND j.data->>'slug' = l.source_ref AND COALESCE(j.data->>'sourceId', 'default') = l.source_id)
+ GROUP BY l.source_id
+ HAVING COUNT(*) > 10 OR MIN(l.created_at) < now() - INTERVAL '1 hour'
+ ORDER BY l.source_id`,
+ [reason],
+ );
+ } catch (err) {
+ if (isMissingSchemaObject(err, 'table', 'minion_jobs')) return [];
+ throw err;
+ }
+}
+
/**
* #6557: conversation-shaped pages skip the page-write backstop
* (`conversation_pipeline`); their facts come from the opt-in conversation
diff --git a/src/core/facts/absorb-log.ts b/src/core/facts/absorb-log.ts
index 3d6333ffd9..81d75741bf 100644
--- a/src/core/facts/absorb-log.ts
+++ b/src/core/facts/absorb-log.ts
@@ -22,6 +22,10 @@
* - 'gateway_billing' — provider credit, quota, or billing hard limit failed.
* - 'gateway_rate_limit' — provider rate limit; retry policy remains with the caller.
* - 'write_refused' — the write path refused the facts write (an OperationError); the detail starts with its code.
+ * - 'write_pending_accepted' — the facts write was accepted and its durable receipt is still queued, running or
+ * recovering after the publish wait; it commits later. Information, not a failure.
+ * - 'write_deferred_unadmitted' — the canonical writer was busy before admission (writer_lock_unavailable, no
+ * receipt): nothing was accepted and the job retries.
* - eligibility_skip is intentionally NOT logged (high cardinality, low signal).
*
* The writer is best-effort — a failure to log SHOULDN'T blow up the
@@ -67,6 +71,10 @@ export const DETERMINISTIC_WRITE_REFUSALS: readonly string[] = [
'writer_coordinator_required', 'permission_denied', 'invalid_params', 'writer_registration_required',
];
+/** #6778: reasons for facts writes that are not refusals; doctor facts_extraction_health keeps them out of the failure threshold. */
+export const WRITE_PENDING_ACCEPTED = 'write_pending_accepted';
+export const WRITE_DEFERRED_UNADMITTED = 'write_deferred_unadmitted';
+
/** The OperationError code of a write-path refusal, or null. Name check keeps this module import-light. */
export function writeRefusalCode(err: unknown): string | null {
const code = (err as { code?: unknown } | null)?.code;
@@ -167,7 +175,19 @@ export async function writeFactsAbsorbFailure(
const errorType = err instanceof Error && err.name ? err.name : 'Error';
const refusal = writeRefusalCode(err);
if (refusal) {
- await writeFactsAbsorbLog(engine, ref, 'write_refused', `${refusal} (${errorType}): ${(err as Error).message}`, sourceId);
+ const message = (err as Error).message;
+ if (refusal === 'write_pending') {
+ const pending = await pendingReceipt(engine, err);
+ if (pending) {
+ await writeFactsAbsorbLog(engine, ref, WRITE_PENDING_ACCEPTED,
+ `${refusal} (${errorType}) request_id ${pending.request_id} (${pending.state}): ${message}`, sourceId);
+ return;
+ }
+ } else if (refusal === 'writer_lock_unavailable' && (err as { writeRequest?: unknown }).writeRequest === undefined) {
+ await writeFactsAbsorbLog(engine, ref, WRITE_DEFERRED_UNADMITTED, `${refusal} (${errorType}): ${message}`, sourceId);
+ return;
+ }
+ await writeFactsAbsorbLog(engine, ref, 'write_refused', `${refusal} (${errorType}): ${message}`, sourceId);
return;
}
const globalClass = classifyGlobalLlmError(err);
@@ -183,6 +203,25 @@ export async function writeFactsAbsorbFailure(
await writeFactsAbsorbLog(engine, ref, reason, `${reason.startsWith('gateway_') ? 'provider request failed' : 'extraction failed'} (${errorType})`, sourceId);
}
+/**
+ * #6778: the durable receipt behind a `write_pending` error, read back from the journal, when it is still queued,
+ * running or recovering; null when the error names no receipt, the row is gone or terminal, or the read fails.
+ */
+async function pendingReceipt(engine: BrainEngine, err: unknown): Promise<{ request_id: string; state: string } | null> {
+ const { writeRequest, receiptFields } = err as { writeRequest?: { request_id?: unknown }; receiptFields?: { principal_kind?: unknown; principal_id?: unknown } };
+ const requestId = writeRequest?.request_id;
+ if (typeof requestId !== 'string' || typeof receiptFields?.principal_kind !== 'string' || typeof receiptFields.principal_id !== 'string') return null;
+ try {
+ const [row] = await engine.executeRaw<{ request_id: string; state: string }>(
+ `SELECT request_id::text AS request_id, state FROM persistence_requests
+ WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid AND state IN ('queued','running','recovering')`,
+ [receiptFields.principal_kind, receiptFields.principal_id, requestId]);
+ return row ?? null;
+ } catch {
+ return null;
+ }
+}
+
/**
* Classify an arbitrary error into one of the stable reason codes. Heuristic
* pattern match on error name + message; falls back to 'pipeline_error' when
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 359c5ec74e..8bd32cbd1e 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -117,6 +117,13 @@ export interface FactsBackstopCtx {
notabilityFilter?: FactNotabilityFilter;
/** Abort signal for shutdown propagation. */
abortSignal?: AbortSignal;
+ /**
+ * #6778: the durable job's deadline (MinionJobContext.deadlineAtMs). A managed
+ * facts publish waits for its accepted write up to the job-bounded
+ * MaintenanceWriteWait (persistence/maintenance-wait.ts); without a job the
+ * wait is the 30 s base.
+ */
+ deadlineAtMs?: number | null;
/** Mirrors OperationContext.remote for trust-aware logging paths. */
remote?: boolean;
/** Optional entity hints (extract_facts MCP op forwards these). */
diff --git a/src/core/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.ts
index f601476aec..60aeae42d7 100644
--- a/src/core/minions/handlers/facts-absorb.ts
+++ b/src/core/minions/handlers/facts-absorb.ts
@@ -98,6 +98,7 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {
visibility: job.data.visibility === 'world' ? 'world' : 'private',
...(typeof job.data.model === 'string' && job.data.model ? { model: job.data.model } : {}),
abortSignal: job.signal,
+ deadlineAtMs: job.deadlineAtMs,
},
).catch(refuse);
// An aborted run returns empty counts; completing it would consume the page's extraction.
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 7e7b20e394..812b3c0c24 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -25,8 +25,8 @@ import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
import { getWorktreeBinding, managedPersistenceEnabled, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';
import { authorizeFactsBackstop } from './effect-facts.ts';
import { admitWriteInTransaction, getWriteRequest, getWriteRequestById, receiptFor } from './journal.ts';
-import { assertPersistenceAccepting, persistenceConsumerConfig, waitForWrite, writeResponse } from './service.ts';
-import { maintenancePublishWaitMs } from './maintenance-wait.ts';
+import { assertPersistenceAccepting, awaitWrite, persistenceConsumerConfig, writeResponse } from './service.ts';
+import { MaintenanceWriteWait } from './maintenance-wait.ts';
import { digest, requireUuid, sha256 } from './digest.ts';
import { isTerminal, type WriteAuthority, type WriteRequest } from './model.ts';
import type { WriteReceipt } from './types.ts';
@@ -83,6 +83,13 @@ export interface ManagedFactsSession {
/** #6091: set when the facts come from an ambient capture lane. */
captureSource?: string;
derivation?: DerivationDeclaration;
+ /**
+ * #6778: the publish wait, one budget per session: 30 s bounded by the job's deadline
+ * (FactsBackstopCtx.deadlineAtMs), zero for later publishes once one is still pending.
+ */
+ wait: MaintenanceWriteWait;
+ /** The job's abort signal: a cancelled job stops waiting at once and its write stays pending. */
+ signal?: AbortSignal;
}
/** #6048: follow-up batches one input-keyed extraction may admit for file-check refusals. */
@@ -274,6 +281,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
completionRequestId: ctx.requestId ? requireUuid(ctx.requestId) : managedFactRequestId(batchKey, '__managed_facts_complete__'),
fileRefusalRetry: ctx.reAdmitFileRefusals === true && seed === inputDigest,
inputKeyed: seed === inputDigest,
+ wait: new MaintenanceWriteWait(ctx.deadlineAtMs ?? null), ...(ctx.abortSignal ? { signal: ctx.abortSignal } : {}),
...(captureGateLaneForSource(ctx.source) ? { captureSource: ctx.source } : {}),
...(derivation ? { derivation: declareDerivation(derivation.trust, derivation.inputs) } : {}) };
const prior = await getWriteRequest(engine, authority.principal, session.completionRequestId);
@@ -288,7 +296,7 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSes
`Request ${row.request_id} in source ${row.source_id} was accepted for different extraction input, so this extraction was not merged into it. Give this extraction a new request_id; read the receipt to see the original.`,
{ fix: receiptFix(row.request_id) });
await authorizeStoredRequest(engine, row);
- const finished = await waitForWrite(engine, row, session.config, maintenancePublishWaitMs());
+ const finished = session.wait.observe((await awaitWrite(engine, row, session.config, { waitMs: session.wait.ms(), signal: session.signal })).row);
writeResponse(finished);
result.write_requests.push(receiptFor(finished));
if ((row.intent?.kind ?? row.outcome?.kind) === 'managed_facts_entity') {
diff --git a/src/core/persistence/maintenance-wait.ts b/src/core/persistence/maintenance-wait.ts
index b7a94d65c9..4997572084 100644
--- a/src/core/persistence/maintenance-wait.ts
+++ b/src/core/persistence/maintenance-wait.ts
@@ -12,7 +12,7 @@ import { isTerminal, type WriteRequest } from './model.ts';
export const MAINTENANCE_WRITE_WAIT_MS = 30_000;
/**
* Maintenance publishes that run outside a MaintenanceWriteWait job budget
- * (managed facts, connector checkpoints, grandfathering, projection reindex)
+ * (connector checkpoints, grandfathering, projection reindex)
* wait this long for their accepted write before reporting `write_pending`.
*/
export const MAINTENANCE_PUBLISH_WAIT_MS = 5_000;
diff --git a/test/doctor-facts-absorb-contention-6778.test.ts b/test/doctor-facts-absorb-contention-6778.test.ts
new file mode 100644
index 0000000000..aabaf3bafe
--- /dev/null
+++ b/test/doctor-facts-absorb-contention-6778.test.ts
@@ -0,0 +1,150 @@
+/**
+ * #6778: doctor facts_extraction_health keeps accepted-but-pending facts writes
+ * (`write_pending_accepted`) and retries after writer contention before
+ * admission (`write_deferred_unadmitted`) out of the failure threshold, and
+ * warns when that contention persists: a deferral no facts-absorb job for the
+ * same page completed after, older than an hour, or more than 10 of them in 24 h.
+ *
+ * 1. Protects: deferrals that a completed job followed are information; a
+ * persistent one warns with a read-only `gbrain sources writer status` fix
+ * (`run` on the CLI, relayed to the user over MCP) whose verify clears once
+ * the job completes; accepted rows never warn.
+ * 2. Fails if the info reasons count toward the threshold again, or if
+ * persistent contention stays silent or loses its fix.
+ * 3. No existing test reads these reasons; test/facts-absorb-publish-wait-6778.test.ts
+ * covers how the rows are written.
+ * 4. No production seam: rows are seeded in ingest_log and minion_jobs, and the
+ * journey runs the real CLI against an on-disk PGLite brain.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { WRITE_DEFERRED_UNADMITTED, WRITE_PENDING_ACCEPTED } from '../src/core/facts/absorb-log.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { factsExtractionEntry } from '../src/commands/doctor/checks/knowledge-health.ts';
+import { finalizeCheckFixes } from '../src/commands/doctor/check-fix.ts';
+import { cliRenderContext, type RenderContext } from '../src/core/agent-output.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { gb, oneDocument } from './helpers/agent-journey.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); await engine.setConfig('version', String(LATEST_VERSION)); });
+
+const DEFERRED = 'writer_lock_unavailable (OperationError): The canonical fact writer is busy; extraction has not started.';
+
+async function absorbRow(db: BrainEngine, sourceId: string, slug: string, summary: string, hoursAgo = 0): Promise<void> {
+ await db.logIngest({ source_id: sourceId, source_type: 'facts:absorb', source_ref: slug, pages_updated: [], summary });
+ if (hoursAgo) await db.executeRaw(`UPDATE ingest_log SET created_at = now() - ($1::double precision * interval '1 hour')
+ WHERE id = (SELECT max(id) FROM ingest_log)`, [hoursAgo]);
+}
+
+async function completedJob(db: BrainEngine, sourceId: string, slug: string): Promise<void> {
+ const job = await new MinionQueue(db).add('facts-absorb', { slug, sourceId }, { queue: 'default' });
+ await db.executeRaw("UPDATE minion_jobs SET status='completed', finished_at=now() WHERE id=$1", [job.id]);
+}
+
+async function check(db: BrainEngine = engine): Promise<Check> {
+ const checks = await factsExtractionEntry.run({ engine: db, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[];
+ expect(checks).toHaveLength(1);
+ return checks[0]!;
+}
+
+const mcpRender = (transport: 'stdio' | 'http'): RenderContext => ({ transport, isCallable: op => op === 'run_doctor', preapproved: () => false });
+
+describe('facts_extraction_health and writer contention (#6778)', () => {
+ test('deferrals a completed job followed are information, not a warning', async () => {
+ for (let i = 0; i < 7; i++) {
+ await absorbRow(engine, 'default', `notes/page-${i}`, `${WRITE_DEFERRED_UNADMITTED}: ${DEFERRED}`);
+ await completedJob(engine, 'default', `notes/page-${i}`);
+ }
+ const result = await check();
+ expect(result.status).toBe('ok');
+ expect(result.message).toContain(`default: 7 ${WRITE_DEFERRED_UNADMITTED}`);
+ expect(result.message).toContain('busy before anything was admitted');
+ expect(result.fix).toBeUndefined();
+ });
+
+ test('accepted writes still committing never reach the failure threshold', async () => {
+ for (let i = 0; i < 12; i++) await absorbRow(engine, 'default', `notes/page-${i}`, `${WRITE_PENDING_ACCEPTED}: write_pending (OperationError) request_id 00000000-0000-4000-8000-00000000000${i % 10} (queued): The write is accepted and is still pending.`);
+ await absorbRow(engine, 'default', 'notes/refused', 'write_refused: permission_denied (OperationError): The grant does not cover this source.');
+ const result = await check();
+ expect(result.status).toBe('ok');
+ expect(result.message).toContain(`default: 12 ${WRITE_PENDING_ACCEPTED}, 1 write_refused`);
+ expect(result.message).toContain('they are not failures');
+ });
+
+ test('a deferral with no later completed job, over an hour old, warns with the read-only writer status fix', async () => {
+ await absorbRow(engine, 'notes-src', 'notes/stuck', `${WRITE_DEFERRED_UNADMITTED}: ${DEFERRED}`, 2);
+ await absorbRow(engine, 'notes-src', 'notes/fresh', `${WRITE_DEFERRED_UNADMITTED}: ${DEFERRED}`);
+ const result = await check();
+ expect(result.status).toBe('warn');
+ expect(result.message).toContain('Writer contention persists (source notes-src: 2 facts write(s) deferred before admission');
+ expect(result.details).toMatchObject({ persistent_writer_contention: [{ source_id: 'notes-src', deferred: 2 }] });
+ expect(result.fix).toMatchObject({ argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'notes-src', '--json'], consent: [], actor: 'agent',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'facts_extraction_health', '--json'] } });
+ const [cli] = finalizeCheckFixes([result], cliRenderContext());
+ expect(cli.fix).toMatchObject({ next: 'run', actor: 'agent' });
+ const [stdio] = finalizeCheckFixes([result], mcpRender('stdio'));
+ expect(stdio.fix).toMatchObject({ next: 'tell_user_to_run', actor: 'user' });
+ const [http] = finalizeCheckFixes([result], mcpRender('http'));
+ expect(http.fix).toMatchObject({ next: 'tell_user_to_run', actor: 'host_admin' });
+ });
+
+ test('more than 10 recent deferrals with no later completed job warn; ten do not', async () => {
+ for (let i = 0; i < 10; i++) await absorbRow(engine, 'default', `notes/page-${i}`, `${WRITE_DEFERRED_UNADMITTED}: ${DEFERRED}`);
+ expect((await check()).status).toBe('ok');
+ await absorbRow(engine, 'default', 'notes/page-10', `${WRITE_DEFERRED_UNADMITTED}: ${DEFERRED}`);
+ const result = await check();
+ expect(result.status).toBe('warn');
+ expect(result.details).toMatchObject({ persistent_writer_contention: [{ source_id: 'default', deferred: 11 }] });
+ });
+});
+
+describe('fix envelope: persistent contention to a verified clear through the real CLI', () => {
+ let home: string;
+ /** Opens the journey brain's on-disk PGLite between CLI runs (never while one runs). */
+ let onDisk: (run: (db: PGLiteEngine) => Promise<void>) => Promise<void>;
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-6778-journey-'));
+ onDisk = run => withEnv({ HOME: home, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const db = new PGLiteEngine();
+ await db.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') });
+ try { await run(db); } finally { await db.disconnect(); }
+ });
+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ await onDisk(db => absorbRow(db, 'default', 'notes/stuck', `${WRITE_DEFERRED_UNADMITTED}: ${DEFERRED}`, 2));
+ }, 180_000);
+ afterAll(() => { if (home) rmSync(home, { recursive: true, force: true }); });
+
+ test('render the envelope, run its argv, run its verify once the retried job completed', async () => {
+ const doc = oneDocument(await gb(home, ['doctor', '--only', 'facts_extraction_health', '--json']), 'doctor warn');
+ const warned = (doc.checks as Array<Record<string, any>>).find(c => c.name === 'facts_extraction_health')!;
+ expect(warned.status).toBe('warn');
+ expect(warned.fix.next).toBe('run');
+ expect(warned.fix.argv.slice(0, 7)).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json']);
+ const status = await gb(home, warned.fix.argv.slice(1));
+ expect(status.exitCode).toBe(0);
+ oneDocument(status, 'writer status');
+ // The status read changes nothing; the contention clears when the page's facts-absorb job completes.
+ await onDisk(db => completedJob(db, 'default', 'notes/stuck'));
+ expect(warned.fix.verify.argv.slice(0, 5)).toEqual(['gbrain', 'doctor', '--only', 'facts_extraction_health', '--json']);
+ const verified = oneDocument(await gb(home, warned.fix.verify.argv.slice(1)), 'doctor verify');
+ const cleared = (verified.checks as Array<Record<string, any>>).find(c => c.name === 'facts_extraction_health')!;
+ expect(cleared.status).toBe('ok');
+ expect(cleared.fix).toBeUndefined();
+ expect(cleared.details?.persistent_writer_contention).toBeUndefined();
+ }, 300_000);
+});
diff --git a/test/facts-absorb-publish-wait-6778.test.ts b/test/facts-absorb-publish-wait-6778.test.ts
new file mode 100644
index 0000000000..617ee1265e
--- /dev/null
+++ b/test/facts-absorb-publish-wait-6778.test.ts
@@ -0,0 +1,259 @@
+/**
+ * #6778: a managed facts-absorb job publishes its facts with the job-bounded
+ * maintenance wait (MaintenanceWriteWait: 30 s, capped by the job deadline,
+ * cut short by the job's abort signal) instead of the fixed 5 s publish wait,
+ * and `ingest_log` tells an accepted write that is still committing apart
+ * from a refusal and from writer contention before anything was admitted.
+ *
+ * 1. Protects: a facts write that commits 8 s after admission completes the
+ * job in one attempt with no `facts:absorb` failure row, and the worker
+ * keeps renewing the job's lock while the handler waits; a job deadline
+ * bounds the wait, and the still-pending write is logged
+ * `write_pending_accepted` (19 such rows do not warn the doctor); a busy
+ * canonical writer before admission is logged `write_deferred_unadmitted`
+ * and never as accepted; a `write_pending` error without a real nonterminal
+ * receipt keeps the `write_refused` label.
+ * 2. Fails if the publish goes back to the fixed 5 s wait (the delayed commit
+ * fails the attempt with `write_refused: write_pending`), if the job
+ * deadline or receipt check is dropped, or if contention is relabelled.
+ * 3. Existing coverage runs the handler only against writes that commit at
+ * once (test/helpers/managed-facts-contract.ts) or refusals
+ * (test/facts-absorb-write-refusal.test.ts).
+ * 4. No new production seam: the persistence fault hook stalls publication,
+ * the native worktree lock models contention. The 8 s commit is real time
+ * because awaitWrite has no injectable clock.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { claimPersistenceEffect } from '../src/core/persistence/effect-journal.ts';
+import { dispatchFactsBackstopEffect } from '../src/core/persistence/effect-facts.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { UnrecoverableError } from '../src/core/minions/errors.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { makeFactsAbsorbHandler } from '../src/core/minions/handlers/facts-absorb.ts';
+import { WRITE_DEFERRED_UNADMITTED, WRITE_PENDING_ACCEPTED, writeFactsAbsorbFailure } from '../src/core/facts/absorb-log.ts';
+import { factsExtractionEntry } from '../src/commands/doctor/checks/knowledge-health.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let chatCalls = 0;
+const usage = { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterEach(async () => { installFaultHook(undefined); await disposePersistenceConsumer(engine); });
+afterAll(async () => {
+ __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway();
+ await disposePersistenceConsumer(engine); await engine.disconnect();
+});
+
+interface Fixture { sourceId: string; job: { id: number; data: Record<string, unknown> } }
+
+/** A managed source whose committed page write queued one facts-absorb job; `run` gets the job before it runs. */
+async function fixture(name: string, run: (f: Fixture) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6778-'));
+ const sourceId = `wait-${name}`;
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ chatCalls++;
+ return { text: JSON.stringify({ facts: [
+ { fact: 'Alice-example prefers weekly status reports.', kind: 'preference', entity: 'people/alice-example', confidence: 0.9, notability: 'high' },
+ { fact: 'Acme-example measures monthly growth.', kind: 'fact', entity: 'companies/acme-example', confidence: 0.8, notability: 'medium' },
+ ] }), blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };
+ });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ const root = join(home, 'repo');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ for (const [slug, type, body] of [['people/alice-example', 'person', 'A registered person.'], ['companies/acme-example', 'company', 'A registered company.']]) {
+ await engine.putPage(slug, { type, title: slug, compiled_truth: body } as never, { sourceId });
+ mkdirSync(join(root, slug.split('/')[0]), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown((await engine.getPage(slug, { sourceId }))!, []));
+ }
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, config: { engine: engine.kind }, remote: false, sourceId, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const body = 'A substantive meeting about the registered entities and their operating preferences. '.repeat(4);
+ const content = ['---', 'type: meeting', 'title: Example meeting', '---', '', body].join('\n');
+ await operationsByName.put_page.handler(ctx, { slug: 'meetings/example', content, request_id: randomUUID() });
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE kind<>'facts-backstop'");
+ const [recorded] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_effects WHERE source_id=$1 AND kind='facts-backstop'", [sourceId]);
+ expect(recorded?.state).toBe('queued');
+ const effect = (await claimPersistenceEffect(engine, localHostId()))!;
+ expect(effect.kind).toBe('facts-backstop');
+ await dispatchFactsBackstopEffect(engine, effect, localHostId());
+ const [job] = await engine.executeRaw<{ id: number; data: Record<string, unknown> }>(
+ "SELECT id,data FROM minion_jobs WHERE name='facts-absorb' AND data->>'sourceId'=$1", [sourceId]);
+ expect(job).toBeDefined();
+ chatCalls = 0;
+ await run({ sourceId, job: { id: Number(job.id), data: job.data } });
+ });
+ } finally {
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+function jobContext(job: Fixture['job'], deadlineAtMs: number | null): MinionJobContext {
+ const signal = new AbortController().signal;
+ return { id: job.id, name: 'facts-absorb', data: job.data, attempts_made: 0, signal, deadlineAtMs, shutdownSignal: signal,
+ updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as MinionJobContext;
+}
+
+const absorbRows = (sourceId: string) => engine.executeRaw<{ summary: string }>(
+ "SELECT summary FROM ingest_log WHERE source_type='facts:absorb' AND source_id=$1 ORDER BY id", [sourceId]);
+const factRequests = (sourceId: string) => engine.executeRaw<{ request_id: string; state: string }>(
+ "SELECT request_id,state FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts' ORDER BY sequence", [sourceId]);
+
+/** Stall every extract_facts publication at `consumer:prepared` until `release()`; `firstHit` is when the first one arrived. */
+function stallFactsPublication() {
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const state = { firstHit: 0, release };
+ installFaultHook(async (point, detail) => {
+ if (point !== 'consumer:prepared' || detail.operation !== 'extract_facts') return;
+ state.firstHit ||= performance.now();
+ await gate;
+ });
+ return state;
+}
+
+async function waitUntil(pred: () => Promise<boolean>, ms: number): Promise<void> {
+ const end = performance.now() + ms;
+ while (performance.now() < end) {
+ if (await pred()) return;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+}
+
+test('a facts write that commits 8 s after admission completes the job in one attempt; the worker renews its lock across the wait', async () => {
+ await fixture('delayed', async ({ sourceId, job }) => {
+ const stall = stallFactsPublication();
+ // The shortest lease a job may carry (5 s, renewed every 2.5 s) and a 1 s stall sweep: a lock that stopped
+ // renewing during the 8 s wait would expire and be reclaimed as stalled.
+ await engine.executeRaw('UPDATE minion_jobs SET lock_duration_ms=5000 WHERE id=$1', [job.id]);
+ const worker = new MinionWorker(engine, { queue: 'default', pollInterval: 50, stalledInterval: 1_000 });
+ worker.register('facts-absorb', makeFactsAbsorbHandler(engine));
+ const running = worker.start();
+ const lockUntil = async () => (await engine.executeRaw<{ lock_until: Date | null }>('SELECT lock_until FROM minion_jobs WHERE id=$1', [job.id]))[0]?.lock_until;
+ let releaseTimer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await waitUntil(async () => stall.firstHit > 0, 30_000);
+ expect(stall.firstHit).toBeGreaterThan(0);
+ releaseTimer = setTimeout(stall.release, 8_000);
+ await new Promise(resolve => setTimeout(resolve, 500));
+ const early = await lockUntil();
+ await new Promise(resolve => setTimeout(resolve, 6_000));
+ const late = await lockUntil();
+ expect(early).toBeInstanceOf(Date);
+ expect(late).toBeInstanceOf(Date);
+ expect(new Date(late!).getTime() - new Date(early!).getTime()).toBeGreaterThan(3_000);
+ await waitUntil(async () => {
+ const [row] = await engine.executeRaw<{ status: string }>('SELECT status FROM minion_jobs WHERE id=$1', [job.id]);
+ return row?.status !== 'active' && row?.status !== 'waiting';
+ }, 40_000);
+ expect(performance.now() - stall.firstHit).toBeGreaterThanOrEqual(8_000);
+ } finally {
+ if (releaseTimer) clearTimeout(releaseTimer);
+ stall.release();
+ worker.stop();
+ await running;
+ }
+ const [row] = await engine.executeRaw<{ status: string; attempts_started: number; attempts_made: number; stalled_counter: number; error_text: string | null }>(
+ 'SELECT status,attempts_started,attempts_made,stalled_counter,error_text FROM minion_jobs WHERE id=$1', [job.id]);
+ expect(row).toMatchObject({ status: 'completed', attempts_started: 1, attempts_made: 0, stalled_counter: 0, error_text: null });
+ expect(await absorbRows(sourceId)).toEqual([]);
+ const requests = await factRequests(sourceId);
+ expect(requests.length).toBe(3);
+ expect(requests.every(r => r.state === 'committed')).toBe(true);
+ expect(chatCalls).toBe(1);
+ });
+}, 90_000);
+
+test('a job deadline bounds the publish wait; the pending write is logged as accepted with its receipt, and 19 such rows do not warn', async () => {
+ await fixture('deadline', async ({ sourceId, job }) => {
+ const stall = stallFactsPublication();
+ let error: (Error & { code?: string; writeRequest?: { request_id: string; state: string } }) | null = null;
+ try {
+ error = await makeFactsAbsorbHandler(engine)(jobContext(job, Date.now() + 2_500)).then(() => null, (e: Error) => e);
+ const waited = performance.now() - stall.firstHit;
+ expect(stall.firstHit).toBeGreaterThan(0);
+ expect(waited).toBeLessThan(4_000);
+ expect(error).not.toBeInstanceOf(UnrecoverableError);
+ expect(error?.code).toBe('write_pending');
+ const pending = error!.writeRequest!;
+ expect(['queued', 'running', 'recovering']).toContain(pending.state);
+ const rows = await absorbRows(sourceId);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].summary).toStartWith(`${WRITE_PENDING_ACCEPTED}: write_pending (OperationError)`);
+ expect(rows[0].summary).toContain(pending.request_id);
+ for (let i = 1; i < 19; i++) await writeFactsAbsorbFailure(engine, `meetings/example-${i}`, error, sourceId);
+ const summaries = (await absorbRows(sourceId)).map(r => r.summary);
+ expect(summaries).toHaveLength(19);
+ expect(summaries.every(s => s.startsWith(`${WRITE_PENDING_ACCEPTED}:`))).toBe(true);
+ const [check] = await factsExtractionEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[];
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain(`${sourceId}: 19 ${WRITE_PENDING_ACCEPTED}`);
+ } finally { stall.release(); }
+ await waitUntil(async () => (await factRequests(sourceId)).every(r => r.state === 'committed'), 30_000);
+ expect((await factRequests(sourceId)).map(r => r.state)).toEqual(['committed', 'committed', 'committed']);
+ await engine.executeRaw("DELETE FROM ingest_log WHERE source_type='facts:absorb' AND source_id=$1", [sourceId]);
+ });
+}, 90_000);
+
+test('a busy canonical writer before admission is logged as deferred, never as accepted, and the job retries', async () => {
+ await fixture('contended', async ({ sourceId, job }) => {
+ const lock = (await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 1_000))!;
+ let error: (Error & { code?: string; writeRequest?: unknown }) | null;
+ try {
+ error = await makeFactsAbsorbHandler(engine)(jobContext(job, null)).then(() => null, (e: Error) => e);
+ } finally { await lock.release(); }
+ expect(error).not.toBeInstanceOf(UnrecoverableError);
+ expect(error?.code).toBe('writer_lock_unavailable');
+ expect(error?.writeRequest).toBeUndefined();
+ expect(chatCalls).toBe(0);
+ expect(await factRequests(sourceId)).toEqual([]);
+ const summaries = (await absorbRows(sourceId)).map(r => r.summary);
+ expect(summaries).toHaveLength(1);
+ expect(summaries[0]).toStartWith(`${WRITE_DEFERRED_UNADMITTED}: writer_lock_unavailable (OperationError)`);
+ expect(summaries.some(s => s.startsWith(`${WRITE_PENDING_ACCEPTED}:`))).toBe(false);
+ await engine.executeRaw("DELETE FROM ingest_log WHERE source_type='facts:absorb' AND source_id=$1", [sourceId]);
+ });
+}, 90_000);
+
+test('write_pending without a real nonterminal receipt keeps the write_refused label', async () => {
+ const unknown = new OperationError('write_pending', 'The write is accepted and is still pending.');
+ Object.assign(unknown, { writeRequest: { request_id: randomUUID(), state: 'queued' },
+ receiptFields: { operation: 'extract_facts', source_id: 'default', slug: 'people/alice-example', principal_kind: 'local_cli', principal_id: randomUUID() } });
+ await writeFactsAbsorbFailure(engine, 'notes/unreceipted', unknown, 'receipt-check');
+ await writeFactsAbsorbFailure(engine, 'notes/no-receipt', new OperationError('write_pending', 'The write is accepted and is still pending.'), 'receipt-check');
+ expect((await absorbRows('receipt-check')).map(r => r.summary.split(':')[0])).toEqual(['write_refused', 'write_refused']);
+ await engine.executeRaw("DELETE FROM ingest_log WHERE source_type='facts:absorb' AND source_id='receipt-check'");
+});