Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a write another process claimed but has not begun to publish holds back new lane heads (#5984 G6)

garrytand6d9d59564e5
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 22fd110714..d49289f983 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -14,6 +14,7 @@ import { pipelined } from '../page-state/transactions.ts';
import { writeHealth, type WriteHealthFacts } from './health.ts';
import { writerStamp } from './writer-versions.ts';
import { claimPhaseStamp, startClaimPhase } from './claim-phase.ts';
+import { consumerIdentity } from './consumer-heartbeat.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { catalogueError } from '../error-catalogue.ts';
import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';
@@ -583,14 +584,18 @@ export async function claimNextLaneHead(engine: BrainEngine, hostId: string, wor
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.
- AND NOT ((${foregroundPrioritySql()}) AND EXISTS (SELECT 1 FROM persistence_requests f WHERE f.worktree_id=r.worktree_id AND f.state IN ('queued','recovering')
+ -- 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')}))
- ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, worktreeId, run, seenSequence]);
+ 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();
const [claimed] = await tx.executeRaw<WriteRequest & { seen_sequence: string }>(`UPDATE persistence_requests SET state='running',
diff --git a/test/fixtures/foreground-put-page-worker.ts b/test/fixtures/foreground-put-page-worker.ts
index 7c12cfcef4..3dfc77d0a2 100644
--- a/test/fixtures/foreground-put-page-worker.ts
+++ b/test/fixtures/foreground-put-page-worker.ts
@@ -5,13 +5,16 @@
* 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.
+ * are the same local writer on the same owner host. WORKER_PREPARING_HOLD_MS (optional): when this process claims its
+ * own write, its preparation waits that long first (results record `held: [start, end]`), so the write stays claimed
+ * by this process, unpublished, while the drain's lanes hold the worktree.
*/
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';
import { observeAdmissionTransactions } from '../../scripts/persistence/read-admission.ts';
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
// `admitted`: when the write's admission transaction committed (wall clock), so the test can tell a claim that
// could already see the write from one that chose its row before the write was visible.
@@ -21,7 +24,15 @@ const engine = observeAdmissionTransactions(postgres, () => { admittedAt ??= Dat
await postgres.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; admitted?: number }> = [];
+const results: Array<{ slug: string; state: string; error?: string; submitted: number; returned: number; admitted?: number; held?: [number, number] }> = [];
+const holdMs = Number(process.env.WORKER_PREPARING_HOLD_MS ?? '0');
+let held: [number, number] | undefined;
+if (holdMs > 0) installFaultHook(async (point, detail) => {
+ if (point !== 'consumer:preparing' || detail.operation !== 'put_page' || held) return;
+ const start = Date.now();
+ await Bun.sleep(holdMs);
+ held = [start, Date.now()];
+});
const logger = { info() {}, warn() {}, error() {} };
const go = process.env.WORKER_GO;
if (go) while (!existsSync(go) || !readFileSync(go, 'utf8')) await Bun.sleep(5);
@@ -32,7 +43,7 @@ for (const slug of slugs) {
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(), admitted: admittedAt });
+ results.push({ slug, state: String((out as { state?: string }).state ?? ''), submitted, returned: Date.now(), admitted: admittedAt, ...(held ? { held } : {}) });
} catch (error) {
results.push({ slug, state: 'error', error: (error as Error).message, submitted, returned: Date.now(), admitted: admittedAt });
}
diff --git a/test/managed-sync-foreground-priority.test.ts b/test/managed-sync-foreground-priority.test.ts
index 8ab3253ba9..5dbbc6ce02 100644
--- a/test/managed-sync-foreground-priority.test.ts
+++ b/test/managed-sync-foreground-priority.test.ts
@@ -18,6 +18,7 @@ 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';
+import { setClaimOwnerForTest } from '../src/core/persistence/claim-phase.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-fg-priority-'));
let engine: BrainEngine | undefined;
@@ -60,14 +61,15 @@ function recordClaims(e: BrainEngine): { claims: Map<string, number>; restore: (
} as BrainEngine['executeRaw'];
return { claims, restore: () => { e.executeRaw = execute; } };
}
-function writer(source: string, slugs: string[], intervalMs = 0, go?: string) {
+function writer(source: string, slugs: string[], intervalMs = 0, go?: string, preparingHoldMs = 0) {
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 } : {}) } });
+ 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 } : {}),
+ ...(preparingHoldMs ? { WORKER_PREPARING_HOLD_MS: String(preparingHoldMs) } : {}) } });
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; admitted?: number }>;
+ return JSON.parse(readFileSync(out, 'utf8')) as Array<{ slug: string; state: string; error?: string; submitted: number; returned: number; admitted?: number; held?: [number, number] }>;
};
}
@@ -89,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) {
+async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string, laneHold = 0, preparingHoldMs = 0) {
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
@@ -99,7 +101,16 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string,
let laneOpen = 0, armed = false;
const beside: boolean[] = [];
const written = Promise.withResolvers<void>();
+ // 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 (preparingHoldMs && point === 'consumer:preparing' && detail.operation === 'put_page' && !heldHere) {
+ const start = Date.now();
+ await Bun.sleep(preparingHoldMs);
+ heldHere = [start, Date.now()];
+ }
if (detail.sourceId !== source) return;
if (point === 'publication:before_commit' && detail.operation !== 'submit_job') beside.push(laneOpen > 0);
if (point === 'publication:after_commit' && detail.operation !== 'submit_job') written.resolve();
@@ -114,7 +125,7 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string,
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);
+ const finish = writer(source, [], 0, go, preparingHoldMs);
await until(async () => {
const all = await rows(e, source);
const begun = new Set(all.filter(row => row.state !== 'queued').map(row => row.request_id));
@@ -140,8 +151,8 @@ async function writeDuringDrain(lanes: number, slug: (queued: Row[]) => string,
});
const [written] = await finish();
const result = await drain;
- return { source, target, before, written: written!, result, claims: recorder.claims, final: await rows(e, source), beside };
- } finally { recorder.restore(); installFaultHook(undefined); }
+ return { source, target, before, written: written!, result, claims: recorder.claims, final: await rows(e, source), beside, held: heldHere ?? written!.held };
+ } finally { recorder.restore(); installFaultHook(undefined); setClaimOwnerForTest(undefined); }
}
for (const lanes of [2, 1]) {
@@ -166,6 +177,20 @@ for (const lanes of [2, 1]) {
}), 300_000);
}
+test('a write the writer\'s own process claimed but cannot publish beside the lanes still holds back new lane heads', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ if (!engine) return;
+ resetWriteSwitches();
+ // The write is claimed by a process other than the drain's (the writer's own, or the drain's stamped as another's) and
+ // held in preparation for 1.5 s. No lane head may be chosen while that claim is held.
+ const run = await writeDuringDrain(2, () => 'notes/claimed-elsewhere', 0, 1500);
+ expect(run.written.state).toBe('committed');
+ expect(run.result.status).toBe('first_sync');
+ expect(run.before.length).toBeGreaterThan(0);
+ const [start, end] = run.held!;
+ const heads = run.final.filter(row => row.kind?.startsWith('managed_sync_') && (row.grp ?? row.request_id) === row.request_id);
+ expect(heads.filter(row => { const claimed = run.claims.get(row.id) ?? Infinity; return claimed >= start && claimed < end; }).map(row => row.slug)).toEqual([]);
+}), 300_000);
+
test('a write publishes beside the running lane groups instead of waiting for them, and the lanes keep starting groups', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
if (!engine) return;
resetWriteSwitches();