Skip to content

perf+fix(audiobooks): detail page, browse, sessions & scanner - #169

Merged
Quick104 merged 10 commits into
Silo-Server:mainfrom
fluxis:pr/audiobook-perf
Jun 17, 2026
Merged

Quick104 merged 10 commits into
Silo-Server:mainfrom
fluxis:pr/audiobook-perf

Conversation

@fluxis

@fluxis fluxis commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Audiobook performance + correctness fixes, found by profiling the live library (EXPLAIN ANALYZE + slow-query capture) and a max-effort code review. Server-only; no client changes required.

Detail page

  • Stop re-running ffprobe per file on every detail/watch load. NeedsCriticalProbeRepair required video codec/resolution/tracks, which audio-only files never have, so the repair never converged. Now audio-aware (video fields only required when the file actually has a video stream).
  • Collapse the per-file user-preference N+1. effectiveAudioSelection issued profile/audio/library-pref lookups per media file; a request-scoped resolver memoizes them (a many-track book went from ~hundreds of round-trips to 3).
  • Parallelize the 4 related-content queries in buildAudiobookExtension (were sequential).

Browse (Authors / Narrators)

  • Cache the grouped author/narrator list per (library, group_by, sort, viewer) — the page paged through ~13k groups and re-ran the full aggregation per page (~4.7s cold). One aggregation now serves every page and survives a refresh.
  • (kind, content_id, person_id) index for the people facets (112ms → ~50ms).
  • Incremental-reveal the list client-side instead of mounting ~13k DOM nodes at once.

Sessions / progress

  • Monotonic, finish-preserving resume cursor (UpdateProgressPosition) — out-of-order/second-device sync ticks no longer rewind the saved position.
  • Throttle device & token last_seen hot-row upserts (one per 5 min) — a page's many setting reads were serializing ~250 upserts on one row.
  • Batch the abs list/shelf handler N+1 (GetAudiobooksByIDs).
  • Retention-prune abs_playback_sessions (close abandoned, delete >90d) + (user_id, profile_id, started_at) stats index.

