Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): one global lock order, brain row first, for every journal transaction

garrytan35e0dd8081f0
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index ea9f045570..339d393648 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index bbbe262a28..d54030a883 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 4e31bfa36b..cb2d9420b2 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.60.64.0 -->
+<!-- gbrain-runbook-stamp: 0.60.65.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca4f20c3c0..649180b4ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,40 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.65.0] - 2026-10-05
+
+**Writes no longer stall when a source is added, claimed or archived at the same time.**
+
+On a Postgres brain, adding, claiming or archiving a source while agents were writing made the two wait on each other. One side waited out its 1-second lock timeout, writes were retried, and in many runs every write in flight came back "still pending" instead of committed. Both sides now take their database locks in the same order, so neither waits on the other.
+
+Measured on Postgres 16, directly and through transaction-mode PgBouncer (5 runs each way, 36 writes racing 36 source changes per run, plus 3 forced interleavings of one write against one source change per run):
+
+| | Before | Now |
+| --- | --- | --- |
+| Writes that came back "still pending" instead of committed | 208 of 360 | 0 of 360 |
+| Source changes that failed (11 refused with "retry", 10 claims or archives of a source whose add was refused) | 21 of 360 | 0 of 360 |
+| Lock timeouts (1 s) during the race | 94 | 0 |
+| Lock timeouts in the 30 forced interleavings | 21 | 0 |
+| Deadlocks reported by Postgres | 0 (the 1 s lock timeout fired first) | 0 |
+
+## To take advantage of v0.60.65.0
+
+`gbrain upgrade` does this automatically. There is nothing to configure.
+
+1. **Verify:** while an agent writes, run `gbrain sources add example-probe --path <empty dir> --force` and then `gbrain sources archive example-probe`; the writes commit and both source commands succeed on the first try.
+2. **If writes still come back pending,** run `gbrain sources writer status --json` to see what the owner is running and what is queued behind it.
+
+### Itemized changes
+
+#### Lock order
+- Every journal transaction now locks the brain row (`persistence_brain`) FOR SHARE first, then worktree rows, source rows, counters, requests and page keys. Worktree claims and source topology changes lock the brain row FOR UPDATE before the same rows, so the two orders agree. Before, a write locked its source and counters first and only reached the brain row through the request and effect protocol triggers, which inverted against a concurrent claim or topology change.
+- The lock is taken inside the protocol declaration (`declarePersistenceProtocol`, `declareDurablePersistence` in `src/core/persistence/protocol.ts`), in the same statement as its settings and under its lock timeout, so no transaction gains a round trip. That covers admission, publication, recovery reservation and clearing, completion, grouped publication and page batches.
+- Cancelling a write request and approving a connector retry now declare before locking their source; shared-skill activation takes the brain row FOR UPDATE before declaring, so it never upgrades a shared lock.
+
+#### Tests
+- `test/e2e/persistence-publish-lock-order-postgres.test.ts` pauses a real topology change right after its brain lock, runs an ordinary write until it blocks, then lets the change continue; it also races writes against add, claim and archive. It fails on the previous order with lock timeouts and pending writes and passes now. It runs directly and through PgBouncer (`scripts/e2e-backend-matrix.txt`).
+- The crash robot's lock-order trace has a new rule, `brain_before_rows`: whenever a transaction locks the brain row and any worktree, source or counter row, the brain row comes first. A write to `persistence_requests` or `persistence_effects` counts as the brain-row read its trigger takes. On the previous order the robot reported it for admission, publication, recovery reservation and recovery clearing.
+
## [0.60.64.0] - 2026-10-05
**An agent connected to a remote brain can now save a stack of long pages in under a minute, and gbrain tells it how.**
diff --git a/VERSION b/VERSION
index 5ea8aaeda8..ca43b6c8e3 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.60.64.0
+0.60.65.0
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 919b198a2f..b8c5c5ce53 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -49,6 +49,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `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. `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` 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`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). 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`) and connector retry approval. 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`).
- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 3db202ac2b..d87ca562a2 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 744e831a90..4df6c21e51 100644
--- a/package.json
+++ b/package.json
@@ -218,7 +218,7 @@
"bun": ">=1.4.0"
},
"license": "MIT",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.56",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index becfc3a0b4..8face156bb 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index c8df6ab490..492bb2b1a1 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 901dfa13f9..919debc200 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.64.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.65.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index e1856f9b3d..94d8d47291 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index adec742dfa..caffe8863a 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.64.0",
+ "version": "0.60.65.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index a823006136..0a3a8c6a21 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.64.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.65.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index e401dba19a..b28ab0aecb 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.64.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.65.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index 27b3caffbc..21b942b028 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -51,3 +51,4 @@ test/e2e/write-attribution-postgres.test.ts
test/e2e/write-attribution-read-parity.test.ts
test/e2e/feedback-parity.test.ts
test/e2e/mentions-parity.test.ts
+test/e2e/persistence-publish-lock-order-postgres.test.ts
diff --git a/scripts/persistence/README.md b/scripts/persistence/README.md
index 2077da4cf1..8ce1fed231 100644
--- a/scripts/persistence/README.md
+++ b/scripts/persistence/README.md
@@ -118,8 +118,11 @@ page fences; content rows carry write attribution; no orphan rows; every
request and effect drains (within 20 s on PGLite, whose restarted owner
releases a dead owner's claims, and within the 2-minute effect lease plus
margin on Postgres); a fresh write still commits. `lock-order.ts` checks each
-transaction's row locks: worktrees before sources, sources in id order, and
-no exclusive brain-row lock inside a publication.
+transaction's row locks: worktrees before sources, sources in id order, no
+exclusive brain-row lock inside a publication, and the brain row before any
+worktree, source or counter row whenever one transaction locks both (a write
+to `persistence_requests` or `persistence_effects` counts as the brain-row
+FOR SHARE read its protocol trigger takes).
Postgres runs connect through `GBRAIN_PGBOUNCER_URL` when it is set, with
prepared statements off. A Postgres run with a budget under 300 s (the
diff --git a/scripts/persistence/lock-order.ts b/scripts/persistence/lock-order.ts
index 6a0f19e5df..7020c6ff2e 100644
--- a/scripts/persistence/lock-order.ts
+++ b/scripts/persistence/lock-order.ts
@@ -9,7 +9,13 @@
* `id = ANY($1) ORDER BY id`, or several single-source locks);
* - a publication (a transaction that locks its request row) never takes
* an exclusive lock on the brain row (shared reads by the writer guard
- * and company receipts are counted, not refused).
+ * and company receipts are counted, not refused);
+ * - the brain row is locked before any worktree, source or counter row
+ * whenever one transaction locks both. Writing `persistence_requests` or
+ * `persistence_effects` counts as a brain-row FOR SHARE lock at that
+ * statement, because their protocol triggers read it; worktree claims and
+ * topology changes hold it FOR UPDATE before their worktrees, sources and
+ * counters, so a later brain read inverts against them.
* The core-memory source lock (`lockCoreSources`, when present) is a
* multi-source `sources` lock and is checked by the same rules.
*/
@@ -19,9 +25,13 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
interface Lock { table: string; ids: string[]; sql: string; exclusive: boolean }
interface Trace { locks: Lock[]; publication: boolean }
-export interface LockOrderViolation { rule: 'worktrees_before_sources' | 'sources_in_id_order' | 'publication_locks_brain'; detail: string }
+export interface LockOrderViolation { rule: 'worktrees_before_sources' | 'sources_in_id_order' | 'publication_locks_brain' | 'brain_before_rows'; detail: string }
const LOCK = /^\s*SELECT\b[\s\S]*?\bFROM\s+([a-z_]+)\b(?:\s+[a-z]\b)?[\s\S]*\bFOR\s+(UPDATE|SHARE|NO KEY UPDATE|KEY SHARE)\b(?!\s+OF\b)/i;
+/** A statement writing a journal table fires its protocol trigger's brain-row FOR SHARE read; counters it updates are locked first. */
+const TRIGGERED_BRAIN = /\b(?:INSERT\s+INTO|UPDATE|DELETE\s+FROM)\s+persistence_(?:requests|effects)\b/i;
+const COUNTER_WRITE = /\b(?:INSERT\s+INTO|UPDATE)\s+persistence_counters\b/i;
+const ORDERED_ROWS = new Set(['persistence_worktrees', 'sources', 'persistence_counters']);
const store = new AsyncLocalStorage<Trace>();
const violations: LockOrderViolation[] = [];
let installed = false;
@@ -32,6 +42,11 @@ let sharedBrainPublications = 0;
function record(sql: string, params: unknown[] | undefined): void {
const trace = store.getStore();
if (!trace) return;
+ const flat = sql.replace(/\s+/g, ' ').slice(0, 140);
+ if (!/^\s*SELECT\b/i.test(sql)) {
+ if (COUNTER_WRITE.test(sql)) trace.locks.push({ table: 'persistence_counters', ids: [], sql: flat, exclusive: true });
+ if (TRIGGERED_BRAIN.test(sql)) trace.locks.push({ table: 'persistence_brain', ids: [], sql: `trigger: ${flat}`, exclusive: false });
+ }
const match = LOCK.exec(sql);
if (!match) return;
const table = match[1].toLowerCase();
@@ -39,7 +54,7 @@ function record(sql: string, params: unknown[] | undefined): void {
const position = /\bid\s*=\s*(?:ANY\s*\(\s*)?\$(\d+)/i.exec(sql)?.[1];
const bound = position ? params?.[Number(position) - 1] : undefined;
const ids = Array.isArray(bound) ? bound.map(String) : bound === undefined ? [] : [String(bound)];
- trace.locks.push({ table, ids, sql: sql.replace(/\s+/g, ' ').slice(0, 140), exclusive: /UPDATE/i.test(match[2]) });
+ trace.locks.push({ table, ids, sql: flat, exclusive: /UPDATE/i.test(match[2]) });
if (table === 'persistence_requests' && /\bWHERE\s+id\s*=\s*\$1/i.test(sql)) trace.publication = true;
}
@@ -64,6 +79,9 @@ function check(trace: Trace): void {
}
// The writer guard's trigger and company receipts read the brain row FOR SHARE inside publications;
// an exclusive brain lock there would serialize every write behind topology changes.
+ const firstBrain = trace.locks.findIndex(l => l.table === 'persistence_brain');
+ const early = firstBrain > 0 ? trace.locks.slice(0, firstBrain).find(l => ORDERED_ROWS.has(l.table)) : undefined;
+ if (early) violations.push({ rule: 'brain_before_rows', detail: `${early.sql} [${early.ids}] before ${trace.locks[firstBrain].sql}` });
const brain = trace.locks.find(l => l.table === 'persistence_brain' && l.exclusive);
if (trace.publication && brain) violations.push({ rule: 'publication_locks_brain', detail: brain.sql });
if (trace.publication && trace.locks.some(l => l.table === 'persistence_brain')) sharedBrainPublications++;
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index e63ebcba8a..e98481cc92 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -43,6 +43,7 @@ import { readJournalLimits } from './limits.ts';
import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
import { readConnectorV2Cutoff } from './connector-checkpoint-migration.ts';
+import { declarePersistenceProtocol } from './protocol.ts';
import type { GoogleSourceConfig } from '../google/types.ts';
interface ConnectorLease { handle: DbLockHandle; signal: AbortSignal; }
@@ -844,6 +845,7 @@ export class ManagedConnectorSync {
{ fix: ownerStatusFix(this.sourceId, 'Shows what the canonical owner is running and what is queued behind it.') });
}
row = await this.engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
if (this.binding) await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [this.binding.worktree_id]);
await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [this.sourceId]);
await this.validate(tx, slug);
diff --git a/src/core/persistence/control.ts b/src/core/persistence/control.ts
index 14ed4655b6..b5d7f50681 100644
--- a/src/core/persistence/control.ts
+++ b/src/core/persistence/control.ts
@@ -3,6 +3,7 @@ import { opError, OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest } from './authority.ts';
import { completeWrite, getWriteRequest, lockCounters } from './journal.ts';
import { isTerminal, principalKey, type Principal, type WriteRequest } from './model.ts';
+import { declarePersistenceProtocol } from './protocol.ts';
export async function listWriteRequests(engine: BrainEngine, principal: Principal,
opts: { sourceId: string; before?: string; limit?: number; slugPrefixes?: string[]; operations?: string[]; slugAllowList?: string[];
@@ -48,6 +49,7 @@ export async function cancelWriteRequest(engine: BrainEngine, principal: Princip
const row = await getWriteRequest(engine, principal, requestId);
if (!row) return null;
return engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
await authorizeStoredRequest(tx, row, true);
await lockCounters(tx, ['brain', principalKey(principal), ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])]);
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.ts
index 413758748c..96aa73e2d0 100644
--- a/src/core/persistence/protocol.ts
+++ b/src/core/persistence/protocol.ts
@@ -2,22 +2,38 @@ import type { SqlEngine, WriteRequest } from './model.ts';
import { opError, OperationError } from '../ops/contract.ts';
const declared = new WeakSet<object>();
+/**
+ * Global persistence lock order: the `persistence_brain` row, then worktree
+ * rows (id order), then source rows (id order), then counters, requests and
+ * page keys. The request and effect protocol triggers read the brain row
+ * FOR SHARE, and worktree claims and topology changes lock it FOR UPDATE
+ * before their worktrees, sources and counters. A transaction that locked a
+ * source or counter row before its first request or effect write would wait
+ * for the brain row while holding what the topology change waits for, so
+ * every protocol declaration takes the brain row FOR SHARE first, in the same
+ * statement as its settings (a missing row still declares). Declare before
+ * any other row lock; a transaction that needs the brain row FOR UPDATE takes
+ * that first and declares after it.
+ */
+const BRAIN_SHARE = '(SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain';
+
/** Transaction-local; #5984: a transaction engine declares it once (a savepoint is its own engine object). */
export async function declarePersistenceProtocol(tx: SqlEngine): Promise<void> {
const inTransaction = (tx as { _pageTransaction?: boolean })._pageTransaction === true;
if (inTransaction && declared.has(tx)) return;
- await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");
+ await tx.executeRaw(`SELECT set_config('gbrain.persistence_protocol','2',true),${BRAIN_SHARE}`);
if (inTransaction) declared.add(tx);
}
/**
* #6007: the protocol declaration plus the durable-write settings (synchronous
- * commit, lock and statement timeouts) in one round trip. Later
- * `declarePersistenceProtocol` calls on the same transaction engine are free.
+ * commit, lock and statement timeouts) in one round trip, then the brain row
+ * under that lock timeout. Later `declarePersistenceProtocol` calls on the
+ * same transaction engine are free.
*/
export async function declareDurablePersistence(tx: SqlEngine, lockTimeout = '1s', statementTimeout = '5s'): Promise<void> {
await tx.executeRaw(`SELECT set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true),
- set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)`, [lockTimeout, statementTimeout]);
+ set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),${BRAIN_SHARE}`, [lockTimeout, statementTimeout]);
if ((tx as { _pageTransaction?: boolean })._pageTransaction === true) declared.add(tx);
}
diff --git a/src/core/persistence/skill-activation.ts b/src/core/persistence/skill-activation.ts
index 8243b29777..ae668d09b5 100644
--- a/src/core/persistence/skill-activation.ts
+++ b/src/core/persistence/skill-activation.ts
@@ -46,10 +46,10 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,
locks.push(lock);
}
return await engine.transaction(async tx => {
- await declarePersistenceProtocol(tx);
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true)");
await assertWriterAdminState(tx, options.expectedState);
await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');
+ await declarePersistenceProtocol(tx);
await assertWriterAdminUnlocked(tx);
await tx.executeRaw('SELECT id FROM persistence_worktrees ORDER BY id FOR UPDATE');
await tx.executeRaw('SELECT id FROM sources ORDER BY id FOR SHARE');
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index ae5665e45e..c9a59083bf 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.60.64.0 -->
+<!-- gbrain-template-stamp: 0.60.65.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/e2e/persistence-publish-lock-order-postgres.test.ts b/test/e2e/persistence-publish-lock-order-postgres.test.ts
new file mode 100644
index 0000000000..dc28f58f98
--- /dev/null
+++ b/test/e2e/persistence-publish-lock-order-postgres.test.ts
@@ -0,0 +1,178 @@
+/**
+ * Publication lock order against brain-row administration on Postgres.
+ *
+ * Every journal write (admission, recovery reservation, publication,
+ * completion) writes `persistence_requests` or `persistence_effects`, whose
+ * protocol triggers read the `persistence_brain` row FOR SHARE. Worktree
+ * claims and source topology changes lock that row FOR UPDATE first, then
+ * worktrees, sources and the persistence counters. A write that locked its
+ * source or counters before the trigger's brain read inverts that order: the
+ * topology change waits for the write's counters while the write waits for the
+ * brain row. Each declared persistence transaction therefore takes the brain
+ * row FOR SHARE first (protocol.ts `declareDurablePersistence`).
+ *
+ * The first case forces the interleaving: a real topology change pauses right
+ * after its brain lock, an ordinary put_page runs until it blocks behind it,
+ * then the topology change continues. The second case races ordinary writes
+ * against claims and topology changes. Both count deadlocks (40P01) and lock
+ * timeouts (55P03) seen by either side and require none, at the production
+ * 1 s `lock_timeout`.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { mkdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { hasDatabase } from './helpers.ts';
+import { managedBrain } from '../helpers/managed-brain.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';
+import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';
+
+const describeE2E = hasDatabase() ? describe : describe.skip;
+const note = (title: string, body: string) => `---\ntitle: ${title}\ntype: note\n---\n\n${body}\n`;
+
+interface Scope { label: 'topology' | 'writer'; onBrainLocked?: (pid: number) => Promise<void> }
+const scope = new AsyncLocalStorage<Scope>();
+const failures: Record<string, number> = {};
+const proto = PostgresEngine.prototype as unknown as { executeRaw: (...args: unknown[]) => Promise<unknown> };
+const original = proto.executeRaw;
+
+beforeAll(() => {
+ proto.executeRaw = async function (this: unknown, ...args: unknown[]) {
+ const current = scope.getStore();
+ try {
+ const result = await original.apply(this, args);
+ const hook = current?.onBrainLocked;
+ if (hook && /FROM persistence_brain WHERE singleton=1 FOR UPDATE/.test(String(args[0]))) {
+ current.onBrainLocked = undefined;
+ const [{ pid }] = await original.call(this, 'SELECT pg_backend_pid() AS pid') as Array<{ pid: number }>;
+ await hook(pid);
+ }
+ return result;
+ } catch (error) {
+ const code = String((error as { code?: string }).code);
+ if (code === '40P01' || code === '55P03') {
+ const key = `${current?.label ?? 'writer'}:${code}`;
+ failures[key] = (failures[key] ?? 0) + 1;
+ }
+ throw error;
+ }
+ };
+});
+afterAll(() => { proto.executeRaw = original; });
+
+function resetFailures(): void { for (const key of Object.keys(failures)) delete failures[key]; }
+
+async function writer(engine: BrainEngine) {
+ const registration = await registerLocalWriter(engine, 'cli');
+ return async (slug: string, content: string) => {
+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, 'put_page',
+ { slug, content, request_id: randomUUID(), source_id: 'default' },
+ { remote: false, config: { engine: 'postgres' }, sourceId: 'default', logger: { info() {}, warn() {}, error() {} } }));
+ return { isError: response.isError === true, text: (response.content[0] as { text: string }).text };
+ };
+}
+
+async function deadlocks(monitor: ReturnType<typeof postgres>, engine: BrainEngine): Promise<number> {
+ const [{ name }] = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const [row] = await monitor`SELECT deadlocks::int AS n FROM pg_stat_database WHERE datname=${name}`;
+ return Number(row?.n ?? 0);
+}
+
+async function waitFor<T>(probe: () => Promise<T | undefined>, timeoutMs: number): Promise<T | undefined> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const value = await probe();
+ if (value !== undefined) return value;
+ await new Promise(r => setTimeout(r, 20));
+ }
+ return undefined;
+}
+
+const settle = <T>(promise: Promise<T>) => promise.then(value => ({ ok: true as const, value }), (error: Error) => ({ ok: false as const, error }));
+
+describeE2E('publication lock order vs brain-row administration (Postgres)', () => {
+ let monitor: ReturnType<typeof postgres>;
+ beforeAll(() => { monitor = postgres(process.env.DATABASE_URL!, { max: 1, prepare: false }); });
+ afterAll(async () => { await monitor.end(); });
+
+ test('a write blocked behind a paused topology change commits once it continues; neither side deadlocks or times out', () => managedBrain(async ({ engine, root }) => {
+ resetFailures();
+ const put = await writer(engine);
+ expect((await put('notes/seed', note('Seed', 'seed'))).isError).toBe(false);
+ const before = await deadlocks(monitor, engine);
+ const rounds = 3;
+ const outcomes: Array<{ topology: string; write: string; blockedQuery: string | null }> = [];
+ for (let round = 0; round < rounds; round++) {
+ const probe = join(root, '..', `probe-${round}`); mkdirSync(probe);
+ let resume!: () => void; const resumed = new Promise<void>(r => { resume = r; });
+ let held!: (pid: number) => void; const brainHeld = new Promise<number>(r => { held = r; });
+ const topology = settle(scope.run({ label: 'topology', onBrainLocked: async pid => { held(pid); await resumed; } },
+ () => runManagedSourceLifecycle(engine, { operation: 'add', sourceId: `probe-${round}`, path: probe })));
+ const pid = await brainHeld;
+ const write = settle(scope.run({ label: 'writer' }, () => put(`notes/during-${round}`, note(`During ${round}`, `written during topology ${round}`))));
+ const blocked = await waitFor(async () => {
+ const rows = await monitor`SELECT query FROM pg_stat_activity WHERE ${pid}::int = ANY(pg_blocking_pids(pid))`;
+ return rows.length ? String(rows[0].query) : undefined;
+ }, 5000);
+ resume();
+ const [t, w] = await Promise.all([topology, write]);
+ outcomes.push({
+ topology: t.ok ? 'committed' : `${(t.error as { code?: string }).code ?? ''} ${t.error.message}`,
+ write: w.ok ? (w.value.isError ? `error ${w.value.text.slice(0, 160)}` : 'committed') : `${w.error.message}`,
+ blockedQuery: blocked?.replace(/\s+/g, ' ').slice(0, 120) ?? null,
+ });
+ }
+ const observed = { outcomes, deadlocks: await deadlocks(monitor, engine) - before, failures: { ...failures } };
+ console.log('[lock-order paused topology]', JSON.stringify(observed));
+ expect(observed.failures).toEqual({});
+ expect(observed.deadlocks).toBe(0);
+ expect(outcomes.every(o => o.topology === 'committed' && o.write === 'committed')).toBe(true);
+ }, { databaseUrl: process.env.DATABASE_URL }), 120_000);
+
+ test('ordinary writes racing claims and topology changes never deadlock or hit lock_timeout', () => managedBrain(async ({ engine, root }) => {
+ resetFailures();
+ const put = await writer(engine);
+ expect((await put('notes/seed', note('Seed', 'seed'))).isError).toBe(false);
+ const before = await deadlocks(monitor, engine);
+ let stop = false;
+ const topologyResults: string[] = [];
+ const topology = (async () => {
+ for (let i = 0; !stop && i < 12; i++) {
+ const dir = join(root, '..', `race-${i}`); mkdirSync(dir);
+ const steps: Array<() => Promise<unknown>> = [
+ () => runManagedSourceLifecycle(engine, { operation: 'add', sourceId: `race-${i}` }),
+ () => runManagedSourceLifecycle(engine, { operation: 'claim', sourceId: `race-${i}`, path: dir }),
+ () => runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: `race-${i}` }),
+ ];
+ for (const step of steps) {
+ const result = await settle(scope.run({ label: 'topology' }, step));
+ topologyResults.push(result.ok ? 'committed' : String((result.error as { code?: string }).code ?? result.error.message));
+ }
+ }
+ })();
+ const writes: Array<Promise<{ isError: boolean; text: string }>> = [];
+ for (let wave = 0; wave < 6; wave++) {
+ const batch = Array.from({ length: 6 }, (_, i) => scope.run({ label: 'writer' }, () => put(`notes/race-${wave}-${i}`, note(`Race ${wave} ${i}`, `body ${wave} ${i}`))));
+ writes.push(...batch);
+ await Promise.all(batch);
+ }
+ stop = true;
+ await topology;
+ const results = await Promise.all(writes);
+ const observed = {
+ writes: results.length, writeErrors: results.filter(r => r.isError).map(r => /"code": "([a-z_]+)"/.exec(r.text)?.[1] ?? r.text.slice(0, 160)),
+ topology: topologyResults.reduce<Record<string, number>>((acc, r) => ({ ...acc, [r]: (acc[r] ?? 0) + 1 }), {}),
+ deadlocks: await deadlocks(monitor, engine) - before, failures: { ...failures },
+ };
+ console.log('[lock-order race]', JSON.stringify(observed));
+ expect(observed.failures).toEqual({});
+ expect(observed.deadlocks).toBe(0);
+ expect(observed.writeErrors).toEqual([]);
+ expect(Object.keys(observed.topology)).toEqual(['committed']);
+ }, { databaseUrl: process.env.DATABASE_URL }), 240_000);
+});
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index 0305a41b2b..58ecc823fd 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -25,6 +25,7 @@ import { runSchedule } from '../scripts/persistence/crash-robot.ts';
import { installLockOrderTrace, lockOrderReport } from '../scripts/persistence/lock-order.ts';
import { prepareTopology } from '../scripts/persistence/history-fixture.ts';
import { claimPersistenceEffect, releaseAbandonedClaims } from '../src/core/persistence/effect-journal.ts';
+import { LOCK_COUNTERS_SQL } from '../src/core/persistence/journal.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -116,6 +117,32 @@ describe('lock order', () => {
expect(lockOrderReport().violations.slice(before).map(v => v.rule)).toEqual(['worktrees_before_sources', 'sources_in_id_order']);
});
}, 120_000);
+
+ test('real publications lock the brain row before worktrees, sources and counters; a later brain read is reported', async () => {
+ await robotBrain(async ({ world }) => {
+ installLockOrderTrace();
+ const before = lockOrderReport().violations.length;
+ await runSchedule(world, crossBoundarySequences(ROBOT_TOPOLOGY)[1]);
+ const clean = lockOrderReport();
+ expect(clean.violations.slice(before)).toEqual([]);
+ expect(clean.publications_reading_brain_for_share).toBeGreaterThan(0);
+ await world.engine.transaction(async tx => {
+ await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR SHARE', ['robot-0']);
+ await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE');
+ });
+ await world.engine.transaction(async tx => {
+ await tx.executeRaw(LOCK_COUNTERS_SQL, [['brain']]);
+ await tx.executeRaw('UPDATE persistence_requests SET updated_at=updated_at WHERE false');
+ });
+ await world.engine.transaction(async tx => {
+ await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');
+ await tx.executeRaw('SELECT id FROM persistence_worktrees ORDER BY id FOR UPDATE');
+ await tx.executeRaw('SELECT id FROM sources WHERE id=ANY($1::text[]) ORDER BY id FOR UPDATE', [['robot-0', 'robot-1']]);
+ await tx.executeRaw(LOCK_COUNTERS_SQL, [['brain']]);
+ });
+ expect(lockOrderReport().violations.slice(before).map(v => v.rule)).toEqual(['brain_before_rows', 'brain_before_rows']);
+ });
+ }, 120_000);
});
// TODOS.md "A held sync lock reaches agents as internal_error": fails until the agent rows map the lock errors.