Skip to content

perf(audiobooks): stop Audiobookshelf heavy reads from loading the whole library - #4211

Merged
Quick104 merged 5 commits into
mainfrom
perf/abs-heavy-reads
Nov 15, 2026
Merged

Quick104 merged 5 commits into
mainfrom
perf/abs-heavy-reads

Conversation

@Quick104

@Quick104 Quick104 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none passed; reaches #1254 C3 (pagination under load) and C4, and #1247 C1 and C2, all not run yet

Other clients: N/A (the change is on the Audiobookshelf-compatible API used by third-party Audiobookshelf apps; Silo's Apple, Android, Roku, and web clients use /api/v2)

This builds on #4208, which moved the library items filters and sort into SQL. Several Audiobookshelf requests loaded far more than they return. With "collapse series" on, the Audiobookshelf app sent collapseseries=1 on every page, and each page loaded and hydrated the whole library to fold series in Go (0.8–1.1 s at 30,000 books). The unauthenticated author image route loaded every book by the author to read one photo path, and the cover route ran a full item lookup for one column. The home shelves sorted the whole library for Recently Added and aggregated every series row before paging the series list. The authors view was refreshed by every API node every 15 minutes and paged by name with no tiebreaker. This change makes each of those read only what it returns.

  • collapseseries=1. Series are folded and paged in SQL: matches are numbered in the requested order, each series keeps its first book, and only the page's books are loaded. The entry lists the series' matching books and carries the same series ID and name as the series list.
  • limit=0. Real Audiobookshelf reads it as the whole library, so it still is; the official app pages with limit=20 and never sends 0. The response is now streamed in batches of 1,000 books instead of building every hydrated book in memory first. Response time is about the same.
  • Cover and author image. Each reads one column. The author image now serves only people credited as an audiobook author; before, any person's photo was served without sign-in.
  • Home shelves. Recently Added walks idx_item_libraries_folder newest first. The series list picks its page of series before reading up to four preview books for each, and caches its count like the items list. Discover still uses ORDER BY random(); it measured 26 ms at 30,000 books.
  • Authors view. A node refreshes only if no node refreshed within the interval, under an advisory lock, with the time kept in a new one-row table. The refresh runs on the connection that holds the lock, so a one-connection pool does not wait on itself, and each run has a deadline. Name order breaks ties on the person ID. When a book in the library is also in a library the profile disabled, the list takes the live access-checked query, since the view counts that book.

Approach

The items query from #4208 gains a collapsed form and a streaming form that share its filter, sort, and access conditions. The narrow lookups and shelf queries keep the library and access conditions they had. One reviewer lead did not hold: audiobook_item_file_stats sums every file in a folder, while the shown duration picks one presentation, so reading it for durations would double a book that has two versions in one folder.

Validation

  • Go: go build ./..., gofmt, go mod tidy -diff, go vet ./..., make lint-changed, make lint-router-recovery: pass. Audiobooks and backup packages pass with and without a database; the rest of make test-go ran on fix(audiobooks): make Audiobookshelf library filters, sort, and search return the right books #4208 (same results there; two real-FFmpeg tests fail the same way on main with this host's FFmpeg).
  • make verify-migrations, verify-local-paths, verify-bidi, verify-size-ratchet, verify-case-collisions: pass.
  • Database contract: a new test covers collapsed pages (entry order, member lists, totals, a filter applied inside a series), the narrow cover and photo lookups, that a second refresh within the interval is skipped, and that the refresh completes on a pool capped at one connection. A unit test checks that the streamed limit=0 response is one valid envelope.
  • Web, generated contracts, and API v2 checks: not run; nothing here touches them.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-4211/

Same sandbox and 30,000-book synthetic library as #4208, warm, three runs each. The build host was under heavy load from other work (load average near 50), so differences under about 50 ms are noise.

Request Main #4208 This branch
items?collapseseries=1 page 0 810–1100 ms 990–1270 ms 240–260 ms
items?collapseseries=1 page 100 1080–1220 ms 910–1180 ms 230–520 ms
items?limit=0 (28 MB) 1360–1400 ms 1410–1660 ms 1630–2650 ms
/personalized 230–290 ms 250–340 ms 38–108 ms
/series?limit=50&page=0 120–150 ms 100–140 ms 10–17 ms
author image, author of 6,581 books 165–200 ms 195–205 ms 14–37 ms
items?limit=50&page=500 150–160 ms 140–190 ms 130–320 ms

The limit=0 and page-500 runs on this branch were repeated six times and moved between 1.6 and 2.7 s and 130 and 200 ms with the host load; neither path's query changed apart from batching. The author image returns 404 in all three columns because the synthetic authors have no photos; the time is the lookup.

Risks

  • One migration: a one-row abs_author_counts_refresh table, listed as server state for backups. No index changes.
  • The author image route stops serving photos of people who wrote no audiobook. Audiobookshelf apps only ask for authors the API listed.
  • A limit=0 response that fails partway is cut short instead of returning an error status, since the status line is already sent.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or how I checked a change nobody sees.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated; not yet verified by a person
  • Adversarial review: one independent review of this diff after fix(audiobooks): make Audiobookshelf library filters, sort, and search return the right books #4208 merged (repository code-review skill, medium). Fixed: a refresh recorded its finish time, so a slow refresh made the next tick skip; Recently Added ordered ties against its index; dead code; misplaced interface comments. Kept as tradeoffs: limit=0 together with collapseseries=1 still builds the collapsed list in memory (the official app never sends limit=0; I did not check third-party apps); the series total shares the 60-second count cache that the items list already uses; the collapsed page loads series members in a separate query. The disabled-library check runs on every authors page for a profile that disabled a library: with no overlapping book it reads one side's memberships (Postgres picks the smaller side for the semi-join), an indexed scan per page rather than a cached access answer; a summary table kept in step with membership changes would remove it but is a larger change than this pull request. Earlier bot reviews: Codex's single-connection refresh finding is fixed and tested. Kody's review of that head: the disabled-library overlap check is an access answer and is read on every request again (a test adds a book to a disabled library and checks the next request); zero counts are no longer cached; whole-library loads read at most 1,000 IDs per query.

🤖 Generated with Claude Code

Note

Move Audiobookshelf heavy reads (collapsed listings, streaming, covers) into SQL

Stops loading the whole library to serve heavy ABS endpoints. Filtering, series collapse, sorting, and pagination now happen in SQL in ABSMediaStore.listAudiobooks in media_store.go.

  • GET /abs/api/libraries/{libraryId}/items with collapseseries=1 uses the new ListAudiobooksCollapsed store method; limit=0 requests stream items in batches through Handler.streamLibraryItems in libraries_handler.go, writing one JSON envelope with the total.
  • Cover and author-image handlers use new narrow store lookups (AudiobookPosterPath, AuthorPhotoPath) instead of loading full media items.
  • Author-count materialized-view refresh now runs on a 15-minute ticker with a 14-minute freshness interval, an advisory lock, and a per-attempt timeout; the last refresh time persists in the new abs_author_counts_refresh table (migration).
  • Author listings fall back to the live access-aware query when a book belongs to a disabled library; series listings load preview books only for the paged series.
  • Behavioral Change: a stream error after writing starts leaves a truncated JSON body; zero audiobook counts are no longer cached; library-scoped recently-added ordering adds a content-ID tie-breaker; the in-memory abs.CollapseBySeries helper is removed in favor of store-side collapse.

Macroscope summarized 66846d3.

@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 12 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 05226e1c-b1fe-4715-818f-437788d9bfd6
Commits

Reviewing files that changed from the base of the PR and between d3d59f8 and 66846d3.

Files selected for processing: 2

  • internal/audiobooks/abs/collapse.go
  • internal/audiobooks/abs/handler.go
Walkthrough

Audiobook listings now support batched streaming and store-level collapsed-series pagination. Related queries and path lookups have changed. Author-count refreshes now use interval checks and cluster-wide coordination.

Changes: Audiobook reads and author metadata

Layer / File(s) Summary
Listing contracts and delivery
internal/audiobooks/abs/handler.go, internal/audiobooks/abs/collapse.go, internal/audiobooks/abs/libraries_handler.go, internal/audiobooks/media_store.go, internal/audiobooks/abs/stream_items_test.go, internal/audiobooks/media_store_heavy_reads_db_test.go, internal/audiobooks/media_store_items_db_test.go, internal/audiobooks/abs/login_refresh_test.go
The store now paginates collapsed series and streams full-library results in batches. The handler uses these store methods instead of collapsing and paginating the full result set in Go. Tests cover streaming responses and collapsed pagination.
Related listing and path lookups
internal/audiobooks/media_store.go, internal/audiobooks/abs/handler.go, internal/audiobooks/abs/libraries_handler.go, internal/audiobooks/media_store_heavy_reads_db_test.go, internal/audiobooks/abs/login_refresh_test.go
Recently added and series queries use updated ordering and pagination. Poster and author-image handlers retrieve paths through dedicated store lookups. Database tests cover the new lookups and listing behavior.
Author-count refresh coordination
internal/audiobooks/media_store.go, internal/audiobooks/service.go, migrations/sql/20261114224347_abs_author_counts_refresh_state.sql, internal/backup/tables.go, internal/audiobooks/media_store_heavy_reads_db_test.go, scripts/ci/db-contracts.txt
Author-count refreshes use a freshness interval, advisory lock, and persisted refresh timestamp. Author listings use an access-aware query when a book overlaps a disabled library. The refresh scheduler, backup state, and database-contract tests are updated.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant handleLibraryItems
  participant streamLibraryItems
  participant StreamAudiobooks
  participant streamListing
  participant Database
  Client->>handleLibraryItems: Request full uncollapsed listing
  handleLibraryItems->>streamLibraryItems: Stream response
  streamLibraryItems->>StreamAudiobooks: Request total and item batches
  StreamAudiobooks->>streamListing: Start listing stream
  streamListing->>Database: Query total and audiobook ID batches
  Database-->>streamListing: Return total and IDs
  streamListing-->>streamLibraryItems: Emit total and item batches
  streamLibraryItems-->>Client: Write JSON response
Loading

Suggested reviewers: pukabyte

Merge Risk: Low · previous review d3d59

The change moves collapsing, paging and streaming of audiobook listings into the store and coordinates author-count refreshes across nodes. No runtime defect was identified. One repository gate still needs attention: a Go file grows past the 1,000-line limit, which would fail the size-ratchet check until the new declarations are moved to another file.

Security architecture risk: Minimal · up to d3d59

The inspected changes preserve listing access controls, narrow anonymous author-image eligibility, and bound refresh execution. No introduced or worsened issue materially affecting security, failure containment, rollback, or ownership was established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — The image endpoints accept anonymous requests identifying a stored audiobook or person and redirect to its stored or resolved artwork URL. This exposure predates the PR and remains unscoped by profile. The new author-photo lookup narrows eligible people to those credited as an audiobook author; it does not grant arbitrary people-photo access.

Trust Boundaries and Controls

  • observed — Library listing routes remain inside bearer authentication. Access-resolution failure returns 403 before library lookup. Request-provided image identifiers enter parameterized queries; the database returns the stored path rather than accepting an image path directly from the request.

Resilience and Maintainability Implications

  • observed — Batched streaming releases the initial ID-query rows before hydration and stops further batch emission when loading or writing fails. Hydration memory is bounded by batch size, although the complete ID set remains in memory and the operation still represents a whole-library read.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the primary change: Audiobookshelf heavy reads (collapsed series, library listing, cover and author-image lookups) now read only the data they return, instead of loading the whole libr…
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.
Description check Passed The description is detailed and directly related to the changeset. It covers the Audiobookshelf heavy-read changes: collapsed series paging in SQL, streaming for limit=0 responses, narrow cover and au…
Full details: Title check

Explanation

The title names the primary change: Audiobookshelf heavy reads (collapsed series, library listing, cover and author-image lookups) now read only the data they return, instead of loading the whole library. The raw summary and description confirm the changes cover this aim, and the title's scope is clearly related to the changeset. The title follows the conventional commit form and is a single line of 80 characters.

Full details: Description check

Explanation

The description is detailed and directly related to the changeset. It covers the Audiobookshelf heavy-read changes: collapsed series paging in SQL, streaming for limit=0 responses, narrow cover and author-image lookups, home shelf query changes, and the coordinated author-view refresh with its new one-row table. It also lists the validation performed, the benchmark evidence, and the risks, such as the truncated-body behavior on stream errors and the author image route no longer serving non-author photos.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-triage silo-triage Bot added the size/XL 500–999 added + deleted lines (all files); change volume, not priority. label Nov 14, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T00:32:00.667444Z 66846d3 New commits
🔒 Security Review ✅ Completed 2026-11-15T00:34:13.205083Z 66846d3 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8fef242f02

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/audiobooks/media_store.go Outdated
Comment on lines +1141 to +1143
if err := s.Pool.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM abs_author_counts_refresh WHERE refreshed_at > now() - $1::interval)`,
minInterval).Scan(&fresh); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Run refresh queries on the connection holding the lock

When database.max_connections is 1 (explicitly permitted by internal/config/admin_settings.go), pglock.TryAcquire reserves the pool's only connection, and this s.Pool.QueryRow waits forever for another connection. The background refresh in service.go uses context.Background(), so it never times out or reaches the deferred lock release, leaving other database requests blocked too. Execute the freshness check, refresh, and timestamp update through lock.Conn() instead of acquiring additional pooled connections.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed and fixed in 0344ba6. With one pooled connection, the advisory lock held it and the freshness query waited for a second one forever. The refresh now runs every statement on the connection that holds the lock (lock.Conn()), and each background run gets a deadline of one interval. A database test runs the refresh on a pool capped at one connection: it times out on the previous code and passes now.

@silo-triage silo-triage Bot added go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish stacked Base is another open PR; merge in stack order named in the body labels Nov 14, 2026
Base automatically changed from fix/abs-library-items-filters-and-sort to main November 15, 2026 00:07
@silo-triage silo-triage Bot added size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. and removed size/XL 500–999 added + deleted lines (all files); change volume, not priority. labels Nov 15, 2026
Quick104 and others added 3 commits November 14, 2026 19:08
…ole library

collapseseries=1 loaded and hydrated every book to fold series in Go;
it now folds and pages in SQL and loads only the page. limit=0 keeps
meaning the whole library, as real ABS does, and streams it in batches
of 1,000 books instead of holding every hydrated book in memory.

The unauthenticated author image route read every book by the author to
find one photo path, and the cover route ran a full item lookup; both
now read one column. The author image only serves people who wrote an
audiobook.

Recently Added walks the library's first-seen index instead of sorting
every book, and the series list picks its page before reading preview
books. The authors view refreshes once per interval across the cluster
instead of on every node, pages by name with the person ID as a
tiebreaker, and is bypassed when a book in the library is also in a
library the profile disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nection

With database.max_connections at 1, the refresh held the pool's only
connection for its advisory lock and then waited forever for another.
The refresh now runs on the locked connection, and each background run
gets a deadline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Record when an author view refresh started, so a slow refresh does not
make the next tick skip. Cache the disabled-library overlap check with
the other short-lived counts. Order Recently Added the way its index
does, drop the unused library filter in the no-library fallback, and fix
the store interface comments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Quick104
Quick104 force-pushed the perf/abs-heavy-reads branch from 42c306a to a6329b9 Compare November 15, 2026 00:16
@silo-kody

silo-kody Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@silo-triage silo-triage Bot added size/XL 500–999 added + deleted lines (all files); change volume, not priority. and removed size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. labels Nov 15, 2026
Comment thread internal/audiobooks/media_store.go Outdated
Comment on lines +1184 to +1190
n, err := s.cachedAudiobookCount(ctx, `
SELECT COUNT(*) FROM (
SELECT 1 FROM media_item_libraries here
JOIN media_item_libraries hidden ON hidden.content_id = here.content_id
WHERE here.media_folder_id = $1 AND hidden.media_folder_id = ANY($2)
LIMIT 1
) overlap`, []any{int(libraryID), disabled})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Security critical

Cached overlap check can expose authors from disabled libraries

After a book is added to a disabled library, a cached negative overlap lets ListLibraryAuthors expose its author and book count until the cache expires. Recheck current membership before using the materialized view, or invalidate the cached result on membership changes.

Prompt for LLM
File internal/audiobooks/media_store.go, lines 1184-1190:

Cached overlap check can expose authors from disabled libraries

A cached negative overlap lets `ListLibraryAuthors` read the unrestricted materialized view after a book is added to a disabled library, exposing its author and book count until the cache expires. Recheck overlap against current membership before using the materialized view, or invalidate the cached result on membership changes.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d3d59f8. This is an access answer, so it is no longer cached: every request runs an EXISTS that starts from the disabled libraries' memberships, probes this library by primary key, and stops at the first overlap. A new database test refreshes the author view, adds a book to a disabled library, and checks the next request leaves its author out; it fails on the cached version.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That addresses the reported issue: checking overlap on every request removes the stale cached access decision, and the regression test covers the membership-change scenario.

I haven’t independently verified the commit or run the test.

Comment thread internal/audiobooks/media_store.go Outdated

// loadListing loads and hydrates the books ids names, in that order.
func (s *ABSMediaStore) loadListing(ctx context.Context, ids []string, access catalog.AccessFilter, libraryID int64) ([]*models.MediaItem, error) {
items, err := s.Items.GetByIDs(ctx, ids)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Kody Rules high

Unbounded listings produce unbounded media-record batches

ListAudiobooks and ListAudiobooksCollapsed can request a whole library, producing an arbitrarily large database batch. Limit the IDs passed to each GetByIDs call, then combine the results before restoring the requested order.

Kody rule violation: Batch scoped Go lookups and bound dependency fan-out

Prompt for LLM
File internal/audiobooks/media_store.go, line 339:

Unbounded listings produce unbounded media-record batches

Bound the number of IDs passed to each `GetByIDs` call and combine the results before restoring the requested order. `ListAudiobooks` and `ListAudiobooksCollapsed` can call this path without a limit, so a whole-library request can otherwise produce an arbitrarily large database batch.

Kody rule violation: [Batch scoped Go lookups and bound dependency fan\-out](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/d2a64d9a-568c-46c2-9fa4-ad93c54ef90e?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d3d59f8: loadListing loads and hydrates at most 1,000 IDs per query, and the other whole-library loader (listAudiobookIDs, used by author and series detail and the shelves) now goes through it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the update. The reported 1,000-ID batching in loadListing, and routing listAudiobookIDs through it, addresses the unbounded database batch concern. I haven’t independently verified the commit.

Comment on lines +1395 to +1400
total, err := s.cachedAudiobookCount(ctx, `SELECT COUNT(*) FROM (
SELECT LOWER(s.series_name)
FROM audiobook_series s JOIN media_items mi ON mi.content_id = s.content_id
WHERE ` + where + `
WHERE `+where+`
GROUP BY LOWER(s.series_name) HAVING COUNT(*) > 1
) t`
if err := s.Pool.QueryRow(ctx, countSQL, args...).Scan(&total); err != nil {
) t`, args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

