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(backup): keep time capsule snapshots and index together

[._.]/ Adam Eivy08d1fcd337d8
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 5dde93123d..06fe7df655 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -104,6 +104,7 @@ Admission inventory (`withBackupAssetPublication`):
| Image generation completion, upscale/clean tails, variants and sketch pairs (`imageGen/*.js`, `mediaSketches.js`) | Covered (#9982 partial): provider output publication through sidecar and cleanup takes one lease; remote replacement and variant/sketch rewrites restore previous files on failure |
| Pipeline audio mux (music, voice, generated cues, silent strip), including Creative Director stitch/final assembly | Covered (#9982 partial): encoding runs outside admission; replacement of the already-recorded video and rollback hold the lease. CD final/rough-cut rows only reference the existing history entry |
| Music Video Making-of export (`makingOf.js`, `makingOfVisuals.js`) | Reference-only: reads existing assets and transforms buffers for the ZIP response; no durable file or row writes |
+| Time Capsule snapshots (`timeCapsule.js`) | Covered (#9982 partial): snapshot creation and deletion lease the file and index entry together, acquiring before the shared index write tail |
| Durable replacement/deletion owners not yet classified | Outstanding (#9982) |
| Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) |
| Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index a25c47cbc3..1f164f83cd 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -399,6 +399,13 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
id: 'operator-file-purge', status: 'admitted',
modules: ['services/dataManager.js', 'routes/uploads.js', 'routes/attachments.js'],
},
+ {
+ // Snapshot JSON and its index entry are one pair, including unlink-before-
+ // index deletion. Acquire before the index tail so queued writes drain.
+ id: 'time-capsule-snapshot-index',
+ status: 'admitted',
+ modules: ['services/timeCapsule.js'],
+ },
// Anything the sweep did not reach. A new asset owner lands here until it is
// classified; the claim cannot become `global` while this entry exists.
{ id: 'unclassified-durable-owners', status: 'outstanding', modules: [] },
diff --git a/server/services/timeCapsule.backupAdmission.test.js b/server/services/timeCapsule.backupAdmission.test.js
new file mode 100644
index 0000000000..4aa7c91b10
--- /dev/null
+++ b/server/services/timeCapsule.backupAdmission.test.js
@@ -0,0 +1,93 @@
+/** Snapshot/index pairs must be copied together, including unlink-first deletion. */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+let beforeIndexWrite = async () => {};
+let bypassAdmission = false;
+vi.mock('../lib/fileUtils.js', async importOriginal => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, {
+ dataRoot: () => lazyTempDataRoot('portos-timecapsule-backup-'),
+ overrides: { atomicWrite: async (path, data) => {
+ if (path.endsWith('index.json')) await beforeIndexWrite();
+ return actual.atomicWrite(path, data);
+ } },
+ });
+});
+vi.mock('../lib/backupSnapshotBoundary.js', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, withBackupAssetPublication: work => bypassAdmission ? work() : actual.withBackupAssetPublication(work) };
+});
+const { PATHS } = await import('../lib/fileUtils.js');
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const { createSnapshot, deleteSnapshot } = await import('./timeCapsule.js');
+const dir = () => join(PATHS.digitalTwin, 'snapshots');
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+};
+const settle = () => new Promise(resolve => setImmediate(resolve));
+const capture = async () => ({
+ files: (await readdir(dir())).filter(name => name !== 'index.json').sort(),
+ rows: JSON.parse(await readFile(join(dir(), 'index.json'), 'utf8')).snapshots.map(row => `${row.id}.json`).sort(),
+});
+beforeEach(async () => {
+ beforeIndexWrite = async () => {}; bypassAdmission = false;
+ await rm(PATHS.data, { recursive: true, force: true });
+ await mkdir(dir(), { recursive: true });
+ await writeFile(join(dir(), 'index.json'), '{"snapshots":[]}');
+});
+afterAll(cleanupTempDataRoots);
+
+const cases = [
+ { name: 'create', setup: async () => () => createSnapshot('Example snapshot') },
+ { name: 'delete', setup: async () => {
+ const snapshot = await createSnapshot('Example snapshot');
+ return () => deleteSnapshot(snapshot.id);
+ } },
+];
+describe.each(cases)('$name snapshot pair', ({ setup }) => {
+ it('does not mutate either half during an open cut', async () => {
+ const run = await setup();
+ const before = await capture();
+ const release = await acquireBackupSnapshotCut();
+ const work = run();
+ try { await settle(); await settle(); expect(await capture()).toEqual(before); }
+ finally { release(); }
+ await work;
+ const after = await capture();
+ expect(after.files).toEqual(after.rows);
+ expect(after).not.toEqual(before);
+ });
+
+ it('drains from the first file mutation through the index commit', async () => {
+ const run = await setup();
+ const reached = deferred(); const commit = deferred();
+ beforeIndexWrite = async () => { reached.resolve(); await commit.promise; };
+ const work = run();
+ await reached.promise;
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ try { await settle(); expect(cutReady).toBe(false); }
+ finally { commit.resolve(); }
+ await work;
+ const release = await cut;
+ try { const after = await capture(); expect(after.files).toEqual(after.rows); }
+ finally { release(); }
+ });
+});
+
+it('negative control exposes a copied index naming a file created after the file-copy phase', async () => {
+ bypassAdmission = true;
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const copiedFiles = (await capture()).files;
+ await createSnapshot('Example unadmitted snapshot');
+ const copiedIndex = (await capture()).rows;
+ expect(copiedIndex).toHaveLength(1);
+ expect(copiedFiles).not.toEqual(copiedIndex);
+ } finally { release(); }
+});
diff --git a/server/services/timeCapsule.js b/server/services/timeCapsule.js
index efcd58ff0a..f6df8a33e9 100644
--- a/server/services/timeCapsule.js
+++ b/server/services/timeCapsule.js
@@ -10,6 +10,7 @@ import { join } from 'path';
import { createHash } from 'crypto';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile, readJSONFileStrict, tryReadFile } from '../lib/fileUtils.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
const DIGITAL_TWIN_DIR = PATHS.digitalTwin;
@@ -159,7 +160,8 @@ export async function createSnapshot(label, description = '') {
summary: buildSummary(data)
};
- return queueIndexWrite(async () => {
+ // Admit before the shared write tail: a cut drains the complete file/index pair.
+ return withBackupAssetPublication(() => queueIndexWrite(async () => {
// Load (and maybe rebuild) the index BEFORE writing this snapshot file so
// a recovery scan cannot pick up the file we are about to add, then
// unshift a duplicate of it.
@@ -170,7 +172,7 @@ export async function createSnapshot(label, description = '') {
await saveIndex(index);
console.log(`📸 Time capsule created: "${label}" (${snapshot.id.slice(0, 8)})`);
return snapshot;
- });
+ }));
}
/**
@@ -194,7 +196,7 @@ export async function getSnapshot(id) {
* Delete a snapshot
*/
export async function deleteSnapshot(id) {
- return queueIndexWrite(async () => {
+ return withBackupAssetPublication(() => queueIndexWrite(async () => {
const index = await loadIndex();
const exists = index.snapshots.find(s => s.id === id);
if (!exists) return false;
@@ -209,7 +211,7 @@ export async function deleteSnapshot(id) {
console.log(`🗑️ Time capsule deleted: "${exists.label}" (${id.slice(0, 8)})`);
return true;
- });
+ }));
}
/**