Scanner

  • Reconcile deleted audiobook files (mirrors the ebook path: soft MarkMissing + membership reconcile + grace-period purge; unmounted-root and empty-walk guards so a flapping mount can't wipe the catalog).

Also includes max-effort review fixes: a SessionCleaner data race and an incremental-scan cleanup-guard correctness fix.

Testing

RED→GREEN unit tests for the probe-repair, query-count, group-cache, and device-throttle changes; full changed-package suites pass under -race; gofmt/go vet clean; deployed and verified on a live 31k-audiobook library.

Based on main; builds against the published SDK v0.6.0 (no manga dependency). AI-assisted (Claude).

Summary by CodeRabbit

Release Notes

  • New Features

    • Audiobook groups now load progressively as you scroll through your library.
  • Performance

    • Audiobook groups use improved server-side caching and larger client page slices.
    • Playback details now optimize audio preference lookups (once per request) and fetch related content concurrently.
    • Progress and content hydration now use batched audiobook lookups; device “seen” registration and ABS session touch updates are throttled.
  • Bug Fixes

    • Playback progress position no longer moves backward.
    • Audio-only media is no longer incorrectly flagged for maintenance.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Quick104, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 48 minutes and 9 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a80aa699-142e-4eff-99f9-8e9c82ebbb80

📥 Commits

Reviewing files that changed from the base of the PR and between 3c020bc and 8de4fe6.

📒 Files selected for processing (5)
  • internal/catalog/audiobook_groups_cache.go
  • internal/catalog/audiobook_groups_cache_test.go
  • internal/worker/cleanup.go
  • migrations/sql/20260616130000_abs_playback_sessions_stats_index.sql
  • web/src/hooks/queries/progress.ts
📝 Walkthrough

Walkthrough

This PR delivers broad audiobook performance and reliability improvements: a server-side TTL cache for audiobook group browsing with frontend incremental reveal, batch GetAudiobooksByIDs replacing per-row DB calls in ABS handlers, monotonic and completion-preserving progress position SQL, per-token and per-device seen throttling, a fullScan flag for safe missing-file reconciliation in the scanner, audio-only probe repair correctness, an ABS session retention sweep, and two supporting DB indexes.

Changes

Audiobook performance & reliability hardening

Layer / File(s) Summary
AudiobookGroupsCache: catalog layer and listAllAudiobookGroups refactor
internal/catalog/audiobook_groups.go, internal/catalog/audiobook_groups_cache.go, internal/catalog/audiobook_groups_cache_test.go
Introduces AudiobookGroupsCache with a TTL-backed Page method and stable cache-key helpers; refactors listAudiobookGroups to accept a maxLimit and adds listAllAudiobookGroups for full-list caching. Two unit tests verify single-fetch-per-key and per-viewer isolation.
CatalogHandler lazy cache wiring and API limit increase
internal/api/handlers/catalog.go, internal/api/handlers/audiobook_groups.go, web/src/hooks/queries/audiobookGroups.ts, web/src/components/audiobooks/AudiobookGroupsView.tsx
Adds sync.Once lazy init of AudiobookGroupsCache to CatalogHandler, raises the handler limit cap to 5000, switches to h.audiobookGroups().Page(...), increases GROUPS_PAGE_SIZE to 2000, and implements IntersectionObserver-based incremental reveal with a sentinel element on the client.
SettingsHandler device-seen registration throttling
internal/api/handlers/settings.go, internal/api/handlers/settings_device_test.go, internal/api/handlers/settings_device_throttle_test.go
Adds shouldRegisterDevice with a TTL cache to SettingsHandler; converts registerRequestDevice to a method with a throttle guard; updates all four call sites (device setting read/delete, effective settings, effective subtitle appearance); adds throttle and nil-store tests.
GetAudiobooksByIDs batch contract and implementation
internal/audiobooks/abs/handler.go, internal/audiobooks/media_store.go
Adds GetAudiobooksByIDs to the MediaStore interface and implements it on ABSMediaStore with batched DB fetch, access filtering, and non-fatal people/series hydration.
ABS item and progress handlers: per-row to batch lookups
internal/audiobooks/abs/items_handler.go, internal/audiobooks/abs/progress.go, internal/audiobooks/abs/bookmarks_handler_test.go, internal/audiobooks/abs/login_refresh_test.go
handleSimilarItems, handleItemsInProgress, and handleGetMyProgress replace per-ID GetAudiobookByID loops with single GetAudiobooksByIDs calls; handleSessionSync now surfaces UpdateProgressPosition errors via slog.Warn; test stubs extended.
Monotonic, completion-preserving progress and throttled session touches
internal/audiobooks/abs_progress_store.go, internal/audiobooks/abs_session_store.go, web/src/hooks/queries/progress.ts
UpdateProgressPosition SQL changes to GREATEST(position_seconds, $4) for monotonic advancement and adds AND NOT completed to prevent overwriting finished rows; ABSSessionStore.TouchToken skips the last_seen_at UPDATE when touched within the throttle window; progress mutation onSuccess narrows invalidation from all catalog queries to only progressKeys.all plus the specific item detail.
Catalog detail: concurrent related-content fetches and memoized audio pref resolver
internal/catalog/detail.go, internal/catalog/detail_audio_prefs_query_test.go, migrations/sql/20260616120000_item_people_kind_facet_index.sql
buildAudiobookExtension launches four lookups concurrently via WaitGroup; audioPrefResolver memoizes user-store/profile/library audio-pref lookups so buildPlaybackInfo pays the cost once per request; new test verifies O(1) lookup count; migration adds index on item_people(kind, content_id, person_id) for kind-leading facet queries.
Scanner: fullScan flag, seenPaths reconciliation, and probe repair audio fix
internal/scanner/audiobook_scan.go, internal/scanner/scanner.go, internal/scanner/audiobook_test.go, internal/scanner/probe_repair.go, internal/scanner/probe_repair_audio_test.go
ScanAudiobookFolder gains a fullScan bool; adds per-root walk helpers to track seenPaths and filter reconciliation roots; reconcileAudiobookMissingFiles enforces cleanup only on full scans via ebookEmptyCleanupAllowed. NeedsCriticalProbeRepair no longer requires video fields for audio-only files. All call sites and tests updated.
Worker: ABS session retention sweep and playback sessions stats index
internal/worker/cleanup.go, migrations/sql/20260616130000_abs_playback_sessions_stats_index.sql
SessionCleaner gains an hourly mutex-guarded closeAbandonedABSSessions that closes abandoned open sessions beyond a grace window and deletes closed sessions older than 90 days. Migration adds index on abs_playback_sessions(user_id, profile_id, started_at) for session stats queries.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • Silo-Server/silo-server#103: Both PRs modify the audiobook scanner reconciliation pipeline in internal/scanner/audiobook_scan.go (main PR changes scan/reconcile behavior via a fullScan flag and root reconciliation, while retrieved PR adds embedded-cover extraction plus tighter dedupe/lookup logic).

Suggested labels

v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.63% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and specifically summarizes the main change: performance and correctness improvements across audiobook components (detail page, browse, sessions, scanner).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@fluxis
fluxis force-pushed the pr/audiobook-perf branch from c0e6cf0 to 1b86cdd Compare June 16, 2026 20:10
@fluxis
fluxis changed the base branch from codex/rebase-pr-137 to main June 16, 2026 20:10
fluxis and others added 7 commits June 17, 2026 14:50
Audiobook detail pages were slow in proportion to track count (up to 433
files/book). Root causes, found by EXPLAIN ANALYZE on the live DB:

- effectiveAudioSelection ran 3-4 user-store queries (profile, audio pref,
  library pref) per file inside buildPlaybackInfo's loop, though the results
  are invariant across a request. Introduce a request-scoped audioPrefResolver
  that memoizes the store lookups (library prefs keyed by folder); a 400-file
  audiobook now issues each query once instead of per file. Selection logic is
  unchanged (audioPreference returns a copy so the original-language sentinel
  is still resolved per file).
- buildAudiobookExtension ran its four independent related-content queries
  serially; run them concurrently so latency is the slowest, not the sum.
- author/narrator browse facets did a full people-table scan; add a
  (kind, content_id, person_id) index so the facet resolves from an index-only
  scan of just that kind's credits (~112ms -> ~49ms on the live library).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Authors/Narrators audiobook pages were slow on cold load and slow again
after a hard refresh (fast only while the React Query client cache was warm).

Root cause (EXPLAIN ANALYZE on live, 31K-audiobook library): the grouped
browse query is ~234ms/page, there are ~13K distinct authors, and the client
pages through the entire list on every load (sequential 500-row requests). With
no server-side cache each of the ~20 pages re-ran the full aggregation
(COUNT(*) OVER() forces it), so a cold load was ~20x234ms. The client's 60s
staleTime was the only thing making a warm revisit fast; a refresh wiped it.

Fix: AudiobookGroupsCache caches the full sorted group list per (library,
group_by, sort, viewer) for 60s (matching the client staleTime, so no extra
staleness) and serves every page as an in-memory slice — one aggregation per
window instead of one per page, and a refresh is a cache hit. Also raise the
client page size 500->2000 so fewer sequential round-trips are needed now that
a larger page is a cheap slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Device-setting reads (HandleGetDeviceSetting, HandleGetEffectiveSettings,
HandleGetEffectiveSubtitleAppearance) each registered the request's device — an
INSERT ... ON CONFLICT upsert of last_seen_at on a single per-device row. A page
that fetches many settings fired hundreds of these concurrently; they serialized
on that row's lock (observed 100-237ms each, ~250 per page load in the slow
query log), taxing every settings fetch.

