Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(migrate): our own implementation of the #6106 fix (#6106)

time-attack60b795dc78a5
diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.ts
index 1982e40b4d..877b2ba869 100644
--- a/src/core/persistence/engine-graduation.ts
+++ b/src/core/persistence/engine-graduation.ts
@@ -1233,7 +1233,8 @@ async function rollbackBeforeCutover(run: Run): Promise<GraduationRollbackResult
async function rollbackAfterCutover(run: Run, opts: RunOptions): Promise<GraduationRollbackResult> {
const from = run.m.state;
- assertRetainedCopy(run, from);
+ const noRetainedCopy = () => retainedCopyMissingError({ runId: run.m.runId, retainedPath: graduatedPath(run.dataDir, run.m.runId) });
+ if (!retainedDatastore(run, from)) throw noRetainedCopy();
const hadAuthority = from === 'authoritative' || from === 'graduated';
await openTargets(run);
if (hadAuthority) {
@@ -1252,7 +1253,7 @@ async function rollbackAfterCutover(run: Run, opts: RunOptions): Promise<Graduat
try {
await claimPause(run);
await takeKernelLock(run);
- assertRetainedCopy(run, from);
+ if (!retainedDatastore(run, from)) throw noRetainedCopy();
if (hadAuthority) losses = await detectRollbackLosses(run);
} catch (error) {
if (hadAuthority) await returnToAuthority(run);
@@ -1276,13 +1277,24 @@ async function rollbackAfterCutover(run: Run, opts: RunOptions): Promise<Graduat
dropped: losses.filter(l => l.lossKind === 'operational').map(l => ({ relation: l.relation, rows: l.rows, lossKind: l.lossKind })) };
}
-/** Rollback after cutover restores the retained copy; with it gone, going on would open an empty brain at the old path and route this machine to it. */
-function assertRetainedCopy(run: Run, from: ManifestState): void {
- const movedTo = graduatedPath(run.dataDir, run.m.runId);
- let unmoved = false;
- try { unmoved = from === 'cutover' && lstatSync(run.dataDir).isDirectory(); } catch { /* absent */ }
- if (existsSync(movedTo) || unmoved) return;
- throw retainedCopyMissingError({ runId: run.m.runId, retainedPath: movedTo });
+/**
+ * Where the PGLite datastore a post-cutover rollback would restore is right
+ * now, or null when it no longer exists. Cutover renames it to
+ * `<dataDir>.graduated-<run>`; only a run interrupted in `cutover` before that
+ * rename still has it at the data dir itself, and there it must be a
+ * directory (from `tombstoned` on, the data dir path is the tombstone file).
+ * Without it, finishRollback would open a fresh empty PGLite brain at the old
+ * path and route this machine to it.
+ */
+function retainedDatastore(run: Run, from: ManifestState): string | null {
+ const renamed = graduatedPath(run.dataDir, run.m.runId);
+ if (existsSync(renamed)) return renamed;
+ if (from !== 'cutover') return null;
+ try {
+ return lstatSync(run.dataDir).isDirectory() ? run.dataDir : null;
+ } catch {
+ return null;
+ }
}
async function approveAndRestore(run: Run): Promise<void> {
diff --git a/src/core/persistence/graduation-errors.ts b/src/core/persistence/graduation-errors.ts
index 75d1250778..3228a67773 100644
--- a/src/core/persistence/graduation-errors.ts
+++ b/src/core/persistence/graduation-errors.ts
@@ -278,15 +278,15 @@ export function rollbackWritesLostError(opts: { losses: readonly { relation: str
user_message: `Going back to PGLite would lose what changed on Postgres since the move: ${listed}. Should I go back anyway? If not, nothing changes and Postgres stays in use.` } });
}
-/** `not_found`: after cutover, the retained PGLite copy a rollback would restore is gone. */
+/** `not_found`: a post-cutover rollback has no retained PGLite datastore left to restore. */
export function retainedCopyMissingError(opts: { runId: string; retainedPath: string }): OperationError {
const docs = `${GRADUATION_GUIDE}#check-resume-or-roll-back`;
- const why = `A rollback makes the PGLite brain kept by graduation run ${opts.runId} authoritative again, and that copy is no longer at ${opts.retainedPath}. Nothing was changed: the Postgres brain stays authoritative and this machine stays routed to it.`;
- return opError('not_found', `Rollback refused: the retained PGLite copy of graduation run ${opts.runId} is gone, so there is nothing to roll back to.`,
- 'Keep using the Postgres brain; nothing changed.',
+ const why = `Rolling back means restoring the local PGLite datastore that graduation run ${opts.runId} set aside at ${opts.retainedPath}, and no datastore is there any more. The rollback stopped before changing anything: Postgres is still the authoritative brain and this machine still routes to it.`;
+ return opError('not_found', `Cannot roll back graduation run ${opts.runId}: its retained PGLite datastore (${opts.retainedPath}) no longer exists.`,
+ 'Nothing changed; carry on with the Postgres brain.',
{ why, docs,
fix: { consent: [], actor: 'agent', requires_exclusive: false, docs, verify: STATUS_VERIFY, why,
- user_message: 'Your brain cannot go back to PGLite: the local copy a rollback would restore was deleted. It keeps working on Postgres.' } });
+ user_message: 'Going back to the local PGLite brain is no longer possible because its saved copy was deleted. Your brain stays on Postgres and keeps working.' } });
}
/** `graduation_target_auth_failed`: the recorded target URL no longer authenticates. */
diff --git a/test/graduation-rollback.test.ts b/test/graduation-rollback.test.ts
index 9f6dbe3c35..c76d7bd459 100644
--- a/test/graduation-rollback.test.ts
+++ b/test/graduation-rollback.test.ts
@@ -11,11 +11,12 @@
* approval, forward to rolled_back after it). Regressions that fail it: a
* timestamp-based security check (revocations delete rows), a refusal that
* strands the target fenced, a crash after approval that restores authority,
- * a rollback that runs without its retained copy (it would open an empty
- * brain at the old path and route this machine to it).
+ * and a post-cutover rollback that proceeds when the PGLite datastore it must
+ * restore is gone (it would open an empty brain at the old path and route
+ * this machine to it), including the copy disappearing at the fence.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs';
+import { existsSync, lstatSync, readFileSync, renameSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import {
planGraduation, readGraduationManifest, reconcileGraduation, rollbackGraduation, runGraduation, type GraduationOptions,
@@ -111,36 +112,73 @@ for (const [label, postgresUrl] of targets) {
});
}, 120_000);
- async function assertRetainedCopyRefusal(refused: { code?: string; message: string }, copy: string): Promise<void> {
+ const retainedDir = () => `${h.dataDir}.graduated-${manifest().runId}`;
+ /** A missing-copy refusal must leave graduation exactly where it was: graduated, routed to Postgres, nothing recreated. */
+ async function expectUntouchedAfterMissingCopy(refused: Awaited<ReturnType<typeof refusal>>, copyPath: string): Promise<void> {
expect(refused.code).toBe('not_found');
- expect(refused.message).toContain('nothing to roll back to');
+ expect(refused.message).toContain(copyPath);
+ expect(refused.fix?.argv).toBeUndefined();
expect(manifest().state).toBe('graduated');
- expect(config().engine).toBe('postgres');
- expect(existsSync(copy)).toBe(false);
+ expect(config()).toMatchObject({ engine: 'postgres' });
+ expect(existsSync(copyPath)).toBe(false);
+ expect(readTombstone(h.dataDir)?.runId).toBe(manifest().runId);
await assertTargetAuthoritative();
}
- test('a retained copy deleted before the rollback: refused before the fence, nothing changes', async () => {
+ test('retained copy gone before the rollback starts: not_found before any fence, nothing recreated', async () => {
await fresh();
await h.inHome(async () => {
await graduate();
- const copy = `${h.dataDir}.graduated-${manifest().runId}`;
- rmSync(copy, { recursive: true, force: true });
- let fenced = false;
- const refused = await refusal(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: async () => { fenced = true; } })));
- expect(fenced).toBe(false);
- await assertRetainedCopyRefusal(refused, copy);
+ const copyPath = retainedDir();
+ rmSync(copyPath, { recursive: true, force: true });
+ let reachedFence = false;
+ const refused = await refusal(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: async () => { reachedFence = true; } })));
+ expect(reachedFence).toBe(false);
+ await expectUntouchedAfterMissingCopy(refused, copyPath);
});
}, 120_000);
- test('a retained copy removed between the fence and the kernel lock: refused under the lock, the target returns to authority', async () => {
+ test('a copy left by a different run does not stand in for this run\'s copy', async () => {
await fresh();
await h.inHome(async () => {
await graduate();
- const copy = `${h.dataDir}.graduated-${manifest().runId}`;
- const removeAtFence = async (step: string) => { if (step === 'rollback_fenced') rmSync(copy, { recursive: true, force: true }); };
- const refused = await refusal(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: removeAtFence })));
- await assertRetainedCopyRefusal(refused, copy);
+ const copyPath = retainedDir();
+ const otherRun = `${h.dataDir}.graduated-some-earlier-run`;
+ renameSync(copyPath, otherRun);
+ const refused = await refusal(rollbackGraduation(rollbackOpts()));
+ await expectUntouchedAfterMissingCopy(refused, copyPath);
+ expect(lstatSync(otherRun).isDirectory()).toBe(true);
+ });
+ }, 120_000);
+
+ test('retained copy deleted while the rollback waits at its fence: refused under the kernel lock, target back to authority', async () => {
+ await fresh();
+ await h.inHome(async () => {
+ await graduate();
+ const copyPath = retainedDir();
+ const deleteWhenFenced = async (step: string) => {
+ if (step !== 'rollback_fenced') return;
+ expect((await readGraduationRow(h.target))?.state).toBe('rollback_fenced');
+ rmSync(copyPath, { recursive: true, force: true });
+ };
+ const refused = await refusal(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: deleteWhenFenced })));
+ await expectUntouchedAfterMissingCopy(refused, copyPath);
+ });
+ }, 120_000);
+
+ test('a run interrupted in cutover before the move-aside still rolls back from the datastore at the old path', async () => {
+ await fresh();
+ await h.inHome(async () => {
+ const hash = (await planGraduation(runOpts(''))).planHash;
+ await expect(runGraduation(runOpts(hash, { pauseAt: 'source_cutover', pauseHook: crashAt('source_cutover') }))).rejects.toThrow();
+ expect(manifest().state).toBe('cutover');
+ expect(existsSync(retainedDir())).toBe(false);
+ expect(lstatSync(h.dataDir).isDirectory()).toBe(true);
+ const result = await rollbackGraduation(rollbackOpts());
+ expect(result.state).toBe('rolled_back');
+ expect(manifest().state).toBe('rolled_back');
+ expect(lstatSync(h.dataDir).isDirectory()).toBe(true);
+ expect(config()).toMatchObject({ engine: 'pglite', database_path: h.dataDir });
});
}, 120_000);
@@ -223,15 +261,26 @@ for (const [label, postgresUrl] of targets) {
});
}
-test('the missing-retained-copy refusal renders the agent contract without naming a discard flag', () => {
- const env = toAgentError(retainedCopyMissingError({ runId: 'run1', retainedPath: '/home/alice-example/.gbrain/brain.pglite.graduated-run1' }),
+describe('retainedCopyMissingError', () => {
+ const retainedPath = '/home/alice-example/.gbrain/brain.pglite.graduated-run-7';
+ const rendered = () => toAgentError(retainedCopyMissingError({ runId: 'run-7', retainedPath }),
{ transport: 'cli', command: 'migrate', render: cliRenderContext() });
- expect(env.code).toBe('not_found');
- expect(env.why).toContain('Nothing was changed');
- expect(env.docs).toContain('#check-resume-or-roll-back');
- expect(env.fix?.next).toBe('report');
- expect(env.fix?.argv).toBeUndefined();
- expect(env.fix?.verify?.argv).toEqual(['gbrain', 'migrate', '--status', '--json']);
- expect(env.fix?.user_message).toContain('keeps working on Postgres');
- expect(JSON.stringify(env)).not.toContain('--discard-source');
+
+ test('is a report-only not_found that names the run and the missing path', () => {
+ const env = rendered();
+ expect(env.code).toBe('not_found');
+ expect(env.message).toContain('run-7');
+ expect(env.message).toContain(retainedPath);
+ expect(env.fix?.next).toBe('report');
+ expect(env.fix?.argv).toBeUndefined();
+ expect(env.docs).toEndWith('docs/guides/move-to-postgres.md#check-resume-or-roll-back');
+ });
+
+ test('verifies read-only and tells the user the brain stays on Postgres', () => {
+ const env = rendered();
+ expect(env.fix?.verify?.argv).toEqual(['gbrain', 'migrate', '--status', '--json']);
+ expect(env.why).toContain('before changing anything');
+ expect(env.fix?.user_message).toContain('stays on Postgres');
+ expect(JSON.stringify(env)).not.toMatch(/discard-source|rm -rf/);
+ });
});