Skip to content

perf(catalog): build the letter index in one window pass - #3994

Merged
Quick104 merged 1 commit into
mainfrom
perf/catalog-letters-index
Nov 11, 2026
Merged

Quick104 merged 1 commit into
mainfrom
perf/catalog-letters-index

Conversation

@Quick104

@Quick104 Quick104 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

On a large library, the A–Z jump bar shows up a second or more after the grid. queryCatalogLetters builds the bar, and the web LetterBar waits for it, as will the Apple and Android rails. On 100,000 titles, a cold request takes 0.82–1.02 s, while the first catalog page takes about 75 ms. The per-node cache keeps an index for two minutes, so every later open pays the same cost again.

The query sorted the whole list by title, folded each row's first character to a letter with translate/upper, buffered every row again for COUNT(*) OVER (), then sorted the list a second time by position to find where the letter changes. This change does the same work in one window pass, which cuts a cold request on 100,000 titles to 0.53–0.56 s.

Approach

letterIndexSQL numbers the rows once, using the browse's own ORDER BY as a named window. From that pass it keeps only the first row, each row whose first character differs from the row before, and the last row. Only those rows, usually a few hundred, are folded to a letter. The Go reader merges neighbouring runs that fold to the same letter (e then é under a linguistic collation) and gets the total from the last row's position. The letters, counts, positions and runs in the response are unchanged, and positions still count rows in the order queryCatalogItems pages.

The remaining cost is the title sort itself, which runs strcoll once per comparison under a glibc collation. An index-ordered scan avoids that sort, but the planner chooses it only with enable_sort off, and it is slower for a small library inside a large catalog, so this change leaves the plan to the planner. The cache's TTL stays as it is. The web client refetches the index after a scan, so serving an expired entry would hand it the old one. Only scans and item refreshes publish a change event, so invalidating on events would miss edits and deletions.

Server only. No API, schema, or migration change. silo-apple and silo-android need nothing.

Validation

  • Postgres tests for the letter index pass, including with the old implementation and the new test. The test now walks the cursor pager three titles a page instead of one page, and seeds 'Allo 'Allo! and Ève, which glibc en_US sorts among the A and E titles. Both tests are already in scripts/ci/db-contracts.txt.
  • One-off comparison of old and new output on 100,032 seeded titles: identical for asc and desc, under the database's en_US.utf8 collation and with the title key forced to COLLATE "C"; also identical for a last_watched rule (which adds a CTE), empty results, and the episode scope.
  • go build ./..., go vet, gofmt, go mod tidy -diff, make lint-changed, make lint-router-recovery, make verify-apiv2-openapi, make verify-apiv2-contract, make verify-local-paths, make verify-case-collisions, make verify-size-ratchet: pass.
  • make test-go: all packages pass except two real-ffmpeg tests in internal/mediasample and internal/playback, which fail against the local ffmpeg 6.1 and do not import internal/catalog.
  • Web checks not run; no web files changed.

Measured on a disposable sandbox with PostgreSQL 18, en_US.utf8 (glibc), default work_mem, warm buffers, one movie library seeded to 25,032 and then 100,032 titles. Endpoint times are curl totals on the host, with the server restarted before each cold request.

Old New
SQL, 25,032 titles, asc 182–188 ms ~120 ms
SQL, 100,032 titles, asc 930–1,170 ms 555–595 ms
SQL, 100,032 titles, desc 816–857 ms 578–628 ms
Endpoint cold, 100,032, asc 0.89–1.02 s 0.56 s
Endpoint cold, 100,032, desc 0.82–0.85 s 0.53–0.54 s
Endpoint warm (cache hit) 5–50 ms 3–6 ms
First catalog page, same library — 68–88 ms

Not measured: the production library that prompted this, ICU or C as the database's default collation (only COLLATE "C" on the key), and behaviour under concurrent load or across several nodes.

EXPLAIN (ANALYZE, BUFFERS) excerpts, 100,032 titles, asc

Old (842–899 ms in this run). Of that, ~135 ms is scan and joins, ~390 ms the title sort, ~270 ms the COUNT(*) OVER () node where the per-row fold is evaluated, and ~70 ms the second sort and LAG:

