Skip to content

fix(scanner): keep the audiobook duplicate lookup fast before statistics catch up - #4280

Merged
Quick104 merged 2 commits into
mainfrom
fix/audiobook-duplicate-lookup-plan
Nov 15, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/audiobook-duplicate-lookup-plan

Conversation

@Quick104

@Quick104 Quick104 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

Other clients: N/A (no client-visible change)

The first audiobook scan on a server that already holds a large catalog gets slower with every book it adds. For each new book the scanner asks whether it is a moved copy of a book already indexed. That lookup joined people, credits, and items in whatever order the planner chose. PostgreSQL refreshes a table's statistics only after about a tenth of its rows change, so for much of that first scan the statistics still say there are no audiobooks and no author or narrator credits. The planner then starts from every author credit and checks each against every audiobook, normalizing each title with two regular expressions. One lookup took over 20 seconds, every scan worker was waiting on it, and the database host ran at full CPU.

This change makes the lookup's plan independent of statistics.

Approach

The query now resolves the author and narrator names through the LOWER(name) index first, materializes the items credited to both, and reads media_items by primary key into a second materialized set. The type = 'audiobook' test runs on that set. Tested on media_items itself, it lets the planner choose a partial books index and scan every audiobook once per candidate, which is the same trap.

The result set is unchanged: audiobooks with an author credit and a narrator credit matching the tagged names, filtered by year, duration, and title as before, in the same order and with the same limit.

Other statements that run once per book were not slow in the same scan and are not changed.

Validation

  • go build ./..., gofmt -l, go vet, make lint-changed, make verify-size-ratchet BASE_REF=origin/main, make verify-local-paths: clean.
  • go test ./internal/scanner/ for the audiobook tests against a migrated PostgreSQL 18 with pgvector: pass, including the contract that a renamed folder still finds its item through this lookup.
  • No new test. The lookup's result is covered by that contract. The fault is the planner's choice under stale statistics, which a test cannot hold steady: autovacuum refreshes statistics on small test tables within a minute.

Evidence

Nothing visible changes. Reproduced on a throwaway PostgreSQL 18 with autovacuum off and synthetic rows: a movie catalog with cast credits, analyzed, then audiobooks with one author and one narrator each inserted without a new ANALYZE, as during a first audiobook scan. EXPLAIN (ANALYZE, BUFFERS) under a generic plan for the same book, main at 1452ea2d10 against this branch at 7d0c185fca:

main    Execution Time: 54525.385 ms   Buffers: shared hit=9147453
        Index Only Scan on item_people (kind = 7)        rows=3000
          Index Scan on media_items (type = 'audiobook') loops=3000
branch  Execution Time: 0.986 ms       Buffers: shared hit=65
        Index Scan on people (lower(name))               rows=1
        Index Only Scan on item_people (kind, person_id) rows=1
        Index Scan on media_items (content_id)           loops=1
both    1 row: the same item

The same plan and timing difference showed on a real server whose statistics predated its first audiobook scan, where the old and new queries returned identical rows for a sample of indexed books.

Risks

  • On PostgreSQL versions without index skip scan, the credits lookup may read all credits of one kind from the index. That is a linear index-only read and does not depend on the number of audiobooks compared.

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, GitHub CLI
  • Model(s): claude-fable-5-2
  • Involvement: Fully AI-generated; human verification pending maintainer review
  • Review: Kody's finding that the type check ran after the row limit is fixed.
  • Adversarial review: n/a (one query rewritten; equivalence checked by comparing old and new results on real data)

🤖 Generated with Claude Code

Note

Rewrite scanner.audiobookDuplicateCandidateSQL with materialized CTEs

  • Reworks the audiobook duplicate candidate query in audiobook_scan.go to keep the lookup fast while library statistics catch up.
  • Uses a MATERIALIZED CTE with INTERSECT to find content IDs credited to both the matching author and narrator, instead of joining media_items, item_people, and people directly.
  • A second MATERIALIZED CTE joins those IDs back to media_items and carries content_id, title, type, and year into the existing downstream filtering and ordering.
  • Behavioral Change: qualifying content IDs are deduplicated before the media_items join, so multiple matching credit rows no longer produce repeated candidate rows.

Macroscope summarized 7d0c185.

…ics catch up

The lookup that decides whether a new audiobook is a moved copy of an
indexed one joined people, credits, and items in an order the planner chose.
During the first audiobook scan on a server with a large catalog, planner
statistics still say there are no audiobooks, and the chosen plan compares
every author credit with every audiobook, so each lookup gets slower as the
library fills.

Resolve the author and narrator names first, materialize the items credited
to both, and read media_items by primary key. The type check moves to the
caller so the planner cannot pick the partial books index.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@silo-triage silo-triage Bot added the size/S 0–49 added + deleted lines (all files); change volume, not priority. label Nov 15, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 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-15T05:04:39.960565Z 7d0c185 New commits
🔒 Security Review ✅ Completed 2026-11-15T05:06:45.029703Z 7d0c185 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.

@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 bug Something isn't working go Pull requests that update go code impact: perf Unusable slowness on normal hardware priority: P2 Limited scope, workaround exists, or polish labels Nov 15, 2026
@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The duplicate-candidate query now resolves author and narrator matches separately, intersects their credited content IDs, and applies existing filters and ordering to materialized media-item rows.

Changes: Audiobook duplicate candidates

Layer / File(s) Summary
Candidate query
internal/scanner/audiobook_scan.go
The query replaces direct joins with separate case-insensitive author and narrator lookups, intersects their credited content IDs, and applies the existing filters and ordering to materialized media-item rows.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: rxwatcher, rhainland, blurbery

Merge Risk: Minimal · up to 7d0c1

This change speeds up the audiobook duplicate lookup without intended behavior changes. No concrete defect was found, and the change is easy to roll back, so merge risk is minimal.

Architecture risk: Low · up to 7d0c1

The change affects 1 system.

Changed systems: internal

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — internal (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in internal/scanner/audiobook_scan.go: audiobookDuplicateCandidateSQL replaces direct joins from media items through author and narrator credits with separate case-insensitive person lookups, an intersection of their content IDs, and materialized candidate/item CTEs. The subsequent candidate query reads from the materialized items; later filters and ordering remain in place.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the audiobook duplicate lookup in the scanner is made fast regardless of planner statistics. The changeset rewrites audiobookDuplicateCandidateSQL to resolve names thr…
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 directly related to the changeset. It explains the slow audiobook duplicate lookup under stale PostgreSQL statistics, describes the new approach of resolving author and narrator nam…
Full details: Title check

Explanation

The title names the main change: the audiobook duplicate lookup in the scanner is made fast regardless of planner statistics. The changeset rewrites audiobookDuplicateCandidateSQL to resolve names through indexes, materialize credited IDs, and read media_items by primary key, which matches the title's intent. The title is specific and concise, and the 81-character length is acceptable.

Full details: Description check

Explanation

The description is directly related to the changeset. It explains the slow audiobook duplicate lookup under stale PostgreSQL statistics, describes the new approach of resolving author and narrator names through the LOWER(name) index, materializing credited item IDs, and reading media_items by primary key. It also gives validation steps and a performance evidence section, which match the audiobook_scan.go query rewrite in the raw summary and the PR objectives.

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
Recent 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: 970dbdc0-2ee0-47cf-9fce-0b2ce63c2e30
Commits

Reviewing files that changed from the base of the PR and between 93f2244 and 7d0c185.

Files selected for processing: 1

  • internal/scanner/audiobook_scan.go

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/scanner/audiobook_scan.go Outdated
return nil
}
if audiobookDedupeTitlesMatch(candidateTitle, cleanTitle) {
if candidateType == "audiobook" && audiobookDedupeTitlesMatch(candidateTitle, cleanTitle) {

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 critical

Non-audiobooks can crowd valid duplicates out of the candidate limit

Enough better-ranked non-audiobook rows can hide a moved audiobook, giving it a new identity and losing its listening progress. Apply the audiobook type filter before the 25-row limit while preserving a primary-key-driven lookup plan.

Prompt for LLM
File internal/scanner/audiobook_scan.go, line 1402:

Non-audiobooks can crowd valid duplicates out of the candidate limit

Non-audiobook rows now consume the SQL query's 25-row limit before the Go type check, so enough better-ranked matches can hide a moved audiobook and cause it to be assigned a new identity, losing its associated listening progress. Apply the audiobook type filter before the limit while preserving a primary-key-driven lookup plan.

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 7d0c185. The type test is back in SQL, applied to the materialized candidate rows before the limit, so a non-audiobook item can no longer take a slot. media_items is still read by primary key inside the materialized step, which keeps the plan independent of statistics.

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 fix. Applying the audiobook type filter before the limit addresses the reported issue, while the materialized primary-key lookup preserves the intended query plan.

Filter on the materialized candidate rows so a non-audiobook item cannot
take one of the 25 slots, while media_items is still read by primary key.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@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 ❌

@Quick104
Quick104 merged commit dfda77d into main Nov 15, 2026
21 checks passed
@Quick104
Quick104 deleted the fix/audiobook-duplicate-lookup-plan branch November 15, 2026 05:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code impact: perf Unusable slowness on normal hardware priority: P2 Limited scope, workaround exists, or polish size/S 0–49 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant