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: serialize concurrent peer media-library asset pulls on the destination path (#3929)

[._.]/ Adam Eivy4c446c86e1fb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 90e7373392..a994640d20 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -70,3 +70,4 @@
- Pushing a series or music video project to a peer running an older PortOS no longer fires the same rejected request every sync cycle forever. When the older peer's strict schema rejects a newer bundled key (`manuscriptReview`, `reverseOutline`, `linkedTrack`), the sender strips it and retries — and deliberately withholds `lastPushedHash` so the stripped doc is re-sent once that peer upgrades. With nothing else recorded, the next cycle had no way to tell a settled record from a new edit, so every 60-second tick re-ran the same 400-plus-retry pair for content that had not moved. A second water-mark (`lastPushedLegacyHash`) now records what was actually delivered in stripped form, so an unchanged record short-circuits; any real edit still moves the hash and re-attempts the full push, and the `peer:online` re-probe still pushes unconditionally, which is where the stripped key finally lands after an upgrade. A pending doc the *receiver* reported (its bundled merge threw) is left un-water-marked, since that one is transient and must genuinely retry.
- A failed first read on the Quota Burn page no longer strands you on a dead end. `load()` swallowed the error and left `config` null, and the unavailable branch returns before the header — so the only control that could re-read, "Refresh quota", was never rendered, and the one line on screen named neither the cause nor a way out short of reloading the browser tab. The read's failure is now kept in its own state (`null` = never failed, distinct from "the server answered and has no plan"), and the unavailable branch renders an error banner carrying that message with a Retry button that re-reads and clears it on success.
- Deleting a prompt variable now asks first. The 14px trash icon on each row in the Prompt Manager's Variables list fired `DELETE /api/prompts/variables/:key` on the first click, so a mis-click — easy on a touch screen or with tight cursor tracking — destroyed the variable and its template content with no warning and no undo. The trash button now arms an inline confirm row in place of that row ("Delete "Tone Guide"?" with Delete / Cancel), using the shared `useConfirmDelete` + `InlineConfirmRow` pattern, so only one row is armed at a time and cancelling leaves the variable untouched. The trash button's accessible name now also names the variable it deletes instead of the generic "Delete variable".
+- Media-library sweeps from two or more full-sync peers no longer race on the same asset file. The in-flight pull guard is keyed by `(peer, kind, filename)` on purpose — a re-render pushed by one peer should still be able to overwrite an older copy another peer served — but that also meant two peers advertising the same filename, which is exactly what a mirrored library looks like, both passed the guard and downloaded and wrote `data/{images,videos,audio,music}/<name>` at the same time. Pulls now serialize on a queue keyed by the destination alone, so the later peer waits its turn rather than writing alongside the first, and the local file is re-checked against the advertised hash once the turn arrives: for every asset kind, not just images, matching bytes mean a hash instead of a second download. The all-peers sweep also picked up a global re-entrancy guard, since a sweep that outran the 60-second tick let the next tick start peer B while peer A was still mid-pull, and the derived `media_assets` reconcile now runs on a single tail with concurrent requests collapsed into one pass instead of stacking overlapping full-table rebuilds.
diff --git a/server/services/sharing/peerMediaLibrarySync.js b/server/services/sharing/peerMediaLibrarySync.js
index 505dc95859..ddc8182313 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 { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
@@ -199,15 +200,30 @@ const librarySweepInFlight = new Set(); // peerInstanceId
// The manifest JSON itself (not the bytes — those ride the per-asset 100MB cap).
const MEDIA_LIBRARY_MANIFEST_MAX_BYTES = 32 * 1024 * 1024;
-async function reconcileMediaLibraryIndex() {
- // Dynamic import keeps the DB-backed index module out of peerSync's static
- // graph (it no-ops under the file/test backend). image+video rows are rebuilt
- // 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) => {
- console.log(`⚠️ peerSync: media_assets reconcile after library sweep failed: ${err.message}`);
+// `reconcileMediaAssets` rebuilds the WHOLE media_assets index from disk, so two
+// sweeps finishing close together would fire overlapping full-table upsert/delete
+// passes against the same rows (#3929). Serialize on one tail AND collapse
+// requests that arrive while a pass is still QUEUED — one pass reading disk after
+// the last pull settles already covers every caller. `reconcilePending` clears the
+// moment the work starts, so a request that arrives mid-pass gets its own pass
+// chained behind (it may have landed bytes the running pass already read past).
+const reconcileQueue = createFileWriteQueue();
+let reconcilePending = null;
+
+function reconcileMediaLibraryIndex() {
+ if (reconcilePending) return reconcilePending;
+ reconcilePending = reconcileQueue(async () => {
+ reconcilePending = null;
+ // Dynamic import keeps the DB-backed index module out of peerSync's static
+ // graph (it no-ops under the file/test backend). image+video rows are rebuilt
+ // 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) => {
+ console.log(`⚠️ peerSync: media_assets reconcile after library sweep failed: ${err.message}`);
+ });
});
+ return reconcilePending;
}
/**
@@ -306,18 +322,36 @@ export async function syncMediaLibraryFromPeer(peer) {
}
}
+// Global (all-peers) re-entrancy guard — distinct from the per-peer
+// `librarySweepInFlight` above. That set only stops ONE peer's sweep from
+// overlapping itself; a sweep that outlives the 60s tick would still let tick N+1
+// start peer B while tick N is mid-pull on peer A. Two full-sync peers commonly
+// advertise the SAME filenames (that is what full-sync means), so overlapping
+// per-peer sweeps are exactly the cross-peer download + reconcile race in #3929.
+// One library sweep at a time; the next tick picks up wherever this one left off.
+let allPeersSweepInFlight = false;
+
/**
* Periodic driver: sweep the standalone media library from every full-sync peer.
- * Called on a timer from initSharing. Each peer's sweep is independent and
+ * Called on a timer from initSharing. Peers are swept one at a time and
* best-effort; the per-peer re-entrancy guard + manifestHash short-circuit keep
* an unchanged library cheap.
+ *
+ * @returns {Promise<{ peers:number, skipped?:string }>}
*/
export async function syncMediaLibraryWithAllPeers() {
- const peers = await getPeers().catch(() => []);
- const fullSyncPeers = peers.filter((p) => p?.fullSync === true && p?.enabled !== false && isStr(p.instanceId));
- for (const peer of fullSyncPeers) {
- await syncMediaLibraryFromPeer(peer).catch((err) => {
- console.log(`⚠️ peerSync: media-library sweep for ${peer.name || peer.instanceId} failed: ${err.message}`);
- });
+ if (allPeersSweepInFlight) return { peers: 0, skipped: 'in-flight' };
+ allPeersSweepInFlight = true;
+ try {
+ const peers = await getPeers().catch(() => []);
+ const fullSyncPeers = peers.filter((p) => p?.fullSync === true && p?.enabled !== false && isStr(p.instanceId));
+ for (const peer of fullSyncPeers) {
+ await syncMediaLibraryFromPeer(peer).catch((err) => {
+ console.log(`⚠️ peerSync: media-library sweep for ${peer.name || peer.instanceId} failed: ${err.message}`);
+ });
+ }
+ return { peers: fullSyncPeers.length };
+ } finally {
+ allPeersSweepInFlight = false;
}
}
\ No newline at end of file
diff --git a/server/services/sharing/peerSyncAssets.concurrency.test.js b/server/services/sharing/peerSyncAssets.concurrency.test.js
new file mode 100644
index 0000000000..a9b65c02e1
--- /dev/null
+++ b/server/services/sharing/peerSyncAssets.concurrency.test.js
@@ -0,0 +1,166 @@
+/**
+ * #3929 — concurrent standalone media-library sweeps from MULTIPLE full-sync
+ * peers must not race on the same destination asset file (nor stack whole-index
+ * reconciles). The per-peer `inflightPulls` guard is keyed by peer id, so two
+ * peers advertising the same filename both pass it; the destination-keyed
+ * `assetWriteQueue` is what serializes them.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, readFileSync, mkdirSync, writeFileSync } 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-asset-race-boot-'));
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: () => tempRoot });
+});
+
+const peers = [];
+vi.mock('../instances.js', () => ({
+ getPeers: vi.fn(async () => peers),
+}));
+
+vi.mock('../../lib/peerHttpClient.js', () => ({ peerFetch: vi.fn() }));
+
+const { peerFetch } = await import('../../lib/peerHttpClient.js');
+const { pullMissingAssetsFromPeer, assetWriteQueue } = await import('./peerSyncAssets.js');
+const { syncMediaLibraryWithAllPeers } = await import('./peerMediaLibrarySync.js');
+
+const sha = (buf) => createHash('sha256').update(buf).digest('hex');
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// Minimal fetch Response stand-in: peerSyncAssets requires a trustworthy
+// content-length before it will buffer a body.
+const mkRes = (buffer) => ({
+ ok: true,
+ headers: {
+ has: (h) => h === 'content-length',
+ get: (h) => (h === 'content-length' ? String(buffer.length) : null),
+ },
+ arrayBuffer: async () => buffer,
+});
+
+// Distinct TEST-NET-1 addresses so a test can tell the two peers' fetch URLs apart.
+const mkPeer = (id, address) => ({ instanceId: id, name: id, address, port: 5555, fullSync: true });
+
+function setPeers(...entries) {
+ peers.length = 0;
+ peers.push(...entries);
+}
+
+// `audio` is the simplest kind end-to-end: no gen-params sidecar fetch (images)
+// and no local thumbnail regeneration (videos), so every peerFetch call in these
+// tests is an asset-byte pull.
+const audioEntry = (filename, buffer) => ({ filename, kind: 'audio', sha256: sha(buffer) });
+
+/** Wrap peerFetch so the test can observe how many byte-pulls overlap. */
+function trackingFetch(bodyFor, delayMs = 20) {
+ const state = { inFlight: 0, maxInFlight: 0, urls: [] };
+ vi.mocked(peerFetch).mockImplementation(async (url) => {
+ state.urls.push(url);
+ state.inFlight += 1;
+ state.maxInFlight = Math.max(state.maxInFlight, state.inFlight);
+ await sleep(delayMs);
+ state.inFlight -= 1;
+ return mkRes(bodyFor(url));
+ });
+ return state;
+}
+
+describe('#3929 — cross-peer asset pull serialization', () => {
+ beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-asset-race-'));
+ assetWriteQueue.clear();
+ vi.mocked(peerFetch).mockReset();
+ setPeers(mkPeer('peer-a', '192.0.2.10'), mkPeer('peer-b', '192.0.2.11'));
+ });
+ afterEach(() => {
+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });
+ });
+
+ // Bypass probe: the harness CAN observe overlap — two pulls for DIFFERENT
+ // destinations do run concurrently, so `maxInFlight === 1` in the tests below
+ // is the queue working, not the instrumentation failing to see a second call.
+ it('leaves pulls for DIFFERENT filenames concurrent', async () => {
+ const a = Buffer.from('alpha-bytes');
+ const b = Buffer.from('beta-bytes-longer');
+ const state = trackingFetch((url) => (url.endsWith('a.mp3') ? a : b));
+ await Promise.all([
+ pullMissingAssetsFromPeer('peer-a', [audioEntry('a.mp3', a)]),
+ pullMissingAssetsFromPeer('peer-b', [audioEntry('b.mp3', b)]),
+ ]);
+ expect(state.maxInFlight).toBe(2);
+ });
+
+ it('serializes two peers pulling the SAME filename and skips the duplicate download', async () => {
+ const bytes = Buffer.from('shared-library-audio');
+ const entry = audioEntry('shared.mp3', bytes);
+ const state = trackingFetch(() => bytes);
+ await Promise.all([
+ pullMissingAssetsFromPeer('peer-a', [entry]),
+ pullMissingAssetsFromPeer('peer-b', [entry]),
+ ]);
+ // Never two writers on one destination path...
+ expect(state.maxInFlight).toBe(1);
+ // ...and the second peer's turn found the bytes already correct, so it
+ // re-hashed instead of re-downloading.
+ expect(state.urls).toHaveLength(1);
+ expect(readFileSync(join(tempRoot, 'audio', 'shared.mp3'))).toEqual(bytes);
+ });
+
+ it('serializes even when the two peers advertise DIFFERENT bytes for one filename', async () => {
+ // Distinct lengths so a torn/interleaved write is detectable: the final file
+ // must be exactly one complete version, never a blend or a truncation.
+ const older = Buffer.from('older-render');
+ const newer = Buffer.from('newer-render-with-more-bytes');
+ // Each peer serves its OWN version — the peers sit on distinct addresses, so
+ // the requested URL identifies which one is being pulled.
+ const state = trackingFetch((url) => (url.includes('192.0.2.11') ? newer : older));
+ await Promise.all([
+ pullMissingAssetsFromPeer('peer-a', [audioEntry('contested.mp3', older)]),
+ pullMissingAssetsFromPeer('peer-b', [audioEntry('contested.mp3', newer)]),
+ ]);
+ expect(state.maxInFlight).toBe(1);
+ const onDisk = readFileSync(join(tempRoot, 'audio', 'contested.mp3'));
+ expect([older.toString(), newer.toString()]).toContain(onDisk.toString());
+ });
+
+ it('skips the pull entirely when local bytes already match the advertised hash', async () => {
+ const bytes = Buffer.from('already-here');
+ mkdirSync(join(tempRoot, 'audio'), { recursive: true });
+ writeFileSync(join(tempRoot, 'audio', 'present.mp3'), bytes);
+ const state = trackingFetch(() => bytes);
+ await pullMissingAssetsFromPeer('peer-a', [audioEntry('present.mp3', bytes)]);
+ expect(state.urls).toHaveLength(0);
+ });
+});
+
+describe('#3929 — syncMediaLibraryWithAllPeers global re-entrancy guard', () => {
+ beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-sweep-race-'));
+ vi.mocked(peerFetch).mockReset();
+ setPeers(mkPeer('peer-a', '192.0.2.10'), mkPeer('peer-b', '192.0.2.11'));
+ });
+ afterEach(() => {
+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });
+ });
+
+ it('refuses a second all-peers sweep while one is still running', async () => {
+ // A manifest fetch that outlives the tick — the exact condition that would
+ // otherwise let tick N+1 start peer B while tick N is mid-pull on peer A.
+ vi.mocked(peerFetch).mockImplementation(async () => {
+ await sleep(30);
+ return { ok: false, headers: { has: () => false, get: () => null } };
+ });
+ const first = syncMediaLibraryWithAllPeers();
+ const second = await syncMediaLibraryWithAllPeers();
+ expect(second).toEqual({ peers: 0, skipped: 'in-flight' });
+ expect(await first).toEqual({ peers: 2 });
+ // Guard releases: a later tick sweeps normally.
+ expect(await syncMediaLibraryWithAllPeers()).toEqual({ peers: 2 });
+ });
+});
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 18e0cc4531..66aa1741df 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -36,6 +36,7 @@ import { imageUrlToAppAsset } from '../moodBoard/index.js';
import { WRITERS_ROOM_DRAFT_ASSET_KIND } from '../writersRoom/syncLogic.js';
import { WORK_ID_RE, DRAFT_ID_RE, wrWorkDir, wrDraftPath } from '../writersRoom/_shared.js';
import { getWorkForSync } from '../writersRoom/sync.js';
+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { peerSyncEvents, findPeerById, isNonEmptyStr } from './peerSyncShared.js';
@@ -636,6 +637,20 @@ export function inflightKey(peerId, kind, filename) {
return `${peerId}:${kind}:${filename}`;
}
+// Per-DESTINATION serialization (#3929). `inflightPulls` above is deliberately
+// peer-scoped, so two DIFFERENT full-sync peers advertising the same filename —
+// the normal case for a mirrored media library — both pass its guard and would
+// otherwise download and write `data/{images,videos,...}/<name>` concurrently.
+// Key this queue on the destination (kind + filename) ONLY, so those pulls run
+// one-after-another instead of racing on the same target path. Serializing (not
+// dropping) preserves the peer-scoped guard's intent — the later-pushing peer
+// still gets its turn to win — while the re-check at the top of doPullOneAsset
+// means the second turn usually costs a hash instead of a second download.
+export const assetWriteQueue = createKeyCachedQueue();
+export function assetDestinationKey(kind, filename) {
+ return `${kind}:${filename}`;
+}
+
/**
* Background-fetch every asset in `missingAssets` from the named peer's
* static `/data/{kind-dir}/` mount, writing each to the local PATHS dir for
@@ -815,25 +830,40 @@ async function pullOneAsset(peer, base, entry) {
if (inflightPulls.has(key)) return;
inflightPulls.add(key);
try {
- await doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName);
+ // Serialize on the DESTINATION path so a concurrent sweep from a different
+ // peer for this same filename waits its turn instead of writing alongside us
+ // (#3929). See assetWriteQueue.
+ await assetWriteQueue(
+ assetDestinationKey(entry.kind, safeName),
+ () => doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName),
+ );
} finally {
inflightPulls.delete(key);
}
}
async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName) {
- // Sidecar-only divergence: image bytes are already present and hash-match
- // the sender's manifest (diffAssetManifestAgainstLocal still returned this
- // entry because the local sidecar is absent or stale). Skip the image
- // re-pull and go straight to the sidecar fetch — avoids re-downloading a
- // potentially large PNG for a metadata-only update.
- if (entry.kind === 'image' && isStr(entry.sha256)) {
+ // Re-check disk against the advertised hash before spending a download. Two
+ // distinct cases land here with the bytes already correct:
+ // - sidecar-only divergence: the image bytes hash-match and
+ // diffAssetManifestAgainstLocal returned this entry purely because the
+ // local gen-params sidecar is absent or stale;
+ // - a concurrent sweep from ANOTHER peer just committed these same bytes
+ // while we waited on the destination queue (#3929) — the diff that queued
+ // this entry ran before the lock, so it can be stale by the time we run.
+ // Checking for EVERY kind (not just images) is the point: a video/music
+ // re-pull is the expensive duplicate, and hashing a local file beats
+ // re-streaming it from the peer.
+ if (isStr(entry.sha256)) {
const localFullPath = join(localDir, safeName);
if (existsSync(localFullPath)) {
- const localHash = (await getOrComputeImageSha256(localFullPath))?.hash ?? null;
+ const localHash = entry.kind === 'image'
+ ? (await getOrComputeImageSha256(localFullPath))?.hash ?? null
+ : await sha256File(localFullPath).catch(() => null);
if (localHash === entry.sha256) {
- // Image bytes already up-to-date — pull sidecar only.
- await pullSidecarForImage(peer, base, safeName).catch(() => {});
+ // 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(() => {});
return;
}
}