Cached zero count hides newly created series

A newly scanned multi-book series remains absent from the endpoint until the 60-second cache expires. Avoid caching zero counts in cachedAudiobookCount, or invalidate the series count when membership or series metadata changes.

Prompt for LLM
File internal/audiobooks/media_store.go, lines 1395-1400:

Cached zero count hides newly created series

A cached zero series count makes the endpoint return an empty list even after a scan creates a multi-book series, until the 60-second cache expires. Avoid caching zero counts or invalidate the series count when library membership or series metadata changes.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d3d59f8: cachedAudiobookCount no longer caches a zero, so a library that reads empty mid-scan shows its first series and books on the next request.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for addressing this. Based on your description, not caching zero counts resolves the reported issue: the next request will recount and can show newly scanned books and series. I haven’t independently verified the commit.

return nil, 0, fmt.Errorf("abs_media_store: list audiobooks: %w", err)
return nil, nil, 0, fmt.Errorf("abs_media_store: list audiobooks: %w", err)
}
ids, err := pgx.CollectRows(rows, pgx.RowTo[string])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Performance medium

Whole-library streaming buffers every matching ID before sending data

Whole-library requests use unbounded memory and wait for the complete ID query before onTotal or any items are sent. Replace pgx.CollectRows with bounded ID batches and hydrate each batch before fetching the next.

