Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): drop a bulk group whose head the single path already admitted and guard admission on the frozen intent (#6075)

garrytana0670322edc2
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index f565e22d28..e13e6dd47f 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -17,7 +17,7 @@
- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`) sets `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; jobs, serve, the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`. Tests: `test/sync-drain.test.ts`, `test/managed-sync-drain.test.ts`.
-- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`.
+- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`.
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index c5ad59355b..d6bc30f21e 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, receiptFor } from './journal.ts';
+import { getWriteRequest, admitWriteInTransaction, 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';
@@ -536,9 +536,18 @@ async function formGroup(engine: BrainEngine, head: Cursor, pending: Pending, ke
if (!followers.length) return head;
// Members name their group (the head's request ID), so a consumer can claim them together.
const lane = laneRunOf(head, bulk);
- const members = [pending, ...followers].map(member => ({ ...member, intent: { ...member.intent, group: pending.requestId, ...(lane ? { lane } : {}) } }));
+ const members = [pending, ...followers].map(member => ({ ...member, intent: groupedIntent(member.intent, pending.requestId, lane) }));
return saveCursor(engine, key, head, { ...head, pending: members[0], group: members }, false, assertActive);
}
+/** The keys formGroup adds to a frozen intent; `ungroupedIntent` removes exactly these. */
+function groupedIntent(intent: SyncIntent, group: string, lane: string | null): SyncIntent {
+ return { ...intent, group, ...(lane ? { lane } : {}) };
+}
+/** #6075: the intent a head carried before formGroup named its group, as a single-path pass admits it. */
+function ungroupedIntent(intent: SyncIntent): SyncIntent {
+ const { group: _group, lane: _lane, ...single } = intent;
+ return single;
+}
/** #5984 lanes: the drain's lane run, opened for this cursor's worktree on first use; null when lanes are off. */
function laneRunOf(cursor: Cursor, bulk: BulkPass): string | null {
@@ -618,6 +627,15 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
let rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
[principal.kind, principal.id, members.map(member => member.requestId)]);
if (rows.length < members.length) {
+ // #6075: a pass that froze the head before it was grouped may have admitted it on the single path. The group is
+ // dropped and the single path takes that request; the followers were never admitted (a group admits in one
+ // transaction) and are frozen again. Any other intent under the head's request ID stays an idempotency_conflict.
+ const head = members[0]!, single = ungroupedIntent(head.intent);
+ const prior = rows.find(row => row.request_id === head.requestId);
+ if (prior && !cursor.window && prior.digest === intentDigest({ operation: 'submit_job', sourceId: cursor.sourceId, slug: head.slug, callerIntent: single })) {
+ const next: Cursor = { ...cursor, pending: { ...head, intent: single } }; delete next.group;
+ return { cursor: await saveCursor(engine, key, cursor, next) };
+ }
const admitted = await admitGroup(engine, members, cursor, async tx => {
const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key]);
return held?.request_id === members[0]!.requestId;
@@ -935,13 +953,22 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,
worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation,
principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });
- // ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry.
- const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id
- FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key]);
- if (held?.request_id !== pending.requestId) throw new CursorMoved();
+ // ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry
+ // with this intent (#6075: a bulk pass may have grouped the head since this pass read it).
+ const [held] = await tx.executeRaw<{ request_id: string | null; same: boolean | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id,
+ completed_keys->0->'pending'->'intent' = $3::text::jsonb AS same FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, JSON.stringify(pending.intent)]);
+ if (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();
assertActive();
return accepted;
- })).catch(error => { if (error instanceof CursorMoved) return null; throw error; });
+ })).catch(async error => {
+ if (error instanceof CursorMoved) return null;
+ // #6075: the group admitted this request first with its grouped intent; re-read the cursor instead of failing the pass.
+ if (error instanceof OperationError && error.code === 'idempotency_conflict') {
+ const current = await readCursor(engine, key, admitting);
+ if (current?.pending?.requestId === pending.requestId && digest(current.pending.intent) !== digest(pending.intent)) return null;
+ }
+ throw error;
+ });
if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }
await validateSyncAuthority(engine, cursor.authority, pending.slug);
assertSyncDispatchActive();
diff --git a/test/managed-sync-stale-group-head.test.ts b/test/managed-sync-stale-group-head.test.ts
new file mode 100644
index 0000000000..ead65eceb3
--- /dev/null
+++ b/test/managed-sync-stale-group-head.test.ts
@@ -0,0 +1,166 @@
+/**
+ * #6075: a bulk drain groups a frozen head under its request ID (adding `group`, and `lane` under lanes)
+ * while another owner loop that read the head before it was grouped admits it on the single path. The
+ * group step must not wedge on `idempotency_conflict`, and the single-path guard must notice the
+ * grouped intent instead of admitting the stale one. Bulk groups are Postgres-only.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import postgres from '#postgres';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.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 { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { admitWrite } from '../src/core/persistence/journal.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-stale-head-'));
+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(); }
+async function fixture(e: BrainEngine, count: number) {
+ const id = `head-${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${i}.md`), `---\ntitle: Note ${i}\n---\nObservation ${i} from acme-example.\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 StoredCursor = { pending?: { requestId: string; slug: string; pageId: number | null; intent: Record<string, unknown> }; group?: unknown[];
+ incarnation: string; binding: { worktree_id: string; topology_generation: string | number }; authority: { writer: { principal: { kind: string; id: string } } & Record<string, unknown> } };
+async function storedCursor(e: BrainEngine, sourceId: string): Promise<StoredCursor | null> {
+ const [row] = await e.executeRaw<{ c: StoredCursor }>("SELECT completed_keys->0 AS c FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [sourceId]);
+ return row?.c ?? null;
+}
+/** What an owner loop that read the head before it was grouped submits: the same request ID with the pre-group intent. */
+async function admitAsStaleSinglePass(e: BrainEngine, sourceId: string, c: StoredCursor, intent: Record<string, unknown>) {
+ const head = c.pending!;
+ await admitWrite(e, { requestId: head.requestId, operation: 'submit_job', sourceId, sourceIncarnation: c.incarnation, slug: head.slug, pageId: head.pageId,
+ worktreeId: c.binding.worktree_id, topologyGeneration: c.binding.topology_generation, principal: c.authority.writer.principal as never,
+ authority: c.authority.writer as never, callerIntent: intent, intent });
+}
+const ungrouped = (intent: Record<string, unknown>) => { const { group: _g, lane: _l, ...rest } = intent; return rest; };
+async function importedTitles(e: BrainEngine, sourceId: string, count: number) {
+ const titles: Array<string | undefined> = [];
+ for (let i = 0; i < count; i++) titles.push((await e.getPage(`notes/n${i}`, { sourceId }))?.title);
+ return titles;
+}
+
+beforeAll(async () => {
+ if (!process.env.DATABASE_URL) return;
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL, 'instance', 10);
+ engine = pg.engine; closePostgres = pg.close; databaseUrl = pg.databaseUrl;
+}, 120_000);
+afterAll(async () => {
+ installFaultHook(undefined);
+ 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 });
+});
+
+for (const lanes of [1, 2]) {
+ test(`a group whose head was already admitted on the single path is dropped and the drain finishes (lanes=${lanes})`, async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ if (!engine) return;
+ const e = engine, sourceId = await fixture(e, 10);
+ let stale = false;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'sync:mid_checkpoint' || detail.sourceId !== sourceId || stale) return;
+ const c = await storedCursor(e, sourceId);
+ if (!c?.pending || !c.group) return;
+ stale = true;
+ expect(c.pending.intent.group).toBe(c.pending.requestId);
+ if (lanes > 1) expect(typeof c.pending.intent.lane).toBe('string');
+ await admitAsStaleSinglePass(e, sourceId, c, ungrouped(c.pending.intent));
+ });
+ try {
+ const done = await performSync(e, { sourceId, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes });
+ expect(stale).toBe(true);
+ expect(done).toMatchObject({ status: 'first_sync', added: 10 });
+ } finally { installFaultHook(undefined); }
+ expect(await importedTitles(e, sourceId, 10)).toEqual(Array.from({ length: 10 }, (_, i) => `Note ${i}`));
+ const rows = await e.executeRaw<{ state: string }>(`SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'`, [sourceId]);
+ expect(rows).toHaveLength(10);
+ expect(rows.every(row => row.state === 'committed')).toBe(true);
+ }), 120_000);
+}
+
+test('a head admitted under its request ID with a different intent still refuses with idempotency_conflict', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ if (!engine) return;
+ const e = engine, sourceId = await fixture(e, 6);
+ let stale = false;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'sync:mid_checkpoint' || detail.sourceId !== sourceId || stale) return;
+ const c = await storedCursor(e, sourceId);
+ if (!c?.pending || !c.group) return;
+ stale = true;
+ await admitAsStaleSinglePass(e, sourceId, c, { ...ungrouped(c.pending.intent), content: 'different bytes' });
+ });
+ try {
+ await expect(performSync(e, { sourceId, noPull: true, noEmbed: true, noExtract: true, drain: true })).rejects.toMatchObject({ code: 'idempotency_conflict' });
+ expect(stale).toBe(true);
+ } finally { installFaultHook(undefined); }
+}), 120_000);
+
+test('a non-bulk pass that read the head before a drain grouped it does not admit the stale intent', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ if (!engine) return;
+ const e = engine, sourceId = await fixture(e, 10);
+ // An independent connection holds the admission counters, so the non-bulk pass blocks inside its admission
+ // transaction after reading the ungrouped head, and resumes only once the drain has grouped it.
+ const blocker = postgres(databaseUrl, { max: 1, prepare: false });
+ let stage = 0, single: Promise<unknown> | undefined, release: (() => void) | undefined;
+ const lockHeld = new Promise<void>(resolve => { release = resolve; });
+ let locked: Promise<unknown> | undefined;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'sync:mid_checkpoint' || detail.sourceId !== sourceId) return;
+ const c = await storedCursor(e, sourceId);
+ if (stage === 0 && c?.pending && !c.group) {
+ stage = 1;
+ let acquired!: () => void;
+ const ready = new Promise<void>(resolve => { acquired = resolve; });
+ locked = blocker.begin(async sql => {
+ await sql`INSERT INTO persistence_counters(key) VALUES ('brain') ON CONFLICT DO NOTHING`;
+ await sql`SELECT key FROM persistence_counters WHERE key='brain' FOR UPDATE`;
+ acquired();
+ await lockHeld;
+ });
+ await ready;
+ single = performSync(e, { sourceId, noPull: true, noEmbed: true, noExtract: true }).then(value => ({ value }), error => ({ error }));
+ for (let i = 0; i < 200; i++) {
+ const [waiting] = await e.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pg_stat_activity WHERE wait_event_type='Lock' AND datname=current_database()");
+ if (waiting!.n > 0) break;
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ } else if (stage === 1 && c?.pending && c.group) {
+ stage = 2;
+ release!();
+ await locked;
+ }
+ });
+ try {
+ const drained = await performSync(e, { sourceId, noPull: true, noEmbed: true, noExtract: true, drain: true }).then(value => ({ value }), error => ({ error }));
+ const singled = await single;
+ expect(stage).toBe(2);
+ expect(singled).not.toHaveProperty('error');
+ expect(drained).not.toHaveProperty('error');
+ } finally { installFaultHook(undefined); release?.(); await locked?.catch(() => undefined); await blocker.end(); }
+ const resumed = await performSync(e, { sourceId, noPull: true, noEmbed: true, noExtract: true, drain: true });
+ expect(['synced', 'first_sync', 'up_to_date']).toContain(resumed.status);
+ expect(await importedTitles(e, sourceId, 10)).toEqual(Array.from({ length: 10 }, (_, i) => `Note ${i}`));
+ const [head] = await e.executeRaw<{ grp: string | null }>(`SELECT intent->>'group' AS grp FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence LIMIT 1`, [sourceId]);
+ expect(head?.grp).not.toBeNull();
+}), 120_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 56369fdc79..6ecd2a7458 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -50,6 +50,7 @@ test/managed-sync-drain.test.ts
test/managed-sync-group-completion.test.ts
test/managed-sync-images-5493.test.ts
test/managed-sync-lanes.test.ts
+test/managed-sync-stale-group-head.test.ts
test/pack-relation-direction-engine.test.ts
test/page-embedding-install-batch.test.ts
test/page-state-engine.test.ts