Throttle device registration to one upsert per (profile, device) per 5 minutes
via an in-process TTL cache, marking the device seen before the upsert so a
concurrent burst collapses to a single write. last_seen_at stays fresh to within
the window. Reads no longer issue a contended write on the hot path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ups reveal, hot-row + stats index

From the full audiobook code review (EXPLAIN + slow-query trace on live):

- Silo-Server#1 (P0, detail-page killer): NeedsCriticalProbeRepair required video codec/
  resolution/tracks, which audio-only files never have, so PlaybackProbeEnsurer
  re-ran ffprobe per file on every detail/watch load (up to N serial spawns for
  an N-track book) and never converged. Gate video-field checks on the file
  actually having a video stream. TDD.
- Silo-Server#3 (P0): abs session-sync rewound the resume cursor — UpdateProgressPosition
  did an unconditional SET with no monotonic guard, ignored its error, and
  no-op'd when no row existed (first-listen resume lost). Now a finish-preserving
  GREATEST upsert; caller logs failures.
- Silo-Server#4 (P0 perf): progress reports fired every ~10s invalidated all of
  catalogKeys.all → refetched every active browse/detail query incl the 13k
  audiobook group lists. Scope invalidation to the reported item's detail.
- Silo-Server#6 (P1 perf): Authors/Narrators page rendered all ~13k groups + cover images
  at once (main-thread freeze). Incremental reveal: render a capped window, grow
  on scroll via IntersectionObserver.
- Silo-Server#10: throttle abs TouchToken last_seen upsert (one per token per 5min) — same
  hot-row contention class as the device fix.
- Silo-Server#8: index abs_playback_sessions (user_id, profile_id, started_at) for the
  listening-stats aggregations.

Deferred (need contract/validation): listening-time idempotency (client delta-vs-
cumulative), scanner deleted-file reconcile, abs session retention job, abs list-
handler batch fetch, scanner-output P2s (need re-backfill).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
handleSimilarItems, handleItemsInProgress, and handleGetMyProgress called
MediaStore.GetAudiobookByID once per row — up to ~500 single fetches (each a
few queries) on app open. Add GetAudiobooksByIDs (one access-scoped fetch +
people/series hydrated once for the whole set) and look results up from the
returned map, preserving order. Underlying primitives (GetByIDsWithAccess,
hydratePeople/Series) were already batch-capable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Silo-Server#5: ScanAudiobookFolder only ever upserted — deleted/renamed books leaked
media_items/media_files/memberships forever. Mirror the ebook reconcile: collect
seenPaths during the walk, MarkMissing files no longer on disk, then
reconcileLibraryMemberships. Safety mirrors ebooks/video: an inaccessible root
(unmounted source) is skipped entirely, and a walk that saw zero files while the
DB has rows only reconciles after operator cleanup confirmation
(ebookEmptyCleanupAllowed) — so a flapping mount can't wipe the catalog. Soft
mark only; the existing grace-period purge hard-deletes later. Reconcile runs
only on a fully-completed (non-cancelled) scan. (Silo-Server#9 coarse case already handled:
audiobookFolderShouldSkip skips unchanged folders; per-file reuse deferred.)

Silo-Server#8-retention: abs_playback_sessions grew unbounded (one row per play-start, never
deleted) and fed every listening-stats scan. Add an hourly sweep in
SessionCleaner: close abandoned open sessions (no /close, stopped syncing >24h)
and delete closed sessions older than 90 days. Mirrors the recommendation_cache /
missing-files prune pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
From /code-review max on the pre-PR diff:
- DATA RACE (P0): SessionCleaner.lastABSSessionPrune is read+written by both the
  15s ticker goroutine and the shutdown-path CleanStale call (main.go defers
  Stop() to after that call). Guard the prune-due gate with a mutex. (CleanStale
  was stateless before this branch, so concurrent calls were previously safe.)
