Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

persistence: writes wait for imports and recovery behind the refresh barrier; derived retry hint (GST-1582)

garrytanf8c263fdb9d4
diff --git a/docs/designs/REFRESH_WRITE_BARRIER.md b/docs/designs/REFRESH_WRITE_BARRIER.md
index 43dad5ccde..50763c6d76 100644
--- a/docs/designs/REFRESH_WRITE_BARRIER.md
+++ b/docs/designs/REFRESH_WRITE_BARRIER.md
@@ -169,9 +169,10 @@ it are deferred to it, so a steady stream cannot keep a drain from reaching zero
released rows are claimed normally during the next refresh's `draining` and counted by its drain
(the claim moves them to `running`), within the existing `--wait-drain` budget.
-**Capacity.** Deferred rows reserve the existing outstanding and intent-byte counters. A per-worktree
-cap `persistence.refresh_barrier_max_deferred` (default 1000) bounds one refresh; past it, admission
-refuses `worktree_refreshing` as today (retryable, `fix.next: wait`).
+**Capacity.** Deferred rows reserve the existing outstanding and intent-byte counters, which bound
+them like queued rows. GST-1582 removed the per-refresh cap (`persistence.refresh_barrier_max_deferred`):
+a write past it queued as deferred instead of being refused, because a refusal there bounced exactly
+the writes the barrier exists to keep. The setting is no longer read.
**Age bound.** A deferred row whose refresh is still unreleased after
`persistence.refresh_barrier_max_wait_ms` (default 15 minutes; a tick runs a few minutes) is finished
@@ -180,6 +181,46 @@ that rechecks `released_at IS NULL` and releases its counters. Nothing is applie
resubmits with a new request id. If the owner host is down, nothing claims or expires rows; receipts
stay pending and readable, as for any queued row on that host.
+### Writes that wait for an import
+
+GST-1582: a write must never bounce because a sync is running. Three refusals bounced writes the
+barrier exists to keep, and with the flag on each now waits instead (with it off, each is unchanged):
+
+- **A refresh in `recovery_required`.** Admission defers behind it like behind any active refresh.
+ The row is released when the refresh is resumed or abandoned (both end it `completed` or
+ `aborted`), takes the refresh-change check, and is bound by the same age limit.
+- **The per-refresh cap.** Removed (see Capacity).
+- **`pending_import`.** A `put_page`, `capture` or `remember` whose page file holds a change
+ committed through Git that managed sync has not imported yet was refused at preparation
+ (`source_changed`, reason `pending_import`), after admission. The refusal now carries the last
+ imported commit the check compared against (read before the check, so a commit the check saw
+ imported is never awaited), and the consumer moves its own claim back to `deferred` with
+ `deferred_import_from` set to that commit (`''` when the source had never imported). The row is
+ released when `sources.last_commit` differs from it (and any refresh it also names is released),
+ then claimed and prepared from scratch, as if it had queued behind the import: a `remember` or
+ `capture` applies on top; a `put_page` with `expected_revision` meets the moved page and ends
+ `revision_conflict`; a blind (`force`) `put_page` lands. An import that lands without covering
+ the file only re-arms the hold at the new commit. The receipt reads `queued` with
+ `deferred: { pending_import: true }`, and the caller's wait returns pending at once.
+
+**What a blind write replaced.** A held `put_page` that replaces content an import brought in names
+it in three places, so the replacement is auditable and recoverable without digging: the receipt's
+`supersedes` (`slug`, `path`, the replaced `revision`, the imported `commit`: the newest commit
+after the held-at commit that touched the file), a `gbrain-supersedes: <path>: revision <id> from
+<commit>` trailer on its commit, and a `supersedes` list on that commit's ledger line (effect and
+door commits). The replaced revision stays in `page_versions` and the imported commit stays in
+Git, an ancestor of the write's commit.
+
+**Age bound and schema.** A row held for an import that has not landed past
+`persistence.refresh_barrier_max_wait_ms` ends `failed` with `pending_import_expired` in the owner's
+housekeeping turn, which rechecks under the request lock that the row is still unclaimed and its
+import still pending. Migration v291 adds the nullable `persistence_requests.deferred_import_from` and
+widens `gbrain_guard_deferred_request`: a running row may move to `deferred` only under the barrier's
+session declaration and only naming the import it waits for, and a deferred row moves to `running`
+only once every hold it names is released. Only the write owner's consumer, already a barrier
+consumer, holds a row for an import; a mixed-version window on one owner host is the
+consumer-capability gap #8688 tracks.
+
### Idempotency
The request id is the idempotency key. A replay of a deferred request id finds the prior row (same
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7ee421d66f..e4c4f10649 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3414,6 +3414,16 @@ More: [docs/guides/dream-patterns.md#cadence](../../docs/guides/dream-patterns.m
|---|---|---|---|---|---|---|
| The payload exceeds the configured size cap. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### pending_import_expired
+
+<a id="pending_import_expired"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A write that waited for managed sync to import a committed change to its page's file was not applied, because the import had not landed after the barrier's wait limit. | With persistence.refresh_barrier on, a put_page, capture or remember whose page file holds a change committed through Git that managed sync has not imported yet is accepted and waits for that import instead of being refused pending_import. An import that never lands (no sync owner running, a sync stopped on the file) would hold the write forever, so the owner finishes it failed after persistence.refresh_barrier_max_wait_ms (15 minutes by default). Nothing was applied. | Check the source with gbrain sync status --source <id> --json, then read the page again and submit the write with a new request_id. | provider | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#pending_import_expired](../../docs/guides/write-refusals.md#pending_import_expired)
+
### pending_verify
<a id="pending_verify"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 01af859b4e..aa0f3433dd 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -55,7 +55,7 @@ of making a duplicate.
| <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). |
| <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. |
| <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). |
-| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: wait for the source's running sync owner (`gbrain serve`, autopilot or a sync job) to import the commit, which the refusal's read-only fix `gbrain sync status --source <source> --json` shows, then read the page again and resubmit with a new request ID. Neither refusal tells the caller to start a sync, because a second sync beside a running owner competes with it; when status shows no owner running, ask the user to sync the source on its host. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. |
+| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: wait for the source's running sync owner (`gbrain serve`, autopilot or a sync job) to import the commit, which the refusal's read-only fix `gbrain sync status --source <source> --json` shows, then read the page again and resubmit with a new request ID. Neither refusal tells the caller to start a sync, because a second sync beside a running owner competes with it; when status shows no owner running, ask the user to sync the source on its host. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. With `persistence.refresh_barrier` on, a `put_page`, `capture` or `remember` waits for the import instead of being refused ([deferred writes](#pending_import_expired)). |
| <a id="sync_write_through_off"></a>`sync_write_through_off` | `unavailable` (`forget` / `forget_fact`, detail `sync_write_through_off`) | `sync.write_through` is off and a canonical file carries the claim. The struck row would not reach the file, so a brain rebuilt from Git would bring the claim back; nothing was withdrawn. A claim that only database-only pages carry is still withdrawn. A sandboxed subagent's forget of such a claim refuses the same way with `scope_denied`, detail `subagent_sandbox`. | `gbrain config set sync.write_through true`, then forget the fact again; from a subagent sandbox, forget it from the main session. |
| <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. An owner purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted --older-than 72h --yes`) of such a page once it is soft-deleted writes no tombstone, so it removes the page row, its chunks, links and facts database-only and leaves the file and the surviving page untouched (#7311); a census that changed under it defers to the next run, which re-reads the claimants and, when the tombstone now owns the file alone, purges it normally, file included. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge of a live page, soft-delete it instead; a soft-deleted one is removed by the retention purge (a tombstone an older release parked after its refusals is retried once by the first purge run after the upgrade). After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. |
| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The exception is relationship `unreadable_state` (#7636): the database role gbrain connects as cannot see the writer state the guard reads (the `persistence_brain` or `git_canonical_brain` row, or the source or page row the write names) because row-level security hides it, or a `persistence_brain` / `git_canonical_brain` row is missing, so the guard refuses instead of letting the write through as if the brain were unmanaged or the row absent. A derived-state maintainer trigger raises the same refusal (#7637, raiser `gbrain_forget_page_retrievals`, `gbrain_queue_page_projection` and the others [listed in ENGINES.md](../ENGINES.md#derived-state-maintainers)) when row-level security applies to the role on a table it keeps up to date and the role holds no policy for it there, instead of leaving that derived state stale. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. For relationship `unreadable_state` the build is not the cause: run gbrain as a role that can see that state (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows, though a change to which sources are Git-canonical passes only the first two; see [writer-protocol fences](../ENGINES.md#opt-in-rls-source-scope-binding-gbrain_rls_scope_binding), and for a maintainer's table the [policies a scoped writer needs](../ENGINES.md#derived-state-maintainers)), then retry with a **new** request ID; a missing row, which `gbrain init` never leaves, is reported like a defect. Never force-write, edit SQL or disable the guard. |
@@ -573,7 +573,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.
| <a id="refresh_sync_timeout"></a>`refresh_sync_timeout` | `refresh_sync_timeout` | Reported per source in a refresh's `sync_blocked`, not as a refusal: the source's managed sync committed nothing within its share of the refresh sync budget (each member gets an equal share of what is left; `sources.refresh_sync_budget_ms`, `GBRAIN_REFRESH_SYNC_BUDGET_MS`, default 5 min), for example because no consumer claimed its write. The message names that write and its state. The checkout is at the upstream commit, the refresh completed and released its lock, and the source is behind until its next sync. A sync stopped by the drain's own rules is reported with that stop's code instead (`drain_stalled` and the others). | Run the `resume` command (`gbrain sync --source <source> --no-pull`). If it stalls the same way, check the write it names with `gbrain sources writer status <source> --json`. |
| <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout), or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. When HEAD moved or work reached the checkout after the drain check, the run already retried once from a fresh precheck, and the message names why that retry was refused too. | Retry `gbrain sources refresh <source>`. |
| <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. Writer status reads HEAD and names the one step left when HEAD already sits at one of those commits: `--resume` at the upstream commit, `--abandon` at the start commit when no member source has synced past it. When one has (its `last_commit` is set and is neither the start commit nor an ancestor of it; a commit git cannot find counts too), `--abandon` refuses with this code and changes nothing, because the next sync would roll that member's pages back; `--resume` refuses too, and both name the one way out that keeps those pages: the fix (`next: ask_user`) previews with `git -C <checkout> status --short`, fast-forwards the checkout with `git merge --ff-only` to the commit the members synced (the upstream commit, or a later one a member already synced; it keeps uncommitted edits and refuses if one overlaps an incoming file), then runs `--resume`. When git refuses, the fix names a hard reset to that commit instead (destructive: it discards local commits and uncommitted edits not in that commit). `--resume` finishes a `recovery_required` refresh whose HEAD is the upstream commit or descends from it, unless a member synced a commit on this refresh's line (or one git cannot place) that HEAD does not contain; then it refuses with the same fast-forward fix. |
-| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not journaled. `detail` is `retry_after_ms=1000`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s, or its explicit `wait_ms` if lower, before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. With `persistence.refresh_barrier` on, a single page or memory write waits behind the refresh instead ([deferred writes](#deferred-writes)). | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
+| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not saved. `detail` is `retry_after_ms=<n>`, estimated from the refresh itself: the median duration of the worktree's last completed refreshes minus how long this one has run, never below 15 s while it syncs or 2 s in its other phases (so a refresh of several minutes is never answered with a 1 s retry). The message names the phase, how long the refresh has run and typically takes, and the CLI's human output ends with one line, `Nothing was saved; retry the same command in about <n> s (retry_after_ms=<n>).`, which survives `| tail -1`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s, or its explicit `wait_ms` if lower, before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. With `persistence.refresh_barrier` on, a single page or memory write waits behind the refresh instead ([deferred writes](#deferred-writes)). | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
A refresh is recorded in `persistence_worktree_refreshes` and survives a crash.
When the owner restarts it finishes the deterministic steps on its own: an
@@ -614,10 +614,23 @@ syncing it is accepted and waits for the refresh instead of being refused `workt
`persistence.refresh_barrier_max_wait_ms` (default 15 minutes) ends `failed` with
`refresh_barrier_expired`, nothing applied. Check the refresh with
`gbrain sources writer status --source <source> --json`, then submit again with a new request ID.
+- A refresh in `recovery_required` holds writes the same way: they wait until the refresh is resumed
+ or abandoned, under the same wait limit. There is no per-refresh cap: deferred writes count against
+ the journal's ordinary outstanding and byte limits, like queued ones.
+- <a id="pending_import_expired"></a>A `put_page`, `capture` or `remember` whose page file holds a
+ committed change managed sync has not imported yet ([`pending_import`](#pending_import)) also waits
+ instead of being refused: the receipt stays pending with `deferred: { pending_import: true }`, and
+ once the import lands the write is prepared again against the imported page. A `remember` or
+ `capture` applies on top; a `put_page` with `expected_revision` ends `revision_conflict` when the
+ import moved the page; a blind (`force`) `put_page` lands, and its receipt (`supersedes`), its
+ commit trailer (`gbrain-supersedes: <path>: revision <id> from <commit>`) and the commit ledger
+ name the imported revision and commit it replaced, both still in page history and Git. A write
+ whose import has not landed after the wait limit ends `failed` with `pending_import_expired`,
+ nothing applied: check `gbrain sync status --source <source> --json`, then read the page again and
+ submit with a new request ID.
- Still refused as before: batches (`put_pages`, `remember` with `items`), jobs, skill bundles,
- a refresh in `recovery_required`, more than `persistence.refresh_barrier_max_deferred` (default
- 1000) writes waiting on one refresh, and any brain where a live consumer on the owner host runs a
- release without the barrier. Repo-less brains and database-only sources never wait.
+ and any brain where a live consumer on the owner host runs a release without the barrier.
+ Repo-less brains and database-only sources never wait.
- `gbrain sources writer status --json` shows `deferred: { count, oldest_age_ms, refresh_id }` on
each active refresh.
- <a id="downgrade_blocked_deferred_writes"></a>Before installing an older release, turn the barrier
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 16277edadc..6d654d5291 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1658 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured)
+src/core/behavior-change-notice.ts 1659 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move)
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index 7ee75fe31b..a60b6a567e 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -874,6 +874,9 @@ export function renderCliError(e: unknown, opts: { json: boolean; command: strin
lines.push(`Fix: ${env.fix?.command ?? relay ?? env.suggestion}`);
if (env.why) lines.push(`Why: ${env.why}`);
if (env.docs) lines.push(`Docs: ${env.docs}`);
+ // GST-1582: a retryable refusal that names its delay ends with one line saying so, which survives `| tail -1`.
+ const retryAfter = env.retryable === true ? Number(/^retry_after_ms=(\d+)$/.exec(String(env.detail ?? ''))?.[1]) : NaN;
+ if (retryAfter > 0) lines.push(`Nothing was saved; retry the same command in about ${Math.max(1, Math.round(retryAfter / 1000))} s (retry_after_ms=${retryAfter}).`);
return { stderr: `${lines.join('\n')}\n`, exitCode };
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 09fd5042a2..0a1abf96a4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1456,6 +1456,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', id: 'doctor_foreign_writers_prb', text: 'New doctor check `foreign_writers`: in every source checkout on this host, managed worktrees included, a commit gbrain\'s commit ledger does not name fails the check with the newest such commit and a fix that asks who makes it; an unconfirmed commit (a crash between `git commit` and the ledger line) and page files left uncommitted for over 30 minutes warn. Commits before the ledger started are reported as uncovered, not foreign. A repo-less brain reports not_applicable.' },
{ since: 'TBD', id: 'sources_guard_prb', text: 'New `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]`: the commit guard on a managed source\'s worktree, from its owner host only, installed in a hooks directory private to that worktree. `--mode enforce` also refuses cherry-pick, revert, rebase and sequencer commits. `gbrain git guard` is unchanged.' },
{ since: 'TBD', id: 'refresh_barrier_prb', text: 'New setting `persistence.refresh_barrier` (off by default): with it on, a single page write (`put_page`, `remember` and the other single-page verbs) that reaches a checkout while `gbrain sources refresh` drains or merges it is journaled and answered `pending` at once (MCP `isError: false`, CLI exit 10) instead of refused `worktree_refreshing`. It commits after the refresh, or ends `revision_conflict` when the refresh changed its file, or `refresh_barrier_expired` after `persistence.refresh_barrier_max_wait_ms` (15 minutes). Syncs, jobs and batches keep the refusal. `gbrain upgrade --check-downgrade` exits 3 `downgrade_blocked_deferred_writes` while such writes wait.' },
+ { since: 'TBD', id: 'refresh_barrier_import_gst1582', text: 'With `persistence.refresh_barrier` on, no page write bounces because a sync is running: a `put_page`, `capture` or `remember` whose page file holds a committed change managed sync has not imported yet is answered `pending` (receipt `deferred: { pending_import: true }`) instead of refused `pending_import`, and is prepared again once the import lands (a `put_page` with `expected_revision` then ends `revision_conflict` if the import moved the page; a blind one lands and names the revision and commit it replaced in `supersedes`, a `gbrain-supersedes:` commit trailer and the commit ledger), or ends `pending_import_expired` after the wait limit. A write during a refresh in `recovery_required` waits too, and `persistence.refresh_barrier_max_deferred` is no longer read: no write past it is refused. With the barrier off those refusals are unchanged. Wherever `worktree_refreshing` still refuses, `retry_after_ms` is estimated from the refresh (its typical duration minus how long it has run, at least 15 s while syncing and 2 s otherwise) instead of a fixed 1000, the message says the write was not saved and when to retry, and the CLI\'s human output ends with one line saying the same.' },
{ since: 'TBD', id: 'commit_push_base_prb', text: '`gbrain git commit-push` takes `--base <path>=<blob>|absent` (repeatable, each path one the command commits): it refuses `commit_base_moved`, committing nothing, when the file at HEAD is no longer the blob the caller read. Without `--base` nothing changes.' },
{ since: 'TBD', id: 'file_drift_held_needs_prefer_8615', text: '`gbrain repair file-drift` with `--held`, `--side`, `--state`, `--cursor` or `--provenance` and no `--prefer` now refuses with the usage line (`invalid_params`, and `file_drift_state_required` for a deleted side without `--state`) instead of silently running the all-drifted survey, which counted a different set of pages (#8615).' },
{ since: 'TBD', id: 'refresh_source_changed_retry_8617', text: 'A `gbrain sources refresh` run refused `refresh_source_changed` because the checkout HEAD moved (a writer committing) or work reached the checkout after the drain check now retries once from a fresh precheck in the same run, so the tick is not lost (#8617). When the retry is refused too, the run returns the first `refresh_source_changed` refusal with the retry\'s cause appended; ownership or source-membership changes are not retried.' },
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index f5ebcd7a3e..d3a3406069 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -663,6 +663,7 @@ export const CODES = {
refresh_no_upstream: { class: 'caller', summary: "The worktree has no upstream to refresh from." },
refresh_not_managed: { class: 'host_only', summary: "The source is not managed, so it cannot be refreshed." },
refresh_not_owner: { class: 'host_only', summary: "This process does not own the worktree it would refresh." },
+ pending_import_expired: { class: 'caller', actor: 'provider', summary: "A write that waited for managed sync to import a committed change to its page's file was not applied, because the import had not landed after the barrier's wait limit.", why: "With persistence.refresh_barrier on, a put_page, capture or remember whose page file holds a change committed through Git that managed sync has not imported yet is accepted and waits for that import instead of being refused pending_import. An import that never lands (no sync owner running, a sync stopped on the file) would hold the write forever, so the owner finishes it failed after persistence.refresh_barrier_max_wait_ms (15 minutes by default). Nothing was applied.", docs: 'docs/guides/write-refusals.md#pending_import_expired', suggestion: 'Check the source with gbrain sync status --source <id> --json, then read the page again and submit the write with a new request_id.' },
refresh_barrier_expired: { class: 'caller', actor: 'provider', summary: "A write that waited behind a worktree refresh was not applied, because the refresh was still unfinished after the barrier's wait limit.", why: "With persistence.refresh_barrier on, a page write that reaches a refreshing checkout is accepted and waits for the refresh to end. A refresh that never ends (a stuck member sync, a host that stopped) would hold those writes forever, so the owner finishes each one failed after persistence.refresh_barrier_max_wait_ms (15 minutes by default). Nothing was applied.", docs: 'docs/guides/write-refusals.md#deferred-writes', suggestion: 'Check the refresh with gbrain sources writer status --source <id> --json, then submit the write again with a new request_id.' },
refresh_source_changed: { class: 'caller', summary: "The source changed during the refresh." },
refresh_sync_timeout: { class: 'retryable', summary: "A refresh's member sync committed nothing within the refresh sync budget." },
diff --git a/src/core/git/commit-ledger.ts b/src/core/git/commit-ledger.ts
index ae256087d3..03112617d6 100644
--- a/src/core/git/commit-ledger.ts
+++ b/src/core/git/commit-ledger.ts
@@ -32,12 +32,12 @@ export const LEDGER_ROTATE_BYTES = 4 * 1024 * 1024;
const LINE_MAX_BYTES = 1023;
const LOCK_WAIT_MS = 2_000;
-export interface LedgerCommit { sha: string; writer: LedgerWriter; ref?: string | null; request_id?: string | null; worktree_id?: string | null }
+export interface LedgerCommit { sha: string; writer: LedgerWriter; ref?: string | null; request_id?: string | null; worktree_id?: string | null; supersedes?: string[] }
export interface LedgerIntent { writer: LedgerWriter; head_before: string | null; message: string }
export type LedgerRecord =
| { v: 1; e: 'start'; t: string }
- | { v: 1; e: 'commit'; t: string; sha: string; writer: LedgerWriter; request_id: string | null; worktree: string | null; worktree_id: string | null; ref: string | null; pid: number; host: string | null }
+ | { v: 1; e: 'commit'; t: string; sha: string; writer: LedgerWriter; request_id: string | null; worktree: string | null; worktree_id: string | null; ref: string | null; pid: number; host: string | null; supersedes?: string[] }
| { v: 1; e: 'intent'; t: string; writer: LedgerWriter; head_before: string | null; msg_sha256: string; worktree: string | null; pid: number; host: string | null };
interface Location { common: string; gitDir: string; worktree: string | null }
@@ -109,7 +109,8 @@ function line(record: LedgerRecord): string {
function commitRecord(loc: Location, entry: LedgerCommit): LedgerRecord {
return { v: 1, e: 'commit', t: new Date().toISOString(), sha: entry.sha, writer: entry.writer, request_id: entry.request_id ?? null,
- worktree: loc.worktree, worktree_id: entry.worktree_id ?? null, ref: entry.ref === undefined ? headRef(loc.gitDir) : entry.ref, pid: process.pid, host: hostId() };
+ worktree: loc.worktree, worktree_id: entry.worktree_id ?? null, ref: entry.ref === undefined ? headRef(loc.gitDir) : entry.ref, pid: process.pid, host: hostId(),
+ ...(entry.supersedes?.length ? { supersedes: entry.supersedes } : {}) };
}
function intentRecord(loc: Location, intent: LedgerIntent): LedgerRecord {
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 83641967f0..e97496f067 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -30,6 +30,7 @@ import { mayReprepare } from './semantic.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects } from './effect-journal.ts';
import { deferredReplayRefusal } from './refresh-barrier.ts';
+import { holdForImport } from './import-deferral.ts';
import { timePublicationStep } from './publication-timing.ts';
import type { AppendedRange, GitCommitNote } from './effect-model.ts';
import { authorizePageVisibility } from './page-visibility.ts';
@@ -387,6 +388,9 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRe
const charged = await releaseChargedInterruption(engine, row, error, stage);
if (charged) return charged;
const failure = withAttempt(requestError(error), stage, engine);
+ // GST-1582: with the refresh barrier on, a write refused because its file awaits an import waits for that import instead.
+ const held = failure.code === 'source_changed' ? await holdForImport(engine, row, error) : null;
+ if (held) return held;
if (mayReprepare(row, failure) || transientDatabaseFailure(error)) {
await releaseUnpublishedClaim(engine, row, transientDatabaseFailure(error) ? 'database_contention' : 'revision_changed_repreparing');
return (await getWriteRequestById(engine, row.id))!;
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 29cb68a08f..a6e41c23cf 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -13,6 +13,7 @@ import type { Action } from '../agent-output.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { proveIndexLockAbandoned, reclaimIndexLock, type IndexLockReclaim } from './index-lock-reclaim.ts';
import { recordCommitAsync, recordIntentAsync } from '../git/commit-ledger.ts';
+import { supersededBy } from './import-deferral.ts';
/** An index lock younger than this is contention; an older one is reported as stale. */
const INDEX_LOCK_GRACE_MS = 10 * 60 * 1000;
@@ -377,7 +378,8 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
} finally { if (messageDir) rmSync(messageDir, { recursive: true, force: true }); }
if (result.code === 0) {
const head = await git(session, ['rev-parse', 'HEAD']);
- if (head.code === 0) await recordCommitAsync(root, { sha: head.stdout.trim(), writer: 'effect' });
+ const supersedes = supersededBy([...noted.values()].flatMap(note => note.trailers ?? []));
+ if (head.code === 0) await recordCommitAsync(root, { sha: head.stdout.trim(), writer: 'effect', ...(supersedes.length ? { supersedes } : {}) });
}
const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',
`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.ts
index a573c663cd..f074e9d642 100644
--- a/src/core/persistence/git-door.ts
+++ b/src/core/persistence/git-door.ts
@@ -53,6 +53,7 @@ import type { FileRecoveryRecord, SqlEngine } from './model.ts';
import { nativeFileTarget } from './native-file-target.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { recordCommitAsync } from '../git/commit-ledger.ts';
+import { supersededBy } from './import-deferral.ts';
import { committedBlob, headBlob, headCommit } from './pending-import.ts';
/** Whether `sourceId` is a strict (git-canonical) source; `lock` reads its row FOR SHARE inside a publication. */
@@ -328,7 +329,8 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[],
if (commit.code !== 0) throw gitFailure('Cannot commit the canonical Git target.',
`git commit-tree failed for ${changed.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
const created = commit.stdout.trim();
- await recordCommitAsync(root, { sha: created, writer: 'door', ref: branch });
+ const supersedes = supersededBy([...noted.values()].flatMap(note => note.trailers ?? []));
+ await recordCommitAsync(root, { sha: created, writer: 'door', ref: branch, ...(supersedes.length ? { supersedes } : {}) });
await doorSeams.beforeUpdateRef?.(root, attempt);
const moved = await git(session, ['update-ref', '-m', `commit: ${message[0]!.split('\n')[0]}`, branch, created, head]);
if (moved.code === 0) {
diff --git a/src/core/persistence/import-deferral.ts b/src/core/persistence/import-deferral.ts
new file mode 100644
index 0000000000..3aae427856
--- /dev/null
+++ b/src/core/persistence/import-deferral.ts
@@ -0,0 +1,65 @@
+/**
+ * GST-1582 (docs/designs/REFRESH_WRITE_BARRIER.md, "Writes that wait for an import"): with the refresh write barrier on, a
+ * put_page, capture or remember whose page file holds a committed change managed sync has not imported yet is not refused
+ * `pending_import`. The consumer moves its own claim back to `deferred`, naming the source's last imported commit, and the
+ * row waits (invisible to claims, journal.ts RELEASED_DEFERRED) until `sources.last_commit` moves past it. It is then
+ * prepared again from scratch, as if it had queued behind the import: a remember or capture applies on top, a put_page
+ * with expected_revision ends revision_conflict when the import moved the page, and a blind put_page lands. A blind
+ * put_page that replaces content the import brought in names what it replaced (`supersedes`) on its receipt, in a
+ * `gbrain-supersedes:` commit trailer and on the commit ledger line; the replaced revision stays in page history and
+ * the imported commit in git. A held write whose import never lands ends `pending_import_expired` (refresh-barrier.ts).
+ */
+import { relative, sep } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { PreparedMutation } from './coordinator.ts';
+import { publicationGroupKey, REFRESH_BARRIER_CLAIM_PREDICATE } from './journal.ts';
+import type { WriteRequest } from './model.ts';
+import { landedCommit } from './pending-import.ts';
+import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { writeSwitchOn } from './switches.ts';
+
+const IMPORT_HELD_OPERATIONS = ['put_page', 'capture', 'remember'];
+export const SUPERSEDES_TRAILER_KEY = 'gbrain-supersedes';
+
+/**
+ * A claimed write whose preparation was refused `pending_import` (`importFrom`: the last imported commit the check saw),
+ * moved back to `deferred` behind that import; null when it keeps the refusal (barrier off, another operation, a batch).
+ */
+export async function holdForImport(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<WriteRequest | null> {
+ const from = (error as { importFrom?: unknown } | null)?.importFrom;
+ if (typeof from !== 'string' || !IMPORT_HELD_OPERATIONS.includes(row.operation) || (row.target_kind ?? 'page') !== 'page' || !row.worktree_id
+ || publicationGroupKey(row) !== null || !await writeSwitchOn(engine, 'refresh_barrier').catch(() => false)) return null;
+ const [held] = await engine.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='deferred',deferred_import_from=$3,execution_token=NULL,
+ claim_expires_at=NULL,blocked_reason=NULL,claim_phase=NULL,updated_at=now()
+ WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND recovery IS NULL AND publication_started=false
+ AND ${PERSISTENCE_PROTOCOL_PREDICATE} AND ${REFRESH_BARRIER_CLAIM_PREDICATE} RETURNING *`, [row.id, row.execution_token, from]);
+ return held ?? null;
+}
+
+/** The trailer value a superseding write commits with: `<path>: revision <revision> from <commit>`. */
+const supersedesNote = (path: string, revision: string, commit: string) => `${path}: revision ${revision} from ${commit}`;
+
+/** The `gbrain-supersedes:` values among a commit's notes, for its ledger line. */
+export function supersededBy(trailers: Iterable<string>): string[] {
+ const key = `${SUPERSEDES_TRAILER_KEY}: `;
+ return [...trailers].filter(trailer => trailer.startsWith(key)).map(trailer => trailer.slice(key.length));
+}
+
+/**
+ * A put_page that was held for an import and replaces the page the import wrote: its outcome carries `supersedes`
+ * (slug, path, the replaced revision, the imported commit) and its commit the matching trailer.
+ */
+export async function withSupersedes(row: WriteRequest, prepared: PreparedMutation): Promise<PreparedMutation> {
+ if (row.deferred_import_from == null || row.operation !== 'put_page' || !prepared.file || prepared.noop || !prepared.observedRevision) return prepared;
+ const { root, path } = prepared.file;
+ const commit = await landedCommit(root, row.deferred_import_from || null, path);
+ if (!commit) return prepared;
+ const rel = relative(root, path).split(sep).join('/');
+ const supersedes = { slug: row.slug, path: rel, revision: prepared.observedRevision, commit };
+ const trailer = `${SUPERSEDES_TRAILER_KEY}: ${supersedesNote(rel, prepared.observedRevision, commit)}`;
+ const note = prepared.file.commit;
+ prepared.file.commit = note ? { ...note, trailers: [...(note.trailers ?? []), trailer] } : { subject: '', line: '', trailers: [trailer] };
+ const apply = prepared.apply.bind(prepared);
+ prepared.apply = async (tx, preimage) => ({ ...await apply(tx, preimage), supersedes });
+ return prepared;
+}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 1c3dfc0854..0294c68a6c 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -26,6 +26,7 @@ import { classifyHolderLiveness, syncLockId } from '../db-lock.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { catalogueError } from '../error-catalogue.ts';
import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear, RELEASED_DEFERRED } from './worktree-refresh-schema.ts';
+import { refreshProgress, refreshRetryHint, seconds } from './refresh-retry-hint.ts';
import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertGraduationAdmission } from './graduation-custody.ts';
import { schemaAdmissionRefusal } from './schema-admission.ts';
@@ -248,8 +249,8 @@ export async function getWriteRequestById(engine: SqlEngine, id: string, signal?
return row ?? null;
}
/** #5984: the columns a waiter needs while a request is unfinished; the full row is read once it is terminal. */
-export type WriteRequestProgress = Pick<WriteRequest, 'state' | 'error_code' | 'error_message' | 'completed_at' | 'updated_at' | 'blocked_reason' | 'outcome'>;
-export const WRITE_PROGRESS_SQL = 'SELECT state,error_code,error_message,completed_at,updated_at,blocked_reason,outcome FROM persistence_requests WHERE id=$1::uuid';
+export type WriteRequestProgress = Pick<WriteRequest, 'state' | 'error_code' | 'error_message' | 'completed_at' | 'updated_at' | 'blocked_reason' | 'outcome' | 'deferred_refresh_id' | 'deferred_import_from'>;
+export const WRITE_PROGRESS_SQL = 'SELECT state,error_code,error_message,completed_at,updated_at,blocked_reason,outcome,deferred_refresh_id,deferred_import_from FROM persistence_requests WHERE id=$1::uuid';
export async function getWriteRequestProgress(engine: SqlEngine, id: string, signal?: AbortSignal): Promise<WriteRequestProgress | null> {
const [row] = await engine.executeRaw<WriteRequestProgress>(WRITE_PROGRESS_SQL, [id], { signal });
return row ?? null;
@@ -294,7 +295,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
const origin = resolveAdmissionOrigin(input.origin);
// #6741 C: a declared background producer is refused before any receipt when the source's owner fails its verification.
if (input.worktreeId && declaredBackground(input.origin)) await assertBackgroundOwner(engine, input.sourceId, ownerStatusFix);
- const barrier = input.worktreeId && deferrable(input) ? await readRefreshBarrier(engine) : null;
+ const barrier = !!input.worktreeId && deferrable(input) && await readRefreshBarrier(engine);
return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {
await declarePersistenceProtocol(tx);
// The guards are sent together in lock order (worktree, source, writer, counters) and judged in
@@ -594,7 +595,7 @@ export async function chargePreparationAttempt(engine: SqlEngine, row: WriteRequ
* binding (#6007: both read in one statement after the lock; the fence is
* judged first, as before).
*/
-async function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission, replayable = false, barrier: RefreshBarrier | null = null): Promise<string | null> {
+async function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission, replayable = false, barrier = false): Promise<string | null> {
// Sent together: the server takes the share lock before it reads the fence and the binding. PR B: with the barrier on, the
// active refresh row is locked right after the worktree (protocol.ts lock order), so a deferral and the refresh's terminal
// transition serialize on it, and the syncing completion below upgrades no lock.
@@ -617,34 +618,30 @@ async function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission, r
return deferTo;
}
-/** PR B: the refresh barrier's bound when it is on (docs/designs/REFRESH_WRITE_BARRIER.md). */
-export interface RefreshBarrier { maxDeferred: number }
-export const REFRESH_BARRIER_MAX_DEFERRED_KEY = 'persistence.refresh_barrier_max_deferred';
-export const REFRESH_BARRIER_MAX_DEFERRED = 1000;
/** What a consumer advertises (consumer-heartbeat.ts CONSUMER_CAPABILITIES) and admission requires of every live one on the owner host. */
export const REFRESH_BARRIER_CAPABILITY = 'refresh_barrier_1';
/** A single page write whose caller opted in may wait behind a refresh; jobs (managed sync included), grouped batches and skill bundles keep the refusal. */
function deferrable(input: WriteAdmission): boolean {
return input.deferrable === true && (input.targetKind ?? 'page') === 'page' && input.operation !== 'submit_job' && publicationGroupKey({ operation: input.operation, intent: input.intent }) === null;
}
-async function readRefreshBarrier(engine: BrainEngine): Promise<RefreshBarrier | null> {
- if (!await writeSwitchOn(engine, 'refresh_barrier').catch(() => false)) return null;
- const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [REFRESH_BARRIER_MAX_DEFERRED_KEY]);
- const configured = Number(row?.value);
- return { maxDeferred: Number.isSafeInteger(configured) && configured > 0 ? configured : REFRESH_BARRIER_MAX_DEFERRED };
+/** PR B: whether the refresh barrier is on (docs/designs/REFRESH_WRITE_BARRIER.md). */
+async function readRefreshBarrier(engine: BrainEngine): Promise<boolean> {
+ return writeSwitchOn(engine, 'refresh_barrier').catch(() => false);
}
-/** Room under the per-refresh cap, and every live consumer of the worktree's owner host can drain a deferred write. */
-async function deferralRoom(tx: BrainEngine, worktreeId: string, refreshId: string, barrier: RefreshBarrier): Promise<boolean> {
- const [row] = await tx.executeRaw<{ deferred: number; incapable: boolean }>(`SELECT
- (SELECT count(*) FROM persistence_requests WHERE worktree_id=$2::uuid AND state='deferred' AND deferred_refresh_id=$1::uuid)::int AS deferred,
- EXISTS (SELECT 1 FROM persistence_consumers c JOIN persistence_worktrees w ON w.owner_host_id=c.host_id WHERE w.id=$2::uuid
- AND c.renewed_at>now()-($3::integer*interval '1 millisecond') AND NOT ($4=ANY(c.capabilities))) AS incapable`,
- [refreshId, worktreeId, CONSUMER_LIVE_MS, REFRESH_BARRIER_CAPABILITY]);
- return !!row && !row.incapable && Number(row.deferred) < barrier.maxDeferred;
+/**
+ * Every live consumer of the worktree's owner host can drain a deferred write. GST-1582: there is no per-refresh cap; the
+ * journal's outstanding and byte limits bound deferred writes like queued ones.
+ */
+async function deferralRoom(tx: BrainEngine, worktreeId: string): Promise<boolean> {
+ const [row] = await tx.executeRaw<{ incapable: boolean }>(`SELECT
+ EXISTS (SELECT 1 FROM persistence_consumers c JOIN persistence_worktrees w ON w.owner_host_id=c.host_id WHERE w.id=$1::uuid
+ AND c.renewed_at>now()-($2::integer*interval '1 millisecond') AND NOT ($3=ANY(c.capabilities))) AS incapable`,
+ [worktreeId, CONSUMER_LIVE_MS, REFRESH_BARRIER_CAPABILITY]);
+ return !!row && !row.incapable;
}
/** The refresh to defer this write behind, or null when it is admitted normally; otherwise refuses. */
async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmission, refresh: { id: string; state: string; source_ids: string[] }, replayable: boolean,
- barrier: RefreshBarrier | null): Promise<string | null> {
+ barrier: boolean): Promise<string | null> {
const managedSync = input.operation === 'submit_job' && String(input.intent.kind ?? '').startsWith('managed_sync_');
if (refresh.state === 'syncing' && managedSync) return null;
if (refresh.state === 'syncing') {
@@ -653,22 +650,27 @@ async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmissio
AND s.last_commit IS DISTINCT FROM f.target_head) RETURNING f.id`, [refresh.id]);
if (completed.length) return null;
}
+ // GST-1582: with the barrier on, a write waits behind a refresh awaiting recovery too, and lands once it is released.
+ if (refresh.state === 'recovery_required' && barrier && input.worktreeId && await deferralRoom(tx, input.worktreeId)) return refresh.id;
if (refresh.state === 'recovery_required') throw catalogueError('refresh_recovery_required',
`Refresh ${refresh.id} could not verify the checkout HEAD of source ${input.sourceId}; writes to its worktree stay fenced.`,
`gbrain sources writer status ${input.sourceId}, then gbrain sources refresh ${input.sourceId} --resume. Retry the same request_id afterwards.`);
- const error = catalogueError('worktree_refreshing',
- `Source ${input.sourceId}'s checkout is being fast-forwarded by refresh ${refresh.id} (${refresh.state}); this write was not journaled.`,
- `Retry the same request_id after retry_after_ms: 1000. Check progress with gbrain sources writer status ${input.sourceId}.`);
// A single write's replay of a request already accepted (its acknowledgement lost before the fence) reconciles to its
// receipt instead; a group admission never bypasses, since its other items may be new.
if (replayable && input.requestId && await getWriteRequest(tx, input.principal, input.requestId)) return null;
// PR B: with the barrier on, the write waits behind the refresh as a deferred request instead of being refused.
- if (barrier && input.worktreeId && await deferralRoom(tx, input.worktreeId, refresh.id, barrier)) return refresh.id;
- error.detail = 'retry_after_ms=1000';
+ if (barrier && input.worktreeId && await deferralRoom(tx, input.worktreeId)) return refresh.id;
+ // GST-1582: the retry hint comes from the refresh's own state (its phase, how long it has run, how long this worktree's
+ // refreshes typically take), never a fixed second that sends the caller back into the same refresh.
+ const hint = await refreshRetryHint(tx, refresh);
+ const error = catalogueError('worktree_refreshing',
+ `This write was not saved: refresh ${refresh.id} is fast-forwarding source ${input.sourceId}'s checkout (${refreshProgress(hint)}). Retry the same request_id in about ${seconds(hint.retryAfterMs)} s.`,
+ `Retry the same request_id after retry_after_ms: ${hint.retryAfterMs}. Check progress with gbrain sources writer status ${input.sourceId}.`);
+ error.detail = `retry_after_ms=${hint.retryAfterMs}`;
error.retryable = true;
// GST-1387: nothing was recorded, so the same call is retried after the delay (actor provider renders next: wait).
error.fix = { argv: ['gbrain', 'sources', 'writer', 'status', '--source', input.sourceId, '--json'], consent: [], actor: 'provider', requires_exclusive: false,
- why: `A refresh of source ${input.sourceId}'s checkout holds its writes until it finishes syncing; this write was not recorded. Repeat the same call with the same request_id after about 1 s (retry_after_ms=1000); this read-only command shows the refresh's progress.` };
+ why: `A refresh of source ${input.sourceId}'s checkout holds its writes until it finishes syncing; this write was not recorded. Repeat the same call with the same request_id after about ${seconds(hint.retryAfterMs)} s (retry_after_ms=${hint.retryAfterMs}); this read-only command shows the refresh's progress.` };
throw markNotAdmitted(error);
}
@@ -1278,7 +1280,8 @@ export function receiptFor(stored: WriteRequest, facts?: WriteHealthFacts, now =
...(row.outcome ?? {}),
...(row.outcome ? { outcome: row.outcome } : {}),
request_id: row.request_id, ...(row.client_request_id ? { client_request_id: row.client_request_id } : {}), state,
- ...(stored.state === 'deferred' && stored.deferred_refresh_id ? { deferred: { refresh_id: stored.deferred_refresh_id } } : {}),
+ ...(stored.state === 'deferred' ? { deferred: { ...(stored.deferred_refresh_id ? { refresh_id: stored.deferred_refresh_id } : {}),
+ ...(stored.deferred_import_from != null ? { pending_import: true } : {}) } } : {}),
...writeHealth(row, facts, now),
...(row.error_code ? { write_error: row.error_code } : {}),
...(row.error_detail ? { write_error_detail: publicFailureDetail(row.error_detail) } : {}),
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.ts
index 5db30f9a9c..9b5c73f7e3 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -126,6 +126,8 @@ export interface WriteRequest {
state: RequestState;
/** The refresh a deferred write was admitted behind; kept after it drains, so its claim runs the refresh-change check. */
deferred_refresh_id?: string | null;
+ /** GST-1582: the source's last imported commit ('' for none) when a claimed write was held for an import; kept after it lands. */
+ deferred_import_from?: string | null;
execution_token: string | null;
claim_expires_at: Date | string | null;
recovery: RecoveryRecord | null;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index e435cd9a12..64122a7171 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -458,7 +458,11 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's
// #6394: a page that never recorded its file reconciles against the file at its slug path only when adopted explicitly.
const adopt = !snapshot.page.source_path && !snapshot.page.source_uri ? ['--adopt-slug-path'] : [];
// #6693: a committed Git change sync has not imported yet (another agent's commit), on a page that records its file.
- if (!adopt.length && await waitingOnWhile(options.clock, 'git', () => committedPendingImport(engine, row.source_id, root, path, options.clock?.signal))) throw pendingImportRefusal(row, options.remote === true);
+ if (!adopt.length) {
+ // GST-1582: read before the check, so a write held for the import never waits on a commit the check already saw imported.
+ const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [row.source_id]);
+ if (await waitingOnWhile(options.clock, 'git', () => committedPendingImport(engine, row.source_id, root, path, options.clock?.signal))) throw pendingImportRefusal(row, options.remote === true, source?.last_commit ?? '');
+ }
// #8109: drift confined to ordinary frontmatter keys never blocks a write that leaves the frontmatter alone.
const spliced = !adopt.length && options.deleting !== true && typeof content === 'string' && before instanceof Buffer && !bodyUnread(snapshot.page) && before.length <= PUSH_SCAN_MAX_FILE_BYTES
? await frontmatterDriftWrite(engine, row.slug, before.toString('utf8'), snapshot, content, options.activePack) : null;
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index e78d619eb9..183c6d94d0 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -128,7 +128,7 @@ function quiet(read: Promise<string>, signal?: AbortSignal): Promise<string | nu
* The refusal: nothing was overwritten; a remember waits for its replay, any other write is resubmitted after the next sync.
* GBRA-133: neither fix starts a sync; both read the status, so no caller puts a second sync owner beside a running one.
*/
-export function pendingImportRefusal(row: { source_id: string; slug: string; operation?: string }, remote: boolean): OperationError {
+export function pendingImportRefusal(row: { source_id: string; slug: string; operation?: string }, remote: boolean, importFrom?: string): OperationError {
const status = ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'];
const remember = row.operation === 'remember';
const fix: Action = remember
@@ -138,9 +138,11 @@ export function pendingImportRefusal(row: { source_id: string; slug: string; ope
: { argv: status, consent: [], actor: remote ? 'host_admin' : 'agent', requires_exclusive: false,
verify: { argv: status }, docs: 'docs/guides/write-refusals.md#pending_import',
why: `${PENDING_IMPORT_OWNER.replace('<source>', row.source_id)} Once it has, read the page again and resubmit the intended write with a new request_id.` };
- return opError('source_changed', PENDING_IMPORT_MESSAGE,
+ const refusal = opError('source_changed', PENDING_IMPORT_MESSAGE,
`Nothing was overwritten. The canonical file of ${row.slug} in source ${row.source_id} holds a change committed through Git that managed sync has not imported yet, `
+ (remember ? 'so this remember was refused and kept: the first sync that imports the file makes one replay attempt, with its original date and authority.'
: 'so this write was refused rather than replacing those bytes: after the next sync imports them, read the page again and resubmit with a new request_id.'),
{ detail: 'file_database_drift', reason: PENDING_IMPORT, fix });
+ // GST-1582: the last imported commit the check compared against, so a refresh-barrier consumer can hold the write for the import.
+ return importFrom === undefined ? refusal : Object.assign(refusal, { importFrom });
}
diff --git a/src/core/persistence/refresh-barrier.ts b/src/core/persistence/refresh-barrier.ts
index 6a442ee95a..2d92300d14 100644
--- a/src/core/persistence/refresh-barrier.ts
+++ b/src/core/persistence/refresh-barrier.ts
@@ -77,6 +77,9 @@ export const REFRESH_BARRIER_MAX_WAIT_MS = 15 * 60_000;
* The owner's housekeeping: a deferred write whose refresh is still unreleased past the wait limit ends failed with
* `refresh_barrier_expired` (nothing applied, counters released). The refresh row is locked first (lock order: worktree,
* refresh, counters, request), so an expiry and the release that would make the row claimable never both win.
+ * GST-1582: one held for an import that has not landed past the limit ends `pending_import_expired` the same way; its
+ * claim and its expiry both move the row, so the expiry checks the row is still unclaimed and its import still pending
+ * under the request lock completeWrite takes.
*/
export async function expireDeferredWrites(engine: BrainEngine, hostId: string, signal?: AbortSignal): Promise<WriteRequest[]> {
const [config] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [REFRESH_BARRIER_MAX_WAIT_KEY], { signal });
@@ -96,21 +99,41 @@ export async function expireDeferredWrites(engine: BrainEngine, hostId: string,
});
if (done) finished.push(done);
}
+ const imports = await engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ JOIN persistence_worktrees w ON w.id=r.worktree_id JOIN sources s ON s.id=r.source_id
+ WHERE w.owner_host_id=$1::uuid AND r.state='deferred' AND r.deferred_import_from IS NOT NULL AND COALESCE(s.last_commit,'')=r.deferred_import_from
+ AND (r.deferred_refresh_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktree_refreshes f WHERE f.id=r.deferred_refresh_id AND f.released_at IS NOT NULL))
+ AND r.created_at<now()-($2::double precision*interval '1 millisecond') ORDER BY r.sequence LIMIT 100`, [hostId, maxWaitMs], { signal });
+ for (const row of imports) {
+ const done = await engine.transaction(async tx => {
+ const [held] = await tx.executeRaw(`SELECT 1 FROM persistence_requests r JOIN sources s ON s.id=r.source_id
+ WHERE r.id=$1::uuid AND r.state='deferred' AND COALESCE(s.last_commit,'')=r.deferred_import_from`, [row.id]);
+ if (!held) return null;
+ return completeWrite(tx, row, 'failed', {}, { code: 'pending_import_expired',
+ message: `Request ${row.request_id} waited more than ${Math.round(maxWaitMs / 1000)} s for managed sync to import a committed change to the file of ${row.slug}, and the import has not landed, so nothing was applied. Check the source with gbrain sync status --source ${row.source_id} --json, then submit the write again with a new request_id.` });
+ }).catch(error => { if ((error as { code?: string })?.code === 'write_claim_lost') return null; throw error; });
+ if (done) finished.push(done);
+ }
return finished;
}
-/** Whether the refresh a deferred write waits behind has ended (a read that fails counts as not ended). */
-export async function refreshReleased(engine: SqlEngine, refreshId: string | null | undefined): Promise<boolean> {
- if (!refreshId) return true;
- const [row] = await engine.executeRaw<{ released: boolean }>('SELECT released_at IS NOT NULL AS released FROM persistence_worktree_refreshes WHERE id=$1::uuid', [refreshId]).catch(() => []);
- return row?.released === true;
+/**
+ * Whether a deferred write still waits: behind a refresh not yet released, or (GST-1582) for an import that has not landed
+ * (`sources.last_commit` still the commit it was held at). A read that fails counts as waiting.
+ */
+export async function deferredWaiting(engine: SqlEngine, row: Pick<WriteRequest, 'source_id' | 'deferred_refresh_id' | 'deferred_import_from'>): Promise<boolean> {
+ const [held] = await engine.executeRaw<{ waiting: boolean }>(`SELECT
+ ($1::uuid IS NOT NULL AND NOT EXISTS (SELECT 1 FROM persistence_worktree_refreshes WHERE id=$1::uuid AND released_at IS NOT NULL))
+ OR ($2::text IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sources WHERE id=$3 AND COALESCE(last_commit,'')<>$2::text)) AS waiting`,
+ [row.deferred_refresh_id ?? null, row.deferred_import_from ?? null, row.source_id]).catch(() => [{ waiting: true }]);
+ return held?.waiting !== false;
}
/** Writes admitted deferred that have not finished (waiting, or claimed and still publishing), for `gbrain upgrade --check-downgrade`. */
export async function deferredBacklog(engine: SqlEngine): Promise<{ count: number; oldest_age_ms: number }> {
const [row] = await engine.executeRaw<{ count: number; oldest_age_ms: number | null }>(`SELECT count(*)::int AS count,
(EXTRACT(EPOCH FROM now()-min(created_at))*1000)::bigint AS oldest_age_ms FROM persistence_requests
- WHERE deferred_refresh_id IS NOT NULL AND state IN ('deferred','queued','running','recovering')`);
+ WHERE (deferred_refresh_id IS NOT NULL OR deferred_import_from IS NOT NULL) AND state IN ('deferred','queued','running','recovering')`);
return { count: Number(row?.count ?? 0), oldest_age_ms: Number(row?.oldest_age_ms ?? 0) };
}
diff --git a/src/core/persistence/refresh-retry-hint.ts b/src/core/persistence/refresh-retry-hint.ts
new file mode 100644
index 0000000000..885d9c41fa
--- /dev/null
+++ b/src/core/persistence/refresh-retry-hint.ts
@@ -0,0 +1,36 @@
+/**
+ * GST-1582: when a write or managed sync refused by an active `gbrain sources refresh` (`worktree_refreshing`) should
+ * retry, from the refresh's actual state instead of a fixed second. A refresh tick takes minutes, so a fixed 1 s hint
+ * sent an obedient caller back into the same tick to be refused again. The estimate is the median duration of the
+ * worktree's last completed refreshes minus how long this one has run, never below its phase's floor: a refresh with no
+ * history, or already past its typical duration, is retried in floor-sized steps.
+ */
+import type { SqlEngine } from './model.ts';
+
+const PHASE_FLOOR_MS: Record<string, number> = { draining: 2_000, fenced: 2_000, merged: 2_000, syncing: 15_000 };
+const MAX_RETRY_AFTER_MS = 10 * 60_000;
+const HISTORY = 10;
+
+export interface RefreshRetryHint { retryAfterMs: number; phase: string; elapsedMs: number | null; typicalMs: number | null }
+
+export async function refreshRetryHint(engine: SqlEngine, refresh: { id: string; state: string }): Promise<RefreshRetryHint> {
+ const [row] = await engine.executeRaw<{ elapsed_ms: number | string | null; typical_ms: number | string | null }>(`SELECT
+ (EXTRACT(EPOCH FROM now()-f.created_at)*1000)::bigint AS elapsed_ms,
+ (SELECT (percentile_cont(0.5) WITHIN GROUP (ORDER BY d.ms))::bigint FROM (SELECT EXTRACT(EPOCH FROM p.completed_at-p.created_at)*1000 AS ms
+ FROM persistence_worktree_refreshes p WHERE p.worktree_id=f.worktree_id AND p.state='completed' AND p.completed_at IS NOT NULL
+ ORDER BY p.completed_at DESC LIMIT ${HISTORY}) d) AS typical_ms
+ FROM persistence_worktree_refreshes f WHERE f.id=$1::uuid`, [refresh.id]).catch(() => []);
+ const elapsedMs = row?.elapsed_ms == null ? null : Number(row.elapsed_ms);
+ const typicalMs = row?.typical_ms == null ? null : Number(row.typical_ms);
+ const floor = PHASE_FLOOR_MS[refresh.state] ?? PHASE_FLOOR_MS.syncing!;
+ const left = typicalMs !== null && elapsedMs !== null ? typicalMs - elapsedMs : 0;
+ return { retryAfterMs: Math.min(MAX_RETRY_AFTER_MS, Math.max(floor, Math.round(left))), phase: refresh.state, elapsedMs, typicalMs };
+}
+
+/** The refresh's progress for a refusal message: `syncing, running 20 s, typically 220 s`. */
+export function refreshProgress(hint: RefreshRetryHint): string {
+ return [hint.phase, ...(hint.elapsedMs !== null ? [`running ${seconds(hint.elapsedMs)} s`] : []),
+ ...(hint.typicalMs !== null ? [`typically ${seconds(hint.typicalMs)} s`] : [])].join(', ');
+}
+
+export const seconds = (ms: number) => Math.max(1, Math.round(ms / 1000));
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index f39b5ce924..c2a787f905 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -1,5 +1,6 @@
import { PENDING_IMPORT, pendingImportRefusal } from './pending-import.ts';
-import { refreshReleased } from './refresh-barrier.ts';
+import { deferredWaiting } from './refresh-barrier.ts';
+import { withSupersedes } from './import-deferral.ts';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { OperationError } from '../ops/contract.ts';
@@ -116,8 +117,8 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);
if (row.operation === 'add_link' || row.operation === 'remove_link') return (await import('./manual-links.ts')).prepareManualLinkMutation(e, row, cfg);
if (row.operation === 'append_page') return (await import('./page-upload.ts')).withStagedBodyIf(e, row, async () => (await import('./page-append.ts')).prepareAppendMutation(e, row, cfg, signal, clock));
- if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return withValidTimeAdvisory(row, withChangeReason(row, await preparePageMutation(e, row, cfg, undefined, signal,
- { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock, boundedChunkWrites: true })));
+ if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return withValidTimeAdvisory(row, withChangeReason(row, await withSupersedes(row, await preparePageMutation(e, row, cfg, undefined, signal,
+ { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock, boundedChunkWrites: true }))));
throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);
}
/**
@@ -238,8 +239,9 @@ export type WriteWait =
export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig,
opts: { waitMs?: number; signal?: AbortSignal; whileHeldMs?: number } = {}): Promise<WriteWait> {
if (isTerminal(row)) return { kind: 'terminal', row };
- // PR B: a write deferred behind a refresh still running cannot publish before it ends, so its pending receipt is returned at once.
- if (row.state === 'deferred' && !await refreshReleased(engine, row.deferred_refresh_id)) return { kind: 'pending', row };
+ // PR B: a write deferred behind a refresh still running (GST-1582: or an import not landed) cannot publish before it ends,
+ // so its pending receipt is returned at once.
+ if (row.state === 'deferred' && await deferredWaiting(engine, row)) return { kind: 'pending', row };
const consumer = startPersistenceConsumer(engine, config);
const service = services.get(engine)!;
const id = row.id;
@@ -264,7 +266,11 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:
let ownerRead: SharedOwnerRead | undefined;
try {
while (!service.stopping && !opts.signal?.aborted) {
- if (handed) { row = handed; handed = undefined; if (isTerminal(row)) return { kind: 'terminal', row }; }
+ if (handed) {
+ row = handed; handed = undefined;
+ if (isTerminal(row)) return { kind: 'terminal', row };
+ if (row.state === 'deferred' && await deferredWaiting(engine, row)) return { kind: 'pending', row };
+ }
const remaining = deadline - performance.now();
if (!ownerRead && row.worktree_id && remaining <= OWNER_READ_BUDGET_MS) ownerRead = sharedOwnerRead(engine, row.worktree_id);
if (remaining <= 0) {
@@ -292,6 +298,7 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:
if (!read.row) continue;
row = { ...row, ...read.row };
if (isTerminal(row)) return { kind: 'terminal', row: await getWriteRequestById(engine, id).catch(() => null) ?? row };
+ if (row.state === 'deferred' && await deferredWaiting(engine, row)) return { kind: 'pending', row: await getWriteRequestById(engine, id).catch(() => null) ?? row };
}
// A stopped wait settles only what this process can settle at once: one consumer tick (it claims and publishes the
// request when nothing holds it back) and the request this consumer is still executing. A write that cannot move
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index 4ee0376c15..b620864c9f 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -61,7 +61,7 @@ export interface WriteReceipt {
updated_at?: string;
diagnostic?: WriteDiagnostic;
/** PR B: the write waits behind this worktree refresh and publishes after it (docs/guides/write-refusals.md#deferred-writes). */
- deferred?: { refresh_id: string };
+ deferred?: { refresh_id?: string; pending_import?: boolean };
/** #7248: a remember's target page and the entity slug its fact is keyed under (set on its own replies, never read back from the journal). */
target?: { slug: string | null; entity_slug: string | null };
}
@@ -164,7 +164,9 @@ export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {
...(receipt.created_at !== undefined ? { created_at: receipt.created_at } : {}),
...(receipt.updated_at !== undefined ? { updated_at: receipt.updated_at } : {}),
...(receipt.target !== undefined ? { target: receipt.target } : {}),
- ...(receipt.deferred !== undefined && !isTerminalWriteState(receipt.state) ? { deferred: { refresh_id: receipt.deferred.refresh_id } } : {}),
+ ...(receipt.deferred !== undefined && !isTerminalWriteState(receipt.state) ? { deferred: {
+ ...(receipt.deferred.refresh_id !== undefined ? { refresh_id: receipt.deferred.refresh_id } : {}),
+ ...(receipt.deferred.pending_import === true ? { pending_import: true } : {}) } } : {}),
...(!isTerminalWriteState(receipt.state) && isWriteDiagnostic(receipt.diagnostic) ? { diagnostic: {
age_ms: receipt.diagnostic.age_ms, assessment: receipt.diagnostic.assessment,
reason: receipt.diagnostic.reason, next_action: receipt.diagnostic.next_action,
diff --git a/src/core/persistence/worktree-refresh-schema.ts b/src/core/persistence/worktree-refresh-schema.ts
index 0196ccb6f9..0816978a1d 100644
--- a/src/core/persistence/worktree-refresh-schema.ts
+++ b/src/core/persistence/worktree-refresh-schema.ts
@@ -45,11 +45,15 @@ export const ACTIVE_REFRESH_STATES_SQL = "('draining','fenced','merged','syncing
export const CHECKOUT_EFFECT_KINDS_SQL = "('git','withdrawal-mirror')";
/**
- * PR B (docs/designs/REFRESH_WRITE_BARRIER.md): a `deferred` request whose refresh is released is waiting work like a queued
- * row; one whose refresh is still running is invisible to every claim, head and drain check (it waits for the refresh).
+ * PR B (docs/designs/REFRESH_WRITE_BARRIER.md): a `deferred` request whose holds are all released is waiting work like a
+ * queued row; one whose refresh is still running, or (GST-1582) whose import has not landed (`sources.last_commit` still
+ * the commit it was held at), is invisible to every claim, head and drain check.
*/
-export const RELEASED_DEFERRED = (r: string) => `(${r}.state='deferred' AND EXISTS (SELECT 1 FROM persistence_worktree_refreshes released
- WHERE released.id=${r}.deferred_refresh_id AND released.released_at IS NOT NULL))`;
+export const RELEASED_DEFERRED = (r: string) => `(${r}.state='deferred' AND (${r}.deferred_refresh_id IS NOT NULL OR ${r}.deferred_import_from IS NOT NULL)
+ AND (${r}.deferred_refresh_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktree_refreshes released
+ WHERE released.id=${r}.deferred_refresh_id AND released.released_at IS NOT NULL))
+ AND (${r}.deferred_import_from IS NULL OR EXISTS (SELECT 1 FROM sources imported
+ WHERE imported.id=${r}.source_id AND COALESCE(imported.last_commit,'')<>${r}.deferred_import_from)))`;
/**
* Claim predicate for a row aliased `alias` whose `column` (default `worktree_id`) names the worktree: while
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 1b9d6f4f91..77f35b9a1a 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -48,6 +48,7 @@ import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
import { redactUrlsInText } from '../url-redact.ts';
import { classifyPgAccessError } from '../pg-access-classify.ts';
import { classifyOriginUniqueViolation } from './origin-guard.ts';
+import { refreshProgress, refreshRetryHint, seconds } from './refresh-retry-hint.ts';
export interface WorktreeRefreshRow {
id: string; worktree_id: string; source_ids: string[]; principal_id: string; owner_epoch: string | number;
@@ -1148,9 +1149,10 @@ export async function assertManagedSyncAllowed(engine: BrainEngine, worktreeId:
if (refresh.state === 'recovery_required') throw refusal('refresh_recovery_required',
`Refresh ${refresh.id} could not verify the checkout HEAD of source ${sourceId}; sync stays fenced.`,
`gbrain sources writer status ${sourceId}, then gbrain sources refresh ${sourceId} --resume`, refresh.id);
- const error = refusal('worktree_refreshing', `Source ${sourceId}'s checkout is being fast-forwarded by refresh ${refresh.id} (${refresh.state}); this sync did not start.`,
- `Retry after retry_after_ms: 1000; the refresh runs this sync itself. Check progress with gbrain sources writer status ${sourceId}.`);
- error.detail = 'retry_after_ms=1000';
+ const hint = await refreshRetryHint(engine, refresh);
+ const error = refusal('worktree_refreshing', `Source ${sourceId}'s checkout is being fast-forwarded by refresh ${refresh.id} (${refreshProgress(hint)}); this sync did not start. Retry in about ${seconds(hint.retryAfterMs)} s.`,
+ `Retry after retry_after_ms: ${hint.retryAfterMs}; the refresh runs this sync itself. Check progress with gbrain sources writer status ${sourceId}.`);
+ error.detail = `retry_after_ms=${hint.retryAfterMs}`;
throw error;
}
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index c794939689..e9b5222f7a 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 290;
+export const LATEST_SCHEMA_VERSION = 291;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index f467ec5438..38d1b33e0a 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -291,6 +291,7 @@ import { v287 } from './v287-multi-page-recovery-record.ts';
import { v288 } from './v288-decide-proposals-claim-pair-index.ts';
import { v289 } from './v289-page-change-reasons.ts';
import { v290 } from './v290-refresh-write-barrier.ts';
+import { v291 } from './v291-refresh-barrier-import-deferral.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -580,4 +581,5 @@ export const MIGRATIONS: Migration[] = [
v288,
v289,
v290,
+ v291,
];
diff --git a/src/core/schema-migrations/v291-refresh-barrier-import-deferral.ts b/src/core/schema-migrations/v291-refresh-barrier-import-deferral.ts
new file mode 100644
index 0000000000..f016c2cb59
--- /dev/null
+++ b/src/core/schema-migrations/v291-refresh-barrier-import-deferral.ts
@@ -0,0 +1,37 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GST-1582 (docs/designs/REFRESH_WRITE_BARRIER.md, "Writes that wait for an import"): with the refresh write barrier on,
+// a page write whose file holds a committed change managed sync has not imported yet waits instead of being refused.
+// - persistence_requests.deferred_import_from: the source's last imported commit ('' when it had none) when a claimed
+// write was held for an import; the row waits in state 'deferred' until sources.last_commit moves past it.
+// - gbrain_guard_deferred_request: a refresh-barrier consumer may move its own running claim to 'deferred' when it names
+// the import it waits for; a deferred row is claimed only once every hold it names (refresh, import) is released.
+// A nullable column with no backfill; fresh installs get it from this migration too, so fresh and upgraded brains share
+// column ordinals. The number is a placeholder restamped at the merge slot.
+export const v291: Migration = {
+ version: 291,
+ name: 'refresh_barrier_import_deferral',
+ idempotent: true,
+ sql: `
+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS deferred_import_from text;
+ CREATE OR REPLACE FUNCTION gbrain_guard_deferred_request() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
+ BEGIN
+ IF NEW.state='deferred' THEN
+ IF OLD.state='deferred' THEN RETURN NEW; END IF;
+ IF OLD.state='running' AND NEW.deferred_import_from IS NOT NULL AND COALESCE(current_setting('gbrain.refresh_barrier',true),'')='1' THEN RETURN NEW; END IF;
+ RAISE EXCEPTION 'unsupported_mutation_protocol: only admission, or a refresh-barrier consumer holding its claim for an import, defers a request' USING ERRCODE='42501';
+ END IF;
+ IF NEW.state IN ('conflict','failed','cancelled') THEN RETURN NEW; END IF;
+ IF NEW.state='running' AND COALESCE(current_setting('gbrain.refresh_barrier',true),'')='1'
+ AND (OLD.deferred_refresh_id IS NOT NULL OR OLD.deferred_import_from IS NOT NULL)
+ AND (OLD.deferred_refresh_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktree_refreshes f WHERE f.id=OLD.deferred_refresh_id AND f.released_at IS NOT NULL))
+ AND (OLD.deferred_import_from IS NULL OR EXISTS (SELECT 1 FROM sources s WHERE s.id=OLD.source_id AND COALESCE(s.last_commit,'')<>OLD.deferred_import_from)) THEN
+ RETURN NEW;
+ END IF;
+ RAISE EXCEPTION 'writer_upgrade_required: a deferred request is claimed only by a refresh-barrier consumer after its refresh and import are released' USING ERRCODE='42501';
+ END $$;
+ `,
+};
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 8c21024d02..3462c92cbd 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -596,7 +596,7 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
- "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
@@ -3670,7 +3670,8 @@
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
"46 next_attempt_at timestamp with time zone/timestamptz NULL",
- "47 deferred_refresh_id uuid/uuid NULL"
+ "47 deferred_refresh_id uuid/uuid NULL",
+ "48 deferred_import_from text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index d2f0d2bbe4..4f7520e647 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -596,7 +596,7 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
- "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
@@ -3670,7 +3670,8 @@
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
"46 next_attempt_at timestamp with time zone/timestamptz NULL",
- "47 deferred_refresh_id uuid/uuid NULL"
+ "47 deferred_refresh_id uuid/uuid NULL",
+ "48 deferred_import_from text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index c83a65a39a..527592d4ee 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -596,7 +596,7 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
- "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
@@ -3666,7 +3666,8 @@
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
"46 next_attempt_at timestamp with time zone/timestamptz NULL",
- "47 deferred_refresh_id uuid/uuid NULL"
+ "47 deferred_refresh_id uuid/uuid NULL",
+ "48 deferred_import_from text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 7442580f14..937e61e789 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -599,7 +599,7 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
- "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
@@ -3682,7 +3682,8 @@
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
"46 next_attempt_at timestamp with time zone/timestamptz NULL",
- "47 deferred_refresh_id uuid/uuid NULL"
+ "47 deferred_refresh_id uuid/uuid NULL",
+ "48 deferred_import_from text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 399dfef20d..c4a087a0fb 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -599,7 +599,7 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
- "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
@@ -3682,7 +3682,8 @@
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
"46 next_attempt_at timestamp with time zone/timestamptz NULL",
- "47 deferred_refresh_id uuid/uuid NULL"
+ "47 deferred_refresh_id uuid/uuid NULL",
+ "48 deferred_import_from text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 5849322340..1807ce37c4 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -599,7 +599,7 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
- "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
@@ -3678,7 +3678,8 @@
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
"46 next_attempt_at timestamp with time zone/timestamptz NULL",
- "47 deferred_refresh_id uuid/uuid NULL"
+ "47 deferred_refresh_id uuid/uuid NULL",
+ "48 deferred_import_from text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 519a9314d8..91745bfeca 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6835,7 +6835,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 1f09d5e509..d3f4183301 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 285,
+ "count": 286,
"gaps": [
17,
18,
@@ -95,7 +95,7 @@
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67",
"withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"
},
- "latest": 290,
+ "latest": 291,
"records": [
{
"handler": {
@@ -4729,6 +4729,19 @@
"transaction": false,
"verify": "absent",
"version": 290
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "refresh_barrier_import_deferral",
+ "sql": {
+ "length": 1530,
+ "sha256": "26c97caa36ce1c4a05bcda4d16aed85a3b3f152064b92cd43d97f3444d28b1cb"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 291
}
],
"versions": [
@@ -5016,7 +5029,8 @@
287,
288,
289,
- 290
+ 290,
+ 291
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index ec94e13cc4..9d6a9404ff 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -596,7 +596,7 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
- "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
@@ -3670,7 +3670,8 @@
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
"46 next_attempt_at timestamp with time zone/timestamptz NULL",
- "47 deferred_refresh_id uuid/uuid NULL"
+ "47 deferred_refresh_id uuid/uuid NULL",
+ "48 deferred_import_from text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/import-write-barrier.test.ts b/test/import-write-barrier.test.ts
new file mode 100644
index 0000000000..a72bbafd6d
--- /dev/null
+++ b/test/import-write-barrier.test.ts
@@ -0,0 +1,219 @@
+/**
+ * GST-1582: a page write never bounces because a sync is running (docs/designs/REFRESH_WRITE_BARRIER.md, "Writes that
+ * wait for an import").
+ *
+ * Protects: with persistence.refresh_barrier on, a put_page, capture or remember whose page file holds a committed change
+ * managed sync has not imported yet (`pending_import`) is held `deferred` and answered pending, then published by itself
+ * once the import lands, prepared again as if it had queued behind the import: remember applies on top, a put_page with
+ * expected_revision (what a remote caller must send for an existing page) ends revision_conflict, a blind (force) put_page or capture lands, and a put_page's receipt,
+ * its commit trailer and the commit ledger name the imported revision and commit it replaced (both stay in page history and git). A write admitted while a
+ * refresh is in recovery_required waits behind it and lands once the refresh is released. A held write whose import never
+ * lands ends `pending_import_expired`. With the barrier off the refusal is unchanged.
+ * Seams: the real managed sync and refresh state machine; GBRAIN_REFRESH_BARRIER; the effect worker run in-process.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';
+import { getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { resetWriteSwitches } from '../src/core/persistence/switches.ts';
+import { _setRefreshFenceWaitForTests } from '../src/core/persistence/admission-retry.ts';
+import { _resetRefreshBarrierCacheForTests, deferredBacklog, expireDeferredWrites } from '../src/core/persistence/refresh-barrier.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { refreshWorktree, resumeWorktreeRefreshes } from '../src/core/persistence/worktree-refresh.ts';
+import { readLedger } from '../src/core/git/commit-ledger.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { commitFile, git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+});
+beforeEach(() => { _setRefreshFenceWaitForTests(0); _resetRefreshBarrierCacheForTests(); });
+afterEach(() => { resetWriteSwitches(); _setRefreshFenceWaitForTests(null); });
+
+const each = (fn: (f: RefreshFixture) => Promise<void>, barrier = '1') => withEnv({ GBRAIN_REFRESH_BARRIER: barrier }, async () => {
+ resetWriteSwitches();
+ for (const engine of engines) await withRefreshFixture(engine, async f => {
+ git(f.root, 'config', 'user.name', 'Example'); git(f.root, 'config', 'user.email', '[email protected]'); git(f.root, 'config', 'commit.gpgsign', 'false');
+ await fn(f);
+ });
+});
+
+async function call(f: RefreshFixture, name: string, params: Record<string, unknown>) {
+ const result = await dispatchToolCall(f.engine, name, params, { remote: true, transport: 'stdio', sourceId: f.alpha, admissionOrigin: 'interactive' });
+ return { isError: result.isError === true, body: JSON.parse(result.content[0]!.text) as Record<string, any> };
+}
+async function requestRow(f: RefreshFixture, requestId: string): Promise<WriteRequest> {
+ const [row] = await f.engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ return row!;
+}
+/** A blind local CLI write (force, no expected_revision): its receipt whether it settled or was left pending (write_pending). */
+async function local(f: RefreshFixture, operation: 'put_page' | 'capture', params: Record<string, unknown>): Promise<{ pending: boolean; receipt: Record<string, any> }> {
+ try {
+ const receipt = await submitPageMutation(f.ctx(f.alpha), { operation, params: { request_id: randomUUID(), force: true, ...params } }) as Record<string, any>;
+ return { pending: false, receipt };
+ } catch (error) {
+ const e = error as { code?: string; writeError?: string; writeRequest?: Record<string, any> };
+ if ((e.code === 'write_pending' || e.writeError === 'write_pending') && e.writeRequest) return { pending: true, receipt: e.writeRequest };
+ throw error;
+ }
+}
+const settle = async (f: RefreshFixture, row: WriteRequest) => waitForWrite(f.engine, (await getWriteRequestById(f.engine, row.id))!, { engine: f.engine.kind } as never, 30_000);
+const importNow = (f: RefreshFixture) => performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true });
+const file = (f: RefreshFixture, rel: string) => readFileSync(join(f.root, 'alpha', rel), 'utf8');
+const IMPORTED = 'Another writer committed this line.';
+/** Runs the effect worker until request `id`'s Git effect has committed (the resident consumer may hold it meanwhile). */
+async function gitEffectDone(f: RefreshFixture, id: string): Promise<void> {
+ for (let i = 0; i < 100; i++) {
+ await runPersistenceEffects(f.engine, { engine: f.engine.kind } as never, { hostId: localHostId() });
+ const [effect] = await f.engine.executeRaw<{ state: string; outcome: { git?: string } | null }>("SELECT state,outcome FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [id]);
+ if (effect?.state === 'committed') { expect(effect.outcome?.git).toBe('committed'); return; }
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error(`the Git effect of request ${id} did not commit`);
+}
+/** Records Git durability on for the owner, so its Git effects commit instead of completing as skipped. */
+const durable = (f: RefreshFixture) => f.engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");
+
+/** Another writer's commit to alpha/<rel> that managed sync has not imported yet. */
+const foreignCommit = (f: RefreshFixture, rel: string, content: string) => commitFile(f.root, `alpha/${rel}`, content, 'another writer');
+
+test('a blind put_page onto a file awaiting import is held pending, lands after the import, and names the imported revision it replaced', () => each(async f => {
+ await durable(f);
+ const before = await f.lastCommit(f.alpha);
+ const imported = foreignCommit(f, 'one.md', page('Alpha one', IMPORTED));
+ const out = await local(f, 'put_page', { slug: 'one', content: page('Alpha one', 'Mine, written while the import waited.') });
+ expect(out).toMatchObject({ pending: true, receipt: { state: 'queued', deferred: { pending_import: true } } });
+ const held = await requestRow(f, out.receipt.request_id);
+ expect(held).toMatchObject({ state: 'deferred', deferred_refresh_id: null, deferred_import_from: before });
+ expect((await deferredBacklog(f.engine)).count).toBe(1);
+ await importNow(f);
+ const done = await settle(f, held);
+ expect(done.state).toBe('committed');
+ expect(file(f, 'one.md')).toContain('Mine, written while the import waited.');
+ const supersedes = (done.outcome as { supersedes?: { slug: string; revision: unknown; commit: string } }).supersedes;
+ expect(supersedes).toMatchObject({ slug: 'one', commit: imported });
+ expect(supersedes!.revision).toBeTruthy();
+ // The replaced content stays in page history and in git.
+ const history = await f.engine.executeRaw<{ compiled_truth: string | null }>(
+ 'SELECT v.compiled_truth FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2', [f.alpha, 'one']);
+ expect(history.some(v => (v.compiled_truth ?? '').includes(IMPORTED))).toBe(true);
+ expect(git(f.root, 'show', `${imported}:alpha/one.md`)).toContain(IMPORTED);
+ git(f.root, 'merge-base', '--is-ancestor', imported, 'HEAD');
+ await gitEffectDone(f, done.id);
+ const commit = git(f.root, 'log', '-1', '--format=%H', '--', 'alpha/one.md');
+ expect(git(f.root, 'log', '-1', '--format=%B', commit)).toContain(`gbrain-supersedes: one.md: revision ${supersedes!.revision} from ${imported}`);
+ const line = readLedger(join(f.root, '.git')).find(r => r.e === 'commit' && r.sha === commit) as { supersedes?: string[] } | undefined;
+ expect(line?.supersedes).toEqual([`one.md: revision ${supersedes!.revision} from ${imported}`]);
+ expect((await deferredBacklog(f.engine)).count).toBe(0);
+}), 180_000);
+
+test('a capture onto a file awaiting import lands after the import', () => each(async f => {
+ foreignCommit(f, 'one.md', page('Alpha one', IMPORTED));
+ const out = await local(f, 'capture', { slug: 'one', content: 'Captured while the import waited.' });
+ expect(out.pending).toBe(true);
+ const held = await requestRow(f, out.receipt.request_id);
+ expect(held.state).toBe('deferred');
+ await importNow(f);
+ expect((await settle(f, held)).state).toBe('committed');
+ expect(file(f, 'one.md')).toContain('Captured while the import waited.');
+}), 180_000);
+
+const PERSON = '---\ntitle: Alice Example\ntype: person\n---\nAlice is a person.\n';
+
+test('a remember onto a file awaiting import lands on top of the imported page', () => each(async f => {
+ foreignCommit(f, 'people/alice-example.md', PERSON);
+ await importNow(f);
+ foreignCommit(f, 'people/alice-example.md', PERSON.replace('Alice is a person.', `Alice is a person. ${IMPORTED}`));
+ const out = await call(f, 'remember', { fact: 'alice-example likes tea', entity: 'people/alice-example', provenance: 'test' });
+ expect(out.isError).toBe(false);
+ expect(out.body.status).toBe('pending');
+ const held = await requestRow(f, out.body.request_id);
+ expect(held.state).toBe('deferred');
+ await importNow(f);
+ expect((await settle(f, held)).state).toBe('committed');
+ const content = file(f, 'people/alice-example.md');
+ expect(content).toContain(IMPORTED);
+ expect(content).toContain('alice-example likes tea');
+}), 180_000);
+
+test('a put_page with expected_revision onto a file awaiting import ends revision_conflict once the import moved the page', () => each(async f => {
+ const seen = (await f.engine.readPageSnapshot('one', { sourceId: f.alpha }))!.revision;
+ foreignCommit(f, 'one.md', page('Alpha one', IMPORTED));
+ const out = await call(f, 'put_page', { slug: 'one', content: page('Alpha one', 'Based on the old revision.'), expected_revision: seen });
+ expect(out.isError).toBe(false);
+ const held = await requestRow(f, out.body.request_id);
+ expect(held.state).toBe('deferred');
+ await importNow(f);
+ expect(await settle(f, held)).toMatchObject({ state: 'conflict', error_code: 'revision_conflict' });
+ expect(file(f, 'one.md')).toContain(IMPORTED);
+}), 180_000);
+
+test('a held write whose import never lands ends pending_import_expired with nothing applied', () => each(async f => {
+ foreignCommit(f, 'one.md', page('Alpha one', IMPORTED));
+ const out = await local(f, 'put_page', { slug: 'one', content: page('Alpha one', 'Never applied.') });
+ const held = await requestRow(f, out.receipt.request_id);
+ expect(held.state).toBe('deferred');
+ await f.engine.executeRaw("INSERT INTO config(key,value) VALUES('persistence.refresh_barrier_max_wait_ms','1') ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value");
+ await new Promise(resolve => setTimeout(resolve, 20));
+ const [{ owner }] = await f.engine.executeRaw<{ owner: string }>('SELECT owner_host_id::text AS owner FROM persistence_worktrees WHERE id=$1::uuid', [f.worktreeId]);
+ expect((await expireDeferredWrites(f.engine, owner)).map(row => row.id)).toEqual([held.id]);
+ expect(await getWriteRequestById(f.engine, held.id)).toMatchObject({ state: 'failed', error_code: 'pending_import_expired' });
+ await f.engine.executeRaw("DELETE FROM config WHERE key='persistence.refresh_barrier_max_wait_ms'");
+ expect(file(f, 'one.md')).toContain(IMPORTED);
+}), 180_000);
+
+test('with the barrier off a write onto a file awaiting import keeps the pending_import refusal', () => each(async f => {
+ const seen = (await f.engine.readPageSnapshot('one', { sourceId: f.alpha }))!.revision;
+ foreignCommit(f, 'one.md', page('Alpha one', IMPORTED));
+ const out = await call(f, 'put_page', { slug: 'one', content: page('Alpha one', 'Refused.'), expected_revision: seen });
+ expect(out.isError).toBe(true);
+ const [row] = await f.engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE operation=$1 ORDER BY sequence DESC LIMIT 1', ['put_page']);
+ expect(row).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ expect((row!.error_detail as { origin?: string }).origin).toBe('pending_import');
+}, '0'), 180_000);
+
+test('a write while a refresh is in recovery_required waits behind it and lands once the refresh is released', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ const old = f.head();
+ await expect(refreshWorktree(f.engine, f.alpha, { hooks: { boundary: point => { if (point === 'merged') throw new Error('simulated crash after merge'); } } }))
+ .rejects.toThrow('simulated crash');
+ git(f.root, 'reset', '-q', '--hard', old);
+ git(f.root, 'commit', '-q', '--allow-empty', '-m', 'unrelated');
+ await resumeWorktreeRefreshes(f.engine);
+ expect((await f.refreshRows()).map(r => r.state)).toEqual(['recovery_required']);
+ const out = await call(f, 'put_page', { slug: 'notes/during-recovery', content: page('During recovery', 'Accepted while the refresh awaited recovery.') });
+ expect(out.isError).toBe(false);
+ expect(out.body.status).toBe('pending');
+ const held = await requestRow(f, out.body.request_id);
+ expect(held.state).toBe('deferred');
+ git(f.root, 'reset', '-q', '--hard', old);
+ expect((await refreshWorktree(f.engine, f.alpha, { abandon: true })).status).toBe('abandoned');
+ expect((await settle(f, held)).state).toBe('committed');
+ expect(file(f, 'notes/during-recovery.md')).toContain('Accepted while the refresh awaited recovery.');
+}), 180_000);
diff --git a/test/refresh-retry-hint-gst1582.test.ts b/test/refresh-retry-hint-gst1582.test.ts
new file mode 100644
index 0000000000..db35249454
--- /dev/null
+++ b/test/refresh-retry-hint-gst1582.test.ts
@@ -0,0 +1,143 @@
+/**
+ * GST-1582: a write refused because `gbrain sources refresh` holds its checkout (`worktree_refreshing`, the barrier off or
+ * a consumer without it) is told when to retry from the refresh's actual state, never a fixed 1 s, and the CLI says on
+ * one line that nothing was saved and when to retry.
+ *
+ * Protects: `retry_after_ms` is the typical duration of the worktree's recent completed refreshes minus how long this one
+ * has run, never below its phase's floor (syncing 15 s, the fenced phases 2 s), the same for a managed sync the refresh
+ * refused; the message says the write was not saved and when to retry; the CLI's human output ends with one line that
+ * says nothing was saved and when to retry, so it survives `| tail -1`.
+ * Regression it catches: a refresh tick of several minutes answered "retry after retry_after_ms: 1000", so a caller that
+ * obeyed retried inside the same tick, was refused again and gave up.
+ * Seams: refresh rows inserted at a chosen age (the refresh state machine is not driven); the fence wait test seam.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { createEngine } from '../src/core/engine-factory.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { assertManagedSyncAllowed } from '../src/core/persistence/worktree-refresh.ts';
+import { _setRefreshFenceWaitForTests } from '../src/core/persistence/admission-retry.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { page, setupRefreshFixture, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+});
+afterEach(() => _setRefreshFenceWaitForTests(null));
+
+const each = (fn: (f: RefreshFixture) => Promise<void>) => withEnv({ GBRAIN_REFRESH_BARRIER: '0' }, async () => {
+ for (const engine of engines) await withRefreshFixture(engine, fn);
+});
+
+/** Completed refreshes of the worktree that each took `seconds`, finished in the past hour. */
+async function history(engine: BrainEngine, f: Pick<RefreshFixture, 'worktreeId' | 'alpha' | 'beta' | 'head'>, seconds: number[]): Promise<void> {
+ const [w] = await engine.executeRaw<{ e: string }>('SELECT owner_epoch::text AS e FROM persistence_worktrees WHERE id=$1::uuid', [f.worktreeId]);
+ const [b] = await engine.executeRaw<{ g: string }>('SELECT topology_generation::text AS g FROM persistence_source_bindings WHERE source_id=$1', [f.alpha]);
+ for (const [i, s] of seconds.entries()) {
+ await engine.executeRaw(`INSERT INTO persistence_worktree_refreshes (worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref,created_at,completed_at)
+ VALUES($1::uuid,$2::text[],gen_random_uuid(),$3,$4,'completed',$5,$5,'origin/main',now()-(($6::integer+$7::integer)*interval '1 second'),now()-($7::integer*interval '1 second'))`,
+ [f.worktreeId, [f.alpha, f.beta], w!.e, b!.g, f.head(), s, 600 + i * 900]);
+ }
+}
+/** An active refresh in `state`, started `ageSeconds` ago, short of its target so it keeps the fence. */
+async function activeRefresh(engine: BrainEngine, f: Pick<RefreshFixture, 'worktreeId' | 'alpha' | 'beta' | 'head' | 'push'>, state: string, ageSeconds: number): Promise<void> {
+ const target = f.push('alpha/two.md', page('Alpha two', 'upstream'));
+ const [w] = await engine.executeRaw<{ e: string }>('SELECT owner_epoch::text AS e FROM persistence_worktrees WHERE id=$1::uuid', [f.worktreeId]);
+ const [b] = await engine.executeRaw<{ g: string }>('SELECT topology_generation::text AS g FROM persistence_source_bindings WHERE source_id=$1', [f.alpha]);
+ await engine.executeRaw(`INSERT INTO persistence_worktree_refreshes (worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref,created_at)
+ VALUES($1::uuid,$2::text[],gen_random_uuid(),$3,$4,$5,$6,$7,'origin/main',now()-($8::integer*interval '1 second'))`,
+ [f.worktreeId, [f.alpha, f.beta], w!.e, b!.g, state, f.head(), target, ageSeconds]);
+}
+async function refused(f: RefreshFixture) {
+ const result = await dispatchToolCall(f.engine, 'put_page', { slug: 'notes/refused', content: page('Refused', 'body') },
+ { remote: true, transport: 'stdio', sourceId: f.alpha, admissionOrigin: 'interactive' });
+ const body = JSON.parse(result.content[0]!.text) as Record<string, any>;
+ expect(result.isError).toBe(true);
+ expect(body.code).toBe('worktree_refreshing');
+ return { body, retryAfterMs: Number(/^retry_after_ms=(\d+)$/.exec(String(body.detail))?.[1]) };
+}
+
+test('a write refused during a syncing refresh is told the time its refresh typically has left, not 1 s', () => each(async f => {
+ _setRefreshFenceWaitForTests(0);
+ await history(f.engine, f, [200, 240, 220]);
+ await activeRefresh(f.engine, f, 'syncing', 20);
+ const { body, retryAfterMs } = await refused(f);
+ expect(retryAfterMs).toBeGreaterThanOrEqual(190_000);
+ expect(retryAfterMs).toBeLessThanOrEqual(201_000);
+ expect(body.message).toContain('not saved');
+ expect(body.message).toMatch(/[Rr]etry the same request_id in about (19\d|200|201) s/);
+ expect(body.message).not.toContain('\n');
+}), 120_000);
+
+test('with no refresh history, or past its typical duration, the hint is the phase floor, never 1 s', () => each(async f => {
+ _setRefreshFenceWaitForTests(0);
+ await activeRefresh(f.engine, f, 'syncing', 5);
+ expect((await refused(f)).retryAfterMs).toBe(15_000);
+ await f.engine.executeRaw("UPDATE persistence_worktree_refreshes SET state='fenced' WHERE state='syncing'");
+ expect((await refused(f)).retryAfterMs).toBe(2_000);
+ await history(f.engine, f, [3]);
+ await f.engine.executeRaw("UPDATE persistence_worktree_refreshes SET state='syncing',created_at=now()-interval '60 seconds' WHERE state='fenced'");
+ expect((await refused(f)).retryAfterMs).toBe(15_000);
+}), 120_000);
+
+test('a managed sync the refresh refused gets the same derived hint', () => each(async f => {
+ await history(f.engine, f, [120]);
+ await activeRefresh(f.engine, f, 'fenced', 30);
+ const error = await assertManagedSyncAllowed(f.engine, f.worktreeId, f.alpha).then(() => null, e => e as OperationError);
+ expect(error?.code).toBe('worktree_refreshing');
+ const hinted = Number(/^retry_after_ms=(\d+)$/.exec(String(error!.detail))?.[1]);
+ expect(hinted).toBeGreaterThanOrEqual(85_000);
+ expect(hinted).toBeLessThanOrEqual(91_000);
+}), 120_000);
+
+test('CLI text output ends with one line saying nothing was saved and when to retry', async () => {
+ if (!backends.includes('pglite')) return;
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-gst1582-'));
+ const home = join(dir, 'home');
+ try {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ const cfg = { engine: 'pglite' as const, database_path: join(home, '.gbrain', 'brain.pglite') };
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(cfg));
+ const alpha = await withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = await createEngine(cfg);
+ await engine.connect(cfg); await engine.initSchema();
+ try {
+ const f = await setupRefreshFixture(engine, dir);
+ await history(engine, f, [200, 240, 220]);
+ await activeRefresh(engine, f, 'syncing', 20);
+ return f.alpha;
+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ });
+ const out = spawnSync('bun', ['run', 'src/cli.ts', 'put', 'notes/refused', '--source-id', alpha], { cwd: process.cwd(), encoding: 'utf8', input: page('Refused', 'body'), timeout: 120_000,
+ env: { ...process.env, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_REFRESH_BARRIER: '0' } });
+ expect(out.status).toBe(1);
+ const last = out.stderr.trimEnd().split('\n').at(-1)!;
+ expect(last).toMatch(/^Nothing was saved; retry the same command in about \d+ s \(retry_after_ms=\d+\)\.$/);
+ expect(Number(/retry_after_ms=(\d+)/.exec(last)![1])).toBeGreaterThanOrEqual(150_000);
+ expect(out.stderr).toContain('This write was not saved');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}, 240_000);
diff --git a/test/refresh-write-barrier.test.ts b/test/refresh-write-barrier.test.ts
index 7a43927edf..b7190a5ae9 100644
--- a/test/refresh-write-barrier.test.ts
+++ b/test/refresh-write-barrier.test.ts
@@ -6,7 +6,7 @@
* refresh ends it commits, unless the refresh changed its file, which ends it `revision_conflict` with nothing applied;
* a consumer claim without the barrier's session declaration (an older binary) cannot move a deferred row; a replay of the
* request id returns the same receipt; a write past the wait limit ends `refresh_barrier_expired` with its counters
- * released; a token revoked while its write waits ends it `permission_denied`; past the per-refresh cap a further write keeps the refusal; a live consumer without the capability keeps the
+ * released; a token revoked while its write waits ends it `permission_denied`; every write during a refresh is deferred, with no per-refresh cap; a live consumer without the capability keeps the
* refusal; a repo-less source is never deferred; `gbrain upgrade --check-downgrade` exits 3 while a deferred write waits.
* Seams: the real refresh state machine paused at its drained boundary (`hooks.boundary`); GBRAIN_REFRESH_BARRIER.
*/
@@ -206,23 +206,21 @@ test('a live consumer without the capability keeps the refusal; a repo-less sour
expect((await refresh).status).toBe('completed');
}), 180_000);
-test('past persistence.refresh_barrier_max_deferred a further write during the refresh keeps the refusal', () => each(async f => {
+test('GST-1582: writes during one refresh are all deferred, none refused, and each commits after it (a configured cap no longer refuses)', () => each(async f => {
await f.engine.executeRaw("INSERT INTO config(key,value) VALUES('persistence.refresh_barrier_max_deferred','1') ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value");
- let first!: WriteRequest;
+ const held: WriteRequest[] = [];
try {
const refresh = await duringRefresh(f, async () => {
- const out = await call(f, 'put_page', { slug: 'notes/cap-one', content: page('Cap one', 'deferred') });
- expect(out.body.status).toBe('pending');
- first = await requestRow(f, out.body.request_id);
- expect(first.state).toBe('deferred');
- const before = await f.requestCount();
- const refused = await call(f, 'put_page', { slug: 'notes/cap-two', content: page('Cap two', 'refused') });
- expect(refused.isError).toBe(true);
- expect(refused.body.code).toBe('worktree_refreshing');
- expect(await f.requestCount()).toBe(before);
+ for (const name of ['cap-one', 'cap-two', 'cap-three']) {
+ const out = await call(f, 'put_page', { slug: `notes/${name}`, content: page(name, 'deferred') });
+ expect(out.isError).toBe(false);
+ expect(out.body.status).toBe('pending');
+ held.push(await requestRow(f, out.body.request_id));
+ }
+ expect(held.map(row => row.state)).toEqual(['deferred', 'deferred', 'deferred']);
});
expect((await refresh).status).toBe('completed');
- expect((await settle(f, first)).state).toBe('committed');
+ for (const row of held) expect((await settle(f, row)).state).toBe('committed');
} finally {
await f.engine.executeRaw("DELETE FROM config WHERE key='persistence.refresh_barrier_max_deferred'");
}
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index 1d8eb04687..cb201c03be 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -1261,6 +1261,8 @@ const COLUMN_EXEMPTIONS = new Set<string>([
'persistence_worktree_refreshes.released_at',
'persistence_requests.deferred_refresh_id',
'persistence_consumers.capabilities',
+ // GST-1582 (v291): migration-only like the PR B columns above, for the same reason.
+ 'persistence_requests.deferred_import_from',
]);
test('every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap (column-only class)', async () => {
diff --git a/test/write-refusal-refresh-fence-8621.test.ts b/test/write-refusal-refresh-fence-8621.test.ts
index 8a27924d10..7229def775 100644
--- a/test/write-refusal-refresh-fence-8621.test.ts
+++ b/test/write-refusal-refresh-fence-8621.test.ts
@@ -52,6 +52,7 @@ afterAll(async () => {
afterEach(() => _setRefreshFenceWaitForTests(null));
const each = async (fn: (f: RefreshFixture) => Promise<void>) => { for (const engine of engines) await withRefreshFixture(engine, fn); };
+const retryAfter = (body: Record<string, any>) => Number(/^retry_after_ms=(\d+)$/.exec(String(body.detail))?.[1]);
const PERSON = '---\ntitle: Alice Example\ntype: person\n---\nAlice is a person.\n';
/** An entity page on the managed source, committed and synced through a completed refresh. */
@@ -84,7 +85,10 @@ test('remember items: a batch the fence refused entirely is an MCP error with a
const before = await f.requestCount();
const out = await call(f, 'remember', { items: [{ fact: 'alice-example likes tea', entity: 'people/alice-example', provenance: 'test' }] });
expect(out.isError).toBe(true);
- expect(out.body).toMatchObject({ error: 'unavailable', code: 'worktree_refreshing', retryable: true, detail: 'retry_after_ms=1000' });
+ expect(out.body).toMatchObject({ error: 'unavailable', code: 'worktree_refreshing', retryable: true });
+ expect(out.body.detail).toMatch(/^retry_after_ms=\d+$/);
+ // GST-1582: derived from the refresh's state, at least the fenced phases' 2 s floor (refresh-retry-hint-gst1582.test.ts).
+ expect(retryAfter(out.body)).toBeGreaterThanOrEqual(2000);
expect(out.body.message).toContain('items[0]');
expect(out.body.message).toContain('None of the 1 item(s) was saved');
expect(out.body.fix.next).toBe('wait');
@@ -112,7 +116,9 @@ test('put_page past the wait cap is refused retryable with fix.next wait and ret
const out = await call(f, 'put_page', { slug: 'notes/capped', content: page('Capped', 'refused after the cap') });
expect(performance.now() - started).toBeGreaterThanOrEqual(250);
expect(out.isError).toBe(true);
- expect(out.body).toMatchObject({ error: 'worktree_refreshing', code: 'worktree_refreshing', class: 'retryable', retryable: true, detail: 'retry_after_ms=1000' });
+ expect(out.body).toMatchObject({ error: 'worktree_refreshing', code: 'worktree_refreshing', class: 'retryable', retryable: true });
+ expect(out.body.detail).toMatch(/^retry_after_ms=\d+$/);
+ expect(retryAfter(out.body)).toBeGreaterThanOrEqual(2000);
expect(out.body.fix.next).toBe('wait');
expect(out.body.message).toContain('waited');
expect(await f.requestCount()).toBe(before);