Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
backup create: remove gbrain's dead IPC sockets from the PGLite data dir before the dump; typed backup_dump_failed names what blocks it (#5312)
garrytan8a24f0f21f57
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a20918744e..be8349aa45 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -164,6 +164,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| The autopilot job is bound to a different brain. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### backup_dump_failed++<a id="backup_dump_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| `gbrain backup create` could not dump the PGLite data dir: an entry PGLite cannot read (a socket, FIFO or symlink that is not a dead gbrain socket) is still inside it. | The backup removes only gbrain's own IPC sockets, and only when nothing listens on them; a live gbrain socket, a foreign socket or FIFO, or a symlink is left in place and named in the message, because the database lock proves no other PGLite owner, not who owns an arbitrary endpoint. | Stop the process that uses each named entry (or move the entry out of the data dir), then rerun the same `gbrain backup create` command. Do not delete an entry something is still listening on. Run: gbrain doctor --json | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database](../../docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database)+### benchmark_duplicate_task_id<a id="benchmark_duplicate_task_id"></a>diff --git a/docs/guides/in-agent-setup.md b/docs/guides/in-agent-setup.mdindex 0afe723ee0..8ecc6222fa 100644--- a/docs/guides/in-agent-setup.md+++ b/docs/guides/in-agent-setup.md@@ -188,6 +188,17 @@ destination on a local filesystem with Windows ACL support and permittedWindows PowerShell. A busy database or achanging file fails the operation instead of publishing a success receipt.+Before the dump, the command removes gbrain's own IPC socket files+(`.gbrain-resolve.sock`, `.gbrain-persistence.sock`) from the data dir when+nothing listens on them, so a `gbrain serve` that was killed does not block+later backups; each removal is listed in the archive's `omitted` inventory.+Any other socket, FIFO or symlink in the data dir is left alone and the+command refuses with `backup_dump_failed` naming it: stop the process that+uses it (or move it out of the data dir) and run the same command again.+This cleanup is verified on Linux and macOS; on Windows a stale socket is+removed through the native lock binding and has not been exercised on a+native runner.+| Included | Excluded or inventoried for reconnection || --- | --- || Full PGLite database: pages, DB-only facts, jobs, settings, authentication state, and other tables | Runtime packages, Bun, caches, Git metadata, previous backups |diff --git a/src/core/backup/runtime-artefacts.ts b/src/core/backup/runtime-artefacts.tsnew file mode 100644index 0000000000..97fe8f76c8--- /dev/null+++ b/src/core/backup/runtime-artefacts.ts@@ -0,0 +1,94 @@+/**+ * #5312: gbrain's own IPC endpoints live INSIDE the PGLite data dir+ * (`resolveSocketPathForConfig` → `<database_path>/.gbrain-<kind>.sock`), and+ * PGLite's `dumpDataDir` cannot read a non-regular file, so one socket left by+ * a killed `gbrain serve` wedges every later `backup create` until a human+ * deletes it. The sweep below runs under the engine's writer lock, right+ * before the dump, and removes ONLY those two gbrain artefacts, ONLY when their+ * holder is provably dead (no bind claim holder AND no live listener). Any+ * other socket, FIFO or symlink at the data dir's top level is left in place+ * and named, so the typed `backup_dump_failed` refusal tells the operator what+ * blocks the dump instead of a bare WASI errno. Symlinks are never followed and+ * regular files are never deleted: the engine lock proves there is no PGLite+ * owner, not that an arbitrary endpoint belongs to a dead gbrain process.+ */+import { lstatSync, readdirSync, unlinkSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { resolveSocketPathForConfig, socketHasLiveListener } from '../context/resolve-ipc.ts';+import { claimLocalIpcBinding } from '../context/ipc-path.ts';+import { AgentInstallError } from '../agent-install/state.ts';++export type KeptArtefactReason = 'live_listener' | 'symlink' | 'not_a_socket' | 'foreign_socket' | 'foreign_fifo';++export interface RuntimeArtefactSweep {+ /** gbrain runtime sockets whose holder was dead; unlinked before the dump. */+ removed: string[];+ /** Non-regular entries the sweep refused to touch, with the reason it left each one. */+ kept: { path: string; reason: KeptArtefactReason }[];+}++const GBRAIN_SOCKET_KINDS = ['resolve', 'persistence'] as const;++function entryStat(path: string) {+ try { return lstatSync(path); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }+}++/** Remove gbrain's dead runtime sockets from `dataDir`; list every other non-regular top-level entry. Call only while holding the PGLite writer lock. */+export async function sweepStaleRuntimeArtefacts(dataDir: string): Promise<RuntimeArtefactSweep> {+ const dir = resolve(dataDir);+ const sweep: RuntimeArtefactSweep = { removed: [], kept: [] };+ const owned = new Set<string>();+ for (const kind of GBRAIN_SOCKET_KINDS) {+ const path = resolveSocketPathForConfig({ engine: 'pglite', database_path: dataDir }, kind);+ // A path budget overflow relocates the socket under the system temp root; nothing in the data dir then.+ if (!path || dirname(resolve(path)) !== dir) continue;+ owned.add(resolve(path));+ const stat = entryStat(path);+ if (!stat) continue;+ if (stat.isSymbolicLink()) { sweep.kept.push({ path, reason: 'symlink' }); continue; }+ if (!stat.isSocket()) { sweep.kept.push({ path, reason: 'not_a_socket' }); continue; }+ // An accepted (or timed-out) probe connect means "not ours to remove"; the+ // bind claim a live serve retains for its whole lifetime is taken only for a+ // dead-looking socket, so removal is serialized with a serve starting up,+ // and the probe is repeated under it before anything is unlinked.+ if (await socketHasLiveListener(path)) { sweep.kept.push({ path, reason: 'live_listener' }); continue; }+ const binding = await claimLocalIpcBinding(path).catch(() => null);+ if (!binding) { sweep.kept.push({ path, reason: 'live_listener' }); continue; }+ try {+ if (await socketHasLiveListener(path)) { sweep.kept.push({ path, reason: 'live_listener' }); continue; }+ if (binding.removeStaleWindowsSocket) binding.removeStaleWindowsSocket();+ else unlinkSync(path);+ sweep.removed.push(path);+ } finally { await binding.release(); }+ }+ for (const name of readdirSync(dir).sort()) {+ const path = join(dir, name);+ if (owned.has(path)) continue;+ const stat = entryStat(path);+ if (!stat) continue;+ if (stat.isSymbolicLink()) sweep.kept.push({ path, reason: 'symlink' });+ else if (stat.isSocket()) sweep.kept.push({ path, reason: 'foreign_socket' });+ else if (stat.isFIFO()) sweep.kept.push({ path, reason: 'foreign_fifo' });+ }+ return sweep;+}++const KEPT_REASON_TEXT: Record<KeptArtefactReason, string> = {+ live_listener: 'a gbrain socket something is still listening on',+ symlink: 'a symbolic link (not followed)',+ not_a_socket: 'a regular file where a gbrain socket is expected',+ foreign_socket: 'a socket gbrain does not own',+ foreign_fifo: 'a FIFO gbrain does not own',+};++/** The typed refusal for a `dumpDataDir` failure: the WASI errno plus every non-regular entry the sweep left in the data dir. */+export function backupDumpFailed(cause: unknown, sweep: RuntimeArtefactSweep): AgentInstallError {+ const detail = (typeof cause === 'object' && cause !== null ? cause : {}) as { errno?: unknown; message?: unknown };+ const errno = typeof detail.errno === 'number' ? ` (errno ${detail.errno})` : '';+ const kept = sweep.kept.map(entry => `${entry.path}: ${KEPT_REASON_TEXT[entry.reason]}`);+ const blockers = kept.length+ ? ` The data dir holds entries the dump cannot read and the backup will not remove: ${kept.join('; ')}. Stop the process using each one, or move it out of the data dir, then retry.`+ : typeof detail.message === 'string' && detail.message.trim() ? ` ${detail.message.trim()}` : '';+ return new AgentInstallError('backup_dump_failed', `PGLite could not dump the data dir${errno}.${blockers}`);+}diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.tsindex 59a065cf5d..5a23ec2e7f 100644--- a/src/core/backup/snapshot.ts+++ b/src/core/backup/snapshot.ts@@ -7,6 +7,7 @@ import { PGLiteEngine } from '../pglite-engine.ts';import { acquireBootstrapLock } from '../bootstrap/lock.ts';import { configDir, type GBrainConfig } from '../config.ts';import { LATEST_VERSION } from '../migrate.ts';+import { backupDumpFailed, sweepStaleRuntimeArtefacts } from './runtime-artefacts.ts';import { AgentInstallError, checkedManagedPaths, checkedRoot, confinedPath, privateWrite, readFileConfigState, readInstallReceipt, syncDirectory, type AgentInstallReceipt } from '../agent-install/state.ts';import { extractPgliteDump, hashFile, isBackupArchiveFile, readBackupArchive, writeBackupArchive, type ArchiveManifest } from './archive.ts';import { quarantineRestoredExecution, rebaseRestorePath, relativeBackupPath, type RestoreQuarantine } from './quarantine.ts';@@ -163,7 +164,9 @@ export async function createPgliteBackup(options: { output: string; root?: strinconst externalPaths: string[] = [];rebaseManagedConfig(state.config, root, root, managedPaths, externalPaths);const inventoryBefore = originals.map(path => ({ path, ...hashFile(confinedPath(root, path)) }));- const dump = await engine.db.dumpDataDir('none');+ // Under the writer lock: a dead serve's IPC socket in the data dir would fail the dump (#5312).+ const sweep = await sweepStaleRuntimeArtefacts(dbPath);+ const dump = await engine.db.dumpDataDir('none').catch(cause => { throw backupDumpFailed(cause, sweep); });privateWrite(join(work, 'database.tar'), new Uint8Array(await dump.arrayBuffer()));const files = [{ path: 'database.tar', file: join(work, 'database.tar') },@@ -186,6 +189,7 @@ export async function createPgliteBackup(options: { output: string; root?: strin'Unmanaged files, including .gbrain/credential-deliveries, browser sessions, git metadata, caches and prior backups outside managed data paths, are not included.',...excludedPaths,...externalPaths,+ ...sweep.removed.map(path => `Removed stale runtime socket left by an exited gbrain process: ${path}`),...(state.config.storage && (state.config.storage as { backend?: string }).backend !== 'local' ? ['Remote object storage content is not included; reconnect and verify the configured storage backend.'] : []),...sources.filter(s => s.local_path && !s.managed_relative_path).map(s => `External source ${s.id}: ${s.local_path}`),'Native harness skills/routines must be reattached and verified; no platform account state is included.',diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 04f73052dd..4521a3acc7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -437,6 +437,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.165.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades. On a managed brain, `extract_entities` now writes stubs, timeline rows and backlinks through the coordinator (creating a stub needs permission to write pages); a refusal or pending write returns its error envelope and names the entities already written, instead of a raw `writer_coordinator_required` error or a silently missing timeline row.' },// Memory proof wave 2 W1 (question-ranked recall).{ since: '0.60.169.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },+ // Fix wave 15 G5 (GBRA-79).+ { since: '0.60.176.0', text: '`gbrain backup create` on a PGLite brain now removes gbrain\'s own IPC socket files (`.gbrain-resolve.sock`, `.gbrain-persistence.sock`) from the data dir before the dump when nothing listens on them, so a `serve` that was killed no longer blocks every later backup; each removal is listed in the archive\'s `omitted`. Any other socket, FIFO or symlink in the data dir is left alone and the backup refuses with `backup_dump_failed` naming it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex ca91d28e6a..20d40e9461 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -62,6 +62,7 @@ export const CODES = {approval_required: { class: 'consent', summary: "The change needs the owner's explicit approval before it can proceed." },autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },budget_below_recent_runtime: { class: 'unavailable', summary: "The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend.", why: 'An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed.', docs: 'docs/guides/dream-patterns.md#budget-sizing', suggestion: 'Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`.' },+ backup_dump_failed: { class: 'host_only', summary: "`gbrain backup create` could not dump the PGLite data dir: an entry PGLite cannot read (a socket, FIFO or symlink that is not a dead gbrain socket) is still inside it.", why: "The backup removes only gbrain's own IPC sockets, and only when nothing listens on them; a live gbrain socket, a foreign socket or FIFO, or a symlink is left in place and named in the message, because the database lock proves no other PGLite owner, not who owns an arbitrary endpoint.", docs: 'docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database', suggestion: 'Stop the process that uses each named entry (or move the entry out of the data dir), then rerun the same `gbrain backup create` command. Do not delete an entry something is still listening on.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only: reports the brain's lock holders and storage state so the user can see what still runs against the data dir.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },benchmark_duplicate_task_id: { class: 'caller', summary: "Benchmark duplicate task id." },benchmark_empty: { class: 'caller', summary: "The benchmark file has no tasks." },benchmark_exists: { class: 'caller', summary: "A benchmark already exists at the target path." },diff --git a/test/backup-stale-socket-5312.test.ts b/test/backup-stale-socket-5312.test.tsnew file mode 100644index 0000000000..64a78c96a9--- /dev/null+++ b/test/backup-stale-socket-5312.test.ts@@ -0,0 +1,155 @@+/**+ * #5312 (defect 2): gbrain's IPC sockets live inside the PGLite data dir and+ * `dumpDataDir` cannot read a non-regular file, so a socket left behind by a+ * killed `gbrain serve` wedged every later `backup create` (WASI errno 28 on+ * Linux, errno 2 on Windows) until a human deleted it by hand.+ *+ * `createPgliteBackup` now sweeps the data dir under its writer lock before+ * the dump and removes ONLY gbrain's own `.gbrain-<kind>.sock` endpoints, ONLY+ * when nothing holds their bind claim or answers a probe connect. Everything+ * else at the top level (a live gbrain socket, a foreign socket or FIFO, a+ * symlink) stays, and the refusal is the typed `backup_dump_failed` naming it.+ *+ * Linux-verified: the Windows AF_UNIX reparse-point branch (`removeStaleWindowsSocket`)+ * is exercised only on a native Windows runner.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { execFileSync, spawn } from 'node:child_process';+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';+import * as net from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { privateWrite } from '../src/core/agent-install/state.ts';+import { createPgliteBackup } from '../src/core/backup/snapshot.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resolveSocketPathForConfig } from '../src/core/context/resolve-ipc.ts';++const posix = process.platform !== 'win32';+let temporary: string;+let root: string;+let dataDir: string;+let outputs = 0;++/** A child that listens on `path` and is SIGKILLed: the socket file outlives it, exactly like a crashed serve. */+async function leaveStaleSocket(path: string): Promise<void> {+ const child = spawn(process.execPath, ['-e', `const net = require('node:net'); const s = net.createServer(); s.listen(${JSON.stringify(path)}, () => console.log('listening')); setInterval(() => {}, 1000);`], { stdio: ['ignore', 'pipe', 'inherit'] });+ await new Promise<void>((resolve, reject) => {+ child.stdout!.on('data', (chunk: Buffer) => { if (String(chunk).includes('listening')) resolve(); });+ child.on('exit', code => reject(new Error(`listener exited early (${code})`)));+ });+ const exited = new Promise(resolve => child.on('exit', resolve));+ child.kill('SIGKILL');+ await exited;+ expect(lstatSync(path).isSocket()).toBe(true);+}++/** Byte-level fingerprint of the regular files in the data dir top level plus the entry names: the "source intact" witness. */+function dataDirFingerprint(): string {+ const hash = createHash('sha256');+ for (const name of readdirSync(dataDir).sort()) {+ const stat = lstatSync(join(dataDir, name));+ hash.update(`${name}:${stat.isSocket() ? 'socket' : stat.isFIFO() ? 'fifo' : stat.isSymbolicLink() ? 'symlink' : stat.isDirectory() ? 'dir' : 'file'}\n`);+ if (stat.isFile()) hash.update(readFileSync(join(dataDir, name)));+ }+ return hash.digest('hex');+}++function nextOutput(): string { return join(temporary, `out-${++outputs}.gbrain-backup`); }++async function backupFailure(): Promise<{ code: string; message: string }> {+ try { await createPgliteBackup({ output: nextOutput(), root }); }+ catch (error) { return error as { code: string; message: string }; }+ throw new Error('backup unexpectedly succeeded');+}++beforeAll(async () => {+ temporary = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-5312-socket-')));+ root = join(temporary, 'brain');+ mkdirSync(join(root, '.gbrain'), { recursive: true, mode: 0o700 });+ dataDir = join(root, '.gbrain', 'brain.pglite');+ privateWrite(join(root, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dataDir, embedding_disabled: true }));+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: dataDir });+ try {+ await engine.initSchema();+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Survives the backup.' });+ } finally { await engine.disconnect(); }+});++afterAll(() => { rmSync(temporary, { recursive: true, force: true }); });++test.if(posix)('a stale gbrain socket from a SIGKILLed holder is removed, the dump succeeds and omitted names the removal', async () => {+ const socket = resolveSocketPathForConfig({ engine: 'pglite', database_path: dataDir }, 'persistence')!;+ expect(socket).toBe(join(dataDir, '.gbrain-persistence.sock'));+ await leaveStaleSocket(socket);+ const output = nextOutput();+ const { manifest } = await createPgliteBackup({ output, root });+ expect(existsSync(socket)).toBe(false);+ expect(statSync(output).size).toBeGreaterThan(0);+ expect(manifest.entries.map(e => e.path)).toContain('database.tar');+ const omitted = (manifest as unknown as { omitted: string[] }).omitted;+ expect(omitted).toContain(`Removed stale runtime socket left by an exited gbrain process: ${socket}`);+});++test.if(posix)('a live listener on a gbrain socket without a PGLite owner is kept and the dump refuses with backup_dump_failed', async () => {+ const socket = join(dataDir, '.gbrain-resolve.sock');+ const server = net.createServer();+ await new Promise<void>(resolve => server.listen(socket, () => resolve()));+ try {+ const before = dataDirFingerprint();+ const failure = await backupFailure();+ expect(failure.code).toBe('backup_dump_failed');+ expect(failure.message).toContain(socket);+ expect(failure.message).toContain('still listening');+ expect(lstatSync(socket).isSocket()).toBe(true);+ // The listener is untouched: it still accepts a connection.+ await new Promise<void>((resolve, reject) => { const c = net.connect(socket, () => { c.destroy(); resolve(); }); c.on('error', reject); });+ expect(dataDirFingerprint()).toBe(before);+ } finally { await new Promise(resolve => server.close(resolve)); }+});++test.if(posix)('a FIFO gbrain does not own is left in place and named', async () => {+ const fifo = join(dataDir, '.operator-tap.fifo');+ execFileSync('mkfifo', [fifo]);+ try {+ const before = dataDirFingerprint();+ const failure = await backupFailure();+ expect(failure.code).toBe('backup_dump_failed');+ expect(failure.message).toContain(fifo);+ expect(failure.message).toContain('FIFO gbrain does not own');+ expect(lstatSync(fifo).isFIFO()).toBe(true);+ expect(dataDirFingerprint()).toBe(before);+ } finally { unlinkSync(fifo); }+});++test.if(posix)('a symlink in place of the gbrain socket is not followed: the link and its target stay', async () => {+ const elsewhere = join(temporary, 'elsewhere.sock');+ await leaveStaleSocket(elsewhere);+ const link = join(dataDir, '.gbrain-persistence.sock');+ symlinkSync(elsewhere, link);+ try {+ const failure = await backupFailure();+ expect(failure.code).toBe('backup_dump_failed');+ expect(failure.message).toContain(link);+ expect(failure.message).toContain('symbolic link');+ expect(lstatSync(link).isSymbolicLink()).toBe(true);+ expect(lstatSync(elsewhere).isSocket()).toBe(true);+ } finally { unlinkSync(link); unlinkSync(elsewhere); }+});++test.if(posix)('a dump failure leaves the data dir intact and the next backup of the same brain succeeds', async () => {+ const fifo = join(dataDir, '.operator-tap.fifo');+ execFileSync('mkfifo', [fifo]);+ const before = dataDirFingerprint();+ try {+ expect((await backupFailure()).code).toBe('backup_dump_failed');+ expect(dataDirFingerprint()).toBe(before);+ } finally { unlinkSync(fifo); }+ // Nothing of the failed attempt is left behind, the writer lock is free again and the brain dumps.+ expect(readdirSync(temporary).filter(name => name.startsWith('.gbrain-backup-'))).toEqual([]);+ const output = nextOutput();+ const { manifest } = await createPgliteBackup({ output, root });+ expect(manifest.entries.map(e => e.path)).toContain('database.tar');+ expect(statSync(output).size).toBeGreaterThan(0);+});