Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: retain restore recovery admission until journal release syncs (#9873)
Adam Eivy1c5a61b3dec3
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 8833c8d182..c76c4c2959 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -190,7 +190,8 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER- While the journal exists, every ordinary database operation in the server is refused with `503 DATABASE_RESTORE_RECOVERY` (`server/lib/db.js`); only the maintenance context that owns that operation may inspect or repair. The fence survives restart.- `psql` exit 0 means the replay committed (stage `repairing`). Any other outcome — an SQL error, a timeout kill, a lost connection at `COMMIT` — is settled from the receipt: no live `portos-restore-<id>` session and no receipt is a **proven rollback**, which clears the journal and reopens admission with current rows intact; a receipt is a commit; anything else (a replay session still alive, an unreachable database) stays fenced as `restore_commit_unknown`.-- Repair runs forced schema upgrades, ordered migrations, feed-sequence flooring at the **recorded** positions (never re-read after the replay) and the inbound cursor rewind. All steps are idempotent. Admission reopens only after every step succeeds and the journal is removed.+- Repair runs forced schema upgrades, ordered migrations, feed-sequence flooring at the **recorded** positions (never re-read after the replay) and the inbound cursor rewind. All steps are idempotent. Admission reopens only after every step succeeds, the journal is removed, and its parent directory is synced.+- If journal unlink fails, the durable record remains pending. If unlink succeeds but directory sync fails, the journal instance retains the operation and original feed positions in memory: status and ordinary database admission stay pending, and same-operation recovery retries finish directory sync. On a fresh process, a surviving journal invokes idempotent repair; if deletion persisted, completed repair needs no destructive replay. This process-local retry cannot provide stronger crash guarantees than the filesystem.- **Resume**, never repeat. Settings → Backup shows the pending operation with a **Resume recovery** action (`POST /api/backup/restore-db/recover` with the operation `id`), and `GET /api/backup/status` reports it as `restoreRecovery`. Restarting PortOS resumes it automatically before any route, scheduler or writer loads (`server/start.js`); if recovery still fails, boot is refused with the reason in the server log and the fence stays closed. Recovery never runs the reset or the dump again, and starting another restore is refused (`restore_recovery_pending`) until this one finishes.- An unreadable or damaged journal fails closed: the database stays fenced and boot is refused. Inspect the file and the logs; do not delete it unless you have established how the restore ended (with the database reachable, `SELECT * FROM restore_receipts WHERE operation_id = '<id>'` answers whether it committed).diff --git a/server/lib/databaseRestoreRecovery.js b/server/lib/databaseRestoreRecovery.jsindex e4cb638326..8b9e27b200 100644--- a/server/lib/databaseRestoreRecovery.js+++ b/server/lib/databaseRestoreRecovery.js@@ -13,7 +13,8 @@* transaction) is inspected.* repairing — replay committed; schema/migration/sequence/cursor repair is* pending. Never replays again.- * Completion (or a proven rollback) removes the file, reopening admission.+ * Completion (or a proven rollback) removes the file and syncs its directory+ * before reopening admission.*/import { closeSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';import { join } from 'node:path';@@ -64,12 +65,14 @@ function writeDurableExclusive(path, value) {export function createDatabaseRestoreRecovery(dataDir = PATHS.data) {const recordPath = join(dataDir, DATABASE_RESTORE_RECOVERY_FILE);+ let pendingRelease = null;const pendingPath = () => join(dataDir, `.database-restore-recovery-${randomUUID()}.pending`);- // The FILE is the fence, not a successfully parsed record: anything at the+ // A pending directory sync also fences this process. Otherwise anything at the// path other than a confirmed ENOENT (unreadable, wrong type, damaged)// keeps ordinary database work closed.const isFenced = () => {+ if (pendingRelease) return true;try {lstatSync(recordPath);return true;@@ -85,6 +88,7 @@ export function createDatabaseRestoreRecovery(dataDir = PATHS.data) {// null when no restore is pending; throws (fails closed) when the record// exists but cannot be read or validated.const read = () => {+ if (pendingRelease) return recordSchema.parse(pendingRelease);if (!isFenced()) return null;try {if (!lstatSync(recordPath).isFile()) throw databaseRestoreRecoveryError();@@ -100,6 +104,7 @@ export function createDatabaseRestoreRecovery(dataDir = PATHS.data) {// overwrite a pending operation's original feed positions.const begin = ({ snapshotId, dumpSha256, feedPositions }) => {assertNotRealDataWrite(recordPath, 'database restore recovery begin');+ assertAdmission();const record = recordSchema.parse({version: 1, id: randomUUID(), stage: 'replaying', createdAt: new Date().toISOString(),snapshotId, dumpSha256, feedPositions,@@ -138,8 +143,14 @@ export function createDatabaseRestoreRecovery(dataDir = PATHS.data) {assertNotRealDataWrite(recordPath, 'database restore recovery release');const current = read();if (!current || current.id !== id) throw databaseRestoreRecoveryError();- unlinkSync(recordPath);+ if (!pendingRelease) {+ unlinkSync(recordPath);+ // Unlink alone is not durable completion. Retain identity and admission+ // locally until the directory sync succeeds, including across retries.+ pendingRelease = current;+ }syncDirectory(dataDir);+ pendingRelease = null;};return { path: recordPath, isFenced, assertAdmission, read, begin, markCommitted, release };diff --git a/server/lib/db.restoreRecovery.test.js b/server/lib/db.restoreRecovery.test.jsindex 6f8c48f222..f1f6358aa4 100644--- a/server/lib/db.restoreRecovery.test.js+++ b/server/lib/db.restoreRecovery.test.js@@ -2,13 +2,41 @@// The journal is the real one, in a temp data root; pg is a stub pool, so no// statement can reach a real database even if admission regressed.import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { spawnSync } from 'node:child_process';import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';-const fixture = vi.hoisted(() => ({ dataRoot: null }));+const fixture = vi.hoisted(() => ({ dataRoot: null, releaseFault: null }));+vi.mock('node:fs', async (importOriginal) => {+ const fs = await importOriginal();+ return {+ ...fs,+ unlinkSync: vi.fn((path) => {+ if (fixture.releaseFault === 'unlink' && path === join(fixture.dataRoot, 'database-restore-recovery.json')) {+ throw Object.assign(new Error('synthetic unlink failure'), { code: 'EIO' });+ }+ return fs.unlinkSync(path);+ }),+ fsyncSync: vi.fn((fd) => {+ if (fixture.releaseFault === 'directory-sync' && fs.fstatSync(fd).isDirectory()) {+ throw Object.assign(new Error('synthetic directory sync failure'), { code: 'EIO' });+ }+ return fs.fsyncSync(fd);+ }),+ };+});+vi.mock('./db.js', async (importOriginal) => ({+ ...await importOriginal(),+ ensureSchema: vi.fn(async () => {}),+}));+vi.mock('../scripts/run-db-migrations.js', () => ({+ runDbMigrations: vi.fn(async () => 0),+}));+vi.mock('../services/syncOrchestrator.js', () => ({+ rewindPostgresSyncCursors: vi.fn(async () => 2),+}));vi.mock('./paths.js', async (importOriginal) => {const actual = await importOriginal();const { mkdtempSync: mkdtemp } = await import('node:fs');@@ -33,6 +61,8 @@ vi.mock('pg', async (importOriginal) => ({const { query, withTransaction, withDatabaseMaintenance, databaseRestoreRecovery } = await import('./db.js');+const { resumeDatabaseRestore, getDatabaseRestoreRecoveryStatus } = await import('../services/backupRestoreRecovery.js');+const begin = () => databaseRestoreRecovery.begin({snapshotId: 'snap-1', dumpSha256: 'a'.repeat(64),feedPositions: [{ sequencename: 'memories_sync_feed_seq', last_value: '500' }],@@ -71,6 +101,51 @@ describe('restore recovery admission', () => {await expect(query('SELECT 5')).resolves.toEqual({ rows: [] });});+ it.each([null, 'unlink', ...(process.platform === 'win32' ? [] : ['directory-sync'])])('keeps release completion and recovery admission consistent (%s)', async (fault) => {+ const record = databaseRestoreRecovery.markCommitted(begin().id);+ fixture.releaseFault = fault;+ try {+ const result = await resumeDatabaseRestore(record.id);+ if (fault) {+ expect(result).toMatchObject({ status: 'failed', reason: 'restore_recovery_release', recovery: { id: record.id } });+ // Post-unlink failure really has no file: record and fence must survive+ // in the journal instance until directory sync completes.+ expect(existsSync(databaseRestoreRecovery.path)).toBe(fault === 'unlink');+ expect(databaseRestoreRecovery.read()).toEqual(record);+ expect(getDatabaseRestoreRecoveryStatus()).toMatchObject({ pending: true, id: record.id, stage: 'repairing' });+ await expect(query('SELECT ordinary')).rejects.toMatchObject(FENCED);+ await expect(withTransaction(() => {})).rejects.toMatchObject(FENCED);+ await expect(resumeDatabaseRestore('00000000-0000-4000-8000-000000000009'))+ .rejects.toMatchObject({ code: 'RESTORE_RECOVERY_MISMATCH' });+ expect(() => databaseRestoreRecovery.release('00000000-0000-4000-8000-000000000009')).toThrow();+ expect(() => begin()).toThrow();+ expect(databaseRestoreRecovery.read()).toEqual(record);+ fixture.releaseFault = null;+ await expect(resumeDatabaseRestore(record.id)).resolves.toMatchObject({ status: 'ok', outcome: 'repaired' });+ } else {+ expect(result).toMatchObject({ status: 'ok', outcome: 'repaired' });+ }+ expect(existsSync(databaseRestoreRecovery.path)).toBe(false);+ expect(getDatabaseRestoreRecoveryStatus()).toEqual({ pending: false });+ await expect(query('SELECT ordinary')).resolves.toEqual({ rows: [] });+ await expect(withTransaction(client => client.query('SELECT ordinary'))).resolves.toEqual({ rows: [] });+ const queriesBeforeRetry = pool.query.mock.calls.length;+ await expect(resumeDatabaseRestore(record.id)).resolves.toEqual({ status: 'ok', outcome: 'none' });+ expect(pool.query).toHaveBeenCalledTimes(queriesBeforeRetry);+ // Recovery only floors original positions; no reset, replay or receipt inspection.+ expect(pool.query.mock.calls).toEqual([+ ...Array.from({ length: fault ? 2 : 1 }, () => [+ expect.stringContaining('SELECT setval'),+ [record.feedPositions.map(p => p.sequencename), record.feedPositions.map(p => p.last_value)],+ ]),+ ['SELECT ordinary', undefined],+ ]);+ } finally {+ fixture.releaseFault = null;+ if (databaseRestoreRecovery.isFenced()) databaseRestoreRecovery.release(record.id);+ }+ });+it('withdraws recovery authority from work that outlives the maintenance context', async () => {const { id } = begin();let escape;