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: compact Media History pages before they reach PostgreSQL (#9676)
[._.]/ Adam Eivy0b65758582f3
diff --git a/scripts/perf/README.md b/scripts/perf/README.mdindex 1fd26a18eb..5e2d1bca9c 100644--- a/scripts/perf/README.md+++ b/scripts/perf/README.md@@ -143,3 +143,11 @@ fixture and is counted as unavailable. Inbox summary/detail and Contacts idlegates passed, including a full idle minute with zero HTTP transfer and fourbytes of socket heartbeat payload. This runner does not claim all #8232contracts are met.++#9676 moved the compact projection ahead of PostgreSQL for no-search pages:+the bound video-history parameter for the 60-row mixed page fell from+10,297,081 to 705,481 bytes, the SQL result from 511,058 to 31,998 bytes, and+the plan's temporary I/O from 2,682 blocks each way to none at the default+work_mem. Searches still match the full stored metadata. The browser response+is unchanged at 32,212 decoded bytes. `galleryCollections.db.test.js` prints+these measurements with `PORTOS_COLLECTION_BENCHMARK=1`.diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.jsindex e89932ba80..122fcddfcc 100644--- a/server/services/mediaAssetIndex/db.js+++ b/server/services/mediaAssetIndex/db.js@@ -26,7 +26,10 @@ import { readFile } from 'fs/promises';import { join } from 'path';import { query } from '../../lib/db.js';import { dedupeByKey } from '../../lib/arrayUtils.js';-import { imageToRow, videoToRow } from './logic.js';+import {+ imageToRow, videoToRow, compactGalleryRecord, compactSource, compactSourceToRow,+ COMPACT_SOURCE_FIELDS, COMPACT_PREVIEW_KEY, COMPACT_PROMPT_CHARS,+} from './logic.js';function rowToAsset(row) {if (!row) return null;@@ -132,15 +135,53 @@ function assetFilter({ kind, q = '', hidden, filename, cleanedFrom, mediaKeys, ereturn { params, where: clauses.length ? ` WHERE ${clauses.join(' AND ')}` : '' };}+// The characters String.prototype.trim() removes, as a regex bracket body, so+// the SQL "non-blank prompt" test agrees with logic.js (an all-whitespace+// prompt falls back to metadata.prompt in both).+const JS_TRIM_CLASS = String.raw`\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff`;+const SOURCE_KEYS = COMPACT_SOURCE_FIELDS.map(field => `'${field}'`).join(', ');++/**+ * SQL twin of logic.js compactSource() for an indexed record, in one pass over+ * its keys so the stored JSONB is decoded once: present keys only (an explicit+ * JSON null survives, an absent key stays absent) plus the bounded preview+ * source — prompt, else metadata.prompt. left() counts code points, never+ * fewer than the UTF-16 units the JS preview cuts at, so the final preview is+ * identical to one cut from the full prompt. Index rows are always objects+ * (logic.js imageToRow), which jsonb_each requires.+ */+function compactSourceSql(column) {+ const preview = (key, json) => `min(left(${json} #>> '{}', ${COMPACT_PROMPT_CHARS + 1})) FILTER (WHERE field.key = '${key}'+ AND jsonb_typeof(${json}) = 'string' AND (${json} #>> '{}') ~ '[^${JS_TRIM_CLASS}]')`;+ return `(SELECT COALESCE(jsonb_object_agg(field.key, field.value) FILTER (WHERE field.key IN (${SOURCE_KEYS})), '{}'::jsonb)+ || jsonb_strip_nulls(jsonb_build_object('${COMPACT_PREVIEW_KEY}',+ COALESCE(${preview('prompt', 'field.value')}, ${preview('metadata', "(field.value -> 'prompt')")})))+ FROM jsonb_each(${column}) AS field)`;+}++// Compact rows are projected before SQL only without a search: search matches+// words anywhere in the full stored metadata, beyond any preview.+const projectsCompact = (compact, q = '') => Boolean(compact) && !String(q).trim();++// Final row shape for a reader: full records, compact rows cut from full+// records (search), or compact rows from a projected source (internal keys dropped).+const rowShape = (compact, projected) => !compact ? data => data+ : projected ? compactSourceToRow : compactGalleryRecord;+// Videos stay authoritative in video-history: prompt/visibility edits and uploads// do not all refresh the derived index. Mixed pages join that snapshot in SQL,// rather than using stale video rows or downloading either full list to the client.-function assetSource(params, videos, materialized = false) {- if (videos === undefined) return { cte: '', table: 'media_assets' };- params.push(JSON.stringify(videos.map(data => ({ data, createdAt: Number.isFinite(Date.parse(data.createdAt)) ? new Date(data.createdAt).toISOString() : new Date(0).toISOString() }))));+// A compact source (#9676) carries only card/filter fields of either kind, so+// neither the bound parameter nor the materialized CTE holds full detail bodies.+function assetSource(params, videos, { materialized = false, compact = false } = {}) {+ const data = compact ? `${compactSourceSql('data')} AS data` : 'data';+ if (videos === undefined) return { cte: '', table: 'media_assets', data };+ params.push(JSON.stringify(videos.map(video => ({ data: compact ? compactSource(video) : video,+ createdAt: Number.isFinite(Date.parse(video.createdAt)) ? new Date(video.createdAt).toISOString() : new Date(0).toISOString() }))));return {+ data: 'data',cte: `WITH gallery_assets AS ${materialized ? 'MATERIALIZED ' : ''}(- SELECT media_key, kind, ref, data, created_at FROM media_assets WHERE kind = 'image'+ SELECT media_key, kind, ref, ${data}, created_at FROM media_assets WHERE kind = 'image'UNION ALLSELECT 'video:' || (value->'data'->>'id'), 'video', value->'data'->>'id', value->'data',(value->>'createdAt')::timestamptz@@ -151,9 +192,10 @@ function assetSource(params, videos, materialized = false) {}/** List index rows. Omitting limit retains the legacy array contract. */-export async function listAssets({ limit, offset = 0, videos, typed = false, orderedKeys, ...filters } = {}) {+export async function listAssets({ limit, offset = 0, videos, typed = false, orderedKeys, compact = false, ...filters } = {}) {+ const projected = projectsCompact(compact, filters.q);const { params, where } = assetFilter(filters);- const { cte, table } = assetSource(params, videos);+ const { cte, table, data } = assetSource(params, videos, { compact: projected });let order = 'created_at DESC, media_key ASC';if (orderedKeys) {params.push(orderedKeys);@@ -165,25 +207,27 @@ export async function listAssets({ limit, offset = 0, videos, typed = false, ordpaging = ` LIMIT $${params.length - 1} OFFSET $${params.length}`;}const result = await query(- `${cte}SELECT ${typed ? 'kind, ' : ''}data FROM ${table}${where} ORDER BY ${order}${paging}`, params,+ `${cte}SELECT ${typed ? 'kind, ' : ''}${data} FROM ${table}${where} ORDER BY ${order}${paging}`, params,);- return result.rows.map(row => typed ? { kind: row.kind, data: row.data } : rowToAsset(row));+ const shape = rowShape(compact, projected);+ return result.rows.map(row => typed ? { kind: row.kind, data: shape(row.data) } : shape(rowToAsset(row)));}/** Count matching rows without materializing their JSONB payloads. */-export async function countAssets({ videos, ...filters } = {}) {+export async function countAssets({ videos, compact = false, ...filters } = {}) {const { params, where } = assetFilter(filters);- const { cte, table } = assetSource(params, videos);+ const { cte, table } = assetSource(params, videos, { compact: projectsCompact(compact, filters.q) });const result = await query(`${cte}SELECT COUNT(*) AS count FROM ${table}${where}`, params);return parseInt(result.rows[0].count, 10);}/** One snapshot expansion serves the mixed page and every summary count. */export async function listMixedGalleryPage({- videos = [], limit = 60, offset = 0, orderedKeys, cover, countMediaKeys, ...filters+ videos = [], limit = 60, offset = 0, orderedKeys, cover, countMediaKeys, compact = false, ...filters} = {}) {const params = [];- const { cte, table } = assetSource(params, videos, true);+ const projected = projectsCompact(compact, filters.q);+ const { cte, table } = assetSource(params, videos, { materialized: true, compact: projected });const predicate = options => assetFilter(options, params).where.slice(' WHERE '.length) || 'TRUE';const totalFilter = predicate(filters);const hiddenFilter = predicate({ ...filters, hidden: true });@@ -211,7 +255,8 @@ export async function listMixedGalleryPage({const row = result.rows[0];const image = Number(row.image);const video = Number(row.video);- return { items: row.items, total: Number(row.total), hiddenTotal: Number(row.hiddenTotal),+ const shape = rowShape(compact, projected);+ return { items: row.items.map(item => ({ kind: item.kind, data: shape(item.data) })), total: Number(row.total), hiddenTotal: Number(row.hiddenTotal),counts: { image, video, all: image + video } };}diff --git a/server/services/mediaAssetIndex/gallery.js b/server/services/mediaAssetIndex/gallery.jsindex 98432e5ad6..3c02d0b3af 100644--- a/server/services/mediaAssetIndex/gallery.js+++ b/server/services/mediaAssetIndex/gallery.js@@ -1,6 +1,7 @@import { mapWithConcurrency } from '../../lib/mapWithConcurrency.js';import { isTestRunner } from '../../lib/runtimeEnv.js';import { listAssets, countAssets, galleryFacets, listMixedGalleryPage, collectionCovers, visibleImageCollections } from './db.js';+import { compactGalleryRecord } from './logic.js';const escapeHatch = () => process.env.MEMORY_BACKEND === 'file' || isTestRunner();const keyFor = ({ kind, data }) => `${kind}:${kind === 'image' ? data.filename : data.id}`;@@ -9,33 +10,6 @@ const time = value => Number.isFinite(Date.parse(value)) ? Date.parse(value) : 0const text = value => typeof value === 'string' && value.trim() ? value : null;const readImages = async diskReader => (diskReader || (await import('../imageGen/local.js')).listGallery)();-// Card fields a compact list row keeps: identity, file addressing, lineage-// badges and the chips MediaCard renders. Everything else — full prompts,-// negative prompts, provider payloads — stays on the record and is read on-// demand (`/gallery/lookup`, `/video-gen/history/:id`).-const COMPACT_FIELDS = ['id', 'filename', 'path', 'thumbnail', 'createdAt', 'hidden', 'width', 'height',- 'appId', 'model', 'modelId', 'mode', 'seed', 'steps', 'numFrames', 'fps', 'renderMs', 'loraFilenames',- 'lora_filenames', 'loraPaths', 'lora_paths', 'stitchedFrom', 'upscaledFrom', 'extractedFromVideoId',- 'cleanedFrom', 'autoCleaned', 'regenerated', 'watermarkRemoved'];-const COMPACT_PROMPT_CHARS = 240;--/**- * Opt-in list projection (#8292). `compact: true` marks the row as a PREVIEW:- * its prompt is cut to a display label, so a consumer must hydrate the full- * record before editing it or handing its prompt/settings to a generation- * action. Search and counts still run over the full stored metadata.- */-function compactGalleryRecord(data) {- if (!data || typeof data !== 'object') return data;- const row = { compact: true };- for (const field of COMPACT_FIELDS) if (data[field] !== undefined) row[field] = data[field];- const prompt = text(data.prompt) || text(data.metadata?.prompt);- if (prompt) {- row.prompt = prompt.length > COMPACT_PROMPT_CHARS ? `${prompt.slice(0, COMPACT_PROMPT_CHARS).trimEnd()}…` : prompt;- }- return row;-}-async function resolveScope({ collectionId, starred, mediaKeys, collectionSnapshot }) {let keys = mediaKeys;let excludeKeys;@@ -104,20 +78,22 @@ export async function listGalleryPage({counts = { image: counted.filter(row => row.kind === 'image').length,video: counted.filter(row => row.kind === 'video').length, all: counted.length };}+ if (compact) {+ items = items.map(item => mixed ? { kind: item.kind, data: compactGalleryRecord(item.data) } : compactGalleryRecord(item));+ }} else if (summary && mixed) {+ // The DB reader returns compact rows itself: without a search it never+ // sends or buffers full prompts/detail bodies (#9676).const countScope = starred ? await resolveScope({ collectionId, mediaKeys, collectionSnapshot }) : scope;({ items, total, hiddenTotal, counts } = await listMixedGalleryPage({- ...filters, limit, offset, orderedKeys: scope.orderedKeys, cover, countMediaKeys: countScope.mediaKeys,+ ...filters, limit, offset, orderedKeys: scope.orderedKeys, cover, countMediaKeys: countScope.mediaKeys, compact,}));} else {[items, total, hiddenTotal] = await Promise.all([- listAssets({ ...filters, limit, offset, typed: mixed, orderedKeys: scope.orderedKeys, cover }),- countAssets(filters), summary ? countAssets({ ...filters, hidden: true }) : undefined,+ listAssets({ ...filters, limit, offset, typed: mixed, orderedKeys: scope.orderedKeys, cover, compact }),+ countAssets({ ...filters, compact }), summary ? countAssets({ ...filters, hidden: true, compact }) : undefined,]);}- if (compact) {- items = items.map(item => mixed ? { kind: item.kind, data: compactGalleryRecord(item.data) } : compactGalleryRecord(item));- }return { items, total, limit, offset, ...(summary ? { hiddenTotal, ...(counts ? { counts } : {}) } : {}) };}diff --git a/server/services/mediaAssetIndex/gallery.test.js b/server/services/mediaAssetIndex/gallery.test.jsindex 16ed20ce4c..43564151dd 100644--- a/server/services/mediaAssetIndex/gallery.test.js+++ b/server/services/mediaAssetIndex/gallery.test.js@@ -53,18 +53,31 @@ describe('indexed gallery page', () => {expect(params.slice(-2)).toEqual([1, 1]);});- it('projects compact mixed rows after the indexed query without changing counts', async () => {+ // Row/count equivalence against real PostgreSQL lives in+ // galleryCollections.db.test.js; this pins what crosses into SQL (#9676).+ it('binds compact video sources for a no-search compact page and full records for a search', async () => {vi.stubEnv('NODE_ENV', 'production');vi.stubEnv('VITEST', undefined);vi.stubEnv('MEMORY_BACKEND', 'db');- loadHistory.mockResolvedValue([]);- const video = { id: 'clip-1', filename: 'clip.mp4', thumbnail: 'clip.png', prompt: 'x'.repeat(8192), stitchedFrom: ['a', 'b'], guidanceScale: 3 };- query.mockResolvedValue({ rows: [{ items: [{ kind: 'video', data: video }], total: '9', hiddenTotal: '2', image: '4', video: '5' }] });- const page = await listGalleryPage({ kind: 'all', media: true, summary: true, hidden: false, compact: true, limit: 60 });+ const video = { id: 'clip-1', filename: 'clip.mp4', thumbnail: 'clip.png', prompt: 'x'.repeat(8192), stitchedFrom: ['a', 'b'], guidanceScale: 3, universeId: 'u' };+ loadHistory.mockResolvedValue([video]);+ const compactCard = { compact: true, id: 'clip-1', filename: 'clip.mp4', thumbnail: 'clip.png', stitchedFrom: ['a', 'b'], prompt: 'x'.repeat(240) + '…' };+ const input = { kind: 'all', media: true, summary: true, hidden: false, compact: true, limit: 60 };++ query.mockImplementation(async (_sql, params) => ({ rows: [{ items: [{ kind: 'video', data: JSON.parse(params[0])[0].data }],+ total: '9', hiddenTotal: '2', image: '4', video: '5' }] }));+ const page = await listGalleryPage(input);expect(page).toMatchObject({ total: 9, hiddenTotal: 2, counts: { image: 4, video: 5, all: 9 } });- expect(page.items).toEqual([{ kind: 'video', data: {- compact: true, id: 'clip-1', filename: 'clip.mp4', thumbnail: 'clip.png', stitchedFrom: ['a', 'b'], prompt: 'x'.repeat(240) + '…',- } }]);+ expect(page.items).toEqual([{ kind: 'video', data: compactCard }]);+ const [sql, params] = query.mock.calls[0];+ expect(JSON.parse(params[0])[0].data).toEqual({ id: 'clip-1', filename: 'clip.mp4', thumbnail: 'clip.png',+ stitchedFrom: ['a', 'b'], universeId: 'u', _promptPreviewSource: 'x'.repeat(241) });+ expect(sql).toContain('jsonb_each(data)');++ query.mockClear();+ expect((await listGalleryPage({ ...input, q: 'x' })).items).toEqual([{ kind: 'video', data: compactCard }]);+ expect(JSON.parse(query.mock.calls[0][1][0])[0].data).toEqual(video);+ expect(query.mock.calls[0][0]).not.toContain('jsonb_each(data)');});it('does not turn an index failure into a full disk scan', async () => {diff --git a/server/services/mediaAssetIndex/galleryCollections.db.test.js b/server/services/mediaAssetIndex/galleryCollections.db.test.jsindex bbb0fd4e5b..aafe5de7b0 100644--- a/server/services/mediaAssetIndex/galleryCollections.db.test.js+++ b/server/services/mediaAssetIndex/galleryCollections.db.test.js@@ -3,13 +3,16 @@ 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';+import { listGalleryCollectionSummaries, listGalleryFacets, listGalleryPage } from './gallery.js';+import { compactGalleryRecord } from './logic.js';-const state = vi.hoisted(() => ({ file: false, images: [], videos: [], collections: [], query: vi.fn() }));+const state = vi.hoisted(() => ({ file: false, images: [], videos: [], collections: [], annotations: {}, 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 }));+vi.mock('../mediaCollections.js', () => ({ listCollections: async () => state.collections,+ getCollection: async id => state.collections.find(collection => collection.id === id) }));+vi.mock('../mediaAnnotations.js', () => ({ listAnnotations: async () => state.annotations }));let client;let available = false;beforeAll(async () => {@@ -120,3 +123,116 @@ it('keeps summary and picker query counts constant for the synthetic 2400-image/expect(state.query).toHaveBeenCalledTimes(2);}});++// The pre-#9676 contract: full records through SQL, compacted afterwards.+const compactedFull = page => ({ ...page, items: page.items.map(item => item.kind && item.data+ ? { kind: item.kind, data: compactGalleryRecord(item.data) } : compactGalleryRecord(item)) });+const planNodes = plan => [plan, ...(plan.Plans || []).flatMap(planNodes)];++it('projects compact no-search pages before SQL with identical rows, previews and counts', async context => {+ if (!available) return context.skip();+ const beyond = 'needle-beyond-preview';+ const images = [+ { filename: 'nested.png', createdAt: '2026-02-01', prompt: null, metadata: { prompt: 'nested fallback' }, seed: null,+ universeId: 'u1', entryCategory: 'places', entryKind: 'canon', negativePrompt: 'x'.repeat(500) },+ { filename: 'blank.png', createdAt: '2026-02-02', prompt: ' \t\u3000\ufeff', metadata: { prompt: '🦊'.repeat(300) },+ hidden: true, cleanedFrom: 'nested.png', universeId: 'u1' },+ { filename: 'long.png', createdAt: '2026-02-03', prompt: `${'x'.repeat(238)} ${beyond}`, upscaledFrom: 'nested.png',+ autoCleaned: false, regenerated: true, watermarkRemoved: null },+ { filename: 'short.png', createdAt: '2026-02-04', prompt: 'short ✓ é', width: 0, loraPaths: [], extractedFromVideoId: 'v1' },+ { filename: 'odd.png', createdAt: '2026-02-05', metadata: 'not-an-object', universeId: 'u2', entryCategory: null },+ { filename: 'spaces.png', createdAt: '2026-02-06', prompt: `${'\u00a0'.repeat(300)}late`, stitchedFrom: ['a.png', 'b.png'] },+ ];+ await seed(images, [{ id: 'v1', prompt: 'stale indexed video' }]);+ state.videos = [+ { id: 'v1', filename: 'v1.mp4', thumbnail: 'v1.png', createdAt: '2026-02-07', prompt: `${'é'.repeat(300)} ${beyond}`,+ stitchedFrom: ['a', 'b'], guidanceScale: 3, settings: { steps: 9 } },+ { id: 'v2', filename: 'v2.mp4', thumbnail: null, createdAt: 'invalid', hidden: true, metadata: { prompt: 'video nested' } },+ { id: 'v3', createdAt: '2026-02-08', prompt: `${'\u2028'.repeat(300)}late`, upscaledFrom: 'v1', entryKind: 'canon' },+ ];+ state.collections = [{ id: 'col', name: 'Example', items: [member('video', 'v1', '2026-03-01'),+ member('image', 'short.png', '2026-03-03'), member('image', 'blank.png', '2026-03-02')] }];+ state.annotations = { 'image:long.png': { own: { starred: true } }, 'video:v3': { own: { starred: true } } };+ const cases = [+ {}, { kind: 'image' }, { kind: 'video' }, { hidden: false }, { hidden: true }, { starred: true },+ { starred: true, kind: 'video' }, { collectionId: 'col' }, { collectionId: 'unsorted' }, { filename: 'long.png' },+ { filename: 'v1.mp4', kind: 'video' }, { universeId: 'u1' }, { entryCategory: 'places', entryKind: 'canon' },+ { entryKind: 'canon', kind: 'all' }, { offset: 2, limit: 3 }, { cover: true }, { q: ' ' },+ ];+ const surfaces = [{ media: true, kind: 'all', summary: true }, { media: true, kind: 'all' }, { kind: 'image', summary: true }];+ for (const surface of surfaces) {+ for (const options of cases) {+ const input = { limit: 60, ...surface, ...options };+ const expected = compactedFull(await listGalleryPage({ ...input, compact: false }));+ state.query.mockClear();+ expect(await listGalleryPage({ ...input, compact: true }), JSON.stringify(input)).toEqual(expected);+ for (const [sql, params] of state.query.mock.calls) {+ // Image-only counts read no record payload at all.+ if (!sql.startsWith('SELECT COUNT(*)')) expect(sql).toContain('jsonb_each(data)');+ expect(JSON.stringify(params)).not.toContain(beyond);+ }+ }+ }+ const all = await listGalleryPage({ media: true, kind: 'all', summary: true, compact: true });+ const card = key => all.items.find(item => (item.data.id || item.data.filename) === key).data;+ expect(card('nested.png')).toEqual({ compact: true, filename: 'nested.png', createdAt: '2026-02-01', seed: null,+ prompt: 'nested fallback' });+ expect(card('blank.png').prompt).toBe('🦊'.repeat(120) + '…');+ expect(card('long.png')).toMatchObject({ prompt: 'x'.repeat(238) + '…', watermarkRemoved: null });+ expect(card('spaces.png').prompt).toBe('…');+ expect(card('v1')).toEqual({ compact: true, id: 'v1', filename: 'v1.mp4', thumbnail: 'v1.png', createdAt: '2026-02-07',+ stitchedFrom: ['a', 'b'], prompt: 'é'.repeat(240) + '…' });+ expect(card('v2')).toMatchObject({ thumbnail: null, prompt: 'video nested' });+ expect(card('v3').prompt).toBe('…');++ // Search keeps full-metadata matching beyond the preview, in both kinds.+ const found = await listGalleryPage({ media: true, kind: 'all', summary: true, compact: true, q: beyond });+ expect(found.items.map(item => item.data.id || item.data.filename)).toEqual(['v1', 'long.png']);+ expect(found.items.every(item => item.data.compact)).toBe(true);+ // Non-compact and lookup callers still receive full records with saved prompts/settings.+ const full = await listGalleryPage({ media: true, kind: 'video', filename: 'v1.mp4' });+ expect(full.items).toEqual([{ kind: 'video', data: state.videos[0] }]);+ expect((await listGalleryPage({ limit: 200, mediaKeys: ['image:nested.png'] })).items).toEqual([images[0]]);+});++it('sends no full video detail to SQL and does not spill for the synthetic 2400-image/1200-video page', 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));+ state.collections = [];+ await client.query('RESET work_mem');+ const measure = async compact => {+ state.query.mockClear();+ const page = await listGalleryPage({ media: true, kind: 'all', summary: true, hidden: false, compact, limit: 60 });+ expect(state.query).toHaveBeenCalledTimes(1);+ const [sql, params] = state.query.mock.calls[0];+ const result = await client.query(sql, params);+ const explained = await client.query(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${sql}`, params);+ const nodes = planNodes(explained.rows[0]['QUERY PLAN'][0].Plan);+ return { page, params, videoBytes: Buffer.byteLength(params[0]), resultBytes: Buffer.byteLength(JSON.stringify(result.rows)),+ responseBytes: Buffer.byteLength(JSON.stringify(page)),+ tempReadBlocks: Math.max(...nodes.map(node => node['Temp Read Blocks'] || 0)),+ tempWrittenBlocks: Math.max(...nodes.map(node => node['Temp Written Blocks'] || 0)),+ executionMs: explained.rows[0]['QUERY PLAN'][0]['Execution Time'] };+ };+ const before = await measure(false);+ const after = await measure(true);+ expect(after.page).toEqual(compactedFull(before.page));+ expect(after.page.items).toHaveLength(60);+ const videos = JSON.parse(after.params[0]);+ expect(videos).toHaveLength(1200);+ for (const { data } of videos) {+ expect(data).not.toHaveProperty('prompt');+ expect(data._promptPreviewSource.length).toBeLessThanOrEqual(241);+ }+ expect(after.tempReadBlocks).toBe(0);+ expect(after.tempWrittenBlocks).toBe(0);+ expect(after.videoBytes).toBeLessThan(before.videoBytes / 10);+ expect(after.resultBytes).toBeLessThan(before.resultBytes / 10);+ if (process.env.PORTOS_COLLECTION_BENCHMARK === '1') {+ for (const [label, run] of [['full', before], ['compact', after]]) {+ const { page: _page, params: _params, ...metrics } = run;+ process.stdout.write(JSON.stringify({ label, ...metrics }) + '\n');+ }+ }+});diff --git a/server/services/mediaAssetIndex/logic.js b/server/services/mediaAssetIndex/logic.jsindex 5c7d8e2002..af86d2de20 100644--- a/server/services/mediaAssetIndex/logic.js+++ b/server/services/mediaAssetIndex/logic.js@@ -69,3 +69,59 @@ export function videoToRow(entry, { now } = {}) {createdAt: mirrorTimestamp(entry.createdAt, fallback),};}++// Card fields a compact list row keeps: identity, file addressing, lineage+// badges and the chips MediaCard renders. Everything else — full prompts,+// negative prompts, provider payloads — stays on the record and is read on+// demand (`/gallery/lookup`, `/video-gen/history/:id`).+const COMPACT_FIELDS = ['id', 'filename', 'path', 'thumbnail', 'createdAt', 'hidden', 'width', 'height',+ 'appId', 'model', 'modelId', 'mode', 'seed', 'steps', 'numFrames', 'fps', 'renderMs', 'loraFilenames',+ 'lora_filenames', 'loraPaths', 'lora_paths', 'stitchedFrom', 'upscaledFrom', 'extractedFromVideoId',+ 'cleanedFrom', 'autoCleaned', 'regenerated', 'watermarkRemoved'];+export const COMPACT_PROMPT_CHARS = 240;+// Scalars the list predicates read (db.js assetFilter) that are not card+// fields. A compact source keeps them so scope filters match exactly as they+// do over the full record; compactSourceToRow drops them.+const COMPACT_FILTER_FIELDS = ['universeId', 'entryCategory', 'entryKind'];+export const COMPACT_SOURCE_FIELDS = [...COMPACT_FIELDS, ...COMPACT_FILTER_FIELDS];+// Internal key carrying the chosen prompt, bounded to one character past the+// preview so the preview (and its ellipsis) is identical to one cut from the+// full prompt. Never returned to a client.+export const COMPACT_PREVIEW_KEY = '_promptPreviewSource';++const nonBlank = value => typeof value === 'string' && value.trim() ? value : null;++/**+ * Bounded projection of a full record: card fields, filter-only scalars and+ * the bounded preview source. This is what a compact no-search list sends to+ * SQL in place of the full video-history record (#9676); db.js builds the+ * same shape for indexed images in SQL.+ */+export function compactSource(data) {+ if (!data || typeof data !== 'object') return data;+ const source = {};+ for (const field of COMPACT_SOURCE_FIELDS) if (data[field] !== undefined) source[field] = data[field];+ const prompt = nonBlank(data.prompt) || nonBlank(data.metadata?.prompt);+ if (prompt) source[COMPACT_PREVIEW_KEY] = prompt.slice(0, COMPACT_PROMPT_CHARS + 1);+ return source;+}++/** The client-facing compact row for a compact source; internal fields are dropped. */+export function compactSourceToRow(source) {+ if (!source || typeof source !== 'object') return source;+ const row = { compact: true };+ for (const field of COMPACT_FIELDS) if (source[field] !== undefined) row[field] = source[field];+ const prompt = source[COMPACT_PREVIEW_KEY];+ if (typeof prompt === 'string' && prompt) {+ row.prompt = prompt.length > COMPACT_PROMPT_CHARS ? `${prompt.slice(0, COMPACT_PROMPT_CHARS).trimEnd()}…` : prompt;+ }+ return row;+}++/**+ * Opt-in list projection (#8292). `compact: true` marks the row as a PREVIEW:+ * its prompt is cut to a display label, so a consumer must hydrate the full+ * record before editing it or handing its prompt/settings to a generation+ * action. Search and counts still run over the full stored metadata.+ */+export const compactGalleryRecord = data => compactSourceToRow(compactSource(data));