Skip to content

feat(catalog): typo-tolerant Postgres search fallback (did-you-mean) - #386

Merged
Quick104 merged 5 commits into
mainfrom
feat/db-fuzzy-search-fallback
Jul 17, 2026
Merged

Quick104 merged 5 commits into
mainfrom
feat/db-fuzzy-search-fallback

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Two commits: one feature (typo-tolerant Postgres search) and one follow-up hardening/correctness pass from an adversarial review.

Problem

Misspelled searches returned nothing on Postgres-backed deployments. When someone searched the library and mistyped a title — intersteller, godfathr, jurasic — the Postgres search path returned an empty result set, because it only did exact full-text matching. Users saw a "no results" screen for titles that plainly exist. (Meilisearch deployments already had typo tolerance; this only affected the Postgres fallback path.)

The obvious fix was a performance trap. Simply OR-ing a fuzzy match into the main search made every search slow. On a real library that turned routine, correctly-spelled searches into multi-second queries — a reliability regression for everyone in order to help the misspelling minority.

The first cut of the fallback paginated incorrectly. Fuzzy matches are shown after the exact matches as one combined list. The initial stitching used page-offset math and drifted past the first page: the reported result count grew as you paged (page 1 said "31", page 2 said "33"), titles from page 1 reappeared on page 2, paging far past the end kept re-running the pointless fuzzy query, and a tiny page size (e.g. an autocomplete asking for 3) could hide the fuzzy results behind a page the client was told didn't exist.

Solution

feat(catalog): typo-tolerant search for the Postgres (non-Meilisearch) path

The fuzzy arm is a completely separate query (buildFuzzySearchSQL / buildFuzzySearchFromParsed in internal/catalog/item_repo.go), not an OR into the main FTS WHERE. It matches only on the trigram-indexed title_normalized column (public.normalize_search_text($1) % mi.title_normalized) and ranks only by similarity() on that same column — it never references the title tsvectors, so it pays no per-row search-vector rebuild. That rebuild over the lossy trigram candidate set was the entire cause of the multi-second regression.

It fires only when the exact FTS block is sparse (< fuzzyFallbackThreshold = 5 hits) and the query clears a min-token gate (>= 4 chars, eligibleForFuzzy in search_query.go), so the common case stays on the untouched fast exact path. It's wired into SearchPage (not just the thin Search wrapper) so the catalog search provider benefits too. Shared scope predicates (type / library / access / manga-chapter exclusion) are extracted into appendSearchScopeFilters so the exact and fuzzy queries filter identically.

Speed (measured):

  • Exact full-text only: ~60 ms vs. fuzzy OR'd into the main query: ~217 ms on a 175k-title dev DB (and far worse on prod-sized data) — the reason for the separate-query design.
  • On the live 183k-title catalog (EXPLAIN ANALYZE): exact query for a typo ~0.8 ms (0 hits → triggers fallback); fuzzy fallback ~5–27 ms, always via the trigram index, no vector rebuild.

Search examples it now fixes:

  • intersteller → Interstellar (similarity 0.63)
  • godfathr → GodFather (0.58), The Godfather
  • jurasic → Jurassic titles
  • breakin (134 exact hits) → fuzzy correctly does not fire (common case stays on the fast path)

refactor(catalog): correct fuzzy-search pagination and parse the query once

Because the fallback only runs when exact results are sparse (< 5) and the fuzzy part is capped at fuzzyMaxResults = 50, the whole combined list is tiny. So instead of fragile per-page offset math, searchWithFuzzyFallback fetches that small combined list once and slices the requested page in memory (execSearchBlock is the shared engine behind both blocks). Every page is then correct by construction: stable total, no repeats, no wasted work past the end. Cursor-style callers (no total requested) get the fuzzy results as a single terminal first page rather than a misleading "more results" flag.

Before → after, typo search intersteller (21 results, page size 5):

  • Total reported on page 2: 31 → 33 (drifting) → 21 (stable)
  • Repeated titles across pages: yes → none
  • Request past the end (offset 500): 2–3 DB queries → 0 extra queries
  • Autocomplete (page size 1): fuzzy hidden → paginates correctly

This commit also parses the raw query once in SearchPage (was parsed three times — the eligibility check plus each SQL builder) and precomputes the normalized form the gate needs at parse time.

