Skip to content

fix(jellycompat): guard aux search paths and index-back person search - #252

Merged
Quick104 merged 2 commits into
mainfrom
feat/aux-search-guards
Jul 1, 2026
Merged

Quick104 merged 2 commits into
mainfrom
feat/aux-search-guards

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

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 /Items BoxSet list are served directly by PostgreSQL and in-memory scans, not by the Meilisearch index that backs the main /Items media 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 SearchTerm requests 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 /Persons request 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):

SearchTerm Server time to respond
a 13,048 ms / 14,781 ms
am 2,474 ms
ame 1,298 ms
amer 1,396 ms
ameri 1,258 ms / 1,454 ms
americ 1,212 ms / 1,694 ms
america 919–2,611 ms

Even 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:

  • auxSearchTermTooShort rejects a non-empty SearchTerm shorter than 3 runes without touching any backend; clampAuxSearchLimit caps 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.
  • The 3-rune floor is deliberate: 3 runes is the shortest length a pg_trgm trigram 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 (/Items BoxSet, in-memory collection filter)

The Meilisearch-backed /Items media 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: a and am fall below the 3-rune floor and are rejected without touching any backend (13–15 s → instant), while ame through america now 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 with name ILIKE '%' || $1 || '%' instead of 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 scan on idx_people_name that walked the whole table for rare terms. 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 itself case-insensitive, so matching behavior is preserved (including the pre-existing treatment of % and _ in the term as LIKE wildcards).

Risk / follow-ups

  • The term-length floor and result cap are compile-time constants, not server-configurable. A reasonable follow-up is to move them into server_settings so operators can tune or disable them without a rebuild.
  • Terms of 1–2 characters now return empty on the three gated paths (people, hints, box-sets). This is intentional, but clients that previously showed suggestions for 1–2 char input will show an empty state; there is no "keep typing" signal to the client.
  • Client teams (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.
  • Under a PostgreSQL generic plan, a common 3-char term takes ~83 ms (trigram bitmap + top-N sort) rather than the ~8 ms the custom plan achieves — still far below the prior pathology, but noted.
  • No new user-facing capability; this is a reliability/perf bugfix, so it is not gated by the v1 scope process.

Verification

  • go build ./internal/..., go vet ./internal/jellycompat/ ./internal/catalog/, and go test ./internal/jellycompat/ ./internal/catalog/ all pass; gofmt clean; make verify-local-paths passes.
  • Adversarial review found no correctness defect: the ILIKE swap preserves wildcard, case-folding, and NULL semantics; the only other PersonRepository.Search caller is unaffected; no test asserts the old SQL or threshold.
  • EXPLAIN ANALYZE on production silo-postgres (889,302 people), using the parameterized query under both custom and generic plan-cache modes:
    • rare 3-char qzx: 304 ms → 1–8 ms (trigram bitmap index)
    • rare 4-char zzzz: 329 ms → 1–2 ms (trigram bitmap index)
    • common 3-char ann: 15 ms → 7–74 ms (btree early-stop / trigram bitmap)
    • New worst case across all terms is ~83 ms (generic-plan common 3-char term).

AI-use disclosure

Implemented with assistance from Claude Code (analysis, code, and the production EXPLAIN ANALYZE measurements above).

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).
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@CoffeeKnyte, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 18 minutes

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).

How can I continue?

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 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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7ed751a5-2b63-44f2-bcbc-b05e33141872

📥 Commits

Reviewing files that changed from the base of the PR and between 75bcafb and 28699fa.

📒 Files selected for processing (2)
  • internal/jellycompat/handlers_collections.go
  • internal/jellycompat/handlers_items.go
📝 Walkthrough

Walkthrough

This PR adds a search-guard module (search_guard.go) providing term-length checks and result-limit clamping, integrates it into HandleGetPersons, HandleSearchHints, and handleBoxSetsList to short-circuit short search terms and cap limits, and switches the person search SQL predicate to ILIKE for pg_trgm compatibility.

Changes

Auxiliary search guarding

Layer / File(s) Summary
Search guard helpers and tests
internal/jellycompat/search_guard.go, internal/jellycompat/search_guard_test.go
New unexported constants and auxSearchTermTooShort/clampAuxSearchLimit helpers gate minimum term length and cap result limits, validated by table-driven tests.
Handler integration of search guards
internal/jellycompat/handlers_persons.go, internal/jellycompat/handlers_items.go, internal/jellycompat/handlers_collections.go
HandleGetPersons, HandleSearchHints, and handleBoxSetsList now return empty results early for too-short search terms and clamp requested limits via the guard helpers.
ILIKE predicate for trigram index
internal/catalog/person_repo.go
PersonRepository.Search predicate changed to name ILIKE '%' || $1 || '%' from a LOWER(name) comparison, with comments on pg_trgm index intent and case-insensitive equivalence.

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
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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
Title check ✅ Passed The title accurately summarizes the main changes: guarding auxiliary search paths and restoring indexed person search.
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 Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/aux-search-guards

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.

@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: 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".

Comment thread internal/jellycompat/handlers_items.go Outdated
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) {

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 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 👍 / 👎.

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.

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).

@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

🧹 Nitpick comments (1)
internal/jellycompat/search_guard.go (1)

23-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Confusing constant semantics: auxSearchMinTermLen actually stores the max rejected length, not the minimum allowed length.

auxSearchMinTermLen = 2 combined with len(...) <= auxSearchMinTermLen is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 712059c and 75bcafb.

📒 Files selected for processing (6)
  • internal/catalog/person_repo.go
  • internal/jellycompat/handlers_collections.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/handlers_persons.go
  • internal/jellycompat/search_guard.go
  • internal/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.
@Quick104
Quick104 merged commit dd9e01f into main Jul 1, 2026
7 checks passed
@Quick104
Quick104 deleted the feat/aux-search-guards branch July 1, 2026 13:05
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants