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 canon→catalog projection freshness reads into one query (#3941)

[._.]/ Adam Eivy135408db5d50
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a41535bb7d..649cfba838 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -76,3 +76,4 @@
- Opening a job skill in the Prompt Manager now shows up in the URL. The Stages and Variables tabs already encode their selection as `?stage=` / `?var=`, but the Job Skills tab kept the open skill in local state, so the editor could not be linked or bookmarked and a reload — or a round-trip through another tab — dropped the user back on the "Select a job skill" placeholder. Selection now lives in `?skill=`, and a `selectedJobSkill`-keyed effect fetches the template and metadata, so `?tab=job-skills&skill=<name>` opens that skill's editor directly and a cleared param resets the panel.
- Exporting a catalog slice no longer issues three database queries per ingredient. `exportSliceForRef` hydrated scraps, refs and media one ingredient at a time, so a universe holding 100 ingredients cost 300 round-trips and pinned the connection pool for the length of the export. The three lookups are now batched with `WHERE ingredient_id = ANY($1)` and grouped in memory (`listScrapsForIngredients` / `listRefsForIngredients` / `listMediaForIngredients`, sharing `groupRowsByIngredient`), so one slice costs four queries regardless of how many ingredients it holds. The per-ingredient helpers stay on the same names and shapes — they now delegate to the batched query — and the exported payload, its ordering (scraps oldest-first, portraits ahead of other media) and its empty-array handling are unchanged.
- A failed job-skill save in the Prompt Manager no longer looks like a successful one. `saveJobSkill` sent the PUT with `{ silent: true }` and an empty `.catch(() => {})`, so a network blip, an auth failure, or a 500 dropped the edit on the floor while the Save button simply re-enabled — the exact shape of a save that worked. The failure now raises a toast naming the cause, a successful save confirms itself ("Job skill saved"), and the Preview button on the same panel likewise reports a failed render instead of leaving the preview panel blank with no explanation.
+- Saving a universe no longer issues one database read per canon entry. `projectToCatalog` — which runs synchronously inside `updateUniverse` to keep each catalog row in step with its embedded character/place/object entry — called `getIngredient` once per entry just to compare timestamps, so a universe with 50 canon items cost 50 single-row `SELECT`s before the first write, on the request the user is waiting on. The freshness lookup is now a single batched query (`getIngredientTimestamps`, `WHERE id = ANY($1)`, two columns rather than the whole jsonb row), with the loop-break guard applied before the batch so a guarded ingredient is never fetched at all. The LWW rule is unchanged (an entry at least as fresh as its row wins; an older one is skipped), missing rows still count as skipped instead of being confused with stale ones, and a per-entry write failure is still logged and skipped without aborting the rest of the pass.
diff --git a/server/services/catalogCanonProjection.batch.test.js b/server/services/catalogCanonProjection.batch.test.js
new file mode 100644
index 0000000000..500e4fca2d
--- /dev/null
+++ b/server/services/catalogCanonProjection.batch.test.js
@@ -0,0 +1,168 @@
+/**
+ * Unit tests for the BATCHED canon→catalog projection (#3941).
+ *
+ * `projectToCatalog` used to issue one `getIngredient` per embedded canon entry
+ * before deciding whether to write — N single-row SELECTs inside the
+ * synchronous `updateUniverse` request. It now issues ONE
+ * `getIngredientTimestamps` lookup for every candidate id and writes only the
+ * rows the LWW comparison says are stale.
+ *
+ * `catalogDB` is mocked wholesale (no Postgres): the assertions are the query
+ * COUNT + shape and that the skip/write accounting is byte-identical to the
+ * per-entry version. The live-DB round-trip (loop break, exactly-once writes)
+ * stays in `catalogCanonProjection.test.js`.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./catalogDB.js', () => ({
+ getIngredient: vi.fn(),
+ getIngredientTimestamps: vi.fn(),
+ updateIngredient: vi.fn(async () => ({})),
+ listRefsForIngredient: vi.fn(async () => []),
+}));
+
+const catalogDB = await import('./catalogDB.js');
+const { projectToCatalog } = await import('./catalogCanonProjection.js');
+
+const ROW_AT = '2026-02-01T00:00:00.000Z';
+const NEWER = '2026-03-01T00:00:00.000Z';
+const OLDER = '2026-01-01T00:00:00.000Z';
+
+// An embedded canon entry: the full bible payload plus the catalog backlink.
+const entry = (ingredientId, { name = 'Example Character', updatedAt = NEWER, ...rest } = {}) => ({
+ id: `entry-${ingredientId}`,
+ ingredientId,
+ name,
+ updatedAt,
+ createdAt: OLDER,
+ schemaVersion: 3,
+ ...rest,
+});
+
+const timestampMap = (pairs) => new Map(pairs);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ catalogDB.updateIngredient.mockResolvedValue({});
+});
+
+describe('projectToCatalog batching', () => {
+ it('issues ONE timestamp lookup for every canon array and no per-entry getIngredient', async () => {
+ catalogDB.getIngredientTimestamps.mockResolvedValue(timestampMap([
+ ['ing-c1', ROW_AT], ['ing-c2', ROW_AT], ['ing-p1', ROW_AT], ['ing-o1', ROW_AT],
+ ]));
+
+ const stats = await projectToCatalog('universe-1', {
+ characters: [entry('ing-c1'), entry('ing-c2')],
+ places: [entry('ing-p1')],
+ objects: [entry('ing-o1')],
+ });
+
+ expect(catalogDB.getIngredient).not.toHaveBeenCalled();
+ expect(catalogDB.getIngredientTimestamps).toHaveBeenCalledTimes(1);
+ expect(catalogDB.getIngredientTimestamps).toHaveBeenCalledWith(['ing-c1', 'ing-c2', 'ing-p1', 'ing-o1']);
+ expect(catalogDB.updateIngredient).toHaveBeenCalledTimes(4);
+ expect(stats).toEqual({ written: 4, skipped: 0 });
+ });
+
+ it('writes the stripped payload with the sync source, exactly as the per-entry version did', async () => {
+ catalogDB.getIngredientTimestamps.mockResolvedValue(timestampMap([['ing-c1', ROW_AT]]));
+
+ await projectToCatalog('universe-1', {
+ characters: [entry('ing-c1', { name: 'Renamed', role: 'Hero', tagline: 'Fake tagline' })],
+ });
+
+ expect(catalogDB.updateIngredient).toHaveBeenCalledWith(
+ 'ing-c1',
+ { name: 'Renamed', payload: { role: 'Hero', tagline: 'Fake tagline' } },
+ { source: 'sync', actor: 'canon-projection' },
+ );
+ });
+
+ it('keeps LWW: an embedded entry OLDER than its row is skipped, equal timestamps still write', async () => {
+ catalogDB.getIngredientTimestamps.mockResolvedValue(timestampMap([
+ ['ing-stale', ROW_AT], ['ing-equal', ROW_AT], ['ing-fresh', ROW_AT],
+ ]));
+
+ const stats = await projectToCatalog('universe-1', {
+ characters: [
+ entry('ing-stale', { updatedAt: OLDER }),
+ entry('ing-equal', { updatedAt: ROW_AT }),
+ entry('ing-fresh', { updatedAt: NEWER }),
+ ],
+ });
+
+ expect(catalogDB.updateIngredient.mock.calls.map(([id]) => id)).toEqual(['ing-equal', 'ing-fresh']);
+ expect(stats).toEqual({ written: 2, skipped: 1 });
+ });
+
+ it('skips an id the batch returned no row for (deleted / never existed)', async () => {
+ catalogDB.getIngredientTimestamps.mockResolvedValue(timestampMap([['ing-live', ROW_AT]]));
+
+ const stats = await projectToCatalog('universe-1', {
+ characters: [entry('ing-live'), entry('ing-gone')],
+ });
+
+ expect(catalogDB.updateIngredient).toHaveBeenCalledTimes(1);
+ expect(catalogDB.updateIngredient).toHaveBeenCalledWith('ing-live', expect.anything(), expect.anything());
+ expect(stats).toEqual({ written: 1, skipped: 1 });
+ });
+
+ it('excludes the guarded ingredient from the batch entirely (loop break)', async () => {
+ catalogDB.getIngredientTimestamps.mockResolvedValue(timestampMap([['ing-other', ROW_AT]]));
+
+ const stats = await projectToCatalog('universe-1', {
+ characters: [entry('ing-guarded'), entry('ing-other')],
+ }, { guardToken: 'ing-guarded' });
+
+ expect(catalogDB.getIngredientTimestamps).toHaveBeenCalledWith(['ing-other']);
+ expect(stats).toEqual({ written: 1, skipped: 1 });
+ });
+
+ it('queries nothing when no entry carries an ingredientId', async () => {
+ const stats = await projectToCatalog('universe-1', {
+ characters: [{ id: 'e1', name: 'Unlinked' }],
+ places: [],
+ });
+
+ expect(catalogDB.getIngredientTimestamps).not.toHaveBeenCalled();
+ expect(catalogDB.updateIngredient).not.toHaveBeenCalled();
+ expect(stats).toEqual({ written: 0, skipped: 0 });
+ });
+
+ it('counts every candidate as skipped when the batched lookup itself fails', async () => {
+ catalogDB.getIngredientTimestamps.mockRejectedValue(new Error('connection reset'));
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const stats = await projectToCatalog('universe-1', {
+ characters: [entry('ing-c1'), entry('ing-c2')],
+ });
+
+ expect(catalogDB.updateIngredient).not.toHaveBeenCalled();
+ expect(stats).toEqual({ written: 0, skipped: 2 });
+ expect(errSpy).toHaveBeenCalledTimes(1);
+ errSpy.mockRestore();
+ });
+
+ it('keeps a single failing write best-effort — the remaining entries still project', async () => {
+ catalogDB.getIngredientTimestamps.mockResolvedValue(timestampMap([['ing-bad', ROW_AT], ['ing-ok', ROW_AT]]));
+ catalogDB.updateIngredient.mockImplementation(async (id) => {
+ if (id === 'ing-bad') throw new Error('constraint violation');
+ return {};
+ });
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const stats = await projectToCatalog('universe-1', {
+ characters: [entry('ing-bad'), entry('ing-ok')],
+ });
+
+ expect(stats).toEqual({ written: 1, skipped: 1 });
+ errSpy.mockRestore();
+ });
+
+ it('returns an empty stat block for a non-object canonArrays', async () => {
+ expect(await projectToCatalog('universe-1', null)).toEqual({ written: 0, skipped: 0 });
+ expect(catalogDB.getIngredientTimestamps).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/catalogCanonProjection.js b/server/services/catalogCanonProjection.js
index 0c81742fc5..57db85e82d 100644
--- a/server/services/catalogCanonProjection.js
+++ b/server/services/catalogCanonProjection.js
@@ -40,13 +40,10 @@
*/
import * as catalogDB from './catalogDB.js';
-import { BIBLE_KIND, BIBLE_FIELD } from '../lib/storyBible.js';
+import { BIBLE_FIELD } from '../lib/storyBible.js';
-// Catalog `type` ↔ canon array key, derived from the bible registry so a future
-// kind added there flows through without editing this file.
-const TYPE_FOR_ARRAY = Object.freeze(
- Object.fromEntries(Object.values(BIBLE_KIND).map((k) => [BIBLE_FIELD[k], k])),
-);
+// Canon array keys, derived from the bible registry so a future kind added
+// there flows through without editing this file.
const CANON_ARRAY_KEYS = Object.freeze(Object.values(BIBLE_FIELD));
// Fields that live on the embedded canon entry but are NOT part of the catalog
@@ -160,9 +157,13 @@ export async function projectToCatalog(universeId, canonArrays, { guardToken = n
const stats = { written: 0, skipped: 0 };
if (!canonArrays || typeof canonArrays !== 'object') return stats;
+ // Pass 1 — collect the candidate entries across every canon array and apply
+ // the loop break up front, so the batched lookup below asks only for rows we
+ // could actually write. A universe with N canon entries used to cost N
+ // single-row SELECTs here (#3941); it now costs one.
+ const candidates = [];
for (const arrayKey of CANON_ARRAY_KEYS) {
const list = Array.isArray(canonArrays[arrayKey]) ? canonArrays[arrayKey] : [];
- const type = TYPE_FOR_ARRAY[arrayKey];
for (const entry of list) {
const ingredientId = entry?.ingredientId;
if (!ingredientId) continue;
@@ -172,25 +173,49 @@ export async function projectToCatalog(universeId, canonArrays, { guardToken = n
stats.skipped++;
continue;
}
- try {
- const row = await catalogDB.getIngredient(ingredientId);
- if (!row) { stats.skipped++; continue; }
- // LWW on updatedAt — only overwrite the catalog row when the embedded
- // entry is at-least-as-fresh. An older embedded snapshot (e.g. a
- // concurrent catalog edit won) is left alone.
- const entryAt = Date.parse(entry.updatedAt || '') || 0;
- const rowAt = Date.parse(row.updatedAt || '') || 0;
- if (entryAt < rowAt) { stats.skipped++; continue; }
- await catalogDB.updateIngredient(
- ingredientId,
- { name: entry.name, payload: entryToPayload(entry) },
- { source: 'sync', actor: 'canon-projection' },
- );
- stats.written++;
- } catch (err) {
- console.error(`🔁 projectToCatalog: ingredient ${ingredientId} update failed: ${err.message}`);
- stats.skipped++;
- }
+ candidates.push({ ingredientId, entry });
+ }
+ }
+ if (candidates.length === 0) return stats;
+
+ // ONE query for every candidate's freshness. A lookup failure is fatal to the
+ // whole projection pass (there is no per-entry state to fall back on), so it
+ // is logged once and every candidate counts as skipped — same best-effort
+ // contract the per-entry catch below keeps.
+ const timestamps = await catalogDB.getIngredientTimestamps(
+ candidates.map((c) => c.ingredientId),
+ ).catch((err) => {
+ console.error(`🔁 projectToCatalog: batched lookup of ${candidates.length} ingredients failed: ${err.message}`);
+ return null;
+ });
+ if (!timestamps) {
+ stats.skipped += candidates.length;
+ return stats;
+ }
+
+ // Pass 2 — write only the rows the LWW comparison says are stale. Sequential
+ // by design: each updateIngredient is a multi-statement write (sanitize +
+ // update + revision), and firing N of them at once would trade the read
+ // stampede this fix removed for a write one.
+ for (const { ingredientId, entry } of candidates) {
+ const rowUpdatedAt = timestamps.get(ingredientId);
+ if (rowUpdatedAt === undefined) { stats.skipped++; continue; } // no live row
+ // LWW on updatedAt — only overwrite the catalog row when the embedded entry
+ // is at-least-as-fresh. An older embedded snapshot (e.g. a concurrent
+ // catalog edit won) is left alone.
+ const entryAt = Date.parse(entry.updatedAt || '') || 0;
+ const rowAt = Date.parse(rowUpdatedAt || '') || 0;
+ if (entryAt < rowAt) { stats.skipped++; continue; }
+ try {
+ await catalogDB.updateIngredient(
+ ingredientId,
+ { name: entry.name, payload: entryToPayload(entry) },
+ { source: 'sync', actor: 'canon-projection' },
+ );
+ stats.written++;
+ } catch (err) {
+ console.error(`🔁 projectToCatalog: ingredient ${ingredientId} update failed: ${err.message}`);
+ stats.skipped++;
}
}
return stats;
diff --git a/server/services/catalogDB.ingredientTimestamps.test.js b/server/services/catalogDB.ingredientTimestamps.test.js
new file mode 100644
index 0000000000..f33c51690c
--- /dev/null
+++ b/server/services/catalogDB.ingredientTimestamps.test.js
@@ -0,0 +1,69 @@
+/**
+ * Unit tests for `getIngredientTimestamps` (#3941) — the batched freshness
+ * lookup the canon→catalog projection uses instead of N `getIngredient` calls.
+ *
+ * Postgres is mocked: the assertions are the SQL shape (one `= ANY($1)` query,
+ * live rows only, two columns) and the sentinel contract — a MISSING map key
+ * means "no live row", never "row with no timestamp".
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const calls = [];
+const ROWS = [
+ { id: 'ing-1', updated_at: new Date('2026-02-01T00:00:00Z') },
+ { id: 'ing-2', updated_at: new Date('2026-03-02T03:04:05Z') },
+];
+
+vi.mock('../lib/db.js', () => ({
+ query: vi.fn(async (sql, params) => {
+ const flat = sql.replace(/\s+/g, ' ').trim();
+ calls.push({ sql: flat, params });
+ return { rows: ROWS.filter((r) => params[0].includes(r.id)) };
+ }),
+ withTransaction: vi.fn(),
+ pgvectorToArray: vi.fn(() => null),
+ arrayToPgvector: vi.fn(),
+}));
+
+// instances.getInstanceId is pulled in transitively by catalogDB — stub it.
+vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));
+
+const catalogDB = await import('./catalogDB.js');
+
+beforeEach(() => {
+ calls.length = 0;
+ vi.clearAllMocks();
+});
+
+describe('getIngredientTimestamps (#3941)', () => {
+ it('resolves N ids in ONE live-rows-only query and returns ISO strings', async () => {
+ const map = await catalogDB.getIngredientTimestamps(['ing-1', 'ing-2']);
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0].sql).toBe(
+ 'SELECT id, updated_at FROM catalog_ingredients WHERE id = ANY($1) AND deleted = false',
+ );
+ expect(calls[0].params).toEqual([['ing-1', 'ing-2']]);
+ expect(map.get('ing-1')).toBe('2026-02-01T00:00:00.000Z');
+ expect(map.get('ing-2')).toBe('2026-03-02T03:04:05.000Z');
+ });
+
+ it('de-duplicates ids and drops falsy ones before querying', async () => {
+ await catalogDB.getIngredientTimestamps(['ing-1', 'ing-1', null, undefined, '', 'ing-2']);
+ expect(calls[0].params).toEqual([['ing-1', 'ing-2']]);
+ });
+
+ it('omits ids with no live row rather than mapping them to a null timestamp', async () => {
+ const map = await catalogDB.getIngredientTimestamps(['ing-1', 'ing-missing']);
+ expect(map.has('ing-missing')).toBe(false);
+ expect(map.size).toBe(1);
+ });
+
+ it('short-circuits an empty / undefined id list without touching the database', async () => {
+ expect(await catalogDB.getIngredientTimestamps([])).toEqual(new Map());
+ expect(await catalogDB.getIngredientTimestamps()).toEqual(new Map());
+ expect(await catalogDB.getIngredientTimestamps([null])).toEqual(new Map());
+ expect(calls).toHaveLength(0);
+ });
+});
diff --git a/server/services/catalogDB/ingredients.js b/server/services/catalogDB/ingredients.js
index ddbe876b18..bded91a692 100644
--- a/server/services/catalogDB/ingredients.js
+++ b/server/services/catalogDB/ingredients.js
@@ -95,6 +95,24 @@ export async function getIngredient(id) {
return rowToIngredient(result.rows[0]);
}
+/**
+ * Batched freshness lookup for LWW comparisons (#3941) — ONE query for N ids
+ * instead of N `getIngredient` round-trips. Returns
+ * `Map<id, updatedAt ISO string>` holding an entry ONLY for live (non-deleted)
+ * rows, so a MISSING key means "no such row" — distinct from a row that exists
+ * and happens to be stale. Selects two columns, not `*`: the canon→catalog
+ * projection needs existence + freshness, never the jsonb payload.
+ */
+export async function getIngredientTimestamps(ingredientIds) {
+ const ids = [...new Set((ingredientIds || []).filter(Boolean))];
+ if (ids.length === 0) return new Map();
+ const result = await query(
+ `SELECT id, updated_at FROM catalog_ingredients WHERE id = ANY($1) AND deleted = false`,
+ [ids],
+ );
+ return new Map(result.rows.map((row) => [row.id, row.updated_at.toISOString()]));
+}
+
// `{ source, actor }` drive the revision-history row written on a content
// change. `source` is one of user|extract|refine|sync (default 'user'); `actor`
// is an optional free label (agent run id, provider). Embedding-only patches