This branch was rebased onto latest main (160 commits, incl. #282 OPA access groups, #228 media_items NOT NULL, #247 jellycompat fast-paths); the two hardening fixes below fold in as part of the same two commits.

Risk / follow-ups

  • Cursor-mode recall is capped at one page (by design). For callers that don't request a total (SkipTotal), fuzzy results are served only as a terminal first page; there's no next-page fuzzy result, because a bare offset cursor can't locate the FTS/fuzzy block boundary on a follow-up request. Exact-count callers (the default) paginate the combined result fully.
  • The fuzzy path re-reads the small exact block in a second query, so a title written in the sub-millisecond gap between the two reads could be missed until the next search. Harmless and inherent to a multi-query design.
  • The shared scope helper inherits main's FTS library-visibility form (JOIN + NOT ... = ANY(disabled)) rather than the leak-safe EXISTS/NOT-EXISTS form. This is identical to and faithfully mirrors the existing FTS path — not worsened by this change — but the fuzzy fallback does inherit it.
  • No relevant open issue exists for fuzzy/typo search, so this PR does not close one.

Verification

  • go build ./..., go vet ./internal/catalog/..., gofmt — all clean.
  • go test ./internal/catalog/... passes, including the fuzzy-specific suite: TestItemRepo_BuildFuzzySearchSQL, TestItemRepo_BuildFuzzySearchSQL_CursorModeOmitsWindowCount, TestEligibleForFuzzy, TestItemRepo_Search_FTSQueryHasNoFuzzyArm, TestItemRepo_Search_ScoredCTEExposesItemColumnNames, TestItemRepo_Search_GroupByHasNoOutputAliases.
  • Adversarial review (pagination + SQL/integration): confirmed no duplicate/gap/wrong-total in reachable inputs, valid CTE/GROUP BY, correct arg ordering, and scope-filter parity between the FTS and fuzzy builders against rebased main. Two low-risk findings surfaced and were folded into the commits: a negative-limit/offset slice-panic guard in searchWithFuzzyFallback (latent; unreachable via the HTTP parser today), and a comment cross-reference fix (the gin_trgm_ops index is migration 105, not 138).
  • Schema dependencies verified present post-rebase: public.normalize_search_text (migrations 127/138), title_normalized generated column + idx_media_items_title_normalized_trgm GIN index (migration 105).

AI-use disclosure

Implemented with AI assistance (Claude). The rebase onto main, the adversarial review, and the two hardening fixes were AI-assisted; all build/test verification was run and reported as above.

Summary by CodeRabbit

  • New Features

    • Added a trigram-based fuzzy title-match fallback for eligible, sparse searches, improving recall for near matches.
  • Bug Fixes

    • Improved query normalization consistency between exact and fuzzy paths.
    • Fixed pagination totals/“more results” behavior for sparse and cursor-based views.
    • Tightened library scoping so filters apply correctly in both modes.
    • Preserved repo ordering when strict filtering would otherwise yield zero results for fuzzy-eligible queries.
  • Tests

    • Expanded coverage for fuzzy eligibility, cached normalized text, SQL routing (FTS vs fuzzy), pagination semantics, similarity-floor rules, and scoping correctness.

…) path

## What this does (plain language)

When someone searches the library and misspells a title — "intersteller",
"godfathr", "jurasic" — the Postgres-backed search used to return nothing,
because it only did exact full-text matching. This adds a "did you mean"
fallback: when the normal search finds little or nothing, we run a second,
typo-tolerant lookup and surface the closest titles.

This only affects deployments that search via Postgres (the fallback path).
Meilisearch already does its own typo tolerance and is left untouched.

## Why not just make the main query fuzzy

The obvious approach — OR a trigram similarity match into the main search — is a
performance trap. The trigram operator is "lossy", so Postgres re-checks every
near-miss candidate by rebuilding three title search-vectors per row. On a real
library that turned routine searches into multi-second queries.

Measured on a 175k-title dev database:
  - exact full-text only:               ~60 ms
  - fuzzy OR'd into the main query:      ~217 ms (and far worse on prod-sized data)

## How it works

