Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): unavailable process identity probes read as unknown (#6774)
garrytan3db5680cfea5
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.mdindex 575c73f450..dd3d9b755d 100644--- a/docs/architecture/key-files/core-persistence-graduation.md+++ b/docs/architecture/key-files/core-persistence-graduation.md@@ -11,7 +11,7 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo- `src/core/persistence/graduation-errors.ts` — one builder per graduation code (`sourceWriterHeldError` … `engineGraduatedError`) so the orchestrator, CLI, serve and doctor render each refusal one way: `why`, a filled `fix` with real argv (none only for `report`), a read-only verify (`gbrain migrate --status --json`, the `--plan` form, or doctor), `GRADUATION_DOCS` anchors, and the command helpers `planArgv`/`runArgv`/`resumeArgv`/`rollbackArgv`/`statusArgv`, which echo the user's `--to` spelling and name the URL only through `--url-env`. Test: `test/graduation-errors.test.ts` (table-driven over every code; each emitted argv names a real command with accepted flags and parses to its graduation mode).- `src/core/persistence/graduation-serve-guard.ts` — file reads only (marker, tombstone, config, manifest summary; never a lock attempt): `serveGraduationStartRefusal` (a serve launched while another live run owns the host brain exits 75 with `graduation_in_progress`, called from `connectCliOnlyEngine` in `src/cli.ts`), `graduationStatusReason` (a tombstoned path is status-only `engine_graduated`), `exitOnEngineIdentityChange` (status-only and degraded reconnect gates exit 75 for relaunch when the config names another engine, a tombstone appears or a run starts; a serve started with no config keeps recovering in place), `graduationHandoffRequested` (the resident stdio serve's 2 s marker poll in `installStdioLifecycle`), and `readGraduationManifestSummary` (the redacted view of the 0600 manifest). Test: `test/graduation-serve-guard.serial.test.ts` (includes a real `gbrain serve` child exiting 75 and `engine status --json`).- `src/core/persistence/engine-graduation.ts` — the orchestrator behind `gbrain migrate --to postgres`: `planGraduation` (zero mutations: probe-only source open, one read-only target session, refuses while a run is recorded non-terminal), `runGraduation` (needs `yes` plus `expectPlanHash`; a changed plan throws `preview_changed`), `resumeGraduation`, `rollbackGraduation`, `reconcileGraduation` and `graduationStatus` (files plus a read-only target-row read; split brain opens both datastores for counts). The kernel lock is held from step 1 to the routing flip: intent marker before the lock, autopilot pause marker, source open (waits up to 30 s for a resident serve's hand-off, else `graduation_source_writer_held`), in-process source doctor, route cross-check, drain and freeze, target fence, per-table copy with manifest checkpoints, deferred index build on the DDL route, verify (doctor child under `GBRAIN_GRADUATION_RUN`, plus `GBRAIN_GRADUATION_SOURCE_PERSISTENCE` naming the source's `persistence_brain.enabled`; #6331: `persistenceEnabledForHealth` in `ownership.ts` lets `sync_freshness` and `ownedContentFreshness` treat the fenced target as writer-owned only while its graduation row is this run's `verifying` target), then fence both and grant authority (source row `cutover`, lock-retaining close, move-aside, `O_EXCL` tombstone, one target transaction that sets `persistence_brain.enabled` and drops the fence) and flip routing (config, mounts). Every state change follows the transition tables and is mirrored into the 0600 manifest (`<GBRAIN_HOME>/.gbrain/graduation-manifest.json`, the only file holding target URLs) and the marker; each step announces its `graduationBoundary`. Resume continues from the recorded state with recorded identities; a resume after a lock gap recomputes source digests and re-drains and re-copies changed tables with their FK closure. Rollback before cutover abandons the target (fence kept); after cutover it requires the retained copy (checked before the fence and again under the kernel lock; gone refuses `not_found` via `retainedCopyMissingError` with nothing changed), fences first, takes the kernel lock, compares (`graduation-losses.ts`) and returns the target to authority on any refusal; `rollback_approved` onward only rolls forward. `--resume --yes` moves a stray datastore at the old path to `<path>.stray-<run_id>`. All refusals come from `graduation-errors.ts`. Tests: `test/graduation-state.test.ts`, `test/graduation-rollback.test.ts`, `test/e2e/graduation-*.test.ts`.-- `src/core/persistence/graduation-custody.ts` — filesystem custody and the open-path checks: the sibling intent marker (atomic replace, 0600, fsync), the `O_CREAT|O_EXCL` tombstone at the old data dir path, `inspectGraduationPath` (`none`, `in_progress`, `interrupted`, `graduated`, `split_brain`; marker liveness from pid, boot id, pid namespace and process start time), `assertPgliteGraduationOpenable` (called by `PGLiteEngine` before `acquireLock`, so a tombstone refuses `engine_graduated` and a live run `graduation_in_progress` without touching the path, and again after the lock, refusing `graduation_interrupted` past cutover), `assertGraduationConnectAllowed` (every CLI connect: a non-authoritative target or a cut-over source refuses unless the session is the run's) and `assertGraduationAdmission` (writer admission). `moveAsideHeld` renames under the already-held kernel lock as a sanctioned filesystem publication (a managed brain's datastore is a managed root). Test: `test/graduation-custody.test.ts`.+- `src/core/persistence/graduation-custody.ts` — filesystem custody and the open-path checks: the sibling intent marker (atomic replace, 0600, fsync), the `O_CREAT|O_EXCL` tombstone at the old data dir path, `inspectGraduationPath` (`none`, `in_progress`, `interrupted`, `graduated`, `split_brain`; marker liveness from pid, boot id, pid namespace and process start time; a recorded boot id or pid namespace this process cannot read for itself is `unknown`, never a match), `assertPgliteGraduationOpenable` (called by `PGLiteEngine` before `acquireLock`, so a tombstone refuses `engine_graduated` and a live run `graduation_in_progress` without touching the path, and again after the lock, refusing `graduation_interrupted` past cutover), `assertGraduationConnectAllowed` (every CLI connect: a non-authoritative target or a cut-over source refuses unless the session is the run's) and `assertGraduationAdmission` (writer admission). `moveAsideHeld` renames under the already-held kernel lock as a sanctioned filesystem publication (a managed brain's datastore is a managed root). Tests: `test/graduation-custody.test.ts`, `test/graduation-custody-probes.test.ts` (probe mocked in a child via `test/fixtures/graduation-liveness-probe.ts`).- `src/core/persistence/graduation-schema.ts` + `src/core/schema-migrations/v201-persistence-graduation.ts` — the `persistence_graduation` singleton (each engine's own custody row; schema-owned, never copied) and `gbrain_graduation_fence()`. `installGraduationFence` puts a statement-level `ENABLE ALWAYS` trigger on every table that refuses writes unless `gbrain.graduation_run` equals the row's run id; `dropGraduationFence`, `setTargetState`/`setSourceState` (transition-table driven) and `withGraduationRun`.- `src/core/persistence/graduation-losses.ts` — rollback write detection: per carried table, the target digest against the verified receipt (`persistence_brain.enabled` through its transform), requests after the cutover sequence, and the security tables plus `fact_withdrawals` against the retained PGLite copy by identity and content (`last_used_at` ignored, expired OAuth tokens may disappear). Missing or changed security rows and new withdrawals are final.- `src/commands/migrate-graduation.ts` — the `gbrain migrate` graduation CLI, routed before connect from `routeEngineFreeSubcommands` in `src/cli.ts` when `routesToGraduation` holds (run-scoped verbs and `--plan` always; a bare `--to postgres|supabase` on a durable PGLite config unless `migrate.graduation` is false or the host is Windows). Without `--yes --expect` it plans and returns the `confirmation_required` payload (effects egress and destructive, what moves and what stays, `plan_hash`, the `--plan` preview; no stdin prompt); `--plan`/`--dry-run` prints the plan; the run reports the receipt, retained copy, target doctor, `gbrain mcp expose` and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for `graduation_in_progress`, 130 after SIGINT (stops at the next batch boundary). `--json` prints one document; progress goes to stderr per table and batch. Test: `test/migrate-graduation-cli.serial.test.ts`.diff --git a/src/core/persistence/graduation-custody.ts b/src/core/persistence/graduation-custody.tsindex 7c4a3e408c..7003f9b737 100644--- a/src/core/persistence/graduation-custody.ts+++ b/src/core/persistence/graduation-custody.ts@@ -98,14 +98,15 @@ export function currentProcessIdentity(): Pick<IntentMarker, 'pid' | 'bootId' |/*** Whether the marker's requesting process is still running. `unknown` when* the marker comes from another boot or PID namespace (another host on a- * shared filesystem, or a container); callers then treat the kernel lock as- * the authority (an acquirable lock means the run is gone).+ * shared filesystem, or a container), or recorded a boot id / PID namespace+ * this process cannot read for itself (#6774: an unavailable probe proves no+ * match); callers then treat the kernel lock as the authority (an acquirable+ * lock means the run is gone). A marker that recorded neither keeps the pid check.*/export function markerLiveness(marker: IntentMarker): 'alive' | 'dead' | 'unknown' {if (marker.pid === process.pid) return isGraduationRunInProcess(marker.runId) ? 'alive' : 'dead';- const bootId = readBootId(), pidNs = readPidNs();- if (marker.bootId && bootId && marker.bootId !== bootId) return 'unknown';- if (marker.pidNs && pidNs && marker.pidNs !== pidNs) return 'unknown';+ if (marker.bootId && marker.bootId !== readBootId()) return 'unknown';+ if (marker.pidNs && marker.pidNs !== readPidNs()) return 'unknown';if (!isProcessAlive(marker.pid)) return 'dead';if (marker.processStart) {const start = processStartTime(marker.pid);diff --git a/test/fixtures/graduation-liveness-probe.ts b/test/fixtures/graduation-liveness-probe.tsnew file mode 100644index 0000000000..071140f108--- /dev/null+++ b/test/fixtures/graduation-liveness-probe.ts@@ -0,0 +1,19 @@+/**+ * Child-process fixture for test/graduation-custody-probes.test.ts (#6774). It makes one local process-identity+ * probe unavailable with mock.module, in this child only, so every other suite keeps the real probes, then prints+ * markerLiveness for the marker passed as JSON.+ * argv: <bootId|pidNs|none> <marker json>+ */+import { mock } from 'bun:test';+import { join } from 'node:path';+import * as probes from '../../src/core/pglite-lock.ts';++const [missing, markerJson] = process.argv.slice(2);+const real = { ...probes };+mock.module(join(import.meta.dir, '../../src/core/pglite-lock.ts'), () => ({+ ...real,+ readBootId: missing === 'bootId' ? () => null : real.readBootId,+ readPidNs: missing === 'pidNs' ? () => null : real.readPidNs,+}));+const { markerLiveness } = await import('../../src/core/persistence/graduation-custody.ts');+process.stdout.write(markerLiveness(JSON.parse(markerJson!)));diff --git a/test/graduation-custody-probes.test.ts b/test/graduation-custody-probes.test.tsnew file mode 100644index 0000000000..fc077367e0--- /dev/null+++ b/test/graduation-custody-probes.test.ts@@ -0,0 +1,40 @@+/**+ * #6774: an unavailable local boot-id or pid-namespace probe reads as unknown, never as a match.+ *+ * 1. Protects: markerLiveness returns 'unknown' when the marker recorded a boot id or pid namespace and this+ * process cannot read its own, so the kernel lock stays the authority; a marker that recorded null keeps+ * the pid check.+ * 2. Fails when: the comparison is skipped for a null local probe again, so a marker from another host or+ * container reads 'alive' because a local process happens to have the same pid.+ * 3. test/graduation-custody.test.ts runs with real probes, which are readable on Linux CI, so it never reaches+ * the null-probe branch.+ * 4. No production seam: the probe is mocked in a child process (test/fixtures/graduation-liveness-probe.ts).+ */+import { describe, expect, test } from 'bun:test';+import { join } from 'node:path';+import type { IntentMarker } from '../src/core/persistence/engine-graduation.types.ts';++const FIXTURE = join(import.meta.dir, 'fixtures', 'graduation-liveness-probe.ts');+const target = { id: 'target-id', host: 'db.example.test', port: 5432, database: 'brain', user: 'alice-example' };+/** This test process is alive and is not the child's pid, standing in for an unrelated local process with the recorded pid. */+function marker(identity: Pick<IntentMarker, 'bootId' | 'pidNs'>): IntentMarker {+ return { runId: 'run-6774', state: 'copying', pid: process.pid, processStart: null, target, updatedAt: new Date().toISOString(), ...identity } as IntentMarker;+}+function liveness(missing: 'bootId' | 'pidNs' | 'none', value: IntentMarker): string {+ const child = Bun.spawnSync([process.execPath, FIXTURE, missing, JSON.stringify(value)], { stdout: 'pipe', stderr: 'pipe' });+ if (child.exitCode !== 0) throw new Error(child.stderr.toString());+ return child.stdout.toString();+}++describe('markerLiveness with an unavailable local probe', () => {+ test('a recorded boot id with no local boot id is unknown', () => {+ expect(liveness('bootId', marker({ bootId: 'boot-of-another-host', pidNs: null }))).toBe('unknown');+ });+ test('a recorded pid namespace with no local pid namespace is unknown', () => {+ expect(liveness('pidNs', marker({ bootId: null, pidNs: 'pid:[4026531836]' }))).toBe('unknown');+ });+ test('a marker that recorded neither probe still follows the pid', () => {+ expect(liveness('bootId', marker({ bootId: null, pidNs: null }))).toBe('alive');+ expect(liveness('pidNs', marker({ bootId: null, pidNs: null }))).toBe('alive');+ });+});