Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(persistence): a registration that lost its insert checks the winning row on PGLite and Postgres
garrytan9f352fbd60c7
diff --git a/test/e2e/engine-open-postgres.test.ts b/test/e2e/engine-open-postgres.test.tsindex 41614286e6..beebbff45d 100644--- a/test/e2e/engine-open-postgres.test.ts+++ b/test/e2e/engine-open-postgres.test.ts@@ -16,7 +16,8 @@ import { embeddedSettings, hostIdFor, openEngine, type EngineSettings } from '..import { createEngine } from '../../src/core/engine-factory.ts';import { operationsByName, type OperationContext } from '../../src/core/operations.ts';import { startConsumerHeartbeat } from '../../src/core/persistence/consumer-heartbeat.ts';-import { localHostId } from '../../src/core/persistence/identity.ts';+import { localHostId, registerLocalWriterValue, revokeLocalWriter } from '../../src/core/persistence/identity.ts';+import type { SqlEngine } from '../../src/core/persistence/model.ts';import type { BrainEngine } from '../../src/core/engine.ts';import type { EngineConfig } from '../../src/core/types.ts';import { sharedParameterTypes, type SharedParameterTypes } from '../../src/core/pg-type-cache.ts';@@ -138,6 +139,34 @@ describeE2E('openEngine on Postgres', () => {}}, 300_000);+ test('on Postgres, a registration that lost its insert checks the row that won: another credential, lane or id, or a revoked row, refuses', async () => {+ const engine = await openEngine({ embedded_core: true, engine: 'postgres', database: { url: urls[3]! }, pool: { max: 2 }, host: { id: randomUUID() } });+ try {+ await engine.initSchema();+ const writer = writerValue();+ await registerLocalWriterValue(engine, writer);+ const raced = (): SqlEngine => {+ let hidden = false;+ return { executeRaw: (<T>(sql: string, params?: unknown[]) => {+ if (!hidden && sql.startsWith('SELECT revoked_at,credential_hash,lane,grant_ceiling FROM persistence_local_writers')) { hidden = true; return Promise.resolve([] as T[]); }+ return engine.executeRaw<T>(sql, params);+ }) as SqlEngine['executeRaw'] };+ };+ const rows = (id: string) => engine.executeRaw<{ lane: string; revoked: boolean }>('SELECT lane, revoked_at IS NOT NULL AS revoked FROM persistence_local_writers WHERE id=$1::uuid', [id]);+ expect(await codeOf(registerLocalWriterValue(raced(), writer))).toBe('resolved');+ expect(await codeOf(registerLocalWriterValue(raced(), { ...writer, credential: randomBytes(32).toString('hex') }))).toBe('permission_denied');+ expect(await codeOf(registerLocalWriterValue(raced(), { ...writer, lane: 'cli' }))).toBe('permission_denied');+ const other = randomUUID();+ expect(await codeOf(registerLocalWriterValue(raced(), { ...writer, id: other }))).toBe('permission_denied');+ expect(await rows(other)).toEqual([]);+ expect(await revokeLocalWriter(engine, writer.id)).toBe(true);+ expect(await codeOf(registerLocalWriterValue(raced(), writer))).toBe('permission_denied');+ expect(await rows(writer.id)).toEqual([{ lane: 'stdio', revoked: true }]);+ } finally {+ await engine.disconnect();+ }+ }, 120_000);+test('a disconnect during an in-flight reconnect leaves no live pool, drops the settings and refuses a later reconnect', async () => {const engine = await openEngine({ embedded_core: true, engine: 'postgres', database: { url: urls[0]! }, pool: { max: 2 }, host: { id: randomUUID() } });const reconnecting = engine.reconnect().catch(() => {});diff --git a/test/engine-open.test.ts b/test/engine-open.test.tsindex 01508846e8..b582aeb9d4 100644--- a/test/engine-open.test.ts+++ b/test/engine-open.test.ts@@ -15,6 +15,7 @@ import { operationsByName, type OperationContext } from '../src/core/operations.import { readStoredEmbeddingIdentity } from '../src/core/stored-embedding-identity.ts';import { ConnectionManager } from '../src/core/connection-manager.ts';import type { BrainEngine } from '../src/core/engine.ts';+import type { SqlEngine } from '../src/core/persistence/model.ts';import { withEnv } from './helpers/with-env.ts';import { engineKey } from '../src/core/engine-key.ts';import { awaitPendingTelemetryFlush, getTelemetryWriter, recordSearchTelemetry, _telemetryWriterCountForTest } from '../src/core/search/telemetry.ts';@@ -40,6 +41,14 @@ const hostCtx = (engine: BrainEngine): OperationContext => ({engine, config: {}, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: true,} as unknown as OperationContext);const codeOf = async (work: Promise<unknown>) => { try { await work; return 'resolved'; } catch (error) { return (error as { code?: string }).code ?? String(error); } };+/** `engine` whose next registration read answers no row, as when another caller registers between that read and the insert. */+const racedRead = (engine: BrainEngine): SqlEngine => {+ let hidden = false;+ return { executeRaw: (<T>(sql: string, params?: unknown[]) => {+ if (!hidden && sql.startsWith('SELECT revoked_at,credential_hash,lane,grant_ceiling FROM persistence_local_writers')) { hidden = true; return Promise.resolve([] as T[]); }+ return engine.executeRaw<T>(sql, params);+ }) as SqlEngine['executeRaw'] };+};/** Ambient settings that must never reach an embedded engine: a clean GBRAIN_HOME, a canary HOME and bogus database URLs. */function canaries() {const home = dir('canary-home');@@ -328,6 +337,41 @@ describe('writer given as a value', () => {}}, 120_000);+ test('a registration that read no row and then lost its insert checks the row that won, and refuses as an existing row would', async () => {+ const engine = await openEngine(settingsFor());+ try {+ await engine.initSchema();+ const writer = writerValue('stdio');+ await registerLocalWriterValue(engine, writer);+ const rows = (id: string) => engine.executeRaw<{ lane: string; revoked: boolean }>('SELECT lane, revoked_at IS NOT NULL AS revoked FROM persistence_local_writers WHERE id=$1::uuid', [id]);+ expect(await codeOf(registerLocalWriterValue(racedRead(engine), writer))).toBe('resolved');+ expect(await codeOf(registerLocalWriterValue(racedRead(engine), { ...writer, credential: randomBytes(32).toString('hex') }))).toBe('permission_denied');+ expect(await codeOf(registerLocalWriterValue(racedRead(engine), { ...writer, lane: 'cli' }))).toBe('permission_denied');+ const other = randomUUID();+ expect(await codeOf(registerLocalWriterValue(racedRead(engine), { ...writer, id: other }))).toBe('permission_denied');+ expect(await rows(other)).toEqual([]);+ expect(await revokeLocalWriter(engine, writer.id)).toBe(true);+ expect(await codeOf(registerLocalWriterValue(racedRead(engine), writer))).toBe('permission_denied');+ expect(await rows(writer.id)).toEqual([{ lane: 'stdio', revoked: true }]);+ } finally {+ await engine.disconnect();+ }+ }, 120_000);++ test('first writes made at once from one writer value all land under one registration', async () => {+ const writer = writerValue('stdio');+ const engine = await openEngine(settingsFor({ writer }));+ try {+ await engine.initSchema();+ const outcomes = await Promise.all([0, 1, 2, 3].map(i => codeOf(operationsByName.put_page.handler(hostCtx(engine),+ { slug: `notes/first-write-${i}`, content: `---\ntitle: First write ${i}\n---\nEngine write ${i}.\n` }))));+ expect(outcomes).toEqual(['resolved', 'resolved', 'resolved', 'resolved']);+ expect(await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_local_writers WHERE id=$1::uuid', [writer.id])).toEqual([{ n: 1 }]);+ } finally {+ await engine.disconnect();+ }+ }, 120_000);+test('the authority path uses the writer given at open; with none, a write refuses and no credential file is minted', async () => {const { gbrainHome, env } = canaries();const writer = writerValue('stdio');