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

perf: batch artist and album tombstone hash evictions (#5495)

[._.]/ Adam Eivye9cd8e6c6c07
diff --git a/server/services/albums/db.js b/server/services/albums/db.js
index 6ad06b0b8f..89c673ec7d 100644
--- a/server/services/albums/db.js
+++ b/server/services/albums/db.js
@@ -14,6 +14,7 @@ import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
import { buildAlbumRecord, applyAlbumPatch, mergeAlbumRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
function rowToAlbum(row) {
@@ -141,6 +142,8 @@ export async function pruneTombstonedAlbums(olderThanMs) {
RETURNING id`,
[cutoffIso],
);
- for (const r of rows) await deleteSyncBaseHash('album', r.id);
+ await withBaseHashFlushBatch(async () => {
+ for (const r of rows) await deleteSyncBaseHash('album', r.id);
+ });
return { pruned: rows.length };
}
diff --git a/server/services/albums/db.test.js b/server/services/albums/db.test.js
index b1b70e4c6e..b592c516c3 100644
--- a/server/services/albums/db.test.js
+++ b/server/services/albums/db.test.js
@@ -4,8 +4,28 @@
* Snapshots + restores the `albums` table. Mirrors artists/db.test.js.
*/
-import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { describe, it, expect, vi, afterAll, beforeAll, beforeEach } from 'vitest';
+import { rmSync } from 'fs';
+import { join } from 'path';
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+import { getSyncBaseHash, __resetBaseHashCacheForTests } from '../../lib/conflictJournal.js';
+
+const testState = vi.hoisted(() => ({ dataRoot: null, writeCounter: { baseHash: 0 } }));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ testState.dataRoot ??= mkdtempSync(join(tmpdir(), 'albums-db-test-'));
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: testState.dataRoot },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) testState.writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ };
+});
let dbReady = false;
let skipReason = '';
@@ -25,6 +45,8 @@ let skipReason = '';
if (!dbReady) console.log(`⏭️ services/albums/db.test.js skipped: ${skipReason}`);
+afterAll(() => rmSync(testState.dataRoot, { recursive: true, force: true }));
+
describe.skipIf(!dbReady)('albums DB adapter round-trip', () => {
let db;
let snap = [];
@@ -32,7 +54,12 @@ describe.skipIf(!dbReady)('albums DB adapter round-trip', () => {
db = await import('./db.js');
snap = (await query(`SELECT * FROM albums`)).rows;
});
- beforeEach(async () => { await query(`DELETE FROM albums`); });
+ beforeEach(async () => {
+ await query(`DELETE FROM albums`);
+ rmSync(join(testState.dataRoot, 'sharing'), { recursive: true, force: true });
+ __resetBaseHashCacheForTests();
+ testState.writeCounter.baseHash = 0;
+ });
afterAll(async () => {
await query(`DELETE FROM albums`).catch(() => {});
for (const r of snap) {
@@ -72,11 +99,23 @@ describe.skipIf(!dbReady)('albums DB adapter round-trip', () => {
expect(await db.getAlbum(a.id)).toBeNull();
});
- it('pruneTombstonedAlbums removes old tombstones only', async () => {
+ it('pruneTombstonedAlbums batches multiple old tombstone base-hash evictions', async () => {
const live = await db.createAlbum({ title: 'Live' });
const dead = await db.createAlbum({ title: 'Dead' });
- await db.mergeAlbumsFromSync([{ ...dead, deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' }]);
- expect((await db.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z'))).pruned).toBe(1);
+ const deadTwo = await db.createAlbum({ title: 'DeadTwo' });
+ await db.mergeAlbumsFromSync([
+ { ...dead, deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' },
+ { ...deadTwo, deleted: true, deletedAt: '2020-01-02T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' },
+ ]);
+ expect(await getSyncBaseHash('album', dead.id)).not.toBeNull();
+ expect(await getSyncBaseHash('album', deadTwo.id)).not.toBeNull();
+
+ testState.writeCounter.baseHash = 0;
+ expect(await db.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z')))
+ .toEqual({ pruned: 2 });
+ expect(testState.writeCounter.baseHash).toBe(1);
+ expect(await getSyncBaseHash('album', dead.id)).toBeNull();
+ expect(await getSyncBaseHash('album', deadTwo.id)).toBeNull();
expect((await query(`SELECT id FROM albums`)).rows.map((r) => r.id)).toEqual([live.id]);
});
});
diff --git a/server/services/albums/file.js b/server/services/albums/file.js
index dc4bcf3a6f..770b38305a 100644
--- a/server/services/albums/file.js
+++ b/server/services/albums/file.js
@@ -14,6 +14,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { sanitizeAlbum, buildAlbumRecord, applyAlbumPatch, mergeAlbumRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
const ALBUMS_FILE = join(PATHS.data, 'albums.json');
@@ -120,6 +121,8 @@ export async function pruneTombstonedAlbums(olderThanMs) {
}
if (pruned.length === 0) return { pruned: 0 };
await saveAll(survivors);
- for (const id of pruned) await deleteSyncBaseHash('album', id);
+ await withBaseHashFlushBatch(async () => {
+ for (const id of pruned) await deleteSyncBaseHash('album', id);
+ });
return { pruned: pruned.length };
}
diff --git a/server/services/albums/file.test.js b/server/services/albums/file.test.js
index 0cbd561006..dac787ed3f 100644
--- a/server/services/albums/file.test.js
+++ b/server/services/albums/file.test.js
@@ -13,10 +13,18 @@ import { tmpdir } from 'os';
import { join } from 'path';
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'albums-file-test-'));
+const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ };
});
const file = await import('./file.js');
@@ -27,6 +35,7 @@ function reset() {
rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });
rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
}
const journalEntries = () => cj.conflictJournalStore().loadAll();
@@ -106,12 +115,19 @@ describe('albums file backend — mergeAlbumsFromSync (LWW outcomes)', () => {
.toBe(cj.contentHashForRecord('album', remoteWinner));
});
- it('pruneTombstonedAlbums evicts the base hash for a hard-pruned tombstone', async () => {
+ it('pruneTombstonedAlbums batches base-hash eviction for multiple tombstones', async () => {
await file.mergeAlbumsFromSync([
- album('album-dead-base', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),
+ album('album-dead-base-1', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),
+ album('album-dead-base-2', { deleted: true, deletedAt: '2020-01-02T00:00:00.000Z', updatedAt: '2020-01-02T00:00:00.000Z' }),
]);
- expect(await cj.getSyncBaseHash('album', 'album-dead-base')).not.toBeNull();
- await file.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z'));
- expect(await cj.getSyncBaseHash('album', 'album-dead-base')).toBeNull();
+ expect(await cj.getSyncBaseHash('album', 'album-dead-base-1')).not.toBeNull();
+ expect(await cj.getSyncBaseHash('album', 'album-dead-base-2')).not.toBeNull();
+
+ writeCounter.baseHash = 0;
+ expect(await file.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z')))
+ .toEqual({ pruned: 2 });
+ expect(writeCounter.baseHash).toBe(1);
+ expect(await cj.getSyncBaseHash('album', 'album-dead-base-1')).toBeNull();
+ expect(await cj.getSyncBaseHash('album', 'album-dead-base-2')).toBeNull();
});
});
diff --git a/server/services/artists/db.js b/server/services/artists/db.js
index e7b038501b..4c659fe2b7 100644
--- a/server/services/artists/db.js
+++ b/server/services/artists/db.js
@@ -16,6 +16,7 @@ import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
import { buildArtistRecord, applyArtistPatch, mergeArtistRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
function rowToArtist(row) {
@@ -144,6 +145,8 @@ export async function pruneTombstonedArtists(olderThanMs) {
RETURNING id`,
[cutoffIso],
);
- for (const r of rows) await deleteSyncBaseHash('artist', r.id);
+ await withBaseHashFlushBatch(async () => {
+ for (const r of rows) await deleteSyncBaseHash('artist', r.id);
+ });
return { pruned: rows.length };
}
diff --git a/server/services/artists/db.test.js b/server/services/artists/db.test.js
index ffc78cb189..3b3d0bd8b1 100644
--- a/server/services/artists/db.test.js
+++ b/server/services/artists/db.test.js
@@ -11,8 +11,28 @@
* survive the run even on the test DB. Mirrors authors/db.test.js.
*/
-import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { describe, it, expect, vi, afterAll, beforeAll, beforeEach } from 'vitest';
+import { rmSync } from 'fs';
+import { join } from 'path';
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+import { getSyncBaseHash, __resetBaseHashCacheForTests } from '../../lib/conflictJournal.js';
+
+const testState = vi.hoisted(() => ({ dataRoot: null, writeCounter: { baseHash: 0 } }));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ testState.dataRoot ??= mkdtempSync(join(tmpdir(), 'artists-db-test-'));
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: testState.dataRoot },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) testState.writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ };
+});
let dbReady = false;
let skipReason = '';
@@ -32,6 +52,8 @@ let skipReason = '';
if (!dbReady) console.log(`⏭️ services/artists/db.test.js skipped: ${skipReason}`);
+afterAll(() => rmSync(testState.dataRoot, { recursive: true, force: true }));
+
describe.skipIf(!dbReady)('artists DB adapter round-trip', () => {
let db;
let snap = [];
@@ -40,7 +62,12 @@ describe.skipIf(!dbReady)('artists DB adapter round-trip', () => {
snap = (await query(`SELECT * FROM artists`)).rows;
});
- beforeEach(async () => { await query(`DELETE FROM artists`); });
+ beforeEach(async () => {
+ await query(`DELETE FROM artists`);
+ rmSync(join(testState.dataRoot, 'sharing'), { recursive: true, force: true });
+ __resetBaseHashCacheForTests();
+ testState.writeCounter.baseHash = 0;
+ });
afterAll(async () => {
await query(`DELETE FROM artists`).catch(() => {});
@@ -112,16 +139,25 @@ describe.skipIf(!dbReady)('artists DB adapter round-trip', () => {
});
describe('pruneTombstonedArtists', () => {
- it('hard-removes tombstones older than the cutoff, keeps newer + live', async () => {
+ it('hard-removes multiple old tombstones with one base-hash write', async () => {
const live = await db.createArtist({ name: 'Live' });
const oldDead = await db.createArtist({ name: 'OldDead' });
+ const oldDeadTwo = await db.createArtist({ name: 'OldDeadTwo' });
const newDead = await db.createArtist({ name: 'NewDead' });
await db.mergeArtistsFromSync([
{ ...oldDead, deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' },
+ { ...oldDeadTwo, deleted: true, deletedAt: '2020-01-02T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' },
{ ...newDead, deleted: true, deletedAt: '2099-01-01T00:00:00.000Z', updatedAt: '2099-01-02T00:00:00.000Z' },
]);
+ expect(await getSyncBaseHash('artist', oldDead.id)).not.toBeNull();
+ expect(await getSyncBaseHash('artist', oldDeadTwo.id)).not.toBeNull();
+
+ testState.writeCounter.baseHash = 0;
const { pruned } = await db.pruneTombstonedArtists(Date.parse('2030-01-01T00:00:00.000Z'));
- expect(pruned).toBe(1);
+ expect(pruned).toBe(2);
+ expect(testState.writeCounter.baseHash).toBe(1);
+ expect(await getSyncBaseHash('artist', oldDead.id)).toBeNull();
+ expect(await getSyncBaseHash('artist', oldDeadTwo.id)).toBeNull();
const remaining = (await query(`SELECT id FROM artists ORDER BY id`)).rows.map((r) => r.id);
expect(remaining.sort()).toEqual([live.id, newDead.id].sort());
});
diff --git a/server/services/artists/file.js b/server/services/artists/file.js
index 44f241a9e9..72231f0a11 100644
--- a/server/services/artists/file.js
+++ b/server/services/artists/file.js
@@ -14,6 +14,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { sanitizeArtist, buildArtistRecord, applyArtistPatch, mergeArtistRecord } from './logic.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,
+ withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
const ARTISTS_FILE = join(PATHS.data, 'artists.json');
@@ -120,6 +121,8 @@ export async function pruneTombstonedArtists(olderThanMs) {
}
if (pruned.length === 0) return { pruned: 0 };
await saveAll(survivors);
- for (const id of pruned) await deleteSyncBaseHash('artist', id);
+ await withBaseHashFlushBatch(async () => {
+ for (const id of pruned) await deleteSyncBaseHash('artist', id);
+ });
return { pruned: pruned.length };
}
diff --git a/server/services/artists/file.test.js b/server/services/artists/file.test.js
index fdea1ed53c..39bd585c1e 100644
--- a/server/services/artists/file.test.js
+++ b/server/services/artists/file.test.js
@@ -16,10 +16,18 @@ import { tmpdir } from 'os';
import { join } from 'path';
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'artists-file-test-'));
+const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ };
});
const file = await import('./file.js');
@@ -30,6 +38,7 @@ function reset() {
rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });
rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
}
const journalEntries = () => cj.conflictJournalStore().loadAll();
@@ -131,12 +140,19 @@ describe('artists file backend — mergeArtistsFromSync (LWW outcomes)', () => {
.toBe(cj.contentHashForRecord('artist', remoteWinner));
});
- it('pruneTombstonedArtists evicts the base hash for a hard-pruned tombstone', async () => {
+ it('pruneTombstonedArtists batches base-hash eviction for multiple tombstones', async () => {
await file.mergeArtistsFromSync([
- artist('artist-dead-base', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),
+ artist('artist-dead-base-1', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),
+ artist('artist-dead-base-2', { deleted: true, deletedAt: '2020-01-02T00:00:00.000Z', updatedAt: '2020-01-02T00:00:00.000Z' }),
]);
- expect(await cj.getSyncBaseHash('artist', 'artist-dead-base')).not.toBeNull();
- await file.pruneTombstonedArtists(Date.parse('2030-01-01T00:00:00.000Z'));
- expect(await cj.getSyncBaseHash('artist', 'artist-dead-base')).toBeNull();
+ expect(await cj.getSyncBaseHash('artist', 'artist-dead-base-1')).not.toBeNull();
+ expect(await cj.getSyncBaseHash('artist', 'artist-dead-base-2')).not.toBeNull();
+
+ writeCounter.baseHash = 0;
+ expect(await file.pruneTombstonedArtists(Date.parse('2030-01-01T00:00:00.000Z')))
+ .toEqual({ pruned: 2 });
+ expect(writeCounter.baseHash).toBe(1);
+ expect(await cj.getSyncBaseHash('artist', 'artist-dead-base-1')).toBeNull();
+ expect(await cj.getSyncBaseHash('artist', 'artist-dead-base-2')).toBeNull();
});
});