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 catalog portrait replacement atomic under overlapping writes (#8685)

[._.]/ Adam Eivyd6a7d72a660a
diff --git a/server/services/catalogDB.media.db.test.js b/server/services/catalogDB.media.db.test.js
new file mode 100644
index 0000000000..37a73664f9
--- /dev/null
+++ b/server/services/catalogDB.media.db.test.js
@@ -0,0 +1,145 @@
+/**
+ * Real Postgres regression tests for overlapping local portrait replacements.
+ * Query barriers hold one replacement after demotion while another writer
+ * reaches the row lock; no sleeps or simulated SQL locking semantics.
+ */
+import { describe, it, expect, afterAll, afterEach, vi } from 'vitest';
+import { EventEmitter } from 'node:events';
+
+let intercept = null;
+vi.mock('../lib/db.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ withTransaction: (fn) => actual.withTransaction((client) => fn({
+ query: async (sql, params) => {
+ const after = await intercept?.(sql, params);
+ const result = await client.query(sql, params);
+ await after?.();
+ return result;
+ },
+ })),
+ };
+});
+vi.mock('./mediaJobQueue/index.js', () => ({ mediaJobEvents: new EventEmitter() }));
+vi.mock('./catalogMedia.js', () => ({
+ readImageGenerationMetadata: async () => ({ prompt: 'Example portrait', seed: 42 }),
+}));
+
+const { checkHealth, ensureSchema, close, query } = await import('../lib/db.js');
+const { requireDbOrSkip } = await import('../lib/dbTestGate.js');
+const catalogDB = await import('./catalogDB.js');
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const hook = await import('./catalogImageAttachHook.js');
+
+const health = await checkHealth();
+if (health.connected) await ensureSchema();
+const runDb = requireDbOrSkip('catalogDB.media.db.test', health.connected, health.error);
+const ids = [];
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+};
+
+async function ingredient() {
+ const row = await catalogDB.createIngredient({ type: 'character', name: 'Example portrait subject' });
+ ids.push(row.id);
+ return row.id;
+}
+
+afterEach(() => {
+ intercept = null;
+ hook.__testing.reset();
+});
+afterAll(async () => {
+ for (const id of ids) await catalogDB.deleteIngredient(id, { hard: true });
+ await close();
+});
+
+describe.skipIf(!runDb)('atomic local portrait replacement', () => {
+ it.each([false, true])('serializes generic and dedicated writes (existing portrait: %s)', async (existing) => {
+ const id = await ingredient();
+ if (existing) await catalogDB.setPortraitMedia(id, 'old.png');
+ let demoted = false;
+ const release = deferred();
+ let locks = 0;
+ intercept = async (sql, params) => {
+ if (sql.includes('FOR UPDATE')) locks += 1;
+ if (sql.includes('UPDATE catalog_ingredient_media') && params[1] === 'first.png') {
+ return async () => { demoted = true; await release.promise; };
+ }
+ };
+ const first = catalogDB.setPortraitMedia(id, 'first.png');
+ await vi.waitFor(() => expect(demoted).toBe(true));
+ const second = catalogDB.attachMedia(id, 'second.png', 'portrait', { caption: 'Selected' });
+ try {
+ await vi.waitFor(() => expect(locks).toBe(2));
+ } finally {
+ release.resolve();
+ await Promise.all([first, second]);
+ }
+ const live = await catalogDB.listMediaForIngredient(id);
+ expect(live.map((row) => row.mediaKey)).toEqual(['second.png']);
+ expect(live[0].caption).toBe('Selected');
+ const tombstones = await query(
+ 'SELECT media_key, deleted, deleted_at FROM catalog_ingredient_media WHERE ingredient_id = $1 AND media_key <> $2',
+ [id, 'second.png'],
+ );
+ expect(tombstones.rows).toHaveLength(existing ? 2 : 1);
+ expect(tombstones.rows.every((row) => row.deleted && row.deleted_at)).toBe(true);
+ });
+
+ it('serializes a generation completion with a local portrait write and retains provenance', async () => {
+ const id = await ingredient();
+ await catalogDB.setPortraitMedia(id, 'old.png');
+ let demoted = false;
+ const release = deferred();
+ let locks = 0;
+ intercept = async (sql, params) => {
+ if (sql.includes('FOR UPDATE')) locks += 1;
+ if (sql.includes('UPDATE catalog_ingredient_media') && params[1] === 'manual.png') {
+ return async () => { demoted = true; await release.promise; };
+ }
+ };
+ hook.initCatalogImageAttachHook();
+ const manual = catalogDB.setPortraitMedia(id, 'manual.png');
+ await vi.waitFor(() => expect(demoted).toBe(true));
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ params: { catalogAttach: { ingredientId: id, kind: 'portrait' } },
+ result: { filename: 'generated.png' },
+ });
+ try {
+ await vi.waitFor(() => expect(locks).toBe(2));
+ } finally {
+ release.resolve();
+ await manual;
+ }
+ await vi.waitFor(async () => {
+ const live = await catalogDB.listMediaForIngredient(id);
+ expect(live.map((row) => row.mediaKey)).toEqual(['generated.png']);
+ expect(live[0].metadata).toEqual({ prompt: 'Example portrait', seed: 42 });
+ });
+ });
+
+ it('rolls back demotion when insertion fails, and leaves other media kinds additive', async () => {
+ const id = await ingredient();
+ await catalogDB.setPortraitMedia(id, 'old.png', { metadata: { prompt: 'Original' } });
+ for (const kind of ['reference', 'audio', 'video', 'document']) {
+ await catalogDB.attachMedia(id, 'first-asset', kind);
+ await catalogDB.attachMedia(id, 'second-asset', kind);
+ }
+ intercept = async (sql) => {
+ if (sql.includes('INSERT INTO catalog_ingredient_media')) throw new Error('Injected insertion failure');
+ };
+ await expect(catalogDB.attachMedia(id, 'broken.png', 'portrait')).rejects.toThrow('Injected insertion failure');
+ const live = await catalogDB.listMediaForIngredient(id);
+ expect(live.filter((row) => row.kind === 'portrait')).toMatchObject([
+ { mediaKey: 'old.png', metadata: { prompt: 'Original' } },
+ ]);
+ for (const kind of ['reference', 'audio', 'video', 'document']) {
+ expect(live.filter((row) => row.kind === kind)).toHaveLength(2);
+ }
+ });
+});
diff --git a/server/services/catalogDB/media.js b/server/services/catalogDB/media.js
index 546c5eef7b..d2d6690179 100644
--- a/server/services/catalogDB/media.js
+++ b/server/services/catalogDB/media.js
@@ -8,7 +8,7 @@
* detach is a soft-delete so peers receive the tombstone.
*/
-import { query } from '../../lib/db.js';
+import { query, withTransaction } from '../../lib/db.js';
import { resolveImageInputPath } from '../../lib/fileUtils.js';
import { rowToMedia, groupRowsByIngredient } from './shared.js';
@@ -17,6 +17,13 @@ const hasMeaningfulMetadata = (value) => value && typeof value === 'object'
&& !Array.isArray(value) && Object.keys(value).length > 0;
export async function attachMedia(ingredientId, mediaKey, kind, options = {}) {
+ // Every local portrait entry point shares the replacement transaction,
+ // including the generic media API and file uploads.
+ if (kind === 'portrait') return setPortraitMedia(ingredientId, mediaKey, options);
+ return insertMedia(query, ingredientId, mediaKey, kind, options);
+}
+
+async function insertMedia(runQuery, ingredientId, mediaKey, kind, options) {
const { role = null, caption = null } = options;
// Metadata is additive on the wire and optional at the call boundary. When
// absent, leave an existing prompt untouched; a legacy attach/re-attach must
@@ -25,7 +32,7 @@ export async function attachMedia(ingredientId, mediaKey, kind, options = {}) {
const metadataColumn = hasMetadata ? ', metadata' : '';
const metadataPlaceholder = hasMetadata ? ', $6' : '';
const metadataUpdate = hasMetadata ? ', metadata = EXCLUDED.metadata' : '';
- const result = await query(
+ const result = await runQuery(
`INSERT INTO catalog_ingredient_media (ingredient_id, media_key, kind, role, caption${metadataColumn})
VALUES ($1, $2, $3, $4, $5${metadataPlaceholder})
ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE
@@ -53,22 +60,21 @@ export async function detachMedia(ingredientId, mediaKey, kind) {
);
}
-// Set THE portrait for an ingredient: attach `mediaKey` as kind 'portrait' and
-// demote any other live portrait. One active portrait per ingredient — the UI
-// renders it as the ingredient's avatar. Serialized as two statements; the
-// single-user trust model means no competing writer can interleave.
+// Lock the owning row even when there is no media yet. Both demotion and
+// attachment commit together, so overlapping HTTP/generation writes serialize
+// and a failed replacement leaves the previous portrait intact.
export async function setPortraitMedia(ingredientId, mediaKey, options = {}) {
- const { role = null, caption = null } = options;
- await query(
- `UPDATE catalog_ingredient_media
- SET deleted = true, deleted_at = NOW()
- WHERE ingredient_id = $1 AND kind = 'portrait'
- AND media_key <> $2 AND deleted = false`,
- [ingredientId, mediaKey],
- );
- const attachOptions = { role, caption };
- if (hasOwn(options, 'metadata')) attachOptions.metadata = options.metadata;
- return attachMedia(ingredientId, mediaKey, 'portrait', attachOptions);
+ return withTransaction(async (client) => {
+ await client.query('SELECT id FROM catalog_ingredients WHERE id = $1 FOR UPDATE', [ingredientId]);
+ await client.query(
+ `UPDATE catalog_ingredient_media
+ SET deleted = true, deleted_at = NOW()
+ WHERE ingredient_id = $1 AND kind = 'portrait'
+ AND media_key <> $2 AND deleted = false`,
+ [ingredientId, mediaKey],
+ );
+ return insertMedia(client.query.bind(client), ingredientId, mediaKey, 'portrait', options);
+ });
}
// Live (non-tombstoned) media rows for an ingredient's detail "Media" panel,
diff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.js
index 08d463a71e..787945e5e6 100644
--- a/server/services/catalogDBMedia.test.js
+++ b/server/services/catalogDBMedia.test.js
@@ -54,16 +54,18 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
vi.mock('./instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));
const catalogDB = await import('./catalogDB.js');
+const db = await import('../lib/db.js');
beforeEach(() => {
calls.length = 0;
vi.clearAllMocks();
+ db.withTransaction.mockImplementation((fn) => fn({ query: db.query }));
});
describe('attachMedia', () => {
it('upserts the tuple and revives a soft-deleted row on conflict', async () => {
await catalogDB.attachMedia('i1', 'hero.png', 'portrait', { role: 'hero', caption: 'cap' });
- const { sql, params } = calls[0];
+ const { sql, params } = calls.at(-1);
expect(sql).toMatch(/INSERT INTO catalog_ingredient_media/i);
expect(sql).toMatch(/ON CONFLICT \(ingredient_id, media_key, kind\) DO UPDATE/i);
expect(sql).toMatch(/deleted = false, deleted_at = NULL/i);
@@ -97,7 +99,8 @@ describe('detachMedia', () => {
describe('setPortraitMedia', () => {
it('demotes other live portraits then attaches the new one', async () => {
await catalogDB.setPortraitMedia('i1', 'new.png', { caption: 'now' });
- // First statement: demote other portraits.
+ expect(calls.shift().sql).toMatch(/SELECT id FROM catalog_ingredients WHERE id = \$1 FOR UPDATE/);
+ // Demote only after locking the owning ingredient.
expect(calls[0].sql).toMatch(/UPDATE catalog_ingredient_media SET deleted = true/i);
expect(calls[0].sql).toMatch(/kind = 'portrait'/i);
expect(calls[0].sql).toMatch(/media_key <> \$2/);
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index 7da788116e..421b391e17 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -23,6 +23,7 @@ export const DB_TEST_INCLUDE = [
'services/backup.db.test.js',
'services/catalogDB.test.js',
'services/catalogDB.facets.db.test.js',
+ 'services/catalogDB.media.db.test.js',
'services/catalogSync.tombstoneRevival.db.test.js',
'services/humanActivity.db.test.js',
'services/postRunDb.db.test.js',