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: load media collection covers and picker memberships in batches (#8516)
[._.]/ Adam Eivyb950b88ee29f
diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.jsindex 52d0d7eb3f..e89932ba80 100644--- a/server/services/mediaAssetIndex/db.js+++ b/server/services/mediaAssetIndex/db.js@@ -215,6 +215,62 @@ export async function listMixedGalleryPage({counts: { image, video, all: image + video } };}+/** Batch cover selection: membership ordinals retain stable added-at ordering.+ * Only addressing fields cross the video-history boundary; prompts never enter SQL.+ * Hidden assets remain eligible here, just as on the collection grid.+ */+export async function collectionCovers(collections, videos) {+ const videoRows = videos.map(({ id, filename, createdAt, hidden, thumbnail }) => ({+ id, filename, hidden, thumbnail,+ createdAt: Number.isFinite(Date.parse(createdAt)) ? new Date(createdAt).toISOString() : new Date(0).toISOString(),+ }));+ const result = await query(`WITH collections AS MATERIALIZED (+ SELECT * FROM jsonb_to_recordset($1::jsonb) AS c(id text, "coverKey" text, keys jsonb)+ ), memberships AS MATERIALIZED (+ SELECT c.id, c."coverKey", k.key, k.ordinal+ FROM collections c CROSS JOIN LATERAL jsonb_array_elements_text(c.keys) WITH ORDINALITY AS k(key, ordinal)+ ), assets AS MATERIALIZED (+ SELECT media_key, kind, ref, data->>'filename' AS filename, created_at,+ COALESCE(NULLIF(data->>'path', ''), '/data/images/' || (data->>'filename')) AS cover+ FROM media_assets WHERE kind = 'image'+ UNION ALL+ SELECT 'video:' || v.id, 'video', v.id, v.filename, v."createdAt"::timestamptz,+ '/data/video-thumbnails/' || NULLIF(v.thumbnail, '')+ FROM jsonb_to_recordset($2::jsonb) AS v(id text, filename text, "createdAt" text, thumbnail text)+ ), covers AS (+ SELECT DISTINCT ON (m.id) m.id, a.cover+ FROM memberships m JOIN assets a ON a.media_key = m.key+ WHERE a.kind = 'image' OR a.cover IS NOT NULL+ ORDER BY m.id,+ (CASE WHEN a.kind = CASE WHEN m."coverKey" LIKE 'image:%' THEN 'image' ELSE 'video' END+ AND (a.ref = substring(m."coverKey" FROM length(a.kind) + 2)+ OR a.filename = substring(m."coverKey" FROM length(a.kind) + 2)) THEN 0 ELSE 1 END),+ m.ordinal, a.media_key+ ), unsorted AS MATERIALIZED (+ SELECT a.* FROM assets a WHERE NOT EXISTS (SELECT 1 FROM memberships m WHERE m.key = a.media_key)+ )+ SELECT c.id, covers.cover, NULL::bigint AS image, NULL::bigint AS video+ FROM collections c LEFT JOIN covers ON covers.id = c.id+ UNION ALL+ SELECT 'unsorted',+ (SELECT cover FROM unsorted WHERE kind = 'image' OR cover IS NOT NULL ORDER BY created_at DESC, media_key ASC LIMIT 1),+ COUNT(*) FILTER (WHERE kind = 'image'), COUNT(*) FILTER (WHERE kind = 'video')+ FROM unsorted`, [JSON.stringify(collections), JSON.stringify(videoRows)]);+ return result.rows;+}++/** Picker membership only needs existence, never covers, counts or video history. */+export async function visibleImageCollections(collections) {+ const memberships = collections.flatMap(collection => (collection.items || [])+ .filter(item => item.kind === 'image').map(item => ({ id: collection.id, key: `image:${item.ref}` })));+ const result = await query(`SELECT DISTINCT m.id+ FROM jsonb_to_recordset($1::jsonb) AS m(id text, key text)+ JOIN media_assets a ON a.media_key = m.key+ WHERE a.kind = 'image' AND COALESCE(a.data->>'hidden', 'false') <> 'true'`, [JSON.stringify(memberships)]);+ const populated = new Set(result.rows.map(row => row.id));+ return collections.filter(collection => populated.has(collection.id)).map(({ id, name }) => ({ id, name }));+}+/** Compact global picker options, independent of the loaded page/search. */export async function galleryFacets() {const fields = ['universeId', 'universeName', 'entryCategory', 'entryKind'];diff --git a/server/services/mediaAssetIndex/gallery.js b/server/services/mediaAssetIndex/gallery.jsindex f756462ac3..ca60a6ea66 100644--- a/server/services/mediaAssetIndex/gallery.js+++ b/server/services/mediaAssetIndex/gallery.js@@ -1,6 +1,6 @@import { mapWithConcurrency } from '../../lib/mapWithConcurrency.js';import { isTestRunner } from '../../lib/runtimeEnv.js';-import { listAssets, countAssets, galleryFacets, listMixedGalleryPage } from './db.js';+import { listAssets, countAssets, galleryFacets, listMixedGalleryPage, collectionCovers, visibleImageCollections } from './db.js';const escapeHatch = () => process.env.MEMORY_BACKEND === 'file' || isTestRunner();const keyFor = ({ kind, data }) => `${kind}:${kind === 'image' ? data.filename : data.id}`;@@ -133,7 +133,7 @@ export async function listGalleryFacets(diskReader) {if (text(row.entryKind)) kinds.add(row.entryKind);}const collections = await (await import('../mediaCollections.js')).listCollections();- const populated = await mapWithConcurrency(collections, 4, async collection => {+ const populated = !escapeHatch() ? await visibleImageCollections(collections) : await mapWithConcurrency(collections, 4, async collection => {const page = await listGalleryPage({ collectionId: collection.id, collectionSnapshot: collections, hidden: false, limit: 1 }, diskReader);return page.total ? { id: collection.id, name: collection.name } : null;});@@ -145,6 +145,20 @@ export async function listGalleryFacets(diskReader) {export async function listGalleryCollectionSummaries(diskReader) {const collections = await (await import('../mediaCollections.js')).listCollections();const videoSnapshot = await (await import('../videoGen/history.js')).loadHistory();+ if (!escapeHatch()) {+ const rows = await collectionCovers(collections.map(collection => ({+ id: collection.id, coverKey: collection.coverKey,+ keys: [...(collection.items || [])].sort((a, b) => time(b.addedAt) - time(a.addedAt)).map(keyForRef),+ })), videoSnapshot);+ const covers = new Map(rows.map(row => [row.id, row]));+ return [{ id: 'unsorted' }, ...collections].map(collection => {+ const row = covers.get(collection.id);+ const counts = collection.id === 'unsorted'+ ? { image: Number(row.image), video: Number(row.video), all: Number(row.image) + Number(row.video) }+ : (collection.items || []).reduce((result, item) => { result[item.kind]++; return result; }, { image: 0, video: 0 });+ return { id: collection.id, counts, total: counts.image + counts.video, cover: row?.cover ?? null };+ });+ }const summaries = await mapWithConcurrency([{ id: 'unsorted' }, ...collections], 4, async collection => {const page = await listGalleryPage({ collectionId: collection.id, media: true, kind: 'all', limit: 1, summary: collection.id === 'unsorted', cover: true, videoSnapshot, collectionSnapshot: collections }, diskReader);let cover = page.items[0];diff --git a/server/services/mediaAssetIndex/galleryCollections.db.test.js b/server/services/mediaAssetIndex/galleryCollections.db.test.jsnew file mode 100644index 0000000000..bbb0fd4e5b--- /dev/null+++ b/server/services/mediaAssetIndex/galleryCollections.db.test.js@@ -0,0 +1,122 @@+import { afterAll, beforeAll, expect, it, vi } from 'vitest';+import pg from 'pg';+import { mediaDdl } from '../../lib/db/schema/media.js';+import { requireDbOrSkip } from '../../lib/dbTestGate.js';+import { mediaFixture } from '../../../scripts/perf/collectionFixtureData.js';+import { listGalleryCollectionSummaries, listGalleryFacets } from './gallery.js';++const state = vi.hoisted(() => ({ file: false, images: [], videos: [], collections: [], query: vi.fn() }));+vi.mock('../../lib/runtimeEnv.js', () => ({ isTestRunner: () => state.file }));+vi.mock('../../lib/db.js', () => ({ query: (...args) => state.query(...args) }));+vi.mock('../videoGen/history.js', () => ({ loadHistory: async () => state.videos }));+vi.mock('../mediaCollections.js', () => ({ listCollections: async () => state.collections }));+let client;+let available = false;+beforeAll(async () => {+ vi.stubEnv('MEMORY_BACKEND', 'db');+ if (process.env.PGDATABASE !== 'portos_test') {+ requireDbOrSkip('gallery collection batches', false, 'requires portos_test');+ return;+ }+ client = new pg.Client({ database: 'portos_test', host: process.env.PGHOST || '127.0.0.1',+ port: Number(process.env.PGPORT || 5432), user: process.env.PGUSER || 'portos',+ password: process.env.PGPASSWORD || 'portos', options: '', connectionTimeoutMillis: 2000 });+ await client.connect();+ // A session-private table shadows the index, including for EXPLAIN: no live rows.+ const ddl = mediaDdl.filter(sql => /(?:TABLE IF NOT EXISTS media_assets|INDEX IF NOT EXISTS idx_media_assets_)/.test(sql));+ for (const sql of ddl) await client.query(sql.replace('CREATE TABLE IF NOT EXISTS', 'CREATE TEMP TABLE'));+ state.query.mockImplementation((...args) => client.query(...args));+ available = true;+});+afterAll(async () => { await client?.end(); vi.unstubAllEnvs(); });++async function seed(images, indexedVideos = []) {+ state.images = images;+ await client.query('TRUNCATE pg_temp.media_assets');+ const rows = [...images.map(data => ({ kind: 'image', ref: data.filename, data })),+ ...indexedVideos.map(data => ({ kind: 'video', ref: data.id, data }))];+ await client.query(`INSERT INTO pg_temp.media_assets (media_key, kind, ref, data, created_at)+ SELECT kind || ':' || ref, kind, ref, data, COALESCE((data->>'createdAt')::timestamptz, 'epoch')+ FROM jsonb_to_recordset($1::jsonb) AS r(kind text, ref text, data jsonb)`, [JSON.stringify(rows)]);+}+const member = (kind, ref, addedAt = '2026-01-01') => ({ kind, ref, addedAt });+const disk = async () => state.images;++it('preserves cover fallback, stable membership order, visibility and stale-reference contracts at the public boundary', async context => {+ if (!available) return context.skip();+ await seed([+ { filename: 'a.png', createdAt: '2026-01-01', universeId: 'example', entryKind: 'canon' },+ { filename: 'z.png', path: '/custom/z.png', hidden: true, createdAt: '2026-01-01' },+ { filename: 'loose.png', hidden: true, createdAt: '2026-01-03' },+ ], [{ id: 'stale-index', thumbnail: 'stale.png' }]);+ state.videos = [{ id: 'v', filename: 'v.mp4', thumbnail: 'current.png', hidden: true, createdAt: 'bad-date' },+ { id: 'no-thumb', createdAt: '2026-01-04' }, { id: 'loose', createdAt: '2026-01-05' }];+ const items = [member('image', 'z.png'), member('image', 'a.png'), member('video', 'v'), member('image', 'missing.png')];+ state.collections = [+ { id: 'equal-time', name: 'Equal', items },+ { id: 'pin-image', name: 'Image', items, coverKey: 'image:a.png' },+ { id: 'pin-video', name: 'Video', items, coverKey: 'video:v' },+ { id: 'pin-filename', name: 'Filename', items, coverKey: 'video:v.mp4' },+ { id: 'missing-pin', items, coverKey: 'image:missing.png' },+ { id: 'outside-pin', items, coverKey: 'image:loose.png' },+ { id: 'no-thumbnail', items: [member('video', 'no-thumb'), ...items], coverKey: 'video:no-thumb' },+ { id: 'empty', items: [] }, { id: 'stale', items: [member('image', 'gone.png')] },+ { id: 'hidden-only', items: [member('image', 'z.png')] },+ { id: 'video-only', items: [member('video', 'v')] },+ ];+ state.file = true;+ const expected = await listGalleryCollectionSummaries(disk);+ const facets = await listGalleryFacets(disk);+ expect(expected[0]).toEqual({ id: 'unsorted', cover: '/data/images/loose.png', total: 2, counts: { image: 1, video: 1, all: 2 } });+ expect(expected[1]).toMatchObject({ cover: '/custom/z.png', total: 4 });+ state.file = false;+ state.query.mockClear();+ expect(await listGalleryCollectionSummaries(disk)).toEqual(expected);+ expect(state.query).toHaveBeenCalledTimes(1);+ state.query.mockClear();+ expect(await listGalleryFacets(disk)).toEqual(facets);+ expect(state.query).toHaveBeenCalledTimes(2);+ // Empty collection list and no authoritative videos still yield Unsorted.+ state.collections = []; state.videos = [];+ expect((await listGalleryCollectionSummaries(disk))[0]).toMatchObject({ total: 3, counts: { image: 3, video: 0, all: 3 } });+ await seed([]);+ state.videos = [{ id: 'loose-video', thumbnail: 'loose.png', hidden: true, createdAt: '2026-01-01' }];+ expect((await listGalleryCollectionSummaries(disk))[0]).toEqual({ id: 'unsorted', total: 1,+ counts: { image: 0, video: 1, all: 1 }, cover: '/data/video-thumbnails/loose.png' });+ state.videos = [];+ expect((await listGalleryCollectionSummaries(disk))[0]).toEqual({ id: 'unsorted', total: 0,+ counts: { image: 0, video: 0, all: 0 }, cover: null });+});++it('keeps summary and picker query counts constant for the synthetic 2400-image/1200-video fixture', async context => {+ if (!available) return context.skip();+ await seed(Array.from({ length: 2400 }, (_, i) => mediaFixture('image', i)));+ state.videos = Array.from({ length: 1200 }, (_, i) => mediaFixture('video', i));+ for (const count of [0, 10, 30]) {+ state.collections = Array.from({ length: count }, (_, i) => ({ id: `collection-${i}`, name: `Collection ${i}`,+ items: state.images.slice(i * 20, i * 20 + 20).map(image => member('image', image.filename)),+ }));+ state.query.mockClear();+ const started = performance.now();+ const summaries = await listGalleryCollectionSummaries(disk);+ const elapsed = performance.now() - started;+ expect(summaries).toHaveLength(count + 1);+ expect(state.query).toHaveBeenCalledTimes(1);+ const [sql, params] = state.query.mock.calls[0];+ const projected = JSON.parse(params[1]);+ expect(projected).toHaveLength(1200);+ expect(projected.every(video => !('prompt' in video) && !('metadata' in video))).toBe(true);+ const plan = (await client.query(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${sql}`, params)).rows[0]['QUERY PLAN'][0].Plan;+ if (process.env.PORTOS_COLLECTION_BENCHMARK === '1') process.stdout.write(JSON.stringify({ collections: count, queries: 1, videoBytes: Buffer.byteLength(params[1]),+ elapsedMs: Math.round(elapsed), responseBytes: Buffer.byteLength(JSON.stringify(summaries)),+ tempReadBlocks: plan['Temp Read Blocks'], tempWrittenBlocks: plan['Temp Written Blocks'] }) + '\n');+ for (let i = 0; i < count; i++) state.collections[i].coverKey = `image:${state.images[i * 20 + 19].filename}`;+ state.query.mockClear();+ const pinned = await listGalleryCollectionSummaries(disk);+ expect(state.query).toHaveBeenCalledTimes(1);+ for (let i = 0; i < count; i++) expect(pinned[i + 1].cover).toBe(state.images[i * 20 + 19].path);+ state.query.mockClear();+ expect((await listGalleryFacets(disk)).collections).toHaveLength(count);+ expect(state.query).toHaveBeenCalledTimes(2);+ }+});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 6c84973d2e..7da788116e 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -18,6 +18,7 @@ export const DB_TEST_INCLUDE = ['../scripts/perf/collectionFixture.db.test.js','services/appQuality.db.test.js','**/db.test.js',+ 'services/mediaAssetIndex/galleryCollections.db.test.js','services/dbAdmin.db.test.js','services/backup.db.test.js','services/catalogDB.test.js',