Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(persistence): lock-order e2e asserts the wait cycle, not the absence of any 1 s timeout
garrytanf607c2eec3ad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 154c4f0b1f..a7c7a60461 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -37,6 +37,7 @@ Nothing to do: this release changes the persistence validation robot only. `bun#### Crash robot- After a concurrent group, a page may end at the write of a committed sync or connector publish (which return no revision) only when the page carries that member's marker; every receipted revision a later member replaced must still be in the page history. A revision no member explains is still `lost_write`.+- `test/e2e/persistence-publish-lock-order-postgres.test.ts` (from v0.60.65.0) asserted no lock timeout at all and failed once in CI when a slow runner kept a write waiting more than 1 s behind the deliberately paused topology change. It now asserts the inversion itself: once resumed, the topology change never waits on another session, and the race samples `pg_blocking_pids` for two sessions waiting on each other. On the pre-v0.60.65.0 order both still fail (the change waits on the write's counters; the race finds write/topology cycles every run); on the current order they passed 24 of 24 runs with four CPU-burning processes on a 4-CPU machine, direct and through PgBouncer.- `test/persistence-crash-robot.test.ts` runs the put, then the connector republish, through the real handlers and settles them as one group: the previous oracle reported `lost_write` and this one passes; an extra write nobody in the group returned still reports `lost_write`.## [0.60.65.0] - 2026-10-05diff --git a/test/e2e/persistence-publish-lock-order-postgres.test.ts b/test/e2e/persistence-publish-lock-order-postgres.test.tsindex dc28f58f98..5d577619f0 100644--- a/test/e2e/persistence-publish-lock-order-postgres.test.ts+++ b/test/e2e/persistence-publish-lock-order-postgres.test.ts@@ -13,10 +13,14 @@** 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`.+ * then the topology change continues and must never wait on another session:+ * what queued behind it took the brain row before any other row. The second+ * case races ordinary writes against claims and topology changes while+ * sampling `pg_blocking_pids` for two sessions waiting on each other, and+ * requires no such cycle, no deadlock (40P01), and every write and change+ * committed, at the production 1 s `lock_timeout`. Lock timeouts (55P03) are+ * logged, not failed: a starved runner can hold a lock past 1 s without any+ * inversion, and the writer retries.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { AsyncLocalStorage } from 'node:async_hooks';@@ -100,13 +104,13 @@ describeE2E('publication lock order vs brain-row administration (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 }) => {+ test('a write queued behind a paused topology change holds nothing the change needs, so the change never waits on it and both commit', () => 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 }> = [];+ const outcomes: Array<{ topology: string; write: string; topologyWaitedOn: string[] }> = [];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; });@@ -115,31 +119,55 @@ describeE2E('publication lock order vs brain-row administration (Postgres)', ()() => 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);+ await waitFor(async () => (await monitor`SELECT 1 FROM pg_stat_activity WHERE ${pid}::int = ANY(pg_blocking_pids(pid))`).length ? true : undefined, 5000);+ // Let every statement the write reaches queue up behind the paused change, then watch what the change waits on.+ await new Promise(r => setTimeout(r, 300));resume();- const [t, w] = await Promise.all([topology, write]);+ let done = false;+ const settled = Promise.all([topology, write]).finally(() => { done = true; });+ const blockers = new Set<string>();+ while (!done) {+ for (const row of await monitor`SELECT a.query FROM pg_stat_activity a WHERE a.pid = ANY(pg_blocking_pids(${pid}::int))`) {+ blockers.add(String(row.query).replace(/\s+/g, ' ').slice(0, 200));+ }+ await new Promise(r => setTimeout(r, 10));+ }+ const [t, w] = await settled;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,+ topologyWaitedOn: [...blockers],});}const observed = { outcomes, deadlocks: await deadlocks(monitor, engine) - before, failures: { ...failures } };console.log('[lock-order paused topology]', JSON.stringify(observed));- expect(observed.failures).toEqual({});+ // Whatever queued behind the change holds nothing it needs: once resumed, it never waits on another session.+ expect(outcomes.flatMap(o => o.topologyWaitedOn)).toEqual([]);+ expect(Object.keys(observed.failures).filter(key => !key.startsWith('writer:55P03'))).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 }) => {+ test('ordinary writes racing claims and topology changes never wait on each other in a cycle; every write and change commits', () => 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 [{ name }] = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');+ let stop = false; let sampling = true;+ // Two sessions each waiting on the other is the inversion itself; a 1 s lock_timeout on a starved runner is not.+ const cycles = new Set<string>();+ const sampler = (async () => {+ while (sampling) {+ const rows = await monitor`SELECT pid, pg_blocking_pids(pid) AS blockers, left(regexp_replace(query, '[[:space:]]+', ' ', 'g'), 120) AS query+ FROM pg_stat_activity WHERE datname=${name} AND cardinality(pg_blocking_pids(pid)) > 0`;+ const waits = new Map(rows.map(row => [Number(row.pid), { blockers: (row.blockers as number[]).map(Number), query: String(row.query) }]));+ for (const [pid, wait] of waits) for (const blocker of wait.blockers) {+ if (waits.get(blocker)?.blockers.includes(pid)) cycles.add([wait.query, waits.get(blocker)!.query].sort().join(' <-> '));+ }+ await new Promise(r => setTimeout(r, 20));+ }+ })();const topologyResults: string[] = [];const topology = (async () => {for (let i = 0; !stop && i < 12; i++) {@@ -163,14 +191,16 @@ describeE2E('publication lock order vs brain-row administration (Postgres)', ()}stop = true;await topology;+ sampling = false;+ await sampler;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 },+ deadlocks: await deadlocks(monitor, engine) - before, lockTimeouts: { ...failures }, cycles: [...cycles],};console.log('[lock-order race]', JSON.stringify(observed));- expect(observed.failures).toEqual({});+ expect(observed.cycles).toEqual([]);expect(observed.deadlocks).toBe(0);expect(observed.writeErrors).toEqual([]);expect(Object.keys(observed.topology)).toEqual(['committed']);