The fuzzy arm is a completely separate query (buildFuzzySearchSQL). It matches
only on the trigram-indexed title_normalized column and ranks only by
similarity() on that same column — it never touches the title search-vectors, so
it pays no per-row rebuild. It runs only when the exact search is "sparse" (fewer
than 5 hits) and the query is long enough for the trigram index to help (>= 4
characters), so the common case stays on the fast exact path. It is wired into
SearchPage (not just the thin Search wrapper) so the catalog search provider
benefits too.

## Measured on the live 183k-title catalog (read-only EXPLAIN ANALYZE)

  - exact query for a typo:   ~0.8 ms (0 hits -> triggers the fallback)
  - fuzzy fallback query:     ~5-27 ms, always via the trigram index, with no
                              search-vector rebuild
  - "intersteller" -> Interstellar (similarity 0.63)
  - "godfathr"     -> GodFather (0.58), The Godfather
  - "breakin" (134 exact hits) -> fuzzy correctly does NOT fire

Shared scope predicates (type / library / access / manga-exclusion) are extracted
into appendSearchScopeFilters so the exact and fuzzy queries filter identically.

Adapted from the earlier feat/search-fuzzy-fallback prototype onto main's current
SearchPage / includeTotal architecture.
…y once

Follow-up to the fuzzy fallback, from an adversarial code review. Two things: a
pagination correctness fix and a small performance/readability cleanup. Both were
validated against the live 183k-title catalog.

## The pagination bug (plain language)

Fuzzy results are shown after the exact results, as one combined list. The first
version stitched that list together with page-offset math, and got the math wrong
past the first page:

  - the reported result count grew as you paged (page 1 said "31 results",
    page 2 said "33");
  - titles shown on page 1 could reappear on page 2;
  - paging far past the end still ran the (pointless) fuzzy query every time;
  - a tiny page size (e.g. an autocomplete asking for 3) could hide the fuzzy
    results behind a page the client was told did not exist.

## The fix

Because the fuzzy fallback only runs when exact results are sparse (< 5) and the
fuzzy part is capped at 50, the whole combined list is tiny. So instead of
fragile per-page offset math, we now fetch that small combined list once and take
the requested slice in memory. Every page is then correct by construction: stable
total, no repeats, no wasted work past the end.

Before -> after, typo search "intersteller" (21 results, page size 5):
  - total reported on page 2:        31 then 33 (drifting)  ->  21 (stable)
  - repeated titles across pages:    yes                    ->  none
  - request past the end (offset 500): 2-3 DB queries       ->  0 extra queries
  - autocomplete (page size 1):      fuzzy hidden           ->  paginates correctly

