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 peer asset pulls, share imports and the library sweep whole across backups (#9982)

[._.]/ Adam Eivyee8211595261
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 5c7f782618..e749c4424c 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -92,7 +92,8 @@ Admission inventory (`withBackupAssetPublication`):
| Mood board re-hosting, Pinterest and X imports, frame extraction and collages (`moodBoard/*.js`) | Covered (#9982 partial): downloads and renders run outside admission; the board row that first names them, and each in-place rewrite of a URL-keyed download, take the lease |
| 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 |
-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, peer and share imports, archive and document imports |
+| 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 |
| 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 2487943245..2b09b60149 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -289,9 +289,12 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
],
},
{
- // Peer asset and draft-body pulls, share bucket import, and the peer library sweep.
+ // Downloads run outside admission. The write that lands a pulled asset (with
+ // its sidecar, poster and media_assets row), a draft body or a bible file, the
+ // share bucket's asset copy, and the library sweep's index rebuild each hold
+ // the lease.
id: 'peer-and-share-imports',
- status: 'outstanding',
+ status: 'admitted',
modules: [
'services/sharing/peerSyncAssets.js', 'services/sharing/importer.js', 'services/sharing/peerMediaLibrarySync.js',
],
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index edb5aec875..b551cf9d8d 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -26,6 +26,7 @@ import { join, basename } from 'path';
import { readdir } from 'fs/promises';
import { existsSync } from 'fs';
import { EventEmitter } from 'events';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { PATHS, copyFileGuarded, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { isSafeRecordId } from '../../lib/validation.js';
import { logFailureWithStack } from '../../lib/failureLogging.js';
@@ -281,8 +282,17 @@ const LOCAL_TARGET_DIRS = Object.freeze({
'image-ref': PATHS.imageRefs,
});
-/** Copy bundled assets from the bucket into local data dirs. Runs in parallel. */
-async function copyAssetsLocally(bucketPath, assetRefs) {
+/**
+ * Copy bundled assets from the bucket into local data dirs. Runs in parallel.
+ * The copies and the media_assets rows that index them share one backup lease;
+ * the records naming these files merge afterwards, so a cut sees the bytes
+ * durable before any row that names them.
+ */
+function copyAssetsLocally(bucketPath, assetRefs) {
+ return withBackupAssetPublication(() => copyAssetsLocallyAdmitted(bucketPath, assetRefs));
+}
+
+async function copyAssetsLocallyAdmitted(bucketPath, assetRefs) {
await ensureDir(PATHS.images);
await ensureDir(PATHS.videos);
await ensureDir(PATHS.imageRefs);
diff --git a/server/services/sharing/peerMediaLibrarySync.js b/server/services/sharing/peerMediaLibrarySync.js
index 953f99a637..6dadb9b5a6 100644
--- a/server/services/sharing/peerMediaLibrarySync.js
+++ b/server/services/sharing/peerMediaLibrarySync.js
@@ -13,6 +13,7 @@ import { join } from 'path';
import { readdir, stat } from 'fs/promises';
import { createHash } from 'crypto';
import { PATHS } from '../../lib/fileUtils.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
@@ -226,7 +227,9 @@ function reconcileMediaLibraryIndex() {
// from disk; audio/music aren't indexed (served from disk directly).
const mod = await import('../mediaAssetIndex/index.js').catch(() => null);
if (!mod?.reconcileMediaAssets) return;
- await mod.reconcileMediaAssets().catch((err) => {
+ // The pull wrote bytes outside any lease; indexing them takes one, so a cut
+ // that copied the media directories first never dumps a row for a file it missed.
+ await withBackupAssetPublication(() => mod.reconcileMediaAssets()).catch((err) => {
console.log(`⚠️ peerSync: media_assets reconcile after library sweep failed: ${err.message}`);
});
});
diff --git a/server/services/sharing/peerSyncAssets.backupAdmission.test.js b/server/services/sharing/peerSyncAssets.backupAdmission.test.js
new file mode 100644
index 0000000000..a990cdf098
--- /dev/null
+++ b/server/services/sharing/peerSyncAssets.backupAdmission.test.js
@@ -0,0 +1,73 @@
+/**
+ * A peer pull against a backup cut (#9982). The download runs outside admission;
+ * the write that lands the bytes (and, for images, the index row that names
+ * them) holds the lease, so a cut that is already copying files never has a
+ * file appear or be replaced underneath it.
+ */
+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 { createHash } from 'crypto';
+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+let tempRoot = mkdtempSync(join(tmpdir(), 'portos-peer-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: () => {},
+}));
+vi.mock('../instances.js', () => ({
+ getPeers: vi.fn(async () => [{ instanceId: 'peer-a', name: 'peer-a', address: '192.0.2.10', port: 5555 }]),
+}));
+vi.mock('../../lib/peerHttpClient.js', () => ({ peerFetch: vi.fn() }));
+vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn(), trackAudioFilename: vi.fn() }));
+
+const { peerFetch } = await import('../../lib/peerHttpClient.js');
+const { assetWriteQueue, inflightPulls, pullMissingAssetsFromPeer } = await import('./peerSyncAssets.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
+const bytes = Buffer.from('example-peer-audio');
+const response = {
+ ok: true,
+ headers: { has: (name) => name === 'content-length', get: () => String(bytes.length) },
+ arrayBuffer: async () => bytes,
+};
+
+describe('peer asset pull against a backup cut', () => {
+ beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-peer-backup-'));
+ assetWriteQueue.clear();
+ inflightPulls.clear();
+ vi.mocked(peerFetch).mockReset().mockResolvedValue(response);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ rmSync(tempRoot, { recursive: true, force: true });
+ });
+ afterAll(() => rmSync(bootRoot, { recursive: true, force: true }));
+
+ it('lands the downloaded file only after the cut releases', async () => {
+ const target = join(tempRoot, 'music', 'pulled.mp3');
+ const release = await acquireBackupSnapshotCut();
+ let pending;
+ try {
+ pending = pullMissingAssetsFromPeer('peer-a', [
+ { filename: 'pulled.mp3', kind: 'music', sha256: createHash('sha256').update(bytes).digest('hex') },
+ ]);
+ await settle();
+ expect(peerFetch).toHaveBeenCalled();
+ expect(existsSync(target)).toBe(false);
+ } finally {
+ release();
+ }
+ await pending;
+ expect(existsSync(target)).toBe(true);
+ });
+});
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index c59492d5cc..5ce631a3aa 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -38,6 +38,7 @@ import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { peerSyncEvents, findPeerById } from './peerSyncShared.js';
import { isStr } from '../../lib/textUtils.js';
import { mapWithConcurrency } from '../../lib/mapWithConcurrency.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
// Bound file hashing to avoid starving unrelated filesystem work when a
// large record (especially a deck) advertises hundreds of images.
@@ -1032,14 +1033,21 @@ async function pullOneWorkBody(peer, base, entry) {
// will re-push) — don't clobber it with the older peer bytes. A vanished
// draft/work (deleted mid-pull) also skips. (sha256File of the .md equals
// contentHash(text) since the body is the file verbatim.)
- const current = await getWorkForSync(workId).catch(() => null);
- const draft = Array.isArray(current?.drafts) ? current.drafts.find((d) => d?.id === draftId) : null;
- if (!draft || draft.contentHash !== entry.sha256) {
+ // The download above stays outside the backup lease; the compare-and-swap
+ // and the write that replaces the draft file share it, so a cut never copies
+ // the file between the check and the write.
+ const written = await withBackupAssetPublication(async () => {
+ const current = await getWorkForSync(workId).catch(() => null);
+ const draft = Array.isArray(current?.drafts) ? current.drafts.find((d) => d?.id === draftId) : null;
+ if (!draft || draft.contentHash !== entry.sha256) return false;
+ await ensureDir(join(wrWorkDir(workId), 'drafts'));
+ await atomicWrite(wrDraftPath(workId, draftId), buffer);
+ return true;
+ });
+ if (!written) {
console.log(`⚠️ peerSync: draft body ${safeLabel} target moved since diff — skipping write`);
return;
}
- await ensureDir(join(wrWorkDir(workId), 'drafts'));
- await atomicWrite(wrDraftPath(workId, draftId), buffer);
peerSyncEvents.emit('asset-arrived', {
filename: `${draftId}.md`,
kind: WRITERS_ROOM_DRAFT_ASSET_KIND,
@@ -1106,10 +1114,12 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName,
if (localHash === entry.sha256) {
// Bytes already up-to-date. Images still reconcile their sidecar, since
// that may be the only reason this entry was flagged.
- if (entry.kind === 'image') await pullSidecarForImage(peer, base, safeName).catch(() => {});
// A video can have arrived before its video-history metadata. Recheck
// the declared poster even though the mp4 itself does not need a pull.
- if (entry.kind === 'video') await reconcileVideoThumbnail(safeName, localFullPath, peer.instanceId);
+ await withBackupAssetPublication(async () => {
+ if (entry.kind === 'image') await pullSidecarForImage(peer, base, safeName).catch(() => {});
+ if (entry.kind === 'video') await reconcileVideoThumbnail(safeName, localFullPath, peer.instanceId);
+ });
return;
}
}
@@ -1122,6 +1132,13 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName,
console.warn('⚠️ peerSync: discarded asset with mismatched sha256');
return;
}
+ // The download stays outside the backup lease. Replacing the file, its sidecar
+ // and poster, and the media_assets row that indexes them hold it together, so
+ // a cut never captures a row for bytes it did not copy, or the reverse.
+ await withBackupAssetPublication(() => commitPulledAsset(peer, base, entry, localDir, fullPath, safeName, buffer, includeMismatched));
+}
+
+async function commitPulledAsset(peer, base, entry, localDir, fullPath, safeName, buffer, includeMismatched) {
await ensureDir(localDir);
if (!includeMismatched && existsSync(fullPath)) return;
// atomicWrite (temp + rename) so a crash mid-write doesn't leave a
@@ -1166,7 +1183,7 @@ export async function pullMissingWorkBibles(senderInstanceId, entries) {
if (!buffer) return;
const current = await getWorkForSync(entry.workId);
if (!current || current.deleted || current.ephemeral) return;
- if (await applyWorkBibleBytes(entry, buffer, { via: 'peer-sync', peerId: senderInstanceId })) {
+ if (await withBackupAssetPublication(() => applyWorkBibleBytes(entry, buffer, { via: 'peer-sync', peerId: senderInstanceId }))) {
peerSyncEvents.emit('asset-arrived', { filename, kind: 'writers-room-bible', workId: entry.workId, peerId: senderInstanceId });
}
}).catch((err) => console.error(`❌ peerSync: bible pull failed: ${err.message}`));