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 ChatGPT imports, YouTube ingests, twin documents and genome whole across backups (#9982)

Adam Eivy60ceafb5043d
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index e749c4424c..d6a6e53f0f 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -93,7 +93,10 @@ Admission inventory (`withBackupAssetPublication`):
| Code Animation generated HTML, package import and repair revisions, production stage-run artifacts, Blender film publication and the soundtrack mux install (`codeAnimation/index.js`, `projects.js`, `stages.js`, `blenderRender.js`, `sound.js`) | Covered (#9982 partial): write-once revision trees and run artifacts land first, and the revision, run or history row that first names them commits under the lease; the mux's in-place install over an already-named render takes it too |
| Code Animation export staging and output acceptance (`codeAnimation/export.js`, `codeAnimation/acceptance.js`) | Reference-only: staging directories and worker workspaces are scratch no row names, and acceptance names a render that was already durable |
| Peer asset, draft-body and bible pulls, share bucket asset import and the peer library sweep (`sharing/peerSyncAssets.js`, `importer.js`, `peerMediaLibrarySync.js`) | Covered (#9982 partial): downloads run outside admission; the write that lands the bytes with its sidecar, poster and `media_assets` row, the draft or bible replacement, the bucket's asset copy and the sweep's index rebuild each take the lease |
-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, archive and document imports |
+| ChatGPT archive import and import-memory deletion (`chatgptImport.js`, `brain.js`; the ZIP's asset extraction in `chatgptZipImport.js`) | Covered (#9982 partial): assets are extracted outside admission and named only by the memory row; each conversation's archived transcript and that row commit under one lease, and deleting an import memory drops the record and unlinks its transcript and unreferenced assets under one lease |
+| YouTube ingest (`youtubeIngest.js`) | Covered (#9982 partial): downloads run outside admission; the index record that first names a transcript or audio file takes the lease, and forgetting an ingest drops the record and unlinks its files under one lease |
+| Digital twin documents and genome upload/delete (`digital-twin-documents.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion |
+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails |
| 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 2b09b60149..0560820a13 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -300,14 +300,29 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
],
},
{
- // ChatGPT archive import and memory-asset deletion, YouTube ingest, and the
- // digital twin and genome document stores.
- id: 'archive-and-document-imports',
- status: 'outstanding',
- modules: [
- 'services/chatgptZipImport.js', 'services/chatgptImport.js', 'services/youtubeIngest.js',
- 'services/digital-twin-documents.js', 'services/genome.js',
- ],
+ // The ChatGPT zip import extracts assets before any row names them; each
+ // conversation's archived transcript and the memory row that names it (and
+ // its assets) commit under one lease. Deleting an import memory drops the
+ // record, then its transcript and unreferenced assets, under one lease.
+ id: 'chatgpt-import-and-memory-asset-deletion',
+ status: 'admitted',
+ modules: ['services/chatgptImport.js', 'services/brain.js'],
+ },
+ {
+ // The ingest index record that first names a landed transcript or audio
+ // file commits under the lease; forgetting an ingest drops the record and
+ // unlinks its files under one lease. The long yt-dlp downloads stay outside.
+ id: 'youtube-ingest',
+ status: 'admitted',
+ modules: ['services/youtubeIngest.js'],
+ },
+ {
+ // Digital twin document files plus the meta row naming them, and the genome
+ // raw file plus its metadata: each create, edit, upload and delete is one
+ // workflow.
+ id: 'digital-twin-documents-and-genome',
+ status: 'admitted',
+ modules: ['services/digital-twin-documents.js', 'services/genome.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.
diff --git a/server/services/archiveDocumentBackupAdmission.test.js b/server/services/archiveDocumentBackupAdmission.test.js
new file mode 100644
index 0000000000..0c7739751d
--- /dev/null
+++ b/server/services/archiveDocumentBackupAdmission.test.js
@@ -0,0 +1,82 @@
+/**
+ * Document, genome and ChatGPT-import writes against a backup cut (#9982): a
+ * file-plus-record mutation requested while a cut is copying waits for it, so
+ * the copy never sees bytes the record does not name (or the reverse).
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { existsSync, mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const tempRoot = mkdtempSync(join(tmpdir(), 'portos-archive-backup-boot-'));
+const bootRoot = tempRoot;
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: () => tempRoot });
+});
+vi.mock('../lib/databaseMaintenanceJournal.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ assertDatabaseAdmission: () => {},
+}));
+
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const { uploadGenome, deleteGenome } = await import('./genome.js');
+const { createDocument } = await import('./digital-twin-documents.js');
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
+const snps = Array.from({ length: 120 }, (_, i) => `rs${1000 + i}\t1\t${100 + i}\tAA`).join('\n');
+
+describe('archive and document owners against a backup cut', () => {
+ beforeEach(() => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ rmSync(join(tempRoot, 'digital-twin'), { recursive: true, force: true });
+ rmSync(join(tempRoot, 'meatspace'), { recursive: true, force: true });
+ });
+ afterAll(() => rmSync(bootRoot, { recursive: true, force: true }));
+
+ it('lands a genome upload and removes it only outside a cut', async () => {
+ const raw = join(tempRoot, 'meatspace', 'genome-raw.txt');
+ const release = await acquireBackupSnapshotCut();
+ let upload;
+ try {
+ upload = uploadGenome(snps, 'example.txt');
+ await settle();
+ expect(existsSync(raw)).toBe(false);
+ } finally {
+ release();
+ }
+ await upload;
+ expect(existsSync(raw)).toBe(true);
+
+ const second = await acquireBackupSnapshotCut();
+ let removal;
+ try {
+ removal = deleteGenome();
+ await settle();
+ expect(existsSync(raw)).toBe(true);
+ } finally {
+ second();
+ }
+ await removal;
+ expect(existsSync(raw)).toBe(false);
+ });
+
+ it('writes a digital twin document file only after the cut releases', async () => {
+ const release = await acquireBackupSnapshotCut();
+ let created;
+ try {
+ created = createDocument({ filename: 'example-doc.md', title: 'Example', category: 'core', content: '# Example' });
+ await settle();
+ expect(existsSync(join(tempRoot, 'digital-twin', 'example-doc.md'))).toBe(false);
+ } finally {
+ release();
+ }
+ await created;
+ expect(existsSync(join(tempRoot, 'digital-twin', 'example-doc.md'))).toBe(true);
+ });
+});
diff --git a/server/services/brain.js b/server/services/brain.js
index 2420efce35..5591feaf72 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -19,6 +19,7 @@ import { runPromptThroughProvider } from './promptRunner.js';
import { getDomainAutonomyMode } from './cosState.js';
import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { deleteMemoryAssets } from './chatgptImport.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import * as repoCloner from './repoCloner.js';
import { deriveRepoLinkFields } from '../lib/repoLinkFields.js';
import { parseBareUrl } from '../lib/bareUrl.js';
@@ -946,7 +947,10 @@ export const updateMemoryEntry = storage.updateMemoryEntry;
* memories (so a shared transcript/asset still in use — e.g. the same export
* imported twice — isn't pulled out from under them).
*/
-export async function deleteMemoryEntry(id) {
+export const deleteMemoryEntry = (id) => withBackupAssetPublication(() => deleteMemoryEntryLeased(id));
+
+// The record drop and the asset/transcript unlinks are one backup workflow (#9982).
+async function deleteMemoryEntryLeased(id) {
const record = await storage.getMemoryEntryById(id);
const deleted = await storage.deleteMemoryEntry(id);
if (deleted && record?.source === 'chatgpt-import') {
diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.js
index 53448debc5..47bb5c08d4 100644
--- a/server/services/chatgptImport.js
+++ b/server/services/chatgptImport.js
@@ -22,6 +22,7 @@
import { join } from 'path';
import { stripChatgptCitations } from '../lib/chatgptText.js';
import { unlink } from 'fs/promises';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { atomicWrite, ensureDir, PATHS, tryReadFile, safeJSONParse, safeDate } from '../lib/fileUtils.js';
import { createMemoryEntry, updateMemoryEntry, query as queryBrain } from './brainStorage.js';
@@ -534,7 +535,6 @@ export async function importConversations(parsed, options = {}) {
continue;
}
- await archiveConversation(summary, archiveName);
archived += 1;
const tags = [
@@ -555,8 +555,15 @@ export async function importConversations(parsed, options = {}) {
sourceUpdatedAt: summary.updateTime || null
};
+ // The archived transcript and the memory row that names it are one backup
+ // workflow; the assets were extracted earlier and are named only by this row.
+ const commit = (write) => withBackupAssetPublication(async () => {
+ await archiveConversation(summary, archiveName);
+ return write();
+ });
+
if (existingMemory) {
- const entry = await updateMemoryEntry(existingMemory.id, memoryData);
+ const entry = await commit(() => updateMemoryEntry(existingMemory.id, memoryData));
results.push({
id: summary.id,
memoryId: entry.id,
@@ -570,7 +577,7 @@ export async function importConversations(parsed, options = {}) {
continue;
}
- const entry = await createMemoryEntry(memoryData);
+ const entry = await commit(() => createMemoryEntry(memoryData));
results.push({
id: summary.id,
diff --git a/server/services/digital-twin-documents.js b/server/services/digital-twin-documents.js
index ead5e15436..d50e052821 100644
--- a/server/services/digital-twin-documents.js
+++ b/server/services/digital-twin-documents.js
@@ -4,6 +4,7 @@ import { join } from 'path';
import { DIGITAL_TWIN_DIR, generateId, ensureSoulDir } from './digital-twin-helpers.js';
import { loadMeta, saveMeta } from './digital-twin-meta.js';
import { extractVersion } from './digital-twin-meta.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { recordTombstone, clearTombstone, tombstoneTimestamp, supersedingTimestamp } from '../lib/tombstones.js';
export async function getDocuments() {
@@ -37,7 +38,14 @@ export async function getDocumentById(id) {
};
}
-export async function createDocument(data) {
+// The document file and the meta row that names it are one workflow, so each
+// mutation holds the backup lease from its first byte change through the meta
+// write (#9982).
+export const createDocument = (data) => withBackupAssetPublication(() => createDocumentLeased(data));
+export const updateDocument = (id, updates) => withBackupAssetPublication(() => updateDocumentLeased(id, updates));
+export const deleteDocument = (id) => withBackupAssetPublication(() => deleteDocumentLeased(id));
+
+async function createDocumentLeased(data) {
await ensureSoulDir();
const meta = await loadMeta();
@@ -79,7 +87,7 @@ export async function createDocument(data) {
return { ...docMeta, content: data.content };
}
-export async function updateDocument(id, updates) {
+async function updateDocumentLeased(id, updates) {
const meta = await loadMeta();
const docIndex = meta.documents.findIndex(d => d.id === id);
@@ -115,7 +123,7 @@ export async function updateDocument(id, updates) {
return await getDocumentById(id);
}
-export async function deleteDocument(id) {
+async function deleteDocumentLeased(id) {
const meta = await loadMeta();
const docIndex = meta.documents.findIndex(d => d.id === id);
diff --git a/server/services/genome.js b/server/services/genome.js
index 1e9fad8a09..83cbb9008e 100644
--- a/server/services/genome.js
+++ b/server/services/genome.js
@@ -2,6 +2,7 @@ import { noteReadinessChanged } from './readinessNotify.js';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { atomicWrite, PATHS, ensureDir, safeJSONParse, tryReadFile, unlinkGuarded } from '../lib/fileUtils.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { CURATED_MARKERS, MARKER_CATEGORIES, classifyGenotype, formatGenotype, resolveApoeHaplotype } from '../lib/curatedGenomeMarkers.js';
const GENOME_DIR = PATHS.meatspace;
@@ -112,6 +113,11 @@ export async function uploadGenome(content, filename) {
return { error: 'File does not appear to be a valid 23andMe genome export (too few SNPs found)' };
}
+ // The raw file and the metadata that names it are one backup workflow (#9982).
+ return withBackupAssetPublication(() => storeGenome(content, filename, index, build));
+}
+
+async function storeGenome(content, filename, index, build) {
// Save raw file
await atomicWrite(RAW_FILE, content);
@@ -370,8 +376,12 @@ export async function deleteMarker(id) {
* Delete all genome data: raw file, metadata, and clear cache.
*/
export async function deleteGenome() {
- await unlinkGuarded(RAW_FILE).catch(() => {});
- await unlinkGuarded(META_FILE).catch(() => {});
+ // Unlinking the raw file before the metadata would leave a copied record
+ // naming bytes that are gone, so both removals hold the lease (#9982).
+ await withBackupAssetPublication(async () => {
+ await unlinkGuarded(RAW_FILE).catch(() => {});
+ await unlinkGuarded(META_FILE).catch(() => {});
+ });
snpIndex = null;
indexBuiltAt = 0;
noteReadinessChanged();
diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.js
index f817479946..1e52a9d00c 100644
--- a/server/services/youtubeIngest.js
+++ b/server/services/youtubeIngest.js
@@ -43,6 +43,7 @@ import { join } from 'path';
import { randomUUID } from 'crypto';
import { ServerError } from '../lib/errorHandler.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile, shortId, tryReadFile } from '../lib/fileUtils.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { findFfmpeg } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
@@ -155,8 +156,11 @@ async function loadIndex() {
// everything.
const NEW_INGEST = { transcript: null, obsidian: null, video: null, audio: null, taskId: null, agentPrompt: null, incomplete: null };
+// The index record is the row that first names a landed transcript or audio file,
+// so committing it takes the backup lease (#9982). Lease first, then the mutex,
+// everywhere, so the two never invert.
async function putIngest(videoId, patch) {
- return indexMutex(async () => {
+ return withBackupAssetPublication(() => indexMutex(async () => {
const index = await loadIndex();
const existing = index[videoId] || null;
const record = {
@@ -169,7 +173,7 @@ async function putIngest(videoId, patch) {
index[videoId] = record;
await atomicWrite(INDEX_FILE, index);
return record;
- });
+ }));
}
/**
@@ -213,18 +217,24 @@ export async function deleteIngest(videoId) {
// Read the record and drop it inside ONE lock, then clean up its files:
// reading outside the lock would unlink paths from a record a concurrent
// re-ingest had already replaced, and would parse the whole index twice.
- const record = await indexMutex(async () => {
- const index = await loadIndex();
- const found = index[videoId] || null;
- if (!found) return null;
- delete index[videoId];
- await atomicWrite(INDEX_FILE, index);
- return found;
+ // The index is a data file a cut copies apart from the transcript and audio,
+ // so the record drop and the unlinks hold one lease (#9982).
+ const record = await withBackupAssetPublication(async () => {
+ const dropped = await indexMutex(async () => {
+ const index = await loadIndex();
+ const found = index[videoId] || null;
+ if (!found) return null;
+ delete index[videoId];
+ await atomicWrite(INDEX_FILE, index);
+ return found;
+ });
+ if (!dropped) return null;
+ if (dropped.transcript?.path) await unlink(dropped.transcript.path).catch(() => {});
+ if (dropped.audio?.path) await unlink(dropped.audio.path).catch(() => {});
+ return dropped;
});
if (!record) return false;
- if (record.transcript?.path) await unlink(record.transcript.path).catch(() => {});
- if (record.audio?.path) await unlink(record.audio.path).catch(() => {});
if (record.obsidian?.path && record.obsidian?.vaultId) {
await obsidian.deleteNote(record.obsidian.vaultId, record.obsidian.path).catch(() => {});
}