WindowAgg  (actual time=896.925..896.949 rows=37.00 loops=1)
  Window: w1 AS (ORDER BY marked.start)
  ->  Sort  (actual time=896.916..896.927 rows=37.00 loops=1)
        ->  Subquery Scan on marked  (actual time=847.085..896.876 rows=37.00 loops=1)
              Filter: marked.opens_run
              ->  WindowAgg  (actual time=847.084..891.782 rows=100032.00 loops=1)
                    Window: w1 AS (ORDER BY ranked."position")
                    ->  Sort  (actual time=847.066..855.669 rows=100032.00 loops=1)
                          Sort Key: ranked."position"
                          Sort Method: external merge  Disk: 3336kB
                          ->  Subquery Scan on ranked  (actual time=581.387..828.887 rows=100032.00 loops=1)
                                ->  WindowAgg  (actual time=581.386..818.652 rows=100032.00 loops=1)
                                      Window: w2 AS ()
                                      ->  WindowAgg  (actual time=461.195..547.674 rows=100032.00 loops=1)
                                            ->  Sort  (actual time=461.182..525.397 rows=100032.00 loops=1)
                                                  Sort Key: (lower(COALESCE(NULLIF(btrim(mi.sort_title), ''::text), mi.title))), mi.content_id COLLATE "C"
                                                  Sort Method: external merge  Disk: 6160kB
                                                  ->  Hash Semi Join  (actual time=29.645..137.386 rows=100032.00 loops=1)

New (570–668 ms in this run):

Sort  (actual time=568.588..568.599 rows=53.00 loops=1)
  Sort Key: numbered.start
  ->  Subquery Scan on numbered  (actual time=442.120..568.525 rows=53.00 loops=1)
        Filter: (numbered.opens OR numbered.closes)
        Rows Removed by Filter: 99979
        ->  WindowAgg  (actual time=442.113..563.168 rows=100032.00 loops=1)
              Window: w AS (ORDER BY (lower(COALESCE(NULLIF(btrim(mi.sort_title), ''::text), mi.title))), mi.content_id)
              ->  Sort  (actual time=442.092..502.234 rows=100032.00 loops=1)
                    Sort Method: external merge  Disk: 6160kB
                    ->  Hash Semi Join  (actual time=29.480..142.660 rows=100032.00 loops=1)

Evidence

Evidence: none, no user-visible change

Risks

None identified. The response contract is unchanged. A cold request on a large library is faster but still sorts every match, so it still grows with library size and keeps the existing 10-second deadline.

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 says there is none.

AI Disclosure

  • Harness: T3 Code running Claude Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated; not yet human verified
  • Adversarial review: one independent read-only review of the diff by a separate Claude Code review agent (claude-opus-5-5), asked for any input where old and new output differ. No findings. It noted that the CTE plan, empty results, and the episode scope had no test, and old and new output were then compared for those on the sandbox (identical).

🤖 Generated with Claude Code

Note

Build catalog letter index in a single SQL window pass

Reworks previewPagePlan.letterIndexSQL to rank rows by plan order and return only rows that open a letter run plus the final row, with the folded letter, zero-based position, and an opens flag. The Go loader (QueryExecutor.queryLetterIndex) now tracks the total row count from positions and passes run starts to the new letterIndexOfRuns helper, which computes run lengths and per-letter counts. letterBucketSQL now takes an initial-character expression and applies accent folding to it.

  • Adds Ève and 'Allo 'Allo! fixtures to the Postgres test and updates expected letter counts; orderedTitleKeys now collects title keys across up to 100 cursor pages.
  • Behavioral Change: letterBucketSQL callers must pass an initial-character expression, not a full title-key expression; letter counts are now merged in Go for letters that span multiple runs.

Macroscope summarized 41a66a8.

The letter index behind queryCatalogLetters sorted the whole title-ordered
list, folded every row's initial to a letter, buffered the list for a total,
then sorted it again by position to find where the letter changes. It now
numbers the rows in one pass over the browse order, keeps only the rows where
the initial changes plus the last row, folds just those to a letter, and
merges neighbouring runs that share a letter in Go. The response is
unchanged.

The DB test now walks the cursor pager a few titles a page and seeds titles
that a linguistic collation interleaves with the letters ('Allo 'Allo!, Ève).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 11, 2026
@coderabbitai

coderabbitai Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

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 24 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: d30079a0-ae0b-416f-8a02-8352eb7fb26d
Commits

Reviewing files that changed from the base of the PR and between 7b3e84c and 41a66a8.

Files selected for processing: 2

  • internal/catalog/letter_index.go
  • internal/catalog/letter_index_db_test.go
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-kody

silo-kody Bot commented Nov 11, 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 ❌

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 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-11T20:59:31.397408Z 41a66a8 PR opened
🔒 Security Review ✅ Completed 2026-11-11T21:02:54.364552Z 41a66a8 PR opened
ℹ️ 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.

@Quick104
Quick104 merged commit 2ee1b72 into main Nov 11, 2026
18 checks passed
@Quick104
Quick104 deleted the perf/catalog-letters-index branch November 11, 2026 21:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant