Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(#6007): grouped commit publishes a put_pages batch's pages in one transaction

garrytan9c2d6ded0965
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index fa4cd41c47..4969135a21 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -47,7 +47,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).
-- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction, in three statements for any key set (sources share-locked in key order before any guard row is inserted, then guards, then pages rows); a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
+- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply.
- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index cab0f99526..a343c58b83 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, snapshot, sync validation (its source-wide part shared per transaction), apply, effects and receipt, counters locked after the members are applied. 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`. Tests: `test/managed-sync-bulk.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, snapshot, sync validation (its source-wide part shared per transaction), apply, effects and receipt, counters locked after the members are applied. 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 reads of rows it holds FOR SHARE (source, writer registration, the source's local path), the owner's host binding and config values are answered once per group. 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-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. 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. 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. 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` 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. 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`.
- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. Tests: `test/repair-frontmatter.test.ts`.
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 16ddc8ee18..3bb45d6a41 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -71,6 +71,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Fix wave 5 #5401: projection drain CLI and the budgeted resident drain.
"src/commands/projections.ts": ["test/e2e/projection-drain-postgres.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
"src/core/persistence/consumer.ts": ["test/e2e/projection-drain-postgres.test.ts"],
+ "src/core/persistence/group-publish.ts": ["test/e2e/put-pages-group-postgres.test.ts"],
"src/core/persistence/effect-links.ts": ["test/e2e/persistence-links-effect-postgres.test.ts"],
"src/core/page-state/guards.ts": ["test/e2e/page-guards-postgres.test.ts"],
"src/core/persistence/protocol.ts": ["test/e2e/persistence-statement-budget.test.ts"],
diff --git a/src/core/page-state/guards.ts b/src/core/page-state/guards.ts
index 3cb362335a..ce8bd581ac 100644
--- a/src/core/page-state/guards.ts
+++ b/src/core/page-state/guards.ts
@@ -2,48 +2,39 @@ import type { BrainEngine } from '../engine.ts';
import { validateSlug } from '../utils.ts';
import type { PageKey } from './types.ts';
-type SqlExecutor = Pick<BrainEngine, 'executeRaw'>;
-const keyId = (sourceId: string, slug: string) => JSON.stringify([sourceId, slug]);
-
-function orderedPageKeys(keys: readonly PageKey[]): PageKey[] {
+/** Source locks precede auth/request locks in callers; repeat held locks safely. */
+export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, keys: readonly PageKey[]): Promise<void> {
const unique = new Map<string, PageKey>();
for (const key of keys) {
if (!key.sourceId) throw new TypeError('A page guard requires an exact sourceId');
const slug = validateSlug(key.slug);
- unique.set(keyId(key.sourceId, slug), { sourceId: key.sourceId, slug });
+ unique.set(JSON.stringify([key.sourceId, slug]), { sourceId: key.sourceId, slug });
+ }
+ const ordered = [...unique.values()].sort((a, b) => a.sourceId < b.sourceId ? -1 : a.sourceId > b.sourceId ? 1 : a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
+ const sources = new Map<string, string>();
+ for (const { sourceId } of ordered) {
+ if (sources.has(sourceId)) continue;
+ const rows = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR SHARE', [sourceId]);
+ if (!rows.length) throw new Error(`Page source does not exist: ${sourceId}`);
+ sources.set(sourceId, rows[0].incarnation);
+ }
+ if (ordered.length > 1) {
+ // #5984: many keys in three statements, still created and locked in the sorted key order.
+ const incarnations = ordered.map(key => sources.get(key.sourceId)!), slugs = ordered.map(key => key.slug), sourceIds = ordered.map(key => key.sourceId);
+ await engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING', [incarnations, slugs]);
+ await engine.executeRaw(`SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n)
+ JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g`, [incarnations, slugs]);
+ await engine.executeRaw(`SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n)
+ JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p`, [sourceIds, slugs]);
+ return;
+ }
+ for (const key of ordered) {
+ const params = [sources.get(key.sourceId)!, key.slug];
+ await engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING', params);
+ await engine.executeRaw('SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE', params);
+ // Also fence direct SQL row writers. The guard remains when this row is absent.
+ await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE', [key.sourceId, key.slug]);
}
- return [...unique.values()].sort((a, b) => a.sourceId < b.sourceId ? -1 : a.sourceId > b.sourceId ? 1 : a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
-}
-
-/**
- * Locks sorted sources (FOR SHARE), then the sorted page guards, then the
- * sorted pages rows, in three statements for any number of keys (#6007).
- */
-async function lockOrderedPageKeys(engine: SqlExecutor, ordered: readonly PageKey[]): Promise<void> {
- if (!ordered.length) return;
- const sourceIds = [...new Set(ordered.map(key => key.sourceId))];
- // Every source row is share-locked, in key order, before the first guard
- // row is inserted: the insert is gated on reading the whole locked set.
- const sources = await engine.executeRaw<{ id: string; incarnation: string }>(`WITH s AS MATERIALIZED (
- SELECT src.id,src.incarnation FROM unnest($1::text[]) WITH ORDINALITY AS u(id,n) JOIN sources src ON src.id=u.id ORDER BY u.n FOR SHARE OF src),
- created AS (INSERT INTO page_write_guards(source_incarnation,slug)
- SELECT s.incarnation,k.s FROM unnest($2::text[],$3::text[]) WITH ORDINALITY AS k(src,s,n) JOIN s ON s.id=k.src
- WHERE (SELECT count(*) FROM s)=cardinality($1::text[]) ORDER BY k.n ON CONFLICT DO NOTHING)
- SELECT id,incarnation FROM s`, [sourceIds, ordered.map(key => key.sourceId), ordered.map(key => key.slug)]);
- const incarnations = new Map(sources.map(row => [row.id, row.incarnation]));
- const missing = sourceIds.find(id => !incarnations.has(id));
- if (missing !== undefined) throw new Error(`Page source does not exist: ${missing}`);
- await engine.executeRaw(`SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n)
- JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g`,
- [ordered.map(key => incarnations.get(key.sourceId)!), ordered.map(key => key.slug)]);
- // Also fence direct SQL row writers. The guard remains when this row is absent.
- await engine.executeRaw(`SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n)
- JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p`, [ordered.map(key => key.sourceId), ordered.map(key => key.slug)]);
-}
-
-/** Source locks precede auth/request locks in callers; repeat held locks safely. */
-export async function lockPageKeys(engine: SqlExecutor, keys: readonly PageKey[]): Promise<void> {
- await lockOrderedPageKeys(engine, orderedPageKeys(keys));
}
/**
@@ -51,20 +42,19 @@ export async function lockPageKeys(engine: SqlExecutor, keys: readonly PageKey[]
* The transaction's session owns them until the transaction or savepoint
* ends, so they are not re-acquired. That includes a key whose pages row was
* absent when it was locked: the only pages INSERT (engine-sql/pages.ts
- * putPage) runs after both engines' putPage take the same guard, so no other
- * transaction can create that row while the guard is held.
+ * putPage) runs after both engines' putPage take the same guard.
*/
export interface HeldPageKeys { keys: Set<string>; parent: HeldPageKeys | null }
function pageGuardKey(key: PageKey): string | null {
if (!key.sourceId) return null;
- try { return keyId(key.sourceId, validateSlug(key.slug)); } catch { return null; }
+ try { return JSON.stringify([key.sourceId, validateSlug(key.slug)]); } catch { return null; }
}
function holds(held: HeldPageKeys | null, id: string): boolean {
for (; held; held = held.parent) if (held.keys.has(id)) return true;
return false;
}
/** lockPageKeys for keys this transaction does not hold yet; invalid keys still reach its checks. */
-export async function lockUnheldPageKeys(engine: SqlExecutor, held: HeldPageKeys, keys: readonly PageKey[]): Promise<void> {
+export async function lockUnheldPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, held: HeldPageKeys, keys: readonly PageKey[]): Promise<void> {
const pending = keys.filter(key => { const id = pageGuardKey(key); return id === null || !holds(held, id); });
if (!pending.length) return;
await lockPageKeys(engine, pending);
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 3ebd7eef47..8a9dc9d0db 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -217,28 +217,21 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Proje
built?.corpusGeneration !== undefined ? built.corpusGeneration : context.corpusGeneration, stored);
// This is deliberately UPDATE-only: a late embed can never replace text,
// chunk identity, metadata, or membership in the installed projection.
- // #6007: one set-based statement for every chunk with a vector or image;
- // a repeated chunk index keeps its last entry, as sequential updates would.
- const updates = new Map<number, { id: number; vector: string | null; image: string | null; model: string | null; chunk_text: string; input_hash: string }>();
for (const chunk of chunks) {
if (!chunk.embedding && !chunk.embedding_image) continue;
const original = byIndex.get(chunk.chunk_index)!;
const vector = chunk.embedding ? `[${Array.from(chunk.embedding).join(',')}]` : null;
- updates.set(chunk.chunk_index, { id: original.id, vector, image: chunk.embedding_image ? `[${Array.from(chunk.embedding_image).join(',')}]` : null,
- // Bind the full provider:model captured before the provider call. Keeping
- // an old label on a new vector prevents provenance-complete migration.
- model: chunk.model ?? (vector ? prepared.embeddingModel : null) ?? null, chunk_text: original.chunk_text,
- input_hash: embeddingInputHash(provenance, tier, original) });
- }
- if (updates.size) {
- const target = quoteIdentifier(column.name);
- await tx.executeRaw(`UPDATE content_chunks c SET
- ${target}=CASE WHEN u.vector IS NULL THEN c.${target} ELSE u.vector${vectorCastSuffix(column)} END,
- embedding_image=CASE WHEN u.image IS NULL THEN c.embedding_image ELSE u.image::vector END,
- embedding_input_hash=CASE WHEN u.vector IS NULL THEN c.embedding_input_hash ELSE u.input_hash END,
- embedded_at=now(),embedded_text_hash=md5(c.chunk_text),model=COALESCE(u.model,c.model)
- FROM jsonb_to_recordset($1::text::jsonb) AS u(id bigint,vector text,image text,model text,chunk_text text,input_hash text)
- WHERE c.id=u.id AND c.page_id=$2 AND c.chunk_text=u.chunk_text`, [JSON.stringify([...updates.values()]), snapshot.page.id]);
+ const image = chunk.embedding_image ? `[${Array.from(chunk.embedding_image).join(',')}]` : null;
+ await tx.executeRaw(`UPDATE content_chunks SET
+ ${quoteIdentifier(column.name)}=CASE WHEN $2::text IS NULL THEN ${quoteIdentifier(column.name)} ELSE $2${vectorCastSuffix(column)} END,
+ embedding_image=CASE WHEN $3::text IS NULL THEN embedding_image ELSE $3::vector END,
+ embedding_input_hash=CASE WHEN $2::text IS NULL THEN embedding_input_hash ELSE $7 END,
+ embedded_at=now(),embedded_text_hash=md5(chunk_text),model=COALESCE($4,model)
+ WHERE id=$1 AND page_id=$5 AND chunk_text=$6`,
+ // Bind the full provider:model captured before the provider call. Keeping
+ // an old label on a new vector prevents provenance-complete migration.
+ [original.id, vector, image, chunk.model ?? (vector ? prepared.embeddingModel : null), snapshot.page.id, original.chunk_text,
+ embeddingInputHash(provenance, tier, original)]);
}
if (signature) await tx.setPageEmbeddingSignature(slug, { sourceId, signature });
return true;
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 4c8283daba..a3d9ad5f22 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,9 +1,9 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextWrite, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
+import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextWrite, publicationGroupKey, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
-import { executeClaimedGroup } from './group-publish.ts';
+import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX } from './group-publish.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';
@@ -516,15 +516,22 @@ export class PersistenceConsumer {
}
/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */
private async executeOrGroup(row: WriteRequest): Promise<boolean> {
- const group = typeof row.intent?.group === 'string' ? row.intent.group : null;
+ const group = publicationGroupKey(row);
if (!group || this.engine.kind !== 'postgres') return this.execute(row);
- const followers = await claimGroupFollowers(this.engine, row, group, 63);
+ // #6007: a put_pages batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.
+ const followers = await claimGroupFollowers(this.engine, row, group, group.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX - 1 : 63);
if (!followers.length) return this.execute(row);
const rows = [row, ...followers];
for (const member of rows) this.executing.add(member.id);
try {
return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, prepare: member => this.prepare(this.engine, member, this.config),
- settled: done => { this.executing.delete(done.id); this.settled(done); } });
+ settled: done => {
+ this.executing.delete(done.id);
+ if (done.state === 'committed' && done.worktree_id && !String(done.intent?.kind).startsWith('managed_sync_')) {
+ this.foregroundCounts.set(done.worktree_id, this.foregroundCompletions(done.worktree_id) + 1);
+ }
+ this.settled(done);
+ } });
} finally { for (const member of rows) this.executing.delete(member.id); }
}
/** Mandatory barrier: engine.close must be sequenced AFTER this promise. */
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index ea65932592..b0d6e5272d 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -13,7 +13,7 @@ import { authorizeStoredRequest } from './authority.ts';
import { localHostId } from './identity.ts';
import { acquireWorktree, getWorktreeBinding, guardOwnership, type WorktreeBinding } from './ownership.ts';
import { clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecovery, releaseUnpublishedClaim } from './journal.ts';
-import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type RecoveryRecord, type WriteRequest } from './model.ts';
+import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { withCoordinatedWrite } from './context.ts';
import { requestAttribution } from './attribution.ts';
@@ -141,6 +141,29 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Prepared
* The root lock spans all file effects; the DB guards span authorization and
* publication. A rejected/ambiguous commit is recovered before releasing FIFO.
*/
+/**
+ * The recovery record of one page file publication (its before bytes, hashes,
+ * mode and reserved staging names) and the recovery bytes it reserves. Read
+ * while holding the worktree's native lock, before any file is touched.
+ */
+export function pageRecoveryRecord(row: WriteRequest, file: PageMutationFile, binding: WorktreeBinding): { record: FileRecoveryRecord; bytes: number } {
+ const before = existsSync(file.path) ? readFileSync(file.path) : null;
+ const record: FileRecoveryRecord = {
+ version: 1, path: file.path, root: file.root,
+ before: before?.toString('base64') ?? null, beforeHash: before ? sha256(before) : null,
+ afterHash: file.content === null ? null : sha256(file.content),
+ mode: before ? statSync(file.path).mode & 0o7777 : null,
+ ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!,
+ staging: {
+ ...(file.content === null ? {} : { publication: recoveryStagingFile(file.path, file.content) }),
+ ...(before === null ? {} : { restoration: recoveryStagingFile(file.path, before) }),
+ },
+ };
+ const nextBytes = file.content === null ? 0 : typeof file.content === 'string' ? Buffer.byteLength(file.content) : file.content.byteLength;
+ const beforeBytes = before?.byteLength ?? 0;
+ return { record, bytes: Math.max(beforeBytes * 3 + nextBytes * 2, Buffer.byteLength(JSON.stringify(record)) + beforeBytes + nextBytes) + 4096 };
+}
+
export async function publishMutation(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation,
hostId = localHostId(), hooks: PublicationHooks = {}): Promise<WriteRequest> {
let lock: NativeLockHandle | null = null;
@@ -208,18 +231,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
if (!binding || !lock || !isWriteTargetContained(prepared.file.path, prepared.file.root)) throw opError('storage_error', 'Filesystem publication requires a confined canonical owner.',
`This host does not hold source ${row.source_id}'s canonical worktree, or the file of ${row.slug} resolves outside it, so request ${row.request_id} wrote no file. Inspect the owner; the write publishes only on the host that owns the source.`,
{ fix: ownerStatusFix(row.source_id) });
- const before = existsSync(prepared.file.path) ? readFileSync(prepared.file.path) : null;
- const record: RecoveryRecord = {
- version: 1, path: prepared.file.path, root: prepared.file.root,
- before: before?.toString('base64') ?? null, beforeHash: before ? sha256(before) : null,
- afterHash: prepared.file.content === null ? null : sha256(prepared.file.content),
- mode: before ? statSync(prepared.file.path).mode & 0o7777 : null,
- ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!,
- staging: {
- ...(prepared.file.content === null ? {} : { publication: recoveryStagingFile(prepared.file.path, prepared.file.content) }),
- ...(before === null ? {} : { restoration: recoveryStagingFile(prepared.file.path, before) }),
- },
- };
+ const { record, bytes } = pageRecoveryRecord(row, prepared.file, binding);
if (prepared.file.expectedBeforeHash !== undefined && record.beforeHash !== prepared.file.expectedBeforeHash) {
// A coordinated writer (a withdrawal mirror) also advanced the page:
// reprepare against it. Bytes changed at an unchanged revision are an
@@ -230,11 +242,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
}
throw localEditRefusal('The canonical file changed after preparation.', row, skill, 'after the write was prepared, at an unchanged page revision');
}
- const nextBytes = prepared.file.content === null ? 0 : typeof prepared.file.content === 'string'
- ? Buffer.byteLength(prepared.file.content) : prepared.file.content.byteLength;
- const beforeBytes = before?.byteLength ?? 0;
- await prepareRecovery(engine, row, record, Math.max(beforeBytes * 3 + nextBytes * 2,
- Buffer.byteLength(JSON.stringify(record)) + beforeBytes + nextBytes) + 4096);
+ await prepareRecovery(engine, row, record, bytes);
recovery = record;
await hooks.boundary?.('prepared', row);
}
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index 1aa7e3b442..5a62d3a3ad 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -21,7 +21,9 @@ import { pageBatchChildRequestIds } from './page-batch-id.ts';
* nothing while `auto_link` or `mcp.remote_auto_links` is off (unset is on).
*/
export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>, snapshot: PageSnapshot | null,
- outcome: Record<string, unknown>, prepared?: PreparedMutation): Promise<void> {
+ outcome: Record<string, unknown>, prepared?: PreparedMutation,
+ /** A grouped publication completes its members after queueing all of them, then calls `reconcileFinishedBatch` itself. */
+ opts: { deferBatchReconcile?: boolean } = {}): Promise<void> {
if (prepared?.noop || prepared?.target === 'skill_bundle') return;
await declarePersistenceProtocol(tx);
const revision = snapshot?.revision;
@@ -44,15 +46,14 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
if (!(await isFactsExtractionEnabled(tx))) outcome.facts_backstop = { skipped: 'extraction_disabled' };
else queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });
}
- if (row.authority && row.operation && REMOTE_MENTION_OPERATIONS.includes(row.operation)
- && !(row.authority.autoLinkTrusted ?? !row.authority.remote)) {
+ if (queuesMentionLinks(row)) {
const queued = await tx.executeRaw(`INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id)
SELECT $1::uuid,'links',$2::uuid,$3::text::jsonb,$4,$5::uuid,$6::uuid WHERE NOT EXISTS (SELECT 1 FROM config
WHERE key IN ('auto_link',$7) AND lower(btrim(value,E' \\t\\r\\n')) IN ('false','0','no','off'))
ON CONFLICT(request_id,kind) DO NOTHING RETURNING id`,
[row.id, revision ?? null, JSON.stringify(data), row.source_id, row.source_incarnation, row.worktree_id, REMOTE_AUTO_LINKS_KEY]);
if (queued.length) outcome.auto_links = { ...(outcome.auto_links as Record<string, unknown> | undefined), mention_links: 'queued' };
- await reconcileFinishedBatch(tx, row);
+ if (!opts.deferBatchReconcile) await reconcileFinishedBatch(tx, row);
}
// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.
await recordChronicleDecision(tx, row, snapshot, outcome);
@@ -63,12 +64,18 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
[row.id, revision ?? null, row.source_id, row.source_incarnation, row.worktree_id, JSON.stringify(queued)]);
}
+/** Whether a publication of this request queues a mention `links` effect: a remote page write without trusted auto-linking. */
+export function queuesMentionLinks(row: Partial<Pick<WriteRequest, 'operation' | 'authority'>>): boolean {
+ return !!row.authority && !!row.operation && REMOTE_MENTION_OPERATIONS.includes(row.operation)
+ && !(row.authority.autoLinkTrusted ?? !row.authority.remote);
+}
+
/**
* #6007: when the last unfinished page of a `put_pages` batch publishes, its
* earlier pages' links effects may have run before this page existed; re-arm
* them once so forward references inside the batch resolve, with no client poll.
*/
-async function reconcileFinishedBatch(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'intent' | 'principal_kind' | 'principal_id'>>): Promise<void> {
+export async function reconcileFinishedBatch(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'intent' | 'principal_kind' | 'principal_id'>>): Promise<void> {
const batch = row.intent?.page_batch as { id?: unknown; size?: unknown } | undefined;
if (!batch || typeof batch.id !== 'string' || typeof batch.size !== 'number' || batch.size < 2 || !row.principal_kind || !row.principal_id) return;
const siblings = await tx.executeRaw<{ id: string; state: string }>(`SELECT id,state FROM persistence_requests
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index f6890a38f8..cfa7697b1a 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -1,85 +1,186 @@
/**
- * #5984 bulk sync: publishes a claimed group of consecutive managed-sync page
- * requests in one transaction (ENG-A3/A4).
+ * Grouped publication: one transaction publishes a claimed run of consecutive
+ * requests of one worktree that share a group key (journal.ts
+ * `publicationGroupKey`): the database-only pages of a bulk managed sync
+ * (#5984, ENG-A3/A4) or the pages of one `put_pages` batch, files included
+ * (#6007).
*
* Every member keeps its own request row, authorization, page guard,
- * visibility check, attribution, effects and receipt; only the per-transaction
- * work is shared: the worktree lock, the recovery and capacity checks, the
- * ownership guard and the counter and request locks. Counters are locked after
- * the members are applied and before their request rows, so the brain-wide
- * counter row is held only for the completion statements (ENG-A5). A group
- * therefore takes page guards before counters, the reverse of single
+ * visibility check, revision check, attribution, effects and receipt; only
+ * the per-transaction work is shared: the worktree lock, the recovery and
+ * capacity checks, the ownership guard, the counter and request locks, the
+ * recovery records (one transaction records all of them before any file is
+ * touched) and their cleanup (one transaction after commit). Counters are
+ * locked after the members are applied and before their request rows, so the
+ * brain-wide counter row is held only for the completion statements (ENG-A5).
+ * A group therefore takes page guards before counters, the reverse of single
* publication and of forget/mirror recovery; a deadlock with one of those on
* the same page is detected by Postgres (40P01) and both sides retry: the
* group falls back to single publication, admission and withdrawal retry.
*
- * The group is all-or-nothing. Any failure rolls the transaction back and
- * returns null; the caller then publishes the members one at a time, so a
+ * The group is all-or-nothing. Any failure rolls the transaction back; files
+ * already published inside it are restored from their recovery records by
+ * the ordinary recovery path (`recoverPublication`, which also requeues their
+ * claims), and the caller then publishes the members one at a time, so a
* failure is attributed to its own page and no later member overtakes it.
- * Only database-only managed-sync page members qualify; their sync
- * validation includes the knowledge-publication guard. A member with a file,
- * a skill bundle or a source-exclusive checkpoint takes the single path.
+ * A member with a skill bundle or a source-exclusive checkpoint, or whose
+ * file changed since preparation, takes the single path.
*/
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest } from './authority.ts';
import { localHostId } from './identity.ts';
import { acquireWorktree, getWorktreeBinding, guardOwnership } from './ownership.ts';
-import { completeWrite, getWriteRequestById, lockCounters, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
-import { principalKey, requestPrincipal, type WriteRequest } from './model.ts';
+import { clearResolvedRecoveries, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecoveries, publicationGroupKey,
+ reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
+import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';
import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
import { requestAttribution } from './attribution.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
-import { queuePublicationEffects } from './effect-journal.ts';
+import { queuePublicationEffects, queuesMentionLinks, reconcileFinishedBatch } from './effect-journal.ts';
import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
import { declareDurablePersistence } from './protocol.ts';
-import { classifyMirrorPage } from './mirror-read-only.ts';
-import { decoratePublicationOutcome, finishUnpublishedFailure, publishMutation, type PreparedMutation } from './coordinator.ts';
+import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
+import { authorizePageVisibility } from './page-visibility.ts';
+import { withFilesystemPublication } from './filesystem-guard.ts';
+import { isWriteTargetContained } from '../path-confine.ts';
+import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
+import { decoratePublicationOutcome, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, publishMutation, publishPersistenceFile,
+ recoverPublication, type PreparedMutation } from './coordinator.ts';
+
+/** A `put_pages` group publishes at most this many pages per transaction, so one commit stays a few seconds long. */
+export const PAGE_BATCH_GROUP_MAX = 8;
+
+function syncMember(row: WriteRequest): boolean {
+ return row.operation === 'submit_job' && (row.intent?.kind === 'managed_sync_import' || row.intent?.kind === 'managed_sync_delete');
+}
/** Whether a prepared member can share a group transaction. */
export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {
- return row.operation === 'submit_job' && (row.intent?.kind === 'managed_sync_import' || row.intent?.kind === 'managed_sync_delete')
- && (row.target_kind ?? 'page') === 'page' && prepared.target !== 'skill_bundle' && !prepared.file && !prepared.sourceExclusive && typeof prepared.validate === 'function';
+ if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive) return false;
+ if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';
+ return publicationGroupKey(row)?.startsWith('batch:') === true;
+}
+
+const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();
+/**
+ * Reads a group transaction repeats for every member and whose answer cannot
+ * change before it commits: rows the transaction already holds FOR SHARE (the
+ * source and the writer registration, so the source's local path too) and the
+ * owner's host binding (its worktree row is held FOR SHARE by the ownership
+ * guard). Nothing in a page publication writes them.
+ */
+const STABLE_IN_GROUP = new Set([
+ 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE',
+ 'SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid FOR SHARE',
+ 'SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',
+ 'SELECT h.local_path FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id AND w.owner_host_id=h.host_id WHERE w.id=$1::uuid',
+]);
+/**
+ * #6007: the group transaction seen through a per-transaction read snapshot.
+ * The stable reads above and config values (`getConfig`, one consistent value
+ * per key for every member) are answered once; every other call reaches the
+ * transaction unchanged. It lives only for one group transaction, so nothing
+ * survives a rollback.
+ */
+function groupReads(tx: BrainEngine): BrainEngine {
+ const reads = new Map<string, Promise<unknown>>();
+ const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {
+ let value = reads.get(id) as Promise<T> | undefined;
+ if (!value) { value = read(); reads.set(id, value); value.catch(() => reads.delete(id)); }
+ return value;
+ };
+ return new Proxy(tx, { get(target, key) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) =>
+ STABLE_IN_GROUP.has(flat(sql)) ? once(JSON.stringify([flat(sql), params ?? null]), () => target.executeRaw(sql, params, opts)) : target.executeRaw(sql, params, opts);
+ if (key === 'getConfig') return (name: string) => once(`config:${name}`, () => target.getConfig(name));
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
+
+/** Test seams around a group's commit and its rollback. */
+export interface GroupHooks {
+ beforeCommit?(rows: WriteRequest[]): Promise<void>;
+ /** After a failed group transaction and the restoration of any file it published. */
+ rolledBack?(rows: WriteRequest[]): Promise<void>;
}
-/** Publishes the whole group or nothing; null means the transaction did not commit and the claims are untouched. */
-export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId()): Promise<WriteRequest[] | null> {
+/**
+ * Publishes the whole group or nothing. `done` null means the transaction did
+ * not commit; `requeued` lists members whose claims the file restoration
+ * released, which the caller may claim again while it holds the worktree.
+ */
+export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId(),
+ hooks: GroupHooks = {}): Promise<{ done: WriteRequest[] | null; requeued: string[] }> {
const head = rows[0];
- if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || !groupable(row, prepared[i]!))) return null;
+ const none = { done: null, requeued: [] };
+ if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!))) return none;
const binding = await getWorktreeBinding(engine, head.source_id, hostId);
- if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return null;
+ if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return none;
const lock = await acquireWorktree(binding, 0, undefined, engine);
- if (!lock) return null;
+ if (!lock) return none;
let releaseCapacity: (() => void) | null = null;
+ const recorded = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();
+ let committed = false;
try {
const blocked = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND NOT (id=ANY($2::uuid[])) AND recovery IS NOT NULL
UNION ALL SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1`, [head.worktree_id, rows.map(row => row.id)]);
- if (blocked.length) return null;
+ if (blocked.length) return none;
releaseCapacity = tryAcquirePublicationCapacity(engine);
- if (!releaseCapacity) return null;
- return await engine.transaction(async tx => {
+ if (!releaseCapacity) return none;
+ const files = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();
+ for (let i = 0; i < rows.length; i++) {
+ const file = prepared[i]!.file;
+ if (!file || prepared[i]!.noop) continue;
+ if (!isWriteTargetContained(file.path, file.root)) return none;
+ const member = { row: rows[i]!, ...pageRecoveryRecord(rows[i]!, file, binding) };
+ // A file that moved since preparation takes the single path, which decides between reprepare and refusal.
+ if (file.expectedBeforeHash !== undefined && member.record.beforeHash !== file.expectedBeforeHash) return none;
+ files.set(i, member);
+ }
+ if (files.size) {
+ await prepareRecoveries(engine, [...files.values()]);
+ for (const [i, member] of files) recorded.set(i, member);
+ }
+ const done = await engine.transaction(async transaction => {
+ const tx = groupReads(transaction);
await declareDurablePersistence(tx);
const live = await guardOwnership(tx, head, hostId);
if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.', 'Inspect the source owner with gbrain sources writer status; do not claim or transfer the source to push this write.');
+ if (recorded.size) {
+ // A published file needs recovery even if this transaction rolls back; claims are verified first.
+ const members = [...recorded.values()].map(member => member.row);
+ const started = await tx.executeRaw(`UPDATE persistence_requests r SET publication_started=true FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token)
+ WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' RETURNING r.id`, [members.map(row => row.id), members.map(row => row.execution_token)]);
+ if (started.length !== members.length) throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');
+ if (await sourceMirrorReadOnly(tx, head.source_id, true)) throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared.', 'The members publish one at a time.');
+ }
await tx.lockPageKeys(rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug }, ...(prepared[i]!.additionalPageKeys ?? [])]));
const outcomes: Record<string, unknown>[] = [];
// One coordinated write for the group; each member is the attributed actor of what it writes.
await withCoordinatedWrite(tx, [head.source_id], async () => {
for (let i = 0; i < rows.length; i++) {
- const row = rows[i]!, member = prepared[i]!;
- await authorizeStoredRequest(tx, row, true);
+ const row = rows[i]!, member = prepared[i]!, file = recorded.get(i);
+ await authorizeStoredRequest(tx, row, true, { pageVisibility: false });
+ if (!syncMember(row)) await assertKnowledgePublicationAllowed(tx, row, member.file);
const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ await authorizePageVisibility(tx, row.authority, row.slug);
if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.', 'Read the page again and submit a new intent with a new request_id.');
await assertUnboundPublication(tx, row, snapshot?.page.source_path);
if ((snapshot?.revision ?? null) !== member.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');
await member.validate?.(tx);
+ if (file) {
+ if (persistenceFileHash(file.record.path) !== file.record.beforeHash) throw new OperationError('unexpected_file_bytes', 'The canonical file changed during preparation.', 'The members publish one at a time.');
+ await withFilesystemPublication([file.record.root], async () => publishPersistenceFile(member.file!, file.record.staging?.publication?.path));
+ }
await setMemberAttribution(tx, requestAttribution(row));
const outcome = await member.apply(tx);
await classifyUnboundPage(tx, row);
if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
- decoratePublicationOutcome(row, member, outcome, final, 0, false);
- await queuePublicationEffects(tx, row, final, outcome, member);
+ decoratePublicationOutcome(row, member, outcome, final, file ? 1 : 0, false);
+ await queuePublicationEffects(tx, row, final, outcome, member, { deferBatchReconcile: true });
outcomes.push(outcome);
}
}, requestAttribution(head));
@@ -92,10 +193,36 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if (!locked || locked.execution_token !== rows[i]!.execution_token || locked.state !== 'running') throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');
done.push(await completeWrite(tx, locked, 'committed', outcomes[i]!, undefined, locked));
}
+ // Every member is complete in this transaction: the batch's last page re-arms the batch's mention links once.
+ const last = rows[rows.length - 1]!;
+ if (publicationGroupKey(last)?.startsWith('batch:') && queuesMentionLinks(last)) await reconcileFinishedBatch(tx, last);
+ await hooks.beforeCommit?.(rows);
return done;
});
+ committed = true;
+ if (recorded.size) {
+ try { await clearResolvedRecoveries(engine, done); }
+ catch {
+ // The ordinary recovery pass finishes cleanup of a committed receipt, or blocks its worktree on unexpected bytes.
+ for (const row of done) if (row.recovery) {
+ try { await recoverPublication(engine, row.id, hostId, true, undefined, true); } catch { /* the recovery scan retries */ }
+ }
+ }
+ }
+ return { done, requeued: [] };
} catch {
- return null;
+ if (committed || !recorded.size) { await hooks.rolledBack?.(rows); return none; }
+ // Restore every file this group may have published and release those claims; a committed member (an uncertain commit) only cleans up.
+ const requeued: string[] = [];
+ for (const { row } of recorded.values()) {
+ try {
+ await markRecovering(engine, row, 'publication_not_started');
+ const recovered = await recoverPublication(engine, row.id, hostId, true, undefined, true);
+ if (recovered.state === 'queued' && !recovered.recovery) requeued.push(row.id);
+ } catch { /* the recovery record stays; the worktree waits for the recovery scan */ }
+ }
+ await hooks.rolledBack?.(rows);
+ return { done: null, requeued };
} finally {
releaseCapacity?.();
await lock.release();
@@ -106,6 +233,7 @@ export interface GroupExecution {
prepare(row: WriteRequest): Promise<PreparedMutation>;
settled(row: WriteRequest): void;
hostId: string;
+ hooks?: GroupHooks;
}
/**
@@ -122,21 +250,33 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
interval.unref?.();
try {
const prepared: Array<{ ok: PreparedMutation } | { error: unknown }> = new Array(rows.length);
- for (let start = 0; start < rows.length; start += 4) {
- await Promise.all(rows.slice(start, start + 4).map(async (row, offset) => {
+ // A put_pages group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
+ const width = publicationGroupKey(rows[0]!)?.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX : 4;
+ for (let start = 0; start < rows.length; start += width) {
+ await Promise.all(rows.slice(start, start + width).map(async (row, offset) => {
try { prepared[start + offset] = { ok: await run.prepare(row) }; } catch (error) { prepared[start + offset] = { error }; }
}));
}
+ // A put_pages batch is independent page writes: one page's failure never cancels its siblings.
+ const independent = publicationGroupKey(rows[0]!)?.startsWith('batch:') === true;
+ let requeued = new Set<string>();
if (prepared.every(p => 'ok' in p)) {
- const done = await publishGroup(engine, rows, prepared.map(p => (p as { ok: PreparedMutation }).ok), run.hostId);
- if (done) { for (const row of done) run.settled(row); return true; }
+ const result = await publishGroup(engine, rows, prepared.map(p => (p as { ok: PreparedMutation }).ok), run.hostId, run.hooks);
+ if (result.done) { for (const row of result.done) run.settled(row); return true; }
+ requeued = new Set(result.requeued);
}
let progressed = false, stop: 'cancel' | 'release' | null = null;
for (let i = 0; i < rows.length; i++) {
- const row = rows[i]!;
- const current = await getWriteRequestById(engine, row.id);
+ let row = rows[i]!;
+ let current = await getWriteRequestById(engine, row.id);
+ // A claim the group's file restoration released is taken back, in order, while this pass still owns the worktree.
+ if (current?.state === 'queued' && requeued.has(row.id) && stop === null) {
+ const reclaimed = await reclaimReleasedWrite(engine, row.id);
+ if (reclaimed) { row = reclaimed; current = reclaimed; }
+ }
if (!current || current.execution_token !== row.execution_token || current.state !== 'running') {
- if (current && ['committed', 'conflict', 'failed', 'cancelled'].includes(current.state)) { run.settled(current); progressed = true; if (current.state !== 'committed') stop ??= 'cancel'; }
+ if (current && ['committed', 'conflict', 'failed', 'cancelled'].includes(current.state)) { run.settled(current); progressed = true; if (current.state !== 'committed' && !independent) stop ??= 'cancel'; }
+ else if (independent) stop ??= 'release';
continue;
}
if (stop === 'release') { await releaseUnpublishedClaim(engine, row, 'group_member_waiting'); continue; }
@@ -149,7 +289,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
const done = 'ok' in p ? await publishMutation(engine, row, p.ok, run.hostId) : await finishUnpublishedFailure(engine, current, p.error, 'preparation');
run.settled(done);
if (done.state === 'committed') { progressed = true; continue; }
- if (['conflict', 'failed', 'cancelled'].includes(done.state)) { progressed = true; stop = 'cancel'; } else stop = 'release';
+ if (['conflict', 'failed', 'cancelled'].includes(done.state)) { progressed = true; if (!independent) stop = 'cancel'; } else stop = 'release';
}
return progressed;
} finally {
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 7014eac985..71538cbc2e 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -277,11 +277,23 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
* stopping at the first row that is not a queued member of the group. A member
* is never claimed past an unfinished non-member, so the FIFO order holds.
*/
+/**
+ * The publication group key of a request: a bulk sync's `intent.group`, or the
+ * batch id of a `put_pages` child (`intent.page_batch.id`, #6007). Null when it
+ * publishes alone.
+ */
+export function publicationGroupKey(row: Pick<WriteRequest, 'operation' | 'intent'>): string | null {
+ if (typeof row.intent?.group === 'string') return `sync:${row.intent.group}`;
+ const batch = row.intent?.page_batch as { id?: unknown } | undefined;
+ return row.operation === 'put_page' && !row.intent?.kind && typeof batch?.id === 'string' ? `batch:${batch.id}` : null;
+}
+const GROUP_KEY_SQL = `CASE WHEN intent ? 'group' THEN 'sync:'||(intent->>'group')
+ WHEN operation='put_page' AND NOT (intent ? 'kind') AND jsonb_typeof(intent->'page_batch'->'id')='string' THEN 'batch:'||(intent->'page_batch'->>'id') END`;
export async function claimGroupFollowers(engine: BrainEngine, head: WriteRequest, group: string, max: number, leaseMs = 30_000): Promise<WriteRequest[]> {
if (!head.worktree_id || max <= 0) return [];
return engine.transactionDirect(async tx => {
await declarePersistenceProtocol(tx);
- const next = await tx.executeRaw<{ id: string; state: string; grp: string | null; recovering: boolean }>(`SELECT id,state,intent->>'group' AS grp,recovery IS NOT NULL AS recovering
+ const next = await tx.executeRaw<{ id: string; state: string; grp: string | null; recovering: boolean }>(`SELECT id,state,${GROUP_KEY_SQL} AS grp,recovery IS NOT NULL AS recovering
FROM persistence_requests WHERE worktree_id=$1::uuid AND sequence>$2 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL)
ORDER BY sequence LIMIT $3 FOR UPDATE`, [head.worktree_id, head.sequence, max]);
const members: string[] = [];
@@ -380,20 +392,20 @@ export async function hasClaimableWrite(engine: SqlEngine, hostId: string, exclu
return row?.claimable === true;
}
-/**
- * Claims commit before OS-lock waits. An unresolved head blocks its entire
- * root. #6007: one autocommit statement on the direct route selects, locks
- * (skipping locked rows) and claims the head.
- */
+/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */
export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = []): Promise<WriteRequest | null> {
- const [claimed] = await engine.executeRawDirect<WriteRequest>(`UPDATE persistence_requests SET state='running',
- execution_token=$3::uuid,claim_expires_at=now()+($4::double precision*interval '1 millisecond'),
- updated_at=now(),blocked_reason=NULL
- WHERE id=(SELECT r.id FROM persistence_requests r
+ return engine.transactionDirect(async tx => {
+ await declarePersistenceProtocol(tx);
+ const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE ${CLAIMABLE_WRITE_SQL}
- ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED) AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [hostId, excludeRoots, randomUUID(), leaseMs]);
- return claimed ?? null;
+ ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots]);
+ if (!row) return null;
+ const [claimed] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',
+ execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),
+ updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *`, [row.id, randomUUID(), leaseMs]);
+ return claimed;
+ });
}
export async function renewWriteClaim(engine: SqlEngine, id: string, token: string, leaseMs = 30_000, signal?: AbortSignal): Promise<boolean> {
const rows = await engine.executeRaw(`UPDATE persistence_requests SET
@@ -444,6 +456,64 @@ export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, re
});
}
+/**
+ * #6007 grouped publication: records every member's recovery record in one
+ * transaction, before any of their files is touched. All or nothing: a member
+ * whose claim moved, or that already holds a record, fails the whole call and
+ * nothing is recorded.
+ */
+export async function prepareRecoveries(engine: BrainEngine, members: { row: WriteRequest; record: RecoveryRecord; bytes: number }[]): Promise<void> {
+ if (!members.length) return;
+ const worktree = members[0]!.row.worktree_id;
+ if (!worktree || members.some(member => member.row.worktree_id !== worktree)) throw new TypeError('Grouped filesystem recovery requires one worktree.');
+ const limits = await readJournalLimits(engine);
+ const total = members.reduce((sum, member) => sum + member.bytes, 0);
+ if (members.some(member => member.bytes > limits.worktreeRecoveryBytes || member.bytes > limits.brainRecoveryBytes)) {
+ throw new OperationError('request_too_large', 'This request exceeds the configured recovery capacity.', 'Increase recovery capacity before submitting a new request.');
+ }
+ await engine.transaction(async tx => {
+ await declareDurablePersistence(tx);
+ const counters = await lockCounters(tx, ['brain', `worktree:${worktree}`]);
+ for (const c of counters) if (Number(c.recovery_bytes) + total > (c.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) throw capacityError('recovery bytes currently reserved by other requests');
+ const recorded = await tx.executeRaw(`WITH recorded AS (UPDATE persistence_requests r SET recovery=t.record,recovery_bytes=t.bytes,updated_at=now()
+ FROM jsonb_to_recordset($1::text::jsonb) AS t(id uuid,token uuid,record jsonb,bytes bigint)
+ WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' AND r.recovery IS NULL RETURNING r.id),
+ reserved AS (UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$2 WHERE key=ANY($3::text[]) AND (SELECT count(*) FROM recorded)=$4)
+ SELECT id FROM recorded`, [JSON.stringify(members.map(member => ({ id: member.row.id, token: member.row.execution_token, record: member.record, bytes: member.bytes }))),
+ total, counters.map(c => c.key), members.length]);
+ if (recorded.length !== members.length) throw opError('write_claim_lost', 'A grouped write claim changed before its recovery was recorded.',
+ 'Another owner pass holds one of the grouped requests; the group publishes nothing and its members publish one at a time.');
+ });
+}
+
+/** Clears the resolved recovery records of a committed group in one transaction; a record that changed is cleared on its own. */
+export async function clearResolvedRecoveries(engine: BrainEngine, rows: WriteRequest[]): Promise<void> {
+ const resolved = rows.filter(row => row.recovery && isTerminal(row));
+ if (resolved.length < 2) { for (const row of resolved) await clearResolvedRecovery(engine, row.id, row); return; }
+ for (const row of resolved) for (const file of recoveryFiles(row.recovery!)) assertRecoveryStagingAbsent(file);
+ const worktree = resolved[0]!.worktree_id;
+ const cleared = new Set((await engine.transaction(async tx => {
+ await declareDurablePersistence(tx);
+ const keys = ['brain', ...(worktree ? [`worktree:${worktree}`] : [])];
+ await lockCounters(tx, keys);
+ return tx.executeRaw<{ id: string }>(`WITH locked AS (SELECT r.id,r.recovery_bytes FROM persistence_requests r
+ JOIN jsonb_to_recordset($1::text::jsonb) AS t(id uuid,record jsonb) ON t.id=r.id
+ WHERE r.recovery=t.record AND r.worktree_id IS NOT DISTINCT FROM $3::uuid AND r.state IN ('committed','conflict','failed','cancelled') FOR UPDATE OF r),
+ released AS (UPDATE persistence_counters SET recovery_bytes=recovery_bytes-(SELECT COALESCE(SUM(recovery_bytes),0) FROM locked) WHERE key=ANY($2::text[]))
+ UPDATE persistence_requests r SET recovery=NULL,recovery_bytes=0,blocked_reason=NULL FROM locked WHERE r.id=locked.id RETURNING r.id`,
+ [JSON.stringify(resolved.map(row => ({ id: row.id, record: row.recovery }))), keys, worktree]);
+ })).map(row => row.id));
+ for (const row of resolved) if (!cleared.has(row.id)) await clearResolvedRecovery(engine, row.id);
+}
+
+/** #6007: claims again a request this owner pass released to the queue itself, while it still holds the worktree's native lock. */
+export async function reclaimReleasedWrite(engine: BrainEngine, id: string, leaseMs = 30_000): Promise<WriteRequest | null> {
+ const [claimed] = await engine.executeRawDirect<WriteRequest>(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,
+ claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL
+ WHERE id=$1::uuid AND state='queued' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, randomUUID(), leaseMs]);
+ return claimed ?? null;
+}
+
/** In the SAME transaction as page publication. Counters are always before request locks. */
export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'committed' | 'conflict' | 'failed' | 'cancelled',
outcome: Record<string, unknown>, error?: { code: string; message: string; detail?: unknown },
diff --git a/test/e2e/page-guards-postgres.test.ts b/test/e2e/page-guards-postgres.test.ts
index 15fb118cde..02f55bedae 100644
--- a/test/e2e/page-guards-postgres.test.ts
+++ b/test/e2e/page-guards-postgres.test.ts
@@ -1,9 +1,9 @@
/**
- * #6007: set-based page guards and counter locks on real Postgres, with
- * concurrent transactions on separate pooled connections. lockPageKeys takes
- * the source share locks, the guard rows and the pages rows in three
- * statements; a transaction (and its savepoints) never re-acquires a key it
- * holds; lockCounters creates and locks a counter set in one statement.
+ * #6007: page guards and counter locks on real Postgres, with concurrent
+ * transactions on separate pooled connections. A transaction (and its
+ * savepoints) never re-acquires a key it holds, including a key whose pages
+ * row is absent: the only pages INSERT runs after putPage takes the same
+ * guard. lockCounters creates and locks counter sets in key order.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { hasDatabase } from './helpers.ts';
@@ -35,7 +35,7 @@ function holdTransaction(engine: BrainEngine, body: (tx: BrainEngine) => Promise
return { entered, release, done };
}
-d('#6007 set-based page guards on Postgres', () => {
+d('#6007 page guards on Postgres', () => {
let engine: PostgresEngine;
let close: () => Promise<void>;
beforeAll(async () => {
@@ -137,7 +137,7 @@ d('#6007 set-based page guards on Postgres', () => {
});
});
-d('#6007 one-statement counter locks on Postgres', () => {
+d('#6007 counter locks on Postgres', () => {
let engine: PostgresEngine;
let close: () => Promise<void>;
beforeAll(async () => { ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!)); }, 120_000);
diff --git a/test/e2e/persistence-statement-budget.test.ts b/test/e2e/persistence-statement-budget.test.ts
index 53a37dbc15..540f86b28f 100644
--- a/test/e2e/persistence-statement-budget.test.ts
+++ b/test/e2e/persistence-statement-budget.test.ts
@@ -33,12 +33,12 @@ const CRITICAL: Phase[] = ['admission', 'claim', 'prepare', 'recovery_record', '
/**
* Per-phase statement budgets, about 10% above the measured counts (#6007
- * measured admission 25, claim 2, prepare 19, recovery record 6, publication
- * 52, completion 6: 110 on the critical path, and an 8-statement receipt; the
+ * measured admission 25, claim 9, prepare 19, recovery record 6, publication
+ * 54, completion 6: 119 on the critical path, and an 8-statement receipt; the
* code before #6007 measured 29, 9, 21, 9, 61, 10: 139, and 10).
*/
const BUDGET: Record<string, number> = {
- admission: 28, claim: 3, prepare: 21, recovery_record: 7, publication: 57, completion: 7, critical_path: 121, receipt: 9,
+ admission: 28, claim: 10, prepare: 21, recovery_record: 7, publication: 60, completion: 7, critical_path: 131, receipt: 9,
};
const SCAN = [
diff --git a/test/e2e/put-pages-group-postgres.test.ts b/test/e2e/put-pages-group-postgres.test.ts
new file mode 100644
index 0000000000..8026919d9c
--- /dev/null
+++ b/test/e2e/put-pages-group-postgres.test.ts
@@ -0,0 +1,159 @@
+/**
+ * #6007: a put_pages batch publishes on Postgres as grouped transactions
+ * (group-publish.ts): one claim, one recovery-record transaction, one
+ * publication transaction and one cleanup transaction for up to eight pages,
+ * files included. Any member failure rolls the group back, restores every file
+ * it published, and the members then publish one at a time so the failure is
+ * attributed to its own page.
+ */
+import { describe, expect, test as bunTest } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { hasDatabase } from './helpers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer, preparePersistedMutation } from '../../src/core/persistence/service.ts';
+import { claimGroupFollowers, claimNextWrite, publicationGroupKey } from '../../src/core/persistence/journal.ts';
+import { executeClaimedGroup } from '../../src/core/persistence/group-publish.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+const config = { engine: 'postgres' as const, embedding_disabled: true };
+let engine: PostgresEngine;
+let root: string;
+let registration: LocalRegistration;
+const page = (slug: string, body: string) => ({ slug, content: `---\ntitle: ${slug}\ntype: note\n---\n\n${body}\n` });
+
+function test(name: string, run: () => Promise<void>) {
+ bunTest(name, async () => {
+ const fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-group-pg-'));
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine;
+ root = join(fixtureDir, 'brain'); mkdirSync(root);
+ _resetWriteThroughCacheForTest();
+ try {
+ await withEnv({ GBRAIN_HOME: join(fixtureDir, 'home') }, async () => {
+ await engine.setConfig('sync.repo_path', root);
+ await claimWorktree(engine, 'default', root);
+ registration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['default'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'] });
+ try { await run(); } finally { await disposePersistenceConsumer(engine); }
+ });
+ } finally {
+ _resetWriteThroughCacheForTest();
+ await pg.close();
+ rmSync(fixtureDir, { recursive: true, force: true });
+ }
+ }, 60_000);
+}
+async function dispatch(name: string, params: Record<string, unknown>) {
+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, name, params, {
+ remote: true, config, sourceId: 'default',
+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] },
+ logger: { info() {}, warn() {}, error() {} },
+ }));
+ return JSON.parse((response.content[0] as { text: string }).text) as Record<string, any>;
+}
+const requests = () => engine.executeRaw<WriteRequest & { published: string | null }>(
+ "SELECT *,published_at::text AS published FROM persistence_requests WHERE operation='put_page' ORDER BY sequence");
+const recoveryBytes = async () => engine.executeRaw<{ key: string; n: number }>('SELECT key,recovery_bytes::int AS n FROM persistence_counters WHERE recovery_bytes<>0');
+
+d('#6007 grouped put_pages publication on Postgres', () => {
+ test('a batch publishes its file-bearing pages in one transaction with per-page receipts, files, effects and re-armed links', async () => {
+ const slugs = ['notes/g-1', 'notes/g-2', 'notes/g-3', 'notes/g-4'];
+ const result = await dispatch('put_pages', { request_id: randomUUID(), pages: slugs.map((slug, i) => page(slug, `Grouped body ${i} links [[${slugs[(i + 1) % 4]}]].`)), wait_ms: 20_000 });
+ expect(result).toMatchObject({ state: 'committed', counts: { total: 4, committed: 4 } });
+ const rows = await requests();
+ expect(rows.map(row => row.state)).toEqual(['committed', 'committed', 'committed', 'committed']);
+ expect(rows.every(row => publicationGroupKey(row) === publicationGroupKey(rows[0]!))).toBe(true);
+ // now() is the transaction start: one shared publication timestamp proves one transaction.
+ expect(new Set(rows.map(row => row.published)).size).toBe(1);
+ expect(rows.every(row => row.recovery === null && row.publication_started)).toBe(true);
+ expect(await recoveryBytes()).toEqual([]);
+ for (const [i, slug] of slugs.entries()) {
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain(`Grouped body ${i}`);
+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page.compiled_truth).toContain(`Grouped body ${i}`);
+ }
+ const effects = await engine.executeRaw<{ kind: string; n: number; reconciled: number }>(`SELECT kind,count(*)::int AS n,
+ count(*) FILTER (WHERE data ? 'batch_reconciled')::int AS reconciled FROM persistence_effects GROUP BY kind ORDER BY kind`);
+ expect(Object.fromEntries(effects.map(e => [e.kind, e.n]))).toMatchObject({ git: 4, embedding: 4, links: 4 });
+ expect(effects.find(e => e.kind === 'links')!.reconciled).toBe(4);
+ const attributed = await engine.executeRaw<{ slug: string; request: string }>(`SELECT slug,revision_write_request_id::text AS request FROM pages WHERE slug=ANY($1) ORDER BY slug`, [slugs]);
+ expect(attributed.map(row => row.request)).toEqual(rows.map(row => row.id));
+ });
+
+ test('a member failure rolls the group back, restores its published files and publishes the members one at a time', async () => {
+ const existing = join(root, 'notes', 'f-1.md');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ // The first page replaces an existing file so restoration has original bytes to bring back.
+ expect((await dispatch('put_page', { ...page('notes/f-1', 'Original canonical body.'), request_id: randomUUID() })).state).toBe('committed');
+ const original = readFileSync(existing, 'utf8');
+ const [current] = await engine.executeRaw<{ revision: string }>("SELECT knowledge_revision::text AS revision FROM pages WHERE slug='notes/f-1'");
+ await disposePersistenceConsumer(engine);
+ // Hold the worktree so the admission's consumer cannot publish; the test drives the claim itself.
+ const holder = await acquireWorktree((await getWorktreeBinding(engine, 'default'))!, 5000);
+ expect(holder).not.toBeNull();
+ let batch: Record<string, any>;
+ try {
+ batch = await dispatch('put_pages', { request_id: randomUUID(), wait_ms: 0, pages: [
+ { ...page('notes/f-1', 'Replacement body.'), expected_revision: current!.revision },
+ page('notes/f-2', 'Refused body.'), page('notes/f-3', 'Third body.')] });
+ expect(batch.state).toBe('pending');
+ 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");
+ const head = (await claimNextWrite(engine, localHostId()))!;
+ expect(head.slug).toBe('notes/f-1');
+ const followers = await claimGroupFollowers(engine, head, publicationGroupKey(head)!, 7);
+ expect(followers.map(row => row.slug)).toEqual(['notes/f-2', 'notes/f-3']);
+ const settled: WriteRequest[] = [];
+ let restoredBytes: string | undefined;
+ let stagingLeft = true;
+ const progressed = await executeClaimedGroup(engine, [head, ...followers], {
+ hostId: localHostId(),
+ prepare: async row => {
+ const prepared = await preparePersistedMutation(engine, row, config as never);
+ if (row.slug !== 'notes/f-2') return prepared;
+ return { ...prepared, validate: async () => { throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Fixture refusal.'); } };
+ },
+ settled: row => settled.push(row),
+ hooks: { rolledBack: async () => {
+ restoredBytes = readFileSync(existing, 'utf8');
+ stagingLeft = (await engine.executeRaw('SELECT id FROM persistence_requests WHERE recovery IS NOT NULL')).length > 0;
+ } },
+ });
+ expect(progressed).toBe(true);
+ // The group had replaced f-1's file before f-2 failed; the rollback put the original bytes back first.
+ expect(restoredBytes).toBe(original);
+ expect(stagingLeft).toBe(false);
+ expect(existsSync(join(root, 'notes', 'f-2.md'))).toBe(false);
+ const rows = await requests();
+ const bySlug = Object.fromEntries(rows.filter(row => row.intent?.page_batch).map(row => [row.slug, row]));
+ expect(bySlug['notes/f-1']!.state).toBe('committed');
+ expect(bySlug['notes/f-2']!.state).toBe('conflict');
+ expect(bySlug['notes/f-2']!.error_code).toBe('revision_conflict');
+ expect(bySlug['notes/f-3']!.state).toBe('committed');
+ expect(new Set([bySlug['notes/f-1']!.published, bySlug['notes/f-3']!.published]).size).toBe(2);
+ expect(settled.map(row => [row.slug, row.state])).toEqual([['notes/f-1', 'committed'], ['notes/f-2', 'conflict'], ['notes/f-3', 'committed']]);
+ expect(readFileSync(existing, 'utf8')).toContain('Replacement body.');
+ expect(readFileSync(join(root, 'notes', 'f-3.md'), 'utf8')).toContain('Third body.');
+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE slug='notes/f-2'")).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE recovery IS NOT NULL')).toEqual([]);
+ expect(await recoveryBytes()).toEqual([]);
+ const effects = await engine.executeRaw<{ slug: string; kind: string }>(`SELECT r.slug,e.kind FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE r.intent ? 'page_batch' AND e.kind IN ('git','embedding') ORDER BY r.slug,e.kind`);
+ expect(effects.map(e => `${e.slug}:${e.kind}`)).toEqual(['notes/f-1:embedding', 'notes/f-1:git', 'notes/f-3:embedding', 'notes/f-3:git']);
+ const attributed = await engine.executeRaw<{ slug: string; request: string }>("SELECT slug,revision_write_request_id::text AS request FROM pages WHERE slug IN ('notes/f-1','notes/f-3') ORDER BY slug");
+ expect(attributed.map(row => row.request)).toEqual([bySlug['notes/f-1']!.id, bySlug['notes/f-3']!.id]);
+ // The receipt reads the per-page outcomes back.
+ const status = await dispatch('put_pages', { request_id: batch!.batch_request_id });
+ expect(status).toMatchObject({ state: 'partial', counts: { committed: 2, failed: 1 } });
+ });
+});
diff --git a/test/page-embedding-install-batch.test.ts b/test/page-embedding-install-batch.test.ts
index 1d3b1cfc56..c70b48358f 100644
--- a/test/page-embedding-install-batch.test.ts
+++ b/test/page-embedding-install-batch.test.ts
@@ -1,8 +1,7 @@
/**
- * #6007: installPageEmbeddings writes every chunk's vector, image, model,
- * input hash and embedded stamps in one set-based UPDATE. Each case pins the
- * per-chunk semantics the old one-UPDATE-per-chunk loop had, on PGLite and
- * (with DATABASE_URL) an isolated Postgres database.
+ * installPageEmbeddings per-chunk semantics: each chunk's vector, image,
+ * model, input hash and embedded stamps, on PGLite and (with DATABASE_URL) an
+ * isolated Postgres database.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -21,7 +20,7 @@ interface Row { chunk_index: number; chunk_text: string; embedding: string | nul
embedded_at: string | null; embedded_text_hash: string | null; embedding_input_hash: string | null; text_md5: string }
for (const kind of testBackends()) {
- describe(`set-based embedding install (${kind})`, () => {
+ describe(`embedding install per chunk (${kind})`, () => {
let engine: BrainEngine;
let closePostgres: (() => Promise<void>) | undefined;
beforeAll(async () => {