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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf([mediacollections-parallel-merge-prune]): bounded-concurrency fan-out for merge + prune loops
[._.]/ Adam Eivy4b6315e5b89d
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex 89da73150e..a53731acdb 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -28,6 +28,7 @@ import { PATHS } from '../lib/fileUtils.js';import { createCollectionStore } from '../lib/collectionStore.js';import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';+import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,@@ -42,6 +43,12 @@ export const NAME_MAX_LENGTH = 80;export const DESCRIPTION_MAX_LENGTH = 500;export const ITEMS_MAX = 5000;+// Bounded fan-out for the multi-record snapshot-merge / GC-sweep loops. Distinct+// record ids ride distinct per-record write queues, so these are safe to run+// concurrently; the cap keeps a large snapshot from opening hundreds of file+// descriptors at once. (Same-id writes still serialize inside queueRecordWrite.)+const COLLECTION_WRITE_CONCURRENCY = 8;+// A collection id is a filesystem path segment (data/media-collections/<id>/).// The store's idPattern allowlist rejects anything else, so a record whose id// can't round-trip to its own dir is unrepresentable — `sanitizeCollection`@@ -891,23 +898,24 @@ export async function pruneTombstonedCollections(olderThanMs) {const ms = Date.parse(c.deletedAt || '');return Number.isFinite(ms) && ms < olderThanMs;});- let pruned = 0;- for (const c of candidates) {- await store().queueRecordWrite(c.id, async () => {+ // 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).+ 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)// so a concurrent re-create at the same id isn't blown away.const cur = await store().loadOne(c.id);- if (!cur || cur.deleted !== true) return;+ if (!cur || cur.deleted !== true) return false;const ms = Date.parse(cur.deletedAt || '');- if (!(Number.isFinite(ms) && ms < olderThanMs)) return;+ if (!(Number.isFinite(ms) && ms < olderThanMs)) return false;await store().deleteOneNow(c.id);// Evict the conflict-journal base hash so the side store doesn't grow// dead keys (mirrors pruneTombstonedUniverses / pruneTombstonedSeries).await deleteSyncBaseHash('mediaCollection', c.id);- pruned += 1;- });- }- return { pruned };+ return true;+ }));+ return { pruned: outcomes.filter(Boolean).length };}/**@@ -931,11 +939,17 @@ export async function pruneTombstonedCollections(olderThanMs) {*/export async function mergeMediaCollectionsFromSync(remoteCollections, { source = { via: 'sync', peerId: null } } = {}) {if (!Array.isArray(remoteCollections)) return { applied: false, count: 0 };- let changed = 0;- for (const remote of remoteCollections) {+ // Distinct collection ids ride distinct per-record queues, so apply the+ // snapshot batch with a bounded fan-out rather than one-at-a-time. (A duplicate+ // id within the batch still serializes on the same queue, and the merge is+ // LWW so its outcome is order-independent.) The base-hash mutations each+ // record makes accumulate in memory and are persisted by the single+ // `flushBaseHashes()` after the fan-out settles — unchanged from the+ // sequential version.+ const outcomes = await mapWithConcurrency(remoteCollections, COLLECTION_WRITE_CONCURRENCY, (remote) => {const sanitized = sanitizeCollection(remote);- if (!sanitized) continue;- const didChange = await store().queueRecordWrite(sanitized.id, async () => {+ if (!sanitized) return false;+ return store().queueRecordWrite(sanitized.id, async () => {const local = await store().loadOne(sanitized.id);if (!local) {await store().saveOneNow(sanitized.id, sanitized);@@ -995,8 +1009,8 @@ export async function mergeMediaCollectionsFromSync(remoteCollections, { sourceawait store().saveOneNow(sanitized.id, next);return true;});- if (didChange) changed++;- }+ });+ 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).await flushBaseHashes();diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex b36b2cccce..036f1d3bc9 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -966,6 +966,43 @@ describe('mergeMediaCollectionsFromSync', () => {expect(await svc.mergeMediaCollectionsFromSync([])).toEqual({ applied: false, count: 0 });});+ it('applies a multi-record batch (bounded fan-out) — all distinct ids land, count is exact', async () => {+ // The parallelized snapshot-apply path: a batch larger than the concurrency+ // bound, mixing inserts with a no-op (identical to an existing record, which+ // must NOT count as changed). Confirms every distinct id is written and the+ // returned count reflects only the records that actually changed.+ await seedState({+ collections: [{+ id: 'c-existing', name: 'Existing', description: '', coverKey: null,+ universeId: null, seriesId: null,+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T00:00:00Z' }],+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',+ }],+ });+ const remotes = [];+ for (let i = 0; i < 12; i++) {+ remotes.push({+ id: `c-batch-${i}`, name: `Batch ${i}`, description: '', coverKey: null,+ universeId: null, seriesId: null,+ items: [{ kind: 'image', ref: `b${i}.png`, addedAt: '2026-05-22T01:00:00Z' }],+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',+ });+ }+ // A remote identical to the existing record → merges to no change.+ remotes.push({+ id: 'c-existing', name: 'Existing', description: '', coverKey: null,+ universeId: null, seriesId: null,+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T00:00:00Z' }],+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',+ });++ const result = await svc.mergeMediaCollectionsFromSync(remotes);+ expect(result).toEqual({ applied: true, count: 12 }); // 12 new, the identical one no-ops+ const ids = (await svc.listCollections()).map((c) => c.id).sort();+ expect(ids).toContain('c-existing');+ for (let i = 0; i < 12; i++) expect(ids).toContain(`c-batch-${i}`);+ });+it('inserts a previously-unseen collection', async () => {const remote = {id: 'c-remote',@@ -1629,6 +1666,37 @@ describe('pruneTombstonedCollections', () => {expect(await cj.getSyncBaseHash('mediaCollection', c.id)).toBeNull();});+ it('prunes a multi-candidate batch (bounded fan-out) — only the old tombstones, exact count', async () => {+ // The parallelized GC sweep: more candidates than the concurrency bound,+ // interleaved with a live record and a too-recent tombstone that must survive.+ const oldTs = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();+ const futureTs = new Date(Date.now() + 60 * 1000).toISOString();+ const collections = [];+ for (let i = 0; i < 10; i++) {+ collections.push({+ id: `c-old-${i}`, name: `Old ${i}`, description: '', coverKey: null,+ universeId: null, seriesId: null, items: [],+ createdAt: oldTs, updatedAt: oldTs, deleted: true, deletedAt: oldTs,+ });+ }+ collections.push({+ id: 'c-live', name: 'Live', description: '', coverKey: null,+ universeId: null, seriesId: null, items: [],+ createdAt: oldTs, updatedAt: oldTs, deleted: false, deletedAt: null,+ });+ collections.push({+ id: 'c-recent', name: 'RecentDelete', description: '', coverKey: null,+ universeId: null, seriesId: null, items: [],+ createdAt: oldTs, updatedAt: futureTs, deleted: true, deletedAt: futureTs,+ });+ await seedState({ collections });++ const result = await svc.pruneTombstonedCollections(Date.now());+ expect(result).toEqual({ pruned: 10 }); // 10 old tombstones; live + recent survive+ const surviving = (await svc.listCollections({ includeDeleted: true })).map((c) => c.id).sort();+ expect(surviving).toEqual(['c-live', 'c-recent']);+ });+it('does NOT prune a live collection', async () => {await svc.createCollection({ name: 'Live' });const result = await svc.pruneTombstonedCollections(Date.now());