Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync groups: a member after an uncommitted member is cancelled, never published ahead of it (#6252)

garrytana33b20ea8aeb
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index ef6da2f984..80b23c9f96 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -43,7 +43,7 @@ import { describeFixes } from '../fence-repair/report.ts';
import { fenceFixesWire } from '../fence-repair/tier1.ts';
import type { FenceFix } from '../fence-repair/types.ts';
import { VERSION } from '../../version.ts';
-import { windowPredecessor, windowPredecessorAllows } from './sync-window.ts';
+import { earlierGroupMemberFailed, windowPredecessor, windowPredecessorAllows } from './sync-window.ts';
/** The options that select a managed sync cursor (its key), recorded so a refusal can print the exact retry. */
export interface SyncCursorOptions { full: boolean; workingTree: boolean; srcSubpath: string | null; exclude: string[]; includeHidden: string[]; strategy: string | null }
@@ -281,6 +281,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
return held ?? null;
});
await validateSyncAuthority(tx, p.syncAuthority, row.slug);
+ if (await earlierGroupMemberFailed(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p, `Request ${row.request_id} follows a page of the same bulk group that did not commit, so this page must not publish after it.`);
if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id)))) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,
`Another sync run of ${row.source_id} replaced the cursor this request belongs to.`);
if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row,
diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.ts
index 428f9d1dc2..d7e48bb91b 100644
--- a/src/core/persistence/sync-window.ts
+++ b/src/core/persistence/sync-window.ts
@@ -46,12 +46,25 @@ export async function windowPredecessorCommitted(engine: Pick<BrainEngine, 'exec
}
/**
- * Cancels a claimed window group whose predecessor did not commit: the claimed
- * head and its still-queued members. Returns the settled rows, or null when the
- * group may publish.
+ * #6252: whether an earlier member of this row's bulk group ended without committing (failed, cancelled or
+ * conflicted). Such a row must not publish: a group commits in manifest order, so its pages after a member that
+ * did not commit are cancelled and re-frozen once that member is resolved, never written ahead of it.
+ */
+export async function earlierGroupMemberFailed(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'intent' | 'request_id' | 'worktree_id' | 'sequence'>): Promise<boolean> {
+ const group = (row.intent as Record<string, unknown> | null | undefined)?.group;
+ if (typeof group !== 'string' || group === row.request_id || !row.worktree_id) return false;
+ const failed = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'group'=$2
+ AND sequence<$3 AND state IN ('failed','cancelled','conflict') LIMIT 1`, [row.worktree_id, group, row.sequence]);
+ return failed.length > 0;
+}
+
+/**
+ * Cancels a claimed window group whose predecessor did not commit, or a claimed group member whose earlier member
+ * did not commit (#6252): the claimed row and its group's still-queued members. Returns the settled rows, or null
+ * when it may publish.
*/
export async function cancelOrphanedWindowGroup(engine: BrainEngine, head: WriteRequest): Promise<WriteRequest[] | null> {
- if (await windowPredecessorCommitted(engine, head)) return null;
+ if (await windowPredecessorCommitted(engine, head) && !await earlierGroupMemberFailed(engine, head)) return null;
const group = typeof head.intent?.group === 'string' ? head.intent.group : head.request_id;
const members = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'group'=$2
AND state='queued' AND id<>$3::uuid ORDER BY sequence`, [head.worktree_id, group, head.id]);
diff --git a/test/managed-sync-group-uncommitted-head.test.ts b/test/managed-sync-group-uncommitted-head.test.ts
new file mode 100644
index 0000000000..4c0d03ae71
--- /dev/null
+++ b/test/managed-sync-group-uncommitted-head.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #6252: a bulk managed-sync group whose head ends without committing while
+ * its members are still queued (the head cancelled with cancel_write_request,
+ * or settled on its own before its followers published). The members after it
+ * never publish ahead of it: they are cancelled, the run reports the head, and
+ * the pages are imported once the head is resolved. Runs on PGLite (bulk
+ * forced) and, with DATABASE_URL, on Postgres. Synthetic content only.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncOpts } from '../src/commands/sync.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { cancelWriteRequest } from '../src/core/persistence/control.ts';
+import { requestPrincipal, type WriteRequest } from '../src/core/persistence/model.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-group-head-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const BULK = { enabled: true, reason: null, size: 4, maxTxnMs: 15_000 };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation.\n`;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function source(engine: BrainEngine, slugs: string[]) {
+ const id = `head-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of slugs) writeFileSync(join(root, `${slug}.md`), note(slug));
+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, sync: (extra: Partial<SyncOpts> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, ...extra }) };
+}
+
+test.each([['one group', false], ['a group admitted ahead in a drain', true]] as const)(
+ 'a group head cancelled while queued (%s): nothing after it publishes, and the retry imports every page once', (_label, drain) => withEnv(env, async () => {
+ for (const engine of engines) {
+ try {
+ const slugs = Array.from({ length: drain ? 8 : 4 }, (_, i) => `notes/n${i}`);
+ const s = await source(engine, slugs);
+ const lock = (await acquireWorktree((await getWorktreeBinding(engine, s.id))!))!;
+ const stop = new AbortController();
+ try {
+ await s.sync({ bulk: BULK, ...(drain ? { drainStartedAt: Date.now(), signal: stop.signal,
+ onProgress: p => { if (p.phase === 'managed_sync.group_ahead') stop.abort(); } } : {}) });
+ } finally { await disposePersistenceConsumer(engine); await lock.release(); }
+ const members = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent ? 'group' ORDER BY sequence", [s.id]);
+ expect(members.length).toBeGreaterThanOrEqual(drain ? 4 : 2);
+ expect(members.every(member => member.state === 'queued')).toBe(true);
+ expect(await cancelWriteRequest(engine, requestPrincipal(members[0]!), members[0]!.request_id)).toMatchObject({ state: 'cancelled' });
+ const blocked = await s.sync({ bulk: BULK });
+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', added: 0, managedWrite: { slug: 'notes/n0' } });
+ const after = await engine.executeRaw<{ slug: string; state: string }>('SELECT slug,state FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [members.map(member => member.id)]);
+ expect(after.filter(row => row.state !== 'cancelled').map(row => `${row.slug} ${row.state}`)).toEqual([]);
+ for (const member of members) expect(await engine.getPage(member.slug, { sourceId: s.id })).toBeNull();
+ const retried = await s.sync({ bulk: BULK, retryFailed: true });
+ expect(retried.added).toBeGreaterThanOrEqual(members.length);
+ for (const slug of slugs) expect(await engine.getPage(slug, { sourceId: s.id })).not.toBeNull();
+ } finally { await disposePersistenceConsumer(engine); }
+ }
+ }), 180_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index a81520e741..8bf2d8df93 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -49,6 +49,7 @@ test/managed-sync-bulk.test.ts
test/managed-sync-chunker-version.test.ts
test/managed-sync-drain.test.ts
test/managed-sync-group-completion.test.ts
+test/managed-sync-group-uncommitted-head.test.ts
test/managed-sync-images-5493.test.ts
test/managed-sync-lanes.test.ts
test/pack-relation-direction-engine.test.ts