Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(g6): a group member writing a page or file an earlier member writes ends the group before it; the rest is prepared again after the prefix publishes (GBRA-60)

garrytan0929825988d1
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 051dd5d87f..a872e21925 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -104,20 +104,21 @@ export function groupable(row: WriteRequest, prepared: PreparedMutation): boolea
}
/**
- * G6: whether two members of a page group write the same page or the same file (a generation that deletes and writes
- * one path, a batch naming a page twice). Such a group never shares a transaction: its members publish one at a time,
- * in order, so the second sees the first's result. Compared case-insensitively, as a case-insensitive checkout would.
+ * G6: the index of the first member that writes a page or file an earlier member of the group writes (a generation
+ * that deletes and rewrites one path, a batch naming a page twice), or null. Its preparation read the state before the
+ * earlier write, so the group ends before it (executeClaimedGroup). Compared case-insensitively, as a case-insensitive
+ * checkout would. The generation activation journals under a pseudo slug and writes no page, so only its file counts.
*/
-export function sharesTarget(rows: WriteRequest[], prepared: PreparedMutation[]): boolean {
+export function firstSharedTarget(rows: WriteRequest[], prepared: Array<PreparedMutation | undefined>): number | null {
const seen = new Set<string>();
for (const [i, row] of rows.entries()) {
- const file = prepared[i]!.file;
- for (const target of [`page:${row.slug.toLowerCase()}`, ...(file ? [`file:${file.path.toLowerCase()}`] : [])]) {
- if (seen.has(target)) return true;
- seen.add(target);
- }
+ const file = prepared[i]?.file;
+ const page = row.intent?.kind === 'managed_generation_activate' ? [] : [`page:${row.slug.toLowerCase()}`];
+ const targets = [...page, ...(file ? [`file:${file.path.toLowerCase()}`] : [])];
+ if (targets.some(target => seen.has(target))) return i;
+ for (const target of targets) seen.add(target);
}
- return false;
+ return null;
}
const flattened = new Map<string, string>();
@@ -253,7 +254,6 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
const culpritOf = (error: unknown) => error instanceof OperationError && memberOf.has(error) ? { culprit: { index: memberOf.get(error)!, error } } : {};
if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!)
|| rows.length > 1 && singleWrite(row))) return none;
- if (!syncGroup(publicationGroupKey(head)) && sharesTarget(rows, prepared)) return none;
const binding = await getWorktreeBinding(engine, head.source_id, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return none;
// #5984 lanes: lane groups share this process's native lock; a foreground page write (Phase 4.5) joins their
@@ -795,6 +795,13 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
run.publication!.onOverdue?.();
} }) : publish();
const live = rows.map((row, i) => ({ row, i })).filter(({ row }) => !released.has(row.id));
+ // G6: a member writing a page or file an earlier member writes is prepared again after that write publishes: the group
+ // ends before it, and it and the members after it go back to the queue in order.
+ const shared = ordered ? null : firstSharedTarget(live.map(({ row }) => row), live.map(({ i }) => { const p = prepared[i]; return p && 'ok' in p ? p.ok : undefined; }));
+ for (const { row } of shared === null ? [] : live.splice(shared)) {
+ held.delete(row.id); released.add(row.id);
+ await releaseUnpublishedClaim(engine, row, 'group_member_waiting');
+ }
if (!live.length) return progressed;
const liveRows = live.map(({ row }) => row);
if (run.publication) await holdClaimForPublication(lease, () => renewGroupClaims(engine, liveRows, publicationLeaseMs(run.publication!.ceilingMs), undefined,
diff --git a/test/git-door-g6-publication-groups.test.ts b/test/git-door-g6-publication-groups.test.ts
index 8a313d24d3..55ab21f141 100644
--- a/test/git-door-g6-publication-groups.test.ts
+++ b/test/git-door-g6-publication-groups.test.ts
@@ -6,13 +6,15 @@
* with their activation) and an extract_entities batch (put_page and add_timeline_entry) each publish in one
* transaction: one shared published_at (now() is the transaction start) and one commit.
* - Failure semantics: every G6 group is independent. One member forced to fail never cancels the others.
- * - Distinct targets: a group whose members share a page or file never shares a transaction; the batch writers refuse it.
+ * - Distinct targets: the batch writers refuse a batch naming a page twice. A claimed group whose member writes a page or
+ * file an earlier member writes ends before it: the prefix publishes as one group, and that member and the rest go
+ * back to the queue and are prepared again, so every member settles as it would ungrouped.
* - Contiguity: a single write interleaved in a batch splits it into two groups, still fewer commits than members.
* Runs on PGLite, and on Postgres through test/e2e/git-door-g6-publication-groups-postgres.test.ts. Synthetic content only.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { writeFileSync } from 'node:fs';
+import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
@@ -21,7 +23,7 @@ import { enrichEntities } from '../src/core/enrichment-service.ts';
import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';
import { operations } from '../src/core/operations.ts';
import { GROUP_KEY_SQL, publicationGroupKey } from '../src/core/persistence/journal.ts';
-import { sharesTarget } from '../src/core/persistence/group-publish.ts';
+import { firstSharedTarget } from '../src/core/persistence/group-publish.ts';
import type { PreparedMutation } from '../src/core/persistence/coordinator.ts';
import type { WriteRequest } from '../src/core/persistence/model.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
@@ -91,14 +93,17 @@ beforeAll(() => configureGateway({ embedding_model: 'openai:text-embedding-3-lar
afterAll(() => { installFaultHook(undefined); resetGateway(); });
describe('G6 publication groups: shared targets never share a transaction', () => {
- const row = (slug: string) => ({ slug }) as WriteRequest;
+ const row = (slug: string, kind?: string) => ({ slug, intent: kind ? { kind } : null }) as WriteRequest;
const file = (path: string) => ({ file: { path } }) as unknown as PreparedMutation;
const none = {} as PreparedMutation;
- test('two members on one page, or one file in two spellings, share a target; distinct pages and files do not', () => {
- expect(sharesTarget([row('atoms/a'), row('atoms/b')], [file('/r/atoms/a.md'), file('/r/atoms/b.md')])).toBe(false);
- expect(sharesTarget([row('atoms/a'), row('Atoms/A')], [none, none])).toBe(true);
- expect(sharesTarget([row('atoms/a'), row('atoms/b')], [file('/r/atoms/a.md'), file('/r/Atoms/A.md')])).toBe(true);
- expect(sharesTarget([row('__generation_activate__'), row('atoms/a')], [none, file('/r/atoms/a.md')])).toBe(false);
+ test('the first member on a page or file an earlier member writes (in any spelling) is found; distinct pages and files share none', () => {
+ expect(firstSharedTarget([row('atoms/a'), row('atoms/b')], [file('/r/atoms/a.md'), file('/r/atoms/b.md')])).toBeNull();
+ expect(firstSharedTarget([row('atoms/a'), row('atoms/b'), row('Atoms/A'), row('atoms/b')], [none, none, none, none])).toBe(2);
+ expect(firstSharedTarget([row('atoms/a'), row('atoms/b')], [file('/r/atoms/a.md'), file('/r/Atoms/A.md')])).toBe(1);
+ expect(firstSharedTarget([row('atoms/a'), row('atoms/b')], [undefined, none])).toBeNull();
+ // The activation journals under a pseudo slug and writes no page: two of them share no page target.
+ const activate = row('__generation_activate__', 'managed_generation_activate');
+ expect(firstSharedTarget([activate, row('atoms/a'), activate], [none, file('/r/atoms/a.md'), none])).toBeNull();
});
});
@@ -264,6 +269,47 @@ for (const backend of testBackends()) {
expect(await liveAtoms(engine)).not.toContain(retired);
}, { databaseUrl, setup }), 240_000);
+ test('shared target: a member writing a page an earlier group member wrote is prepared again after it, and settles as it would ungrouped', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strictSource(engine);
+ await seedNotes(ctx);
+ const [after, since] = [await lastSequence(engine), await headCommit(root)];
+ const [A, B, C] = ['notes/new-a', 'notes/new-b', 'notes/new-c'];
+ const create = (slug: string, tag: string) => ({ operation: 'put_page' as const, params: { slug, request_id: randomUUID(),
+ content: note(slug, `Alice Example wrote it (${tag}) for source-a.`) } });
+ // Hold the worktree so both batches queue before anything publishes.
+ const holder = await acquireWorktree((await getWorktreeBinding(engine, 'default'))!, 5000);
+ expect(holder).not.toBeNull();
+ try {
+ await submitPageMutations({ ...ctx, writeWaitMs: 0 }, [create(A, 'first'), create(B, 'first')]).catch(() => undefined);
+ await submitPageMutations({ ...ctx, writeWaitMs: 0 }, [create(A, 'second'), create(C, 'second')]).catch(() => undefined);
+ await disposePersistenceConsumer(engine);
+ } finally { await holder!.release(); }
+ await engine.executeRaw("UPDATE persistence_requests SET state='queued',execution_token=NULL,claim_expires_at=NULL,blocked_reason=NULL WHERE state='running' AND recovery IS NULL");
+ // One batch id for all four, so one claim takes page A twice: A, B, A again, C. Every member prepares while A has no page.
+ await engine.transaction(async tx => {
+ await declareDurablePersistence(tx);
+ await tx.executeRaw(`UPDATE persistence_requests SET intent=jsonb_set(intent,'{page_batch,id}',(SELECT intent->'page_batch'->'id' FROM persistence_requests
+ WHERE sequence>$1::bigint ORDER BY sequence LIMIT 1)) WHERE sequence>$1::bigint`, [after]);
+ });
+ const queued = await published(engine, after);
+ expect(queued.map(row => [row.slug, row.state, row.error_code])).toEqual([A, B, A, C].map(slug => [slug, 'queued', null]));
+ expect(new Set(queued.map(row => row.grp)).size).toBe(1);
+ const rows = await waitForWrites(engine, await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE sequence>$1::bigint ORDER BY sequence', [after]),
+ { engine: engine.kind }, 30_000);
+ // As ungrouped: the second create of A finds A written and refuses an overwrite without a revision; A keeps the first write.
+ expect(rows.map(row => [row.slug, row.state, row.error_code ?? null])).toEqual([[A, 'committed', null], [B, 'committed', null],
+ [A, 'conflict', 'revision_required'], [C, 'committed', null]]);
+ expect((await engine.readPageSnapshot(A!, { sourceId: 'default' }))!.page.compiled_truth).toContain('(first)');
+ await settleManagedGitEffects(engine);
+ expect(readFileSync(join(root, `${A}.md`), 'utf8')).toContain('(first)');
+ const done = await published(engine, after);
+ expect(done.filter(row => ['queued', 'running'].includes(row.state))).toEqual([]);
+ // A and B published as one group; C, claimed again with the second A, published after them.
+ expect(done[0]!.published).toBe(done[1]!.published);
+ expect(done[3]!.published).not.toBe(done[0]!.published);
+ expect(await commitsTouching(engine, root, since, [A!, B!, C!])).toBe(2);
+ }, { databaseUrl, setup }), 120_000);
+
test('contiguity: a single write interleaved in a batch splits it into two groups, still fewer commits than writes', () => managedBrain(async ({ engine, ctx, root }) => {
await strictSource(engine);
await seedNotes(ctx);