Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a bulk group member released mid-group follows the member before it, never just the previous group

garrytan3f23629234d4
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 9fa2d55dc9..ad238828b8 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -18,7 +18,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. #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-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. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. Test: `test/sync-group-member-order.test.ts`.
- **`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.
- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, section line), the file line of the first bad row (`meta.line`, from `fenceFileLine` when the screen holds it), `fence_version` and the last repair attempt (`fence_repair`); the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence holds preview `gbrain repair fences --source <id>`, other holds preview `gbrain repair frontmatter`, a mixed source names both. One fence hold's fix (`gitHoldFix` → `fence-repair/hold-fix.ts` `fenceHoldFix`) is that file's `--only <path>` preview with the step its state calls for, and `gitHoldItem` carries the D16 `fence` object (classes, tier, `auto_retry`, `next_attempt_after`); callers that can read the maintenance state pass it (`fenceAutoRepairFor`). `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator (a held fence page gets `fenceHoldRelay`: the owner-host command and whether it clears by itself). Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 85178a4500..30c5d26b96 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -11,7 +11,7 @@ import { ownerExceptionLogText } from './publication-failure.ts';
import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';
import { publicationConcurrency } from './pool-capacity.ts';
-import { cancelOrphanedWindowGroup } from './sync-window.ts';
+import { claimedHeadOrder } from './sync-window.ts';
import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';
import { runPersistenceEffects } from './effects.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
@@ -597,9 +597,11 @@ export class PersistenceConsumer {
private async executeOrGroup(row: WriteRequest, root: RootHold): Promise<boolean> {
// #5984 admit-ahead: a window group whose predecessor did not commit is cancelled, never published after it.
// A lane group may be claimed while its predecessor still publishes; its commit wait decides instead.
+ // A bulk-sync group member released mid-group follows the member before it, not only the previous group (#6153 class).
const lane = laneOf(row);
- const orphaned = lane ? null : await cancelOrphanedWindowGroup(this.engine, row);
- if (orphaned) { for (const done of orphaned) this.settled(done); return true; }
+ const order = await claimedHeadOrder(this.engine, row, lane !== null);
+ if (order === 'wait') { await releaseUnpublishedClaim(this.engine, row, 'group_member_waiting'); return false; }
+ if (order) { for (const done of order) this.settled(done); return true; }
const group = publicationGroupKey(row);
if (!group || this.engine.kind !== 'postgres') return this.execute(row, root);
// #6007: a put_pages batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.
diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.ts
index 3219372267..e5307f208d 100644
--- a/src/core/persistence/sync-window.ts
+++ b/src/core/persistence/sync-window.ts
@@ -45,13 +45,55 @@ export async function windowPredecessorCommitted(engine: Pick<BrainEngine, 'exec
return prior?.state === 'committed';
}
+/** Cancels a claimed window group (outside lanes) that may not publish; null when it may (`claimedHeadOrder`). */
+export async function cancelOrphanedWindowGroup(engine: BrainEngine, head: WriteRequest): Promise<WriteRequest[] | null> {
+ const order = await claimedHeadOrder(engine, head, false);
+ return order === 'wait' ? null : order;
+}
+
+type OrderedRow = Pick<WriteRequest, 'intent' | 'request_id' | 'principal_kind' | 'principal_id' | 'sequence'>;
+const ENDED_UNCOMMITTED = ['failed', 'conflict', 'cancelled'];
+
+/** True for a bulk-sync group member other than its group's head (the head's request ID names the group). */
+function groupMember(row: Pick<WriteRequest, 'intent' | 'request_id'>): string | null {
+ const group = (row.intent as Record<string, unknown> | null | undefined)?.group;
+ return typeof group === 'string' && group !== row.request_id ? group : null;
+}
+
/**
- * 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.
+ * The state of the request a claimed row must follow; null when it follows nothing. A group member follows the
+ * member before it in its own group (members are admitted consecutively in one transaction, so it is the
+ * principal's nearest earlier request of that group); a group head or single request follows its window
+ * predecessor `after` ('missing' when that request is gone). A member's `after` names only the previous group,
+ * so a member claimed on its own (released mid-group, then claimed again) is ordered by this, never by `after`.
*/
-export async function cancelOrphanedWindowGroup(engine: BrainEngine, head: WriteRequest): Promise<WriteRequest[] | null> {
- if (await windowPredecessorCommitted(engine, head)) return null;
+export async function claimedPredecessorState(engine: Pick<BrainEngine, 'executeRaw'>, row: OrderedRow): Promise<string | null> {
+ const group = groupMember(row);
+ if (group) {
+ const [previous] = await engine.executeRaw<{ state: string }>(`SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2
+ AND sequence<$3 AND intent->>'group'=$4 ORDER BY sequence DESC LIMIT 1`, [row.principal_kind, row.principal_id, row.sequence, group]);
+ if (previous) return previous.state;
+ }
+ const after = windowPredecessor(row);
+ if (!after) return null;
+ const [prior] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',
+ [row.principal_kind, row.principal_id, after]);
+ return prior?.state ?? 'missing';
+}
+
+/**
+ * What a claimed head may do given the request it follows (`claimedPredecessorState`): publish (null), wait
+ * (`'wait'`: release the claim so that request goes first), or nothing: its group's claimed head and
+ * still-queued later members are cancelled and returned. Outside lanes any uncommitted predecessor cancels
+ * (the per-worktree FIFO claim means it is final). A lane group head may run while the previous group still
+ * publishes (`awaitLaneTurn` orders the commits and `laneFallback` settles a failed predecessor), but a lane
+ * group member waits for the member before it and is cancelled when that member ended without committing.
+ */
+export async function claimedHeadOrder(engine: BrainEngine, head: WriteRequest, lane: boolean): Promise<WriteRequest[] | 'wait' | null> {
+ const prior = await claimedPredecessorState(engine, head);
+ if (prior === null || prior === 'committed') return null;
+ if (lane && !groupMember(head)) return null;
+ if (lane && !ENDED_UNCOMMITTED.includes(prior)) return 'wait';
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]);
@@ -71,16 +113,14 @@ export async function cancelWindow(engine: BrainEngine, window: Array<Array<{ re
* #5984 lanes: after a drain's lane tasks settled, cancels its lane run's still-queued rows, in manifest order,
* whose predecessor ended without committing (a lane that saw its predecessor go back to the queue releases its
* group, which the window cancellation had skipped while it was claimed). The consumer's FIFO claim cancels the
- * same rows later (`cancelOrphanedWindowGroup`); this settles them before the drain reports.
+ * same rows later (`claimedHeadOrder`); this settles them before the drain reports. A group member is judged by
+ * the member before it (`claimedPredecessorState`), so a member released mid-group is cancelled with its group.
*/
export async function cancelOrphanedLaneRows(engine: BrainEngine, run: string): Promise<void> {
const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE state='queued' AND intent->>'lane'=$1 ORDER BY sequence`, [run]);
for (const row of rows) {
- const after = windowPredecessor(row);
- if (!after) continue;
- const [prior] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',
- [row.principal_kind, row.principal_id, after]);
- if (prior && ['failed', 'conflict', 'cancelled'].includes(prior.state)) await cancelRows(engine, [row]);
+ // In manifest order, so a row cancelled here is the uncommitted predecessor the next row sees.
+ if (ENDED_UNCOMMITTED.includes(await claimedPredecessorState(engine, row) ?? '')) await cancelRows(engine, [row]);
}
}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 235dbd84fe..aa83ef44db 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -95,6 +95,7 @@ test/source-retire-missing-checkout.test.ts
test/stats-health-source-scope.test.ts
test/sync-frontmatter-recovery.test.ts
test/sync-frontmatter-slug-conflict.test.ts
+test/sync-group-member-order.test.ts
test/sync-legacy-holds.test.ts
test/takes-vector-lifecycle-5885.serial.test.ts
test/withdrawal-overlay-concurrency.test.ts
diff --git a/test/sync-group-member-order.test.ts b/test/sync-group-member-order.test.ts
new file mode 100644
index 0000000000..4209b76488
--- /dev/null
+++ b/test/sync-group-member-order.test.ts
@@ -0,0 +1,109 @@
+/**
+ * #6153 class (wave 11, PR #6263 CI): a bulk-sync group member released back to the queue mid-group (its group
+ * fell back to the single path and an earlier member went back to the queue with `writer_busy`) was later
+ * claimed on its own and published, although the member before it in its group then failed. Its `after` names
+ * only the previous group, so the window checks (`cancelOrphanedWindowGroup`, the lane claim, the drain's
+ * `cancelOrphanedLaneRows`) let it through and a page after a failed page published. A group member's
+ * predecessor is the member before it: a member whose predecessor ended without committing is cancelled, and
+ * under lanes a member whose predecessor is still unfinished waits. Postgres only (bulk groups and lanes).
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { cancelWriteRequest } from '../src/core/persistence/control.ts';
+import { cancelOrphanedLaneRows, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
+import { closeLaneRun, openLanes } from '../src/core/persistence/sync-lanes.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type FixtureSource, type HarnessConfig } from '../scripts/persistence/harness.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+async function withBrain(run: (ctx: { engine: BrainEngine; config: HarnessConfig; sources: FixtureSource[] }) => Promise<void>) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-group-order-'));
+ const config: HarnessConfig = { kind: 'postgres', root, dataDir: join(root, 'unused'), hostId: randomUUID(),
+ seed: 6153, schedules: 0, operations: 0, sourceIds: ['group-order'], principalIds: [randomUUID()] };
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!, 'instance', 6);
+ try {
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_PERSISTENCE_FIXTURE_HOME: root }, async () => {
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(pg.engine, config);
+ await run({ engine: pg.engine, config, sources: await fixtures(pg.engine, config) });
+ });
+ } finally { await pg.close(); rmSync(root, { recursive: true, force: true }); }
+}
+
+/** Head `b` and member `c` of one bulk group (as formGroup names them), optionally in an open lane run. */
+async function group(engine: BrainEngine, config: HarnessConfig, source: FixtureSource, lane: string | null) {
+ const headId = randomUUID();
+ const member = (slug: string, requestId: string) => {
+ const intent = { content: `${slug} body`, group: headId, ...(lane ? { lane } : {}) };
+ return admitWrite(engine, admission(config, source, slug, '', 0, { requestId, callerIntent: intent, intent }));
+ };
+ const b = await member('order/b', headId);
+ const c = await member('order/c', randomUUID());
+ return { b, c };
+}
+function consumer(engine: BrainEngine, config: HarnessConfig, sources: FixtureSource[]) {
+ const errors: unknown[] = [];
+ const instance = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_engine, row) => prepared(row, sources),
+ { hostId: config.hostId, concurrency: 1, pollMs: 20, onError: error => errors.push(error) });
+ return { instance, errors };
+}
+const state = async (engine: BrainEngine, row: WriteRequest) => (await getWriteRequestById(engine, row.id))!;
+const pageOf = async (engine: BrainEngine, source: FixtureSource, slug: string) => engine.getPage(slug, { sourceId: source.id });
+
+describe.skipIf(!process.env.DATABASE_URL)('a bulk group member never publishes after the member before it ended without committing', () => {
+ test('FIFO claim: the member is cancelled, not published', () => withBrain(async ({ engine, config, sources }) => {
+ const { b, c } = await group(engine, config, sources[0]!, null);
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: b.principal_id }, b.request_id);
+ const { instance } = consumer(engine, config, sources);
+ try {
+ instance.start();
+ await waitFor(async () => !['queued', 'running'].includes((await state(engine, c)).state), { timeoutMs: 15_000, label: 'the member settles' });
+ } finally { await instance.stop(); }
+ expect(await state(engine, c)).toMatchObject({ state: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE });
+ expect(await pageOf(engine, sources[0]!, 'order/c')).toBeNull();
+ }), 120_000);
+
+ test('lane claim: the member is cancelled, not published', () => withBrain(async ({ engine, config, sources }) => {
+ const run = randomUUID();
+ const { b, c } = await group(engine, config, sources[0]!, run);
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: b.principal_id }, b.request_id);
+ openLanes(sources[0]!.binding.worktree_id, run, 4, null);
+ const { instance } = consumer(engine, config, sources);
+ try {
+ instance.start();
+ await waitFor(async () => !['queued', 'running'].includes((await state(engine, c)).state), { timeoutMs: 15_000, label: 'the member settles' });
+ } finally { await instance.stop(); await closeLaneRun(run, 5_000); }
+ expect(await state(engine, c)).toMatchObject({ state: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE });
+ expect(await pageOf(engine, sources[0]!, 'order/c')).toBeNull();
+ }), 120_000);
+
+ test('the drain-end sweep cancels a queued member whose predecessor failed', () => withBrain(async ({ engine, config, sources }) => {
+ const run = randomUUID();
+ const { b, c } = await group(engine, config, sources[0]!, run);
+ await cancelWriteRequest(engine, { kind: 'local_cli', id: b.principal_id }, b.request_id);
+ await cancelOrphanedLaneRows(engine, run);
+ expect(await state(engine, c)).toMatchObject({ state: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE });
+ }), 120_000);
+
+ test('a member whose predecessor committed still publishes', () => withBrain(async ({ engine, config, sources }) => {
+ const run = randomUUID();
+ const { c } = await group(engine, config, sources[0]!, run);
+ openLanes(sources[0]!.binding.worktree_id, run, 4, null);
+ const { instance } = consumer(engine, config, sources);
+ try {
+ instance.start();
+ await waitFor(async () => (await state(engine, c)).state === 'committed', { timeoutMs: 15_000, label: 'both pages commit' });
+ } finally { await instance.stop(); await closeLaneRun(run, 5_000); }
+ const rows = await engine.executeRaw<{ slug: string; state: string }>(`SELECT slug,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [sources[0]!.id]);
+ expect(rows).toEqual([{ slug: 'order/b', state: 'committed' }, { slug: 'order/c', state: 'committed' }]);
+ }), 120_000);
+});
+