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([mediacollections-parallel-merge-prune]): settle whole fan-out before rethrow

[._.]/ Adam Eivy3dae27b3823b
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index a53731acdb..c949656480 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -901,6 +901,12 @@ export async function pruneTombstonedCollections(olderThanMs) {
// Candidates have distinct ids → distinct per-record queues, so prune them
// with a bounded fan-out instead of one-at-a-time. Each returns whether it
// actually pruned; sum after (no shared mutable counter across the workers).
+ // Each worker catches its own error so mapWithConcurrency never rejects mid-
+ // flight (which would let the OTHER in-flight workers keep writing in the
+ // background past our return); we rethrow the first error after every worker
+ // has settled, preserving the throw-on-failure contract without leaking
+ // background writes.
+ let firstError = null;
const outcomes = await mapWithConcurrency(candidates, COLLECTION_WRITE_CONCURRENCY, (c) =>
store().queueRecordWrite(c.id, async () => {
// Re-check inside the queue (deleteOneNow spans the load→delete boundary)
@@ -914,7 +920,8 @@ export async function pruneTombstonedCollections(olderThanMs) {
// dead keys (mirrors pruneTombstonedUniverses / pruneTombstonedSeries).
await deleteSyncBaseHash('mediaCollection', c.id);
return true;
- }));
+ }).catch((err) => { if (!firstError) firstError = err; return false; }));
+ if (firstError) throw firstError;
return { pruned: outcomes.filter(Boolean).length };
}
@@ -946,6 +953,13 @@ export async function mergeMediaCollectionsFromSync(remoteCollections, { source
// record makes accumulate in memory and are persisted by the single
// `flushBaseHashes()` after the fan-out settles — unchanged from the
// sequential version.
+ //
+ // Each worker catches its own error so mapWithConcurrency never rejects mid-
+ // flight: an early reject would let the other in-flight workers keep writing
+ // (and mutating the in-memory base-hash map) in the background past our return
+ // AND skip the flush below, stranding completed writes' base hashes unsaved.
+ // We let every worker settle, ALWAYS flush, then rethrow the first error.
+ let firstError = null;
const outcomes = await mapWithConcurrency(remoteCollections, COLLECTION_WRITE_CONCURRENCY, (remote) => {
const sanitized = sanitizeCollection(remote);
if (!sanitized) return false;
@@ -1008,12 +1022,14 @@ export async function mergeMediaCollectionsFromSync(remoteCollections, { source
if (collectionsEqual(local, next)) return false;
await store().saveOneNow(sanitized.id, next);
return true;
- });
+ }).catch((err) => { if (!firstError) firstError = err; return false; });
});
const changed = outcomes.filter(Boolean).length;
// Persist the batched conflict-journal base-hash updates accumulated above in
- // one write (seeds on insert + advances on accepted overwrite).
+ // one write (seeds on insert + advances on accepted overwrite). Always runs —
+ // even if a worker threw — so completed writes' base hashes aren't stranded.
await flushBaseHashes();
+ if (firstError) throw firstError;
if (changed === 0) return { applied: false, count: 0 };
return { applied: true, count: changed };
}
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index 036f1d3bc9..2db29344a0 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -1003,6 +1003,39 @@ describe('mergeMediaCollectionsFromSync', () => {
for (let i = 0; i < 12; i++) expect(ids).toContain(`c-batch-${i}`);
});
+ it('rethrows after the whole batch settles + still flushes when a worker fails', async () => {
+ // Error-handling contract for the parallel fan-out: if one record's write
+ // throws, the call must reject (throw-on-failure preserved) — but only AFTER
+ // every other in-flight worker settles, so no write leaks into the
+ // background past the rejection, and the base-hash flush still runs for the
+ // records that DID complete.
+ const store = svc.mediaCollectionStore();
+ const realSave = store.saveOneNow.bind(store);
+ const saveSpy = vi.spyOn(store, 'saveOneNow').mockImplementation((id, rec) => {
+ if (id === 'c-boom') return Promise.reject(new Error('disk full'));
+ return realSave(id, rec);
+ });
+ const mk = (id) => ({
+ id, name: id, description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [{ kind: 'image', ref: `${id}.png`, addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ });
+ const remotes = ['c-ok-1', 'c-ok-2', 'c-boom', 'c-ok-3'].map(mk);
+
+ await expect(svc.mergeMediaCollectionsFromSync(remotes)).rejects.toThrow('disk full');
+ saveSpy.mockRestore();
+
+ // The non-failing records all persisted (no early abort skipped them) and
+ // each carries a seeded base hash (the flush ran despite the throw).
+ const persisted = new Set((await svc.listCollections()).map((c) => c.id));
+ for (const id of ['c-ok-1', 'c-ok-2', 'c-ok-3']) {
+ expect(persisted.has(id)).toBe(true);
+ expect(await cj.getSyncBaseHash('mediaCollection', id)).not.toBeNull();
+ }
+ expect(persisted.has('c-boom')).toBe(false);
+ expect(await cj.getSyncBaseHash('mediaCollection', 'c-boom')).toBeNull();
+ });
+
it('inserts a previously-unseen collection', async () => {
const remote = {
id: 'c-remote',