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: reuse one video snapshot for Media History summaries (#8231)

[._.]/ Adam Eivy7075eb1b1c91
diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.js
index c60f9761cc..52d0d7eb3f 100644
--- a/server/services/mediaAssetIndex/db.js
+++ b/server/services/mediaAssetIndex/db.js
@@ -93,8 +93,7 @@ export async function removeAsset(mediaKey) {
// Parameters stay bound, including literal substring search (percent and underscore
// in a prompt are not SQL wildcards). Count and page share exactly one predicate.
-function assetFilter({ kind, q = '', hidden, filename, cleanedFrom, mediaKeys, excludeKeys, universeId, entryCategory, entryKind, cover } = {}) {
- const params = [];
+function assetFilter({ kind, q = '', hidden, filename, cleanedFrom, mediaKeys, excludeKeys, universeId, entryCategory, entryKind, cover } = {}, params = []) {
const clauses = [];
if (kind) { params.push(kind); clauses.push(`kind = $${params.length}`); }
if (hidden !== undefined) {
@@ -136,11 +135,11 @@ function assetFilter({ kind, q = '', hidden, filename, cleanedFrom, mediaKeys, e
// 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) {
+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() }))));
return {
- cte: `WITH gallery_assets AS (
+ cte: `WITH gallery_assets AS ${materialized ? 'MATERIALIZED ' : ''}(
SELECT media_key, kind, ref, data, created_at FROM media_assets WHERE kind = 'image'
UNION ALL
SELECT 'video:' || (value->'data'->>'id'), 'video', value->'data'->>'id', value->'data',
@@ -179,6 +178,43 @@ export async function countAssets({ videos, ...filters } = {}) {
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
+} = {}) {
+ const params = [];
+ const { cte, table } = assetSource(params, videos, true);
+ const predicate = options => assetFilter(options, params).where.slice(' WHERE '.length) || 'TRUE';
+ const totalFilter = predicate(filters);
+ const hiddenFilter = predicate({ ...filters, hidden: true });
+ // Chips follow search/collection/visibility, before kind and favorites.
+ const facetFilter = predicate({ ...filters, kind: undefined, mediaKeys: countMediaKeys });
+ const pageFilter = predicate({ ...filters, cover });
+ let order = 'created_at DESC, media_key ASC';
+ if (orderedKeys) {
+ params.push(orderedKeys);
+ order = `array_position($${params.length}::text[], media_key), media_key ASC`;
+ }
+ params.push(limit, offset);
+ const result = await query(`${cte}, gallery_page AS (
+ SELECT * FROM ${table} WHERE ${pageFilter}
+ ORDER BY ${order} LIMIT $${params.length - 1} OFFSET $${params.length}
+ )
+ SELECT
+ (SELECT COALESCE(jsonb_agg(jsonb_build_object('kind', kind, 'data', data)
+ ORDER BY ${order}), '[]'::jsonb) FROM gallery_page) AS items,
+ COUNT(*) FILTER (WHERE ${totalFilter}) AS total,
+ COUNT(*) FILTER (WHERE ${hiddenFilter}) AS "hiddenTotal",
+ COUNT(*) FILTER (WHERE (${facetFilter}) AND kind = 'image') AS image,
+ COUNT(*) FILTER (WHERE (${facetFilter}) AND kind = 'video') AS video
+ FROM ${table}`, params);
+ 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),
+ counts: { image, video, all: image + video } };
+}
+
/** 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/db.test.js b/server/services/mediaAssetIndex/db.test.js
index c4e162b1b1..c08a932c66 100644
--- a/server/services/mediaAssetIndex/db.test.js
+++ b/server/services/mediaAssetIndex/db.test.js
@@ -8,10 +8,15 @@
* so it never touches the real media-gen stack, and cleaning its rows up after.
*/
-import { describe, it, expect, afterAll, beforeAll } from 'vitest';
+import { describe, it, expect, afterAll, beforeAll, vi } from 'vitest';
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
import { requireDbOrSkip } from '../../lib/dbTestGate.js';
+vi.mock('../../lib/db.js', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, query: vi.fn(actual.query) };
+});
+
let dbReady = false;
let skipReason = '';
{
@@ -112,6 +117,62 @@ describe.skipIf(!runDb)('media asset index DB round-trip', () => {
await db.removeAsset(`video:${video.id}`);
});
+ it('matches legacy mixed summary semantics and expands the snapshot once, including empty pages', async () => {
+ const images = [
+ { filename: `${PFX}summary-a.png`, prompt: '100% fox', createdAt: '2026-01-03', universeId: 'example-u' },
+ { filename: `${PFX}summary-b.png`, prompt: '100% fox', createdAt: '2026-01-02', hidden: true },
+ ];
+ const videos = [
+ { id: `${PFX}summary-v`, prompt: '100% fox', createdAt: '2026-01-01', thumbnail: 'example.jpg' },
+ { id: `${PFX}summary-hidden`, prompt: 'fox', createdAt: 'invalid', hidden: true },
+ ];
+ for (const image of images) await db.upsertAsset({ mediaKey: `image:${image.filename}`,
+ kind: 'image', ref: image.filename, data: image, createdAt: image.createdAt });
+ const keys = [...images.map(image => `image:${image.filename}`), ...videos.map(video => `video:${video.id}`)];
+ const cases = [
+ {}, { offset: 1 }, { offset: 99 }, { hidden: false }, { hidden: true },
+ { kind: 'video', hidden: false, q: '100% fox' },
+ { mediaKeys: [keys[2]], countMediaKeys: keys, kind: 'video' }, // starred within collection
+ { mediaKeys: [], countMediaKeys: keys }, // no favorites; chips still populated
+ { excludeKeys: [keys[0], keys[2]] }, // unsorted
+ { orderedKeys: [...keys].reverse() },
+ { cover: true }, { universeId: 'example-u' }, { filename: images[0].filename },
+ { videos: [], mediaKeys: [], countMediaKeys: [] }, // entirely empty
+ { videos: [] }, // images only
+ { mediaKeys: keys.slice(2), countMediaKeys: keys.slice(2) }, // videos only
+ ];
+ for (const options of cases) {
+ const input = { videos, limit: 1, offset: 0, mediaKeys: keys, countMediaKeys: keys, ...options };
+ const { limit, offset, orderedKeys, cover, countMediaKeys, ...filters } = input;
+ const items = await db.listAssets({ ...filters, limit, offset, orderedKeys, cover, typed: true });
+ const total = await db.countAssets(filters);
+ const hiddenTotal = await db.countAssets({ ...filters, hidden: true });
+ const image = await db.countAssets({ ...filters, kind: 'image', mediaKeys: countMediaKeys });
+ const video = await db.countAssets({ ...filters, kind: 'video', mediaKeys: countMediaKeys });
+ query.mockClear();
+ expect(await db.listMixedGalleryPage(input)).toEqual({ items, total, hiddenTotal,
+ counts: { image, video, all: image + video } });
+ expect(query).toHaveBeenCalledTimes(1);
+ }
+ // Actual PostgreSQL plan: even with every summary field, the JSONB function
+ // executes once. Synthetic records keep this deterministic, with no timing gate.
+ const syntheticVideos = Array.from({ length: 200 }, (_, i) => ({
+ id: `${PFX}synthetic-${i}`, createdAt: '2026-01-01',
+ }));
+ query.mockClear();
+ await db.listMixedGalleryPage({ videos: syntheticVideos, limit: 1 });
+ const [sql, params] = query.mock.calls[0];
+ const explained = await query(`EXPLAIN (ANALYZE, FORMAT JSON) ${sql}`, params);
+ const nodes = [];
+ const visit = node => { nodes.push(node); (node.Plans || []).forEach(visit); };
+ visit(explained.rows[0]['QUERY PLAN'][0].Plan);
+ const expansions = nodes.filter(node => node['Function Name'] === 'jsonb_array_elements');
+ expect(expansions).toHaveLength(1);
+ expect(expansions[0]['Actual Loops']).toBe(1);
+ expect(expansions[0]['Actual Rows']).toBe(200);
+ for (const image of images) await db.removeAsset(`image:${image.filename}`);
+ });
+
it('upsert refreshes data + created_at on conflict', async () => {
const key = `image:${PFX}b.png`;
await db.upsertAsset({ mediaKey: key, kind: 'image', ref: `${PFX}b.png`, data: { filename: `${PFX}b.png`, v: 1 }, createdAt: '2026-01-01T00:00:00.000Z' });
diff --git a/server/services/mediaAssetIndex/gallery.js b/server/services/mediaAssetIndex/gallery.js
index 1afcebe471..999dde2572 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 } from './db.js';
+import { listAssets, countAssets, galleryFacets, listMixedGalleryPage } from './db.js';
const escapeHatch = () => process.env.MEMORY_BACKEND === 'file' || isTestRunner();
const keyFor = ({ kind, data }) => `${kind}:${kind === 'image' ? data.filename : data.id}`;
@@ -77,17 +77,16 @@ export async function listGalleryPage({
counts = { image: counted.filter(row => row.kind === 'image').length,
video: counted.filter(row => row.kind === 'video').length, all: counted.length };
}
+ } else if (summary && mixed) {
+ 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,
+ }));
} 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,
]);
- if (summary && mixed) {
- const countScope = starred ? await resolveScope({ collectionId, mediaKeys, collectionSnapshot }) : scope;
- const base = { ...filters, mediaKeys: countScope.mediaKeys };
- const [image, video] = await Promise.all(['image', 'video'].map(kind => countAssets({ ...base, kind })));
- counts = { image, video, all: image + video };
- }
}
return { items, total, limit, offset, ...(summary ? { hiddenTotal, ...(counts ? { counts } : {}) } : {}) };
}
diff --git a/server/services/mediaAssetIndex/gallery.test.js b/server/services/mediaAssetIndex/gallery.test.js
index eb088b0dd6..b0178bf214 100644
--- a/server/services/mediaAssetIndex/gallery.test.js
+++ b/server/services/mediaAssetIndex/gallery.test.js
@@ -30,6 +30,29 @@ describe('indexed gallery page', () => {
expect(disk).not.toHaveBeenCalled();
});
+ it('binds and serializes the synthetic video snapshot once for a mixed summary page', async () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('VITEST', undefined);
+ vi.stubEnv('MEMORY_BACKEND', 'db');
+ const serialize = vi.fn(function () { return { id: this.id, createdAt: this.createdAt }; });
+ const videos = Array.from({ length: 200 }, (_, i) => ({
+ id: `example-${i}`, createdAt: '2026-01-01', toJSON: serialize,
+ }));
+ loadHistory.mockResolvedValue(videos);
+ listAnnotations.mockResolvedValue({ 'video:example-1': { own: { starred: true } } });
+ query.mockResolvedValue({ rows: [{ items: [], total: '1', hiddenTotal: '0', image: '0', video: '200' }] });
+ expect(await listGalleryPage({ kind: 'video', summary: true, starred: true, limit: 1, offset: 1 }))
+ .toEqual({ items: [], total: 1, hiddenTotal: 0, counts: { image: 0, video: 200, all: 200 }, limit: 1, offset: 1 });
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(loadHistory).toHaveBeenCalledTimes(1);
+ expect(serialize).toHaveBeenCalledTimes(200);
+ const [sql, params] = query.mock.calls[0];
+ expect(sql.match(/jsonb_array_elements/g)).toHaveLength(1);
+ expect(sql).toContain('gallery_assets AS MATERIALIZED');
+ expect(JSON.parse(params[0])).toHaveLength(200);
+ expect(params.slice(-2)).toEqual([1, 1]);
+ });
+
it('does not turn an index failure into a full disk scan', async () => {
vi.stubEnv('NODE_ENV', 'production');
vi.stubEnv('VITEST', undefined);