Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): registering the same writer value at once is idempotent
Brad Gesslerf55ed7f2007b
diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.tsindex 6c158d160f..2b0e710386 100644--- a/src/core/persistence/identity.ts+++ b/src/core/persistence/identity.ts@@ -238,19 +238,34 @@ async function ensureLocalWriterRow(engine: BrainEngine, lane: 'cli' | 'stdio',const existing = await ensureRegistrationRow(engine, local, grant, () => credentialMismatch(path, local.id, lane));return { local, ...(existing ? { existing } : {}) };}-/** Inserts `local`'s row unless it exists; a revoked row, or one with another lane or credential, refuses. Returns the row it read. */+/**+ * Inserts `local`'s row unless it exists; a revoked row, or one with another lane or credential, refuses. Returns the row it+ * read (undefined when it inserted the registration). Two callers registering the same value at once both read no row and+ * both insert: the insert names no conflict target, because the loser can meet the winner's row on the credential hash's+ * unique index before the id's, and either conflict means the registration may already be there. The loser then reads the+ * row the winner wrote and checks it like any existing one; a credential registered under another id refuses.+ */async function ensureRegistrationRow(engine: SqlEngine, local: LocalRegistration, grant: LocalGrant, mismatch: () => OperationError): Promise<LocalWriterRow | undefined> {- const [existing] = await engine.executeRaw<LocalWriterRow>(- 'SELECT revoked_at,credential_hash,lane,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid', [local.id]);- if (existing?.revoked_at != null) throw new OperationError('permission_denied', 'This local writer registration was revoked.', 'Explicitly register a new writer to authorize future work.');- if (existing && (existing.lane !== local.lane || existing.credential_hash !== sha256(local.credential))) throw mismatch();- // A registered writer is left as it is (the insert would conflict and do nothing).- if (!existing) {- await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)- VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT(id) DO NOTHING`, [local.id, local.lane, sha256(local.credential), JSON.stringify(grant)]);- forgetRequestIdentity();- }- return existing;+ const read = async () => (await engine.executeRaw<LocalWriterRow>(+ 'SELECT revoked_at,credential_hash,lane,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid', [local.id]))[0];+ const check = (row: LocalWriterRow): LocalWriterRow => {+ if (row.revoked_at != null) throw new OperationError('permission_denied', 'This local writer registration was revoked.', 'Explicitly register a new writer to authorize future work.');+ if (row.lane !== local.lane || row.credential_hash !== sha256(local.credential)) throw mismatch();+ return row;+ };+ const existing = await read();+ // A registered writer is left as it is.+ if (existing) return check(existing);+ const inserted = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)+ VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`, [local.id, local.lane, sha256(local.credential), JSON.stringify(grant)]);+ // This request read the registration as missing; its later checks read it again either way.+ forgetRequestIdentity();+ if (inserted.length > 0) return undefined;+ const raced = await read();+ if (!raced) throw opError('permission_denied', 'This local writer credential is registered under another id.',+ `The credential given for registration ${local.id} already belongs to another registration in this brain's database, so nothing was registered. A credential authorizes one registration: pass that registration's own id, or a new credential.`,+ { fix: registrationsFix() });+ return check(raced);}/*** Registers a local writer whose credential the host holds as a value: the row in `persistence_local_writers` and nodiff --git a/test/e2e/engine-open-postgres.test.ts b/test/e2e/engine-open-postgres.test.tsindex 99bf53df1b..41614286e6 100644--- a/test/e2e/engine-open-postgres.test.ts+++ b/test/e2e/engine-open-postgres.test.ts@@ -51,7 +51,7 @@ beforeAll(async () => {if (!DATABASE_URL) return;assertSafeE2eDatabaseUrl(DATABASE_URL);const admin = postgres(DATABASE_URL, { max: 1, prepare: false });- for (let i = 0; i < 3; i++) {+ for (let i = 0; i < 4; i++) {const name = `gbrain_test_engine_open_${randomUUID().replaceAll('-', '')}`;await admin.unsafe(`CREATE DATABASE ${name}`);const url = new URL(DATABASE_URL);@@ -118,6 +118,26 @@ describeE2E('openEngine on Postgres', () => {expect(filesUnder(home)).toEqual([]);}, 300_000);+ test('engines opened from one writer value all make their first write at once: one registration, no refusal', async () => {+ const seed = await openEngine({ embedded_core: true, engine: 'postgres', database: { url: urls[3]! }, pool: { max: 2 }, host: { id: randomUUID() } });+ try { await seed.initSchema(); } finally { await seed.disconnect(); }+ // Each round is a fresh writer, so every round is that writer's first write; the race is between the+ // registration read finding no row and the insert, so it takes a few rounds to land.+ for (let round = 0; round < 12; round++) {+ const settings = { embedded_core: true, engine: 'postgres', database: { url: urls[3]! }, pool: { max: 2 }, host: { id: randomUUID() }, writer: writerValue() } as EngineSettings;+ const engines = await Promise.all([0, 1, 2, 3].map(() => openEngine({ ...settings, writer: { ...settings.writer! } })));+ try {+ const outcomes = await Promise.all(engines.map((engine, i) => codeOf(operationsByName.put_page.handler(hostCtx(engine),+ { slug: `notes/first-write-${round}-${i}`, content: `---\ntitle: First write ${i}\n---\nRound ${round}, engine ${i}.\n` }))));+ expect(outcomes).toEqual(['resolved', 'resolved', 'resolved', 'resolved']);+ const rows = await engines[0]!.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_local_writers WHERE id=$1::uuid', [settings.writer!.id]);+ expect(rows).toEqual([{ n: 1 }]);+ } finally {+ await Promise.all(engines.map(engine => engine.disconnect()));+ }+ }+ }, 300_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 a37a4c1a7a..6751780547 100644--- a/test/engine-open.test.ts+++ b/test/engine-open.test.ts@@ -296,7 +296,7 @@ describe('host identity', () => {});describe('writer given as a value', () => {- test('registration is idempotent; another credential or lane under its id refuses; a revoked one is never replaced', async () => {+ test('registration is idempotent; another credential or lane under its id, or its credential under another id, refuses; a revoked one is never replaced', async () => {const engine = await openEngine(settingsFor());try {await engine.initSchema();@@ -307,6 +307,8 @@ describe('writer given as a value', () => {expect(await rows()).toEqual([{ lane: 'stdio', revoked: false }]);expect(await codeOf(registerLocalWriterValue(engine, { ...writer, credential: randomBytes(32).toString('hex') }))).toBe('permission_denied');expect(await codeOf(registerLocalWriterValue(engine, { ...writer, lane: 'cli' }))).toBe('permission_denied');+ // The same credential under another id is that other registration's, not a second one.+ expect(await codeOf(registerLocalWriterValue(engine, { ...writer, id: randomUUID() }))).toBe('permission_denied');expect(await codeOf(registerLocalWriterValue(engine, { ...writer, id: 'not-a-uuid' }))).toBe('engine_settings_invalid');expect(await codeOf(registerLocalWriterValue(engine, { ...writer, credential: 'x'.repeat(31) }))).toBe('engine_settings_invalid');expect(await codeOf(registerLocalWriterValue(engine, { ...writer, lane: 'http' as 'cli' }))).toBe('engine_settings_invalid');