Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P4.8 #6028: lease refresh/release match (id, holder_pid, acquisition_token), never the acquired_at epoch text

garrytan22e3ceee601d
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index a4d17c1044..348cccd95c 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction. Current-host plugin factories may be called with zero arguments. The host workspace takes precedence; ambiguous/unbound legacy fallback warns and reads no source. The canonical slot ID is `gbrain-context-engine`; `gbrain-context` remains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive. `assemble` uses an authoritative separate prompt: sqlite transcript-storage metadata fences historic turns, whereas an identical final legacy user message already represents the current turn. Reflex-only synthesis leaves messages intact; absent prompt keeps message extraction. These contracts do not prove model recall. `compact()` records the session's seat sidecar (`context/seat.ts`, harness `openclaw`, seat keyed to the agent directory holding `sessions/`) before spooling the segment; a failure never fails the checkpoint.
-- `src/core/db-lock.ts` + `lease-schema.ts` — row leases survive transaction-mode PgBouncer. Migration 152 gives every `gbrain_cycle_locks` acquisition a UUID; refresh/release, dead-holder takeover/reaper and manual/age-gated breaks match the observed token exactly. Epoch text is retained for diagnostics and legacy mutation detection, never treated as unique identity. `withRefreshingLock` always passes an aborting work signal, rejects results after ownership loss/TTL expiry, tracks a single actual renewal through timeout cancellation, and drains late completion before release. Renewal deadlines start before the database round trip. `performSync` composes this signal with caller cancellation. `inspectLock`, `listStaleLocks`, `listLiveLocks`, `classifyHolderLiveness` and namespace-scoped `reapDeadHolderLocks` retain their status/recovery contracts. Tests: `test/db-lock-concurrency.test.ts`, `test/e2e/db-lock-acquisition-token.test.ts`, existing fencing/reaper/inspection suites.
+- `src/core/db-lock.ts` + `lease-schema.ts` — row leases survive transaction-mode PgBouncer. Migration 152 gives every `gbrain_cycle_locks` acquisition a UUID; refresh/release, takeover/reaper and manual/age-gated breaks match (id, holder_pid, acquisition_token), never the `acquired_at` epoch text, which is diagnostics only (#6028). `withRefreshingLock` always passes an aborting work signal, rejects results after ownership loss/TTL expiry, tracks a single actual renewal through timeout cancellation, and drains late completion before release. Renewal deadlines start before the database round trip. `performSync` composes this signal with caller cancellation. `inspectLock`, `listStaleLocks`, `listLiveLocks`, `classifyHolderLiveness` and namespace-scoped `reapDeadHolderLocks` keep their status/recovery contracts. Tests: `test/db-lock-concurrency.test.ts`, `test/db-lock-token-predicate.test.ts`, `test/e2e/db-lock-acquisition-token.test.ts`, fencing/reaper/inspection suites.
- `src/core/db-repair-receipts.ts` — the shared seam between `gbrain db-repair` (writer) and doctor's `db_repair_recurrence` check (reader — it must run in doctor's dead-DB filesystem lane, exactly when repairs are repeating). JSONL at `~/.gbrain/db-repair-receipts.jsonl`; row shape `{ts, brain_id, reason, action, outcome: 'applied'|'refused'|'diagnose'}` — only `applied` rows count toward the recurrence threshold (3+ same-reason per brain in 7 days). Redacted before write (the classifier redacts its own copy; actions are fixed strings), fail-open (a receipts problem never blocks a repair), capped at 200 rows ON EVERY WRITE (the recurrence check reads the file on every doctor run — it must not grow unbounded on exactly the machines having chronic problems) — EXCEPT `applied` rows inside an 8-day retention window, which are exempt from the flat cap (separately bounded at 200): a diagnose flood from an agent loop must never evict the cooldown/recurrence memory. The reader is per-line tolerant (one torn row never discards every other receipt). Also owns `rewriteCooldownBlocked` (24h per (reason, action), rewrite tier only).
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index 3dc1c1a136..85bfdceaa4 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -61,3 +61,4 @@ test/e2e/fence-chunk-overlay-postgres.test.ts
test/e2e/fence-chunk-trust-read-postgres.test.ts
test/e2e/trust-cross-session-parity.test.ts
test/e2e/single-write-group-parity-postgres.test.ts
+test/e2e/db-lock-token-predicate-postgres.test.ts
diff --git a/src/core/db-lock.ts b/src/core/db-lock.ts
index 7b9612d0a5..01aff105ad 100644
--- a/src/core/db-lock.ts
+++ b/src/core/db-lock.ts
@@ -27,14 +27,21 @@ import type { BrainEngine } from './engine.ts';
export interface DbLockHandle {
id: string;
- /** Epoch-seconds timestamp retained for diagnostics and legacy mutation detection. */
+ /** Epoch-seconds text of acquired_at, diagnostics only (#6028: never a predicate term). */
acquiredAt: string;
- /** Opaque UUID identity; timestamps are retained only for compatibility/diagnostics. */
+ /**
+ * The lease identity. Every acquisition mints a fresh UUID (v152), so
+ * refresh/release/cleanup match on (id, holder_pid, acquisition_token)
+ * alone: a successor's row has another token, and a rewrite of
+ * `acquired_at` under a live holder (its epoch text is session-fragile:
+ * numeric scale, DateStyle, a maintenance touch) no longer costs the
+ * holder its own lease (#6028).
+ */
acquisitionToken: string;
release: () => Promise<void>;
/**
* Bump ttl_expires_at + last_refreshed_at. Returns true when this handle
- * still owns the row (exactly one row matched the fenced predicate);
+ * still owns the row (exactly one row matched (id, holder_pid, acquisition_token));
* false means the lock was stolen or released — the caller must stop
* relying on mutual exclusion. Transient DB errors still THROW (they are
* not evidence of a steal; the TTL is the backstop).
@@ -252,13 +259,14 @@ export async function tryAcquireDbLock(
RETURNING id, extract(epoch from acquired_at)::text AS fence
`;
if (rows.length === 0) return null;
- // Epoch text avoids per-session TimeZone/DateStyle differences. The
- // UUID distinguishes acquisitions sharing one transaction-stable NOW().
+ // The UUID is the fence; the epoch text rides on the handle for
+ // diagnostics (migration-orchestration-lock.ts reports it when a lease
+ // is lost) and is never compared (#6028).
const fence = rows[0].fence;
const deregister = registerCleanup(`db-lock:${lockId}`, async () => {
await sql`
DELETE FROM gbrain_cycle_locks
- WHERE id = ${lockId} AND holder_pid = ${pid} AND extract(epoch from acquired_at)::text = ${fence} AND acquisition_token = ${acquisitionToken}::uuid
+ WHERE id = ${lockId} AND holder_pid = ${pid} AND acquisition_token = ${acquisitionToken}::uuid
`;
});
return {
@@ -274,9 +282,9 @@ export async function tryAcquireDbLock(
`UPDATE gbrain_cycle_locks
SET ttl_expires_at = NOW() + ($1)::interval,
last_refreshed_at = NOW()
- WHERE id = $2 AND holder_pid = $3 AND extract(epoch from acquired_at)::text = $4 AND acquisition_token = $5::uuid
+ WHERE id = $2 AND holder_pid = $3 AND acquisition_token = $4::uuid
RETURNING id`,
- [ttl, lockId, pid, fence, acquisitionToken],
+ [ttl, lockId, pid, acquisitionToken],
refreshOpts,
);
return updated.length > 0;
@@ -285,7 +293,7 @@ export async function tryAcquireDbLock(
deregister();
await sql`
DELETE FROM gbrain_cycle_locks
- WHERE id = ${lockId} AND holder_pid = ${pid} AND extract(epoch from acquired_at)::text = ${fence} AND acquisition_token = ${acquisitionToken}::uuid
+ WHERE id = ${lockId} AND holder_pid = ${pid} AND acquisition_token = ${acquisitionToken}::uuid
`;
},
};
@@ -311,12 +319,12 @@ export async function tryAcquireDbLock(
[lockId, pid, host, ttl, stealGraceSeconds, acquisitionToken],
);
if (rows.length === 0) return null;
- // Fencing identity (D5.10) — see the postgres branch for rationale.
+ // Diagnostics only (#6028); the token is the fence — see the postgres branch.
const fence = String((rows[0] as { fence: string }).fence);
const deregister = registerCleanup(`db-lock:${lockId}`, async () => {
await db.query(
- `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2 AND extract(epoch from acquired_at)::text = $3 AND acquisition_token = $4::uuid`,
- [lockId, pid, fence, acquisitionToken],
+ `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2 AND acquisition_token = $3::uuid`,
+ [lockId, pid, acquisitionToken],
);
});
return {
@@ -328,17 +336,17 @@ export async function tryAcquireDbLock(
`UPDATE gbrain_cycle_locks
SET ttl_expires_at = NOW() + $1::interval,
last_refreshed_at = NOW()
- WHERE id = $2 AND holder_pid = $3 AND extract(epoch from acquired_at)::text = $4 AND acquisition_token = $5::uuid
+ WHERE id = $2 AND holder_pid = $3 AND acquisition_token = $4::uuid
RETURNING id`,
- [ttl, lockId, pid, fence, acquisitionToken],
+ [ttl, lockId, pid, acquisitionToken],
);
return res.rows.length > 0;
},
release: async () => {
deregister();
await db.query(
- `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2 AND extract(epoch from acquired_at)::text = $3 AND acquisition_token = $4::uuid`,
- [lockId, pid, fence, acquisitionToken],
+ `DELETE FROM gbrain_cycle_locks WHERE id = $1 AND holder_pid = $2 AND acquisition_token = $3::uuid`,
+ [lockId, pid, acquisitionToken],
);
},
};
diff --git a/src/core/migration-orchestration-lock.ts b/src/core/migration-orchestration-lock.ts
index 41104dab79..0c45dff6fb 100644
--- a/src/core/migration-orchestration-lock.ts
+++ b/src/core/migration-orchestration-lock.ts
@@ -8,7 +8,10 @@
*
* Postgres: a renewable TTL lease row in `gbrain_cycle_locks` (db-lock.ts),
* which survives transaction-mode poolers and reuses its dead-holder
- * takeover rules. A schema without that table has no lease yet; the runner
+ * takeover rules. The lease identity is (id, holder_pid, acquisition_token);
+ * the epoch text of `acquired_at` on the handle is reported by
+ * MigrationLeaseLostError and never compared, so a rewrite of that column
+ * under a live runner cannot make it refuse itself (#6028). A schema without that table has no lease yet; the runner
* then relies on the initSchema lock and acquires the lease once the table
* exists. An unreachable database has nothing to coordinate.
*
diff --git a/test/cycle-lock-steal.serial.test.ts b/test/cycle-lock-steal.serial.test.ts
index cf89b9318c..df24de407e 100644
--- a/test/cycle-lock-steal.serial.test.ts
+++ b/test/cycle-lock-steal.serial.test.ts
@@ -58,10 +58,13 @@ test('mid-run steal → structured partial report, no further phases, successor
yieldBetweenPhases: async () => {
if (stole) return;
stole = true;
- // Simulate a successor taking the row: new acquisition identity.
+ // Simulate a successor taking the row: a new acquisition identity.
+ // Since v152 every acquisition mints a fresh acquisition_token and
+ // that token IS the fence (#6028); acquired_at moves with it.
await engine.executeRaw(
`UPDATE gbrain_cycle_locks
- SET acquired_at = acquired_at + INTERVAL '1 millisecond',
+ SET acquisition_token = gen_random_uuid(),
+ acquired_at = acquired_at + INTERVAL '1 millisecond',
ttl_expires_at = NOW() + INTERVAL '5 minutes',
last_refreshed_at = NOW()
WHERE id = $1`,
diff --git a/test/db-lock-fencing.test.ts b/test/db-lock-fencing.test.ts
index 1f834600d2..cc94a05025 100644
--- a/test/db-lock-fencing.test.ts
+++ b/test/db-lock-fencing.test.ts
@@ -1,12 +1,13 @@
/**
* W0 fix-wave (Tier-1 #1, D5.10) — per-acquisition lock fencing.
*
- * The refresh/release predicates require (id, holder_pid, acquired_at::text),
- * so a handle from a PREVIOUS acquisition — a PID-reuse impostor, or this
- * process after its row was stolen — can never refresh or delete a
- * successor's row. Pre-fix the predicates were (id, holder_pid) only, and an
- * expired holder could refresh a successor's lock while reporting success
- * (Codex eng-review #1 on the fix-wave plan).
+ * The refresh/release predicates require (id, holder_pid, acquisition_token)
+ * (#6028; before that the acquired_at epoch text as well), so a handle from a
+ * PREVIOUS acquisition — a PID-reuse impostor, or this process after its row
+ * was stolen — can never refresh or delete a successor's row. Pre-fix the
+ * predicates were (id, holder_pid) only, and an expired holder could refresh
+ * a successor's lock while reporting success (Codex eng-review #1 on the
+ * fix-wave plan).
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
@@ -30,11 +31,18 @@ beforeEach(async () => {
await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id LIKE 'test-fence-%'`);
});
-/** Simulate a successor stealing the row: rewrite acquisition identity in place. */
+/**
+ * Simulate a successor stealing the row: rewrite the acquisition identity in
+ * place. Since v152 every acquisition mints a fresh acquisition_token and that
+ * token is the fence (#6028): a successor's row always carries a new one.
+ * acquired_at moves with it, as a real takeover's does, but is no longer what
+ * the predicate compares (test/db-lock-token-predicate.test.ts pins both).
+ */
async function stealRow(lockId: string): Promise<void> {
await engine.executeRaw(
`UPDATE gbrain_cycle_locks
SET holder_pid = holder_pid,
+ acquisition_token = gen_random_uuid(),
acquired_at = acquired_at + INTERVAL '1 millisecond',
ttl_expires_at = NOW() + INTERVAL '5 minutes',
last_refreshed_at = NOW()
diff --git a/test/db-lock-token-predicate.test.ts b/test/db-lock-token-predicate.test.ts
new file mode 100644
index 0000000000..bf11148530
--- /dev/null
+++ b/test/db-lock-token-predicate.test.ts
@@ -0,0 +1,99 @@
+/**
+ * #6028 (wave 14 P4.8): the lease identity is (id, holder_pid,
+ * acquisition_token). Every acquisition mints a fresh UUID (v152 made the
+ * column NOT NULL DEFAULT gen_random_uuid()), so the token alone tells this
+ * handle's row from a successor's. The epoch text of `acquired_at` used to
+ * be a fourth predicate term; its text form is session-fragile (numeric
+ * scale, DateStyle, a maintenance rewrite of the row) and made a runner
+ * refuse its OWN lease as `migrations_running` naming its own pid.
+ *
+ * Runs on PGLite here and on Postgres through
+ * test/e2e/db-lock-token-predicate-postgres.test.ts.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { tryAcquireDbLock } from '../src/core/db-lock.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const engines: Array<{ engine: BrainEngine; close: () => Promise<void> }> = [];
+
+beforeAll(async () => {
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ engines.push({ engine, close: () => engine.disconnect() });
+ } else {
+ engines.push(await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ }
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const e of engines) await e.close();
+});
+
+beforeEach(async () => {
+ for (const { engine } of engines) await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id LIKE 'test-token-%'`);
+});
+
+async function row(engine: BrainEngine, id: string) {
+ const rows = await engine.executeRaw<{ acquisition_token: string; ttl_expires_at: Date | string }>(
+ `SELECT acquisition_token::text AS acquisition_token, ttl_expires_at FROM gbrain_cycle_locks WHERE id = $1`, [id]);
+ return rows[0] ?? null;
+}
+
+describe('#6028 token-bearing lease predicate', () => {
+ test('a rewritten acquired_at while holding keeps refresh() and release() valid', async () => {
+ for (const { engine } of engines) {
+ const handle = await tryAcquireDbLock(engine, 'test-token-rewrite', 5);
+ expect(handle).not.toBeNull();
+ await engine.executeRaw(
+ `UPDATE gbrain_cycle_locks SET acquired_at = acquired_at + INTERVAL '1 millisecond' WHERE id = $1`, ['test-token-rewrite']);
+ expect(await handle!.refresh()).toBe(true);
+ expect((await row(engine, 'test-token-rewrite'))?.acquisition_token).toBe(handle!.acquisitionToken);
+ await handle!.release();
+ expect(await row(engine, 'test-token-rewrite')).toBeNull();
+ }
+ });
+
+ test('a successor acquisition (new token) fences the old handle out of refresh, release and cleanup', async () => {
+ for (const { engine } of engines) {
+ const old = await tryAcquireDbLock(engine, 'test-token-successor', 5);
+ expect(old).not.toBeNull();
+ // Expire the row the way a stalled holder does, then let a successor take it over.
+ await engine.executeRaw(
+ `UPDATE gbrain_cycle_locks SET ttl_expires_at = NOW() - INTERVAL '1 minute', last_refreshed_at = NOW() - INTERVAL '1 day' WHERE id = $1`,
+ ['test-token-successor']);
+ const successor = await tryAcquireDbLock(engine, 'test-token-successor', 5);
+ expect(successor).not.toBeNull();
+ expect(successor!.acquisitionToken).not.toBe(old!.acquisitionToken);
+
+ expect(await old!.refresh()).toBe(false);
+ await old!.release();
+ const after = await row(engine, 'test-token-successor');
+ expect(after?.acquisition_token).toBe(successor!.acquisitionToken);
+ expect(await successor!.refresh()).toBe(true);
+ await successor!.release();
+ expect(await row(engine, 'test-token-successor')).toBeNull();
+ }
+ });
+
+ test('a tokenless schema (pre-v152 table) is unchanged: the acquire reports the missing column', async () => {
+ for (const { engine } of engines) {
+ await engine.executeRaw(`ALTER TABLE gbrain_cycle_locks DROP COLUMN acquisition_token`);
+ try {
+ let caught: unknown = null;
+ await tryAcquireDbLock(engine, 'test-token-less', 5).catch((err: unknown) => { caught = err; });
+ const e = caught as { code?: string; message?: string } | null;
+ expect(e).not.toBeNull();
+ expect(e?.code === '42703' || /acquisition_token.*does not exist/i.test(e?.message ?? '')).toBe(true);
+ } finally {
+ await engine.executeRaw(`ALTER TABLE gbrain_cycle_locks ADD COLUMN IF NOT EXISTS acquisition_token UUID NOT NULL DEFAULT gen_random_uuid()`);
+ }
+ }
+ });
+});
diff --git a/test/e2e/db-lock-token-predicate-postgres.test.ts b/test/e2e/db-lock-token-predicate-postgres.test.ts
new file mode 100644
index 0000000000..96ab124c56
--- /dev/null
+++ b/test/e2e/db-lock-token-predicate-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../db-lock-token-predicate.test.ts'));