Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: coordinate database maintenance with backup publication admission (#9983)
Adam Eivy65d1645bf122
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsxindex bb4c9025b6..382303d6b0 100644--- a/client/src/components/settings/BackupTab.jsx+++ b/client/src/components/settings/BackupTab.jsx@@ -40,6 +40,7 @@ const DB_RESTORE_FAILURE_MESSAGES = {dump_incomplete: 'The snapshot database dump is incomplete (truncated or damaged). Nothing was changed; choose another snapshot.',restore_preflight: 'Database restore was refused because the database contains unexpected objects, ownership, or dependencies. Nothing was changed. Check the server logs and resolve the reported database conflict before trying again.',restore_journal: 'The restore recovery journal could not be written. Nothing was changed. Check the server logs and available disk space before trying again.',+ backup_snapshot_busy: 'A backup is capturing the database, or an asset publication did not finish in time. Nothing was changed. Retry once the backup completes.',no_dump: 'No DB dump in this snapshot',not_configured: 'The database is unavailable for restore. Check Database status and the server logs for connection details.',restore_error: 'Database restore failed. Check Backup status, any recovery warning, and the server logs for details.',diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex f8a4a27cf0..d5d60341e2 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -30,6 +30,26 @@ renderer is not stopped and cancellation is unchanged. A terminal write thatfails inside the admission is retried inside it and releases it when it givesup.+Database maintenance shares the same boundary and never terminates a render or+stops PM2 to obtain it:++- **A database restore (execution only; preview takes no cut)** acquires the cut before+ it publishes its recovery journal. Admitted file-plus-row publications drain+ completely first, so the replay never lands under a half-published pair. If a+ backup owns the cut, or a publication does not drain within two minutes, the+ restore returns `backup_snapshot_busy` without changing anything.+- **Accepting a backend cutover** takes the cut around publishing the maintenance+ fence (it waits up to 30 seconds to drain, and refuses with+ `DATABASE_PREFLIGHT_BUSY` while a backup owns it). Once the fence exists, new+ publications are refused before either store changes (`DATABASE_MAINTENANCE`),+ and a backup refuses to start or to take its cut — a backup that already+ reserved a snapshot marks it failed and preserves older recovery points.+ Cancelling the operation reopens publication; nothing stays held.+- Every release is owner-scoped: a failed or cancelled operation releases only the+ cut it acquired and leaves the maintenance journal and restore-recovery+ incomplete guards exactly as they were. The boundary is process-local; the+ detached cutover worker runs only after the server stops.+Admission inventory (`withBackupAssetPublication`):| Owner | Status |@@ -41,7 +61,7 @@ Admission inventory (`withBackupAssetPublication`):| Recovery commit of a completion whose terminal write failed (the next queue write acknowledges it outside any admission) | Outstanding || Other `mediaJobEvents` `completed` subscribers that write rows (universe-builder collection hook, LoRA dataset, character sheet, sprite animation, Creative Director scene runner/plan advance/seed settle, music-video production) | Outstanding || Durable replacement/deletion owners | Outstanding (#9982) |-| Database maintenance | Outstanding (#9983) |+| Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |This is part of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923).Until every owner is covered, `status: ok` reports that the file@@ -225,6 +245,7 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER| `{ 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_compatibility', error }` | Target PostgreSQL major cannot be established — repair the version check and retry preview before execution || `{ status: 'failed', reason: 'restore_journal', error }` | The recovery journal could not be written — refused before any reset |+| `{ status: 'failed', reason: 'backup_snapshot_busy', error }` | A backup cut is active, or admitted asset publications did not drain — refused before the recovery journal or any reset; retry later || `{ 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 |diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.jsindex ab76bcaf8f..96e6139988 100644--- a/server/lib/backupSnapshotBoundary.js+++ b/server/lib/backupSnapshotBoundary.js@@ -3,8 +3,14 @@* Callers hold one mutation lease across BOTH stores, not around individual* filesystem or SQL operations. The backup closes admission before rsync and* keeps it closed through the database dump and manifest write.+ *+ * Database maintenance shares the boundary. A maintenance fence refuses a NEW+ * publication or cut before either store changes, and maintenance that must not+ * observe or replace a half-published pair takes the same cut around its own+ * destructive step. Every refusal that is retryable carries BACKUP_SNAPSHOT_BUSY.*/import { AsyncLocalStorage } from 'node:async_hooks';+import { assertDatabaseAdmission } from './databaseMaintenanceJournal.js';const publicationScope = new AsyncLocalStorage();const DEFAULT_DRAIN_TIMEOUT_MS = 120_000;@@ -14,6 +20,8 @@ let cutActive = false;let drainWaiters = [];let publicationWaiters = [];+const busyError = message => Object.assign(new Error(message), { status: 503, code: 'BACKUP_SNAPSHOT_BUSY' });+function releasePublications() {const waiters = publicationWaiters;publicationWaiters = [];@@ -24,10 +32,14 @@ function releasePublications() {export async function withBackupAssetPublication(work) {const scope = publicationScope.getStore();if (scope?.active) return work();+ // A maintenance fence would fail the row write after the file was published.+ // Refuse before either store changes, and again once a cut has been waited out.+ assertDatabaseAdmission();// Work spawned by a still-admitted lease joins it: the cut already waits for that lease.const joinsAdmitted = scope?.spawnedBy?.active === true;while (!joinsAdmitted && (cutRequested || cutActive)) {await new Promise(resolve => publicationWaiters.push(resolve));+ assertDatabaseAdmission();}admitted += 1;const lease = { active: true };@@ -44,6 +56,27 @@ export async function withBackupAssetPublication(work) {}}+/** Wait for already admitted workflows to settle, or reject when they do not. */+async function awaitDrain(timeoutMs) {+ let timer;+ let onDrained;+ try {+ await Promise.race([+ new Promise(resolve => {+ onDrained = resolve;+ drainWaiters.push(resolve);+ }),+ new Promise((_, reject) => {+ timer = setTimeout(() => reject(busyError('Timed out draining asset publications for backup')), timeoutMs);+ timer.unref?.();+ }),+ ]);+ } finally {+ clearTimeout(timer);+ drainWaiters = drainWaiters.filter(resolve => resolve !== onDrained);+ }+}+/*** Run a synchronous fan-out (an event emit) so each listener acquires its OWN* lease while the caller's lease is still held, even if a cut is already@@ -58,37 +91,25 @@ export function runOutsideBackupAssetPublication(work) {}/**- * Close admission and drain already admitted workflows before copying files.- * The returned release function owns only this cut. A timed-out drain reopens- * admission and rejects, so runBackup marks its incomplete snapshot failed.+ * Close admission and drain already admitted workflows before the caller reads+ * or replaces both stores. The returned release function owns only this cut. A+ * failed drain (timeout, or a maintenance fence that closed meanwhile) reopens+ * admission and rejects: runBackup then marks its incomplete snapshot failed,+ * and maintenance acceptance refuses before publishing its fence.*/export async function acquireBackupSnapshotCut({ timeoutMs = DEFAULT_DRAIN_TIMEOUT_MS } = {}) {// A cut requested from inside an admitted workflow would wait on itself for the whole timeout.if (publicationScope.getStore()?.active) throw new Error('Backup snapshot cut cannot be acquired inside an asset publication');- if (cutRequested || cutActive) throw new Error('Backup snapshot cut already owned');+ if (cutRequested || cutActive) throw busyError('Backup snapshot cut already owned');+ assertDatabaseAdmission();cutRequested = true;- if (admitted > 0) {- let timer;- let onDrained;- try {- await Promise.race([- new Promise(resolve => {- onDrained = resolve;- drainWaiters.push(resolve);- }),- new Promise((_, reject) => {- timer = setTimeout(() => reject(new Error('Timed out draining asset publications for backup')), timeoutMs);- timer.unref?.();- }),- ]);- } catch (error) {- cutRequested = false;- releasePublications();- throw error;- } finally {- clearTimeout(timer);- drainWaiters = drainWaiters.filter(resolve => resolve !== onDrained);- }+ try {+ if (admitted > 0) await awaitDrain(timeoutMs);+ assertDatabaseAdmission();+ } catch (error) {+ cutRequested = false;+ releasePublications();+ throw error;}cutActive = true;cutRequested = false;diff --git a/server/lib/backupSnapshotBoundary.maintenance.test.js b/server/lib/backupSnapshotBoundary.maintenance.test.jsnew file mode 100644index 0000000000..e4a202076a--- /dev/null+++ b/server/lib/backupSnapshotBoundary.maintenance.test.js@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest';++// The real journal reads the install's data root; a seam stands in for its fence.+const fence = vi.hoisted(() => ({ fenced: false }));+vi.mock('./databaseMaintenanceJournal.js', () => ({+ assertDatabaseAdmission: () => {+ if (fence.fenced) throw Object.assign(new Error('Persistent database maintenance is active'), { status: 503, code: 'DATABASE_MAINTENANCE' });+ },+}));++import { acquireBackupSnapshotCut, withBackupAssetPublication } from './backupSnapshotBoundary.js';++const settle = () => new Promise(resolve => setTimeout(resolve, 10));++describe('backup snapshot boundary under database maintenance', () => {+ it('refuses a new publication before either store changes while maintenance is fenced', async () => {+ fence.fenced = true;+ const work = vi.fn();+ try {+ await expect(withBackupAssetPublication(work)).rejects.toMatchObject({ code: 'DATABASE_MAINTENANCE' });+ } finally {+ fence.fenced = false;+ }+ expect(work).not.toHaveBeenCalled();+ await expect(withBackupAssetPublication(() => 'admitted')).resolves.toBe('admitted');+ });++ it('refuses a publication that waited out a cut when maintenance fenced meanwhile', async () => {+ const release = await acquireBackupSnapshotCut();+ const work = vi.fn();+ const waiting = withBackupAssetPublication(work).catch(error => error);+ await settle();+ fence.fenced = true;+ try {+ release();+ expect(await waiting).toMatchObject({ code: 'DATABASE_MAINTENANCE' });+ } finally {+ fence.fenced = false;+ }+ expect(work).not.toHaveBeenCalled();+ });++ it('lets an admitted workflow finish, then refuses the cut and reopens admission when maintenance fenced while draining', async () => {+ let finishRow;+ let completed = false;+ const admitted = withBackupAssetPublication(() => new Promise(resolve => { finishRow = resolve; })).then(() => { completed = true; });+ const cut = acquireBackupSnapshotCut().catch(error => error);+ await settle();+ fence.fenced = true;+ finishRow();+ await admitted;+ try {+ expect(await cut).toMatchObject({ code: 'DATABASE_MAINTENANCE' });+ } finally {+ fence.fenced = false;+ }+ expect(completed).toBe(true);+ // The refused cut owned nothing: a later one is available and publication is open.+ const release = await acquireBackupSnapshotCut();+ release();+ await expect(withBackupAssetPublication(() => 'admitted')).resolves.toBe('admitted');+ });++ it('marks a competing cut and a drain timeout retryable without disturbing the owner', async () => {+ const release = await acquireBackupSnapshotCut();+ await expect(acquireBackupSnapshotCut()).rejects.toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY', status: 503 });+ release();++ let finishRow;+ const stuck = withBackupAssetPublication(() => new Promise(resolve => { finishRow = resolve; }));+ await expect(acquireBackupSnapshotCut({ timeoutMs: 10 })).rejects.toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY' });+ finishRow();+ await stuck;+ });+});diff --git a/server/routes/databasePreflight.test.js b/server/routes/databasePreflight.test.jsindex 9785770f68..0440eacbcb 100644--- a/server/routes/databasePreflight.test.js+++ b/server/routes/databasePreflight.test.js@@ -34,6 +34,7 @@ import { PATHS } from '../lib/paths.js';import { POOL_CONFIG, query } from '../lib/db.js';import { execFile, spawn } from '../lib/childProcess.js';import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { acquireBackupSnapshotCut, withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';import { getSystemActivity } from '../services/activeProcessing.js';import { countActiveCosAgents, getPersistentMindImageWorkGuard } from '../services/updatePreflight.js';@@ -247,6 +248,44 @@ describe('database cutover acceptance HTTP contract', () => {expect(spawnDatabaseMaintenanceWorker).not.toHaveBeenCalled();});+ it('publishes the fence only after an admitted file-plus-row publication drains, then refuses new ones', async () => {+ const journal = createDatabaseMaintenanceJournal(PATHS.data);+ let finishRow;+ const halfPublished = withBackupAssetPublication(() => new Promise(resolve => { finishRow = resolve; }));+ const accepting = accept().then(result => result);+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(journal.read()).toBeNull();++ finishRow();+ await halfPublished;+ expect((await accepting).status).toBe(202);+ expect(journal.read()).toMatchObject({ stage: 'accepted' });+ const work = vi.fn();+ await expect(withBackupAssetPublication(work)).rejects.toMatchObject({ code: 'DATABASE_MAINTENANCE' });+ expect(work).not.toHaveBeenCalled();+ });++ it('refuses without a fence while a backup owns the snapshot cut, and accepts once it is released', async () => {+ const journal = createDatabaseMaintenanceJournal(PATHS.data);+ const releaseBackupCut = await acquireBackupSnapshotCut();+ try {+ const refused = await accept();+ expect(refused.status).toBe(409);+ expect(refused.body.code).toBe('DATABASE_PREFLIGHT_BUSY');+ expect(journal.read()).toBeNull();+ expect(spawnDatabaseMaintenanceWorker).not.toHaveBeenCalled();+ } finally {+ releaseBackupCut();+ }+ expect((await accept()).status).toBe(202);+ });++ it('releases its own cut when acceptance is cancelled, so a backup can still take one', async () => {+ raceFinalCheck(busy);+ expect((await accept()).body.code).toBe('DATABASE_PREFLIGHT_BUSY');+ (await acquireBackupSnapshotCut())();+ });+it('keeps the fence when the saved source changed during acceptance', async () => {raceFinalCheck(() => { saveMode('docker'); return idle(); });const result = await accept();diff --git a/server/services/backup.js b/server/services/backup.jsindex 9ecf1db19a..09f1bff20e 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -17,6 +17,7 @@ import { basename, join, resolve, relative, isAbsolute } from 'path';import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256File } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { acquireBackupSnapshotCut } from '../lib/backupSnapshotBoundary.js';+import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';import { createLineReader } from '../lib/streamLines.js';import { getEvent } from './eventScheduler.js';import { POOL_CONFIG, checkHealth, databaseRestoreRecovery, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';@@ -577,6 +578,9 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl};try {+ // Refuse before reserving a snapshot while database maintenance is fenced;+ // the cut below repeats this check after it drains.+ assertDatabaseAdmission();await access(destPath).catch((cause) => {// Never expose the filesystem message: it can include private paths.const code = ['ENOENT', 'EACCES', 'EPERM', 'EIO'].includes(cause.code) ? cause.code : 'UNKNOWN';@@ -1566,7 +1570,7 @@ 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_compatibility'|'restore_preflight'|'restore_journal'|'restore_error'|'timeout', error? }+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'dump_unreadable'|'dump_incomplete'|'restore_compatibility'|'restore_preflight'|'restore_journal'|'backup_snapshot_busy'|'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@@ -1685,6 +1689,29 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI}if (dryRun) return { status: 'ok', dryRun: true, sizeBytes, tableCount };+ // The replay replaces every row. Take the backup boundary first so no admitted+ // file-plus-row publication is half done underneath it and no backup cut is+ // capturing the database mid-replay. Only this restore's own cut is released.+ let releaseSnapshotCut;+ try {+ releaseSnapshotCut = await acquireBackupSnapshotCut();+ } catch (err) {+ if (err.code !== 'BACKUP_SNAPSHOT_BUSY') throw err;+ console.warn(`⚠️ restore: refused for snapshot ${snapshotId}: ${err.message}`);+ return {+ status: 'failed',+ reason: 'backup_snapshot_busy',+ error: 'A backup is capturing the database or an asset publication did not finish draining. Restore was refused without changing data; retry when it finishes.',+ };+ }+ try {+ return await replayAdmittedDump({ tableCount, sizeBytes, snapshotId, dump, reset, replayPath });+ } finally {+ releaseSnapshotCut();+ }+}++async function replayAdmittedDump({ tableCount, sizeBytes, snapshotId, dump, reset, replayPath }) {return withDatabaseMaintenance(async ({ adoptRestoreRecovery }) => {// Read before the replay rewinds them, then make them durable together// with this operation's identity BEFORE anything destructive runs: adiff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex c07a1ec64f..5affa571b0 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -62,6 +62,14 @@ vi.mock('../lib/db.js', async () => ({getServerMajorVersion: vi.fn(() => null),}));+// The real journal reads the install's data root, never this suite's temp tree.+const maintenanceFence = vi.hoisted(() => ({ fenced: false }));+vi.mock('../lib/databaseMaintenanceJournal.js', () => ({+ assertDatabaseAdmission: () => {+ if (maintenanceFence.fenced) throw Object.assign(new Error('Persistent database maintenance is active'), { status: 503, code: 'DATABASE_MAINTENANCE' });+ },+}));+vi.mock('../scripts/run-db-migrations.js', () => ({runDbMigrations: vi.fn().mockResolvedValue(0),}));@@ -181,6 +189,7 @@ function fakeProc() {// The restore/dump helpers await filesystem and health checks before calling// spawn() and attaching child-process listeners. Wait for the mocked spawn// call itself so CI scheduling cannot emit into an uninitialized fake process.+const settle = () => new Promise(resolve => setTimeout(resolve, 25));const flush = () => vi.waitFor(() => expect(spawn).toHaveBeenCalled());const overridable = DEFAULT_EXCLUDES.filter(e => e.overridable).map(e => e.path);@@ -1331,6 +1340,52 @@ describe('restorePostgres', () => {expect(spawn).not.toHaveBeenCalled();});+ it('refuses a real restore while a backup cut is active and releases only its own admission', async () => {+ const { acquireBackupSnapshotCut, withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });+ mockLegacyDumpRead();+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ const releaseBackupCut = await acquireBackupSnapshotCut();+ try {+ expect(await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false }))+ .toMatchObject({ status: 'failed', reason: 'backup_snapshot_busy' });+ expect(withDatabaseMaintenance).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(readRecoveryJournal()).toBeNull();+ // The refused restore never owned the cut: the backup's remains closed.+ let admitted = false;+ const waiting = withBackupAssetPublication(() => { admitted = true; });+ await settle();+ expect(admitted).toBe(false);+ releaseBackupCut();+ await waiting;+ } finally {+ releaseBackupCut();+ }+ });++ it('starts a real restore only after an admitted file-plus-row publication drains, then reopens publication', async () => {+ const { withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });+ mockLegacyDumpRead();+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ let finishRow;+ const halfPublished = withBackupAssetPublication(() => new Promise(resolve => { finishRow = resolve; }));+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const restore = restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });+ await settle();+ expect(withDatabaseMaintenance).not.toHaveBeenCalled();++ finishRow();+ await halfPublished;+ await flush();+ expect(withDatabaseMaintenance).toHaveBeenCalledTimes(1);+ proc.emit('close', 0);+ expect(await restore).toMatchObject({ status: 'ok', dryRun: false });+ await expect(withBackupAssetPublication(() => 'admitted')).resolves.toBe('admitted');+ });+it('treats a 0-byte dump as no_dump (does not restore a truncated snapshot)', async () => {vi.spyOn(fs, 'stat').mockResolvedValue({ size: 0, isFile: () => true });const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });@@ -3372,7 +3427,7 @@ describe('runBackup lifecycle', () => {expect(isBackupInProgress()).toBe(false);}- afterEach(() => { snapshotCutSeam.wrap = null; });+ afterEach(() => { snapshotCutSeam.wrap = null; maintenanceFence.fenced = false; });it('fails the snapshot without copying, publishing or pruning when admitted takes cannot drain, then reopens admission', async () => {const { withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');@@ -3391,6 +3446,40 @@ describe('runBackup lifecycle', () => {await stuckTake;});+ it('refuses to start while database maintenance is fenced, without reserving a snapshot or pruning', async () => {+ await seedCompletedSnapshots();+ maintenanceFence.fenced = true;+ try {+ await expect(runBackup(destRoot, null, { retentionCount: 1 })).rejects.toMatchObject({ code: 'DATABASE_MAINTENANCE' });+ } finally {+ maintenanceFence.fenced = false;+ }+ expect(spawn).not.toHaveBeenCalled();+ const { listSnapshots, getState } = await import('./backup.js');+ expect((await listSnapshots(destRoot)).map(snapshot => snapshot.id).sort()).toEqual(OLD_IDS);+ expect((await getState()).status).toBe('error');+ expect(isBackupInProgress()).toBe(false);+ });++ it('closes the cut when maintenance fences while admitted takes drain, leaving the admitted take intact', async () => {+ const { withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');+ await seedCompletedSnapshots();+ let finishTake;+ let takeCompleted = false;+ const admittedTake = withBackupAssetPublication(() => new Promise(resolve => { finishTake = resolve; })).then(() => { takeCompleted = true; });+ const pending = runBackup(destRoot, null, { retentionCount: 1 }).catch(error => error);+ await new Promise(resolve => setTimeout(resolve, 25));+ maintenanceFence.fenced = true;+ finishTake();+ await admittedTake;+ expect(await pending).toMatchObject({ code: 'DATABASE_MAINTENANCE' });+ maintenanceFence.fenced = false;+ expect(takeCompleted).toBe(true);+ expect(spawn).not.toHaveBeenCalled();+ await expectFailedSnapshotWithoutPruning();+ await expect(withBackupAssetPublication(() => 'admitted')).resolves.toBe('admitted');+ });+it('fails the snapshot without pruning when the cut cannot be released', async () => {await seedCompletedSnapshots();snapshotCutSeam.wrap = async (acquire, ...args) => {diff --git a/server/services/databasePreflight.js b/server/services/databasePreflight.jsindex 07346c8cd0..cf9606115f 100644--- a/server/services/databasePreflight.js+++ b/server/services/databasePreflight.js@@ -5,6 +5,7 @@ import { join } from 'node:path';import { z } from 'zod';import { PATHS } from '../lib/paths.js';import { POOL_CONFIG } from '../lib/db.js';+import { acquireBackupSnapshotCut } from '../lib/backupSnapshotBoundary.js';import { assertDatabaseAdmission, createDatabaseMaintenanceJournal, databaseMaintenanceEndpointSchema } from '../lib/databaseMaintenanceJournal.js';import { databaseMaintenancePreflightSchema } from '../lib/validation.js';import { ServerError } from '../lib/errorHandler.js';@@ -15,6 +16,7 @@ const refuse = (code, message) => new ServerError(message, { status: 409, code }const unavailable = () => refuse('DATABASE_PREFLIGHT_UNTRUSTED', 'Database configuration or work state could not be verified.');const stale = () => refuse('DATABASE_PREFLIGHT_STALE', 'Requested direction does not match the current database configuration and running pool.');const busy = () => refuse('DATABASE_PREFLIGHT_BUSY', 'PortOS has active or queued work. Wait for it to finish before database maintenance.');+const ACCEPT_DRAIN_TIMEOUT_MS = 30_000;const count = z.number().int().nonnegative();// The dashboard summarizer intentionally accepts partial snapshots. Maintenance// cannot use a missing slice as proof that there are no writers in that domain.@@ -108,11 +110,20 @@ export async function acceptDatabaseMaintenance(input) {const configuration = readConfiguration();validateDirection(direction, configuration);const journal = createDatabaseMaintenanceJournal();+ // Publish the fence only at a whole-workflow boundary: admitted file-plus-row+ // publications finish first, and a backup that owns the cut is never fenced+ // out mid-snapshot. After the fence exists, new publications refuse on their+ // own, so the cut is released as soon as begin() returns or fails.+ const releaseSnapshotCut = await acquireBackupSnapshotCut({ timeoutMs: ACCEPT_DRAIN_TIMEOUT_MS }).catch(err => {+ throw err.code === 'BACKUP_SNAPSHOT_BUSY' ? busy() : err;+ });let operation;try {operation = journal.begin({ source: configuration.source, target: configuration.target });} catch {throw refuse('DATABASE_MAINTENANCE', 'Another database maintenance operation is active or requires recovery.');+ } finally {+ releaseSnapshotCut();}try {await assertTrustedIdle();