From 6d927130370d1a7c1b6e78e7e7150bda7f9f2cce Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 08:40:00 -0400 Subject: [PATCH 01/13] fix(v2): batch gallery cover fetches into windows The v2 gallery hydrated each visible card with its own GET /roms/{id}/simple request (one HTTP round trip and one DB lookup per card). On a full grid that meant ~100 simultaneous requests, which the browser's per-host connection cap serialized into slow waves, taking 1-2 minutes to fill the grid on low-power devices. v1 loaded the same library in 1-2 paginated requests. Route both grid (GalleryShell viewport sync) and list (GameListRow mount) hydration through the store's existing fetchWindowAt, which aligns each visible position to its shared 72-item window and dedupes against pending/loaded windows. A full viewport now resolves in a handful of paginated requests instead of one per card. Drops the now-unused per-card fetchRomAt/cancelFetchAt store actions. Generated-By: PostHog Code Task-Id: 6690877a-9c32-4c91-a78b-3d6fd3851fb7 --- .../v2/components/Gallery/GalleryShell.vue | 52 ++++------ .../src/v2/components/Gallery/GameListRow.vue | 27 ++---- frontend/src/v2/stores/galleryRoms.ts | 97 +++---------------- 3 files changed, 41 insertions(+), 135 deletions(-) diff --git a/frontend/src/v2/components/Gallery/GalleryShell.vue b/frontend/src/v2/components/Gallery/GalleryShell.vue index 7e881d0ca..620296540 100644 --- a/frontend/src/v2/components/Gallery/GalleryShell.vue +++ b/frontend/src/v2/components/Gallery/GalleryShell.vue @@ -551,23 +551,20 @@ const currentLetter = computed(() => { return ""; }); -// Per-card viewport-driven fetch. The shell tracks which positions -// are currently visible (from the rows in `viewportRange`) and keeps -// `byPosition` in sync via per-card `getRom(id)` calls — pure by-id -// DB lookups on the backend, much faster than the paginated -// `getRoms(limit/offset)` pipeline. Each fetch is independent, so -// covers stream in as their individual responses land. +// Viewport-driven fetch. The shell tracks which positions are +// currently visible (from the rows in `viewportRange`) and keeps +// `byPosition` in sync by fetching the 72-item windows those positions +// fall into via `fetchWindowAt`. Windows are shared across cards and +// cached in the store, so a full viewport resolves in a handful of +// paginated requests rather than one per card. // // No idle-time prefetch: when the user stops scrolling, no new -// requests are fired. Cards already in the viewport that are still -// missing keep loading; everything off-screen waits until the user -// scrolls there. +// requests are fired. Windows already covering the viewport keep +// loading; everything off-screen waits until the user scrolls there. // -// Cancellation: positions that leave the viewport while their fetch -// is in flight are aborted via `cancelFetchAt`. A small debounce on -// viewport changes prevents fire-and-cancel storms during smooth -// scrolling — only when the viewport settles for `FETCH_DEBOUNCE_MS` -// do we sync. +// A small debounce on viewport changes prevents request storms during +// smooth scrolling: only when the viewport settles for +// `FETCH_DEBOUNCE_MS` do we sync. const FETCH_DEBOUNCE_MS = 80; const visiblePositions = new Set(); let fetchDebounceTimer: ReturnType | null = null; @@ -591,20 +588,17 @@ function collectVisiblePositions(range: { function syncFetches(range: { first: number; last: number }) { const next = collectVisiblePositions(range); - // Cancel positions that left the viewport before their fetch - // resolved. The store's per-position controller handles the network - // abort; idempotent if nothing was in flight. - for (const p of visiblePositions) { - if (!next.has(p) && !galleryRoms.byPosition.has(p)) { - galleryRoms.cancelFetchAt(p); - } - } - - // Fire per-card fetches for positions that just entered. The store - // dedupes against in-flight + already-loaded internally. + // Fetch the windows covering the positions that just entered. The + // store aligns each position to its 72-item window and dedupes + // against pending + loaded windows, so this collapses to one + // paginated request per window regardless of how many cards are on + // screen. (Fetching per-card instead issued one request plus one DB + // lookup per visible card, so ~100 simultaneous round-trips on a full + // grid, which the browser's per-host connection cap then serialized + // into slow waves on low-power devices.) for (const p of next) { if (!galleryRoms.byPosition.has(p)) { - void galleryRoms.fetchRomAt(p); + void galleryRoms.fetchWindowAt(p); } } @@ -792,12 +786,6 @@ onBeforeUnmount(() => { gallerySelection.clear(); if (searchDebounce) clearTimeout(searchDebounce); if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer); - // Cancel any per-position fetches still in flight for our last - // visible set — `invalidateWindows` / `resetGallery` already aborts - // window-level fetches; this covers per-card cleanup on unmount. - for (const p of visiblePositions) { - if (!galleryRoms.byPosition.has(p)) galleryRoms.cancelFetchAt(p); - } visiblePositions.clear(); inflowResizeObserver?.disconnect(); inflowResizeObserver = null; diff --git a/frontend/src/v2/components/Gallery/GameListRow.vue b/frontend/src/v2/components/Gallery/GameListRow.vue index 324c50610..fee3b35c9 100644 --- a/frontend/src/v2/components/Gallery/GameListRow.vue +++ b/frontend/src/v2/components/Gallery/GameListRow.vue @@ -2,11 +2,10 @@ // GameListRow — single row of the list-mode gallery. // // Owns: -// * Per-row lazy fetch — onMount fires `fetchRomAt(position)`; the -// store dedupes against in-flight + already-loaded. onUnmount aborts -// the fetch via `cancelFetchAt(position)` so a fast scroll past -// mid-flight doesn't keep server work queued for invisible rows. -// Mirror of the per-card flow in grid mode — same "row mount = +// * Per-row lazy fetch: onMount fires `fetchWindowAt(position)` and +// the store aligns the position to its 72-item window, deduping +// against pending + loaded windows, so rows sharing a window share +// one request. Mirror of the grid flow, with the same "row mount = // entered viewport" contract via the shell's RVirtualScroller // overscan window. // @@ -27,7 +26,7 @@ import { RSkeletonBlock, RTooltip, } from "@v2/lib"; -import { computed, onBeforeUnmount, onMounted } from "vue"; +import { computed, onMounted } from "vue"; import { useI18n } from "vue-i18n"; import { useRouter } from "vue-router"; import storePlatforms from "@/stores/platforms"; @@ -266,19 +265,9 @@ onMounted(() => { // Static mode (rom passed as prop) skips the gallery's per-row fetch // entirely — the consumer already owns the rom data. if (isStatic.value || props.position === undefined) return; - // Entered the overscan window — kick the per-row fetch. Store dedupes - // against in-flight + already-loaded. - void galleryRoms.fetchRomAt(props.position); -}); - -onBeforeUnmount(() => { - if (isStatic.value || props.position === undefined) return; - // Left the overscan window before the fetch resolved — abort so the - // server doesn't keep building a row the user already scrolled past. - // Idempotent if nothing was in flight. - if (!galleryRoms.byPosition.has(props.position)) { - galleryRoms.cancelFetchAt(props.position); - } + // Entered the overscan window, so kick the window fetch. Store aligns + // to the window grid and dedupes against pending + loaded windows. + void galleryRoms.fetchWindowAt(props.position); }); diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index ad8036cee..d72d7c817 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -61,9 +61,9 @@ type GalleryFilterStore = ExtractPiniaStoreType; // fewer requests but each one downloads more. const WINDOW_SIZE = 72; -// In-flight `AbortController`s keyed by request — `window:${offset}` -// for the windowed initial fetch, `range:${offset}:${limit}` for the -// per-row dwell prefetch. Lives outside store state so Pinia doesn't +// In-flight `AbortController`s keyed by request: `window:${offset}` +// for a windowed fetch, `bootstrap` for the lightweight metadata +// bootstrap. Lives outside store state so Pinia doesn't // try to proxy native abort objects (which break under reactivity). // `invalidateWindows()` / `resetGallery()` abort every pending request, // so a fast-typed search box or a platform-switch mid-load doesn't @@ -140,10 +140,10 @@ interface State { // phase. initialFetching: boolean; // True once total / charIndex / romIdIndex / filter_values have been - // populated — either by the lightweight `fetchInitialMetadata()` - // bootstrap or by `fetchWindowAt(0)`. Used to gate the initial fetch - // dedup independently of `loadedWindows` (metadata bootstrap doesn't - // load any window). + // populated, either by the lightweight `fetchInitialMetadata()` + // bootstrap or by `fetchWindowAt(0)`. Used to gate the initial + // bootstrap dedup independently of `loadedWindows` (metadata + // bootstrap doesn't load any window). metadataLoaded: boolean; // Order params — gallery-list scoped (separate from v1's localStorage // keys so v1/v2 don't fight over the same value). @@ -363,15 +363,14 @@ export default defineStore("v2GalleryRoms", { /** Lightweight bootstrap: fetch only the gallery's metadata (total, * char_index, rom_id_index, filter_values) without loading any - * items. Use this when items will be hydrated lazily through the - * per-card `fetchRomAt(p)` viewport sync — e.g. grid-mode galleries. + * items. Sizes the virtualiser (via `total`) before any window + * lands, so both layouts can render skeleton rows immediately and + * then hydrate them through the viewport-driven `fetchWindowAt` + * sync. * * The backend's `limit` minimum is 1, so we still pay for one - * `SimpleRomSchema` build server-side, but we discard the item - * client-side: every position (including 0) loads through the - * unified per-card path so the staggered fade-in applies to the - * first rows the same as the rest. List mode still wants - * `fetchWindowAt(0)` because the table reads `byPosition` directly. */ + * `SimpleRomSchema` build server-side, but the item is discarded + * client-side. */ async fetchInitialMetadata(): Promise { if (this.metadataLoaded) return; if (this.initialFetching) return; @@ -483,76 +482,6 @@ export default defineStore("v2GalleryRoms", { } }, - /** Fetch an arbitrary `[offset, offset + limit)` range. Used by the - * per-row dwell prefetch in the gallery views — instead of always - * pulling the full 72-item window, a row asks for exactly its 8 - * positions, so visible rows can resolve in parallel and the user - * sees covers stream in row-by-row. - * - * Skips the request when every position in the range is already - * loaded; dedupes concurrent identical requests by (offset, limit) - * key. The initial window — total / charIndex bootstrapping — still - * goes through `fetchWindowAt(0)`. */ - /** Fetch the single ROM at `position` via `GET /roms/{id}/simple` — - * the lightweight schema endpoint that skips the eager `user_saves` - * / `user_states` / `user_screenshots` / `user_collections` / - * `all_user_notes` arrays (those are 5 separate DB queries each; - * dropping them takes the call from ~500ms to a typical by-id - * lookup). The gallery card only needs the `has_*` indicator - * flags + cover paths + platform info — all on `SimpleRomSchema`. - * Detailed arrays are pulled on demand by the game-details page - * or by quick-action dialogs (note editor, achievements panel) - * when the user actually opens them. - * - * Requires `romIdIndex[position]` — populated by the first - * `fetchWindowAt(0)` for the active gallery. Returns silently - * if the index isn't loaded yet. - * - * Per-position `AbortController` allows the shell to cancel - * fetches for cards that left the viewport before resolving. - * `cancelFetchAt(position)` is the cancel side. */ - async fetchRomAt(position: number): Promise { - if (position < 0) return; - if (this.total > 0 && position >= this.total) return; - if (this.byPosition.has(position)) return; - const romId = this.romIdIndex[position]; - if (!romId) return; - - const ctrlKey = `rom:${position}`; - if (inFlightControllers.has(ctrlKey)) return; - - const controller = new AbortController(); - inFlightControllers.set(ctrlKey, controller); - - try { - const response = await romApi.getRomSimple({ - romId, - signal: controller.signal, - }); - // Re-check that the shell still wants this position — a fast - // scroll past + cancel races against the response landing. - if (!inFlightControllers.has(ctrlKey)) return; - this.byPosition.set(position, response.data); - } catch (err) { - if (axios.isCancel(err)) return; - console.error("[v2GalleryRoms] rom fetch failed", position, romId, err); - } finally { - inFlightControllers.delete(ctrlKey); - } - }, - - /** Cancel an in-flight per-position fetch — typically called by - * the shell when a card leaves the viewport before its request - * resolves. No-op if nothing is in flight for that position. */ - cancelFetchAt(position: number) { - const ctrlKey = `rom:${position}`; - const ctrl = inFlightControllers.get(ctrlKey); - if (ctrl) { - ctrl.abort(); - inFlightControllers.delete(ctrlKey); - } - }, - /** Apply (in place) an updated ROM to whatever position currently * holds it — used by edit / favourite / status flows. Mutating * via `set(pos, rom)` on the reactive Map triggers only the From f6f3519c92304ae1a5d207efeddc7b1fa9a44eb7 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 08:55:58 -0400 Subject: [PATCH 02/13] fix(v2): auto-retry failed gallery windows syncFetches only runs on viewport changes, so a window whose fetch failed once would leave up to WINDOW_SIZE (72) visible cards stranded as skeletons on a static viewport until the user scrolled or the gallery context changed. Since only visible windows are ever fetched, a failed window was always visible when it failed. fetchWindowAt now schedules a bounded, backing-off refetch (up to 3 attempts, 2s/4s/6s) on failure so a transient blip self-heals. Retry timers and attempt counts are cleared on success and aborted alongside in-flight requests on any gallery-context switch, so we never retry against a stale context. Generated-By: PostHog Code Task-Id: 6690877a-9c32-4c91-a78b-3d6fd3851fb7 --- frontend/src/v2/stores/galleryRoms.ts | 43 +++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index d72d7c817..2160adf83 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -70,9 +70,31 @@ const WINDOW_SIZE = 72; // leave server work going for results we'll throw away. const inFlightControllers = new Map(); +// A failed window is only refetched when `fetchWindowAt` is called for it +// again, which for a static viewport (no scroll) never happens on its own. +// So a transient failure would strand up to `WINDOW_SIZE` visible cards as +// skeletons. To self-heal, a failed window schedules a bounded, backing-off +// retry; `retryTimers` holds the pending timeouts (keyed by offset) and +// `retryCounts` the attempts so far. Both are cleared by `abortAllInFlight` +// on any gallery-context switch so we never retry against a stale context. +const RETRY_BACKOFF_MS = 2000; +const MAX_WINDOW_RETRIES = 3; +const retryTimers = new Map>(); +const retryCounts = new Map(); + +function clearRetry(offset: number) { + const timer = retryTimers.get(offset); + if (timer !== undefined) clearTimeout(timer); + retryTimers.delete(offset); + retryCounts.delete(offset); +} + function abortAllInFlight() { for (const ctrl of inFlightControllers.values()) ctrl.abort(); inFlightControllers.clear(); + for (const timer of retryTimers.values()) clearTimeout(timer); + retryTimers.clear(); + retryCounts.clear(); } // Apply items to `byPosition` in row-sized batches with a rAF yield @@ -466,15 +488,32 @@ export default defineStore("v2GalleryRoms", { ); this.loadedWindows.add(offset); + // Recovered — drop any retry bookkeeping for this window. + clearRetry(offset); } catch (err) { // An explicit abort isn't a failure — keep `failedWindows` // clean so the window is eligible to refetch under the new // gallery context without the UI flagging it as broken. if (axios.isCancel(err)) return; this.failedWindows.add(offset); - // Surface in console; UI keeps the skeletons in place — the - // window can be retried by re-entering the row. + // Surface in console; UI keeps the skeletons in place until the + // retry below (or a viewport / gallery-state change) refetches. console.error("[v2GalleryRoms] window fetch failed", offset, err); + // Self-heal a stranded viewport: schedule a bounded, backing-off + // refetch so a transient blip doesn't leave the window's cards as + // skeletons until the user happens to scroll. + const attempts = retryCounts.get(offset) ?? 0; + if (attempts < MAX_WINDOW_RETRIES && !retryTimers.has(offset)) { + retryCounts.set(offset, attempts + 1); + const timer = setTimeout( + () => { + retryTimers.delete(offset); + void this.fetchWindowAt(offset); + }, + RETRY_BACKOFF_MS * (attempts + 1), + ); + retryTimers.set(offset, timer); + } } finally { inFlightControllers.delete(ctrlKey); this.pendingWindows.delete(offset); From 79f350ab3e247447f970cc5ccb1aecd384a70489 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 09:05:25 -0400 Subject: [PATCH 03/13] fix(v2): cancel gallery windows that scroll out of view Switching from per-card to per-window fetching dropped the departure cancellation the per-card path had: scrolling through a large library started a request per 72-item window encountered and left every departed window downloading and applying in the background, the wasted network / backend / render work this change set out to avoid on low-power devices. Add store.syncVisibleWindows(positions): it starts the windows covering the visible positions (deduped in fetchWindowAt) and aborts any in-flight or retry-pending window that no longer covers one. The shell's debounced viewport sync now delegates to it. Also abort in-flight windows when the gallery unmounts (onBeforeRouteLeave doesn't reset the store), keeping the loaded cache so returning is still instant. Drops the shell's dead visiblePositions bookkeeping. Generated-By: PostHog Code Task-Id: 6690877a-9c32-4c91-a78b-3d6fd3851fb7 --- .../v2/components/Gallery/GalleryShell.vue | 54 ++++++++----------- frontend/src/v2/stores/galleryRoms.ts | 47 ++++++++++++++++ 2 files changed, 69 insertions(+), 32 deletions(-) diff --git a/frontend/src/v2/components/Gallery/GalleryShell.vue b/frontend/src/v2/components/Gallery/GalleryShell.vue index 620296540..ca06dad2e 100644 --- a/frontend/src/v2/components/Gallery/GalleryShell.vue +++ b/frontend/src/v2/components/Gallery/GalleryShell.vue @@ -551,22 +551,26 @@ const currentLetter = computed(() => { return ""; }); -// Viewport-driven fetch. The shell tracks which positions are -// currently visible (from the rows in `viewportRange`) and keeps +// Viewport-driven fetch. The shell collects the positions currently in +// view (rows in `viewportRange`) and hands them to the store, which keeps // `byPosition` in sync by fetching the 72-item windows those positions -// fall into via `fetchWindowAt`. Windows are shared across cards and -// cached in the store, so a full viewport resolves in a handful of -// paginated requests rather than one per card. +// fall into. Windows are shared across cards and cached, so a full +// viewport resolves in a handful of paginated requests rather than one +// per card. (Fetching per-card instead issued one request plus one DB +// lookup per visible card, so ~100 simultaneous round-trips on a full +// grid, which the browser's per-host connection cap then serialized into +// slow waves on low-power devices.) // -// No idle-time prefetch: when the user stops scrolling, no new -// requests are fired. Windows already covering the viewport keep -// loading; everything off-screen waits until the user scrolls there. +// The store also aborts windows that scrolled out of view, so paging +// through a large library doesn't leave departed windows downloading. +// +// No idle-time prefetch: when the user stops scrolling, no new requests +// are fired for off-screen positions. // // A small debounce on viewport changes prevents request storms during // smooth scrolling: only when the viewport settles for // `FETCH_DEBOUNCE_MS` do we sync. const FETCH_DEBOUNCE_MS = 80; -const visiblePositions = new Set(); let fetchDebounceTimer: ReturnType | null = null; let pendingRange: { first: number; last: number } | null = null; @@ -586,24 +590,7 @@ function collectVisiblePositions(range: { } function syncFetches(range: { first: number; last: number }) { - const next = collectVisiblePositions(range); - - // Fetch the windows covering the positions that just entered. The - // store aligns each position to its 72-item window and dedupes - // against pending + loaded windows, so this collapses to one - // paginated request per window regardless of how many cards are on - // screen. (Fetching per-card instead issued one request plus one DB - // lookup per visible card, so ~100 simultaneous round-trips on a full - // grid, which the browser's per-host connection cap then serialized - // into slow waves on low-power devices.) - for (const p of next) { - if (!galleryRoms.byPosition.has(p)) { - void galleryRoms.fetchWindowAt(p); - } - } - - visiblePositions.clear(); - for (const p of next) visiblePositions.add(p); + galleryRoms.syncVisibleWindows(collectVisiblePositions(range)); } function scheduleFetchSync(range: { first: number; last: number }) { @@ -619,11 +606,10 @@ function scheduleFetchSync(range: { first: number; last: number }) { } // When the virtualItems list itself changes (gallery context switch, -// search invalidate), drop the visible-position bookkeeping. The -// store's `invalidateWindows` / `resetGallery` already aborts every -// in-flight request, so we just clear local state. +// search invalidate), drop the pending debounced sync. The store's +// `invalidateWindows` / `resetGallery` already aborts every in-flight +// request, so we just clear local state. watch(virtualItems, () => { - visiblePositions.clear(); if (fetchDebounceTimer) { clearTimeout(fetchDebounceTimer); fetchDebounceTimer = null; @@ -786,7 +772,11 @@ onBeforeUnmount(() => { gallerySelection.clear(); if (searchDebounce) clearTimeout(searchDebounce); if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer); - visiblePositions.clear(); + // Leaving the gallery entirely (onBeforeRouteLeave doesn't reset the + // store): stop any window fetches still downloading so navigating away + // mid-scroll doesn't keep the network / backend busy. Keeps the loaded + // cache so returning to the same gallery is instant. + galleryRoms.abortInFlight(); inflowResizeObserver?.disconnect(); inflowResizeObserver = null; // Drop the debug stats so the overlay doesn't show stale gallery numbers diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index 2160adf83..96334fe4c 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -97,6 +97,14 @@ function abortAllInFlight() { retryCounts.clear(); } +// Abort a single in-flight window fetch. The rejected request is caught +// as a cancel in `fetchWindowAt` (no `failedWindows` entry, no retry) and +// its `finally` clears the pending/controller bookkeeping. +function cancelWindow(offset: number) { + const ctrl = inFlightControllers.get(`window:${offset}`); + if (ctrl) ctrl.abort(); +} + // Apply items to `byPosition` in row-sized batches with a rAF yield // between batches. Each Map.set() invalidates Vue's per-key dep, and // when many cards are in the viewport / overscan zone they all @@ -521,6 +529,45 @@ export default defineStore("v2GalleryRoms", { } }, + /** Reconcile in-flight window fetches with the currently visible + * positions. Starts any window covering a visible position (deduped + * inside `fetchWindowAt`) and aborts any in-flight or retry-pending + * window that no longer covers one. Without the abort, scrolling + * through a large library would leave every window it passed + * downloading and applying in the background — the exact wasted + * network / backend / render work this store exists to avoid on + * low-power devices. Driven by the shell's debounced viewport sync. */ + syncVisibleWindows(positions: Iterable) { + const wanted = new Set(); + for (const p of positions) { + if (p < 0) continue; + if (this.total > 0 && p >= this.total) continue; + wanted.add(alignToWindow(p)); + } + // Cancel windows that drifted out of view. Snapshot first: aborting + // settles a fetch's `finally` (which mutates these sets) on a later + // microtask, but iterate a copy to stay safe regardless. + for (const offset of [...this.pendingWindows]) { + if (!wanted.has(offset)) cancelWindow(offset); + } + for (const offset of [...retryTimers.keys()]) { + if (!wanted.has(offset)) clearRetry(offset); + } + for (const offset of wanted) { + void this.fetchWindowAt(offset); + } + }, + + /** Abort every in-flight window fetch + pending retry without wiping + * the loaded cache. The shell calls this when the gallery unmounts so + * navigating away mid-scroll doesn't leave downloads running; a + * return to the same gallery still reuses `loadedWindows`. */ + abortInFlight() { + abortAllInFlight(); + this.pendingWindows = new Set(); + this.initialFetching = false; + }, + /** Apply (in place) an updated ROM to whatever position currently * holds it — used by edit / favourite / status flows. Mutating * via `set(pos, rom)` on the reactive Map triggers only the From a65434cc67d01b33eeac9f6c88248878900b9f73 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 15:59:59 -0400 Subject: [PATCH 04/13] perf(backend): index roms (platform_id, fs_size_bytes) GET /api/platforms and GET /api/stats both sum roms.fs_size_bytes but the column was not in any index, forcing full reads of the wide, JSON-heavy roms table (5-11s on large libraries). A composite index on (platform_id, fs_size_bytes) turns both sums into index-only scans. Fixes #3769 Generated-By: PostHog Code Task-Id: e24ff248-6329-4b70-a826-9a9fee21411e --- .../0097_roms_platform_fs_size_index.py | 40 +++++++++++++++++++ backend/models/rom.py | 3 ++ 2 files changed, 43 insertions(+) create mode 100644 backend/alembic/versions/0097_roms_platform_fs_size_index.py diff --git a/backend/alembic/versions/0097_roms_platform_fs_size_index.py b/backend/alembic/versions/0097_roms_platform_fs_size_index.py new file mode 100644 index 000000000..b46b1ad47 --- /dev/null +++ b/backend/alembic/versions/0097_roms_platform_fs_size_index.py @@ -0,0 +1,40 @@ +"""Add composite index on roms (platform_id, fs_size_bytes) + +GET /api/platforms and GET /api/stats both sum roms.fs_size_bytes (per platform +and across the whole library). fs_size_bytes was not part of any index, so the +database had to read actual rows from the very wide, JSON-heavy roms table, +taking 5-11s on large libraries. This composite index lets both sums resolve as +index-only scans that never touch the wide rows; the optimizer picks it for both +query shapes on its own. + +Revision ID: 0097_roms_platform_fs_size_index +Revises: 0096_fix_virtual_collections +Create Date: 2026-07-16 00:00:00.000000 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "0097_roms_platform_fs_size_index" +down_revision = "0096_fix_virtual_collections" +branch_labels = None +depends_on = None + +INDEX_NAME = "idx_roms_platform_fs_size" +INDEX_COLUMNS = ["platform_id", "fs_size_bytes"] + + +def upgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.create_index( + INDEX_NAME, + INDEX_COLUMNS, + unique=False, + if_not_exists=True, + ) + + +def downgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_index(INDEX_NAME, if_exists=True) diff --git a/backend/models/rom.py b/backend/models/rom.py index 39a3c6413..719463c9d 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -268,6 +268,9 @@ class Rom(BaseModel): "tgdb_id", "id", ), + # Covering index so per-platform and whole-library SUM(fs_size_bytes) + # are index-only scans that never touch the wide roms rows + Index("idx_roms_platform_fs_size", "platform_id", "fs_size_bytes"), Index("idx_roms_name", "name"), Index("idx_roms_name_sort_key", "name_sort_key"), Index("idx_roms_igdb_id", "igdb_id"), From 9b6acf66b4c0884360e34b3495e74b5905135d2c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 16:01:59 -0400 Subject: [PATCH 05/13] fix(backend): lightweight eager-load for /roms/{id}/simple The v2 gallery per-card endpoint reused get_rom, which runs the full detail eager-load (saves, states, screenshots, collections) that SimpleRomSchema never serializes, making cards slow to hydrate. Add get_rom_simple backed by a with_simple_details decorator that loads only what SimpleRomSchema needs: platform, metadatum, rom_users, files, sibling_roms (+ their rom_users), notes, and the deferred file-count columns. Fixes #3771 Generated-By: PostHog Code Task-Id: 9233f519-079f-4990-8b48-9d12c81440b4 --- backend/endpoints/roms/__init__.py | 2 +- backend/handler/database/roms_handler.py | 56 ++++++++++++++++++++++++ backend/tests/endpoints/roms/test_rom.py | 26 +++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 4df859e1a..9539feb87 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -1083,7 +1083,7 @@ def get_rom_simple( fetched on user-driven detail interactions (game details page, quick- note dialog open, achievements panel).""" - rom = db_rom_handler.get_rom(id) + rom = db_rom_handler.get_rom_simple(id) if not rom: raise RomNotFoundInDatabaseException(id) diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 04c9c62a0..51ae73cd4 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -243,6 +243,50 @@ def with_details(func): return wrapper +def with_simple_details(func): + """Lightweight eager-load for the `SimpleRomSchema` (v2 gallery card). + + Loads only the relationships `SimpleRomSchema` serializes (rom_users, + files, sibling_roms + their rom_users, notes) and the deferred file-count + columns, skipping the `saves` / `states` / `screenshots` / `collections` + arrays that `with_details` pulls for the detail view. Keeps per-card + hydration cheap on low-power hosts. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + kwargs["query"] = select(Rom).options( + selectinload(Rom.platform), + selectinload(Rom.rom_users).options(noload(RomUser.rom)), + selectinload(Rom.metadatum).options(noload(RomMetadata.rom)), + selectinload(Rom.files).options( + joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), + selectinload(RomFile.track_meta), + ), + selectinload(Rom.sibling_roms).options( + noload(Rom.platform), + noload(Rom.metadatum), + # Per-sibling is_main_sibling resolution needs each sibling's + # RomUser (relationship is `lazy="raise"`). + selectinload(Rom.rom_users).options(noload(RomUser.rom)), + load_only( + Rom.id, + Rom.name, + Rom.platform_id, + Rom.fs_name_no_tags, + Rom.fs_name_no_ext, + ), + ), + selectinload(Rom.notes), + undefer(Rom.multi_file), + undefer(Rom.top_level_file_count), + undefer(Rom.has_soundtrack), + ) + return func(*args, **kwargs) + + return wrapper + + class DBRomsHandler(DBBaseHandler): @begin_session @with_details @@ -268,6 +312,18 @@ class DBRomsHandler(DBBaseHandler): ) -> Rom | None: return session.scalar(query.filter_by(id=id).limit(1)) + @begin_session + @with_simple_details + def get_rom_simple( + self, + id: int, + *, + query: Query = None, # type: ignore + session: Session = None, # type: ignore + ) -> Rom | None: + """Get a rom by ID with only the loads `SimpleRomSchema` needs.""" + return session.scalar(query.filter_by(id=id).limit(1)) + @begin_session @with_details def get_roms_by_ids( diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index eb3f5f95b..525895a25 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -44,6 +44,32 @@ def test_get_rom(client: TestClient, access_token: str, rom: Rom): assert body["id"] == rom.id +def test_get_rom_simple(client: TestClient, access_token: str, rom: Rom): + response = client.get( + f"/api/roms/{rom.id}/simple", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == status.HTTP_200_OK + + body = response.json() + assert body["id"] == rom.id + # SimpleRomSchema stays lightweight: none of the detail-only arrays are + # present, so the endpoint must not eager-load them. + assert "user_saves" not in body + assert "user_states" not in body + assert "user_screenshots" not in body + assert "user_collections" not in body + assert "all_user_notes" not in body + + +def test_get_rom_simple_missing_returns_404(client: TestClient, access_token: str): + response = client.get( + "/api/roms/999999/simple", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == status.HTTP_404_NOT_FOUND + + def test_download_multi_file_rom_content( client: TestClient, access_token: str, multi_file_rom: Rom ): From 0f36ed50093be2e81e013c3ce5e17d31a6140d74 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 18:38:15 -0400 Subject: [PATCH 06/13] fix(ss): tolerate ScreenScraper's invalid JSON escapes ScreenScraper occasionally returns malformed JSON with raw, unescaped backslashes in text fields (e.g. synopses), which the strict parser rejects with "Invalid \escape". The whole response was then discarded as {}, so ScreenScraper found no match even for trivially-matchable titles while other providers matched fine. Parse leniently: on a decode error, double any backslash that isn't a valid JSON escape and retry, instead of dropping the entire response. Fixes #3764 Generated-By: PostHog Code Task-Id: bbb1e2a8-bcb0-45a3-840e-86ce39f906a9 --- backend/adapters/services/screenscraper.py | 25 +++++++++++++++++-- .../adapters/services/test_screenscraper.py | 21 ++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/backend/adapters/services/screenscraper.py b/backend/adapters/services/screenscraper.py index e993a24f3..7d741bdec 100644 --- a/backend/adapters/services/screenscraper.py +++ b/backend/adapters/services/screenscraper.py @@ -1,6 +1,7 @@ import asyncio import http import json +import re from typing import Final, cast import aiohttp @@ -22,6 +23,26 @@ from utils.rate_limiter import ConcurrencyLimiter LOGIN_ERROR_CHECK: Final = "Erreur de login" +# ScreenScraper occasionally returns malformed JSON with unescaped backslashes in +# text fields (e.g. game synopses), which the strict parser rejects with +# "Invalid \escape" and discards the whole response. Match any backslash that is +# not part of a valid JSON escape so we can repair those before parsing. +_INVALID_ESCAPE_RE: Final = re.compile(r'\\(?!["\\/bfnrtu])') + + +def _loads_lenient(text: str) -> dict: + """Parse a ScreenScraper JSON payload, repairing invalid escapes on failure. + + A single unescaped backslash would otherwise sink an entire response (and thus + the match), so on a decode error we double any backslash that isn't a valid + JSON escape and try once more. + """ + try: + return json.loads(text) + except json.JSONDecodeError: + return json.loads(_INVALID_ESCAPE_RE.sub(r"\\\\", text)) + + # ScreenScraper enforces a per-account *thread* (concurrency) cap rather than a # request rate. Because a request can take several seconds, spacing out request # starts is not enough, as overlapping requests would exceed the cap and get @@ -140,7 +161,7 @@ class ScreenScraperService: status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid ScreenScraper credentials", ) - data = await res.json() + data = await res.json(loads=_loads_lenient) _update_thread_allowance(data) return data except aiohttp.ServerTimeoutError: @@ -213,7 +234,7 @@ class ScreenScraperService: status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid ScreenScraper credentials", ) - data = await res.json() + data = await res.json(loads=_loads_lenient) _update_thread_allowance(data) return data except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as err: diff --git a/backend/tests/adapters/services/test_screenscraper.py b/backend/tests/adapters/services/test_screenscraper.py index 7851d5122..5fde53f62 100644 --- a/backend/tests/adapters/services/test_screenscraper.py +++ b/backend/tests/adapters/services/test_screenscraper.py @@ -11,6 +11,7 @@ from fastapi import HTTPException, status from adapters.services.screenscraper import ( LOGIN_ERROR_CHECK, ScreenScraperService, + _loads_lenient, auth_middleware, is_daily_quota_exhausted, reset_daily_quota, @@ -1124,3 +1125,23 @@ class TestScreenScraperServiceEdgeCases: assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED assert "Invalid ScreenScraper credentials" in exc_info.value.detail assert mock_session.get.call_count == 2 + + +class TestLoadsLenient: + """Test tolerant parsing of ScreenScraper's occasionally malformed JSON.""" + + def test_parses_valid_json(self): + assert _loads_lenient('{"a": 1, "b": "x"}') == {"a": 1, "b": "x"} + + def test_repairs_invalid_backslash_escape(self): + # ScreenScraper sometimes emits raw backslashes in text fields, which the + # strict parser rejects with "Invalid \escape". + raw = '{"synopsis": "path C:\\emu\\games"}' + with pytest.raises(json.JSONDecodeError): + json.loads(raw) + assert _loads_lenient(raw) == {"synopsis": "path C:\\emu\\games"} + + def test_preserves_valid_escapes(self): + assert _loads_lenient('{"s": "line\\nbreak \\"quoted\\" \\u00e9"}') == { + "s": 'line\nbreak "quoted" é' + } From 6a9236aada153ceff9e1ac66a59cd9bb081e1be6 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 18:40:44 -0400 Subject: [PATCH 07/13] fix(v2): link IGDB provider to game page by slug The IGDB provider link built a text-search URL from the numeric ID, which returns no results. Point it at the canonical /games/ page when the slug is present, falling back to the ID search otherwise. The URL builder now receives the DetailedRom so it can reach fields beyond the provider ID. Generated-By: PostHog Code Task-Id: 6843b623-ed80-454f-8373-8192f3c629b4 --- .../src/v2/components/GameDetails/OverviewTab.vue | 2 +- .../src/v2/components/GameDetails/ProviderGrid.vue | 2 +- .../src/v2/components/GameDetails/providers.ts | 14 +++++++++++--- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/frontend/src/v2/components/GameDetails/OverviewTab.vue b/frontend/src/v2/components/GameDetails/OverviewTab.vue index 815d0d6a9..c0bbfc761 100644 --- a/frontend/src/v2/components/GameDetails/OverviewTab.vue +++ b/frontend/src/v2/components/GameDetails/OverviewTab.vue @@ -133,7 +133,7 @@ const dataProviders = computed(() => PROVIDERS.map((p) => { const id = providerId(props.rom, p); if (id === null) return null; - return { name: p.name, href: p.url ? p.url(id) : null }; + return { name: p.name, href: p.url ? p.url(id, props.rom) : null }; }).filter((e): e is { name: string; href: string | null } => e !== null), ); diff --git a/frontend/src/v2/components/GameDetails/ProviderGrid.vue b/frontend/src/v2/components/GameDetails/ProviderGrid.vue index 37506ce30..6901afeaa 100644 --- a/frontend/src/v2/components/GameDetails/ProviderGrid.vue +++ b/frontend/src/v2/components/GameDetails/ProviderGrid.vue @@ -27,7 +27,7 @@ const entries = computed(() => { accent: p.color, logo: p.logo, id, - href: id !== null && p.url ? p.url(id) : null, + href: id !== null && p.url ? p.url(id, props.rom) : null, }; }); // Linked first; the cards know how to dim themselves when unlinked. diff --git a/frontend/src/v2/components/GameDetails/providers.ts b/frontend/src/v2/components/GameDetails/providers.ts index 412abe22f..f594c8967 100644 --- a/frontend/src/v2/components/GameDetails/providers.ts +++ b/frontend/src/v2/components/GameDetails/providers.ts @@ -13,8 +13,10 @@ export type Provider = { color: string; /** Optional favicon for the provider's identity. */ logo: string | null; - /** Optional URL builder; when null the card renders unlinked. */ - url: ((id: string | number) => string) | null; + /** Optional URL builder; when null the card renders unlinked. The ROM is + * passed so builders can reach fields beyond the provider ID (e.g. IGDB + * links by slug, not by numeric ID). */ + url: ((id: string | number, rom: DetailedRom) => string) | null; }; export const PROVIDERS: Provider[] = [ @@ -23,7 +25,13 @@ export const PROVIDERS: Provider[] = [ name: "IGDB", color: "var(--r-color-provider-igdb)", logo: "/assets/scrappers/igdb.png", - url: (id) => `https://www.igdb.com/search?type=1&q=${id}`, + // IGDB game pages live at /games/; the numeric ID only feeds a text + // search that returns nothing. Fall back to the ID search when the slug + // (populated from the IGDB match) is missing. + url: (id, rom) => + rom.slug + ? `https://www.igdb.com/games/${rom.slug}` + : `https://www.igdb.com/search?type=1&q=${id}`, }, { key: "moby_id", From ab01cd0e24d99c82610a10bce793a9c070c9337f Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 18:41:06 -0400 Subject: [PATCH 08/13] feat(v2): link Hasheous provider to game detail page Add a URL builder for the Hasheous provider so its card in the GameDetails provider grid links out to the corresponding game page instead of rendering unlinked. Generated-By: PostHog Code Task-Id: 522c9198-de9b-4973-9057-ce4c0a33dcc9 --- frontend/src/v2/components/GameDetails/providers.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/v2/components/GameDetails/providers.ts b/frontend/src/v2/components/GameDetails/providers.ts index 412abe22f..6f80ee8dc 100644 --- a/frontend/src/v2/components/GameDetails/providers.ts +++ b/frontend/src/v2/components/GameDetails/providers.ts @@ -65,7 +65,8 @@ export const PROVIDERS: Provider[] = [ name: "Hasheous", color: "var(--r-color-provider-hasheous)", logo: "/assets/scrappers/hasheous.png", - url: null, + url: (id) => + `https://hasheous.org/index.html?page=dataobjectdetail&type=game&id=${id}`, }, { key: "flashpoint_id", From d4018e5d3ad49050f08d09f34b852b8b9ad68634 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 18:55:24 -0400 Subject: [PATCH 09/13] fix(v2): skip metadata aggregations on later gallery windows Once the bootstrap or window 0 has populated the filter panel, alpha strip, and id index, later window fetches only need their paged items. Send with_char_index=false and with_filter_values=false so the backend doesn't recompute those aggregations for every window. Generated-By: PostHog Code Task-Id: daf23950-b84a-4537-971c-3f85425c172c --- frontend/src/services/api/rom.ts | 11 +++++++++++ frontend/src/v2/stores/galleryRoms.ts | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index 119463b6b..d88493d15 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -182,6 +182,11 @@ export interface GetRomsParams { playerCountsLogic?: string | null; metadataProvidersLogic?: string | null; tagsLogic?: string | null; + // Skip the char index / filter-value aggregations server-side. Left + // undefined (the server default is `true`) unless a caller has already + // hydrated that metadata and only wants the paged items. + withCharIndex?: boolean; + withFilterValues?: boolean; // Cancellation: pass an AbortSignal to let the caller abort an // in-flight request (e.g. search-typing → previous query aborted, // gallery-context switch → previous platform's windows aborted). @@ -231,6 +236,8 @@ async function getRoms({ playerCountsLogic = null, metadataProvidersLogic = null, tagsLogic = null, + withCharIndex = undefined, + withFilterValues = undefined, signal = undefined, }: GetRomsParams) { const params = { @@ -336,6 +343,10 @@ async function getRoms({ ...(filterSaves !== null ? { has_saves: filterSaves } : {}), ...(filterStates !== null ? { has_states: filterStates } : {}), ...(filterVerified !== null ? { verified: filterVerified } : {}), + ...(withCharIndex !== undefined ? { with_char_index: withCharIndex } : {}), + ...(withFilterValues !== undefined + ? { with_filter_values: withFilterValues } + : {}), }; return api.get(`/roms`, { diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index 96334fe4c..4aa698d81 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -460,9 +460,18 @@ export default defineStore("v2GalleryRoms", { const controller = new AbortController(); inFlightControllers.set(ctrlKey, controller); + // Once the bootstrap (or window 0) has populated the filter panel, + // alpha strip, and id index, later windows only need their paged + // items — skip the char index / filter-value aggregations so the + // backend doesn't recompute them for every window. + const skipMetadata = this.metadataLoaded; + try { const response = await romApi.getRoms({ ...params, + ...(skipMetadata + ? { withCharIndex: false, withFilterValues: false } + : {}), signal: controller.signal, }); // Re-check that this window is still relevant — invalidateWindows From 3dd9c6968765093d6dd4872f505be340c31724e0 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 19:00:42 -0400 Subject: [PATCH 10/13] cleanup comment spam --- frontend/src/services/api/rom.ts | 8 ++------ frontend/src/v2/components/Gallery/GalleryShell.vue | 7 +++---- frontend/src/v2/stores/galleryRoms.ts | 9 ++------- 3 files changed, 7 insertions(+), 17 deletions(-) diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index d88493d15..518411079 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -182,14 +182,10 @@ export interface GetRomsParams { playerCountsLogic?: string | null; metadataProvidersLogic?: string | null; tagsLogic?: string | null; - // Skip the char index / filter-value aggregations server-side. Left - // undefined (the server default is `true`) unless a caller has already - // hydrated that metadata and only wants the paged items. + // Skip the char index / filter-value aggregations server-side withCharIndex?: boolean; withFilterValues?: boolean; - // Cancellation: pass an AbortSignal to let the caller abort an - // in-flight request (e.g. search-typing → previous query aborted, - // gallery-context switch → previous platform's windows aborted). + // Cancel an in-flight request signal?: AbortSignal; } diff --git a/frontend/src/v2/components/Gallery/GalleryShell.vue b/frontend/src/v2/components/Gallery/GalleryShell.vue index ca06dad2e..8ce0279ee 100644 --- a/frontend/src/v2/components/Gallery/GalleryShell.vue +++ b/frontend/src/v2/components/Gallery/GalleryShell.vue @@ -772,10 +772,9 @@ onBeforeUnmount(() => { gallerySelection.clear(); if (searchDebounce) clearTimeout(searchDebounce); if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer); - // Leaving the gallery entirely (onBeforeRouteLeave doesn't reset the - // store): stop any window fetches still downloading so navigating away - // mid-scroll doesn't keep the network / backend busy. Keeps the loaded - // cache so returning to the same gallery is instant. + // When leaving the gallery entirely, stop any window fetches still + // downloading so navigating away mid-scroll doesn't keep the network / + // backend busy. Keeps the loaded cache so returning to the same gallery is instant. galleryRoms.abortInFlight(); inflowResizeObserver?.disconnect(); inflowResizeObserver = null; diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index 4aa698d81..bc3c04305 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -460,16 +460,11 @@ export default defineStore("v2GalleryRoms", { const controller = new AbortController(); inFlightControllers.set(ctrlKey, controller); - // Once the bootstrap (or window 0) has populated the filter panel, - // alpha strip, and id index, later windows only need their paged - // items — skip the char index / filter-value aggregations so the - // backend doesn't recompute them for every window. - const skipMetadata = this.metadataLoaded; - try { const response = await romApi.getRoms({ ...params, - ...(skipMetadata + // Skip char index / filter-value aggregations when initial data is loaded + ...(this.metadataLoaded ? { withCharIndex: false, withFilterValues: false } : {}), signal: controller.signal, From 8c236a982bf7aa7107beaf590b59bc5cbfa2a455 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 19:01:59 -0400 Subject: [PATCH 11/13] upgrade trunk --- .trunk/trunk.yaml | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 8a6c1ad6f..8e929d9c6 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -7,14 +7,14 @@ cli: plugins: sources: - id: trunk - ref: v1.7.5 + ref: v1.10.2 uri: https://github.com/trunk-io/plugins # Many linters and tools depend on runtimes - configure them here. (https://docs.trunk.io/runtimes) runtimes: enabled: - go@1.21.0 - node@22.16.0 - - python@3.13.3 + - python@3.14.4 # This is the section where you manage your linters. (https://docs.trunk.io/check/configuration) lint: disabled: @@ -22,27 +22,29 @@ lint: - oxipng - pyright enabled: + - grype@0.110.0 + - pinact@4.0.0 - dotenv-linter@4.0.0 - hadolint@2.14.0 - - markdownlint@0.48.0 - - eslint@10.0.3 + - markdownlint@0.49.1 + - eslint@10.7.0 - actionlint@1.7.11 - bandit@1.9.4 - - black@26.3.0 - - checkov@3.2.508 + - black@26.5.1 + - checkov@3.3.8 - git-diff-check - isort@8.0.1 - - mypy@1.19.1 + - mypy@2.3.0 - osv-scanner@2.3.3 - - prettier@3.8.1: + - prettier@3.9.5: packages: - "@trivago/prettier-plugin-sort-imports@6.0.2" - - "@vue/compiler-sfc@3.5.29" - - ruff@0.15.5 + - "@vue/compiler-sfc@3.5.40" + - ruff@0.15.22 - shellcheck@0.11.0 - shfmt@3.6.0 - taplo@0.10.0 - - trivy@0.69.3 + - trivy@0.70.0 - trufflehog@3.93.7 - yamllint@1.38.0 ignore: From 0cf5f472a54cbf361ac9d302efdf41d973c7560d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi <3247106+gantoine@users.noreply.github.com> Date: Thu, 16 Jul 2026 19:07:26 -0400 Subject: [PATCH 12/13] Apply suggestion from @greptile-apps[bot] Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --- backend/adapters/services/screenscraper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/adapters/services/screenscraper.py b/backend/adapters/services/screenscraper.py index 7d741bdec..db396b966 100644 --- a/backend/adapters/services/screenscraper.py +++ b/backend/adapters/services/screenscraper.py @@ -27,7 +27,7 @@ LOGIN_ERROR_CHECK: Final = "Erreur de login" # text fields (e.g. game synopses), which the strict parser rejects with # "Invalid \escape" and discards the whole response. Match any backslash that is # not part of a valid JSON escape so we can repair those before parsing. -_INVALID_ESCAPE_RE: Final = re.compile(r'\\(?!["\\/bfnrtu])') +_INVALID_ESCAPE_RE: Final = re.compile(r'\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})') def _loads_lenient(text: str) -> dict: From 3db9cde0842d0513c95313d47d0a46db2dd71e1c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 16 Jul 2026 20:39:54 -0400 Subject: [PATCH 13/13] cleanup --- .../alembic/versions/0097_roms_platform_fs_size_index.py | 7 ------- backend/models/rom.py | 2 -- 2 files changed, 9 deletions(-) diff --git a/backend/alembic/versions/0097_roms_platform_fs_size_index.py b/backend/alembic/versions/0097_roms_platform_fs_size_index.py index b46b1ad47..b556e1cc6 100644 --- a/backend/alembic/versions/0097_roms_platform_fs_size_index.py +++ b/backend/alembic/versions/0097_roms_platform_fs_size_index.py @@ -1,12 +1,5 @@ """Add composite index on roms (platform_id, fs_size_bytes) -GET /api/platforms and GET /api/stats both sum roms.fs_size_bytes (per platform -and across the whole library). fs_size_bytes was not part of any index, so the -database had to read actual rows from the very wide, JSON-heavy roms table, -taking 5-11s on large libraries. This composite index lets both sums resolve as -index-only scans that never touch the wide rows; the optimizer picks it for both -query shapes on its own. - Revision ID: 0097_roms_platform_fs_size_index Revises: 0096_fix_virtual_collections Create Date: 2026-07-16 00:00:00.000000 diff --git a/backend/models/rom.py b/backend/models/rom.py index 719463c9d..4059bd2d0 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -268,8 +268,6 @@ class Rom(BaseModel): "tgdb_id", "id", ), - # Covering index so per-platform and whole-library SUM(fs_size_bytes) - # are index-only scans that never touch the wide roms rows Index("idx_roms_platform_fs_size", "platform_id", "fs_size_bytes"), Index("idx_roms_name", "name"), Index("idx_roms_name_sort_key", "name_sort_key"),