Cursor-style callers (that don't ask for a total) can't locate the boundary
between the two blocks on a later page, so they now get the fuzzy results as a
single terminal first page — no misleading "more results" flag.

## The cleanup

The raw query string was being parsed three times per search (once for the
eligibility check, once in each SQL builder). It is now parsed once in SearchPage
and passed down; the shared search-text derivation is extracted so the two
builders can't disagree; and the normalized form the eligibility gate needs is
precomputed at parse time. ("Performance first", per the repo guidelines.)

Also considered and rejected: excluding exact hits from the fuzzy query with a
NOT(full-text) clause instead of by id. It reintroduced the search-vector rebuild
the whole design avoids — measured ~51 ms vs ~20 ms on the worst case — so
id-based exclusion stayed.

Known limitation: the fuzzy path re-reads the small exact block in a second
query, so a title written in the sub-millisecond gap between the two reads could
be missed until the next search. Harmless and inherent to a multi-query design.
@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9c6353b9-ce89-415c-b44f-2c1f80eab4a2

📥 Commits

Reviewing files that changed from the base of the PR and between 1d06ee7 and 09ac996.

📒 Files selected for processing (3)
  • internal/catalog/catalog_resolver.go
  • internal/catalog/item_repo.go
  • internal/catalog/item_repo_test.go

📝 Walkthrough

Walkthrough

Changes

Fuzzy search fallback

Layer / File(s) Summary
Parsed query eligibility and catalog filtering
internal/catalog/search_query.go, internal/catalog/catalog_resolver.go, internal/catalog/item_repo_test.go
Parsed queries cache normalized text, fuzzy eligibility requires a normalized token of at least four runes, and eligible results bypass empty strict filtering.
Shared FTS and fuzzy SQL
internal/catalog/item_repo.go, internal/catalog/item_repo_test.go
FTS and trigram SQL builders share search text and scope filters while retaining separate ranking, exclusion, similarity-floor, and count behavior.
Sparse result fallback execution
internal/catalog/item_repo.go
Sparse FTS results can be combined with capped, deduplicated fuzzy matches, with cursor and exact pagination metadata derived from the combined results.

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

Sequence Diagram(s)

sequenceDiagram
  participant SearchPage
  participant execSearchBlock
  participant searchWithFuzzyFallback
  participant execFuzzyBlock
  participant buildFuzzySearchFromParsed
  SearchPage->>execSearchBlock: Execute parsed FTS search
  execSearchBlock-->>SearchPage: Return results and sparsity metadata
  SearchPage->>searchWithFuzzyFallback: Combine sparse FTS results with fuzzy candidates
  searchWithFuzzyFallback->>execFuzzyBlock: Execute capped fuzzy block
  execFuzzyBlock->>buildFuzzySearchFromParsed: Build query excluding FTS content IDs
  buildFuzzySearchFromParsed-->>execFuzzyBlock: Return fuzzy SQL and arguments
  execFuzzyBlock-->>searchWithFuzzyFallback: Return fuzzy results and truncation state
  searchWithFuzzyFallback-->>SearchPage: Return combined page and pagination metadata
Loading

Suggested labels: v1

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: a typo-tolerant Postgres search fallback for catalog search.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/db-fuzzy-search-fallback

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.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 12, 2026

@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: 04dca4283f

ℹ️ 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/catalog/item_repo.go Outdated
}
}
if len(filter.DisabledLibraryIDs) > 0 {
*conditions = append(*conditions, fmt.Sprintf("NOT (mil.media_folder_id = ANY($%d))", *argIdx))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use anti-join library filters for fuzzy search

When DisabledLibraryIDs is set and a media item is linked to both a disabled folder and another folder, this joined-row predicate can be satisfied by the non-disabled mil row, then the GROUP BY collapses the item and returns it. Because the new fuzzy fallback also calls this helper, typo searches can surface items from disabled libraries; the existing libraryAccessConditions/appendLibraryAccessConditions path in internal/catalog/access_filter.go uses independent NOT EXISTS predicates specifically to avoid this single-row join leak.

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 — valid, and fixed in 1d06ee7.

appendSearchScopeFilters now delegates to the leak-safe appendLibraryAccessConditions (the same item-scoped EXISTS/NOT EXISTS form GetByIDs/EnsureAccessible already use) instead of the JOIN media_item_libraries mil + NOT (mil.media_folder_id = ANY(...)) predicate. An item linked to both a disabled and a non-disabled library no longer survives via the passing membership row. The disabled-only path keeps the argument-free positive-membership EXISTS so orphan (link-less) items don't slip through a vacuous NOT EXISTS. Since the FTS and fuzzy builders share this helper, both are covered by one fix. Added TestItemRepo_Search_LibraryScopeUsesIndependentExistsPredicates pinning the EXISTS/NOT EXISTS shape and the absence of a JOIN for both builders.

Comment on lines 909 to 910
if !includeTotal {
queryLimit = limit + 1

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 Preserve fuzzy fallback for small cursor pages

For include_total=false callers with small limits, queryLimit = limit + 1 is not enough to decide whether the exact FTS block is sparse. If limit is 1–3 and the typo has 2–4 incidental exact hits, ftsHasMore is true, so ftsFullyKnown is false and fuzzy fallback is skipped; subsequent offsets are explicitly disallowed from triggering fuzzy, making the typo-tolerant results unreachable. Fetch at least fuzzyFallbackThreshold rows for the sparse probe in cursor mode before deciding not to run the fallback.

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.

Valid — fixed in 1d06ee7.

In cursor mode SearchPage now floors the FTS probe at fuzzyFallbackThreshold rows (instead of limit + 1), and execSearchBlock returns the pre-trim fetched count so sparsity is judged as fetched < fuzzyFallbackThreshold — independent of the caller's page size. So limit=2 with 3 incidental exact hits now correctly detects a sparse block and fires the typo fallback, while the returned page is still trimmed to limit with a correct hasMore. Exact mode is unchanged (it judges sparsity by the page-independent window count).

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

🧹 Nitpick comments (1)
internal/catalog/item_repo_test.go (1)

385-532: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add tests for searchWithFuzzyFallback orchestration and cursor-mode hasMore.

The new tests thoroughly cover SQL shape and eligibility gating, but the searchWithFuzzyFallback orchestration (combined-result slicing, cursor vs. exact-mode totals, hasMore at the block boundary) and SearchPage's cursor-mode hasMore path are not exercised. A runtime bug in execSearchBlock's cursor-mode limit handling (see comment in item_repo.go) would not be caught by SQL-shape assertions alone.

🤖 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/catalog/item_repo_test.go` around lines 385 - 532, Add tests
covering searchWithFuzzyFallback orchestration: combined FTS/fuzzy result
slicing, exact-mode totals, cursor-mode behavior, and hasMore when results
exactly reach the page/block boundary. Also exercise SearchPage’s cursor-mode
hasMore path, including the execSearchBlock limit handling described in
item_repo.go, using the repository’s existing test/mocking patterns.
🤖 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.

Nitpick comments:
In `@internal/catalog/item_repo_test.go`:
- Around line 385-532: Add tests covering searchWithFuzzyFallback orchestration:
combined FTS/fuzzy result slicing, exact-mode totals, cursor-mode behavior, and
hasMore when results exactly reach the page/block boundary. Also exercise
SearchPage’s cursor-mode hasMore path, including the execSearchBlock limit
handling described in item_repo.go, using the repository’s existing test/mocking
patterns.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0db2f0a7-892f-402a-abde-dd16d568df62

📥 Commits

Reviewing files that changed from the base of the PR and between 28c6ddc and 04dca42.

📒 Files selected for processing (3)
  • internal/catalog/item_repo.go
  • internal/catalog/item_repo_test.go
  • internal/catalog/search_query.go

…-limit cursor recall

Addresses two findings from the PR #386 review bots.

## Library-scope leak (Codex P1)

The search scope helper shared by the FTS query and the trigram fuzzy fallback
filtered libraries with `JOIN media_item_libraries mil` +
`NOT (mil.media_folder_id = ANY($disabled))`. An item linked to BOTH a disabled
and a non-disabled library fans out to two joined rows; the non-disabled row
satisfies the deny check, GROUP BY collapses the item back, and it surfaces in
search results despite the disabled library. Because the new fuzzy fallback
reuses this helper, typo searches could leak disabled-library items too.

appendSearchScopeFilters now delegates to the leak-safe
appendLibraryAccessConditions (access_filter.go), which emits item-scoped
EXISTS/NOT EXISTS subqueries — the same form GetByIDs/EnsureAccessible already
use — and needs no membership JOIN. The disabled-only path keeps its
argument-free positive-membership EXISTS so orphan items don't slip through a
vacuous NOT EXISTS. The scored CTEs keep GROUP BY (now required only for the
MAX() ranking aggregates). New regression test pins the EXISTS/NOT EXISTS shape
and the absence of a JOIN for both the FTS and fuzzy builders.

## Small-limit cursor recall (Codex P2)

In cursor mode (include_total=false) the FTS probe fetched only limit+1 rows.
For a tiny caller limit (e.g. an autocomplete asking for 2) with a few incidental
exact hits, that made ftsHasMore true, so the block never looked "sparse" and the
typo fallback never fired — and subsequent offsets are barred from triggering it,
so the fuzzy results were unreachable entirely.

SearchPage now floors the cursor-mode probe at fuzzyFallbackThreshold rows, and
execSearchBlock returns the pre-trim row count so sparsity is judged as
`fetched < threshold` independent of the caller's page size. The returned page is
still trimmed to limit with correct hasMore. Exact mode is unchanged (it judges
sparsity by the page-independent window count).
Quick104 and others added 2 commits July 16, 2026 20:54
Addresses the confirmed findings from a deep review of the fuzzy-search
fallback:

- Cursor mode now enters the fallback only when the whole sparse FTS
  block fits the caller's page, so the terminal fuzzy page can never
  hide exact matches the plain hasMore path would have surfaced
  (jellycompat clients with EnableTotalRecordCount=false lost matches).
- execSearchBlock takes a querier and returns its untrimmed rows;
  SearchPage hands the already-fetched block to the fallback instead of
  re-running an identical FTS query on every sparse search.
- Fuzzy truncation is detected with LIMIT cap+1 instead of a
  COUNT(*) OVER () window count that only fed a debug log; truncated
  exact-mode responses now report total_exact=false rather than
  presenting the cap as an exact count.
- The fuzzy query runs in a transaction pinning
  pg_trgm.similarity_threshold via SET LOCAL, so match quality cannot
  drift with cluster configuration.
- When the FTS block has real hits, fuzzy augmentation demands
  similarity >= 0.45 so correctly-spelled sparse queries only gain
  near-identical titles instead of base-threshold trigram noise.
- filterCatalogSearchItems no longer erases fuzzy matches on the
  filtered/sorted/prefix resolver path: a typo token is never a
  substring of the titles it matched, which left typo search returning
  zero results there while the plain search box showed matches.
- The cursor probe floor applies only when the fallback can fire;
  cursor fuzzy fetches no more rows than the terminal page can serve.
- slog.Debug -> slog.DebugContext (sloglint); reuse
  contentIDsFromMediaItems instead of a duplicate helper; document the
  title-only fuzzy scope.

Verified against the dev deployment: stable totals across pages, no
duplicates, small-limit cursor recall restored, filtered-path typo
search working, ~160ms typo-path latency.

Part of PR #386.

Co-Authored-By: Claude Fable 5 <[email protected]>
…search

Full-string trigram similarity is diluted by every extra trigram a long
title contributes, so a typo of one word could never reach titles like
"Avengers: Endgame" ("avegners" scores ~0.38 against "avengers" but far
below threshold against the full title). Swap the fuzzy predicate from %
to <<% (strict_word_similarity), which scores the query against the best
word-boundary extent of the title. At equal thresholds <<% is a strict
superset of %, and the existing gin_trgm_ops index serves both — no
migration needed.

The SET LOCAL pin moves to pg_trgm.strict_word_similarity_threshold and
is load-bearing: the 0.6 server default would reject ordinary one-edit
typos outright.

Ranking is strict word similarity first with whole-title similarity()
as tie-break, so near-identical short titles ("The Avengers") sort above
long titles that merely contain the matched word.

The 0.45 augmentation floor deliberately stays on whole-title
similarity(): word similarity rates embedded prefix words far too high
("coral" scores 0.5 against "coraline"), which dev testing showed would
flood a correctly-spelled sparse query with 27 noise rows. Zero-hit
(true typo) queries skip the floor, so the new long-title recall applies
where it matters.

Dev-verified: "avegners" now returns The Avengers first, then Avengers
Grimm / Avengers: Endgame; "coraline" still returns exactly its 4 real
titles; cursor small-limit recall, filtered-path typo search, pagination
stability, and ~160ms typo-path latency all unchanged.

Part of PR #386.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit b96e359 into main Jul 17, 2026
1 check was pending
@Quick104
Quick104 deleted the feat/db-fuzzy-search-fallback branch July 17, 2026 00:56

@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: 09ac996f35

ℹ️ 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".

// while the plain search box shows matches. When a fuzzy-eligible
// query would be emptied entirely, trust the repo's relevance
// ordering instead.
return items

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Limit the fuzzy bypass to repository-ranked candidates

When an eligible query has no substring match in an exact-ordered source, this returns the original items unchanged. resolveExactOrderedMediaItems also calls this helper for library/user collections and personal sources such as favorites, watchlists, and history, whose items were fetched by ID rather than ranked by SearchPage; for example, searching a watchlist for zzzz now returns the entire watchlist instead of no matches. Only bypass filtering when the candidates are known to come from the fuzzy repository search, or apply an actual fuzzy filter to these sources.

Useful? React with 👍 / 👎.

filtered = append(filtered, item)
}
}
if len(filtered) == 0 && len(items) > 0 && eligibleForFuzzy(parsed) {

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 Preserve fuzzy candidates when sparse FTS has a strict hit

In the non-direct search path, fetchAllSearchCandidates can return the combined FTS and fuzzy blocks, but this bypass is taken only when no item passes the substring filter. If even one of the 1–4 sparse FTS results contains the query tokens—for example, an incidental overview match—all fuzzy correction candidates are discarded, despite that being precisely the result-count range where SearchPage intentionally augments FTS. Advanced-filter searches therefore lose typo corrections that the direct search path returns.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants