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

test: cover snapshot cut acquisition and release failures (#9980)

[._.]/ Adam Eivyc5261afa5edd
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 3428dd0130..c2f20b7ba9 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -13,6 +13,9 @@ new take publications waiting through the SQL dump and manifest write. Browser
code takes, SuperCollider takes, chiptune renders, and painted-waveform renders
stage encoding outside that boundary, then publish their final audio bytes and
track row together inside it. Manual and scheduled backups use the same cut.
+If an admitted take does not drain within two minutes, or the cut cannot be
+released, the snapshot is marked failed (never published or used for retention
+pruning) and take publication reopens.
This is the first slice of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923). Media-job completion, other durable asset
replacement/deletion paths, and database maintenance are tracked as separate
diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.js
index 92cf665e23..2b654a7b08 100644
--- a/server/lib/backupSnapshotBoundary.js
+++ b/server/lib/backupSnapshotBoundary.js
@@ -47,6 +47,8 @@ export async function withBackupAssetPublication(work) {
* admission and rejects, so runBackup marks its incomplete snapshot failed.
*/
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');
cutRequested = true;
if (admitted > 0) {
diff --git a/server/lib/backupSnapshotBoundary.test.js b/server/lib/backupSnapshotBoundary.test.js
index 2f739705dc..a2469bdabf 100644
--- a/server/lib/backupSnapshotBoundary.test.js
+++ b/server/lib/backupSnapshotBoundary.test.js
@@ -36,6 +36,27 @@ describe('backup snapshot publication admission', () => {
expect(secondStarted).toBe(true);
});
+ it('lets only the current owner reopen admission and refuses a competing or nested cut', async () => {
+ const releaseFirst = await acquireBackupSnapshotCut();
+ await expect(acquireBackupSnapshotCut()).rejects.toThrow('already owned');
+ releaseFirst();
+ releaseFirst();
+
+ const releaseSecond = await acquireBackupSnapshotCut();
+ releaseFirst(); // a stale release from the earlier cut must not open this one
+ let admitted = false;
+ const waiting = withBackupAssetPublication(() => { admitted = true; });
+ await new Promise(resolve => setImmediate(resolve));
+ expect(admitted).toBe(false);
+ releaseSecond();
+ await waiting;
+ expect(admitted).toBe(true);
+
+ await withBackupAssetPublication(async () => {
+ await expect(acquireBackupSnapshotCut()).rejects.toThrow('inside an asset publication');
+ });
+ });
+
it('reopens admission when an admitted workflow cannot drain', async () => {
vi.useFakeTimers();
const rowWrite = deferred();
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 2f69054137..a53425d3aa 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -65,6 +65,18 @@ vi.mock('../lib/db.js', async () => ({
vi.mock('../scripts/run-db-migrations.js', () => ({
runDbMigrations: vi.fn().mockResolvedValue(0),
}));
+// Passthrough seam: the snapshot-cut failure tests wrap acquisition to shorten the
+// drain timeout or fail release. Left unset, runBackup uses the real boundary.
+const snapshotCutSeam = vi.hoisted(() => ({ wrap: null }));
+vi.mock('../lib/backupSnapshotBoundary.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ acquireBackupSnapshotCut: (...args) => snapshotCutSeam.wrap
+ ? snapshotCutSeam.wrap(actual.acquireBackupSnapshotCut, ...args)
+ : actual.acquireBackupSnapshotCut(...args),
+ };
+});
import { ensureSchema, query, withDatabaseMaintenance } from '../lib/db.js';
vi.mock('./backupDatabaseReset.js', () => ({
getDatabaseResetPlan: async () => ({ preflight: 'SELECT 1', reset: 'RESET_APPROVED_SCHEMA' }),
@@ -3296,6 +3308,72 @@ describe('runBackup lifecycle', () => {
expect(published).toBe(true);
});
+ describe('snapshot cut failures', () => {
+ const OLD_IDS = ['2020-01-01T00-00-00', '2020-01-02T00-00-00'];
+
+ // Two completed snapshots with retentionCount 1: a run that wrongly reached
+ // retention pruning would delete the older one.
+ async function seedCompletedSnapshots() {
+ const fsp = await actualFs();
+ for (const id of OLD_IDS) {
+ const dir = joinPath(destRoot, 'snapshots', machineHost, id);
+ await fsp.mkdir(joinPath(dir, 'data'), { recursive: true });
+ await fsp.writeFile(joinPath(dir, 'manifest.json'), JSON.stringify({ generatedAt: `${id.slice(0, 10)}T00:00:00.000Z`, fileCount: 0 }));
+ }
+ }
+
+ async function expectFailedSnapshotWithoutPruning() {
+ const { listSnapshots, getState } = await import('./backup.js');
+ const snapshots = await listSnapshots(destRoot);
+ expect(snapshots.map(snapshot => snapshot.id)).toEqual(expect.arrayContaining(OLD_IDS));
+ expect(snapshots).toHaveLength(OLD_IDS.length + 1);
+ const [failed, ...rest] = [...snapshots].sort((a, b) => Number(Boolean(b.failed)) - Number(Boolean(a.failed)));
+ expect(failed).toMatchObject({ failed: true, incomplete: false });
+ expect(rest.every(snapshot => !snapshot.failed && !snapshot.incomplete)).toBe(true);
+ expect((await getState()).status).toBe('error');
+ expect(isBackupInProgress()).toBe(false);
+ }
+
+ afterEach(() => { snapshotCutSeam.wrap = null; });
+
+ 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');
+ await seedCompletedSnapshots();
+ let finishTake;
+ const stuckTake = withBackupAssetPublication(() => new Promise(resolve => { finishTake = resolve; }));
+ snapshotCutSeam.wrap = (acquire) => acquire({ timeoutMs: 20 });
+
+ await expect(runBackup(destRoot, null, { retentionCount: 1 }))
+ .rejects.toThrow('Timed out draining asset publications');
+
+ expect(spawn).not.toHaveBeenCalled();
+ await expectFailedSnapshotWithoutPruning();
+ await expect(withBackupAssetPublication(() => 'admitted')).resolves.toBe('admitted');
+ finishTake();
+ await stuckTake;
+ });
+
+ it('fails the snapshot without pruning when the cut cannot be released', async () => {
+ await seedCompletedSnapshots();
+ snapshotCutSeam.wrap = async (acquire, ...args) => {
+ const release = await acquire(...args);
+ return () => {
+ release();
+ throw new Error('cut release failed');
+ };
+ };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+
+ const pending = runBackup(destRoot, null, { retentionCount: 1 }).catch(error => error);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ proc.emit('close', 0);
+
+ expect(await pending).toMatchObject({ message: 'cut release failed' });
+ await expectFailedSnapshotWithoutPruning();
+ });
+ });
+
it.each([
['data readdir', 'EIO'],
['data readdir', 'EACCES'],
diff --git a/server/services/musicTakePublication.js b/server/services/musicTakePublication.js
index ba23264b0c..69ab612ccc 100644
--- a/server/services/musicTakePublication.js
+++ b/server/services/musicTakePublication.js
@@ -17,9 +17,8 @@ export async function publishMusicTake({ trackId, wav, take, patch = {} }) {
return await withBackupAssetPublication(async () => {
await ensureDir(PATHS.music);
await copyFile(join(stageDir, filename), join(PATHS.music, filename), constants.COPYFILE_EXCL);
- const track = Object.keys(patch).length
- ? await tracks.appendActiveTake(trackId, { ...take, audioFilename: filename }, patch)
- : await tracks.appendActiveTake(trackId, { ...take, audioFilename: filename });
+ const published = { ...take, audioFilename: filename };
+ const track = await tracks.appendActiveTake(trackId, published, ...(Object.keys(patch).length ? [patch] : []));
return { track, filename };
});
} finally {