Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(persistence): reserved transactions send the declaration with BEGIN too; lane groups keep waiting (GBRA-156)

garrytan1ad2a979ad69
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 16a2cfc28d..ac94874a00 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -44,7 +44,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` (over 24 MiB: `body-digests.ts`) and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. FENCE REPAIR RECEIPT: `fence_repair` is a reserved `put_page` param; `preparePageAdmission` refuses it (`invalid_params`) on every operation unless the call is a trusted local (`ctx.remote === false`) `put_page` whose value `parseFenceRepairReceipt` accepts; `page-prepare.ts` re-parses it from the stored intent, returns it in the outcome as `fence_repair` and gives the page's file target the `fenceRepairCommit` note for its source-relative path. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode` and `commit`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
-- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`). GBRA-156: `isPersistenceDeclaration` accepts exactly these declarations (transaction-local `set_config` calls and the brain row FOR SHARE). Admission, the FIFO claim, the effect claims and source guards, the receipt true-up and `publicationTransaction` pass it as `TransactionOptions.pipelineFirst`, so behind a transaction-mode pooler the declaration goes out with BEGIN (one round trip less per transaction) while every later statement still waits for BEGIN's answer; if BEGIN fails, only the declaration has run, in autocommit, where it changes nothing. Tests: `test/persistence-pipeline-first.test.ts` (the predicate and the reviewed call sites), `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`.
+- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`). GBRA-156: `isPersistenceDeclaration` accepts exactly these declarations (transaction-local `set_config` calls and the brain row FOR SHARE). Admission, the FIFO claim, the effect claims and source guards, the receipt true-up, the single publication (`coordinator.ts`) and the consumer's lent lane transactions (`consumer.ts` `onLane`, through `reservedTransactions`) pass it as `TransactionOptions.pipelineFirst`, so behind a transaction-mode pooler the declaration goes out with BEGIN (one round trip less per transaction) while every later statement still waits for BEGIN's answer; if BEGIN fails, only the declaration has run, in autocommit, where it changes nothing. A sync lane group's publication passes none: its begun mark must follow BEGIN's answer (`sync-lanes.ts` `awaitLaneBegin`). Tests: `test/persistence-pipeline-first.test.ts` (the predicate and the reviewed call sites), `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`.
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot (`mayReprepare`: `revision_conflict` or, #5385 [R13], `revision_required`, both only when the caller named no `expected_revision`); exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The `add_timeline_entry` receipt carries `bullet`, the rendered Markdown line (#5970): there is no update/remove verb because the page is the system of record, so the caller corrects an entry by editing that line with `edit_page` and the row follows the page (both timeline op descriptions say so; `test/timeline-correction-path-5970.test.ts`). #5251: `add_tag` / `remove_tag` prepare with `deferEmbedding: true` (a tag change leaves every chunk's text as it was, so no `embedding` effect is queued and `embedding_state` reads `deferred`; the stale sweep still covers any chunk the republication left without a vector); the full page republication they ride stays, so the issue stays open. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 605d2ffa27..8c04211304 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -21,7 +21,7 @@ import { runPersistenceEffects } from './effects.ts';
import { settleNoopEmbeddingEffects, type NoopSettleCursor } from './embedding-noop-settle.ts';
import { runCompactionPass } from './compaction-pass.ts';
import { currentEmbeddingSignature } from '../embedding.ts';
-import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { isWriteErrorCode } from './types.ts';
import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
import { OperationError } from '../ops/contract.ts';
@@ -450,7 +450,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
// the lane is given up whatever `run` makes of the error (admission re-runs on the pool and may still succeed).
let lost = false;
const lend = async <R>(fn: (tx: BrainEngine) => Promise<R>): Promise<R> => {
- try { return await conn.transaction!(fn); }
+ // GBRA-156: every lent body (single-write admission and publication, no lane order) opens with the declaration.
+ try { return await conn.transaction!(fn, { pipelineFirst: isPersistenceDeclaration }); }
catch (error) { if (isConnectionLoss(error)) lost = true; throw error; }
};
try {
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 5a0a4e452c..28f8c3253c 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -38,7 +38,7 @@ import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFil
import { assertManagedFilesystemWrite } from './filesystem-guard.ts';
import { beforeStagePath, fileContentBytes, fileContentHash, hashDescriptor, hashFile, isStreamedContent, LARGE_FILE_MIN_BYTES, stageBeforeCopy, stageStreamedContent, type StreamedFileContent } from './large-file.ts';
import { declarePublication, publicationTransaction } from './publication-deadline.ts';
-import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
@@ -610,7 +610,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);
transactionBodyCompleted = true;
return committed;
- });
+ }, { pipelineFirst: isPersistenceDeclaration });
await hooks.boundary?.('after_commit', done);
if (beliefReport.appended && done.state === 'committed') await markBeliefCommits(engine, [row.id]).catch(() => undefined);
if (recovery) {
diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.ts
index 8b7588df82..975c0ade7d 100644
--- a/src/core/persistence/publication-deadline.ts
+++ b/src/core/persistence/publication-deadline.ts
@@ -19,9 +19,9 @@
* The wave 9 yield between groups is outside any one `boundPublication` call, so it never counts against a group.
*/
import { AsyncLocalStorage } from 'node:async_hooks';
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, TransactionOptions } from '../engine.ts';
import { gucMilliseconds, resolveSessionTimeouts } from '../db.ts';
-import { declareDurablePersistence, isPersistenceDeclaration } from './protocol.ts';
+import { declareDurablePersistence } from './protocol.ts';
export const PUBLICATION_CEILING_KEY = 'persistence.publication_ceiling_ms';
/** `persistence.publication_ceiling_ms`' default (60000 to 3600000 accepted). */
@@ -92,15 +92,17 @@ export async function declarePublication(tx: BrainEngine, bound: Pick<BrainEngin
/**
* `engine.transaction`, passing the current publication's signal on as `{ signal }`. An aborted transaction rejects
* while its body may still be parked, so a rejection waits for the body to settle first: nothing (recovery included)
- * acts on the publication while the body can still rename a file. Its bodies open with `declarePublication`, which
- * goes out with BEGIN (GBRA-156); a body that opens with anything else waits for BEGIN's answer.
+ * acts on the publication while the body can still rename a file. `pipelineFirst` (GBRA-156) is for a body that opens
+ * with `declarePublication` and does nothing that needs BEGIN answered first; a lane group's body does (its begun mark
+ * orders the next group's BEGIN), so the group runner passes none.
*/
-export async function publicationTransaction<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+export async function publicationTransaction<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>,
+ { pipelineFirst }: Pick<TransactionOptions, 'pipelineFirst'> = {}): Promise<T> {
const signal = signals.getStore();
- if (!signal) return engine.transaction(fn, { pipelineFirst: isPersistenceDeclaration });
+ if (!signal) return engine.transaction(fn, { pipelineFirst });
let body: Promise<unknown> = Promise.resolve();
try {
- return await engine.transaction(tx => { const run = fn(tx); body = run; return run; }, { signal, pipelineFirst: isPersistenceDeclaration });
+ return await engine.transaction(tx => { const run = fn(tx); body = run; return run; }, { signal, pipelineFirst });
} catch (error) {
await body.then(() => undefined, () => undefined);
const closed = (error as { cause?: { code?: unknown } })?.cause?.code;
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 2984e18d6a..8db39d162a 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -733,7 +733,7 @@ export class PostgresEngine implements BrainEngine {
return rows as unknown as R[];
},
};
- return await fn(Object.assign(conn, { transaction: <R>(run: (engine: BrainEngine) => Promise<R>) => this.transactionOn(reservedTransactions(reserved), run) } satisfies ReservedTransactions));
+ return await fn(Object.assign(conn, { transaction: <R>(run: (engine: BrainEngine) => Promise<R>, opts?: TransactionOptions) => this.transactionOn(reservedTransactions(reserved), run, opts) } satisfies ReservedTransactions));
} finally {
// Counter/gauge decrements run regardless of release() throwing
// (double-release or socket error must not permanently leak a permit
diff --git a/src/core/postgres-engine/reserved-transactions.ts b/src/core/postgres-engine/reserved-transactions.ts
index e0e202a6f4..9a940fefc0 100644
--- a/src/core/postgres-engine/reserved-transactions.ts
+++ b/src/core/postgres-engine/reserved-transactions.ts
@@ -1,5 +1,5 @@
import type postgres from '#postgres';
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, TransactionOptions } from '../engine.ts';
/**
* Phase 4.4: what `PostgresEngine.withReservedConnection` adds to its
@@ -8,7 +8,7 @@ import type { BrainEngine } from '../engine.ts';
* connection, so a caller that keeps the reservation reuses them. PGLite's
* reserved connection has none.
*/
-export interface ReservedTransactions { transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> }
+export interface ReservedTransactions { transaction<T>(fn: (engine: BrainEngine) => Promise<T>, opts?: TransactionOptions): Promise<T> }
/**
* Phase 4.4: `begin` for one reserved postgres.js connection, as `sql.begin`
@@ -25,6 +25,15 @@ export interface ReservedTransactions { transaction<T>(fn: (engine: BrainEngine)
* statements behind it in autocommit, so a body sent with it could commit its
* writes outside the transaction; #6930's in-transaction pipelining would
* otherwise send them.
+ *
+ * GBRA-156: `begin({ first }, fn)` makes the one exception the driver's
+ * `sql.begin({ first })` makes. There the body starts at once, but only its
+ * first statement goes out before BEGIN's answer, and only when `first`
+ * accepts its text and every argument is a plain value
+ * (`isPersistenceDeclaration`: transaction-local settings, a no-op in
+ * autocommit). Every other statement, savepoints included, waits for the
+ * answer in order, and a refused BEGIN rejects them unsent. The hold sits on
+ * each query's `handler`, which postgres.js calls when the query is executed.
*/
export function reservedTransactions(reserved: postgres.ReservedSql): ReturnType<typeof postgres> {
const settle = async <T>(marker: Promise<unknown>, body: Promise<T>): Promise<T> => {
@@ -33,20 +42,25 @@ export function reservedTransactions(reserved: postgres.ReservedSql): ReturnType
if (ran.status === 'rejected') throw ran.reason;
return ran.value;
};
- const begin = async (fn: (handle: unknown) => Promise<unknown>) => {
+ const begin = async (options: BeginOptions | Body, body?: Body) => {
+ const fn = typeof options === 'function' ? options : body!;
+ const first = typeof options === 'function' ? undefined : options.first;
+ const pipelines = Number((reserved.options as { max_pipeline?: number } | undefined)?.max_pipeline) > 0;
let savepoints = 0;
+ let gate: ((query: HeldQuery) => HeldQuery) | null = null;
const handle = Object.assign(reserved, {
savepoint: async (inner: (child: unknown) => Promise<unknown>) => {
const name = `s${savepoints++}`;
- const marker = reserved.unsafe(`savepoint ${name}`).execute();
+ const marker = (gate ? gate(reserved.unsafe(`savepoint ${name}`) as unknown as HeldQuery) as unknown as ReturnType<typeof reserved.unsafe> : reserved.unsafe(`savepoint ${name}`)).execute();
try { return await settle(marker, Promise.resolve().then(() => inner(handle))); }
catch (error) { if (await marker.then(() => true, () => false)) await reserved.unsafe(`rollback to ${name}`); throw error; }
},
});
const opened = reserved.unsafe('begin').execute();
- const afterBegin = Number((reserved.options as { max_pipeline?: number } | undefined)?.max_pipeline) > 0 ? Promise.resolve() : opened;
+ if (!pipelines && first) gate = holdBehind(opened, first);
+ const afterBegin = pipelines || gate ? Promise.resolve() : opened;
let result: unknown;
- try { result = await settle(opened, afterBegin.then(() => fn(handle))); }
+ try { result = await settle(opened, afterBegin.then(() => fn(gate ? gated(handle, gate) : handle))); }
catch (error) { await reserved.unsafe('rollback').catch(() => reserved.discard()); throw error; }
const done = await reserved.unsafe('commit') as unknown as { command?: string };
if (done.command !== 'COMMIT') throw Object.assign(new Error('The transaction was rolled back at commit.'), { code: '25P02' });
@@ -55,3 +69,41 @@ export function reservedTransactions(reserved: postgres.ReservedSql): ReturnType
return { begin } as unknown as ReturnType<typeof postgres>;
}
+type Body = (handle: unknown) => Promise<unknown>;
+type BeginOptions = { first?: (statement: string) => boolean };
+/** The parts of a postgres.js query the hold reads and replaces. */
+type HeldQuery = { strings: unknown; args: unknown[]; handler: (query: HeldQuery) => unknown; reject(error: unknown): void };
+
+const plainValue = (x: unknown): boolean => x === null || x === undefined || ['string', 'number', 'bigint', 'boolean'].includes(typeof x)
+ || x instanceof Date || x instanceof Uint8Array || (Array.isArray(x) && x.every(plainValue));
+
+/** GBRA-156: each query's send waits for `opened`, except a first one `first` accepts with only plain-value arguments. */
+function holdBehind(opened: Promise<unknown>, first: (statement: string) => boolean): (query: HeldQuery) => HeldQuery {
+ let answered = false;
+ let firstSeen = false;
+ opened.then(() => { answered = true; }, () => undefined);
+ return query => {
+ const send = query.handler;
+ query.handler = q => {
+ if (answered) return send(q);
+ const strings = Array.isArray(q.strings) ? q.strings as string[] : [String(q.strings)];
+ const early = !firstSeen && q.args.every(plainValue) && first(strings.reduce((a, s, i) => a + '$' + i + s));
+ firstSeen = true;
+ if (early) return send(q);
+ opened.then(() => send(q), error => q.reject(error));
+ };
+ return query;
+ };
+}
+
+/** The handle a held body sees: its statements (tagged, `unsafe`) pass through `gate`; everything else is the reserved connection's. */
+function gated(handle: object, gate: (query: HeldQuery) => HeldQuery): unknown {
+ return new Proxy(handle as (...args: unknown[]) => unknown, {
+ apply: (target, self, args) => gate(Reflect.apply(target, self, args) as HeldQuery),
+ get: (target, key) => {
+ const value = Reflect.get(target, key, target);
+ return key === 'unsafe' ? (...args: unknown[]) => gate((value as (...a: unknown[]) => HeldQuery)(...args)) : value;
+ },
+ });
+}
+
diff --git a/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts b/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
index 79293d2558..49580cb96e 100644
--- a/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
+++ b/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
@@ -267,6 +267,45 @@ describe.skipIf(!(pooled && pooledAdmin))('GBRA-156: a transaction\'s first stat
expect(next.slice(1).filter(sql => /swallowed|^commit|^rollback/i.test(sql))).toEqual([]);
}, 60_000);
+ type Lent = { executeRaw(sql: string): Promise<unknown>; transaction<R>(run: (tx: PostgresEngine) => Promise<R>, opts?: { pipelineFirst?: (s: string) => boolean }): Promise<R> };
+
+ test('a reserved transaction sends the declaration with BEGIN and the rest of its body after BEGIN\'s answer', async () => {
+ const records = await traced('first-reserved', 2, async engine => {
+ await engine.withReservedConnection(conn => (conn as unknown as Lent).transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw('SELECT 1 AS reserved_after_declaration');
+ }, { pipelineFirst: isPersistenceDeclaration }));
+ });
+ const begin = records.find(r => /^begin$/i.test(r.sql))!;
+ const declared = records.find(r => r.sql === declaration)!;
+ const after = records.find(r => /AS reserved_after_declaration$/.test(r.sql))!;
+ expect([declared.conn, after.conn]).toEqual([begin.conn, begin.conn]);
+ expect(declared.t < end(begin)).toBe(true);
+ expect(after.t >= end(begin)).toBe(true);
+ }, 60_000);
+
+ test('a reserved transaction whose BEGIN fails sends nothing past the declaration, even when the body swallows the rejection', async () => {
+ let outcome: string | undefined;
+ let count = -1;
+ const records = await traced('first-reserved-fails', 2, async engine => {
+ outcome = await engine.withReservedConnection(async conn => {
+ const lent = conn as unknown as Lent;
+ // An aborted transaction left on the reserved connection makes the server refuse the next BEGIN (25P02).
+ await lent.executeRaw('BEGIN');
+ await lent.executeRaw('SELECT 1/0 AS abort_reserved').catch(() => undefined);
+ return lent.transaction(async tx => {
+ await tx.executeRaw(declaration).catch(() => undefined);
+ await tx.executeRaw(`INSERT INTO ${table} VALUES (4) /* reserved swallowed */`).catch(() => undefined);
+ return 'returned';
+ }, { pipelineFirst: isPersistenceDeclaration }).then(value => `resolved:${value}`, (e: { code?: string }) => e.code);
+ });
+ count = await rows(engine);
+ });
+ expect(outcome).toBe('25P02');
+ expect(count).toBe(0);
+ expect(records.filter(r => /reserved swallowed/.test(r.sql))).toEqual([]);
+ }, 60_000);
+
test('GBRAIN_PG_TXN_PIPELINE=0 keeps the declaration behind BEGIN\'s answer', async () => {
const records = await traced('first-off', 1, async engine => {
await engine.transaction(tx => declarePersistenceProtocol(tx), { pipelineFirst: isPersistenceDeclaration });
diff --git a/test/persistence-pipeline-first.test.ts b/test/persistence-pipeline-first.test.ts
index 3d030d182e..9f76a87787 100644
--- a/test/persistence-pipeline-first.test.ts
+++ b/test/persistence-pipeline-first.test.ts
@@ -10,6 +10,8 @@ import { join, relative } from 'node:path';
import { declareDurablePersistence, declarePersistenceProtocol, isPersistenceDeclaration } from '../src/core/persistence/protocol.ts';
import { declarePublication } from '../src/core/persistence/publication-deadline.ts';
import type { BrainEngine } from '../src/core/engine.ts';
+import type postgres from '#postgres';
+import { reservedTransactions } from '../src/core/postgres-engine/reserved-transactions.ts';
function recorder(kind = 'postgres'): { engine: BrainEngine; sent: string[] } {
const sent: string[] = [];
@@ -47,7 +49,9 @@ describe('isPersistenceDeclaration', () => {
describe('pipelineFirst call sites', () => {
// Each of these opens its transaction with a protocol declaration (journal admitWrite and claimNextWrite, the effect
- // claims and source guards, the receipt true-up, publicationTransaction). A new opt-in is reviewed here first.
+ // claims and source guards, the receipt true-up, the single publication, the consumer's lent lane transactions) and
+ // needs nothing to happen only after BEGIN's answer (a lane group's begun mark does, so group publication passes none).
+ // A new opt-in is reviewed here first.
test('only the reviewed persistence call sites opt in, and only with isPersistenceDeclaration', () => {
const root = join(import.meta.dir, '..', 'src');
const found: Record<string, number> = {};
@@ -64,11 +68,89 @@ describe('pipelineFirst call sites', () => {
};
walk(root);
expect(found).toEqual({
+ 'core/persistence/consumer.ts': 1,
+ 'core/persistence/coordinator.ts': 1,
'core/persistence/effect-journal.ts': 2,
'core/persistence/effects.ts': 2,
'core/persistence/journal.ts': 3,
- 'core/persistence/publication-deadline.ts': 2,
'core/persistence/receipt-true-up.ts': 1,
});
});
});
+
+/**
+ * A reserved connection on a non-pipelining pool whose queries are lazy like postgres.js's: created by the tagged call or
+ * `unsafe`, sent through their `handler` when executed. Records each send with whether BEGIN had been answered.
+ */
+type LazyQuery = {
+ strings: readonly string[]; args: unknown[]; reject(e: unknown): void; executed: boolean; handler(self: LazyQuery): void; execute(): LazyQuery;
+ then(a?: (v: unknown) => unknown, b?: (e: unknown) => unknown): Promise<unknown>; catch(b: (e: unknown) => unknown): Promise<unknown>;
+};
+function lazyReserved(beginFails: boolean) {
+ const sent: Array<{ text: string; beginAnswered: boolean }> = [];
+ let beginAnswered = false;
+ const query = (strings: readonly string[], args: unknown[]) => {
+ let resolve!: (v: unknown) => void, reject!: (e: unknown) => void;
+ const promise = new Promise((a, b) => { resolve = a; reject = b; });
+ promise.catch(() => undefined);
+ const text = strings.reduce((a, s, i) => a + '$' + i + s);
+ // A thenable, not a native promise: `await` calls its `then`, which executes it, as a postgres.js Query does.
+ const q: LazyQuery = {
+ strings, args, reject, executed: false,
+ handler: self => {
+ sent.push({ text, beginAnswered });
+ if (text === 'begin') setTimeout(() => { beginAnswered = true; beginFails ? self.reject(Object.assign(new Error('no server connection available'), { code: '08P01' })) : resolve(Object.assign([], { command: 'BEGIN' })); }, 20);
+ else resolve(Object.assign([], { command: text.toUpperCase() }));
+ },
+ execute: () => { if (!q.executed) { q.executed = true; void Promise.resolve().then(() => q.handler(q)); } return q; },
+ then: (a, b) => { q.execute(); return promise.then(a, b); },
+ catch: b => q.then(undefined, b),
+ };
+ return q;
+ };
+ const reserved = Object.assign((strings: TemplateStringsArray, ...args: unknown[]) => query([...strings], args), {
+ unsafe: (text: string, args: unknown[] = []) => query([text], args), options: { max_pipeline: 0 }, discard: () => undefined,
+ }) as unknown as postgres.ReservedSql;
+ return { reserved, sent };
+}
+type Handle = { unsafe(text: string, args?: unknown[]): Promise<unknown>; savepoint(fn: (child: unknown) => Promise<unknown>): Promise<unknown> }
+ & ((strings: TemplateStringsArray, ...args: unknown[]) => Promise<unknown>);
+const beginFirst = (reserved: postgres.ReservedSql, body: (sql: Handle) => Promise<unknown>) =>
+ (reservedTransactions(reserved) as unknown as { begin(o: object, fn: typeof body): Promise<unknown> }).begin({ first: isPersistenceDeclaration }, body);
+const DECLARATION = "SELECT set_config('gbrain.persistence_protocol','2',true)";
+
+describe('reserved transactions: the declaration goes out with BEGIN', () => {
+ test('only the accepted declaration is sent before BEGIN\'s answer; the next statement and COMMIT wait', async () => {
+ const { reserved, sent } = lazyReserved(false);
+ await beginFirst(reserved, async sql => { await sql.unsafe(DECLARATION); await sql.unsafe('insert into t values (1)'); });
+ expect(sent).toEqual([{ text: 'begin', beginAnswered: false }, { text: DECLARATION, beginAnswered: false },
+ { text: 'insert into t values (1)', beginAnswered: true }, { text: 'commit', beginAnswered: true }]);
+ });
+
+ test('a refused BEGIN: the declaration ran alone, no write is sent even when the body swallows its rejection, and begin rejects with BEGIN\'s error', async () => {
+ const { reserved, sent } = lazyReserved(true);
+ let swallowed: unknown;
+ const error = await beginFirst(reserved, async sql => {
+ await sql.unsafe(DECLARATION);
+ swallowed = await sql.unsafe('insert into t values (1)').then(() => 'sent', (e: { code?: string }) => e.code);
+ return 'returned';
+ }).then(() => null, (e: { code?: string }) => e.code);
+ expect(error).toBe('08P01');
+ expect(swallowed).toBe('08P01');
+ expect(sent.map(s => s.text).filter(t => t !== 'rollback')).toEqual(['begin', DECLARATION]);
+ });
+
+ test('a write first, a fragment argument and a savepoint all wait for BEGIN\'s answer', async () => {
+ for (const body of [
+ async (sql: Handle) => { await sql.unsafe('insert into t values (1)'); },
+ async (sql: Handle) => { await sql`SELECT set_config('lock_timeout',${{ fragment: true }},true)`; },
+ async (sql: Handle) => { await sql.savepoint(async () => undefined); },
+ ]) {
+ const { reserved, sent } = lazyReserved(false);
+ await beginFirst(reserved, body);
+ expect(sent[0]).toEqual({ text: 'begin', beginAnswered: false });
+ expect(sent.slice(1).every(s => s.beginAnswered)).toBe(true);
+ }
+ });
+});
+