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: batch catalog export-slice hydration into 4 queries instead of 3N (#3940)
[._.]/ Adam Eivyeab437514db2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a94a989c70..754df16f18 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -74,3 +74,4 @@- "Refresh quota" on the Quota Burn page no longer blanks the page or hides a failed re-scrape. The handler flipped the same `loading` flag as the first read, so every family card, control, and status number was replaced by a full-page "Loading burn plan…" spinner for the length of a 10–20s PTY quota scrape — and because the read's error was swallowed, a scrape that timed out simply put the stale numbers back with nothing saying they were stale. The refresh now reports itself on the button that asked for it (spinning icon, "Refreshing…", disabled) while the plan stays on screen, and a failure raises a toast naming the cause. The unavailable-state Retry button shares the same path; it stays banner-only there, since the banner already names the error.- A failed job-catalog read on the Quota Burn page no longer empties the config form silently. The fetch was `.catch(() => {})`, so a 500 or a network blip left the catalog at its empty default: the "Add a preset job" picker returned null and vanished, "Add job" sat disabled, and every job row's Job Type / Apps / Universes / Image Modes dropdown rendered blank — with nothing on screen naming a cause, and editing a step in that state saving `jobType: ""` into a 400 that stalls the whole save. The catalog read now keeps its failure in its own state (with a 200 carrying zero job types reported as its own distinct cause rather than as a successful load), and an expanded family card renders an inline warning banner naming it with a "Retry catalog load" button that re-reads the catalog in place — no browser reload, and the plan itself stays on screen throughout.- 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.diff --git a/server/services/catalogDB.exportSlice.test.js b/server/services/catalogDB.exportSlice.test.jsnew file mode 100644index 0000000000..af1685f729--- /dev/null+++ b/server/services/catalogDB.exportSlice.test.js@@ -0,0 +1,164 @@+/**+ * Unit tests for the BATCHED export-slice hydration (#3940).+ *+ * `exportSliceForRef` used to issue three queries per ingredient (scraps, refs,+ * media) — 3N round-trips for an N-ingredient universe. It now issues four+ * queries total, regardless of N. Postgres is mocked: the fake `query` routes on+ * the SQL text, so the suite asserts BOTH the query count and that the payload+ * shape / ordering is byte-identical to the per-ingredient version.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const calls = [];+// Flipped by the empty-slice test so the mocked ref lookup returns no rows+// while still recording its call (mockResolvedValueOnce would bypass the+// recorder and make the "how many queries ran" assertion meaningless).+const sliceIsEmpty = { value: false };++const ingredientRow = (id, name, role) => ({+ id,+ type: 'character',+ name,+ payload: {},+ tags: [],+ embedding: null,+ created_at: new Date('2026-01-01T00:00:00Z'),+ updated_at: new Date('2026-01-01T00:00:00Z'),+ role,+ ref_created_at: new Date('2026-01-01T00:00:00Z'),+});++const scrapRow = (ingredientId, id, createdAt) => ({+ ingredient_id: ingredientId,+ id,+ title: `Scrap ${id}`,+ raw_text: `raw ${id}`,+ source_kind: 'paste',+ metadata: null,+ created_at: new Date(createdAt),+ updated_at: new Date(createdAt),+});++const refRow = (ingredientId, refId) => ({+ ingredient_id: ingredientId,+ ref_kind: 'universe',+ ref_id: refId,+ role: 'cast',+ created_at: new Date('2026-01-01T00:00:00Z'),+ deleted: false,+ deleted_at: null,+ sync_sequence: 1,+});++const mediaRow = (ingredientId, mediaKey, kind) => ({+ ingredient_id: ingredientId,+ media_key: mediaKey,+ kind,+ role: null,+ caption: null,+ created_at: new Date('2026-01-01T00:00:00Z'),+ deleted: false,+ deleted_at: null,+ sync_sequence: 1,+});++// Two ingredients: i1 has 2 scraps / 1 ref / 2 media, i2 has none of any.+const INGREDIENT_ROWS = [ingredientRow('i1', 'Alpha', 'cast'), ingredientRow('i2', 'Beta', 'mentioned')];+const SCRAP_ROWS = [+ scrapRow('i1', 's-old', '2026-01-01T00:00:00Z'),+ scrapRow('i1', 's-new', '2026-02-01T00:00:00Z'),+];+const REF_ROWS = [refRow('i1', 'uni-1')];+const MEDIA_ROWS = [mediaRow('i1', 'portrait.png', 'portrait'), mediaRow('i1', 'ref.png', 'reference')];++vi.mock('../lib/db.js', () => ({+ query: vi.fn(async (sql, params) => {+ const flat = sql.replace(/\s+/g, ' ').trim();+ calls.push({ sql: flat, params });+ if (flat.includes('FROM catalog_ingredients i')) return { rows: sliceIsEmpty.value ? [] : INGREDIENT_ROWS };+ if (flat.includes('FROM catalog_scraps s')) return { rows: SCRAP_ROWS };+ if (flat.includes('FROM catalog_ingredient_refs')) return { rows: REF_ROWS };+ if (flat.includes('FROM catalog_ingredient_media')) return { rows: MEDIA_ROWS };+ return { rows: [] };+ }),+ 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('exportSliceForRef batching (#3940)', () => {+ it('issues exactly four queries regardless of ingredient count', async () => {+ await catalogDB.exportSliceForRef('universe', 'uni-1');+ expect(calls).toHaveLength(4);+ // Three of them are the batched ANY($1) hydration queries.+ const batched = calls.filter((c) => c.sql.includes('= ANY($1)'));+ expect(batched).toHaveLength(3);+ for (const c of batched) expect(c.params[0]).toEqual(['i1', 'i2']);+ });++ it('groups the batched rows back onto their ingredients', async () => {+ const bundle = await catalogDB.exportSliceForRef('universe', 'uni-1');+ expect(bundle.ref).toEqual({ kind: 'universe', id: 'uni-1' });+ const [alpha, beta] = bundle.ingredients;+ expect(alpha.id).toBe('i1');+ expect(alpha.roleForExportedRef).toBe('cast');+ expect(alpha.scraps.map((s) => s.id)).toEqual(['s-old', 's-new']); // per-ingredient order kept+ expect(alpha.refs).toEqual([expect.objectContaining({ refId: 'uni-1', role: 'cast' })]);+ expect(alpha.media.map((m) => m.mediaKey)).toEqual(['portrait.png', 'ref.png']);+ // An ingredient with no rows in any batch gets empty arrays, not undefined.+ expect(beta.id).toBe('i2');+ expect(beta.roleForExportedRef).toBe('mentioned');+ expect(beta.scraps).toEqual([]);+ expect(beta.refs).toEqual([]);+ expect(beta.media).toEqual([]);+ });++ it('strips embeddings from the exported ingredients', async () => {+ const bundle = await catalogDB.exportSliceForRef('universe', 'uni-1');+ for (const ing of bundle.ingredients) expect(ing).not.toHaveProperty('embedding');+ });++ it('skips the hydration queries entirely for an empty slice', async () => {+ sliceIsEmpty.value = true;+ const bundle = await catalogDB.exportSliceForRef('universe', 'empty');+ sliceIsEmpty.value = false;+ expect(bundle.ingredients).toEqual([]);+ expect(calls).toHaveLength(1); // just listIngredientsForRef+ });+});++describe('batched list helpers', () => {+ it('listScrapsForIngredients keys every requested id, empty when it has none', async () => {+ const byId = await catalogDB.listScrapsForIngredients(['i1', 'i2']);+ expect([...byId.keys()]).toEqual(['i1', 'i2']);+ expect(byId.get('i1').map((s) => s.rawText)).toEqual(['raw s-old', 'raw s-new']);+ expect(byId.get('i2')).toEqual([]);+ });++ it('de-dupes repeated ids and issues no query for an empty id list', async () => {+ const byId = await catalogDB.listMediaForIngredients(['i1', 'i1']);+ expect(calls[0].params[0]).toEqual(['i1']);+ expect(byId.get('i1')).toHaveLength(2);+ calls.length = 0;+ expect(await catalogDB.listRefsForIngredients([])).toEqual(new Map());+ expect(calls).toHaveLength(0);+ });++ it('the singular helpers still return a plain array', async () => {+ expect(await catalogDB.listRefsForIngredient('i1')).toEqual([+ expect.objectContaining({ ingredientId: 'i1', refId: 'uni-1' }),+ ]);+ expect(await catalogDB.listScrapsForIngredient('i2')).toEqual([]);+ });+});diff --git a/server/services/catalogDB/facets.js b/server/services/catalogDB/facets.jsindex d0504bd8b0..7fe72674a9 100644--- a/server/services/catalogDB/facets.js+++ b/server/services/catalogDB/facets.js@@ -8,35 +8,48 @@*/import { query } from '../../lib/db.js';-import { rowToRef, rowToIngredient, liveHomingTargetSql, HOMING_REF_KINDS_SQL } from './shared.js';-import { listIngredientsForRef, listRefsForIngredient } from './refs.js';-import { listMediaForIngredient } from './media.js';+import { rowToRef, rowToIngredient, liveHomingTargetSql, HOMING_REF_KINDS_SQL, groupRowsByIngredient } from './shared.js';+import { listIngredientsForRef, listRefsForIngredients } from './refs.js';+import { listMediaForIngredients } from './media.js';++const rowToExportScrap = (row) => ({+ id: row.id,+ title: row.title,+ rawText: row.raw_text,+ sourceKind: row.source_kind,+ metadata: row.metadata || {},+ createdAt: row.created_at.toISOString(),+ updatedAt: row.updated_at.toISOString(),+});/**- * Hydrate one ingredient with its scraps for the export bundle. Issues two- * queries: the sources join to look up the scrap ids, then a single batch- * lookup of those scraps. Returns `[]` when an ingredient has no sources.+ * Hydrate one ingredient with its live scraps for the export bundle, oldest+ * first. Returns `[]` when an ingredient has no sources.*/export async function listScrapsForIngredient(ingredientId) {+ const byIngredient = await listScrapsForIngredients([ingredientId]);+ return byIngredient.get(ingredientId);+}++// Batched `listScrapsForIngredient` for bulk hydration paths (#3940) — ONE+// query for N ingredients instead of N. `src.ingredient_id` comes back on each+// row purely to group by; the outer sort key doesn't disturb the per-ingredient+// `created_at ASC` order. Returns `Map<ingredientId, scraps[]>` with an entry+// (possibly `[]`) for every id.+export async function listScrapsForIngredients(ingredientIds) {+ const ids = [...new Set(ingredientIds)];+ if (ids.length === 0) return new Map();const result = await query(- `SELECT s.id, s.title, s.raw_text, s.source_kind, s.metadata,+ `SELECT src.ingredient_id, s.id, s.title, s.raw_text, s.source_kind, s.metadata,s.created_at, s.updated_atFROM catalog_scraps sJOIN catalog_ingredient_sources src ON src.scrap_id = s.id- WHERE src.ingredient_id = $1+ WHERE src.ingredient_id = ANY($1)AND s.deleted = false- ORDER BY s.created_at ASC`,- [ingredientId],+ ORDER BY src.ingredient_id, s.created_at ASC`,+ [ids],);- return result.rows.map((row) => ({- id: row.id,- title: row.title,- rawText: row.raw_text,- sourceKind: row.source_kind,- metadata: row.metadata || {},- createdAt: row.created_at.toISOString(),- updatedAt: row.updated_at.toISOString(),- }));+ return groupRowsByIngredient(ids, result.rows, rowToExportScrap);}/**@@ -49,14 +62,16 @@ export async function listScrapsForIngredient(ingredientId) {*/export async function exportSliceForRef(refKind, refId) {const rows = await listIngredientsForRef(refKind, refId);- // Hydrate scraps + refs + media in parallel per ingredient. Small N (one- // slice is typically <100 ingredients); a per-row round-trip is fine.- const ingredients = await Promise.all(rows.map(async ({ ingredient, role }) => {- const [scraps, refs, media] = await Promise.all([- listScrapsForIngredient(ingredient.id),- listRefsForIngredient(ingredient.id),- listMediaForIngredient(ingredient.id),- ]);+ // Hydrate scraps + refs + media for the WHOLE slice in three batched queries+ // (#3940) — a per-ingredient round-trip made this 3N queries, which pinned the+ // connection pool on a large universe. Four queries total, regardless of N.+ const ingredientIds = rows.map(({ ingredient }) => ingredient.id);+ const [scrapsById, refsById, mediaById] = await Promise.all([+ listScrapsForIngredients(ingredientIds),+ listRefsForIngredients(ingredientIds),+ listMediaForIngredients(ingredientIds),+ ]);+ const ingredients = rows.map(({ ingredient, role }) => {const { embedding: _embedding, ...rest } = ingredient;return {...rest,@@ -64,11 +79,11 @@ export async function exportSliceForRef(refKind, refId) {// round-trip re-imports that want to preserve roleness without// re-deriving it from the full refs list.roleForExportedRef: role,- refs,- scraps,- media,+ refs: refsById.get(ingredient.id) || [],+ scraps: scrapsById.get(ingredient.id) || [],+ media: mediaById.get(ingredient.id) || [],};- }));+ });return {version: 1,ref: { kind: refKind, id: refId },diff --git a/server/services/catalogDB/media.js b/server/services/catalogDB/media.jsindex 74d79435ee..4469a48b14 100644--- a/server/services/catalogDB/media.js+++ b/server/services/catalogDB/media.js@@ -9,7 +9,7 @@import { query } from '../../lib/db.js';import { resolveImageInputPath } from '../../lib/fileUtils.js';-import { rowToMedia } from './shared.js';+import { rowToMedia, groupRowsByIngredient } from './shared.js';export async function attachMedia(ingredientId, mediaKey, kind, { role = null, caption = null } = {}) {const result = await query(@@ -55,13 +55,25 @@ export async function setPortraitMedia(ingredientId, mediaKey, { role = null, ca// Live (non-tombstoned) media rows for an ingredient's detail "Media" panel,// newest first. Portrait(s) first so the avatar is easy to pluck off the head.export async function listMediaForIngredient(ingredientId) {+ const byIngredient = await listMediaForIngredients([ingredientId]);+ return byIngredient.get(ingredientId);+}++// Batched `listMediaForIngredient` for bulk hydration paths (#3940) — ONE query+// for N ingredients instead of N. Same live filter and same per-ingredient+// ordering (portraits first, then newest-first); the outer `ingredient_id` sort+// key only groups the rows, it doesn't reorder within a group. Returns+// `Map<ingredientId, media[]>` with an entry (possibly `[]`) for every id.+export async function listMediaForIngredients(ingredientIds) {+ const ids = [...new Set(ingredientIds)];+ if (ids.length === 0) return new Map();const result = await query(`SELECT * FROM catalog_ingredient_media- WHERE ingredient_id = $1 AND deleted = false- ORDER BY (kind = 'portrait') DESC, created_at DESC`,- [ingredientId],+ WHERE ingredient_id = ANY($1) AND deleted = false+ ORDER BY ingredient_id, (kind = 'portrait') DESC, created_at DESC`,+ [ids],);- return result.rows.map(rowToMedia);+ return groupRowsByIngredient(ids, result.rows, rowToMedia);}// The media kinds whose `media_key` resolves against the image library today.diff --git a/server/services/catalogDB/refs.js b/server/services/catalogDB/refs.jsindex 964fd3acbe..5c4cb7559c 100644--- a/server/services/catalogDB/refs.js+++ b/server/services/catalogDB/refs.js@@ -12,7 +12,7 @@import { query } from '../../lib/db.js';import { resolveRefs } from '../catalogRefResolver.js';-import { rowToRef, rowToSource, rowToIngredient } from './shared.js';+import { rowToRef, rowToSource, rowToIngredient, groupRowsByIngredient } from './shared.js';// `{ client }` is optional — see the createIngredient comment. Passing the same// client used to insert the ingredient row keeps the source-link row in the@@ -124,11 +124,23 @@ export async function listRefsForIngredient(ingredientId) {// Filter `deleted = false` so the "Appears in" panel doesn't surface// tombstoned unlinks. Tombstones are read-only state for sync purposes;// user-facing list paths only show live links.+ const byIngredient = await listRefsForIngredients([ingredientId]);+ return byIngredient.get(ingredientId);+}++// Batched `listRefsForIngredient` for bulk hydration paths (#3940) — ONE query+// for N ingredients instead of N, with the same `deleted = false` live filter.+// Returns `Map<ingredientId, refs[]>` with an entry (possibly `[]`) for every id.+export async function listRefsForIngredients(ingredientIds) {+ const ids = [...new Set(ingredientIds)];+ if (ids.length === 0) return new Map();const result = await query(- `SELECT * FROM catalog_ingredient_refs WHERE ingredient_id = $1 AND deleted = false`,- [ingredientId],+ `SELECT * FROM catalog_ingredient_refs+ WHERE ingredient_id = ANY($1) AND deleted = false+ ORDER BY ingredient_id`,+ [ids],);- return result.rows.map(rowToRef);+ return groupRowsByIngredient(ids, result.rows, rowToRef);}// Like listRefsForIngredient, but drops refs whose TARGET no longer resolves todiff --git a/server/services/catalogDB/shared.js b/server/services/catalogDB/shared.jsindex 162c8e710c..91d0d9e351 100644--- a/server/services/catalogDB/shared.js+++ b/server/services/catalogDB/shared.js@@ -208,6 +208,24 @@ export function rowToRevision(row) {};}+// Group the rows of a batched `WHERE ingredient_id = ANY($1)` fetch into a+// `Map<ingredientId, mapped[]>`, preserving the SQL result order within each+// group (so a per-ingredient ORDER BY carries through the batching unchanged).+// `ids` seeds the map so every requested id has an entry — a caller can read+// `map.get(id)` without a `?? []` fallback and an ingredient with no rows still+// gets `[]` rather than `undefined`.+export function groupRowsByIngredient(ids, rows, mapRow) {+ const grouped = new Map(ids.map((id) => [id, []]));+ for (const row of rows) {+ const bucket = grouped.get(row.ingredient_id);+ // Defensive: a row for an id we didn't ask for can't come back from+ // `= ANY($1)`, but don't drop it on the floor if the query ever widens.+ if (bucket) bucket.push(mapRow(row));+ else grouped.set(row.ingredient_id, [mapRow(row)]);+ }+ return grouped;+}+// Ref kinds that "home" an ingredient — i.e. drive the linked / unlinked (Raw) /// orphaned bucket classification + the Orphaned album. universe/series define// album membership; creative-director joined this set in #1812 so a CD project's