Prompt for LLM
File internal/audiobooks/media_store.go, line 294:

Whole-library streaming buffers every matching ID before sending data

The streaming path collects every matching content ID before calling `onTotal` or emitting any items, so whole-library requests still incur unbounded per-request memory and wait for the complete ID query before sending a response. Fetch IDs in bounded pages or batches and hydrate each batch before fetching the next.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Leaving this. The stream holds only the matching IDs before the first batch: a few megabytes at 150,000 books, while the hydrated books, the large part, go out 1,000 at a time. The official Audiobookshelf app pages with limit=20 and never sends limit=0. Keyset batches would need the ordering columns per sort key carried between batches, which is more than this path is worth.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That’s a reasonable tradeoff for this PR. The streaming path still buffers all matching IDs and waits for the ID query before sending the first batch, but it avoids buffering the much larger hydrated results.

I’m comfortable leaving the suggestion unresolved as an accepted limitation, especially given the keyset-pagination complexity and the official app’s paginated usage. Third-party limit=0 usage remains the main uncertainty.

…e-library loads

The check that sends a profile with a disabled library to the
access-checked authors list was cached for a minute, so a book that had
just joined a disabled library still counted. It now runs on every
request and stops at the first overlap. Zero counts are no longer
cached, so a library mid-scan shows its first books at once, and every
listing loads at most 1,000 books per query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Comment on lines +1183 to +1191
err := s.Pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM media_item_libraries hidden
WHERE hidden.media_folder_id = ANY($2)
AND EXISTS (
SELECT 1 FROM media_item_libraries here
WHERE here.content_id = hidden.content_id AND here.media_folder_id = $1
)
)`, int(libraryID), disabled).Scan(&overlap)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Performance medium

Author pagination repeatedly scans disabled library memberships

Revises an earlier Kody suggestion on internal/audiobooks/media_store.go:1184 (2026-11-15 00:19 UTC).

Author syncs can repeat library-sized database work on every page when a large disabled library has no overlapping books. Avoid repeated scans of media_item_libraries while preserving fresh access decisions, for example with an overlap summary maintained transactionally with membership changes.

Prompt for LLM
File internal/audiobooks/media_store.go, lines 1183-1191:

**Revises an earlier Kody suggestion** on `internal/audiobooks/media_store.go:1184` (2026-11-15 00:19 UTC).

Author pagination repeatedly scans disabled library memberships

A profile with a large disabled library and no overlapping books must scan its disabled memberships again for every author page, so an author sync repeats library-sized database work for each request. Preserve fresh access decisions while avoiding repeated full membership scans, for example with an overlap summary maintained transactionally with membership changes.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Leaving this. When no book overlaps, any check has to read one side's memberships in full: this library's or the disabled libraries'. The query is a semi-join on the existing media_item_libraries indexes, so Postgres drives it from whichever side its statistics say is smaller and stops at the first overlap. That is one indexed scan per authors page, and only for viewers who have disabled a library. I'd rather pay that for a fresh access decision than cache it. A summary table kept in step with membership changes would remove the scan but is a larger change than this pull request; the cost is noted in the description's tradeoffs.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That tradeoff is reasonable for this PR. The query preserves fresh access decisions, and the repeated scan affects only profiles with disabled libraries. A transactionally maintained overlap summary could reduce that cost, but it would add complexity beyond this change.

One qualification: the indexes make either join direction possible, but the actual plan depends on PostgreSQL’s estimates and data distribution. If author pagination becomes slow for affected profiles, an EXPLAIN (ANALYZE, BUFFERS) on a representative no-overlap case would help quantify the cost.

…d listing

handler.go crossed the 1,000-line limit once #4211's base became main;
CollapsedAudiobook belongs in collapse.go with the code that builds it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@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

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2319b774-1c02-4f12-adb2-5256d9a85dc4
Commits

Reviewing files that changed from the base of the PR and between 436f0fb and d3d59f8.

Files selected for processing: 12

  • internal/audiobooks/abs/collapse.go
  • internal/audiobooks/abs/handler.go
  • internal/audiobooks/abs/libraries_handler.go
  • internal/audiobooks/abs/login_refresh_test.go
  • internal/audiobooks/abs/stream_items_test.go
  • internal/audiobooks/media_store.go
  • internal/audiobooks/media_store_heavy_reads_db_test.go
  • internal/audiobooks/media_store_items_db_test.go
  • internal/audiobooks/service.go
  • internal/backup/tables.go
  • migrations/sql/20261114224347_abs_author_counts_refresh_state.sql
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment thread internal/audiobooks/abs/handler.go Resolved
@Quick104
Quick104 merged commit d892d6e into main Nov 15, 2026
25 checks passed
@Quick104
Quick104 deleted the perf/abs-heavy-reads branch November 15, 2026 01:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/XL 500–999 added + deleted lines (all files); change volume, not priority. stacked Base is another open PR; merge in stack order named in the body

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant