Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): the FIFO claim no longer starts a sync head ahead of a waiting foreground write

garrytana383126d00ae
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d66ca9f462..b3003f1ecc 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -722,6 +722,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// W2 belief ledger page-at-time. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.267.0', text: 'A page rename (a sync that sees a file move, a frontmatter slug repair, a held-file or import move) now saves the page as it stood before the move as a version, as an edit does, so `get_versions` and `gbrain history` list one more snapshot per rename. The move advances the page\'s revision, and until now no version held the body from before it.' },
{ since: '0.60.267.0', text: '`purge_fact` now saves each page it rewrites as a version before dropping the purged fence row, and its version redaction then removes the claim from that version as from every other, so `get_versions` and `gbrain history` list one more snapshot per page a fact purge rewrites. The snapshot holds the page as it stood before the purge, without the purged claim.' },
+ // FIFO claim foreground guard (fgp-park-before-claim). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.267.0', text: 'A foreground write no longer loses to an idle drain\'s sync head. While a managed sync drains, a page write that may go ahead of the queued sync groups (none of them names its page) now holds back the next sync group even when the drain\'s lanes are idle and the write\'s own process is still claiming it; before, the drain could start a group in that moment and the write waited for it. The sync side still gets one group after each such write commits, so a stream of writes cannot stall it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 80ae4d37e7..2d599742e3 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -193,6 +193,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
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>();
+ /** The newest sequence when this process last claimed a sync head on each worktree, FIFO or lane (one FIFO sync head per foreground commit). */
+ private syncHeadSeen = 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. */
@@ -616,10 +618,12 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {
const claimed = laneClaim();
try {
+ await faultPoint('consumer:claiming');
// A root where lanes run here owes the sync side no FIFO turn: the write publishes beside its groups.
const row = await this.phase('claim', () => claimNextWrite(this.engine, this.hostId, this.opts.claimLeaseMs ?? 30_000, [...attemptedRoots],
- [...this.owesSyncTurn].filter(key => !laneRootKeys.includes(key)), laneRootKeys.filter(key => !attemptedRoots.has(key))));
+ [...this.owesSyncTurn].filter(key => !laneRootKeys.includes(key)), laneRootKeys.filter(key => !attemptedRoots.has(key)), Object.fromEntries(this.syncHeadSeen)));
if (!row) break;
+ if (row.worktree_id && row.seen_sequence) this.syncHeadSeen.set(row.worktree_id, row.seen_sequence);
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.statements, row, 'consumer_stopping'); break; }
@@ -667,9 +671,11 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
while (!this.stopping && (this.laneTasks.get(worktreeId) ?? 0) < capacity) {
const claimed = laneClaim();
try {
+ await faultPoint('consumer:claiming');
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.syncHeadSeen.set(worktreeId, row.seen_sequence);
this.owesSyncTurn.delete(worktreeId);
this.startLaneTask(row, worktreeId);
} finally { claimed(); }
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index cde93754dd..2f29a536a6 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -4,7 +4,7 @@
* recovery path must finish: publication boundaries, after an effect's side
* effect but before its completion is recorded, before a recovery record is
* cleared, between sync checkpoints, after the consumer prepared a
- * claimed request, (`sync:after_freeze`) after a managed sync import entry is frozen and before it is admitted, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, (`stuck_recovery:*`) between the steps of a stuck-recovery resolution, and (`segmented:*`) between the stages of a segmented write. Production never installs a hook, so every call is a
+ * claimed request, (`consumer:claiming`) before the consumer claims a request or a lane head, (`sync:after_freeze`) after a managed sync import entry is frozen and before it is admitted, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, (`stuck_recovery:*`) between the steps of a stuck-recovery resolution, and (`segmented:*`) between the stages of a segmented write. Production never installs a hook, so every call is a
* no-op there; the gate's workers install one that SIGKILLs or stalls the
* process at a chosen point.
*/
@@ -16,6 +16,9 @@ export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['bound
export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid` | 'effect:embedding:settle'
| 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'sync:prescreened' | 'consumer:prepared'
| 'consumer:preparing' | 'lane:applied'
+ // Before each claim attempt of the consumer, a FIFO claim or a lane head's: a stalling hook keeps this process from starting
+ // another request or lane group meanwhile, while the requests it already holds run on.
+ | 'consumer:claiming'
// #6712 PR 0: after `freezeEntry` froze an import entry (its bytes are read) and before the request is admitted or published.
| 'sync:after_freeze'
// #6712 PR 1 (L2): after the cursor step that holds a failed entry and settles its index commits (`holdUnderGate`), and after
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index dfef9e3826..efae645051 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -634,11 +634,33 @@ export async function hasClaimableWrite(engine: SqlEngine, hostId: string, exclu
* or breaks up its lane groups. With no live lease nothing changes: a crashed drainer's rows still drain through any consumer.
* The holder is read only when the head row is a sync row, so a foreground write's claim costs no extra statement.
*/
-const LEASE_HELD = `EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE ${SYNC_KIND('r')} AND l.id=$5::text||r.source_id
- AND l.ttl_expires_at>now() AND NOT (l.holder_pid=$6::integer AND l.holder_host IS NOT DISTINCT FROM $7::text))`;
+const LEASE_HELD = `EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE ${SYNC_KIND('r')} AND l.id=$7::text||r.source_id
+ AND l.ttl_expires_at>now() AND NOT (l.holder_pid=$8::integer AND l.holder_host IS NOT DISTINCT FROM $9::text))`;
+/**
+ * #5984 Phase 4.5: the worktrees (`f.worktree_id`) where a foreground write that may go first waits, so no new sync head
+ * is claimed there: one queued or recovering, or claimed by another process (claim owner nonce other than `nonce`) that
+ * has not begun to publish (it cannot publish while this process's sync group holds the worktree, so it releases the claim
+ * and this process takes it), and not waiting on an earlier sync row that names its page. A non-sync request committed on
+ * the worktree after sequence `seen` (the newest sequence when this process last claimed a sync head there) earns the sync
+ * side one head, so a stream of writes cannot starve it. Uncorrelated with the candidate row, so a claim reads it once.
+ */
+const FOREGROUND_WAITING_ON = (nonce: string, seen: string, worktree = 'TRUE') => `SELECT f.worktree_id FROM persistence_requests f
+ WHERE ${worktree} AND f.state IN ('queued','running','recovering') AND (f.state<>'running' OR (NOT f.publication_started
+ AND f.claim_phase->'owner'->>'nonce' IS DISTINCT FROM ${nonce}))
+ 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(${seen},0) AND c.worktree_id=f.worktree_id
+ AND c.state='committed' AND NOT ${SYNC_KIND('c')})`;
+/**
+ * `syncSeen` maps a worktree id to the newest request sequence when this process last claimed a sync head there: a
+ * sync row is not claimed while a foreground write that may go first waits on its worktree (`FOREGROUND_WAITING`), so
+ * a write its own process is claiming (its row skipped as locked) or has claimed is not overtaken. A claimed sync row
+ * returns `seen_sequence`.
+ */
export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = [], fifoRoots: string[] = [],
- laneRoots: string[] = []): Promise<(WriteRequest & { passed_sync?: boolean }) | null> {
+ laneRoots: string[] = [], syncSeen: Record<string, string> = {}): Promise<(WriteRequest & { passed_sync?: boolean; seen_sequence?: string | null }) | null> {
const first = `(${foregroundPrioritySql()}) AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($3::text[]))`;
const holderOnly = !RESIDENT_CONSUMER_KINDS.includes(claimOwnerKind());
return engine.transactionDirect(async tx => {
@@ -650,8 +672,9 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM
WHERE ${claimableWriteSql(`(${first})`, '$4::text[]')}
-- On a root whose lane groups run in this process only a foreground write is claimed (beside them).
AND NOT (r.worktree_id::text=ANY($4::text[]) AND (${SYNC_KIND('r')} OR NOT (${first})))
+ AND NOT (${SYNC_KIND('r')} AND ${first} AND r.worktree_id IN (${FOREGROUND_WAITING_ON('$5::text', "($6::text::jsonb->>f.worktree_id::text)::bigint")}))
ORDER BY ${holderOnly ? `${LEASE_HELD}, ` : ''}${CLAIM_ORDER(`(${first})`)} LIMIT 1 FOR UPDATE OF r SKIP LOCKED`,
- [hostId, excludeRoots, fifoRoots, laneRoots, ...(holderOnly ? [syncLockId(''), process.pid, hostname()] : [])]),
+ [hostId, excludeRoots, fifoRoots, laneRoots, consumerIdentity().nonce, JSON.stringify(syncSeen), ...(holderOnly ? [syncLockId(''), process.pid, hostname()] : [])]),
]) as [unknown, WriteRequest[]];
if (!row) return null;
if (holderOnly && String(row.intent?.kind ?? '').startsWith('managed_sync_')) {
@@ -662,11 +685,12 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM
// `passed_sync`: the claimed row went ahead of a queued sync row of its root.
// #6278: the claim stamps its own `preparing` phase, so a kill before the first renewal is charged like any other.
const token = randomUUID();
- const [claimed] = await tx.executeRaw<WriteRequest & { passed_sync: boolean }>(`UPDATE persistence_requests SET state='running',
+ const [claimed] = await tx.executeRaw<WriteRequest & { passed_sync: boolean; seen_sequence: string | null }>(`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,claim_phase=$4::text::jsonb WHERE id=$1::uuid RETURNING *,EXISTS (SELECT 1 FROM persistence_requests earlier
WHERE earlier.worktree_id=persistence_requests.worktree_id AND earlier.sequence<persistence_requests.sequence
- AND earlier.state='queued' AND ${SYNC_KIND('earlier')}) AS passed_sync`,
+ AND earlier.state='queued' AND ${SYNC_KIND('earlier')}) AS passed_sync,
+ CASE WHEN ${SYNC_KIND('persistence_requests')} THEN (SELECT max(sequence) FROM persistence_requests)::text END AS seen_sequence`,
[row.id, token, leaseMs, claimPhaseStamp(startClaimPhase(), token)]);
return claimed ? { ...claimed, previous_claim_phase: row.claim_phase } : null;
});
@@ -699,19 +723,9 @@ 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)))
- -- #5984 Phase 4.5: no new lane head while a foreground write that may go first waits to be claimed (a claimed
- -- one publishes beside the lanes), except one head after each foreground commit since this run's last head
- -- claim, so a stream of writes cannot starve the drain. A write another process claimed but has not begun to
- -- publish still waits: it cannot publish while this process's lanes hold the worktree, so it releases the claim
- -- and this process takes it.
- AND NOT ((${foregroundPrioritySql()}) AND EXISTS (SELECT 1 FROM persistence_requests f WHERE f.worktree_id=r.worktree_id
- AND (f.state IN ('queued','recovering') OR (f.state='running' AND NOT f.publication_started
- AND f.claim_phase->'owner'->>'nonce' IS DISTINCT FROM $5::text))
- 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($4::bigint,0) AND c.worktree_id=r.worktree_id
- AND c.state='committed' AND NOT ${SYNC_KIND('c')}))
+ -- #5984 Phase 4.5: no new lane head while a foreground write that may go first waits (a claimed one publishes
+ -- beside the lanes), except one head after each foreground commit since this run's last head claim.
+ AND NOT ((${foregroundPrioritySql()}) AND r.worktree_id IN (${FOREGROUND_WAITING_ON('$5::text', '$4::bigint', 'f.worktree_id=$2::uuid')}))
ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, worktreeId, run, seenSequence, consumerIdentity().nonce]);
if (!row) return null;
const token = randomUUID();
diff --git a/test/claim-fifo-foreground-waiting.test.ts b/test/claim-fifo-foreground-waiting.test.ts
new file mode 100644
index 0000000000..dd923863ed
--- /dev/null
+++ b/test/claim-fifo-foreground-waiting.test.ts
@@ -0,0 +1,138 @@
+/**
+ * The FIFO claim gives a foreground write that may go first the guard the lane-head claim has (`FOREGROUND_WAITING`,
+ * journal.ts): no sync head of its worktree is claimed while the write is queued, locked by its own process's claim
+ * transaction (skipped by SKIP LOCKED, so ordering alone cannot put it first) or claimed by another process that has not
+ * begun to publish. Before the guard, an idle drain's FIFO claim started a sync group there and the write waited behind it.
+ * Each foreground commit since this process's last sync head earns the sync side one head, so a stream of writes claimed
+ * by other processes cannot starve it.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { activatePersistence } from '../src/core/persistence/activation.ts';
+import { setClaimOwnerForTest } from '../src/core/persistence/claim-phase.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { editRequest } from './helpers/persistence-request-fixture.ts';
+
+const engines: BrainEngine[] = [];
+const sourceId = 'fifo-foreground-waiting-example';
+let databaseUrl = '';
+let closePostgres: (() => Promise<void>) | undefined;
+const foreign = { kind: 'mcp', pid: 1, version: 'test', nonce: 'another-process' };
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine();
+ await lite.connect({}); await lite.initSchema();
+ engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close; databaseUrl = pg.databaseUrl;
+ }
+ for (const engine of engines) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ expect((await activatePersistence(engine, { confirmQuiesced: true })).enabled).toBe(true);
+ }
+}, 120_000);
+afterAll(async () => {
+ setClaimOwnerForTest(undefined);
+ await engines[0]?.disconnect(); await closePostgres?.();
+});
+
+/** A worktree on its own host, so each scene's claims see only its own rows. */
+async function scene(engine: BrainEngine) {
+ const host = randomUUID(), worktree = randomUUID();
+ await engine.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id) VALUES($1::uuid,$2::uuid)', [worktree, host]);
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);
+ const context: OperationContext = { engine, sourceId, remote: false, dryRun: false, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } };
+ const add = async (slug: string, kind?: string) => {
+ const authority = await submissionAuthority(context, 'put_page', sourceId, source!.incarnation, slug);
+ const content = '---\ntitle: Example\ntype: note\n---\nA synthetic note.\n';
+ const row = await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId, sourceIncarnation: source!.incarnation,
+ slug, pageId: null, requestId: randomUUID(), callerIntent: { slug, content }, intent: { slug, content }, authority });
+ await editRequest(engine, row.id, `worktree_id=$2::uuid${kind ? `,intent=jsonb_set(intent,'{kind}',to_jsonb($3::text))` : ''}`, kind ? [worktree, kind] : [worktree]);
+ return row.id;
+ };
+ const sync = (slug: string) => add(slug, 'managed_sync_import');
+ /** This process's next claim on the scene's host, as the drain's consumer makes it, with its sync-head cursor. */
+ const seen: Record<string, string> = {};
+ const claim = async () => {
+ const row = await claimNextWrite(engine, host, 30_000, [], [], [], seen);
+ if (row?.seen_sequence) seen[worktree] = row.seen_sequence;
+ return row?.id ?? null;
+ };
+ const claimAsAnotherProcess = async () => {
+ setClaimOwnerForTest(foreign);
+ try { return (await claimNextWrite(engine, host))?.id ?? null; } finally { setClaimOwnerForTest(undefined); }
+ };
+ const commit = (id: string) => editRequest(engine, id, `state='committed',execution_token=NULL,claim_expires_at=NULL,completed_at=now()`);
+ const maxSequence = async () => (await engine.executeRaw<{ s: string }>('SELECT max(sequence)::text AS s FROM persistence_requests'))[0]!.s;
+ return { worktree, seen, add, sync, claim, claimAsAnotherProcess, commit, maxSequence };
+}
+
+/** Postgres: another connection holds a write's row as its own process's claim transaction does, until released. */
+async function lockAsItsOwnProcess(id: string) {
+ const { default: postgres } = await import('#postgres');
+ const other = postgres(databaseUrl, { max: 1, prepare: false });
+ const locked = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();
+ const holder = other.begin(async tx => { await tx`SELECT id FROM persistence_requests WHERE id=${id}::uuid FOR UPDATE`; locked.resolve(); await release.promise; });
+ await locked.promise;
+ return async () => { release.resolve(); await holder; await other.end(); };
+}
+
+test('Postgres: a write its own process is claiming (row locked) is not overtaken by a sync head; once claimable it goes first', async () => {
+ const engine = engines.find(e => e.kind === 'postgres');
+ if (!engine) return;
+ const s = await scene(engine);
+ await s.sync('notes/synced-a');
+ s.seen[s.worktree] = await s.maxSequence();
+ const write = await s.add('notes/foreground-a');
+ const unlock = await lockAsItsOwnProcess(write);
+ try { expect(await s.claim()).toBeNull(); } finally { await unlock(); }
+ expect(await s.claim()).toBe(write);
+}, 60_000);
+
+test('Postgres: a steady stream of writes, each mid-claim in its own process, still lets the sync side claim a head after every second write', async () => {
+ const engine = engines.find(e => e.kind === 'postgres');
+ if (!engine) return;
+ const s = await scene(engine);
+ const heads: string[] = [];
+ for (let i = 0; i < 5; i++) heads.push(await s.sync(`notes/synced-c${i}`));
+ s.seen[s.worktree] = await s.maxSequence();
+ let write = await s.add('notes/foreground-c0');
+ let unlock = await lockAsItsOwnProcess(write);
+ const claimed: Array<string | null> = [];
+ try {
+ expect(await s.claim()).toBeNull();
+ for (let round = 1; round <= 10; round++) {
+ // The write its process was claiming publishes; the next is admitted and is at once mid-claim in its own process.
+ await unlock(); await s.commit(write);
+ write = await s.add(`notes/foreground-c${round}`);
+ unlock = await lockAsItsOwnProcess(write);
+ // A commit of a write admitted after this process's last sync head earns one head (the next write, admitted before
+ // that head, earns none), so a head comes every second round; it publishes before the next round.
+ const head = await s.claim();
+ claimed.push(head);
+ if (head) { await s.commit(head); expect(await s.claim()).toBeNull(); }
+ }
+ } finally { await unlock(); }
+ expect(claimed).toEqual(heads.flatMap(head => [head, null]));
+}, 120_000);
+
+test('a write another process claimed and has not begun to publish holds back the sync head of its worktree until it commits', async () => {
+ for (const engine of engines) {
+ const s = await scene(engine);
+ const head = await s.sync('notes/synced-b');
+ s.seen[s.worktree] = await s.maxSequence();
+ const write = await s.add('notes/foreground-b');
+ expect(await s.claimAsAnotherProcess()).toBe(write);
+ expect(await s.claim()).toBeNull();
+ await s.commit(write);
+ expect(await s.claim()).toBe(head);
+ }
+}, 60_000);
diff --git a/test/managed-sync-foreground-priority.test.ts b/test/managed-sync-foreground-priority.test.ts
index 5571f2f591..63e560f23f 100644
--- a/test/managed-sync-foreground-priority.test.ts
+++ b/test/managed-sync-foreground-priority.test.ts
@@ -91,7 +91,7 @@ afterAll(async () => {
* 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, laneHold = 0, preparingHoldMs = 0) {
+async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string, laneHold = 0, preparingHoldMs = 0, force = false) {
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. With
@@ -101,15 +101,22 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string,
let laneOpen = 0, armed = false, holdStarts = false;
const beside: boolean[] = [];
const written = Promise.withResolvers<void>();
- // Without `laneHold`, from the moment 4 unstarted groups are seen until `before` is read, each lane parks its group
- // at `lane:applied`, so no lane starts another group and the groups queued ahead of the write stay queued however
- // long the write takes to be admitted (each lane can take at most one more group before it parks).
+ // Without `laneHold`, from the moment 4 unstarted rows are seen until `before` is read, the drain's process claims
+ // nothing (`consumer:claiming`): no lane takes another group, while the groups the lanes hold run on and commit, so the
+ // groups queued ahead of the write stay queued however long the write takes to be admitted. (Parking a lane at
+ // `lane:applied` of its next group instead let each lane past that point claim one more group first: with as many
+ // groups queued as lanes, both could start before the write was admitted.)
const counted = Promise.withResolvers<void>();
+ // `force` (forced probe of that race): the write is admitted only after every group running when the test parked has
+ // committed and the lanes have had their chance to claim the queued ones, and the drain admits no new group meanwhile
+ // (`sync:after_freeze`), so only the parking keeps groups queued ahead of the write.
+ const runningAtReady = new Set<string>();
// With `preparingHoldMs`, whichever process claims the write holds its preparation that long, and this process stamps
// its claims with another process's owner, so either way the write is claimed elsewhere and unpublished meanwhile.
let heldHere: [number, number] | undefined;
if (preparingHoldMs) setClaimOwnerForTest({ kind: 'mcp', pid: 1, version: 'test', nonce: 'another-process' });
installFaultHook(async (point, detail) => {
+ if (!laneHold && holdStarts && point === 'consumer:claiming') await Promise.race([counted.promise, Bun.sleep(30_000)]);
if (preparingHoldMs && point === 'consumer:preparing' && detail.operation === 'put_page' && !heldHere) {
const start = Date.now();
await Bun.sleep(preparingHoldMs);
@@ -122,7 +129,7 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string,
laneOpen++;
try { await Promise.race([written.promise, Bun.sleep(laneHold)]); } finally { laneOpen--; }
}
- if (!laneHold && holdStarts && point === 'lane:applied') await Promise.race([counted.promise, Bun.sleep(30_000)]);
+ if (force && holdStarts && point === 'sync:after_freeze') await Promise.race([counted.promise, Bun.sleep(30_000)]);
if (!laneHold && point === 'publication:before_commit' && detail.operation === 'submit_job') await Bun.sleep(150);
});
try {
@@ -137,13 +144,22 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string,
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.
const ready = all.some(row => row.state === 'committed') && (lanes > 1 ? queued.length >= 4 : all.some(row => row.state === 'running' && row.kind?.startsWith('managed_sync_')));
- if (ready && lanes > 1) holdStarts = true;
+ if (ready && lanes > 1) {
+ for (const row of all) if (row.state === 'running' && row.kind?.startsWith('managed_sync_')) runningAtReady.add(row.grp ?? row.request_id);
+ holdStarts = true;
+ }
return ready;
});
const target = slug(queued.length ? queued : await rows(e, source).then(all => all.filter(row => row.state === 'queued')));
armed = true;
// With `laneHold`, the write is sent while a lane group holds the worktree lease, so only the drain's process can publish it.
if (laneHold) await until(async () => laneOpen > 0);
+ if (force) {
+ const ids = new Set(queued.map(row => row.grp ?? row.request_id));
+ await until(async () => (await rows(e, source)).every(row => !runningAtReady.has(row.grp ?? row.request_id) || !['queued', 'running'].includes(row.state)));
+ const deadline = Date.now() + 1000;
+ while (Date.now() < deadline && (await rows(e, source)).some(row => ids.has(row.request_id) && row.state === 'queued')) await Bun.sleep(10);
+ }
writeFileSync(go, target);
let before: Row[] = [];
await until(async () => {
@@ -163,11 +179,11 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string,
} finally { counted.resolve(); recorder.restore(); installFaultHook(undefined); setClaimOwnerForTest(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 () => {
+for (const [lanes, force] of [[2, false], [1, false], [2, true]] as const) {
+ test(`a write to a page no queued group names commits before another sync group starts (lanes ${lanes})${force ? ', forced probe: the lanes finish their groups before the write is admitted' : ''}`, async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
if (!engine) return;
resetWriteSwitches();
- const run = await writeDuringDrain(lanes, () => `notes/foreground-${lanes}`);
+ const run = await writeDuringDrain(lanes, () => `notes/foreground-${lanes}${force ? '-forced' : ''}`, 0, 0, force);
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.
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index fab049ff7d..e74dda6b33 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -29,6 +29,7 @@ test/belief-ledger-trust.test.ts
test/capture-consent-admission.test.ts
test/capture-dispatch-provenance-6524.test.ts
test/chronicle-backfill-max-usd.test.ts
+test/claim-fifo-foreground-waiting.test.ts
test/claim-lease-holder-only-6712.test.ts
test/claude-cli-output-cap.test.ts
test/colon-slug-windows-5032.test.ts