Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a managed import or sync of a new page over 4 MiB replies at commit with searchable pending (#7106)
garrytan1d32c8f939f0
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 242766d0cd..42ebf2acc4 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -24,7 +24,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. Engine helpers that bypass `executeRaw` (`readPageSnapshot`, the import pipeline) stay under the consumer's race and the ceiling. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`. GBRA-75 wave 9: `withBoundedReadSession` gives a waiver screen (`unchangedSyncImport`) one reserved ordinary-pool connection (a long-hold permit; none left, or PGLite, runs the screen as before) on which its bounded reads share one transaction: `BEGIN; SET LOCAL statement_timeout` once, `COMMIT` when the screen settles. The bound stays per statement on the server: it is set again in the read's pipeline once the bound in force differs from the read's own by more than `BOUNDED_SESSION_SLACK_MS` (25 ms). A waiver run (`waiveRun` in `sync-run.ts`) opens one session for all its screens, and a screen inside it joins it. Session reads are named prepared statements (`ReservedConnection.executeRaw` `prepare`, ANDed with the connection option as `runUnsafe` does). A failed read rolls back and the reads it aborted (25P02) run again in a new transaction; a read after the screen settled takes the per-read path. Test: `test/persistence-bounded-read-session.test.ts` (real lock wait and no remaining statement on Postgres).- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`. `transfer_in_progress` is `wait` until the drain's `prepared_at` is `TRANSFER_STALE_MINUTES` (30) old, then `ask_user` naming the accept and the exact `transfer cancel` argv (a drain with no `prepared_at` keeps the wait).- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. A statement the database ended with 57014 (statement timeout or cancel: `coordinator.ts` `writeInterruption`) is charged too, in `finishUnpublishedFailure` and in `publishMutation`'s recovery route, and at the limit ends the request `failed` with `write_interrupted` instead of a `database_contention` release; contention with other transactions (55P03, 40001, 40P01), a dropped connection or a restarting database is never charged (`test/persistence-write-interrupted.test.ts`). The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes); a provably dead owner's claim goes in 5 s (#6650). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. A statement the database ended with 57014 (statement timeout or cancel: `coordinator.ts` `writeInterruption`) is charged too, in `finishUnpublishedFailure` and in `publishMutation`'s recovery route, and at the limit ends the request `failed` with `write_interrupted` instead of a `database_contention` release; contention with other transactions (55P03, 40001, 40P01), a dropped connection or a restarting database is never charged (`test/persistence-write-interrupted.test.ts`). The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes); a provably dead owner's claim goes in 5 s (#6650). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`). #7106: `publishSingle` passes `projectionPending` (coordinator.ts `PublicationHooks`): a committed write whose outcome says `searchable: 'pending'` (a new segmented page over SEGMENTED_CREATE_SEAL_MAX_BYTES: `segmentedOutcome` in searchable.ts, recorded by the managed import, sync and put_page preparers) settles its waiter at commit and its `afterCommit` projection runs on in `outlived` (stop() waits for it), holding neither the reply nor the root; a publication without the hook awaits afterCommit as before (`test/large-pages/managed-import-projection-pending.test.ts`).- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken or waived entry, or #6712 a slug or page id shared with a member in flight or held, `dependencyKeys`) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the pending entry (settled by fault class; later members stay in the window, #6712), a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). #6712: each member keeps its own fate (sync groups keep claim 64, width four, ordered release, `syncGroup`): a failed preparation settles before the rest publish as a group; a sync member its lane group's transaction refused settles alone, the rest requeue (`settleCulprit`); other failures roll back and members publish singly. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). A `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member (GBRA-75 wave 10: `preparationReads` answers `getConfig` from one `getAllConfig` per group; an import group's members also read their own `{ sourceId, includeDeleted: true }` snapshot from one batch and coalesce `findDuplicatePage` into one `findDuplicatePages` statement through `import-reads.ts`, and the group's preparation runs inside `withScreeningPaths`; publication's `validate`/`checkPaths` run after it, unmemoized) and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex a2c9feda4e..97d8273363 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -179,8 +179,12 @@ minute, no running gbrain process is building it (a brain with no residentwriter, or a build that died): `gbrain projections drain`, the fix's fallback,builds it now, and doctor `text_projection_readiness` names how many suchpages wait. A quarantined page says-`searchable: false`. `gbrain import` waits for the build and reports-`searchable` in its result the same way.+`searchable: false`. A managed `gbrain import` or `gbrain sync` of such a+page replies the same way, when the write commits: its result says+`searchable: "pending"` and `projection: "pending"` with the `request_id` to read+again, `searchable_retry_after_ms` and `searchable_fix`, and the build does not+hold up the source's next write. A new page up to 4 MiB still imports+searchable (`searchable: true`).Deleting and restoring a segmented page on a source backed by files works upto the page ceiling. A restore reserves room for its file twice (the stagingdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 0e71e7f8e2..3df18455bf 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1016,6 +1016,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.324.0', text: 'New `append_page` adds text to the end of a page in time proportional to the text added, idempotent by `request_id`; use it for conversation logs instead of re-putting the page. `expected_tail_sha256` (the `tail_sha256` that `get_page` with `body: \'none\'` returns) refuses `tail_changed` when another writer appended first. `gbrain append <slug> [--file f | stdin]` calls it.' },{ since: '0.60.324.0', text: 'New upload sessions (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`) let remote and thin clients write pages larger than one request, up to the page ceiling; `gbrain put --file` and `gbrain capture --file` use them on remote brains. A session is bound to the principal, source and page that began it (any other caller gets `upload_not_found`), staged bytes count against `persistence.limits` upload quotas (`write_quota_exhausted`), and an idle session expires after an hour. Locally, `gbrain put --file` and `gbrain capture --file` stream a file over 24 MiB straight in.' },{ since: '0.60.324.0', text: '`edit_page` accepts `within` to restrict a match to a range returned by a window read (`edit_target`), and edits a page stored in segments by rewriting only the segments the match touches instead of reading the whole page back.' },+ // Wave B follow-ups lane F2 (#7106: a managed import or sync of a new page over 4 MiB replies at commit). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'A managed `gbrain import` or `gbrain sync` of a new page over 4 MiB stored in segments now replies when the write commits, before its search index is built, instead of waiting for that build (which on a loaded host outlasted the 30 s import wait and replied `write_pending`). The import result and the write\'s receipt say `searchable: "pending"` and `projection: "pending"`; the import result also carries the `request_id`, `searchable_retry_after_ms` and `searchable_fix`. Read the receipt again (`gbrain write-request -- <request_id>`, `get_write_request`) at that interval until it says `searchable: true`; search finds the page from then on. The build no longer holds up the source\'s next write either. A new page up to 4 MiB, and an edit of a page stored in segments, is still searchable when its import replies (`searchable: true`). A `put_page` of a new page over 4 MiB, whose receipt already said `searchable: "pending"`, now also replies at commit instead of after the build.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 1bfa1a4f21..0b865f5147 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -149,8 +149,10 @@ export interface ImportResult {/** Which flag tier fired, when `flagged` (`instruction_like`: the #5575 write gate). */flag_reason?: 'markup_heavy' | 'oversized' | 'instruction_like';gate?: WriteGateAssessment; // #5575: the write-gate assessment, when the caller passed writeGate- /** Wave B, a segmented write imported outside the coordinator: whether search sees it on return (searchable.ts). */+ /** Wave B: whether search sees a segmented write on return (searchable.ts), outside the coordinator or through a managed import. */searchable?: boolean | 'pending';+ /** #7106: a managed import of a new segmented page over 4 MiB replies at commit; read receipt `request_id` again after `searchable_retry_after_ms` (`searchable_fix`) until `searchable` is true. */+ projection?: 'pending'; request_id?: string; searchable_retry_after_ms?: number; searchable_fix?: Record<string, unknown>;/** #5050: unchanged content below the safe-chunk fence was re-sealed; chunks left to embed. */resealed?: { pendingChunks: number; pendingChars: number };/**diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex f820d3c6d1..04360771c5 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -418,8 +418,11 @@ export class PersistenceConsumer implements PersistenceConsumerLike {*/private async publishSingle(row: WriteRequest, prepared: PreparedMutation): Promise<{ done: WriteRequest; settled: boolean }> {// A waiter learns of the commit before the recovery record is cleared (the clear still runs under the worktree lock).+ // #7106: a write whose projection is built after commit settles at commit; the build runs on, tracked until it ends+ // (stop() waits for it), and holds neither the reply nor the source's next write.let settled = false;- const hooks = { committed: (rows: WriteRequest[]) => { settled = true; this.settled(rows[0]!); } };+ const hooks = { committed: (rows: WriteRequest[]) => { settled = true; this.settled(rows[0]!); },+ projectionPending: (done: WriteRequest, afterCommit: Promise<void>) => { settled = true; this.settled(done); this.keepUntilSettled(afterCommit); } };const published = await this.onLane(transaction => publishSingleWrite(this.engine, row, prepared, this.hostId, hooks, transaction));const done = published === LANE_BUSY ? await publishSingleWrite(this.engine, row, prepared, this.hostId, hooks) : published;return { done, settled: settled && done.state === 'committed' };diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 8322ef91a2..deae62804c 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -108,6 +108,12 @@ export interface PublicationHooks {stagingFlushed?(request: WriteRequest): void;fileBoundary?(name: 'before_file' | 'staging_flushed' | 'file_replaced' | 'directory_flushed' | 'after_file'| 'before_restore' | 'restoration_staging_flushed' | 'restoration_file_replaced' | 'restoration_directory_flushed' | 'after_restore', request: WriteRequest, index: number): void;+ /**+ * #7106: a committed write whose outcome says its projection is built after commit (`searchable: 'pending'`): the+ * caller settles its waiter with `done` now and tracks `afterCommit` (that build) itself, so the reply and the+ * source's next write do not wait for it. Without this hook the publication awaits afterCommit before it returns.+ */+ projectionPending?(done: WriteRequest, afterCommit: Promise<void>): void;}/** SHA-256 of the file at `path` read in pieces (large-file.ts), null when absent. */const fileHash = hashFile;@@ -439,7 +445,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prlet recovery: RecoveryRecord | null = null;let published = false;let transactionBodyCompleted = false;- let afterCommitDue = false;+ let afterCommitDue: WriteRequest | null = null;const skill = prepared.target === 'skill_bundle';const files = skill ? prepared.files ?? [] : prepared.file ? [prepared.file] : [];const beliefReport = { appended: 0 };@@ -607,7 +613,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prif (staged.version === 1 && staged.staging?.before) await withFilesystemPublication([staged.root], async () => cleanupRecoveryStaging(staged));await clearResolvedRecovery(engine, row.id, done);}- afterCommitDue = done.state === 'committed';+ if (done.state === 'committed') afterCommitDue = done;return done;} catch (error) {if (recovery) {@@ -638,7 +644,11 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr} finally {releaseCapacity?.();await lock?.release();- if (afterCommitDue) await prepared.afterCommit?.(engine).catch(() => undefined);+ if (afterCommitDue) {+ const work = (prepared.afterCommit?.(engine) ?? Promise.resolve()).catch(() => undefined);+ if (callerHooks.projectionPending && afterCommitDue.outcome?.searchable === 'pending') callerHooks.projectionPending(afterCommitDue, work);+ else await work;+ }}}diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 0f7ca821f7..b82b061d59 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -61,7 +61,7 @@ import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guimport { isStreamedContent } from './large-file.ts';import { sharedReadFailure } from './bounded-reads.ts';import { chargedInterruption, decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, preparationAbortReason,- publicationPostimage, publishMutation, publishPersistenceFile, recoverPublication, releaseChargedInterruption, type PreparedMutation } from './coordinator.ts';+ publicationPostimage, publishMutation, publishPersistenceFile, recoverPublication, releaseChargedInterruption, type PreparedMutation, type PublicationHooks } from './coordinator.ts';import { withAttempt } from './publication-failure.ts';import { transientInterruption, type TransientInterruption } from './transient-retry.ts';import { pipelined } from '../page-state/transactions.ts';@@ -206,6 +206,8 @@ export interface GroupHooks {rolledBack?(rows: WriteRequest[]): Promise<void>;/** Right after the commit, before the recovery records are cleared: the committed rows, for waiters. */committed?(rows: WriteRequest[]): void;+ /** A single write that falls back to publishMutation: its PublicationHooks.projectionPending. */+ projectionPending?: PublicationHooks['projectionPending'];}/**@@ -446,10 +448,11 @@ function seam(name: PublicationBoundary, row: WriteRequest): Promise<void> {*/export async function publishSingleWrite(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation, hostId = localHostId(), hooks: GroupHooks = {},transaction?: TransactionRunner): Promise<WriteRequest> {+ const single: PublicationHooks = hooks.projectionPending ? { projectionPending: hooks.projectionPending } : {};if (engine.kind !== 'postgres' || !singleWrite(row) || !groupable(row, prepared) || !await writeSwitchOn(engine, 'single_write_group').catch(() => true)) {- return publishMutation(engine, row, prepared, hostId);+ return publishMutation(engine, row, prepared, hostId, single);}- try { assertMutationProtocol(row); } catch { return publishMutation(engine, row, prepared, hostId); }+ try { assertMutationProtocol(row); } catch { return publishMutation(engine, row, prepared, hostId, single); }const result = await publishGroup(engine, [row], [prepared], hostId, hooks, null, transaction);if (result.done) return result.done[0]!;let current = await getWriteRequestById(engine, row.id);@@ -459,7 +462,7 @@ export async function publishSingleWrite(engine: BrainEngine, row: WriteRequest,current = reclaimed;} else if (!current || current.execution_token !== row.execution_token) return current ?? row;if (current.state !== 'running' || current.recovery) return current;- return publishMutation(engine, current, prepared, hostId);+ return publishMutation(engine, current, prepared, hostId, single);}/** A group publication: its committed receipts, or why it did not commit and, for a member's own refusal, which member. */diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex 09ff123186..afd54b13d0 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -8,7 +8,8 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { currentVerifiedLocalWriter, localHostId } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';-import { SCREENING_SHARED_READS, batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';+import { SCREENING_SHARED_READS, batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission,+ withLiveSearchable } from './page-mutations.ts';import { admitBatch } from './page-batch.ts';import { writeOutcomeUnknown } from './admission-retry.ts';import { assertPersistenceAccepting, waitForWrites } from './service.ts';@@ -213,6 +214,9 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,const value = outcome.value;done(member.i, { slug: String(value.slug), status: value.status as ImportResult['status'], chunks: Number(value.chunks ?? 0),...(typeof value.error === 'string' ? { error: value.error } : {}),+ ...(value.searchable !== undefined ? { searchable: value.searchable as ImportResult['searchable'] } : {}),+ ...(value.searchable === 'pending' ? { projection: 'pending' as const, request_id: String(value.request_id),+ searchable_retry_after_ms: Number(value.searchable_retry_after_ms), searchable_fix: value.searchable_fix as ImportResult['searchable_fix'] } : {}),...(value.type_warning ? { type_warning: value.type_warning as ImportResult['type_warning'] } : {}) });return;}@@ -266,14 +270,15 @@ async function submitManagedImports(ctx: OperationContext, batch: string, params}rows.sort((a, b) => a.index - b.index);const done = await waitForWrites(ctx.engine, rows.map(entry => entry.row), ctx.config, IMPORT_WAIT_MS * rows.length);- rows.forEach((entry, position) => {+ await Promise.all(rows.map(async (entry, position) => {try {- const response = pendingAwareResponse(ctx, done[position]!);+ // #7106: a new segmented page over 4 MiB replies at commit with `searchable: 'pending'`, read live here.+ const response = await withLiveSearchable(ctx, pendingAwareResponse(ctx, done[position]!));if (entry.admitted) emitFenceNotice(ctx, response, done[position]!.slug);settled[entry.index] = { status: 'fulfilled', value: { ...response, ...(entry.typeWarning ? { type_warning: entry.typeWarning } : {}),...(entry.slugAdvisory ? { slug_advisory: entry.slugAdvisory } : {}) } };} catch (reason) { settled[entry.index] = { status: 'rejected', reason }; }- });+ }));return settled;}diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex 38c3c6ba1e..581e2f3da4 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -37,6 +37,8 @@ import type { PageSnapshot } from '../page-state/types.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import { bindOrigin } from './origin-guard.ts';+import { segmentedOutcome } from './searchable.ts';+import { isQuarantined } from '../quarantine.ts';export type ImportPack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };/** A Markdown file over the single-string ceiling, journaled by reference: the preparer streams and verifies it (Wave B). */@@ -293,7 +295,8 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wrimutation.postimage = final;} else if (!ready.noop && !image) await sealPageTextProjection(tx, row.slug, row.source_id);// #6188: the canonical file is written from the normalized page; the outcome reports what Tier 1 rewrote.- return { ...result, parsedPage: undefined, imported_file: true, source_id: row.source_id, fences_normalized: result.fences_normalized?.length+ return { ...result, parsedPage: undefined, imported_file: true, source_id: row.source_id,+ ...(ready.noop ? {} : segmentedOutcome(applied?.segmented, isQuarantined(ready.parsedPage?.frontmatter ?? {}))), fences_normalized: result.fences_normalized?.length? pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: result.fences_normalized, writer: row.principal_kind, path: p.sourcePath, remote: false }) : undefined };} };return mutation;@@ -351,9 +354,9 @@ async function prepareStreamedManagedImport(engine: BrainEngine, row: WriteRequevalidate: async tx => { await checkPlacement(tx); await prepared.validate(tx); },...(prepared.afterCommit ? { afterCommit: prepared.afterCommit } : {}),apply: async tx => {- await prepared.apply(tx);+ const applied = await prepared.apply(tx);mutation.postimage = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- return { ...result, imported_file: true, source_id: row.source_id };+ return { ...result, imported_file: true, source_id: row.source_id, ...segmentedOutcome(applied?.segmented, isQuarantined(prepared.frontmatter)) };} };return mutation;}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 23e85cb6dd..f07c7badc8 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -187,7 +187,7 @@ export function pendingAwareResponse(ctx: OperationContext, row: WriteRequest):* A committed reply whose outcome left the projection pending says whether search sees the page now (searchable.ts), in* the reply and its `write_request`; `projection: 'pending'` stays only while it still is.*/-async function withLiveSearchable(ctx: OperationContext, response: Record<string, unknown>): Promise<Record<string, unknown>> {+export async function withLiveSearchable(ctx: OperationContext, response: Record<string, unknown>): Promise<Record<string, unknown>> {if (response.searchable !== 'pending') return response;const live = await liveSearchable(ctx, response as Parameters<typeof liveSearchable>[1]);const settle = (fields: Record<string, unknown>) => {diff --git a/src/core/persistence/searchable.ts b/src/core/persistence/searchable.tsindex 405b6584c2..f876444c8e 100644--- a/src/core/persistence/searchable.ts+++ b/src/core/persistence/searchable.ts@@ -18,6 +18,16 @@ export function searchableRetryAfterMs(bodyBytes: number): number {return Math.min(5_000, Math.max(1_000, Math.round(bodyBytes / 4_000)));}+/**+ * #7106: the outcome fields of a managed import's or sync's segmented publication (`complete`: it sealed): `searchable`,+ * and `projection: 'pending'` while the projection is built after commit. A pending outcome is settled at commit+ * (PublicationHooks.projectionPending); its receipt turns `searchable: true` once the build seals the page.+ */+export function segmentedOutcome(segmented: { complete: boolean } | undefined, quarantined: boolean): Record<string, unknown> {+ if (!segmented) return {};+ return { searchable: quarantined ? false : segmented.complete ? true : 'pending', ...(segmented.complete ? {} : { projection: 'pending' }) };+}+/** Whether search sees a segmented page now: its text projection is sealed at its current revision. */export async function segmentedPageSearchable(engine: OperationContext['engine'], sourceId: string, slug: string): Promise<true | 'pending'> {const [page] = await engine.executeRaw<{ sealed: boolean }>(`SELECT text_projection_revision=knowledge_revision AS sealed FROM pagesdiff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex d113ad11c1..10131ccd78 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -69,6 +69,8 @@ import { fenceFixesWire } from '../fence-repair/tier1.ts';import type { FenceFix } from '../fence-repair/types.ts';import { VERSION } from '../../version.ts';import { bindOrigin } from './origin-guard.ts';+import { segmentedOutcome } from './searchable.ts';+import { isQuarantined } from '../quarantine.ts';/** The options that select a managed sync cursor (its key), recorded so a refusal can print the exact retry. */export interface SyncCursorOptions { full: boolean; workingTree: boolean; srcSubpath: string | null; exclude: string[]; includeHidden: string[]; strategy: string | null }@@ -942,6 +944,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _cconst sizeState = applied.noop ? {} : await sizeStateField(tx, row.source_id, row.slug, live?.page);return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}), ...sizeState,+ ...(applied.noop ? {} : segmentedOutcome(installed?.segmented, isQuarantined(applied.parsedPage?.frontmatter))),...(recovery?.length ? { recovered_frontmatter: true } : {}), ...(commentValue ? { comment_value: true } : {}),...(fenceFixes.length ? { fences_normalized: fenceFixesWire(fenceFixes) } : {}) };} };diff --git a/src/core/persistence/sync-streamed.ts b/src/core/persistence/sync-streamed.tsindex e559e4d12e..14402e0a5a 100644--- a/src/core/persistence/sync-streamed.ts+++ b/src/core/persistence/sync-streamed.ts@@ -37,6 +37,8 @@ import { recordSyncImportProvenance, type SyncImportProvenanceBase } from './synimport type { WriteRequest } from './model.ts';import type { SyncIntent, SyncPreparedMutation } from './sync-prepare.ts';import { bindOrigin } from './origin-guard.ts';+import { segmentedOutcome } from './searchable.ts';+import { isQuarantined } from '../quarantine.ts';/** A frozen Markdown file over the single-string ceiling: the bytes the owner streams and verifies. */export interface SyncBodyRef { kind: 'git_blob' | 'input_file'; sha256: string; bytes: number; blob_oid: string }@@ -123,7 +125,7 @@ export async function prepareManagedSyncStreamed(engine: BrainEngine, row: Write// The page moves first, keeping its id, links and history; the import prepared at the new path then applies to it.if (renamed && await tx.updateSlug(renamed.slug, row.slug, source) !== 1) throw refuse('page_identity_changed', 'The renamed page could not move to its new slug.',`Page ${renamed.slug} could not move to ${row.slug}.`);- await prepared.apply(tx);+ const applied = await prepared.apply(tx);// An unchanged body keeps its chunks (the no-op required a sealed page), so the move's new revision is sealed here.if (renamed && prepared.noop) await sealSegmentedPage(tx, renamed.pageId);await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath });@@ -138,7 +140,7 @@ export async function prepareManagedSyncStreamed(engine: BrainEngine, row: Writeconst live = final && final.page.deleted_at == null ? final.page : null;return { status: renamed ? 'renamed' : prepared.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,chunks: prepared.result.chunks, noop: prepared.noop && !renamed, imported_file: true, ...(renamed ? { renamed_from: renamed.slug } : {}),- ...(prepared.noop ? {} : await sizeStateField(tx, row.source_id, row.slug, live)) };+ ...(prepared.noop ? {} : { ...await sizeStateField(tx, row.source_id, row.slug, live), ...segmentedOutcome(applied?.segmented, isQuarantined(prepared.frontmatter)) }) };} };return mutation;}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex de6eb6e6a5..25c2f21eb7 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4615,10 +4615,14 @@"frontmatter_recovery?: { quoted: boolean; comment_value: boolean; } | undefined","gate?: WriteGateAssessment | undefined","parsedPage?: ParsedPage | undefined",+ "projection?: \"pending\" | undefined","quarantined?: boolean | undefined","refusal?: ContentRefusal | undefined",+ "request_id?: string | undefined","resealed?: { pendingChunks: number; pendingChars: number; } | undefined","searchable?: boolean | \"pending\" | undefined",+ "searchable_fix?: Record<string, unknown> | undefined",+ "searchable_retry_after_ms?: number | undefined","skip_reason?: \"purged_content\" | \"content_rejected\" | \"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_fence\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\" | \"write_gate_rejected\" | \"malformed_path\" | \"slug_collision\" | undefined","slug: string","status: \"error\" | \"imported\" | \"skipped\"",diff --git a/test/large-pages/managed-import-outside-root.test.ts b/test/large-pages/managed-import-outside-root.test.tsindex e7bb2ed8ed..1b6cc910bc 100644--- a/test/large-pages/managed-import-outside-root.test.ts+++ b/test/large-pages/managed-import-outside-root.test.ts@@ -83,6 +83,9 @@ test('a file over the ceiling from outside the root is refused with the move inexpect(e.fix?.user_message).toContain(`Move ${file} to ${target}`);expect(await engine.getPage('notes/big', { sourceId: f.sourceId })).toBeNull();renameSync(file, target);- expect(await importManagedFile(engine, target, 'notes/big.md', { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ slug: 'notes/big', status: 'imported' });+ expect(await importManagedFile(engine, target, 'notes/big.md', { sourceId: f.sourceId, noEmbed: true }))+ .toMatchObject({ slug: 'notes/big', status: 'imported', searchable: 'pending' });+ // #7106: the import replied at commit; the consumer's stop waits for the projection it left running.+ await disposePersistenceConsumer(engine);}}), 600_000);diff --git a/test/large-pages/managed-import-projection-pending.test.ts b/test/large-pages/managed-import-projection-pending.test.tsnew file mode 100644index 0000000000..739a0dbef5--- /dev/null+++ b/test/large-pages/managed-import-projection-pending.test.ts@@ -0,0 +1,154 @@+/**+ * A managed import of a new segmented page over 4 MiB replies at commit, before its projection is built (#7106).+ *+ * 1. Protects: a managed import (by reference, over the single-string ceiling, or by content, between 4 MiB and the+ * ceiling) whose publication leaves the projection to be built after commit replies `imported` with+ * `searchable: 'pending'`, `projection: 'pending'`, its `request_id` and the poll interval, while that build is+ * still held; another import on the same source commits meanwhile; the receipt read (`get_write_request`) says+ * `pending` until the page seals and `searchable: true` after. One build chunks the page. A new page up to 4 MiB+ * is still sealed when its import replies, with no post-commit build.+ * 2. Fails when: the owner settles such an import only after its projection (the reply then waits for chunking and+ * the per-row `to_tsvector` of the whole page, which on a loaded host outlasted the 30 s import wait and replied+ * `write_pending`), the source's next write queues behind the build, the reply claims searchable before the seal,+ * or the receipt never turns searchable.+ * 3. Existing coverage: managed-streamed-import.test.ts and managed-sync-streamed.test.ts assert the page seals; only+ * a loaded host made the projection outlast the reply wait.+ * 4. Seam: the existing `segmented:projection_batch` fault point (fault-points.ts), held on a promise the test+ * releases; `segmentChunkWork` counts the chunks built. Stopping the persistence consumer waits for the build it+ * tracks, so the seal check after it is deterministic.+ * Runs on PGLite, and on Postgres when DATABASE_URL is set (test/postgres-unit-arms.txt).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { SEGMENTED_CREATE_SEAL_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { segmentChunkWork } from '../../src/core/page-body/ingest.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { withEnv } from '../helpers/with-env.ts';+import { conversationPage } from '../helpers/conversation-page.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-projection-pending-'));+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const streamed = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 81 });+const midsize = conversationPage(SEGMENTED_CREATE_SEAL_MAX_BYTES + 512 * 1024, { seed: 82 });+const small = conversationPage(2 * 1024 * 1024, { seed: 83 });++afterAll(() => { rmSync(home, { recursive: true, force: true }); });++for (const kind of testBackends()) {+ describe(`a managed import of a new page over 4 MiB replies at commit (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ }, 120_000);+ afterEach(() => installFaultHook(undefined));+ afterAll(async () => {+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await close(); });+ });++ async function managedSource(): Promise<{ sourceId: string; root: string }> {+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ const sourceId = `pending-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { sourceId, root };+ }++ const importFile = async (f: { sourceId: string; root: string }, slug: string, body: string): Promise<Record<string, unknown>> => {+ writeFileSync(join(f.root, `${slug}.md`), body);+ return importManagedFile(engine, join(f.root, `${slug}.md`), `${slug}.md`, { sourceId: f.sourceId, noEmbed: true })+ .then(result => ({ ...result }), error => ({ status: 'error', code: (error as { code?: string }).code }));+ };+ const pageRow = async (sourceId: string, slug: string) => (await engine.executeRaw<{ body_storage: string; sealed: boolean; chunks: number }>(+ `SELECT body_storage, COALESCE(text_projection_revision = knowledge_revision, false) AS sealed,+ (SELECT count(*)::int FROM content_chunks c WHERE c.page_id = p.id) AS chunks FROM pages p WHERE source_id=$1 AND slug=$2`, [sourceId, slug]))[0] ?? null;+ const receipt = async (requestId: string) => {+ const registration = await registerLocalWriter(engine, 'cli');+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, 'get_write_request', { request_id: requestId },+ { remote: false, config: { engine: engine.kind }, sourceId: 'default', logger: { info() {}, warn() {}, error() {} } } as never));+ return JSON.parse((response.content[0] as { text: string }).text) as Record<string, unknown>;+ };++ for (const [label, body] of [['by reference, over the single-string ceiling', streamed], ['by content, over 4 MiB', midsize]] as const) {+ test(`${label}: replies pending while its projection is held; the source's next import commits; the receipt turns searchable at the seal`, () => withEnv(env, async () => {+ const f = await managedSource();+ const slug = 'notes/pending';+ let release!: () => void;+ const held = new Promise<void>(resolve => { release = resolve; });+ let reached!: () => void;+ const entered = new Promise<void>(resolve => { reached = resolve; });+ installFaultHook(async (point, detail) => {+ if (point !== 'segmented:projection_batch' || detail.sourceId !== f.sourceId || detail.slug !== slug) return;+ reached();+ await held;+ });+ try {+ segmentChunkWork.chunks = 0;+ const reply = await importFile(f, slug, body);+ expect(reply).toMatchObject({ slug, status: 'imported', searchable: 'pending', projection: 'pending' });+ expect(typeof reply.request_id).toBe('string');+ expect(reply.searchable_retry_after_ms).toBeGreaterThanOrEqual(1000);+ // The reply came first; the build it left runs on to its first batch, where the hook holds it.+ await entered;+ expect(await pageRow(f.sourceId, slug)).toEqual({ body_storage: 'segmented', sealed: false, chunks: 0 });+ expect(await receipt(String(reply.request_id))).toMatchObject({ state: 'committed', searchable: 'pending' });++ expect(await importFile(f, 'notes/beside', '---\ntitle: Beside\n---\nA small note written while the projection is held.\n'))+ .toMatchObject({ slug: 'notes/beside', status: 'imported' });++ release();+ await disposePersistenceConsumer(engine);+ const sealed = await pageRow(f.sourceId, slug);+ expect(sealed).toMatchObject({ body_storage: 'segmented', sealed: true });+ expect(segmentChunkWork.chunks).toBe(sealed!.chunks);+ const settled = await receipt(String(reply.request_id));+ expect(settled).toMatchObject({ state: 'committed', searchable: true });+ expect(settled.projection).toBeUndefined();+ } finally {+ release();+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine);+ }+ }), 300_000);+ }++ test('a new page up to 4 MiB is sealed when its import replies, with no post-commit build', () => withEnv(env, async () => {+ const f = await managedSource();+ let reached = false;+ installFaultHook(point => { if (point === 'segmented:projection_batch') reached = true; });+ expect(Buffer.byteLength(small)).toBeLessThanOrEqual(SEGMENTED_CREATE_SEAL_MAX_BYTES);+ const reply = await importFile(f, 'notes/small', small);+ expect(reply).toMatchObject({ slug: 'notes/small', status: 'imported', searchable: true });+ expect(reply.projection).toBeUndefined();+ expect(await pageRow(f.sourceId, 'notes/small')).toMatchObject({ body_storage: 'segmented', sealed: true });+ expect(reached).toBe(false);+ await disposePersistenceConsumer(engine);+ }), 120_000);+ });+}diff --git a/test/large-pages/managed-streamed-import.test.ts b/test/large-pages/managed-streamed-import.test.tsindex 166805298a..00005f673b 100644--- a/test/large-pages/managed-streamed-import.test.ts+++ b/test/large-pages/managed-streamed-import.test.ts@@ -4,9 +4,12 @@** 1. Protects: on a managed brain with `pages.segmented_storage` on, a file* over PAGE_MAX_BYTES inside the canonical root imports through its owner- * with an intent that holds a `body_ref` (sha256, bytes) and no content; the- * page round-trips byte-identical from its manifest, `content_hash` equals- * `contentHash`, and the canonical file is left untouched. A file within+ * with an intent that holds a `body_ref` (sha256, bytes) and no content; it+ * replies at commit with `searchable: 'pending'` (#7106: a new page over 4 MiB+ * is projected after commit) and seals once the build the owner tracks ends+ * (the consumer's stop waits for it); the page round-trips byte-identical+ * from its manifest, `content_hash` equals `contentHash`, and the canonical+ * file is left untouched. A file within* the ceiling stages its segments in the owner's preparation (the writer* guard admits it) and publishes segmented. Segment GC on a managed brain* collects an abandoned preparation's staged rows under the guard. A file that@@ -99,7 +102,8 @@ describe('managed import over the single-string ceiling', () => {writeFileSync(file, content);const before = statSync(file);const result = await importManagedFile(engine, file, 'notes/huge.md', { sourceId: f.sourceId, noEmbed: true });- expect(result).toMatchObject({ slug: 'notes/huge', status: 'imported' });+ expect(result).toMatchObject({ slug: 'notes/huge', status: 'imported', searchable: 'pending', projection: 'pending' });+ await disposePersistenceConsumer(engine);const parsed = parseMarkdown(content, 'notes/huge.md');const { page, body, hash } = await reconstructedPage(engine, 'notes/huge', f.sourceId);expect(page.body_storage).toBe('segmented');@@ -110,9 +114,10 @@ describe('managed import over the single-string ceiling', () => {const after = statSync(file);expect(after.mtimeMs).toBe(before.mtimeMs);expect(sha256(readFileSync(file))).toBe(sha256(Buffer.from(content)));- const [request] = await engine.executeRaw<{ intent_bytes: string; intent: Record<string, unknown>; state: string }>(- `SELECT intent_bytes::text AS intent_bytes, intent, state FROM persistence_requests WHERE source_id=$1 AND slug=$2`, [f.sourceId, 'notes/huge']);+ const [request] = await engine.executeRaw<{ intent_bytes: string; intent: Record<string, unknown>; state: string; outcome: Record<string, unknown> }>(+ `SELECT intent_bytes::text AS intent_bytes, intent, state, outcome FROM persistence_requests WHERE source_id=$1 AND slug=$2`, [f.sourceId, 'notes/huge']);expect(request!.state).toBe('committed');+ expect(request!.outcome).toMatchObject({ searchable: 'pending', projection: 'pending' });expect(Number(request!.intent_bytes)).toBeLessThan(16 * 1024);expect(request!.intent.content).toBeUndefined();expect(request!.intent.body_ref).toMatchObject({ kind: 'input_file', sha256: sha256(Buffer.from(content)), bytes: Buffer.byteLength(content) });diff --git a/test/large-pages/managed-sync-streamed-crash.test.ts b/test/large-pages/managed-sync-streamed-crash.test.tsindex 4f80dd7193..f6ba60cd02 100644--- a/test/large-pages/managed-sync-streamed-crash.test.ts+++ b/test/large-pages/managed-sync-streamed-crash.test.ts@@ -7,7 +7,9 @@* running with a reference-only intent and its staging prepared; once the* dead claim lapses, the next run's owner prepares the request again from* its `body_ref` (re-streaming and re-verifying the file) and publishes the- * page byte-identical, and segment GC collects the dead staging.+ * page byte-identical (its receipt says `searchable: 'pending'`, #7106; it+ * seals once the build the owner tracks ends, which the consumer's stop+ * waits for), and segment GC collects the dead staging.* 2. Fails when: the journal needs the body to re-prepare, the dead staging* blocks the re-preparation, or GC keeps it.* Seams: test/fixtures/convergence-fault-kill.ts preloaded into the child (the@@ -93,6 +95,10 @@ test('an owner killed between preparation and publication: the next run re-prepalet result = await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true });for (let pass = 0; result.status === 'partial' && pass < 30; pass++) result = await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true });expect(result.status).toBe('first_sync');+ const [receipt] = await engine.executeRaw<{ outcome: Record<string, unknown> }>(+ "SELECT outcome FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [sourceId]);+ expect(receipt!.outcome).toMatchObject({ status: 'created', searchable: 'pending', projection: 'pending' });+ await disposePersistenceConsumer(engine);const { page, body, hash } = await reconstructedPage(engine, 'notes/huge', sourceId);expect(page.body_storage).toBe('segmented');expect(body.compiled_truth).toBe(parseMarkdown(huge, 'notes/huge.md').compiled_truth);diff --git a/test/large-pages/managed-sync-streamed.test.ts b/test/large-pages/managed-sync-streamed.test.tsindex 191e2c3a6f..43a1503e80 100644--- a/test/large-pages/managed-sync-streamed.test.ts+++ b/test/large-pages/managed-sync-streamed.test.ts@@ -6,7 +6,11 @@* sha256, size and pinned blob; no content in the journal) and its owner* streams it into a segmented page that round-trips byte-identical, with* the canonical file untouched; on a source at a repository subdirectory- * (git-root slugs), on an edit, on a full walk and on a rename. A file the+ * (git-root slugs), on an edit, on a full walk and on a rename. A new page+ * commits with `searchable: 'pending'` on its receipt (#7106: a new page over+ * 4 MiB is projected after commit) and seals once the build the owner tracks+ * ends (the consumer's stop waits for it); an edit or a rename with an edit+ * is sealed when it commits. A file the* streamed path refuses (a facts fence) is held `file_too_large` and the* run checkpoints, as before. A dry run lists the file as screened only by* its owner (`page_body_segmented`), not as a hold. With the switch off the@@ -82,13 +86,18 @@ async function sync(engine: BrainEngine, opts: { sourceId: string; full?: boolea}async function syncRequest(engine: BrainEngine, sourceId: string, slug: string) {- const [row] = await engine.executeRaw<{ intent_bytes: string; intent: Record<string, unknown>; state: string }>(- `SELECT intent_bytes::text AS intent_bytes, intent, state FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_sync_import'+ const [row] = await engine.executeRaw<{ intent_bytes: string; intent: Record<string, unknown>; state: string; outcome: Record<string, unknown> | null }>(+ `SELECT intent_bytes::text AS intent_bytes, intent, state, outcome FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_sync_import'ORDER BY sequence DESC LIMIT 1`, [sourceId, slug]);return row;}-async function expectStreamed(engine: BrainEngine, sourceId: string, slug: string, content: string, path: string) {+/** `created`: a new page, whose receipt says its projection is pending at commit; the consumer's stop waits for that build. */+async function expectStreamed(engine: BrainEngine, sourceId: string, slug: string, content: string, path: string, created = false) {+ if (created) {+ expect((await syncRequest(engine, sourceId, slug))!.outcome).toMatchObject({ status: 'created', searchable: 'pending', projection: 'pending' });+ await disposePersistenceConsumer(engine);+ }const parsed = parseMarkdown(content, path);const { page, body, hash } = await reconstructedPage(engine, slug, sourceId);expect(page.body_storage).toBe('segmented');@@ -116,7 +125,7 @@ describe('managed sync over the single-string ceiling', () => {expect(preview.would_hold).toBeUndefined();expect(preview.screen_skipped).toEqual([{ path: 'notes/huge.md', code: 'page_body_segmented' }]);expect(await sync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'first_sync', filesImported: 2 });- await expectStreamed(engine, f.sourceId, 'notes/huge', huge, 'notes/huge.md');+ await expectStreamed(engine, f.sourceId, 'notes/huge', huge, 'notes/huge.md', true);expect(statSync(file).mtimeMs).toBe(before.mtimeMs);expect(sha256(readFileSync(file))).toBe(sha256(Buffer.from(huge)));expect((await readGitSourceHolds(engine, { sourceIds: [f.sourceId] }))[0]?.holds ?? []).toEqual([]);@@ -156,7 +165,7 @@ describe('managed sync over the single-string ceiling', () => {await engine.setConfig('pages.segmented_storage', 'on');const f = await fixture(engine, { 'notes/huge.md': huge }, 'brain');expect(await sync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'first_sync', filesImported: 1 });- const page = await expectStreamed(engine, f.sourceId, 'brain/notes/huge', huge, 'brain/notes/huge.md');+ const page = await expectStreamed(engine, f.sourceId, 'brain/notes/huge', huge, 'brain/notes/huge.md', true);expect((await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE id=$1', [page.id]))[0]!.source_path).toBe('brain/notes/huge.md');await disposePersistenceConsumer(engine);}@@ -168,7 +177,7 @@ describe('managed sync over the single-string ceiling', () => {const f = await fixture(engine, { 'notes/small.md': '---\ntitle: Small\n---\nA small note.\n' });writeFileSync(join(f.root, 'notes/huge.md'), huge);expect((await sync(engine, { sourceId: f.sourceId, workingTree: true })).status).not.toBe('failed');- await expectStreamed(engine, f.sourceId, 'notes/huge', huge, 'notes/huge.md');+ await expectStreamed(engine, f.sourceId, 'notes/huge', huge, 'notes/huge.md', true);expect((await syncRequest(engine, f.sourceId, 'notes/huge'))!.intent.body_ref).toMatchObject({ kind: 'input_file' });await disposePersistenceConsumer(engine);}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 15d79af331..d27f79442d 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -102,6 +102,7 @@ test/large-pages/gbra117-segmented-classes-window.test.tstest/large-pages/held-budget-count-list.test.tstest/large-pages/held-budget-shrink.test.tstest/large-pages/managed-import-outside-root.test.ts+test/large-pages/managed-import-projection-pending.test.tstest/large-pages/managed-links-timeline-heap.test.tstest/large-pages/managed-streamed-import.test.tstest/large-pages/managed-sync-segmented-rename.test.ts