Skip to content

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

fix: keep a committed database restore fenced until recovery finishes (#9725)

[._.]/ Adam Eivy9db03f5f51e2
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index 4b76d03919..85a29ef0fe 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -10,7 +10,7 @@ import Modal from '../ui/Modal';
import Banner from '../ui/Banner';
import CollapsibleSection from '../ui/CollapsibleSection';
import CollapsibleListItem from '../ui/CollapsibleListItem';
-import { getSettings, updateSettings, getBackupStatus, getBackupSnapshots, restoreDatabase, deleteBackupSnapshot } from '../../services/api';
+import { getSettings, updateSettings, getBackupStatus, getBackupSnapshots, restoreDatabase, recoverDatabaseRestore, deleteBackupSnapshot } from '../../services/api';
import { formatBytes } from '../../utils/formatters';
import { describeCron } from '../../utils/cronHelpers';
import CronSchedulePicker from '../CronSchedulePicker';
@@ -94,6 +94,10 @@ export function BackupTab() {
const [showSnapshots, setShowSnapshots] = useState(false);
const [restoreTarget, setRestoreTarget] = useState(null); // source-bound request pending confirm
const [restorePreview, setRestorePreview] = useState(null); // dry-run result
+ // A committed database restore awaiting recovery (#9725): the server keeps
+ // ordinary database work fenced until it is resumed to completion.
+ const [restoreRecovery, setRestoreRecovery] = useState(null);
+ const [recovering, setRecovering] = useState(false);
const restorePreviewGenerationRef = useRef(0);
const [deleteTarget, setDeleteTarget] = useState(null); // snapshot pending delete confirm
const [deletingIds, setDeletingIds] = useState(new Set());
@@ -159,6 +163,7 @@ export function BackupTab() {
setDefaultExcludes(asArray(status?.defaultExcludes));
setPgBackup(status?.pgBackup ?? null);
setBackupStatus(status?.status ?? 'never');
+ setRestoreRecovery(status?.restoreRecovery?.pending ? status.restoreRecovery : null);
setSnapshots(Array.isArray(snaps) ? snaps : []);
})
.catch(() => {
@@ -340,16 +345,34 @@ export function BackupTab() {
toast.success(`Database restored from ${target.request.snapshotId}`, { icon: '💾' });
} else if (DB_RESTORE_REFUSALS[result.reason]) {
toast.error(DB_RESTORE_REFUSALS[result.reason]);
- } else if (result.reason === 'restore_schema_reconciliation') {
- toast.error('The database dump was applied, but schema recovery is incomplete. It was not rolled back. Restart PortOS to retry recovery; if it still fails, check the server logs and repair the database before continuing.', { duration: Infinity });
- } else if (result.reason === 'restore_sync_resync') {
- toast.error('The database dump was applied, but peer sync could not be reset. Memories and Catalog records pulled from peers after this snapshot may stay missing; check the server logs and repeat the restore.', { duration: Infinity });
+ } else if (result.recovery) {
+ // Committed (or not yet provably rolled back): the server keeps the
+ // database fenced. Resume — never repeat — the restore.
+ setRestoreRecovery({ pending: true, ...result.recovery });
+ toast.error(result.error || 'The database restore needs recovery before the database can be used.', { duration: Infinity });
} else {
toast.error(`DB restore failed: ${result.reason || 'unknown'}`);
}
setRestorePreview(null);
};
+ const resumeRestoreRecovery = async () => {
+ if (!restoreRecovery?.id || recovering) return;
+ setRecovering(true);
+ const result = await recoverDatabaseRestore(restoreRecovery.id, { silent: true })
+ .catch(err => ({ status: 'failed', error: err?.message }))
+ .finally(() => setRecovering(false));
+ if (result.status === 'ok') {
+ setRestoreRecovery(null);
+ toast.success(result.outcome === 'rolled_back'
+ ? 'The restore had rolled back; the database is unchanged and available again.'
+ : 'Database restore recovery finished; the database is available again.', { icon: '💾' });
+ return;
+ }
+ if (result.recovery) setRestoreRecovery({ pending: true, ...result.recovery });
+ toast.error(result.error || 'Database restore recovery is still pending; check the server logs.');
+ };
+
const handleDeleteSnapshot = (snapshot) => {
setDeleteTarget({
identity: snapshotIdentity(snapshot),
@@ -382,6 +405,26 @@ export function BackupTab() {
className="@container bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-5"
>
<h2 id="backup-settings-heading" className="sr-only">Backup operations and configuration</h2>
+ {restoreRecovery && (
+ <Banner tone="error" icon={AlertTriangle} title="Database restore needs recovery" size="md">
+ {restoreRecovery.damaged ? (
+ <>The restore recovery journal is unreadable, so database features stay paused. Check the server logs; the journal is never cleared automatically.</>
+ ) : (
+ <>
+ The restore from snapshot <code>{restoreRecovery.snapshotId}</code> is not finished, so database features are paused.
+ Resume it to finish schema and peer-sync repair. The dump is never replayed again.{' '}
+ <button
+ type="button"
+ onClick={resumeRestoreRecovery}
+ disabled={recovering}
+ className="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-sm bg-port-error hover:bg-port-error/80 text-white font-medium rounded-lg transition-colors disabled:opacity-50"
+ >
+ {recovering ? <BrailleSpinner text="Recovering" className="text-white" /> : <><Database size={14} aria-hidden="true" /> Resume recovery</>}
+ </button>
+ </>
+ )}
+ </Banner>
+ )}
{backupStatus === 'degraded' && (
<Banner tone="warning" icon={AlertTriangle} title="Last backup degraded" size="md">
Files were saved but the database dump failed.{' '}
diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsx
index 6713f5393c..3091b1ce44 100644
--- a/client/src/components/settings/BackupTab.test.jsx
+++ b/client/src/components/settings/BackupTab.test.jsx
@@ -8,6 +8,7 @@ vi.mock('../../services/api', () => ({
triggerBackup: vi.fn(),
getBackupSnapshots: vi.fn(),
restoreDatabase: vi.fn(),
+ recoverDatabaseRestore: vi.fn(),
deleteBackupSnapshot: vi.fn(),
// FolderPicker imports `* as api` from the same module; it only calls this
// when its picker is opened (never in these tests), but the mock defines it
@@ -34,6 +35,7 @@ import {
triggerBackup,
getBackupSnapshots,
restoreDatabase,
+ recoverDatabaseRestore,
deleteBackupSnapshot,
} from '../../services/api';
import toast from '../ui/Toast';
@@ -288,6 +290,47 @@ describe('BackupTab', () => {
expect(toast.success).toHaveBeenCalledWith('Database restored from snap-2026-06-09', { icon: '💾' });
});
+ // #9725: a committed restore whose repair failed stays fenced server-side;
+ // the tab must offer to RESUME it (never to repeat the restore).
+ it('surfaces a committed restore awaiting recovery and resumes exactly that operation', async () => {
+ withSnapshot();
+ const recovery = { id: '00000000-0000-4000-8000-000000000001', stage: 'repairing', snapshotId: 'snap-2026-06-09' };
+ restoreDatabase
+ .mockResolvedValueOnce({ status: 'ok', sizeBytes: 2048, tableCount: 12 })
+ .mockResolvedValueOnce({ status: 'failed', reason: 'restore_sync_resync', error: 'Peer sync could not be reset yet.', recovery });
+ recoverDatabaseRestore
+ .mockResolvedValueOnce({ status: 'failed', reason: 'restore_sync_resync', error: 'Still failing.', recovery })
+ .mockResolvedValueOnce({ status: 'ok', outcome: 'repaired' });
+ await renderTab();
+
+ await act(async () => {
+ fireEvent.click(await screen.findByRole('button', { name: /Restore DB/i }));
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Restore$/i }));
+ });
+ expect(toast.error).toHaveBeenCalledWith('Peer sync could not be reset yet.', { duration: Infinity });
+ expect(screen.getByText('Database restore needs recovery')).toBeInTheDocument();
+
+ const resume = screen.getByRole('button', { name: /Resume recovery/i });
+ await act(async () => { fireEvent.click(resume); });
+ expect(recoverDatabaseRestore).toHaveBeenLastCalledWith(recovery.id, { silent: true });
+ expect(toast.error).toHaveBeenLastCalledWith('Still failing.');
+ expect(screen.getByText('Database restore needs recovery')).toBeInTheDocument();
+
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Resume recovery/i })); });
+ await waitFor(() => expect(screen.queryByText('Database restore needs recovery')).toBeNull());
+ expect(restoreDatabase).toHaveBeenCalledTimes(2);
+ });
+
+ it('shows a pending recovery reported by the status endpoint on load', async () => {
+ getBackupStatus.mockResolvedValue({ status: 'ok', defaultExcludes: [], pgBackup: null,
+ restoreRecovery: { pending: true, id: '00000000-0000-4000-8000-000000000001', stage: 'replaying', snapshotId: 'snap-1' } });
+ await renderTab({ openExclusions: false, openSnapshots: false });
+ expect(screen.getByText('Database restore needs recovery')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Resume recovery/i })).toBeEnabled();
+ });
+
it('binds database preview and confirmation to the selected source', async () => {
getBackupSnapshots.mockResolvedValue([
...Array.from({ length: 10 }, (_, index) => ({
@@ -334,25 +377,6 @@ describe('BackupTab', () => {
}, { silent: true });
});
- it('explains that schema recovery failed after the dump committed', async () => {
- withSnapshot();
- restoreDatabase
- .mockResolvedValueOnce({ status: 'ok', sizeBytes: 2048, tableCount: 12 })
- .mockResolvedValueOnce({ status: 'failed', reason: 'restore_schema_reconciliation' });
- await renderTab();
- await act(async () => {
- fireEvent.click(await screen.findByRole('button', { name: /Restore DB/i }));
- });
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: /^Restore$/i }));
- });
- expect(toast.success).not.toHaveBeenCalled();
- expect(toast.error).toHaveBeenCalledWith(
- expect.stringMatching(/dump was applied.*not rolled back.*Restart PortOS/),
- { duration: Infinity },
- );
- });
-
it('toasts an error when the confirmed restore fails', async () => {
withSnapshot();
restoreDatabase
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index dd02488fd6..73cc97dff5 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -364,6 +364,8 @@ export async function downloadBackupSnapshot(snapshotId, source) {
return { filename };
}
export const restoreDatabase = (data, options) => request('/backup/restore-db', { method: 'POST', body: JSON.stringify(data), ...options });
+// Resume a committed database restore awaiting recovery (#9725). Never replays the dump.
+export const recoverDatabaseRestore = (id, options) => request('/backup/restore-db/recover', { method: 'POST', body: JSON.stringify({ id }), ...options });
export const deleteBackupSnapshot = (snapshotId, source, options = {}) => {
const query = source ? `?source=${encodeURIComponent(source)}` : '';
return request(`/backup/snapshots/${encodeURIComponent(snapshotId)}${query}`, { method: 'DELETE', ...options });
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index eccb17ad9d..8833c8d182 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -176,13 +176,25 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER
| `{ status: 'failed', reason: 'manifest_mismatch' }` | Snapshot's `portos-db.sql` hash disagrees with `manifest.json` — dump considered untrustworthy |
| `{ status: 'failed', reason: 'dump_unreadable', error }` | `portos-db.sql` could not be read, or its private restore copy could not be written — refused before any reset |
| `{ status: 'failed', reason: 'dump_incomplete', error }` | The dump lacks the `pg_dump` completion marker or a core PortOS table (header-only or truncated) — refused before any reset |
-| `{ status: 'failed', reason: 'restore_error', error }` | `psql` replay failed (stderr captured) |
-| `{ status: 'failed', reason: 'restore_schema_reconciliation', error }` | The dump committed, but current schema recovery failed; the restore was **not rolled back** |
-| `{ status: 'failed', reason: 'restore_sync_resync', error }` | The dump committed and the schema recovered, but peer sync could not be repaired (below) |
+| `{ status: 'failed', reason: 'restore_journal', error }` | The recovery journal could not be written — refused before any reset |
+| `{ status: 'failed', reason: 'restore_error' \| 'timeout', error }` | `psql` replay failed (stderr captured) and was **proven rolled back** from its receipt (below) |
+| `{ status: 'failed', reason: 'restore_commit_unknown', error, recovery }` | `psql` did not report success and the receipt could not settle whether the replay committed — recovery pending |
+| `{ status: 'failed', reason: 'restore_schema_reconciliation', error, recovery }` | The dump committed, but current schema recovery failed; **not rolled back**, recovery pending |
+| `{ status: 'failed', reason: 'restore_sync_resync', error, recovery }` | The dump committed and the schema recovered, but peer sync could not be repaired (below) — recovery pending |
+| `{ status: 'failed', reason: 'restore_recovery_release', error, recovery }` | Repair finished but the journal could not be cleared — recovery pending |
+| `{ status: 'failed', reason: 'restore_recovery_pending', error, recovery }` | An earlier restore is still awaiting recovery; preview and replay are refused |
**Peer sync repair (#8710).** Memories and the seven Catalog tables federate through per-stream feed positions. A restore breaks both directions: this install's per-peer pull cursors (`data/instances_sync_cursors.json`) still point past rows the restore discarded, and the dump rewinds each `<table>_sync_feed_seq`, so new rows would reuse positions peers have already passed. Inside the maintenance window, the restore records each feed sequence before replay. After reconciliation, it sets each sequence back to at least that value and rewinds every peer's `memorySeq` and `catalogSeqs` to `0`. Brain cursors and snapshot checksums are left alone. The next sync replays each peer's streams through the idempotent last-writer-wins apply paths. A sync already in flight during the restore does not save its pre-restore cursor positions. Dry-run and failed restores change neither cursors nor sequences.
-On schema-reconciliation failure, restart PortOS to retry its schema upgrades and pending migrations. If recovery still fails, inspect the server logs and repair the database before continuing to use affected features. Reconciliation can partially apply upgrades; it is separate from the completed replay transaction.
+**Committed-restore recovery (#9725).** A replay that commits but whose repair then fails must neither reopen ordinary writes nor be replayed again — the next sequence value would reuse positions peers already passed, inbound cursors would still skip discarded rows, and a repeated restore would also delete anything accepted after the first replay. So, inside the maintenance window and **before** the destructive replay, the restore publishes a durable journal at `data/database-restore-recovery.json` holding a fresh operation id, the admitted dump's SHA-256, the ORIGINAL feed-sequence positions and the pending stage (`replaying`). The `psql` replay appends one `restore_receipts` row for that operation id after the dump, inside the same transaction, and runs with `application_name = portos-restore-<id>`.
+
+- 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.
+- **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).
+
+Reconciliation can partially apply upgrades; it is separate from the completed replay transaction, which is why it is retried rather than rolled back.
A non-dry-run restore requires a reachable DB first (`checkHealth()`), so a restore never half-applies against a down database.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index f6295319c1..96c5b3a38c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -165,6 +165,12 @@ while its worker is running, the retry reports `running`. Once release finishes,
there is no active operation left to recover. A fenced refusal never authorizes
removing the fence or launching another operation.
+### Snapshot database restore recovery
+
+`data/database-restore-recovery.json` (`server/lib/databaseRestoreRecovery.js`) is `file-primary`, machine-local recovery state for ONE in-flight snapshot database restore (#9725). It must be readable before PostgreSQL, so it cannot live in the database it fences. The file's presence is the admission fence: `server/lib/db.js` refuses every ordinary operation while it exists, and boot resumes recovery before loading anything else. The versioned record holds the operation UUID, stage (`replaying` | `repairing`), timestamp, snapshot id, the admitted dump's SHA-256 and the pre-replay sync-feed sequence positions — no credentials, connection details or application records. It is published (atomic no-replace link) before the destructive replay and removed only after repair completes or the replay is proven rolled back. Absent means idle; a malformed or unreadable file fails closed. It is never federated, has no reference seed and needs no migration (absent on every existing install). It and its `.database-restore-recovery-*.pending` scratch are non-overridable backup excludes: a restored copy would fence the database for an operation that no longer exists.
+
+The companion `restore_receipts` table (`db-primary`, machine-local, never federated) holds one row per committed restore operation (`operation_id`, `dump_sha256`, `applied_at`), written inside the replay transaction so a crash or lost response at `COMMIT` is resolved from the database. It is additive base schema (`restoreReceiptsDdl` in `server/lib/db/schema/core.js`, mirrored in `init-db.sql`), and the replay also creates it for dumps that predate it. `pg_dump` excludes its rows (`--exclude-table-data`), and the restore's reset drops it with the other application tables, so receipts describe only this machine's restores. Operator contract: [committed-restore recovery](BACKUP.md#database--restorepostgres).
+
### Calendar daily-review recovery
Daily reviews remain in the existing `data/calendar/daily-reviews/<date>.json`
diff --git a/server/lib/README.md b/server/lib/README.md
index 6d0732ad38..2109a818b3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -798,6 +798,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `databaseMaintenanceJournal.js` | Shared `databaseMaintenanceEndpointSchema` plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership, one-use detached worker reservations, exit-receipt-gated ownership recovery, worker process-group records, immutable recovery-dump and import receipts, durable forward-only stages through `verified`, per-pid target proofs from a restarted server, token-persisting same-operation recovery, and `releaseAdmission` (authority record, then completed archive); source-only cancellation archives an unowned accepted operation. |
+| `databaseRestoreRecovery.js` | `createDatabaseRestoreRecovery(dataDir?)` durable machine-local journal + admission fence for one in-flight snapshot database restore (#9725): operation id, dump digest, ORIGINAL pre-replay feed positions and stage (`replaying` → `repairing`), published before replay and released only after repair or a proven rollback; damaged state fails closed. |
+
| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus `retire(id, archiveDir?)` for proven-quiescent records; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. `classifyWriterQuiescence(row, processes)` classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. |
| `musicVideoCreativeContext.js` | `musicVideoDirectionContext(direction)` bounds the authoritative Cast & Sets bible; `musicVideoCodeDirectionContext(direction)` renders the approved procedural direction (rules + reusable character definitions) for code-authoring requests; `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. |
diff --git a/server/lib/databaseRestoreRecovery.js b/server/lib/databaseRestoreRecovery.js
new file mode 100644
index 0000000000..e4cb638326
--- /dev/null
+++ b/server/lib/databaseRestoreRecovery.js
@@ -0,0 +1,146 @@
+/**
+ * Durable, machine-local journal for ONE in-flight snapshot database restore
+ * (#9725). Its presence is the admission fence: while the file exists, only
+ * the matching recovery operation may use the database, in this process and
+ * across restart. The record carries what recovery needs and nothing else —
+ * the operation id, the admitted dump digest, the ORIGINAL pre-replay sync
+ * feed positions and the pending stage. No credentials, no copied records.
+ *
+ * Stages:
+ * replaying — published BEFORE the destructive replay. Whether the replay
+ * committed is unknown until its transactional receipt (a row in
+ * `restore_receipts` keyed by this id, written inside the replay
+ * 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.
+ */
+import { closeSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { z } from 'zod';
+import { PATHS } from './paths.js';
+import { assertNotRealDataWrite } from './testDataIsolation.js';
+
+export const DATABASE_RESTORE_RECOVERY_FILE = 'database-restore-recovery.json';
+export const DATABASE_RESTORE_RECOVERY_STAGES = Object.freeze(['replaying', 'repairing']);
+
+const recordSchema = z.object({
+ version: z.literal(1),
+ id: z.string().uuid(),
+ stage: z.enum(DATABASE_RESTORE_RECOVERY_STAGES),
+ createdAt: z.string().datetime(),
+ snapshotId: z.string().min(1).max(255),
+ dumpSha256: z.string().regex(/^[0-9a-f]{64}$/),
+ // pg_sequences rows captured before replay; last_value stays a decimal
+ // string because feed positions exceed Number.MAX_SAFE_INTEGER.
+ feedPositions: z.array(z.object({
+ sequencename: z.string().regex(/^[a-z_][a-z0-9_]{0,62}$/),
+ last_value: z.string().regex(/^-?\d{1,20}$/),
+ }).strict()).max(256),
+}).strict();
+
+export const databaseRestoreRecoveryError = () => Object.assign(
+ new Error('A committed database restore is awaiting recovery. Finish it from Settings > Backup (or restart PortOS to retry automatically) before using the database.'),
+ { status: 503, code: 'DATABASE_RESTORE_RECOVERY' },
+);
+
+function syncDirectory(path) {
+ // Windows does not expose directory fsync through Node.
+ if (process.platform === 'win32') return;
+ const fd = openSync(path, 'r');
+ try { fsyncSync(fd); } finally { closeSync(fd); }
+}
+
+function writeDurableExclusive(path, value) {
+ const fd = openSync(path, 'wx', 0o600);
+ try {
+ writeFileSync(fd, JSON.stringify(value, null, 2) + '\n');
+ fsyncSync(fd);
+ } finally {
+ closeSync(fd);
+ }
+}
+
+export function createDatabaseRestoreRecovery(dataDir = PATHS.data) {
+ const recordPath = join(dataDir, DATABASE_RESTORE_RECOVERY_FILE);
+ const pendingPath = () => join(dataDir, `.database-restore-recovery-${randomUUID()}.pending`);
+
+ // The FILE is the fence, not a successfully parsed record: anything at the
+ // path other than a confirmed ENOENT (unreadable, wrong type, damaged)
+ // keeps ordinary database work closed.
+ const isFenced = () => {
+ try {
+ lstatSync(recordPath);
+ return true;
+ } catch (err) {
+ return err.code !== 'ENOENT';
+ }
+ };
+
+ const assertAdmission = () => {
+ if (isFenced()) throw databaseRestoreRecoveryError();
+ };
+
+ // null when no restore is pending; throws (fails closed) when the record
+ // exists but cannot be read or validated.
+ const read = () => {
+ if (!isFenced()) return null;
+ try {
+ if (!lstatSync(recordPath).isFile()) throw databaseRestoreRecoveryError();
+ return recordSchema.parse(JSON.parse(readFileSync(recordPath, 'utf8')));
+ } catch {
+ if (!isFenced()) return null;
+ throw databaseRestoreRecoveryError();
+ }
+ };
+
+ // Published before the destructive replay. link() is an atomic no-replace
+ // publication of already-fsynced bytes, so a second restore can never
+ // overwrite a pending operation's original feed positions.
+ const begin = ({ snapshotId, dumpSha256, feedPositions }) => {
+ assertNotRealDataWrite(recordPath, 'database restore recovery begin');
+ const record = recordSchema.parse({
+ version: 1, id: randomUUID(), stage: 'replaying', createdAt: new Date().toISOString(),
+ snapshotId, dumpSha256, feedPositions,
+ });
+ const pending = pendingPath();
+ writeDurableExclusive(pending, record);
+ try {
+ linkSync(pending, recordPath);
+ } catch (err) {
+ if (err.code === 'EEXIST') throw databaseRestoreRecoveryError();
+ throw err;
+ } finally {
+ unlinkSync(pending);
+ }
+ syncDirectory(dataDir);
+ return record;
+ };
+
+ // Forward-only: replaying -> repairing, for the SAME operation. Identity,
+ // digest and the original floors are carried over unchanged.
+ const markCommitted = (id) => {
+ assertNotRealDataWrite(recordPath, 'database restore recovery commit');
+ const current = read();
+ if (!current || current.id !== id) throw databaseRestoreRecoveryError();
+ if (current.stage === 'repairing') return current;
+ const next = recordSchema.parse({ ...current, stage: 'repairing' });
+ const pending = pendingPath();
+ writeDurableExclusive(pending, next);
+ renameSync(pending, recordPath);
+ syncDirectory(dataDir);
+ return next;
+ };
+
+ // Reopen admission: repair completed, or the replay provably rolled back.
+ const release = (id) => {
+ assertNotRealDataWrite(recordPath, 'database restore recovery release');
+ const current = read();
+ if (!current || current.id !== id) throw databaseRestoreRecoveryError();
+ unlinkSync(recordPath);
+ syncDirectory(dataDir);
+ };
+
+ return { path: recordPath, isFenced, assertAdmission, read, begin, markCommitted, release };
+}
diff --git a/server/lib/db.js b/server/lib/db.js
index 4179b2d8e9..bd91e6ff57 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -10,6 +10,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import { isTestRunner } from './runtimeEnv.js';
import { assertDatabaseAdmission, createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';
import { assertDatabasePoolAuthority } from './databaseAuthority.js';
+import { createDatabaseRestoreRecovery, databaseRestoreRecoveryError } from './databaseRestoreRecovery.js';
const { Pool } = pg;
@@ -211,6 +212,12 @@ const GUARDED_CLIENT_HANDLER = {
const databaseContext = new AsyncLocalStorage();
const activeOperations = new Set();
let maintenanceActive = false;
+// Durable fence for a committed snapshot restore whose repair is pending
+// (#9725). It outlives this process: while the journal exists, only the
+// maintenance context that adopted the matching operation may use the pool.
+// Exported so the restore service writes the SAME journal this gate reads.
+const restoreRecovery = createDatabaseRestoreRecovery();
+export const databaseRestoreRecovery = restoreRecovery;
function maintenanceError() {
return Object.assign(new Error('Database restore in progress; retry after it finishes.'), {
@@ -218,13 +225,20 @@ function maintenanceError() {
});
}
+// The restore operation this async context may act for, if any. Only a live
+// maintenance context (or work it started while live) carries one.
+const restoreRecoveryContext = (store) => (store?.active ? store.restoreRecoveryId : undefined);
+
async function databaseOperation(fn) {
// A process-local restore context cannot bypass a durable cutover fence,
// and a pool still naming a cutover's retired backend never reaches it.
assertDatabaseAdmission();
assertDatabasePoolAuthority(POOL_CONFIG);
- if (maintenanceActive && !databaseContext.getStore()?.active) throw maintenanceError();
- const context = { active: true };
+ const parent = databaseContext.getStore();
+ if (maintenanceActive && !parent?.active) throw maintenanceError();
+ const restoreRecoveryId = restoreRecoveryContext(parent);
+ if (!restoreRecoveryId) restoreRecovery.assertAdmission();
+ const context = { active: true, restoreRecoveryId };
const pending = databaseContext.run(context, async () => fn());
activeOperations.add(pending);
try {
@@ -235,21 +249,36 @@ async function databaseOperation(fn) {
}
}
-/** Drain admitted database work and reject new work until restore completes. */
-export async function withDatabaseMaintenance(fn) {
+/**
+ * Drain admitted database work and reject new work until restore completes.
+ *
+ * A pending restore recovery journal refuses entry unless `restoreRecoveryId`
+ * names that same operation. `fn` receives `{ adoptRestoreRecovery(id) }`, which
+ * lets the restore that just published a journal keep using the database for
+ * that operation only; admission for everyone else stays closed until the
+ * journal is released.
+ */
+export async function withDatabaseMaintenance(fn, { restoreRecoveryId } = {}) {
assertDatabaseAdmission();
assertDatabasePoolAuthority(POOL_CONFIG);
if (maintenanceActive || databaseContext.getStore()?.active) throw maintenanceError();
+ if (restoreRecoveryId === undefined) restoreRecovery.assertAdmission();
+ else if (restoreRecovery.read()?.id !== restoreRecoveryId) throw databaseRestoreRecoveryError();
maintenanceActive = true;
- const context = { active: true };
+ const context = { active: true, restoreRecoveryId };
+ const adoptRestoreRecovery = (id) => {
+ if (!context.active || restoreRecovery.read()?.id !== id) throw databaseRestoreRecoveryError();
+ context.restoreRecoveryId = id;
+ };
try {
// An admitted transaction can start nested work while draining. Track it
// separately and repeat until that work also settles, even when its parent
// did not await it. Async descendants lose admission when their operation ends.
while (activeOperations.size) await Promise.allSettled([...activeOperations]);
- return await databaseContext.run(context, fn);
+ return await databaseContext.run(context, () => fn({ adoptRestoreRecovery }));
} finally {
context.active = false;
+ context.restoreRecoveryId = undefined;
maintenanceActive = false;
}
}
diff --git a/server/lib/db.restoreRecovery.test.js b/server/lib/db.restoreRecovery.test.js
new file mode 100644
index 0000000000..6f8c48f222
--- /dev/null
+++ b/server/lib/db.restoreRecovery.test.js
@@ -0,0 +1,153 @@
+// Database admission while a committed snapshot restore awaits recovery (#9725).
+// 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 { 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 }));
+vi.mock('./paths.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ const { mkdtempSync: mkdtemp } = await import('node:fs');
+ const { tmpdir: tmp } = await import('node:os');
+ const { join: joinPath } = await import('node:path');
+ fixture.dataRoot = mkdtemp(joinPath(tmp(), 'portos-restore-admission-'));
+ return { ...actual, PATHS: { ...actual.PATHS, data: fixture.dataRoot } };
+});
+
+const pool = vi.hoisted(() => ({
+ connect: vi.fn(async () => ({ query: vi.fn(async () => ({ rows: [] })), release: vi.fn() })),
+ on: vi.fn(),
+ query: vi.fn(async () => ({ rows: [] })),
+}));
+vi.mock('pg', async (importOriginal) => ({
+ default: {
+ Client: (await importOriginal()).default.Client,
+ Pool: vi.fn(function Pool() { return pool; }),
+ types: { setTypeParser: vi.fn() },
+ },
+}));
+
+const { query, withTransaction, withDatabaseMaintenance, databaseRestoreRecovery } = await import('./db.js');
+
+const begin = () => databaseRestoreRecovery.begin({
+ snapshotId: 'snap-1', dumpSha256: 'a'.repeat(64),
+ feedPositions: [{ sequencename: 'memories_sync_feed_seq', last_value: '500' }],
+});
+const FENCED = { status: 503, code: 'DATABASE_RESTORE_RECOVERY' };
+
+beforeEach(() => {
+ rmSync(databaseRestoreRecovery.path, { force: true });
+ vi.clearAllMocks();
+});
+afterAll(() => rmSync(fixture.dataRoot, { recursive: true, force: true }));
+
+describe('restore recovery admission', () => {
+ it('keeps ordinary work fenced after the restore that adopted the operation returns', async () => {
+ let id;
+ await withDatabaseMaintenance(async ({ adoptRestoreRecovery }) => {
+ id = begin().id;
+ adoptRestoreRecovery(id);
+ // The owning operation keeps the database for itself, including nested work.
+ await query('SELECT 1');
+ await withTransaction(client => client.query('SELECT 2'));
+ // A committed replay whose repair failed returns with the journal in place.
+ });
+ await expect(query('SELECT 3')).rejects.toMatchObject(FENCED);
+ await expect(withTransaction(() => {})).rejects.toMatchObject(FENCED);
+ await expect(withDatabaseMaintenance(() => {})).rejects.toMatchObject(FENCED);
+ expect(pool.query.mock.calls.map(([sql]) => sql)).toEqual(['SELECT 1']);
+
+ // Only the matching operation may re-enter; release reopens admission.
+ await expect(withDatabaseMaintenance(() => {}, { restoreRecoveryId: '00000000-0000-4000-8000-000000000009' }))
+ .rejects.toMatchObject(FENCED);
+ await withDatabaseMaintenance(async () => {
+ await query('SELECT 4');
+ databaseRestoreRecovery.release(id);
+ }, { restoreRecoveryId: id });
+ await expect(query('SELECT 5')).resolves.toEqual({ rows: [] });
+ });
+
+ it('withdraws recovery authority from work that outlives the maintenance context', async () => {
+ const { id } = begin();
+ let escape;
+ await withDatabaseMaintenance(async () => {
+ escape = () => query('SELECT late');
+ }, { restoreRecoveryId: id });
+ await expect(escape()).rejects.toMatchObject(FENCED);
+ });
+
+ it('fails closed on a damaged journal, including the boot fence', async () => {
+ writeFileSync(databaseRestoreRecovery.path, '{"version":1');
+ await expect(query('SELECT 1')).rejects.toMatchObject(FENCED);
+ expect(() => databaseRestoreRecovery.read()).toThrow();
+ await expect(import('../services/databaseBootFence.js')).rejects.toMatchObject({ code: 'DATABASE_RESTORE_RECOVERY' });
+ expect(pool.query).not.toHaveBeenCalled();
+ });
+
+ it('never lets a second restore overwrite a pending operation', () => {
+ const first = begin();
+ expect(() => begin()).toThrow();
+ expect(databaseRestoreRecovery.read()).toEqual(first);
+ expect(databaseRestoreRecovery.markCommitted(first.id)).toEqual({ ...first, stage: 'repairing' });
+ expect(databaseRestoreRecovery.read().feedPositions).toEqual(first.feedPositions);
+ });
+});
+
+// A restarted server with recovery pending must not reach its application
+// graph: start.js resumes recovery first and refuses boot unless it completes.
+describe('restart with pending restore recovery', () => {
+ const startScript = fileURLToPath(new URL('../start.js', import.meta.url));
+ const childEnv = { ...process.env };
+ delete childEnv.VITEST;
+
+ const boot = (journalBody) => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-restore-boot-'));
+ try {
+ writeFileSync(join(root, '.portos-disposable-root'), '');
+ mkdirSync(join(root, 'data'));
+ const journalPath = join(root, 'data', 'database-restore-recovery.json');
+ writeFileSync(journalPath, journalBody);
+ // No real pg connection is possible: every pool use throws.
+ const stub = `export default {Client:class {connectionParameters={ssl:false,sslnegotiation:"postgres"}},types:{setTypeParser(){}},Pool:class {
+ on(){} query(){throw Error('POOL_REACHED')} connect(){throw Error('POOL_REACHED')}
+ }};`;
+ const loader = join(root, 'pg-loader.mjs');
+ writeFileSync(loader, `export async function resolve(specifier, context, next) {
+ if (specifier === 'pg') return {url: ${JSON.stringify('data:text/javascript,' + encodeURIComponent(stub))}, shortCircuit:true};
+ return next(specifier, context);
+ }`);
+ const result = spawnSync(process.execPath, ['--loader', pathToFileURL(loader).href, startScript], {
+ encoding: 'utf8',
+ env: { ...childEnv, PORTOS_DATA_ROOT: root, PGDATABASE: 'example_test', PGPASSWORD: 'example-only' },
+ timeout: 20_000,
+ });
+ return { ...result, journalAfter: readFileSync(journalPath, 'utf8') };
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ };
+
+ it('refuses boot and keeps the committed operation when repair cannot finish', () => {
+ const record = {
+ version: 1, id: '00000000-0000-4000-8000-000000000003', stage: 'repairing',
+ createdAt: '2026-01-01T00:00:00.000Z', snapshotId: 'snap-1', dumpSha256: 'a'.repeat(64),
+ feedPositions: [{ sequencename: 'memories_sync_feed_seq', last_value: '500' }],
+ };
+ const body = JSON.stringify(record);
+ const result = boot(body);
+ expect(result.status, result.stderr).toBe(1);
+ expect(result.stderr).toContain('Database restore recovery is still pending (restore_schema_reconciliation)');
+ expect(result.journalAfter).toBe(body);
+ });
+
+ it('refuses boot on an unreadable journal without touching it', () => {
+ const result = boot('{ damaged');
+ expect(result.status, result.stderr).toBe(1);
+ expect(result.stderr).toContain('Database restore recovery is still pending (DATABASE_RESTORE_RECOVERY)');
+ expect(result.journalAfter).toBe('{ damaged');
+ });
+});
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
index c54424e51a..c0151ebbc4 100644
--- a/server/lib/db/schema/README.md
+++ b/server/lib/db/schema/README.md
@@ -23,7 +23,7 @@ init-db.sql, each with a one-line reason.
| Module | Export(s) | Domain |
|---|---|---|
-| `core.js` | `coreDdl` | Memory sync columns + the `schema_migrations` version tracker |
+| `core.js` | `coreDdl`, `restoreReceiptsDdl` | Memory sync columns + the `schema_migrations` version tracker + machine-local `restore_receipts` (snapshot restore replay receipts, #9725) |
| `tribe.js` | `tribeDdl` | Tribe CRM — people, network-scoped identities (`tribe_identities`, the durable-handle truth table behind Beeper linking), touchpoints, memory links (machine-local) |
| `humanActivity.js` | `humanActivityDdl` | Human-activity timeline event store (machine-local) |
| `post.js` | `postDdl` | MeatSpace POST normalized runs and attempts (machine-local) |
diff --git a/server/lib/db/schema/core.js b/server/lib/db/schema/core.js
index ac31083694..9caccc275b 100644
--- a/server/lib/db/schema/core.js
+++ b/server/lib/db/schema/core.js
@@ -2,6 +2,22 @@
// tracker. Extracted from ensureSchemaImpl() in server/lib/db.js (#2832) with
// zero behavior change; every statement is idempotent and runs on every boot.
// Parity-locked against server/scripts/init-db.sql by db.ddlParity.test.js.
+
+// Machine-local replay receipts for snapshot database restores (#9725). The
+// restore writes one row for its unique operation id INSIDE the replay
+// transaction, after the dump, so a lost response or crash at COMMIT is
+// resolved from the database instead of guessed. pg_dump excludes its rows
+// (they describe this machine's restores, not application data); historical
+// receipts can never match a fresh operation id. The restore appends this exact
+// statement to its replay, so an older dump that predates the table still gets it.
+export const restoreReceiptsDdl = [
+ `CREATE TABLE IF NOT EXISTS restore_receipts (
+ operation_id UUID PRIMARY KEY,
+ dump_sha256 TEXT NOT NULL,
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )`,
+];
+
export const coreDdl = [
`CREATE TABLE IF NOT EXISTS app_quality_measurements (
app_id TEXT NOT NULL,
@@ -28,4 +44,5 @@ export const coreDdl = [
id TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ ...restoreReceiptsDdl,
];
diff --git a/server/lib/index.js b/server/lib/index.js
index ee6c5d921e..a6b03baccb 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -777,6 +777,8 @@ export * from './databaseAuthority.js';
export * from './databaseMaintenanceJournal.js';
+export * from './databaseRestoreRecovery.js';
+
export * from './databaseWriterRegistry.js';
export * from './musicVideoCreativeContext.js';
diff --git a/server/lib/validation.js b/server/lib/validation.js
index ca07830a78..6249a00289 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1176,6 +1176,12 @@ export const restoreDbRequestSchema = z.object({
dryRun: z.boolean().optional().default(true)
});
+// Resume a committed snapshot database restore awaiting recovery (#9725). The
+// id must name the pending operation; recovery never replays the dump.
+export const restoreDbRecoverRequestSchema = z.object({
+ id: z.string().uuid(),
+}).strict();
+
// Per-feature AI provider assignment: which configured CLI provider/model a
// feature runs through (e.g. `settings.autofixer`, `settings.calendarSync`).
// Empty string (UI "unset" sentinel) is coerced to undefined so it round-trips
diff --git a/server/routes/backup.js b/server/routes/backup.js
index cd657cdc34..464188cc97 100644
--- a/server/routes/backup.js
+++ b/server/routes/backup.js
@@ -5,9 +5,11 @@ import {
validateRequest,
restoreRequestSchema,
restoreDbRequestSchema,
+ restoreDbRecoverRequestSchema,
snapshotDownloadQuerySchema,
} from '../lib/validation.js';
import * as backup from '../services/backup.js';
+import { getDatabaseRestoreRecoveryStatus, resumeDatabaseRestore } from '../services/backupRestoreRecovery.js';
import { getSettings } from '../services/settings.js';
import { resolveBackupConfig } from '../lib/backupConfig.js';
@@ -22,7 +24,9 @@ router.get('/status', asyncHandler(async (req, res) => {
...state,
destPath: settings.backup?.destPath ?? null,
nextRun,
- defaultExcludes: backup.DEFAULT_EXCLUDES
+ defaultExcludes: backup.DEFAULT_EXCLUDES,
+ // A committed database restore awaiting repair keeps the database fenced.
+ restoreRecovery: getDatabaseRestoreRecoveryStatus(),
});
}));
@@ -108,4 +112,12 @@ router.post('/restore-db', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/backup/restore-db/recover
+// Resume the pending committed restore: resolve an unknown replay outcome from
+// its receipt, then finish schema/migration/federation repair. Never replays.
+router.post('/restore-db/recover', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(restoreDbRecoverRequestSchema, req.body);
+ res.json(await resumeDatabaseRestore(id));
+}));
+
export default router;
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 1bfc3b378a..e250cef2a1 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -20,6 +20,11 @@ vi.mock('../services/backup.js', () => ({
]
}));
+vi.mock('../services/backupRestoreRecovery.js', () => ({
+ getDatabaseRestoreRecoveryStatus: vi.fn(() => ({ pending: false })),
+ resumeDatabaseRestore: vi.fn(),
+}));
+
vi.mock('../services/settings.js', () => ({
getSettings: vi.fn(),
settingsEvents: new EventEmitter()
@@ -38,6 +43,7 @@ import { authGate, hostControlRouteGate } from '../services/authGate.js';
import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';
import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
import * as backup from '../services/backup.js';
+import { getDatabaseRestoreRecoveryStatus, resumeDatabaseRestore } from '../services/backupRestoreRecovery.js';
import { getSettings } from '../services/settings.js';
import backupRoutes from './backup.js';
@@ -70,10 +76,20 @@ describe('backup routes', () => {
defaultExcludes: [
{ path: '/browser-profile/', reason: 'test', overridable: false },
{ path: '/loras/*.safetensors', reason: 'test', overridable: true }
- ]
+ ],
+ restoreRecovery: { pending: false },
});
});
+ it('reports a committed restore awaiting recovery (#9725)', async () => {
+ backup.getState.mockResolvedValue({});
+ getSettings.mockResolvedValue({ backup: {} });
+ const pending = { pending: true, id: '00000000-0000-4000-8000-000000000001', stage: 'repairing', snapshotId: 'snap-1', createdAt: '2026-01-01T00:00:00.000Z' };
+ getDatabaseRestoreRecoveryStatus.mockReturnValueOnce(pending);
+ const res = await request(buildApp()).get('/api/backup/status');
+ expect(res.body.restoreRecovery).toEqual(pending);
+ });
+
it('serves a process-local persistence failure without hiding the last successful snapshot', async () => {
const state = {
status: 'error', lastSnapshotId: 'previous-snapshot',
@@ -351,6 +367,25 @@ describe('backup routes', () => {
});
});
+ describe('POST /api/backup/restore-db/recover', () => {
+ it('resumes exactly the named pending operation', async () => {
+ const id = '00000000-0000-4000-8000-000000000001';
+ resumeDatabaseRestore.mockResolvedValue({ status: 'ok', outcome: 'repaired', syncCursorsRewound: 1 });
+ const res = await request(buildApp()).post('/api/backup/restore-db/recover').send({ id });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ status: 'ok', outcome: 'repaired', syncCursorsRewound: 1 });
+ expect(resumeDatabaseRestore).toHaveBeenCalledWith(id);
+ });
+
+ it('rejects a missing or malformed operation id without resuming', async () => {
+ for (const body of [{}, { id: 'snap-1' }, { id: '00000000-0000-4000-8000-000000000001', dryRun: false }]) {
+ const res = await request(buildApp()).post('/api/backup/restore-db/recover').send(body);
+ expect(res.status).toBe(400);
+ }
+ expect(resumeDatabaseRestore).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /api/backup/restore-db', () => {
it('calls restorePostgres with the validated body (dryRun default true)', async () => {
getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 48825b359a..31a0f9c891 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -68,6 +68,15 @@ CREATE TABLE IF NOT EXISTS schema_migrations (
applied_at TIMESTAMPTZ DEFAULT NOW()
);
+-- Machine-local replay receipts for snapshot database restores (#9725): one row
+-- per committed restore operation, written inside the replay transaction.
+-- Mirrors restoreReceiptsDdl in server/lib/db/schema/core.js.
+CREATE TABLE IF NOT EXISTS restore_receipts (
+ operation_id UUID PRIMARY KEY,
+ dump_sha256 TEXT NOT NULL,
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
-- MeatSpace POST normalized run/attempt history. Machine-local: personal
-- performance evidence never rides federation.
CREATE TABLE IF NOT EXISTS post_runs (
diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.js
index 035a0a4c72..231064066d 100644
--- a/server/services/backup.db.test.js
+++ b/server/services/backup.db.test.js
@@ -14,6 +14,29 @@ import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.
// The real rewind rewrites this install's data/instances_sync_cursors.json.
const rewindPostgresSyncCursors = vi.hoisted(() => vi.fn(async () => 0));
vi.mock('./syncOrchestrator.js', () => ({ rewindPostgresSyncCursors }));
+// The restore recovery journal (#9725) lives in data/ and fences the pool; keep
+// it in a disposable data root, never the install's live tree.
+const dataRoot = vi.hoisted(() => ({ path: null }));
+vi.mock('../lib/paths.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir: osTmp } = await import('node:os');
+ dataRoot.path = mkdtempSync(join(osTmp(), 'portos-restore-db-data-'));
+ return { ...actual, PATHS: { ...actual.PATHS, data: dataRoot.path } };
+});
+const runDbMigrationsFault = vi.hoisted(() => ({ next: null }));
+vi.mock('../scripts/run-db-migrations.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ runDbMigrations: async (...args) => {
+ const fault = runDbMigrationsFault.next;
+ runDbMigrationsFault.next = null;
+ if (fault) throw fault;
+ return actual.runDbMigrations(...args);
+ },
+ };
+});
// Load the service before timing restore assertions, as other integration
// suites do. A cold module graph is setup, not database replay time.
@@ -55,6 +78,7 @@ afterAll(async () => {
}
await close();
if (dest) await rm(dest, { recursive: true, force: true });
+ if (dataRoot.path) await rm(dataRoot.path, { recursive: true, force: true });
});
async function restore(dryRun = false, snapshotId = 'old-schema') {
@@ -136,6 +160,31 @@ describe.skipIf(!ready)('restore older database schema', () => {
expect(await runDbMigrations()).toBe(0);
});
+ // #9725: a committed replay whose repair fails keeps ordinary work fenced
+ // with its receipt and ORIGINAL floors, and recovery repairs without replay.
+ it('fences a committed replay whose migrations fail, then recovers from the receipt and original floors', async () => {
+ const { resumeDatabaseRestore } = await import('./backupRestoreRecovery.js');
+ const { databaseRestoreRecovery } = await import('../lib/db.js');
+ await query("SELECT nextval('memories_sync_feed_seq') FROM generate_series(1, 3)");
+ const floorBefore = BigInt((await feedSequenceValues()).memories_sync_feed_seq);
+ runDbMigrationsFault.next = new Error('injected migration fault');
+ const failed = await restore();
+ expect(failed).toMatchObject({ status: 'failed', reason: 'restore_schema_reconciliation', recovery: { stage: 'repairing' } });
+ const journal = databaseRestoreRecovery.read();
+ expect(journal.id).toBe(failed.recovery.id);
+ expect(BigInt(journal.feedPositions.find(p => p.sequencename === 'memories_sync_feed_seq').last_value)).toBe(floorBefore);
+ await expect(query('SELECT 1')).rejects.toMatchObject({ code: 'DATABASE_RESTORE_RECOVERY' });
+ expect(await restore(true)).toMatchObject({ status: 'failed', reason: 'restore_recovery_pending' });
+
+ expect(await resumeDatabaseRestore(journal.id)).toMatchObject({ status: 'ok', outcome: 'repaired' });
+ expect(databaseRestoreRecovery.read()).toBeNull();
+ // The receipt committed with the replay, inside its transaction.
+ expect((await query('SELECT dump_sha256 FROM restore_receipts WHERE operation_id = $1', [journal.id])).rows)
+ .toEqual([{ dump_sha256: journal.dumpSha256 }]);
+ const next = (await query("SELECT nextval('memories_sync_feed_seq')::text AS v")).rows[0].v;
+ expect(BigInt(next)).toBeGreaterThan(floorBefore);
+ });
+
it('rolls back the reset and preserves rows and constraints when replay fails', async () => {
const invalidDir = join(dest, 'snapshots', 'fixture-source', 'invalid-sql');
await mkdir(invalidDir);
diff --git a/server/services/backup.js b/server/services/backup.js
index 87b5ca3ff7..adb673f834 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -18,10 +18,13 @@ import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createLineReader } from '../lib/streamLines.js';
import { getEvent } from './eventScheduler.js';
-import { POOL_CONFIG, checkHealth, ensureSchema, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';
+import { POOL_CONFIG, checkHealth, databaseRestoreRecovery, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';
import { withPgToolEnv, resolvePgDumpBinary } from '../lib/pgTools.js';
import { inspectDatabaseDump } from './backupDatabaseDump.js';
-import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';
+import {
+ captureSyncFeedPositions, pendingRecoveryResult, repairCommittedRestore, restoreApplicationName, restoreReceiptSql,
+ restoreRecoveryRefusal, settleReplayOutcome,
+} from './backupRestoreRecovery.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
import { isSafeSnapshotSource, isSafeSubdirFilter, anchorUserExcludes } from '../lib/sharedSchemas.js';
@@ -182,6 +185,11 @@ export const DEFAULT_EXCLUDES = [
// which model weights are on THIS machine's disks; restoring it onto another
// would claim gigabytes of models that machine does not have, and offer delete
// buttons for them. It is fully re-derivable by a rescan from Models → Status.
+ // Anchored, like every entry here. The restore recovery journal (#9725) is an
+ // admission fence for THIS machine's in-flight database restore; a restored
+ // copy would re-fence the database for an operation that no longer exists.
+ { path: '/database-restore-recovery.json', reason: 'In-flight database restore recovery journal — a machine-local admission fence for one restore operation, never data to restore', overridable: false },
+ { path: '/.database-restore-recovery-*.pending', reason: 'Unpublished database restore recovery journal bytes — scratch from an interrupted journal write', overridable: false },
{ path: '/model-manifest.json', reason: 'Tracked downloaded-model inventory — machine-local and re-derivable by rescanning the model stores; a restored copy would describe another machine\'s disks', overridable: false },
// Anchored, like every entry here. Readiness evidence is bound to THIS
// machine's local image id (a restored copy would read as stale anyway) and
@@ -748,6 +756,9 @@ export async function dumpPostgres(outputPath) {
'--no-acl',
'--clean',
'--if-exists',
+ // Machine-local replay receipts (#9725) describe this install's past
+ // restores, not application data; the table definition is still dumped.
+ '--exclude-table-data=restore_receipts',
'-f', outputPath
], {
shell: false,
@@ -1536,9 +1547,12 @@ const DUMP_UNREADABLE = Object.freeze({ status: 'failed', reason: 'dump_unreadab
* { status: 'ok', dryRun, sizeBytes, tableCount } (dry-run or applied)
* { status: 'skipped', reason: 'no_dump' } (no sql file in snapshot)
* { status: 'skipped', reason: 'not_configured' } (real restore, PG unreachable)
- * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'dump_unreadable'|'dump_incomplete'|'restore_preflight'|'restore_error'|'timeout'|'restore_schema_reconciliation'|'restore_sync_resync', error? }
- * A successful real restore also carries `syncCursorsRewound` (peer count);
- * see resyncFederationAfterRestore.
+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'dump_unreadable'|'dump_incomplete'|'restore_preflight'|'restore_journal'|'restore_error'|'timeout', error? }
+ * (nothing changed; a failed replay is reported only once proven rolled back)
+ * { status: 'failed', reason: 'restore_recovery_pending'|'restore_commit_unknown'|'restore_schema_reconciliation'|'restore_sync_resync'|'restore_recovery_release', error, recovery }
+ * (a restore awaits recovery: ordinary database work stays fenced until
+ * resumeDatabaseRestore finishes it — see backupRestoreRecovery.js, #9725)
+ * A successful real restore also carries `syncCursorsRewound` (peer count).
* @param {string} destPath - Backup destination root
* @param {string} snapshotId
* @param {{dryRun?: boolean}} [options]
@@ -1548,6 +1562,10 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
const { snapshotDir, currentSource } = resolved;
await assertExplicitSnapshotSourceSafe(resolved, snapshotId);
await assertSnapshotRestorable(snapshotDir, snapshotId, currentSource);
+ // A committed restore awaiting repair fences the database; neither a preview
+ // nor another replay may start until it is resolved (#9725).
+ const pendingRecovery = restoreRecoveryRefusal();
+ if (pendingRecovery) return pendingRecovery;
const sqlPath = join(snapshotDir, 'portos-db.sql');
const info = await stat(sqlPath).catch(() => null);
@@ -1631,9 +1649,25 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI
}
if (dryRun) return { status: 'ok', dryRun: true, sizeBytes, tableCount };
- return withDatabaseMaintenance(async () => {
- // Read before the replay rewinds them to the dump's values.
+ return withDatabaseMaintenance(async ({ adoptRestoreRecovery }) => {
+ // Read before the replay rewinds them, then make them durable together
+ // with this operation's identity BEFORE anything destructive runs: a
+ // committed replay whose repair fails (or a restart) must floor sequences
+ // at THESE positions, never at values re-read after the dump reset them.
const feedPositions = await captureSyncFeedPositions();
+ let record;
+ try {
+ record = databaseRestoreRecovery.begin({ snapshotId, dumpSha256: dump.sha256, feedPositions });
+ adoptRestoreRecovery(record.id);
+ } catch (err) {
+ if (record) throw err;
+ console.error(`❌ restore: recovery journal could not be written for snapshot ${snapshotId}: ${err.message}`);
+ return {
+ status: 'failed',
+ reason: 'restore_journal',
+ error: 'The restore recovery journal could not be written. Restore was refused without changing data.',
+ };
+ }
const { host: pgHost, port, database: pgDb, user: pgUser } = POOL_CONFIG;
const pgPort = String(port);
@@ -1644,13 +1678,16 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI
// applies or leaves the live DB untouched — never a mixed snapshot/current
// state. (The dump is written with --clean --if-exists, so the DROPs and
// recreates all commit or roll back as one unit.) psql reads the admitted
- // spool copy, never the snapshot path.
+ // spool copy, never the snapshot path. The trailing receipt commits with
+ // the dump or not at all, and the application name identifies this
+ // replay's session to recovery (#9725).
const proc = spawn('psql', [
'-X', '-v', 'ON_ERROR_STOP=1',
'--single-transaction',
'--echo-all',
- '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-c', reset, '-f', spoolPath
- ], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: pgEnv });
+ '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-c', reset, '-f', spoolPath,
+ '-c', restoreReceiptSql(record),
+ ], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...pgEnv, PGAPPNAME: restoreApplicationName(record.id) } });
let stderr = '';
const watchdog = watchBackupProcess(proc, { label: 'PostgreSQL restore' });
@@ -1684,83 +1721,28 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI
console.warn(`⚠️ psql not available: ${err.message}`);
resolveP({ status: 'failed', reason: 'restore_error', error: err.message });
});
- }));
- if (replay.status !== 'ok') return replay;
-
- // Replay has committed. Reapply this version's upgrades even when readiness
- // was cached before the restore, then honor the restored migration ledger.
- const reconciliationError = await (async () => {
- await ensureSchema({ force: true });
- const { runDbMigrations } = await import('../scripts/run-db-migrations.js');
- await runDbMigrations();
- })().then(() => null, (err) => err);
- if (reconciliationError) {
- console.error(`❌ DB restore schema reconciliation failed: ${reconciliationError.message}`);
- return {
- status: 'failed',
- reason: 'restore_schema_reconciliation',
- error: 'The database dump was applied, but schema recovery is incomplete. The restore was not rolled back. Restart PortOS to retry schema recovery; if it still fails, inspect the server logs and repair the database before continuing.',
- };
- }
- // Still inside maintenance, so no sync apply or feed write can interleave
- // between the restored rows and the federation repair.
- const resync = await resyncFederationAfterRestore(feedPositions).then(
- (syncCursorsRewound) => ({ syncCursorsRewound }),
- (err) => ({ err }),
- );
- if (resync.err) {
- console.error(`❌ DB restore federation resync failed: ${resync.err.message}`);
- return {
- status: 'failed',
- reason: 'restore_sync_resync',
- error: 'The database dump was applied, but peer sync could not be reset. Federated memories and Catalog records pulled after this snapshot may stay missing until the restore is repeated.',
- };
- }
- return { ...replay, syncCursorsRewound: resync.syncCursorsRewound };
- });
-}
+ })).catch((err) => ({ status: 'failed', reason: 'restore_error', error: err.message }));
-// Feed sequences present before the replay (a pre-#8315 install has none).
-// pg_sequences reports a NULL last_value for a never-drawn sequence, which
-// holds no position worth preserving.
-async function captureSyncFeedPositions() {
- const { rows } = await query(
- `SELECT sequencename, last_value::text AS last_value FROM pg_sequences
- WHERE schemaname = current_schema() AND sequencename = ANY($1::text[]) AND last_value IS NOT NULL`,
- [syncFeedTables.map(syncFeedSequenceName)],
- );
- return rows;
-}
+ if (replay.status === 'ok') {
+ // psql exit 0 under --single-transaction means COMMIT succeeded.
+ record = databaseRestoreRecovery.markCommitted(record.id);
+ } else {
+ // A failed/killed/lost psql may still have committed (a crash or lost
+ // response at COMMIT). Only the receipt can say; an unknown outcome stays
+ // fenced instead of reopening writes or replaying again.
+ const settled = await settleReplayOutcome(record);
+ if (settled.outcome === 'rolled_back') return replay;
+ if (settled.outcome === 'uncertain') return pendingRecoveryResult('restore_commit_unknown', record);
+ record = settled.record;
+ }
-/**
- * Repair both directions of peer sync after a dump replay (#8710).
- *
- * Outbound: the dump `setval`s each feed sequence back to the dump's maximum,
- * so new rows would reuse positions peers already passed and never be pulled.
- * Floor every sequence at its pre-restore value so post-restore positions land
- * above any cursor a peer holds.
- *
- * Inbound: our per-peer memory/Catalog cursors still point past rows the
- * restore discarded. Rewind them so the next sync replays each peer's streams
- * through the idempotent LWW / ON CONFLICT apply paths.
- * @param {Array<{sequencename: string, last_value: string}>} feedPositions
- * @returns {Promise<number>} peers whose cursors were rewound
- */
-async function resyncFederationAfterRestore(feedPositions) {
- if (feedPositions.length) {
- // GREATEST ignores the NULL of a sequence the dump left undrawn.
- await query(
- `SELECT setval(format('%I', s.sequencename)::regclass, GREATEST(c.captured::bigint, s.last_value))
- FROM pg_sequences s
- JOIN unnest($1::text[], $2::text[]) AS c(name, captured) ON c.name = s.sequencename
- WHERE s.schemaname = current_schema()`,
- [feedPositions.map((p) => p.sequencename), feedPositions.map((p) => p.last_value)],
- );
- }
- const { rewindPostgresSyncCursors } = await import('./syncOrchestrator.js');
- const peers = await rewindPostgresSyncCursors();
- console.log(`🔄 DB restore: floored ${feedPositions.length} sync feed sequences, rewound memory/Catalog cursors for ${peers} peers`);
- return peers;
+ // Replay has committed. Still inside maintenance and still fenced, so no
+ // sync apply or feed write can interleave with the repair, and a failed
+ // step leaves ordinary work closed with the original positions recorded.
+ const repaired = await repairCommittedRestore(record);
+ if (repaired.status !== 'ok') return repaired;
+ return { status: 'ok', dryRun: false, sizeBytes, tableCount, syncCursorsRewound: repaired.syncCursorsRewound };
+ });
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 907838fb51..793e3b74fa 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -24,7 +24,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
-import { createReadStream, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'fs';
+import { createReadStream, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { basename, dirname, join as joinPath } from 'path';
import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -48,11 +48,14 @@ afterAll(() => {
// Mock the DB health check and child_process.spawn before importing backup.js
const poolConfig = vi.hoisted(() => Object.freeze({ host: 'db.example.test', port: 5439, database: 'example_db', user: 'example_user', password: 'example-secret', ssl: false, sslnegotiation: 'postgres' }));
-vi.mock('../lib/db.js', () => ({
+// The restore recovery journal (#9725) is the real one, rooted in the temp data
+// tree, so the suite exercises its durable publication and fence.
+vi.mock('../lib/db.js', async () => ({
POOL_CONFIG: poolConfig,
checkHealth: vi.fn(),
query: vi.fn().mockResolvedValue({ rows: [] }),
- withDatabaseMaintenance: vi.fn(fn => fn()),
+ withDatabaseMaintenance: vi.fn(fn => fn({ adoptRestoreRecovery: vi.fn() })),
+ databaseRestoreRecovery: (await vi.importActual('../lib/databaseRestoreRecovery.js')).createDatabaseRestoreRecovery(testDataRoot()),
ensureSchema: vi.fn().mockResolvedValue(undefined),
// Default to null (version unknown) so dumpPostgres keeps the bare-`pg_dump`
// path and the existing status tests don't trigger live binary discovery.
@@ -1180,6 +1183,20 @@ function mockDumpStream(...reads) {
});
}
+// Restore recovery journal + replay-receipt inspection (#9725). By default the
+// database reports no live replay session and no receipt, i.e. a failed
+// replay is a proven rollback.
+const RECOVERY_JOURNAL = () => joinPath(testDataRoot(), 'database-restore-recovery.json');
+const readRecoveryJournal = () => (existsSync(RECOVERY_JOURNAL()) ? JSON.parse(readFileSync(RECOVERY_JOURNAL(), 'utf8')) : null);
+function restoreDbAnswer({ feed = [], sessions = 0, receipt = null } = {}) {
+ return async (sql) => {
+ if (sql.includes('pg_stat_activity')) return { rows: [{ sessions, has_receipts: receipt !== null }] };
+ if (sql.includes('FROM restore_receipts')) return { rows: receipt ? [{ dump_sha256: receipt }] : [] };
+ if (sql.includes('FROM pg_sequences') && !sql.includes('setval')) return { rows: feed };
+ return { rows: [] };
+ };
+}
+
describe('restorePostgres', () => {
let restorePostgres;
const mockLegacyDumpRead = (...reads) => {
@@ -1204,6 +1221,8 @@ describe('restorePostgres', () => {
// clearAllMocks does not undo stubEnv — a PGPASSWORD stub from a failed
// (thrown) test would otherwise leak into every test after it.
vi.unstubAllEnvs();
+ rmSync(RECOVERY_JOURNAL(), { force: true });
+ query.mockReset().mockImplementation(restoreDbAnswer());
checkHealth.mockResolvedValue({ connected: true });
({ restorePostgres } = await import('./backup.js'));
});
@@ -1243,6 +1262,8 @@ describe('restorePostgres', () => {
expect(result.sizeBytes).toBe(4096);
expect(result.tableCount).toBe(2);
expect(spawn).not.toHaveBeenCalled();
+ expect(withDatabaseMaintenance).not.toHaveBeenCalled();
+ expect(readRecoveryJournal()).toBeNull();
expect(ensureSchema).not.toHaveBeenCalled();
expect(runDbMigrations).not.toHaveBeenCalled();
});
@@ -1335,6 +1356,8 @@ describe('restorePostgres', () => {
expect(result.status).toBe('failed');
expect(result.reason).toBe('restore_error');
expect(result.error).toContain('already exists');
+ // Proven rollback (no live replay session, no receipt): admission reopens.
+ expect(readRecoveryJournal()).toBeNull();
expect(ensureSchema).not.toHaveBeenCalled();
expect(runDbMigrations).not.toHaveBeenCalled();
});
@@ -1367,23 +1390,143 @@ describe('restorePostgres', () => {
await expect(pending).resolves.toMatchObject({ status: 'ok', dryRun: false });
});
- it.each(['schema', 'migrations'])('reports committed replay when %s reconciliation fails', async (phase) => {
- vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- mockLegacyDumpRead();
- checkHealth.mockResolvedValue({ connected: true });
- (phase === 'schema' ? ensureSchema : runDbMigrations).mockRejectedValueOnce(new Error('upgrade failed'));
- const proc = fakeProc();
- spawn.mockReturnValue(proc);
- const pending = restorePostgres('/dest', 'snap-1', { dryRun: false });
- await flush();
- proc.emit('close', 0);
- const result = await pending;
- expect(result).toMatchObject({ status: 'failed', reason: 'restore_schema_reconciliation' });
- expect(result.error).toContain('dump was applied');
- expect(result.error).toContain('not rolled back');
- expect(result.error).toContain('Restart PortOS');
- if (phase === 'schema') expect(runDbMigrations).not.toHaveBeenCalled();
- expect(rewindPostgresSyncCursors).not.toHaveBeenCalled();
+ // #9725: a replay that COMMITTED must never reopen ordinary writes, lose its
+ // pre-replay feed positions, or be replayed again when repair fails.
+ describe('committed-restore recovery', () => {
+ const ORIGINAL = [{ sequencename: 'memories_sync_feed_seq', last_value: '500' }];
+ const setvalCalls = () => query.mock.calls.filter(([sql]) => sql.includes('setval'));
+ let resumeDatabaseRestore;
+ beforeEach(async () => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ mockLegacyDumpRead();
+ query.mockImplementation(restoreDbAnswer({ feed: ORIGINAL }));
+ ({ resumeDatabaseRestore } = await import('./backupRestoreRecovery.js'));
+ });
+
+ const runRestore = async ({ exitCode = 0, onSpawn } = {}) => {
+ const proc = fakeProc();
+ spawn.mockImplementation((...args) => { onSpawn?.(...args); return proc; });
+ const pending = restorePostgres('/dest', 'snap-1', { dryRun: false });
+ await flush();
+ proc.emit('close', exitCode);
+ return pending;
+ };
+
+ it('publishes the operation and ORIGINAL positions before replay and commits a receipt inside the replay', async () => {
+ let atSpawn;
+ const result = await runRestore({ onSpawn: (_bin, args, opts) => { atSpawn = { args, env: opts.env, journal: readRecoveryJournal() }; } });
+ expect(result).toMatchObject({ status: 'ok', syncCursorsRewound: 2 });
+ expect(atSpawn.journal).toMatchObject({ stage: 'replaying', snapshotId: 'snap-1', feedPositions: ORIGINAL });
+ // The receipt is the LAST command of the single replay transaction.
+ expect(atSpawn.args.at(-2)).toBe('-c');
+ expect(atSpawn.args.at(-1)).toContain(`INSERT INTO restore_receipts (operation_id, dump_sha256) VALUES ('${atSpawn.journal.id}', '${atSpawn.journal.dumpSha256}')`);
+ expect(atSpawn.args.indexOf('-f')).toBeLessThan(atSpawn.args.length - 2);
+ expect(atSpawn.env.PGAPPNAME).toBe(`portos-restore-${atSpawn.journal.id}`);
+ // Success releases admission.
+ expect(readRecoveryJournal()).toBeNull();
+ });
+
+ it.each([
+ ['schema upgrade', () => ensureSchema.mockRejectedValueOnce(new Error('ddl failed')), 'restore_schema_reconciliation'],
+ ['ordered migration', () => runDbMigrations.mockRejectedValueOnce(new Error('migration failed')), 'restore_schema_reconciliation'],
+ ['cursor write', () => rewindPostgresSyncCursors.mockRejectedValueOnce(new Error('disk full')), 'restore_sync_resync'],
+ ])('a %s fault after commit stays fenced, then recovery repairs from the original floors without replaying', async (_case, inject, reason) => {
+ inject();
+ const failed = await runRestore();
+ expect(failed).toMatchObject({ status: 'failed', reason, recovery: { stage: 'repairing', snapshotId: 'snap-1' } });
+ expect(failed.error).toMatch(/not .*replayed/i);
+ const journal = readRecoveryJournal();
+ expect(journal).toMatchObject({ id: failed.recovery.id, stage: 'repairing', feedPositions: ORIGINAL });
+
+ // While pending, neither a preview nor another replay may start.
+ for (const dryRun of [true, false]) {
+ expect(await restorePostgres('/dest', 'snap-1', { dryRun }))
+ .toMatchObject({ status: 'failed', reason: 'restore_recovery_pending', recovery: { id: journal.id } });
+ }
+ expect(spawn).toHaveBeenCalledOnce();
+
+ // The live sequence was reset to the snapshot's 100 and one draw slipped
+ // in; recovery must floor at the recorded 500, never the re-read 101.
+ query.mockClear();
+ query.mockImplementation(restoreDbAnswer({ feed: [{ sequencename: 'memories_sync_feed_seq', last_value: '101' }] }));
+ rewindPostgresSyncCursors.mockClear();
+ expect(await resumeDatabaseRestore(journal.id)).toMatchObject({ status: 'ok', outcome: 'repaired', syncCursorsRewound: 2 });
+ expect(setvalCalls().map(([, params]) => params)).toEqual([[['memories_sync_feed_seq'], ['500']]]);
+ expect(rewindPostgresSyncCursors).toHaveBeenCalledOnce();
+ expect(spawn).toHaveBeenCalledOnce();
+ expect(readRecoveryJournal()).toBeNull();
+ // A finished recovery leaves nothing to resume.
+ expect(await resumeDatabaseRestore()).toEqual({ status: 'ok', outcome: 'none' });
+ });
+
+ it('refuses to resume a different operation than the pending one', async () => {
+ runDbMigrations.mockRejectedValueOnce(new Error('migration failed'));
+ await runRestore();
+ await expect(resumeDatabaseRestore('00000000-0000-4000-8000-000000000001'))
+ .rejects.toMatchObject({ status: 409 });
+ expect(readRecoveryJournal()).toMatchObject({ stage: 'repairing' });
+ });
+
+ it('resolves a lost psql response at COMMIT from the receipt and repairs instead of replaying', async () => {
+ let journal;
+ query.mockImplementation(async (sql, params) => restoreDbAnswer({ feed: ORIGINAL, receipt: journal?.dumpSha256 })(sql, params));
+ const result = await runRestore({ exitCode: 2, onSpawn: () => { journal = readRecoveryJournal(); } });
+ expect(result).toMatchObject({ status: 'ok', syncCursorsRewound: 2 });
+ expect(ensureSchema).toHaveBeenCalledWith({ force: true });
+ expect(setvalCalls()[0][1]).toEqual([['memories_sync_feed_seq'], ['500']]);
+ expect(readRecoveryJournal()).toBeNull();
+ });
+
+ it('keeps an unprovable outcome fenced, then releases unchanged once the receipt proves a rollback', async () => {
+ query.mockImplementation(async (sql) => {
+ if (sql.includes('pg_stat_activity')) throw new Error('connection refused');
+ return restoreDbAnswer({ feed: ORIGINAL })(sql);
+ });
+ const result = await runRestore({ exitCode: 2 });
+ expect(result).toMatchObject({ status: 'failed', reason: 'restore_commit_unknown', recovery: { stage: 'replaying' } });
+ expect(readRecoveryJournal()).toMatchObject({ stage: 'replaying' });
+ expect(ensureSchema).not.toHaveBeenCalled();
+ expect(rewindPostgresSyncCursors).not.toHaveBeenCalled();
+
+ query.mockImplementation(restoreDbAnswer());
+ expect(await resumeDatabaseRestore(result.recovery.id)).toEqual({ status: 'ok', outcome: 'rolled_back' });
+ expect(readRecoveryJournal()).toBeNull();
+ expect(spawn).toHaveBeenCalledOnce();
+ expect(setvalCalls()).toHaveLength(0);
+ });
+
+ it('treats a still-live replay session or a foreign digest as unprovable, and only a matching receipt as a commit', async () => {
+ // Seed a pending replay whose outcome was never observed (crash at COMMIT).
+ runDbMigrations.mockRejectedValueOnce(new Error('migration failed'));
+ await runRestore();
+ const pending = readRecoveryJournal();
+ writeFileSync(RECOVERY_JOURNAL(), JSON.stringify({ ...pending, stage: 'replaying' }));
+ vi.useFakeTimers();
+ try {
+ query.mockImplementation(restoreDbAnswer({ sessions: 1 }));
+ const live = resumeDatabaseRestore(pending.id);
+ await vi.runAllTimersAsync();
+ expect(await live).toMatchObject({ status: 'failed', reason: 'restore_commit_unknown' });
+ } finally {
+ vi.useRealTimers();
+ }
+ query.mockImplementation(restoreDbAnswer({ receipt: 'b'.repeat(64) }));
+ expect(await resumeDatabaseRestore(pending.id)).toMatchObject({ reason: 'restore_commit_unknown' });
+ expect(readRecoveryJournal()).toMatchObject({ stage: 'replaying' });
+ query.mockImplementation(restoreDbAnswer({ feed: ORIGINAL, receipt: pending.dumpSha256 }));
+ expect(await resumeDatabaseRestore(pending.id)).toMatchObject({ status: 'ok', outcome: 'repaired' });
+ expect(readRecoveryJournal()).toBeNull();
+ expect(spawn).toHaveBeenCalledOnce();
+ });
+
+ it('fails closed on a damaged journal', async () => {
+ writeFileSync(RECOVERY_JOURNAL(), '{ not json');
+ expect(await restorePostgres('/dest', 'snap-1', { dryRun: true }))
+ .toMatchObject({ status: 'failed', reason: 'restore_recovery_pending', recovery: { damaged: true } });
+ await expect(resumeDatabaseRestore()).rejects.toMatchObject({ code: 'DATABASE_RESTORE_RECOVERY' });
+ expect(spawn).not.toHaveBeenCalled();
+ expect(readFileSync(RECOVERY_JOURNAL(), 'utf8')).toBe('{ not json');
+ });
});
// #8710: a restore must not leave peers skipping rows in either direction.
@@ -1393,11 +1536,8 @@ describe('restorePostgres', () => {
beforeEach(() => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
mockLegacyDumpRead();
- query.mockImplementation(async (sql) => (sql.includes('FROM pg_sequences') && !sql.includes('setval')
- ? { rows: [{ sequencename: 'memories_sync_feed_seq', last_value: '1000000000000500' }] }
- : { rows: [] }));
+ query.mockImplementation(restoreDbAnswer({ feed: [{ sequencename: 'memories_sync_feed_seq', last_value: '1000000000000500' }] }));
});
- afterEach(() => query.mockReset().mockResolvedValue({ rows: [] }));
const runRestore = async ({ exitCode = 0 } = {}) => {
const proc = fakeProc();
diff --git a/server/services/backupRestoreRecovery.js b/server/services/backupRestoreRecovery.js
new file mode 100644
index 0000000000..1325d978eb
--- /dev/null
+++ b/server/services/backupRestoreRecovery.js
@@ -0,0 +1,235 @@
+/**
+ * Committed-restore recovery for snapshot database restores (#9725).
+ *
+ * restorePostgres publishes a durable journal (server/lib/databaseRestoreRecovery.js)
+ * with the ORIGINAL feed positions before its destructive replay, and the replay
+ * writes a receipt row for that operation inside its own transaction. From then
+ * on ordinary database work stays fenced until this module finishes repair:
+ * forced schema upgrades, ordered migrations, feed-sequence flooring at the
+ * recorded positions and the inbound cursor rewind. A committed replay is never
+ * replayed again; an unknown outcome is resolved only from the receipt.
+ */
+import { databaseRestoreRecovery, ensureSchema, query, withDatabaseMaintenance } from '../lib/db.js';
+import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';
+import { restoreReceiptsDdl } from '../lib/db/schema/core.js';
+
+// Ties the replay's psql session to its operation, so recovery can prove no
+// session of that replay is still able to commit before reading "no receipt"
+// as a rollback.
+export const restoreApplicationName = (id) => `portos-restore-${id}`;
+
+// Appended after the dump inside the same --single-transaction replay. The
+// id/digest come from the validated journal (uuid / lowercase hex), never from
+// the snapshot. pg_dump empties search_path, so restore the application schema
+// first (ensureSchema creates the table there too).
+export const restoreReceiptSql = ({ id, dumpSha256 }) =>
+ `SET search_path = public;\n${restoreReceiptsDdl.join(';\n')};\nINSERT INTO restore_receipts (operation_id, dump_sha256) VALUES ('${id}', '${dumpSha256}');`;
+
+const SESSION_SETTLE_ATTEMPTS = 10;
+const SESSION_SETTLE_MS = 200;
+
+const MESSAGES = {
+ restore_commit_unknown: 'The restore could not confirm whether the database dump was committed. Ordinary database work stays paused and the dump will NOT be replayed; retry recovery from Settings > Backup once PostgreSQL is reachable.',
+ restore_schema_reconciliation: 'The database dump was applied, but schema recovery is incomplete. It was not rolled back and will not be replayed. Ordinary database work stays paused: retry recovery from Settings > Backup, or restart PortOS to retry automatically. If it keeps failing, check the server logs.',
+ restore_sync_resync: 'The database dump was applied, but peer sync could not be reset yet. It will not be replayed. Ordinary database work stays paused: retry recovery from Settings > Backup, or restart PortOS to retry automatically.',
+ restore_recovery_release: 'The database dump was applied and repaired, but the recovery journal could not be cleared. Ordinary database work stays paused: retry recovery from Settings > Backup.',
+ restore_recovery_pending: 'A previous database restore is awaiting recovery. Finish it from Settings > Backup before starting another restore.',
+ restore_recovery_damaged: 'The database restore recovery journal is unreadable, so the database stays fenced. Inspect data/database-restore-recovery.json and the server logs; never delete it unless you have confirmed how the restore ended.',
+};
+
+/** Bounded status projection — never feed positions, paths or digests. */
+function recoveryProjection(record) {
+ return { id: record.id, stage: record.stage, snapshotId: record.snapshotId, createdAt: record.createdAt };
+}
+
+export function pendingRecoveryResult(reason, record) {
+ return { status: 'failed', reason, error: MESSAGES[reason], recovery: recoveryProjection(record) };
+}
+
+/**
+ * Pending restore recovery, for the API/UI. A damaged journal still fences the
+ * database and is reported as such rather than as "nothing pending".
+ */
+export function getDatabaseRestoreRecoveryStatus() {
+ if (!databaseRestoreRecovery.isFenced()) return { pending: false };
+ let record;
+ try {
+ record = databaseRestoreRecovery.read();
+ } catch {
+ return { pending: true, damaged: true };
+ }
+ return record ? { pending: true, ...recoveryProjection(record) } : { pending: false };
+}
+
+/** A restore refusal while recovery is pending, or null when none is. */
+export function restoreRecoveryRefusal() {
+ const status = getDatabaseRestoreRecoveryStatus();
+ if (!status.pending) return null;
+ return {
+ status: 'failed',
+ reason: 'restore_recovery_pending',
+ error: status.damaged ? MESSAGES.restore_recovery_damaged : MESSAGES.restore_recovery_pending,
+ recovery: status.damaged ? { damaged: true } : recoveryProjection(status),
+ };
+}
+
+// Feed sequences present before the replay (a pre-#8315 install has none).
+// pg_sequences reports a NULL last_value for a never-drawn sequence, which
+// holds no position worth preserving.
+export async function captureSyncFeedPositions() {
+ const { rows } = await query(
+ `SELECT sequencename, last_value::text AS last_value FROM pg_sequences
+ WHERE schemaname = current_schema() AND sequencename = ANY($1::text[]) AND last_value IS NOT NULL`,
+ [syncFeedTables.map(syncFeedSequenceName)],
+ );
+ return rows.map(({ sequencename, last_value }) => ({ sequencename, last_value }));
+}
+
+/**
+ * Resolve a replay whose outcome the restoring process did not observe
+ * (non-zero/killed psql, lost response, crash) from its transactional receipt.
+ * 'committed' — this operation's receipt row exists
+ * 'rolled_back' — no session of the replay remains and no receipt exists
+ * 'uncertain' — a replay session is still live, or the database could not
+ * be inspected; nothing may reopen or replay
+ */
+async function inspectReplayOutcome(record) {
+ const inspect = async () => {
+ // A replay backend that is still running could yet commit: the receipt's
+ // absence proves a rollback only once no session of that replay remains.
+ let sessions = 1;
+ for (let attempt = 0; attempt < SESSION_SETTLE_ATTEMPTS && sessions > 0; attempt++) {
+ if (attempt) await new Promise(resolve => setTimeout(resolve, SESSION_SETTLE_MS));
+ const { rows } = await query(
+ `SELECT (SELECT count(*) FROM pg_stat_activity WHERE application_name = $1)::int AS sessions,
+ to_regclass('public.restore_receipts') IS NOT NULL AS has_receipts`,
+ [restoreApplicationName(record.id)],
+ );
+ sessions = rows[0]?.sessions ?? 1;
+ if (!sessions && !rows[0]?.has_receipts) return 'rolled_back';
+ }
+ if (sessions > 0) return 'uncertain';
+ const { rows } = await query('SELECT dump_sha256 FROM restore_receipts WHERE operation_id = $1', [record.id]);
+ if (!rows.length) return 'rolled_back';
+ // A receipt for this unique id with another digest is not ours to trust.
+ return rows[0].dump_sha256 === record.dumpSha256 ? 'committed' : 'uncertain';
+ };
+ return inspect().catch((err) => {
+ console.error(`❌ DB restore ${record.id}: replay outcome could not be inspected: ${err.message}`);
+ return 'uncertain';
+ });
+}
+
+/**
+ * Repair both directions of peer sync after a committed replay (#8710).
+ *
+ * Outbound: the dump `setval`s each feed sequence back to the dump's maximum,
+ * so new rows would reuse positions peers already passed and never be pulled.
+ * Floor every sequence at its ORIGINAL pre-restore value (from the journal,
+ * never re-captured) so post-restore positions land above any peer cursor.
+ *
+ * Inbound: our per-peer memory/Catalog cursors still point past rows the
+ * restore discarded. Rewind them so the next sync replays each peer's streams
+ * through the idempotent LWW / ON CONFLICT apply paths. Both steps are
+ * idempotent, so a retried recovery repeats them safely.
+ * @returns {Promise<number>} peers whose cursors were rewound
+ */
+async function resyncFederationAfterRestore(feedPositions) {
+ if (feedPositions.length) {
+ // GREATEST ignores the NULL of a sequence the dump left undrawn.
+ await query(
+ `SELECT setval(format('%I', s.sequencename)::regclass, GREATEST(c.captured::bigint, s.last_value))
+ FROM pg_sequences s
+ JOIN unnest($1::text[], $2::text[]) AS c(name, captured) ON c.name = s.sequencename
+ WHERE s.schemaname = current_schema()`,
+ [feedPositions.map((p) => p.sequencename), feedPositions.map((p) => p.last_value)],
+ );
+ }
+ const { rewindPostgresSyncCursors } = await import('./syncOrchestrator.js');
+ const peers = await rewindPostgresSyncCursors();
+ console.log(`🔄 DB restore: floored ${feedPositions.length} sync feed sequences, rewound memory/Catalog cursors for ${peers} peers`);
+ return peers;
+}
+
+/**
+ * Finish a COMMITTED replay. Must run inside the maintenance context that owns
+ * this operation. Releases admission only after every step succeeded.
+ * @returns {Promise<{status:'ok', syncCursorsRewound:number}|object>} ok, or a pending-recovery failure
+ */
+export async function repairCommittedRestore(record) {
+ // Reapply this version's upgrades even when readiness was cached before the
+ // restore, then honor the restored migration ledger.
+ const reconciliationError = await (async () => {
+ await ensureSchema({ force: true });
+ const { runDbMigrations } = await import('../scripts/run-db-migrations.js');
+ await runDbMigrations();
+ })().then(() => null, (err) => err);
+ if (reconciliationError) {
+ console.error(`❌ DB restore ${record.id}: schema reconciliation failed: ${reconciliationError.message}`);
+ return pendingRecoveryResult('restore_schema_reconciliation', record);
+ }
+ const resync = await resyncFederationAfterRestore(record.feedPositions).then(
+ (syncCursorsRewound) => ({ syncCursorsRewound }),
+ (err) => ({ err }),
+ );
+ if (resync.err) {
+ console.error(`❌ DB restore ${record.id}: federation resync failed: ${resync.err.message}`);
+ return pendingRecoveryResult('restore_sync_resync', record);
+ }
+ const releaseError = await Promise.resolve().then(() => databaseRestoreRecovery.release(record.id)).then(() => null, (err) => err);
+ if (releaseError) {
+ console.error(`❌ DB restore ${record.id}: recovery journal could not be cleared: ${releaseError.message}`);
+ return pendingRecoveryResult('restore_recovery_release', record);
+ }
+ console.log(`💾 DB restore ${record.id}: recovery complete, database admission reopened`);
+ return { status: 'ok', syncCursorsRewound: resync.syncCursorsRewound };
+}
+
+/**
+ * Settle an operation whose replay outcome was not observed as a commit.
+ * Inside the owning maintenance context. Returns 'rolled_back' after releasing
+ * admission, 'committed' (with the record now at `repairing`) after recording
+ * the commit, or 'uncertain'.
+ * @returns {Promise<{outcome: string, record: object}>}
+ */
+export async function settleReplayOutcome(record) {
+ const outcome = await inspectReplayOutcome(record);
+ if (outcome === 'rolled_back') {
+ databaseRestoreRecovery.release(record.id);
+ console.log(`💾 DB restore ${record.id}: replay rolled back; database admission reopened without changes`);
+ return { outcome, record };
+ }
+ if (outcome === 'committed') return { outcome, record: databaseRestoreRecovery.markCommitted(record.id) };
+ console.error(`❌ DB restore ${record.id}: replay outcome unknown; database stays fenced`);
+ return { outcome, record };
+}
+
+/**
+ * Resume the pending restore recovery: resolve an unknown replay outcome from
+ * its receipt, then repair a committed replay. Never resets or replays.
+ * { status: 'ok', outcome: 'repaired', syncCursorsRewound }
+ * { status: 'ok', outcome: 'rolled_back' } (proven rollback, nothing changed)
+ * { status: 'ok', outcome: 'none' } (nothing pending)
+ * { status: 'failed', reason, error, recovery } (still pending)
+ * @param {string} [id] - operation to resume; omitted = whichever is pending
+ */
+export async function resumeDatabaseRestore(id) {
+ const record = databaseRestoreRecovery.read();
+ if (!record) return { status: 'ok', outcome: 'none' };
+ if (id && record.id !== id) {
+ throw Object.assign(new Error('A different database restore operation is pending.'), { status: 409, code: 'RESTORE_RECOVERY_MISMATCH' });
+ }
+ return withDatabaseMaintenance(async () => {
+ // Re-read inside maintenance: another resume may have finished meanwhile.
+ let current = databaseRestoreRecovery.read();
+ if (current?.id !== record.id) return { status: 'ok', outcome: 'none' };
+ if (current.stage === 'replaying') {
+ const settled = await settleReplayOutcome(current);
+ if (settled.outcome === 'rolled_back') return { status: 'ok', outcome: 'rolled_back' };
+ if (settled.outcome === 'uncertain') return pendingRecoveryResult('restore_commit_unknown', current);
+ current = settled.record;
+ }
+ const repaired = await repairCommittedRestore(current);
+ return repaired.status === 'ok' ? { ...repaired, outcome: 'repaired' } : repaired;
+ }, { restoreRecoveryId: record.id });
+}
diff --git a/server/services/databaseBootFence.js b/server/services/databaseBootFence.js
index d3d35702f8..093ffcefaf 100644
--- a/server/services/databaseBootFence.js
+++ b/server/services/databaseBootFence.js
@@ -2,9 +2,12 @@
// A pending or damaged journal must not allow boot-time writers/schedulers,
// and a process whose pool still names the backend a completed cutover
// retired (a cached PM2 environment, a stale shell PGPORT) must not boot.
+// A committed snapshot restore awaiting repair (#9725) fences boot the same
+// way; server/start.js resumes that repair before reaching this fence.
import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';
import { assertDatabasePoolAuthority } from '../lib/databaseAuthority.js';
-import { POOL_CONFIG } from '../lib/db.js';
+import { POOL_CONFIG, databaseRestoreRecovery } from '../lib/db.js';
assertDatabaseAdmission();
assertDatabasePoolAuthority(POOL_CONFIG);
+databaseRestoreRecovery.assertAdmission();
diff --git a/server/start.js b/server/start.js
index 646f191e09..c244464129 100644
--- a/server/start.js
+++ b/server/start.js
@@ -17,6 +17,21 @@ if (args.length === 0) {
process.exit(1);
}
}
+ // A committed snapshot database restore awaiting repair (#9725). Finish it
+ // before any writer, scheduler or route can load: resolve an unknown replay
+ // outcome from its receipt, then repair. It never replays the dump. Anything
+ // short of a completed recovery (including an unreadable journal) refuses
+ // boot with the fence still closed; a restart alone is never success.
+ const { createDatabaseRestoreRecovery } = await import('./lib/databaseRestoreRecovery.js');
+ if (createDatabaseRestoreRecovery().isFenced()) {
+ const { resumeDatabaseRestore } = await import('./services/backupRestoreRecovery.js');
+ const result = await resumeDatabaseRestore().catch(err => ({ status: 'failed', reason: err.code || 'restore_recovery_error', error: err.message }));
+ if (result.status !== 'ok') {
+ console.error(`❌ Database restore recovery is still pending (${result.reason}); boot refused. ${result.error || ''}`.trim());
+ process.exit(1);
+ }
+ console.log(`💾 Database restore recovery finished at boot (${result.outcome})`);
+ }
await import('./services/databaseBootFence.js');
await import('./index.js');
} else if (args.length === 2 && args[0] === '--verify-database') {