Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): foreground page writes go ahead of queued sync groups (#5984 Phase 4.5)

garrytan1c08c5c2e994
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 50be98bdd5..a675870561 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -44,4 +44,6 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/persistence/automatic-sync-policy.ts` — `automaticSyncPull(engine, source)`: whether an automatic sync (autopilot freshness `sync` job, per-source fanout cycle) may request a Git pull. It needs a parsed `remote_url`, exactly one boolean `persistence_brain` state that is off, and no worktree binding; a managed brain or claimed source syncs local HEAD with `pull: false`. Missing, duplicated or non-boolean persistence metadata throws `storage_error` (why, read-only `gbrain sources writer status --probe --json` fix) instead of granting a pull, so the caller queues nothing. Clone, immutable and federation flags grant nothing. Pinned by `test/automatic-sync-pull-policy.test.ts`.
- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.4.0 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`. `native/locks/package.json` (private, no entry points, outside `buildInputs` and `prebuilds/`) is a package boundary so plugin hosts that namespace native addons by the nearest package.json do not treat the whole checkout as one package (#6026; guard `test/native-locks-package-boundary.test.ts`).
-- `src/core/persistence/switches.ts` + `preadmit-cache.ts` + `config-snapshot.ts` — the single-write fast path for foreground page writes on Postgres. `switches.ts` reads every write-path kill switch (`persistence.single_write_group` / `GBRAIN_SINGLE_WRITE_GROUP`, `persistence.preadmit_cache` / `GBRAIN_PREADMIT_CACHE`, `sync.waive_batch` / `GBRAIN_SYNC_WAIVE_BATCH`; on by default, `0`/`false` off, env over config) in one `SELECT key,value FROM config WHERE key = ANY(...)` per engine, kept 5 s (the consumer tick reads it under its phase deadline); read-through views register their engine (`registerEngineView`) to share it. With `single_write_group` on: the consumer publishes an eligible single page write (put_page, capture, edit/delete/restore/revert without an internal `intent.kind` or group key) as a group of one through `publishGroup` (`publishSingleWrite`; its intent carries no group marker, its effects queue without `deferBatchReconcile`, and a group that does not commit falls back to `publishMutation`, reclaiming a claim its file restoration released); PGLite and refused shapes keep `publishMutation`. The waiter's own wake (`wake(true)`) claims without the periodic scans (recovery records still block the claim through `CLAIMABLE_WRITE_SQL`); preparation reads the config table once (`config-snapshot.ts`) and sends its independent reads together; the coordinated (`coordinated: true`) put_page apply reuses the publisher's locked read as the import base, pipelines its follow-up statements and reads the page once after its last write for the read-back check, seal, core notice and receipt. Publication, the own admission and the recovery transactions run on the consumer's reserved lane (`onLane`: the idle-probe connection, taken while two other pool connections stay free and kept across writes; never lent while an idle probe runs on it, and probes skip it while lent), so their prepared statements stay warm; the waiter is told of the commit before the recovery record is cleared. `preadmit-cache.ts` (with `preadmit_cache` on, Postgres) answers the brain id, source row, worktree binding and local-writer reads of `submitPageMutation` from a per-engine cache (30 s, keyed by brain id; absences never cached); admission rechecks each under lock and the brain id against its protocol statement, and a refusal the cache could explain (`source_changed`, `permission_denied`, a changed brain) drops the cache and runs the whole preparation once more uncached. Pinned by `test/e2e/single-write-fast-path-postgres.test.ts` (switches, cache rechecks, replay, restoration after a failure past the file rename, the recovery-blocked direct claim) and `test/single-write-group-parity.test.ts` + `test/e2e/single-write-group-parity-postgres.test.ts` (row-for-row parity with the switches off); measured by `scripts/bench/foreground-put-page.ts`.
+- `src/core/persistence/switches.ts` + `preadmit-cache.ts` + `config-snapshot.ts` — the single-write fast path for foreground page writes on Postgres. `switches.ts` reads every write-path kill switch (`persistence.single_write_group` / `GBRAIN_SINGLE_WRITE_GROUP`, `persistence.preadmit_cache` / `GBRAIN_PREADMIT_CACHE`, `sync.waive_batch` / `GBRAIN_SYNC_WAIVE_BATCH`, `sync.foreground_priority` / `GBRAIN_SYNC_FOREGROUND_PRIORITY`; on by default, `0`/`false` off, env over config) in one `SELECT key,value FROM config WHERE key = ANY(...)` per engine, kept 5 s (the consumer tick reads it under its phase deadline); read-through views register their engine (`registerEngineView`) to share it. With `single_write_group` on: the consumer publishes an eligible single page write (put_page, capture, edit/delete/restore/revert without an internal `intent.kind` or group key) as a group of one through `publishGroup` (`publishSingleWrite`; its intent carries no group marker, its effects queue without `deferBatchReconcile`, and a group that does not commit falls back to `publishMutation`, reclaiming a claim its file restoration released); PGLite and refused shapes keep `publishMutation`. The waiter's own wake (`wake(true)`) claims without the periodic scans (recovery records still block the claim through `claimableWriteSql`); preparation reads the config table once (`config-snapshot.ts`) and sends its independent reads together; the coordinated (`coordinated: true`) put_page apply reuses the publisher's locked read as the import base, pipelines its follow-up statements and reads the page once after its last write for the read-back check, seal, core notice and receipt. Publication, the own admission and the recovery transactions run on the consumer's reserved lane (`onLane`: the idle-probe connection, taken while two other pool connections stay free and kept across writes; never lent while an idle probe runs on it, and probes skip it while lent), so their prepared statements stay warm; the waiter is told of the commit before the recovery record is cleared. `preadmit-cache.ts` (with `preadmit_cache` on, Postgres) answers the brain id, source row, worktree binding and local-writer reads of `submitPageMutation` from a per-engine cache (30 s, keyed by brain id; absences never cached); admission rechecks each under lock and the brain id against its protocol statement, and a refusal the cache could explain (`source_changed`, `permission_denied`, a changed brain) drops the cache and runs the whole preparation once more uncached. Pinned by `test/e2e/single-write-fast-path-postgres.test.ts` (switches, cache rechecks, replay, restoration after a failure past the file rename, the recovery-blocked direct claim) and `test/single-write-group-parity.test.ts` + `test/e2e/single-write-group-parity-postgres.test.ts` (row-for-row parity with the switches off); measured by `scripts/bench/foreground-put-page.ts`.
+
+- Foreground priority (#5984 Phase 4.5, `foreground_priority` switch, `journal.ts`): `claimableWriteSql` lets a non-sync request pass earlier queued sync rows of its root that have not started and do not name its page (slug, page id or `intent.renameFrom.slug`), claims it first, and holds a passed sync row while that request runs; `claimNextLaneHead` starts no lane head while such a request is unfinished, except one head per foreground commit since the run's last head claim (`seen_sequence`). A consumer whose claimed write passed sync rows (`passed_sync`) claims plain FIFO on that root after it commits (`owesSyncTurn`), so a stream of writes cannot starve the drain. The sync side's pauses (no admit-ahead for 60 s after a write, no group while one is queued, the 25-page credit wait) apply only with the switch off. Receipt health judges a claimed write only against earlier started writes. Pinned by `test/managed-sync-foreground-priority.test.ts` (two processes) and `test/persistence-diagnostics.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 1d4c6376bf..27c485e2e0 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -29,7 +29,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
-- `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 mirroring the claim, recovery, expired-claim, effect, projection 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. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. 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 `CLAIMABLE_WRITE_SQL` 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 (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms 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). 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, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`. See [persistence stalls](persistence-stalls.md).
+- `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 mirroring the claim, recovery, expired-claim, effect, projection 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. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. 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 (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms 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). 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, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`. See [persistence stalls](persistence-stalls.md).
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 4f6cf2ce96..cdd39ea9ce 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -48,10 +48,9 @@ Up to 16 groups publish at once in **lanes**, each on its own connection
(`--lanes N`, `--no-lanes`, `sync.lanes` or `GBRAIN_SYNC_LANES`), capped by the
pool: the default pool of 10 runs 6, `GBRAIN_POOL_SIZE=20` runs 16. Lanes apply pages at the same time but commit in file order, so a reader never
sees a later page without the earlier ones. While lanes publish, the drain keeps
-freezing and admitting the next groups. Nothing is admitted ahead while
-foreground writes are recent (one was queued in the last minute), and a
-foreground write that needs the worktree makes the lanes finish their current
-groups and step aside. Groups after a failed page are cancelled ("An earlier
+freezing and admitting the next groups. A page write goes ahead of
+queued groups that do not name its page (lanes finish their groups, then one
+group runs between writes); `sync.foreground_priority false` restores FIFO. Groups after a failed page are cancelled ("An earlier
page of the same sync did not commit") and re-frozen once it is fixed. A lock or statement timeout in a lane costs one lane for
the rest of the run.
diff --git a/llms-full.txt b/llms-full.txt
index 5949df7490..7e6d65fbe9 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6293,10 +6293,9 @@ Up to 16 groups publish at once in **lanes**, each on its own connection
(`--lanes N`, `--no-lanes`, `sync.lanes` or `GBRAIN_SYNC_LANES`), capped by the
pool: the default pool of 10 runs 6, `GBRAIN_POOL_SIZE=20` runs 16. Lanes apply pages at the same time but commit in file order, so a reader never
sees a later page without the earlier ones. While lanes publish, the drain keeps
-freezing and admitting the next groups. Nothing is admitted ahead while
-foreground writes are recent (one was queued in the last minute), and a
-foreground write that needs the worktree makes the lanes finish their current
-groups and step aside. Groups after a failed page are cancelled ("An earlier
+freezing and admitting the next groups. A page write goes ahead of
+queued groups that do not name its page (lanes finish their groups, then one
+group runs between writes); `sync.foreground_priority false` restores FIFO. Groups after a failed page are cancelled ("An earlier
page of the same sync did not commit") and re-frozen once it is fixed. A lock or statement timeout in a lane costs one lane for
the rest of the run.
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index d2ac99726c..b23c6660bb 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,6 +1,6 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
+import { claimableWriteSql, foregroundPriority, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
import { finishUnpublishedFailure, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
@@ -96,6 +96,12 @@ export class PersistenceConsumer {
/** #5984 lanes: running lane tasks per worktree. */
private laneTasks = new Map<string, number>();
private foregroundCounts = new Map<string, number>();
+ /** #5984 Phase 4.5: the newest sequence when this process last claimed a head of each lane run (one head per foreground commit). */
+ private laneHeadSeen = new Map<string, string>();
+ /** #5984 Phase 4.5: roots where a foreground write this consumer claimed ahead of queued sync rows committed since it last claimed a sync row there. */
+ private owesSyncTurn = new Set<string>();
+ /** Requests this consumer claimed ahead of a queued sync row of their root. */
+ private passedSync = new Set<string>();
private rootRetryAfter = new Map<string, number>();
private projectionWorker: Promise<unknown> | undefined;
private effectsWorker: Promise<void> | undefined;
@@ -149,7 +155,7 @@ export class PersistenceConsumer {
* to at most one pass per poll interval. `ownAdmission` (the waiter of a
* write this process just admitted) makes that tick skip the scans and
* claim directly; the scans keep their own cadence, and recovery records
- * still block the claim (CLAIMABLE_WRITE_SQL).
+ * still block the claim (claimableWriteSql).
*/
wake(ownAdmission = false): void {
if (ownAdmission) this.ownAdmission = true;
@@ -190,7 +196,7 @@ export class PersistenceConsumer {
const retryingTopologies = [...this.topologyRetryAfter.keys()];
const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(this.laneInUse ? undefined : await this.acquireIdleLane(signal), `SELECT (
EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
- WHERE ${CLAIMABLE_WRITE_SQL}
+ WHERE ${claimableWriteSql('$5')}
AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))
OR EXISTS (SELECT 1 FROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT (r.worktree_id::text=ANY($2::text[])))
@@ -213,7 +219,7 @@ export class PersistenceConsumer {
OR EXISTS (SELECT 1 FROM persistence_topology_changes c
JOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuid
WHERE c.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND NOT (c.id::text=ANY($4::text[])))
- ) AS work`, [this.hostId, excluded, publicationConcurrency(this.engine) > 0, retryingTopologies], signal));
+ ) AS work`, [this.hostId, excluded, publicationConcurrency(this.engine) > 0, retryingTopologies, await foregroundPriority(this.engine)], signal));
return row?.work === true;
}
/**
@@ -445,8 +451,10 @@ export class PersistenceConsumer {
while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {
const claimed = laneClaim();
try {
- const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, this.opts.claimLeaseMs ?? 30_000, [...attemptedRoots]));
+ const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, this.opts.claimLeaseMs ?? 30_000, [...attemptedRoots], [...this.owesSyncTurn]));
if (!row) break;
+ if (String(row.intent?.kind ?? '').startsWith('managed_sync_')) this.owesSyncTurn.delete(row.worktree_id ?? `db:${row.source_incarnation}`);
+ else if (row.passed_sync) this.passedSync.add(row.id);
if (this.stopping) { await releaseUnpublishedClaim(this.engine, row, 'consumer_stopping'); break; }
const key = row.worktree_id ?? `db:${row.source_incarnation}`;
attemptedRoots.add(key);
@@ -466,8 +474,10 @@ export class PersistenceConsumer {
while (!this.stopping && (this.laneTasks.get(worktreeId) ?? 0) < capacity) {
const claimed = laneClaim();
try {
- const row = await this.phase('claim', () => claimNextLaneHead(this.engine, this.hostId, worktreeId, run));
+ const row = await this.phase('claim', () => claimNextLaneHead(this.engine, this.hostId, worktreeId, run, undefined, this.laneHeadSeen.get(run) ?? null));
if (!row) break;
+ this.laneHeadSeen.set(run, row.seen_sequence);
+ this.owesSyncTurn.delete(worktreeId);
this.startLaneTask(row, worktreeId);
} finally { claimed(); }
}
@@ -504,6 +514,9 @@ export class PersistenceConsumer {
/** CEO-A7: this process holds the claim, so its outcome reaches waiters through `onSettled` without a read. */
holds(id: string): boolean { return this.executing.has(id); }
private settled(row: WriteRequest): boolean {
+ // #5984 Phase 4.5: after a foreground write that went ahead of queued sync rows commits, this consumer's next
+ // claim on its root is plain FIFO, so a stream of writes cannot starve the sync side.
+ if (isTerminal(row) && this.passedSync.delete(row.id) && row.state === 'committed') this.owesSyncTurn.add(row.worktree_id ?? `db:${row.source_incarnation}`);
try { this.opts.onSettled?.(row); } catch (error) { this.report(error); }
return isTerminal(row);
}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index f5729da855..13d2a2ec3f 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -1,4 +1,5 @@
import { randomUUID } from 'node:crypto';
+import { writeSwitchOn } from './switches.ts';
import type { BrainEngine } from '../engine.ts';
import { assertRecoveryStagingAbsent } from './staging.ts';
import { OperationError, opError } from '../ops/contract.ts';
@@ -404,7 +405,24 @@ async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmissio
* unfinished withdrawal mirror of its page (of every page, for an untargeted
* mirror), so the mirror never rewrites a file under an accepted request.
*/
-export const CLAIMABLE_WRITE_SQL = `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
+const SYNC_KIND = (row: string) => `COALESCE(${row}.intent->>'kind','') LIKE 'managed_sync_%'`;
+/** Whether sync row `sync` names the page of request `write`: its slug, page id or rename source. */
+const NAMES_PAGE = (sync: string, write: string) => `(${sync}.source_id=${write}.source_id AND (${sync}.slug=${write}.slug
+ OR ${sync}.page_id=${write}.page_id OR ${sync}.intent->'renameFrom'->>'slug'=${write}.slug))`;
+/**
+ * #5984 Phase 4.5 (with `priority`, the `foreground_priority` switch): a foreground request passes an earlier
+ * sync row that has not started and does not name its page. Running and recovering rows, recovery records and
+ * a sync row naming the page still come first; a passed sync row waits until the foreground request finishes.
+ */
+const PASSES_QUEUED_SYNC = (earlier: string, r: string, priority: string) => `(${priority}::boolean AND NOT ${SYNC_KIND(r)}
+ AND ${earlier}.state='queued' AND ${earlier}.recovery IS NULL AND ${SYNC_KIND(earlier)} AND NOT ${NAMES_PAGE(earlier, r)})`;
+/**
+ * The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN
+ * persistence_worktrees w`, with $1 = host id and $2 = excluded root keys and
+ * `priority` the parameter carrying the `foreground_priority` switch. An
+ * unresolved head blocks its entire root.
+ */
+export const claimableWriteSql = (priority: string) => `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
AND (r.worktree_id IS NULL OR ${refreshFenceClear('r')})
AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))
AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
@@ -415,31 +433,49 @@ export const CLAIMABLE_WRITE_SQL = `r.state='queued' AND (r.worktree_id IS NULL
AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier
WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)
=COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)
- AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))`;
+ AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering')
+ AND NOT ${PASSES_QUEUED_SYNC('earlier', 'r', priority)})
+ AND NOT (${priority}::boolean AND ${SYNC_KIND('r')} AND EXISTS (SELECT 1 FROM persistence_requests ahead
+ WHERE ahead.worktree_id=r.worktree_id AND ahead.sequence>r.sequence AND ahead.state IN ('running','recovering') AND NOT ${SYNC_KIND('ahead')}))`;
+/** With the switch on, a claimable foreground request is claimed before the sync rows it passes. */
+const CLAIM_ORDER = (priority: string) => `(${priority}::boolean AND NOT ${SYNC_KIND('r')}) DESC, r.sequence`;
+/** Whether `foreground_priority` is on for this brain; on when the switch cannot be read. */
+export function foregroundPriority(engine: SqlEngine): Promise<boolean> {
+ return writeSwitchOn(engine, 'foreground_priority').catch(() => true);
+}
/** #5401: whether `claimNextWrite` would find a row now. Read-only: no lock and no claim. */
export async function hasClaimableWrite(engine: SqlEngine, hostId: string, excludeRoots: string[] = [], signal?: AbortSignal): Promise<boolean> {
const [row] = await engine.executeRaw<{ claimable: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests r
- LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${CLAIMABLE_WRITE_SQL} LIMIT 1) AS claimable`, [hostId, excludeRoots], { signal });
+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${claimableWriteSql('$3')} LIMIT 1) AS claimable`, [hostId, excludeRoots, await foregroundPriority(engine)], { signal });
return row?.claimable === true;
}
/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */
-export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = []): Promise<WriteRequest | null> {
+/**
+ * `fifoRoots` (#5984 Phase 4.5) are roots where this consumer owes the sync side a turn: a foreground write it
+ * claimed ahead of a queued sync row (`passed_sync`) committed since it last claimed a sync row, so there the claim is plain FIFO.
+ */
+export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = [], fifoRoots: string[] = []): Promise<(WriteRequest & { passed_sync?: boolean }) | null> {
+ const priority = await foregroundPriority(engine);
+ const first = `($3::boolean AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($4::text[])))`;
return engine.transactionDirect(async tx => {
// The protocol declaration and the FIFO head read are sent together.
const [, [row]] = await pipelined(tx, [
() => declarePersistenceProtocol(tx),
- () => tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ // `passed_sync`: the claimed row went ahead of a queued sync row of its root.
+ () => tx.executeRaw<WriteRequest & { passed_sync: boolean }>(`SELECT r.*,EXISTS (SELECT 1 FROM persistence_requests earlier
+ WHERE earlier.worktree_id=r.worktree_id AND earlier.sequence<r.sequence AND earlier.state='queued' AND ${SYNC_KIND('earlier')}) AS passed_sync
+ FROM persistence_requests r
LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
- WHERE ${CLAIMABLE_WRITE_SQL}
- ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots]),
- ]) as [unknown, WriteRequest[]];
+ WHERE ${claimableWriteSql(first)}
+ ORDER BY ${CLAIM_ORDER(first)} LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots, priority, fifoRoots]),
+ ]) as [unknown, Array<WriteRequest & { passed_sync: boolean }>];
if (!row) return null;
const [claimed] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',
execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),
updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *`, [row.id, randomUUID(), leaseMs]);
- return claimed;
+ return claimed && { ...claimed, passed_sync: row.passed_sync === true };
});
}
/**
@@ -452,7 +488,13 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM
* as under the FIFO claim. Followers are claimed with their head by
* `claimGroupFollowers`.
*/
-export async function claimNextLaneHead(engine: BrainEngine, hostId: string, worktreeId: string, run: string, leaseMs = 30_000): Promise<WriteRequest | null> {
+/**
+ * `seenSequence` is the newest request sequence when this process last claimed a head of the run (#5984
+ * Phase 4.5): a foreground write admitted and committed since then earns the drain one head while others wait.
+ */
+export async function claimNextLaneHead(engine: BrainEngine, hostId: string, worktreeId: string, run: string, leaseMs = 30_000,
+ seenSequence: string | null = null): Promise<(WriteRequest & { seen_sequence: string }) | null> {
+ const priority = await foregroundPriority(engine);
return engine.transactionDirect(async tx => {
await declarePersistenceProtocol(tx);
const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
@@ -465,11 +507,19 @@ export async function claimNextLaneHead(engine: BrainEngine, hostId: string, wor
AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier WHERE earlier.worktree_id=r.worktree_id AND earlier.sequence<r.sequence
AND (earlier.state IN ('queued','recovering') OR (earlier.state='running' AND COALESCE(earlier.intent->>'lane','')<>$3)))
- ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, worktreeId, run]);
+ -- #5984 Phase 4.5: no new lane head while a foreground write that may go first is unfinished, except one head
+ -- after each foreground commit since this run's last head claim, so a stream of writes cannot starve the drain.
+ AND NOT ($4::boolean AND EXISTS (SELECT 1 FROM persistence_requests f WHERE f.worktree_id=r.worktree_id AND f.state IN ('queued','running','recovering')
+ AND f.recovery IS NULL AND NOT ${SYNC_KIND('f')}
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests named WHERE named.worktree_id=f.worktree_id AND named.sequence<f.sequence
+ AND named.state IN ('queued','running','recovering') AND ${SYNC_KIND('named')} AND ${NAMES_PAGE('named', 'f')}))
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE c.sequence>COALESCE($5::bigint,0) AND c.worktree_id=r.worktree_id
+ AND c.state='committed' AND NOT ${SYNC_KIND('c')}))
+ ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, worktreeId, run, priority, seenSequence]);
if (!row) return null;
- const [claimed] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',
+ const [claimed] = await tx.executeRaw<WriteRequest & { seen_sequence: string }>(`UPDATE persistence_requests SET state='running',
execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),
- updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *`, [row.id, randomUUID(), leaseMs]);
+ updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *,(SELECT max(sequence) FROM persistence_requests)::text AS seen_sequence`, [row.id, randomUUID(), leaseMs]);
return claimed;
});
}
diff --git a/src/core/persistence/switches.ts b/src/core/persistence/switches.ts
index 9c485821fc..837bdc8b97 100644
--- a/src/core/persistence/switches.ts
+++ b/src/core/persistence/switches.ts
@@ -17,6 +17,8 @@ export const WRITE_SWITCHES = {
preadmit_cache: { key: 'persistence.preadmit_cache', env: 'GBRAIN_PREADMIT_CACHE' },
/** Batched waiver runs; `GBRAIN_SYNC_WAIVE_NOOP=0` wins over it. */
waive_batch: { key: 'sync.waive_batch', env: 'GBRAIN_SYNC_WAIVE_BATCH' },
+ /** Phase 4.5: a foreground write goes ahead of queued sync groups that do not name its page; off restores the FIFO and the sync side's pauses. */
+ foreground_priority: { key: 'sync.foreground_priority', env: 'GBRAIN_SYNC_FOREGROUND_PRIORITY' },
} as const;
export type WriteSwitch = keyof typeof WRITE_SWITCHES;
export type WriteSwitches = Record<WriteSwitch, boolean>;
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 65e913abb1..074a8ec365 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -8,7 +8,7 @@ import type { RegistryCode } from '../error-registry.ts';
import { currentSourceFilesystemSignal } from '../minions/source-filesystem.ts';
import { throwIfAborted } from '../abort-check.ts';
import { digest, sha256 } from './digest.ts';
-import { getWriteRequest, admitWriteInTransaction, intentDigest, receiptFor } from './journal.ts';
+import { getWriteRequest, admitWriteInTransaction, foregroundPriority, intentDigest, receiptFor } from './journal.ts';
import { retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';
@@ -552,7 +552,9 @@ interface BulkPass { settings: BulkSettings; perMemberMs: number | null;
/** Groups this pass formed, and the heads of window groups it admitted (saved and admitted in one transaction). */
formed?: number; admitted?: Set<string>;
/** #5984 admit-ahead: when this pass last saw a foreground write queued on the worktree. */
- foregroundAt?: number }
+ foregroundAt?: number;
+ /** #5984 Phase 4.5 (`foreground_priority`): foreground writes go first at claim time, so the sync side does not pause for them. */
+ foregroundFirst?: boolean }
/** While foreground writes are recent, nothing is admitted ahead, so a new foreground write waits behind at most the publishing group. */
const FOREGROUND_RECENT_MS = 60_000;
/** A foreground write queued or committed this recently sizes new lane groups to the foreground budget. */
@@ -704,7 +706,7 @@ async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk
AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [current.binding.worktree_id]);
if (foreground) bulk.foregroundAt = performance.now();
}
- if (bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_RECENT_MS) break;
+ if (!bulk.foregroundFirst && bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_RECENT_MS) break;
// The window's free slots are frozen and then admitted and saved in one transaction, up to a lane count of
// groups at a time, so lanes start on the first ones while the rest are frozen.
const formed: Pending[][] = [];
@@ -1037,7 +1039,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;
let creditedPages = 0, creditStarted = 0, foregroundQueued = false;
const sliceStarted = performance.now(), sliceFirstIndex = cursor.index, drainStartedAt = opts.drainStartedAt ?? Date.now();
- const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null };
+ const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };
const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(engine);
opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });
while (!cursor.done) {
@@ -1050,7 +1052,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [cursor.binding.worktree_id]);
assertActive();
if ((foregroundQueued = Boolean(foreground))) bulk.foregroundAt = performance.now();
- if (foreground && creditedPages === 0) {
+ if (foreground && creditedPages === 0 && !bulk.foregroundFirst) {
startPersistenceConsumer(engine, config);
if (!foregroundWaitStart) {
foregroundWaitStart = performance.now();
@@ -1097,7 +1099,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
continue;
}
const freezeAt: FreezeAt = base => async index => { const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'hold' in frozen ? null : frozen; };
- if (bulk.settings.enabled && !foregroundQueued && !prior && !cursor.group && !pending.rebound && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);
+ if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);
if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {
const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000 }, drainStartedAt, opts.onProgress,
opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);
diff --git a/test/fixtures/foreground-put-page-worker.ts b/test/fixtures/foreground-put-page-worker.ts
new file mode 100644
index 0000000000..7341e41d2e
--- /dev/null
+++ b/test/fixtures/foreground-put-page-worker.ts
@@ -0,0 +1,38 @@
+/**
+ * Child process for test/managed-sync-foreground-priority.test.ts: the agent's
+ * page writes from a second process while another process drains a managed sync.
+ * Env: WORKER_DATABASE_URL, WORKER_SOURCE, WORKER_SLUGS (comma-separated, one
+ * put_page each, in order; with WORKER_GO, the go file's content instead), WORKER_INTERVAL_MS (gap between writes; 0 = back to
+ * back), WORKER_OUT (JSON results), WORKER_GO (optional: a file whose creation starts the writes, so a
+ * test can start the process ahead and write at a chosen moment). GBRAIN_HOME is the drain's, so both processes
+ * are the same local writer on the same owner host.
+ */
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+
+const engine = new PostgresEngine();
+await engine.connect({ database_url: process.env.WORKER_DATABASE_URL!, poolSize: 4 });
+const sourceId = process.env.WORKER_SOURCE!;
+const interval = Number(process.env.WORKER_INTERVAL_MS ?? '0');
+const results: Array<{ slug: string; state: string; error?: string; submitted: number; returned: number }> = [];
+const logger = { info() {}, warn() {}, error() {} };
+const go = process.env.WORKER_GO;
+if (go) while (!existsSync(go) || !readFileSync(go, 'utf8')) await Bun.sleep(5);
+const slugs = (go ? readFileSync(go, 'utf8') : process.env.WORKER_SLUGS!).split(',');
+for (const slug of slugs) {
+ const submitted = Date.now();
+ try {
+ const out = await submitPageMutation({ engine, config: { engine: 'postgres', database_url: process.env.WORKER_DATABASE_URL! }, remote: false, dryRun: false, sourceId, logger } as never,
+ { operation: 'put_page', params: { slug, content: `---\ntitle: ${slug}\n---\nA foreground note written during the catch-up.\n` }, waitMs: 60_000 });
+ results.push({ slug, state: String((out as { state?: string }).state ?? ''), submitted, returned: Date.now() });
+ } catch (error) {
+ results.push({ slug, state: 'error', error: (error as Error).message, submitted, returned: Date.now() });
+ }
+ if (interval) await Bun.sleep(interval);
+}
+writeFileSync(process.env.WORKER_OUT!, JSON.stringify(results));
+await disposePersistenceConsumer(engine);
+await engine.disconnect();
+process.exit(0);
diff --git a/test/managed-sync-foreground-priority.test.ts b/test/managed-sync-foreground-priority.test.ts
new file mode 100644
index 0000000000..e9e628ecc4
--- /dev/null
+++ b/test/managed-sync-foreground-priority.test.ts
@@ -0,0 +1,183 @@
+/**
+ * #5984 Phase 4.5 (Postgres only): an agent's page write from another process goes ahead of the queued sync
+ * groups of a draining managed sync that do not name its page, waits in order behind one that does, and a
+ * stream of writes still lets the drain publish a group after each one. `GBRAIN_SYNC_FOREGROUND_PRIORITY=0`
+ * restores the FIFO (and fails the first case).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resetWriteSwitches } from '../src/core/persistence/switches.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-fg-priority-'));
+let engine: BrainEngine | undefined;
+let databaseUrl = '';
+let closePostgres: (() => Promise<void>) | undefined;
+const sources: string[] = [];
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+const pad = (i: number) => String(i).padStart(3, '0');
+async function fixture(e: BrainEngine, count: number) {
+ const id = `fgp-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < count; i++) writeFileSync(join(root, 'notes', `n${pad(i)}.md`), `---\ntitle: Note ${i}\n---\nA durable observation number ${i}.\n`);
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await e.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await e.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(e, id, root);
+ await e.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return id;
+}
+type Row = { id: string; request_id: string; created: number; grp: string | null; slug: string; sequence: string; state: string; kind: string | null; completed: number | null };
+const rows = (e: BrainEngine, source: string) => e.executeRaw<Row>(`SELECT id::text,request_id::text,intent->>'group' AS grp,slug,sequence::text,state,intent->>'kind' AS kind,
+ (extract(epoch FROM created_at)*1000)::float8 AS created,
+ (extract(epoch FROM completed_at)*1000)::float8 AS completed FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [source]);
+const until = async (check: () => Promise<boolean>, ms = 60_000) => {
+ const deadline = Date.now() + ms;
+ while (!await check()) { if (Date.now() > deadline) throw new Error('timed out'); await Bun.sleep(10); }
+};
+/** Records every request the drain's process claims (FIFO, lane head or group follower), with the time. */
+function recordClaims(e: BrainEngine): { claims: Map<string, number>; restore: () => void } {
+ const claims = new Map<string, number>();
+ const execute = e.executeRaw;
+ // When each claim transaction chose its row: a claim already deciding when the write was admitted is not an overtake.
+ const chose = new WeakMap<object, number>();
+ e.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[], opts?: unknown) {
+ const sent = Date.now();
+ if (/FOR UPDATE OF r SKIP LOCKED/.test(sql)) chose.set(this, sent);
+ const out = await execute.call(this, sql, params, opts as never) as Array<{ id?: string; state?: string }>;
+ if (/^UPDATE persistence_requests( r)? SET state='running'/.test(sql.trim())) for (const row of out) if (row.id && row.state === 'running') claims.set(String(row.id), chose.get(this) ?? sent);
+ return out as never;
+ } as BrainEngine['executeRaw'];
+ return { claims, restore: () => { e.executeRaw = execute; } };
+}
+function writer(source: string, slugs: string[], intervalMs = 0, go?: string) {
+ const out = join(home, `worker-${randomUUID()}.json`);
+ const child = Bun.spawn([process.execPath, join(import.meta.dir, 'fixtures', 'foreground-put-page-worker.ts')], { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ env: { ...process.env, GBRAIN_HOME: home, WORKER_DATABASE_URL: databaseUrl, WORKER_SOURCE: source, WORKER_SLUGS: slugs.join(',') || '-', WORKER_INTERVAL_MS: String(intervalMs), WORKER_OUT: out, ...(go ? { WORKER_GO: go } : {}) } });
+ return async () => {
+ const [stderr, code] = await Promise.all([new Response(child.stderr).text(), child.exited]);
+ if (code !== 0) throw new Error(`writer exited ${code}: ${stderr.slice(-2000)}`);
+ return JSON.parse(readFileSync(out, 'utf8')) as Array<{ slug: string; state: string; error?: string; submitted: number; returned: number }>;
+ };
+}
+
+beforeAll(async () => {
+ if (!process.env.DATABASE_URL) return;
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL, 'instance', 12);
+ engine = pg.engine; closePostgres = pg.close; databaseUrl = pg.databaseUrl;
+}, 120_000);
+afterAll(async () => {
+ if (engine) await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine!); await engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine!.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+/**
+ * Starts a drain, waits until it has sync groups queued that nobody claimed, then writes `slug` from another
+ * process. Returns the queued sync rows admitted before the write, the drain's claims and the final rows.
+ */
+async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string) {
+ const e = engine!, source = await fixture(e, 64);
+ const recorder = recordClaims(e);
+ // Each sync page holds its group open a little before commit, so groups stay queued while the writer starts.
+ const hold = 150;
+ installFaultHook(async (point, detail) => { if (point === 'publication:before_commit' && detail.sourceId === source) await Bun.sleep(hold); });
+ try {
+ const drain = performSync(e, { sourceId: source, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes });
+ let queued: Row[] = [];
+ // The writer process starts now and writes (the slug the go file names) once a sync group is queued that nobody has started.
+ const go = join(home, `go-${randomUUID()}`);
+ const finish = writer(source, [], 0, go);
+ await until(async () => {
+ const all = await rows(e, source);
+ const begun = new Set(all.filter(row => row.state !== 'queued').map(row => row.request_id));
+ queued = all.filter(row => row.state === 'queued' && row.kind?.startsWith('managed_sync_') && !(row.grp && begun.has(row.grp)) && !begun.has(row.request_id));
+ // With lanes the drain admits groups ahead; without them only the publishing group is out, so the write comes while one runs.
+ return all.some(row => row.state === 'committed') && (lanes > 1 ? queued.length >= 4 : all.some(row => row.state === 'running' && row.kind?.startsWith('managed_sync_')));
+ });
+ const target = slug(queued.length ? queued : await rows(e, source).then(all => all.filter(row => row.state === 'queued')));
+ writeFileSync(go, target);
+ let before: Row[] = [];
+ await until(async () => {
+ const all = await rows(e, source);
+ const put = all.find(row => row.slug === target && !row.kind?.startsWith('managed_sync_'));
+ if (!put) return false;
+ // Queued sync rows admitted before the write whose group has not started (a started group's followers go with it).
+ const started = new Set(all.filter(row => row.state !== 'queued').map(row => row.request_id));
+ before = all.filter(row => row.kind?.startsWith('managed_sync_') && row.state === 'queued' && BigInt(row.sequence) < BigInt(put.sequence)
+ && !(row.grp && started.has(row.grp)));
+ return true;
+ });
+ const [written] = await finish();
+ const result = await drain;
+ return { source, target, before, written: written!, result, claims: recorder.claims, final: await rows(e, source) };
+ } finally { recorder.restore(); installFaultHook(undefined); }
+}
+
+for (const lanes of [2, 1]) {
+ test(`a write to a page no queued group names commits before another sync group starts (lanes ${lanes})`, async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ resetWriteSwitches();
+ const run = await writeDuringDrain(lanes, () => `notes/foreground-${lanes}`);
+ expect(run.written.state).toBe('committed');
+ expect(run.result.status).toBe('first_sync');
+ // With lanes, groups admitted ahead were queued when the write arrived; it still went first.
+ if (lanes > 1) expect(run.before.length).toBeGreaterThan(0);
+ const put = run.final.find(row => row.slug === run.target)!;
+ // No sync group started (its head chosen) after the write was admitted and before it committed.
+ const heads = run.final.filter(row => row.kind?.startsWith('managed_sync_') && (row.grp ?? row.request_id) === row.request_id);
+ const early = heads.filter(row => { const claimed = run.claims.get(row.id) ?? Infinity; return claimed >= put.created && claimed < put.completed!; }).map(row => row.slug);
+ expect(early).toEqual([]);
+ expect(run.final.filter(row => row.kind?.startsWith('managed_sync_import')).every(row => row.state === 'committed')).toBe(true);
+ }), 300_000);
+}
+
+test('a write to a page a queued group names waits for that group and settles after it, in order', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ resetWriteSwitches();
+ const run = await writeDuringDrain(2, queued => queued.at(-1)!.slug);
+ expect(run.result.status).toBe('first_sync');
+ const sync = run.final.find(row => row.slug === run.target && row.kind === 'managed_sync_import')!;
+ const put = run.final.find(row => row.slug === run.target && row.kind !== 'managed_sync_import')!;
+ expect(sync.state).toBe('committed');
+ // The write was claimed after the import it names committed, so it met the imported page: a write that creates
+ // the page is refused because the page now exists, exactly as if it had arrived after the sync.
+ expect(run.written).toMatchObject({ state: 'error', error: expect.stringContaining('already exists') });
+ expect(['failed', 'conflict']).toContain(put.state);
+ expect(sync.completed!).toBeLessThan(put.completed!);
+ expect(run.claims.has(put.id) ? run.claims.get(put.id)! : put.completed!).toBeGreaterThanOrEqual(sync.completed! - 5);
+ const lastSync = Math.max(...run.final.filter(row => row.kind === 'managed_sync_import').map(row => row.completed!));
+ expect(put.completed!).toBeLessThanOrEqual(lastSync + 5_000);
+}), 300_000);
+
+test('a stream of writes from another process still lets the drain publish a group after each write', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ resetWriteSwitches();
+ const e = engine, source = await fixture(e, 64);
+ const drain = performSync(e, { sourceId: source, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 2 });
+ await until(async () => (await rows(e, source)).some(row => row.state === 'committed' && row.kind === 'managed_sync_import'));
+ const written = await writer(source, Array.from({ length: 12 }, (_, i) => `notes/stream-${i}`))();
+ const result = await drain;
+ expect(written.map(write => write.state)).toEqual(written.map(() => 'committed'));
+ expect(result.status).toBe('first_sync');
+ const final = await rows(e, source);
+ const writes = final.filter(row => row.slug.startsWith('notes/stream-')).map(row => row.completed!).sort((a, b) => a - b);
+ const groupCommits = final.filter(row => row.kind === 'managed_sync_import' && (row.grp ?? row.request_id) === row.request_id).map(row => row.completed!);
+ // The drain kept publishing while the writes kept coming: sync groups committed throughout the stream, about one
+ // per write (each foreground commit lets the drain start a group before the next write goes ahead).
+ const during = groupCommits.filter(at => at > writes[0]! && at < writes.at(-1)!).length;
+ expect(during).toBeGreaterThanOrEqual(Math.floor((writes.length - 1) / 2));
+}), 300_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index f0951d4ac0..ec06b91861 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -54,6 +54,7 @@ test/managed-sync-bulk.test.ts
test/managed-sync-chunker-version.test.ts
test/managed-sync-concurrent-write-hold.test.ts
test/managed-sync-drain.test.ts
+test/managed-sync-foreground-priority.test.ts
test/managed-sync-group-completion.test.ts
test/managed-sync-group-uncommitted-head.test.ts
test/managed-sync-images-5493.test.ts