Repository navigation
fix(jellycompat): guard aux search paths and index-back person search - #252
Conversation
Short, recursive type-ahead terms (e.g. a single "a") against the
PostgreSQL people index and the in-memory collection/box-set filter
produced multi-second scans that pegged the server when a client fired
one search per keystroke. Every jellycompat search path except the
Meilisearch-backed /Items media search now rejects a provided SearchTerm
shorter than 3 runes without touching any backend, and caps results at
20 regardless of the client-requested Limit:
- /Persons (PostgreSQL people scan)
- /Search/Hints (catalog search)
- /Items BoxSet (in-memory collection filter)
Shared policy + helpers live in search_guard.go (auxSearchMinTermLen=2,
i.e. reject 1-2 runes / allow 3+, and auxSearchMaxResults=20) with unit
coverage. The 3-rune floor is deliberate: 3 runes is the point where a
pg_trgm trigram index becomes usable, so the gate lines up with the index
and still lets legitimate short titles/names ("300", "Saw", 3-letter
actors) and 3-char type-ahead hints through.
PersonRepository.Search filters with `name ILIKE '%'||$1||'%'` rather
than `LOWER(name) LIKE '%'||LOWER($1)||'%'`. The old expression filtered
on LOWER(name), which the trigram GIN index idx_people_name_trgm (built
on name) could not serve, so every search fell back to an ordered index
scan on idx_people_name that walked the whole table for rare terms
(~300-400ms on the 889k-row production people table). ILIKE on name lets
pg_trgm serve rare 3+ char terms from the trigram index, while the planner
still picks the ordered btree scan with early termination for common
terms. ILIKE is case-insensitive, so behavior is preserved (including the
pre-existing treatment of % and _ in the term as LIKE wildcards).
Verified on production silo-postgres (889,302 people), parameterized query
under both custom and generic plan cache modes:
rare 3-char 'qzx': 304ms -> 1-8ms (trgm bitmap index)
rare 4-char 'zzzz': 329ms -> 1-2ms (trgm bitmap index)
common 3-char 'ann': 15ms -> 7-74ms (btree early-stop / trgm bitmap)
New worst case across all terms is ~83ms (generic-plan common 3-char).
|
Warning Review limit reached
Next review available in: 18 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. 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, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThis PR adds a search-guard module ( ChangesAuxiliary search guarding
Estimated code review effort: 2 (Simple) | ~12 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant Handler as HandleGetPersons/HandleSearchHints/handleBoxSetsList
participant Guard as SearchGuard
participant Repo as PersonRepository/DB
Client->>Handler: search request (searchTerm, limit)
Handler->>Guard: auxSearchTermTooShort(searchTerm)
alt term too short
Guard-->>Handler: true
Handler-->>Client: empty result (200)
else term valid
Guard-->>Handler: false
Handler->>Guard: clampAuxSearchLimit(limit)
Guard-->>Handler: clamped limit
Handler->>Repo: query with clamped limit
Repo-->>Handler: results
Handler-->>Client: search results
end
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 75bcafbcf2
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if query == "" { | ||
| // Gate short type-ahead terms and cap results, matching the policy applied | ||
| // to every search path outside the Meilisearch-backed /Items media search. | ||
| if query == "" || auxSearchTermTooShort(query) { |
There was a problem hiding this comment.
Allow short media queries in search hints
When a Jellyfin client calls /Search/Hints with a 1- or 2-character media title or prefix, such as SearchTerm=Up or It, this branch returns an empty hint response before reaching the h.content.SearchItems call below. Search hints are themselves a media-search path backed by the same catalog search provider used by /Items, so valid short titles become undiscoverable through global typeahead even though /Items?SearchTerm=Up can still return them. Limit this guard to the non-media auxiliary paths, or make it provider-aware, so short media-title hints are still served.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch — fixed in 28699fa.
You're right that /Search/Hints is served by h.content.SearchItems → directContentService.SearchItems → the catalog (Meilisearch-backed) search provider, i.e. the same path as /Items. That contradicts the guard's own "non-Meilisearch paths only" rationale, and Meilisearch already does its own short-term handling + bounding. Removed the auxSearchTermTooShort gate from HandleSearchHints so short titles (Up, It) stay discoverable; kept the empty-term check and the result clamp. The guard now applies only to the two genuinely non-Meilisearch paths (/Persons and box-sets).
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/jellycompat/search_guard.go (1)
23-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConfusing constant semantics:
auxSearchMinTermLenactually stores the max rejected length, not the minimum allowed length.
auxSearchMinTermLen = 2combined withlen(...) <= auxSearchMinTermLenis correct today (rejects ≤2, allows 3+), but the name strongly implies "the minimum term length allowed" (which would be 3, compared with<). The 18-line doc comment above exists specifically to explain away this mismatch. A future edit that "fixes" the off-by-one by changing<=to<(matching the apparent semantics of the name) would silently allow 2-char terms through.♻️ Suggested rename to align name/semantics
const ( - // auxSearchMinTermLen is the maximum SearchTerm length (counted in runes, - // after trimming) that is rejected. A non-empty term of this length or - // shorter returns no results WITHOUT querying any backend; only terms - // strictly longer than this are allowed to run. - auxSearchMinTermLen = 2 + // auxSearchMinTermLen is the minimum number of runes (after trimming) a + // non-empty SearchTerm must contain to run on a guarded aux search path. + auxSearchMinTermLen = 3 // auxSearchMaxResults caps how many results a guarded search path may return, // regardless of the client-requested Limit. auxSearchMaxResults = 20 ) func auxSearchTermTooShort(term string) bool { trimmed := strings.TrimSpace(term) if trimmed == "" { return false } - return len([]rune(trimmed)) <= auxSearchMinTermLen + return len([]rune(trimmed)) < auxSearchMinTermLen }🤖 Prompt for 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. In `@internal/jellycompat/search_guard.go` around lines 23 - 46, The constant in auxSearchTermTooShort has misleading semantics: auxSearchMinTermLen is being used as the maximum rejected length, not the minimum allowed length. Rename the symbol in internal/jellycompat/search_guard.go to match its behavior, and update the auxSearchTermTooShort comparison and surrounding comment so the name, docs, and `len([]rune(trimmed))` check all agree and future edits don’t introduce an off-by-one mistake.
🤖 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/jellycompat/handlers_collections.go`:
- Around line 298-305: Clamp the box-set search limit before paging in the
in-memory collection search path. The current flow in the collection handler
leaves query.limit unbounded, and slicePage interprets non-positive values as
uncapped, so apply clampAuxSearchLimit(query.limit) in the same path used by
HandleGetPersons and HandleSearchHints before building the result page. Keep the
change near the existing auxSearchTermTooShort and paging logic so the
collection search respects the same cap as the other search handlers.
---
Nitpick comments:
In `@internal/jellycompat/search_guard.go`:
- Around line 23-46: The constant in auxSearchTermTooShort has misleading
semantics: auxSearchMinTermLen is being used as the maximum rejected length, not
the minimum allowed length. Rename the symbol in
internal/jellycompat/search_guard.go to match its behavior, and update the
auxSearchTermTooShort comparison and surrounding comment so the name, docs, and
`len([]rune(trimmed))` check all agree and future edits don’t introduce an
off-by-one mistake.
🪄 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: d5c372ec-44df-441e-94e2-55a93fb17aa2
📒 Files selected for processing (6)
internal/catalog/person_repo.gointernal/jellycompat/handlers_collections.gointernal/jellycompat/handlers_items.gointernal/jellycompat/handlers_persons.gointernal/jellycompat/search_guard.gointernal/jellycompat/search_guard_test.go
Two review follow-ups on the aux-search guards:
- HandleSearchHints is served by the catalog (Meilisearch-backed) search
provider, which already bounds and short-term-handles its own results.
Gating it with auxSearchTermTooShort contradicted the guard's own
"non-Meilisearch paths only" policy and hid valid 1-2 char titles
("Up", "It") from global type-ahead. Drop the too-short gate there;
keep the empty-term check and the result clamp.
- handleBoxSetsList gated short terms but passed query.limit straight to
slicePage, which treats <=0 as no cap, so a box-set *search* was
uncapped unlike Persons/Hints. Clamp the limit when a search term is
present; empty-term browse keeps its client paging window.
…Silo-Server#252) * fix(jellycompat): guard aux search paths and index-back person search Short, recursive type-ahead terms (e.g. a single "a") against the PostgreSQL people index and the in-memory collection/box-set filter produced multi-second scans that pegged the server when a client fired one search per keystroke. Every jellycompat search path except the Meilisearch-backed /Items media search now rejects a provided SearchTerm shorter than 3 runes without touching any backend, and caps results at 20 regardless of the client-requested Limit: - /Persons (PostgreSQL people scan) - /Search/Hints (catalog search) - /Items BoxSet (in-memory collection filter) Shared policy + helpers live in search_guard.go (auxSearchMinTermLen=2, i.e. reject 1-2 runes / allow 3+, and auxSearchMaxResults=20) with unit coverage. The 3-rune floor is deliberate: 3 runes is the point where a pg_trgm trigram index becomes usable, so the gate lines up with the index and still lets legitimate short titles/names ("300", "Saw", 3-letter actors) and 3-char type-ahead hints through. PersonRepository.Search filters with `name ILIKE '%'||$1||'%'` rather than `LOWER(name) LIKE '%'||LOWER($1)||'%'`. The old expression filtered on LOWER(name), which the trigram GIN index idx_people_name_trgm (built on name) could not serve, so every search fell back to an ordered index scan on idx_people_name that walked the whole table for rare terms (~300-400ms on the 889k-row production people table). ILIKE on name lets pg_trgm serve rare 3+ char terms from the trigram index, while the planner still picks the ordered btree scan with early termination for common terms. ILIKE is case-insensitive, so behavior is preserved (including the pre-existing treatment of % and _ in the term as LIKE wildcards). Verified on production silo-postgres (889,302 people), parameterized query under both custom and generic plan cache modes: rare 3-char 'qzx': 304ms -> 1-8ms (trgm bitmap index) rare 4-char 'zzzz': 329ms -> 1-2ms (trgm bitmap index) common 3-char 'ann': 15ms -> 7-74ms (btree early-stop / trgm bitmap) New worst case across all terms is ~83ms (generic-plan common 3-char). * fix(jellycompat): stop gating meilisearch hints, clamp box-set search Two review follow-ups on the aux-search guards: - HandleSearchHints is served by the catalog (Meilisearch-backed) search provider, which already bounds and short-term-handles its own results. Gating it with auxSearchTermTooShort contradicted the guard's own "non-Meilisearch paths only" policy and hid valid 1-2 char titles ("Up", "It") from global type-ahead. Drop the too-short gate there; keep the empty-term check and the result clamp. - handleBoxSetsList gated short terms but passed query.limit straight to slicePage, which treats <=0 as no cap, so a box-set *search* was uncapped unlike Persons/Hints. Clamp the limit when a search term is present; empty-term browse keeps its client paging window.
One commit: a guard for the slow jellycompat search paths, plus an index-backed rewrite of the people-search query.
Important
These search paths do NOT go through Meilisearch — that is exactly why they need this guard.
/Persons,/Search/Hints, and the/ItemsBoxSet list are served directly by PostgreSQL and in-memory scans, not by the Meilisearch index that backs the main/Itemsmedia search. Meilisearch already does its own short-term handling, relevance ranking, and result bounding; these paths have none of that, so an unbounded short/recursive type-ahead term degrades to a full people-table scan or a full collection sweep on every keystroke. The guard supplies the missing floor + result cap for exactly these non-Meilisearch paths. The Meilisearch-backed media search is untouched.The captured incident happened to come from an Infuse client, but this is not Infuse-specific — any Jellyfin-compatible client that issues per-keystroke
SearchTermrequests to these endpoints (Infuse, VidHub, Roku, the web UI, etc.) can trigger the same stalls. The fix is server-side and applies to all of them.Problem
Type-ahead search could stall the server for seconds. Jellyfin-compatible clients send a new search request on every keystroke. Three search surfaces — the cast/people list, the global search-suggestions box, and the collections (box-set) list — ran unbounded scans that got slower the more people are in the library. A real example from production: a viewer typing "america" into people search made the client fire one
/Personsrequest per letter, and the server took multiple seconds to answer almost every keystroke — including 13–15 seconds just for the first "a". Because the requests pile up back-to-back as the user types, the whole server bogged down while someone was simply searching.Real production timings (
/Persons, Infuse client, one row per keystroke; server/user/network identifiers removed):aamameamerameriamericamericaEven completed searches stayed slow. Once a term was long enough to return results, a people-by-name search still took hundreds of milliseconds to over a second (e.g. "america" at ~1–2.6 s above) because the query was written in a way the existing name-search index could not help with, so the database walked the entire ~889,000-row people table every time.
Solution
Gate the non-Meilisearch search paths
A shared policy lives in
internal/jellycompat/search_guard.go:auxSearchTermTooShortrejects a non-emptySearchTermshorter than 3 runes without touching any backend;clampAuxSearchLimitcaps results at 20 regardless of the client-requested limit. An empty term is treated as a browse/list request, not a search, so browsing is never blocked.pg_trgmtrigram index can serve (a 1–2 char pattern forms no usable trigram), so the gate lines up with the index while still letting legitimate short titles/names ("300", "Saw", three-letter actors) and 3-char type-ahead hints through.Applied at the three gated callers:
internal/jellycompat/handlers_persons.go—HandleGetPersons(/Persons, PostgreSQL people scan)internal/jellycompat/handlers_items.go—HandleSearchHints(/Search/Hints, catalog search)internal/jellycompat/handlers_collections.go—handleBoxSetsList(/ItemsBoxSet, in-memory collection filter)The Meilisearch-backed
/Itemsmedia search (movies, TV, audiobooks, ebooks, music) is intentionally left ungated — it still works from the first character for every media type.Net effect on the cascade in the Problem section:
aandamfall below the 3-rune floor and are rejected without touching any backend (13–15 s → instant), whileamethroughamericanow clear the floor and are served by the trigram index below (≈10 ms instead of 1–3 s).Index-back person search
PersonRepository.Search(internal/catalog/person_repo.go) now filters withname ILIKE '%' || $1 || '%'instead ofLOWER(name) LIKE '%' || LOWER($1) || '%'. The old expression filtered onLOWER(name), which the trigram GIN indexidx_people_name_trgm(built onname) could not serve, so every search fell back to an ordered scan onidx_people_namethat walked the whole table for rare terms.ILIKEonnameletspg_trgmserve rare 3+ char terms from the trigram index, while the planner still picks the ordered btree scan with early termination for common terms.ILIKEis itself case-insensitive, so matching behavior is preserved (including the pre-existing treatment of%and_in the term asLIKEwildcards).Risk / follow-ups
server_settingsso operators can tune or disable them without a rebuild.silo-android,silo-apple): the gated-path behavior change is server-side only and additive, but worth a glance if a client relies on 1–2 char people/hint results.Verification
go build ./internal/...,go vet ./internal/jellycompat/ ./internal/catalog/, andgo test ./internal/jellycompat/ ./internal/catalog/all pass;gofmtclean;make verify-local-pathspasses.ILIKEswap preserves wildcard, case-folding, and NULL semantics; the only otherPersonRepository.Searchcaller is unaffected; no test asserts the old SQL or threshold.EXPLAIN ANALYZEon productionsilo-postgres(889,302 people), using the parameterized query under both custom and generic plan-cache modes:qzx: 304 ms → 1–8 ms (trigram bitmap index)zzzz: 329 ms → 1–2 ms (trigram bitmap index)ann: 15 ms → 7–74 ms (btree early-stop / trigram bitmap)AI-use disclosure
Implemented with assistance from Claude Code (analysis, code, and the production
EXPLAIN ANALYZEmeasurements above).