- ScanAudiobookFolder hardcoded fullScan=true into the empty-walk cleanup guard,
  but it's also called from ScanSubtree (incremental scans). An empty subtree
  scan would wrongly consume the operator's one-shot empty-cleanup allowance and
  warn. Thread a real fullScan flag (true from ScanFolder, false from the two
  subtree call sites), mirroring the ebook path.
- Revert UpdateProgressPosition to UPDATE-only (drop the INSERT-on-missing):
  keep the monotonic GREATEST + finish guard that fixes the resume rewind, but
  restore the no-op-on-missing contract so a stray sync tick can't resurrect
  just-cleared progress or create a zero-duration continue-listening row.
- Clamp the audiobook-groups handler limit (paging moved into the cache, leaving
  the old 500/page bound stranded); also gofmt the Scanner struct.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@fluxis
fluxis marked this pull request as ready for review June 17, 2026 12:53
@fluxis
fluxis force-pushed the pr/audiobook-perf branch from 1b86cdd to 70bbfe0 Compare June 17, 2026 12:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/catalog/audiobook_groups_cache_test.go`:
- Around line 24-31: The TTLCache instances created within the
AudiobookGroupsCache initialization have background sweeper goroutines that need
to be cleaned up. In both test functions where AudiobookGroupsCache is
instantiated (around the cache.NewTTLCache[*groupsCacheEntry]() calls), add a
defer statement immediately after the cache variable is assigned to ensure
Close() is called on the cache object, which will properly shut down the
background goroutines and prevent test pollution.

In `@internal/catalog/audiobook_groups_cache.go`:
- Around line 33-37: The issue is in the cache retrieval pattern where a Get
operation followed by a fetch outside synchronization allows multiple concurrent
cache misses for the same key to each trigger the expensive aggregation
operation independently. To fix this, add synchronization to the cache miss
handling in the 61-69 range by implementing a request deduplication mechanism,
such as using a sync.Mutex to guard a map of in-flight fetch operations keyed by
the cache key. When a cache miss occurs, check if a fetch is already in progress
for that key, and if so, wait for it to complete and use the cached result
instead of starting another fetch. Only the first miss should trigger the actual
fetch, with subsequent concurrent misses waiting for that single fetch to
complete before accessing the cache.
- Around line 90-103: The audiobookGroupsCacheKey function is missing
filter.ExcludedMediaTypes when constructing the cache key string, which causes
queries with different excluded media types to incorrectly reuse the same cached
result. Add filter.ExcludedMediaTypes to the cache key by appending it to the
strings.Builder in the audiobookGroupsCacheKey function, similar to how
AllowedContentIDs and other filter fields are currently included, ensuring the
key uniquely identifies all relevant query parameters that affect the results.

In `@internal/scanner/audiobook_scan.go`:
- Around line 214-215: The issue is that roots are being added to the
reconcileRoots slice at line 214 before verifying that the filepath.WalkDir
operation completes successfully. When walk errors occur (logged and ignored at
lines 219-229), the root is still reconciled at lines 354-357, which can
incorrectly mark existing files as missing. To fix this, use a flag variable to
track whether the walk completes without errors, initialize it to false before
the walk starts, set it to true only after the walk successfully completes with
no errors, and then conditionally append the root to reconcileRoots only if this
flag is true. This ensures reconciliation only occurs for roots that were fully
and successfully observed.

In `@migrations/sql/20260616130000_abs_playback_sessions_stats_index.sql`:
- Around line 1-14: The migration is using plain CREATE INDEX and DROP INDEX
statements which will block writes to the abs_playback_sessions table during
deployment. To fix this, add `-- +goose NO TRANSACTION` directive after the `--
+goose Up` and `-- +goose Down` lines respectively, and modify both the CREATE
INDEX statement to use `CREATE INDEX CONCURRENTLY` and the DROP INDEX statement
to use `DROP INDEX CONCURRENTLY`. This allows the index operations to proceed
without blocking concurrent writes to the table.

In `@web/src/hooks/queries/progress.ts`:
- Around line 106-108: The cache invalidation in the invalidateQueries call uses
a hardcoded 4-element key array that doesn't match the key structure generated
by the read queries. Replace the hardcoded queryKey with the same
catalogKeys.itemDetail() method used in the read path at line 50, ensuring it
includes the libraryId component. Use the appropriate ID from the mutation
context to call catalogKeys.itemDetail() instead of the hardcoded key array to
ensure proper cache invalidation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b6a3c9f1-db37-49f1-9b9c-7cee109f0759

📥 Commits

Reviewing files that changed from the base of the PR and between 7abfb5a and 70bbfe0.

📒 Files selected for processing (29)
  • internal/api/handlers/audiobook_groups.go
  • internal/api/handlers/catalog.go
  • internal/api/handlers/settings.go
  • internal/api/handlers/settings_device_test.go
  • internal/api/handlers/settings_device_throttle_test.go
  • internal/audiobooks/abs/bookmarks_handler_test.go
  • internal/audiobooks/abs/handler.go
  • internal/audiobooks/abs/items_handler.go
  • internal/audiobooks/abs/login_refresh_test.go
  • internal/audiobooks/abs/progress.go
  • internal/audiobooks/abs_progress_store.go
  • internal/audiobooks/abs_session_store.go
  • internal/audiobooks/media_store.go
  • internal/catalog/audiobook_groups.go
  • internal/catalog/audiobook_groups_cache.go
  • internal/catalog/audiobook_groups_cache_test.go
  • internal/catalog/detail.go
  • internal/catalog/detail_audio_prefs_query_test.go
  • internal/scanner/audiobook_scan.go
  • internal/scanner/audiobook_test.go
  • internal/scanner/probe_repair.go
  • internal/scanner/probe_repair_audio_test.go
  • internal/scanner/scanner.go
  • internal/worker/cleanup.go
  • migrations/sql/20260616120000_item_people_kind_facet_index.sql
  • migrations/sql/20260616130000_abs_playback_sessions_stats_index.sql
  • web/src/components/audiobooks/AudiobookGroupsView.tsx
  • web/src/hooks/queries/audiobookGroups.ts
  • web/src/hooks/queries/progress.ts

Comment thread internal/scanner/audiobook_scan.go Resolved
Comment thread web/src/hooks/queries/progress.ts Resolved
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jun 17, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/worker/cleanup.go`:
- Around line 155-163: The lastABSSessionPrune timestamp is being updated before
the cleanup operation c.closeAbandonedABSSessions(ctx) is executed, which
prevents retries if the operation fails. Move the assignment of
c.lastABSSessionPrune = time.Now() to occur only after the
c.closeAbandonedABSSessions(ctx) call completes successfully, so that failed
cleanup attempts can be retried on the next cleanup tick instead of waiting for
the full interval to elapse.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 13e7558c-e730-4dec-9360-1f3f67aecb6b

📥 Commits

Reviewing files that changed from the base of the PR and between 70bbfe0 and 3c020bc.

📒 Files selected for processing (4)
  • internal/scanner/audiobook_scan.go
  • internal/scanner/audiobook_test.go
  • internal/worker/cleanup.go
  • web/src/components/audiobooks/AudiobookGroupsView.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/components/audiobooks/AudiobookGroupsView.tsx

Comment thread internal/worker/cleanup.go Resolved
@Quick104
Quick104 merged this pull request into Silo-Server:main Jun 17, 2026
1 check passed
Quick104 added a commit that referenced this pull request Jun 17, 2026
* perf(catalog): fix audiobook detail N+1 + slow people facets

Audiobook detail pages were slow in proportion to track count (up to 433
files/book). Root causes, found by EXPLAIN ANALYZE on the live DB:

- effectiveAudioSelection ran 3-4 user-store queries (profile, audio pref,
  library pref) per file inside buildPlaybackInfo's loop, though the results
  are invariant across a request. Introduce a request-scoped audioPrefResolver
  that memoizes the store lookups (library prefs keyed by folder); a 400-file
  audiobook now issues each query once instead of per file. Selection logic is
  unchanged (audioPreference returns a copy so the original-language sentinel
  is still resolved per file).
- buildAudiobookExtension ran its four independent related-content queries
  serially; run them concurrently so latency is the slowest, not the sum.
- author/narrator browse facets did a full people-table scan; add a
  (kind, content_id, person_id) index so the facet resolves from an index-only
  scan of just that kind's credits (~112ms -> ~49ms on the live library).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(catalog): cache audiobook author/narrator group browse

The Authors/Narrators audiobook pages were slow on cold load and slow again
after a hard refresh (fast only while the React Query client cache was warm).

Root cause (EXPLAIN ANALYZE on live, 31K-audiobook library): the grouped
browse query is ~234ms/page, there are ~13K distinct authors, and the client
pages through the entire list on every load (sequential 500-row requests). With
no server-side cache each of the ~20 pages re-ran the full aggregation
(COUNT(*) OVER() forces it), so a cold load was ~20x234ms. The client's 60s
staleTime was the only thing making a warm revisit fast; a refresh wiped it.

Fix: AudiobookGroupsCache caches the full sorted group list per (library,
group_by, sort, viewer) for 60s (matching the client staleTime, so no extra
staleness) and serves every page as an in-memory slice — one aggregation per
window instead of one per page, and a refresh is a cache hit. Also raise the
client page size 500->2000 so fewer sequential round-trips are needed now that
a larger page is a cheap slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(settings): throttle per-request device last_seen upserts

Device-setting reads (HandleGetDeviceSetting, HandleGetEffectiveSettings,
HandleGetEffectiveSubtitleAppearance) each registered the request's device — an
INSERT ... ON CONFLICT upsert of last_seen_at on a single per-device row. A page
that fetches many settings fired hundreds of these concurrently; they serialized
on that row's lock (observed 100-237ms each, ~250 per page load in the slow
query log), taxing every settings fetch.

Throttle device registration to one upsert per (profile, device) per 5 minutes
via an in-process TTL cache, marking the device seen before the upsert so a
concurrent burst collapses to a single write. last_seen_at stays fresh to within
the window. Reads no longer issue a contended write on the hot path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf+fix(audiobooks): probe-repair, resume position, cache storm, groups reveal, hot-row + stats index

From the full audiobook code review (EXPLAIN + slow-query trace on live):

- #1 (P0, detail-page killer): NeedsCriticalProbeRepair required video codec/
  resolution/tracks, which audio-only files never have, so PlaybackProbeEnsurer
  re-ran ffprobe per file on every detail/watch load (up to N serial spawns for
  an N-track book) and never converged. Gate video-field checks on the file
  actually having a video stream. TDD.
- #3 (P0): abs session-sync rewound the resume cursor — UpdateProgressPosition
  did an unconditional SET with no monotonic guard, ignored its error, and
  no-op'd when no row existed (first-listen resume lost). Now a finish-preserving
  GREATEST upsert; caller logs failures.
- #4 (P0 perf): progress reports fired every ~10s invalidated all of
  catalogKeys.all → refetched every active browse/detail query incl the 13k
  audiobook group lists. Scope invalidation to the reported item's detail.
- #6 (P1 perf): Authors/Narrators page rendered all ~13k groups + cover images
  at once (main-thread freeze). Incremental reveal: render a capped window, grow
  on scroll via IntersectionObserver.
- #10: throttle abs TouchToken last_seen upsert (one per token per 5min) — same
  hot-row contention class as the device fix.
- #8: index abs_playback_sessions (user_id, profile_id, started_at) for the
  listening-stats aggregations.

Deferred (need contract/validation): listening-time idempotency (client delta-vs-
cumulative), scanner deleted-file reconcile, abs session retention job, abs list-
handler batch fetch, scanner-output P2s (need re-backfill).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(audiobooks): batch-fetch abs list/shelf handlers (kill N+1)

handleSimilarItems, handleItemsInProgress, and handleGetMyProgress called
MediaStore.GetAudiobookByID once per row — up to ~500 single fetches (each a
few queries) on app open. Add GetAudiobooksByIDs (one access-scoped fetch +
people/series hydrated once for the whole set) and look results up from the
returned map, preserving order. Underlying primitives (GetByIDsWithAccess,
hydratePeople/Series) were already batch-capable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): reconcile deleted files on scan + prune session history

#5: ScanAudiobookFolder only ever upserted — deleted/renamed books leaked
media_items/media_files/memberships forever. Mirror the ebook reconcile: collect
seenPaths during the walk, MarkMissing files no longer on disk, then
reconcileLibraryMemberships. Safety mirrors ebooks/video: an inaccessible root
(unmounted source) is skipped entirely, and a walk that saw zero files while the
DB has rows only reconciles after operator cleanup confirmation
(ebookEmptyCleanupAllowed) — so a flapping mount can't wipe the catalog. Soft
mark only; the existing grace-period purge hard-deletes later. Reconcile runs
only on a fully-completed (non-cancelled) scan. (#9 coarse case already handled:
audiobookFolderShouldSkip skips unchanged folders; per-file reuse deferred.)

#8-retention: abs_playback_sessions grew unbounded (one row per play-start, never
deleted) and fed every listening-stats scan. Add an hourly sweep in
SessionCleaner: close abandoned open sessions (no /close, stopped syncing >24h)
and delete closed sessions older than 90 days. Mirrors the recommendation_cache /
missing-files prune pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): address max-effort code-review findings

From /code-review max on the pre-PR diff:
- DATA RACE (P0): SessionCleaner.lastABSSessionPrune is read+written by both the
  15s ticker goroutine and the shutdown-path CleanStale call (main.go defers
  Stop() to after that call). Guard the prune-due gate with a mutex. (CleanStale
  was stateless before this branch, so concurrent calls were previously safe.)
- ScanAudiobookFolder hardcoded fullScan=true into the empty-walk cleanup guard,
  but it's also called from ScanSubtree (incremental scans). An empty subtree
  scan would wrongly consume the operator's one-shot empty-cleanup allowance and
  warn. Thread a real fullScan flag (true from ScanFolder, false from the two
  subtree call sites), mirroring the ebook path.
- Revert UpdateProgressPosition to UPDATE-only (drop the INSERT-on-missing):
  keep the monotonic GREATEST + finish guard that fixes the resume rewind, but
  restore the no-op-on-missing contract so a stray sync tick can't resurrect
  just-cleared progress or create a zero-duration continue-listening row.
- Clamp the audiobook-groups handler limit (paging moved into the cache, leaving
  the old 500/page bound stranded); also gofmt the Scanner struct.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): address review feedback for scanner and stats

* fix(audiobooks): address review feedback

* fix(audiobooks): retry failed session prune

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Quick <[email protected]>
uffcd pushed a commit to uffcd/silo-server that referenced this pull request Sep 15, 2026
A book with no existing user_watch_progress row never appeared in
Continue Listening no matter how long it played, because every write
in the online path was UPDATE-only.

Two call sites needed the fix, not one. handlePlayStart covers a
genuinely fresh session. But real clients (observed: the ABS iOS app)
can keep heartbeating an existing, still-open session across a server
restart without ever calling /play again, so play-start alone leaves
a gap. handleSessionSync's heartbeat needs the same fallback -- safe
here because every tick that reaches it already passed an open-session
lookup, so it reflects genuinely active playback, not the stray/
delayed tick that PR Silo-Server#169 was protecting against when it reverted an
earlier attempt at this on the same handler.

Both paths populate the item's real duration up front (never a bare
zero-duration row) and leave an existing row untouched, so resuming a
book and the heartbeat's own monotonic update are unaffected.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QQ2WyBtmHMKGbtygvrBZws
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants