Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(D5): disk PGLite brains clone one per-process template

garrytan89318e1bf1a4
diff --git a/test/helpers/brain-template.test.ts b/test/helpers/brain-template.test.ts
new file mode 100644
index 0000000000..cd79ec762d
--- /dev/null
+++ b/test/helpers/brain-template.test.ts
@@ -0,0 +1,61 @@
+/**
+ * brain-template clones are independent brains and never touch the template.
+ *
+ * Protects: the ENG-8 contract of test/helpers/brain-template.ts (distinct
+ * brain identity per clone, independent writes, template bytes unchanged).
+ * Fails when: a clone keeps the template's brain_id, source incarnation or
+ * skill token, two clones share storage, or cloning or writing to a clone
+ * changes the template directory.
+ * Seam: none.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative } from 'node:path';
+import type { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { brainTemplateDir, connectTemplateBrain } from './brain-template.ts';
+
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-template-test-'));
+const engines: PGLiteEngine[] = [];
+afterAll(async () => {
+ for (const engine of engines) await engine.disconnect();
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+function treeDigest(root: string): string {
+ const hash = createHash('sha256');
+ const visit = (dir: string) => {
+ for (const name of readdirSync(dir).sort()) {
+ const path = join(dir, name);
+ hash.update(relative(root, path));
+ if (statSync(path).isDirectory()) visit(path);
+ else hash.update(readFileSync(path));
+ }
+ };
+ visit(root);
+ return hash.digest('hex');
+}
+
+const identity = (engine: PGLiteEngine) => engine.executeRaw<{ brain_id: string; incarnation: string; token_secret: string }>(
+ `SELECT (SELECT brain_id FROM persistence_brain WHERE singleton=1) AS brain_id,
+ (SELECT incarnation::text FROM sources WHERE id='default') AS incarnation,
+ (SELECT token_secret FROM shared_skill_state WHERE singleton=1) AS token_secret`).then(rows => rows[0]);
+
+test('two concurrent clones are distinct, independent brains and the template is unchanged', async () => {
+ const template = await brainTemplateDir();
+ const before = treeDigest(template);
+ const [a, b] = await Promise.all([connectTemplateBrain(join(scratch, 'a')), connectTemplateBrain(join(scratch, 'b'))]);
+ engines.push(a, b);
+
+ const [idA, idB] = await Promise.all([identity(a), identity(b)]);
+ expect(idA.brain_id).not.toBe(idB.brain_id);
+ expect(idA.incarnation).not.toBe(idB.incarnation);
+ expect(idA.token_secret).not.toBe(idB.token_secret);
+
+ await a.putPage('notes/only-in-a', { type: 'note', title: 'Only in A', compiled_truth: 'Example body.', timeline: '', frontmatter: {} });
+ expect(await a.getPage('notes/only-in-a')).not.toBeNull();
+ expect(await b.getPage('notes/only-in-a')).toBeNull();
+
+ expect(treeDigest(template)).toBe(before);
+}, 120_000);
diff --git a/test/helpers/brain-template.ts b/test/helpers/brain-template.ts
new file mode 100644
index 0000000000..c455d2091d
--- /dev/null
+++ b/test/helpers/brain-template.ts
@@ -0,0 +1,71 @@
+/**
+ * Disk-backed PGLite brains cloned from one initialized template per process.
+ *
+ * A fresh disk brain (`connect({ database_path }) + initSchema()`) replays
+ * every migration (~3 s; the schema snapshot only serves in-memory engines).
+ * A clone copies an initialized data directory and reopens it (~1 s).
+ *
+ * Contract:
+ * - One template per process and embedding shape, initialized into a
+ * private cache directory and disconnected before any copy.
+ * - The template is captured right after initSchema: no source
+ * registration, writer registration or physical-root reservation exists
+ * in it (asserted), and nothing outside the data directory is copied, so
+ * locks, reservations and runtime files never travel.
+ * - Each clone gets its own brain identity: brain_id, the default source
+ * incarnation, and the shared-skill token secret and serving epoch are
+ * regenerated. Host identity lives in the caller's GBRAIN_HOME.
+ *
+ * Use it for fixtures that need any initialized disk brain. Tests of
+ * `gbrain init` or migration behavior keep a real initSchema on an empty
+ * directory.
+ */
+import { randomBytes } from 'node:crypto';
+import { cpSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { getEmbeddingDimensions, getEmbeddingModel } from '../../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+
+const templates = new Map<string, Promise<string>>();
+
+async function buildTemplate(): Promise<string> {
+ const cache = mkdtempSync(join(tmpdir(), 'gbrain-brain-template-'));
+ process.once('exit', () => rmSync(cache, { recursive: true, force: true }));
+ const dataDir = join(cache, 'brain');
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ try {
+ await engine.initSchema();
+ const [state] = await engine.executeRaw<{ sources: number; writers: number }>(
+ "SELECT (SELECT count(*)::int FROM sources WHERE id <> 'default') AS sources, (SELECT count(*)::int FROM persistence_local_writers) AS writers");
+ if (state.sources || state.writers) throw new Error('brain-template: the template must be captured before any source or writer registration');
+ } finally { await engine.disconnect(); }
+ return dataDir;
+}
+
+/** The template data directory for the current embedding shape (built on first use). */
+export function brainTemplateDir(): Promise<string> {
+ const key = `${getEmbeddingModel()}:${getEmbeddingDimensions()}`;
+ let template = templates.get(key);
+ if (!template) {
+ template = buildTemplate();
+ templates.set(key, template);
+ template.catch(() => templates.delete(key));
+ }
+ return template;
+}
+
+/** Copies the template into `dataDir` (which must not exist) and returns a connected engine with a fresh brain identity. */
+export async function connectTemplateBrain(dataDir: string): Promise<PGLiteEngine> {
+ cpSync(await brainTemplateDir(), dataDir, { recursive: true, errorOnExist: true, force: false });
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ try {
+ await engine.initSchema();
+ await engine.executeRaw('UPDATE persistence_brain SET brain_id=gen_random_uuid() WHERE singleton=1');
+ await engine.executeRaw("UPDATE sources SET incarnation=gen_random_uuid() WHERE id='default'");
+ await engine.executeRaw('UPDATE shared_skill_state SET token_secret=$1, serving_epoch=gen_random_uuid() WHERE singleton=1', [randomBytes(32).toString('hex')]);
+ } catch (error) { await engine.disconnect(); throw error; }
+ return engine;
+}
diff --git a/test/helpers/connector-fixture.ts b/test/helpers/connector-fixture.ts
index 81e853876f..e7b42d1c8e 100644
--- a/test/helpers/connector-fixture.ts
+++ b/test/helpers/connector-fixture.ts
@@ -4,7 +4,6 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
import type { GBrainConfig } from '../../src/core/config.ts';
-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { claimWorktree } from '../../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
import { isolatedPersistencePostgres } from './persistence-postgres.ts';
@@ -12,6 +11,7 @@ import { syncLockId } from '../../src/core/db-lock.ts';
import { testBackends } from './test-backends.ts';
import { CONNECTOR_WAIT_BUDGET_MS, connectorWaitBudget } from '../../src/core/persistence/connector-sync.ts';
import { testWaitMs } from './wait-for.ts';
+import { connectTemplateBrain } from './brain-template.ts';
import { readManagedConnectorState } from '../../src/core/persistence/connector-state.ts';
export const options = { noEmbed: true, noExtract: true, noSchemaPack: true };
@@ -53,10 +53,7 @@ export function createConnectorFixture() {
// Paused-owner fixtures stop on a 1.5 s wait budget instead of the production 30 s.
connectorWaitBudget.ms = testWaitMs(1_500);
if (backends.includes('pglite')) {
- const lite = new PGLiteEngine();
- await lite.connect({ database_path: join(home, 'database') });
- await lite.initSchema();
- engines.push(lite);
+ engines.push(await connectTemplateBrain(join(home, 'database')));
}
if (backends.includes('postgres')) {
const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);