Skip to content

fix(recommendations): stop distant, obscure and unembedded titles crowding personal rows - #5175

Merged
Quick104 merged 13 commits into
test/recs-eval-harnessfrom
fix/recs-ranking
Nov 23, 2026
Merged

Quick104 merged 13 commits into
test/recs-eval-harnessfrom
fix/recs-ranking

Conversation

@Quick104

@Quick104 Quick104 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5174; review that first.

Problem

Related issue: N/A
Validation tasks: changes #1145 C1

Several ranking rules push weaker titles into personal rows:

  • A cluster row's candidate query ranks by how many of the cluster's genres a title carries before distance, so a distant title tagged with every genre beats a close match with fewer.
  • MMR scores a candidate without an embedding by relevance alone, with no λ and no redundancy penalty, so co-watch-only and Similar Users titles jump ahead of embedded ones.
  • The quality prior reads ratings for every title, so an obscure title with a high rating from a handful of votes gets the full boost.
  • Co-watch neighbors the embedding search missed get only the co-watch share of the blend, however similar they are.
  • Co-watch read errors are dropped silently.

This fixes each, measured with the holdout evaluation from the base pull request.

Approach

  • FindTasteProfileCandidates filters by genre and orders by distance, with a materialized CTE and ORDER BY distance + 0 so the relaxed HNSW scan's small inversions are sorted out. Watch Tonight cards, which want genre-first order, read five times their pool (up to 2000) and keep ranking it with FilterAndRankGenreMatches.
  • MMR gives a candidate without an embedding (missing, empty or all zeros) λ × relevance minus the round's mean redundancy among embedded candidates, and scales relevance by the largest score magnitude.
  • The quality prior reads ratings only for notable titles (notableSQL); other titles read as unrated, which the prior already leaves neutral.
  • Co-watch neighbors with an embedding get their real cosine to the source before blending.
  • Because You Watched reads the source's embedding and metadata in one query, and candidate details with the candidate search. "More like this" validation's remake penalty always lowers a score.
  • Co-watch read failures log at warn and fall back as before.

Two changes were tried and left out. Normalizing vectors before k-means lowered the evaluation's scores. Running "More like this" validation in Because You Watched dropped every candidate sharing no genre with the source, which emptied or shortened the row on a small test library for almost no gain in the evaluation.

Holdout evaluation, seeded data, mean of four personas:

Row Recall@20 before → after NDCG@20 before → after
For You 0.443 → 0.502 0.472 → 0.521
Clusters 0.117 → 0.177 0.107 → 0.163
Because You Watched 0.253 → 0.270 0.247 → 0.288
Similar Users 0.143 → 0.143 0.132 → 0.175

On a library where few titles have a logo and five keywords, the quality prior has little to work with and mostly stays off.

Validation

  • Recommendations and API handler packages against a migrated database: pass.
  • New tests: MMR edge cases (missing, empty and zero embeddings, all-negative pools), co-watch-only similarity, and Watch Tonight cards keeping the best genre match beyond their pool. Each fails without its fix. The MMR test's randomized oracle follows the same rules and now generates zero vectors and all-negative pools. A relevance test checks Because You Watched keeps a co-watched title of another genre.
  • Holdout evaluation: numbers above.
  • Go pre-PR gate: see the stack's top pull request.
  • Before and after web captures on a sandbox with the same seeded data: linked below. On that small library the cluster rows are empty at both builds, so the table above is the evidence for them.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/recs-ranking/

Risks

Personal rows change for every profile on the next refresh. After merge, #1145 C1 needs a re-check against its rubric because the output differs. No migration or API change.

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: Claude Code in T3 Code
  • Tool(s): Claude Code subagents; Codex CLI for review; Antigravity for the initial audit
  • Model(s): claude-opus-5-5 (implementation), gpt-6.2-sol (review), gemini-4-neon (initial audit)
  • Involvement: Fully AI-generated, directed by a maintainer; maintainer review pending
  • Adversarial review: gpt-6.2-sol reviewed each change against the code. It found that dropping the over-fetch cost Watch Tonight cards their best genre matches, that negative scores could reverse MMR and the remake penalty, and that zero vectors escaped the missing-embedding penalty; all are fixed with tests. It also noted Because You Watched could come back empty when its nearest candidates all fail the genre gate; sandbox captures showed that happening, so Because You Watched no longer runs that validation. CodeRabbit flagged that the relaxed scan's order could survive the outer sort on PostgreSQL 17 and later; the query now materializes the CTE and sorts on distance + 0.

Note

Fix personal rows crowded by distant, obscure, unembedded titles

  • Taste-profile candidate queries now select the nearest genre-matching candidates up to the limit, instead of a wider pool reordered by genre-match count. Quality ratings are returned only for notable titles; other titles get NULL (repo.go).
  • The candidate query now returns CandidateDetails (type, genres, embedding, added date, quality) in one round trip. This removes the separate GetBatchEmbeddings, GetItemMediaTypes, GetItemAddedDates, and GetItemQualityRatings reads; ranking now uses these details directly (personal.go, quality.go).
  • Co-watched titles missing from embedding search are now added to candidates and scored by their embedding similarity; co-watch read failures log a warning and continue (similar.go, cowatch.go).
  • applyMMR now preserves order for all-negative score pools and gives unembedded candidates the mean embedded similarity; validation penalties subtract from the score's absolute magnitude instead of multiplying (diversity.go).
  • Discover cards with selected genres now overfetch by 5x (capped at 2000) so genre ranking can find the best match beyond the pool (watch_tonight_cards.go).
  • Risk: profile refresh now emits exactly 114 statements; the budget test in holdout_eval_postgres_test.go fails if a new detail read is added. Genre-filtered candidate queries fetch at most limit from the ANN index, which can return fewer candidates on small genre pools.

Macroscope summarized 6541f5a.

Quick104 and others added 10 commits November 23, 2026 03:54
…ance order

FindTasteProfileCandidates fetched limit×5 nearest neighbours when genres
were given and then ordered them by how many selected genres each shared
before distance. A distant title matching every dominant genre pushed close
matches out of the limited pool, so cluster rows filled with off-taste
titles. The genre constraint now only filters (mi.genres && $genres) and the
pool is the nearest limit titles in distance order; the limit×5 over-fetch
had no purpose left and is gone.

Watch Tonight cards still order their pool genre-first through
FilterAndRankGenreMatches; their pool is now the nearest titles sharing a
selected genre.

Holdout evaluation (seeded data), before -> after:
  clusters R@20 0.117 -> 0.145, N@20 0.107 -> 0.124
  focused clusters R@20 0.119 -> 0.190, decoys in window 5.3 -> 1.3
  page recall 0.907 -> 0.921
  main, byw, similar unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l penalty

applyMMR scored a candidate without an embedding by its normalized
relevance alone, with no lambda and no redundancy penalty, while every
embedded candidate scored lambda × relevance minus (1-lambda) × its
similarity to the picks. An unembedded title therefore beat embedded ones
of noticeably higher relevance: in Similar Users, peer-loved titles from
relevance positions 15-31 landed at positions 2-8.

Such a candidate now scores lambda × relevance minus (1-lambda) × the mean
similarity of the embedded candidates still in the pool, the round's typical
redundancy, so it ranks near its relevance position. An empty embedding
counts as missing everywhere; before, an empty slice was treated as an
embedding with zero similarity. With no embedded candidates left, the
penalty is zero and the order stays relevance order. defaultMMRLambda is
unchanged.

Holdout evaluation (seeded data), before -> after:
  similar N@20 0.132 -> 0.175 (R@20 0.143 unchanged)
  focused similar N@20 0.530 -> 0.700
  unembedded titles in the similar window 6.0 -> 1.5 (the other personas'
  peer-loved titles now sit at positions 22-33, about where relevance puts
  them, instead of 2-8)
  main, clusters, byw unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The quality prior read catalogRatingSQL for every candidate, while the
rating-led rows order through catalogRatingOrderSQL, which puts notable
titles (a logo and at least five keywords) first. An obscure title rated
8.8 to 9.4 on a handful of votes got the prior's full lift and pushed
well-known neighbours out of the window. itemQualityRatingsQuery now applies
notableSQL, so a title that is not notable reads as unrated; applyQualityPrior
leaves an unrated candidate's score as it is and keeps it out of the
pool's rating statistics, so the gate is neutral, not a penalty.

Holdout evaluation (seeded data), before -> after:
  main R@20 0.443 -> 0.502, N@20 0.472 -> 0.521 (obscure in window 5.0 -> 2.5)
  focused main R@20 0.429 -> 0.500, N@20 0.425 -> 0.586
  clusters R@20 0.145 -> 0.177, N@20 0.124 -> 0.163
  byw R@20 0.253 -> 0.270, N@20 0.247 -> 0.288
  page recall 0.921 -> 0.939
  similar unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ty too

Because You Watched and "More like this" blend 0.7 × embedding similarity
with 0.3 × co-watch Jaccard. A co-watch neighbor the embedding search did not
return, because nearer titles filled its limit, got the co-watch share alone,
so it ranked below every title the search found however often the two were
watched together, even though its embedding was loaded right afterwards for
MMR (and, in "More like this", validation).

Both paths now read those embeddings before blending, and
withCowatchSimilarity adds each such neighbor with its cosine similarity to
the source, on the same scale as the search's candidates. A neighbor without
an embedding keeps its co-watch share alone, as the blendScores comment now
says. Neither path issues an extra query: Because You Watched reads the
embeddings once for blending, aversion and MMR, and "More like this" reads
the co-watch details before blending instead of after. Marked titles leave
the co-watch map before that read, which is equivalent to removing them
after the blend.

Holdout evaluation (seeded data), before -> after: unchanged
  byw R@20 0.270, N@20 0.288; similar R@20 0.143, N@20 0.175
  The evaluation's co-watched titles have no embedding, so it cannot show
  this; the new database test does, and fails without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Because You Watched and "More like this" discarded the error from
GetCowatchNeighbors, so a failing co-watch read silently turned both into
embedding-only rankings. They now log it at warn and drop any partial result,
keeping the embedding-only fallback.

Holdout evaluation (seeded data): unchanged (no read fails there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…milar

rankSimilar runs applyValidation (a genre gate and a remake/title-overlap
penalty) on every candidate; becauseYouWatched never did, and no history
shows that was intended. Because You Watched now validates its blended
candidates against the source too.

To read what validation needs without extra queries, it takes the source's
embedding and metadata from GetSimilarSource (one read instead of
GetEmbedding plus GetItemMetadata, whose error it ignored and could leave the
metadata nil), the candidates' details from FindSimilarCandidates, and the
co-watch neighbors' details from GetCandidateDetails, which replaces its
GetBatchEmbeddings read. The co-watch detail read and the embedding map are
shared with rankSimilar (addCowatchDetails, candidateEmbeddings).
applyValidation returns its candidates unchanged without source metadata, so
a nil source can no longer be dereferenced. GetItemMetadata has no caller
left and is removed.

Trade-off: a co-watched title sharing no genre with the source is now dropped
from Because You Watched, as from "More like this". The relevance test whose
co-watched movie was of another genre now uses one of the source's genre; it
checks the media-type rule, not cross-genre co-watch.

Holdout evaluation (seeded data), before -> after:
  byw R@20 0.270 -> 0.270, N@20 0.288 -> 0.289
  everything else unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ards

The case notes described how the ranking misbehaved before the fixes on
this branch. They now say what each set of titles checks, so they stay true
as the ranking changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l for genres

The taste candidate query now returns the nearest titles sharing a selected
genre in distance order, without its old five-fold over-fetch, so the cards'
genre-first ranking only saw the pool's nearest titles. A title matching
every selected genre a little further out could no longer lead. With genres
selected the cards read five times the pool, up to 2000, rank by genre
matches as before and keep the pool's worth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cores

MMR scaled relevance by the highest score, which reverses a pool whose
scores are all negative, and treated a zero vector as an embedding similar
to nothing, so it escaped the redundancy penalty a missing one takes. It now
scales by the largest magnitude and counts a zero vector as missing, as
co-watch blending also does. The remake penalty halved a score, which
raises a negative one; it now always lowers it. The holdout evaluation's
numbers are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Running "More like this" validation in Because You Watched dropped every
candidate sharing no genre with the source. On a small library few of the
nearest titles do, so rows came back with a handful of titles or not at
all, and the row left Home on a test library of a few dozen titles. The
holdout evaluation gained almost nothing from it (Because You Watched NDCG@20
0.288 -> 0.289), so the row goes back to unvalidated candidates; co-watched
titles of another genre are kept, and the relevance test checks that again.
It still reads the source and candidate details in one query each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T15:06:33.628944Z 6541f5a New commits
🔒 Security Review ✅ Completed 2026-11-23T15:09:24.936981Z 6541f5a 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-triage silo-triage Bot added the size/XL 500–999 added + deleted lines (all files); change volume, not priority. label Nov 23, 2026
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

Walkthrough

The changes update genre-filtered taste candidate retrieval, co-watch score blending, quality-rating eligibility, and MMR scoring. Discover-mode searches request additional candidates when genres are selected and cap the filtered results at the pool size.

Changes: Recommendation candidate and ranking flow

Layer / File(s) Summary
Taste candidate retrieval and Discover pool sizing
internal/recommendations/repo.go, internal/recommendations/relevance_test.go, internal/api/handlers/watch_tonight_cards.go, internal/api/handlers/watch_tonight_progress_test.go, internal/recommendations/hnsw_ef_search_db_test.go
Genre filters now restrict candidates without ranking them by genre-match count. Discover-mode searches request up to five times the pool size, capped at 2,000, when genres are selected; filtered results are capped at the pool size. Tests cover candidate ordering, pool limits, and a 1,200-candidate scan.
Co-watch candidate blending
internal/recommendations/cowatch.go, internal/recommendations/personal.go, internal/recommendations/similar.go, internal/recommendations/relevance_postgres_test.go, scripts/ci/db-contracts.txt
Because You Watched and Similar Items blend co-watch similarity with embedding candidates. The ranking paths load missing co-watch candidate details, exclude marked titles before blending, and log co-watch read failures. A Postgres test checks that a co-watched title outside the nearest embedding results can rank first.
Quality eligibility and MMR scoring
internal/recommendations/repo.go, internal/recommendations/diversity.go, internal/recommendations/diversity_test.go, internal/recommendations/defaultrows_postgres_test.go, internal/recommendations/ranking_postgres_test.go, internal/recommendations/holdout_eval_postgres_test.go
Quality-prior ratings are returned only for notable titles. MMR treats missing, empty, and zero-direction embeddings as unavailable, assigns unavailable candidates the mean similarity among remaining embedded candidates, and normalizes relevance by the largest absolute score magnitude. Tests and holdout descriptions reflect these rules.

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

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant BecauseYouWatched
  participant RecommendationRepository
  participant MMR
  Caller->>BecauseYouWatched: Request recommendations
  BecauseYouWatched->>RecommendationRepository: Load source embedding and metadata
  BecauseYouWatched->>RecommendationRepository: Read embedding candidates and co-watch neighbors
  BecauseYouWatched->>RecommendationRepository: Fetch missing co-watch candidate details
  BecauseYouWatched->>BecauseYouWatched: Blend co-watch similarity with embedding scores
  BecauseYouWatched->>MMR: Rank blended candidates
Loading

Possibly related issues

  • Issue 1961: The issue describes notable-title gating for IMDb and TMDB ratings in rating-led rows. This change applies a notable-title gate to quality-prior ratings, but does not implement the issue’s vote-weighted rating proposal.

Suggested reviewers: blurbery, rhainland

Merge Risk: Low · previous review 81a09

Genre-filtered taste candidates may occasionally come back slightly out of distance order on newer PostgreSQL versions, because the relaxed vector scan order can be preserved. This only subtly affects ranking quality and is a small fix. The rest of the ranking changes look sound and are covered by new tests.

Security architecture risk: Minimal · up to 81a09

Genre-selected Discover requests can consider more titles before returning cards, but the same viewing restrictions still apply and the response size does not increase. The review did not establish a new access bypass or a material availability regression.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — Selecting a genre on the personalized Discover path can increase database results transferred and candidates processed before truncation. The larger read does not apply to requests without genres or to the cold-start fallback. The 2,000-row cap does not bound how many entries the database examines.

Trust Boundaries and Controls

  • observed — Co-watch neighbors pass viewer access and media-type checks before the detail lookup. If that check errors, Because You Watched returns an error and Similar drops the co-watch contribution rather than ranking unchecked neighbors.

Hardening Proposals

  • proposed — Compare base and head query duration and database connection occupancy under concurrent genre-selected requests, including restrictive library filters. Use that comparison to determine whether the candidate cap also needs a query-work or concurrency limit.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the fix area (recommendations) and the main problem: distant, obscure and unembedded titles crowding personal rows. The changeset covers genre-first candidate ordering, MMR for unembed…
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 specific and related to the changeset. It states the problems addressed: genre-first cluster ranking, MMR scoring of candidates without embeddings, the quality prior applied to non-…
Full details: Title check

Explanation

The title names the fix area (recommendations) and the main problem: distant, obscure and unembedded titles crowding personal rows. The changeset covers genre-first candidate ordering, MMR for unembedded candidates, notability-gated quality ratings, and co-watch similarity, all aimed at that outcome. The title is specific and accurate, though it is long at 88 characters.

Full details: Description check

Explanation

The description is specific and related to the changeset. It states the problems addressed: genre-first cluster ranking, MMR scoring of candidates without embeddings, the quality prior applied to non-notable titles, co-watch neighbors missing from the embedding results, and silent co-watch read errors. It maps each fix to the affected areas (taste candidate query, MMR, quality prior, co-watch blending, Because You Watched, Watch Tonight cards). It also lists tests, a holdout evaluation table, risks such as personal rows changing on refresh, and the dropped validation change. This matches the diff summaries, including repo.go, diversity.go, cowatch.go, personal.go, similar.go, and the test files.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish stacked Base is another open PR; merge in stack order named in the body labels Nov 23, 2026

@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/recommendations/diversity_test.go: 1

62-63: Trivial · Maintainability & Code Quality · Quick win

Update the reference oracle to match the new MMR rules.

applyMMRQuadratic still differs from applyMMR in two places:

  • It treats a nonempty zero vector as embedded. The oracle then gives it zero redundancy and places it second in the zero-embedding fixture, producing a,u,d,b. Production produces a,d,b,u. The oracle should use the same direction check as production, so such a vector counts as missing.
  • It normalizes relevance by the largest signed score instead of the largest absolute score. For the all-negative fixture, this flips the sign of relevance, and the oracle returns a,c,b instead of a,b,c.

The randomized comparison does not generate either case. Its embeddings are normal draws, so a zero vector does not occur. Its scores are never negative. Add zero vectors and negative scores to the generator so the comparison covers the new rules.

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: 0f6081e1-90bb-45d8-9d72-40a9ab743148
Commits

Reviewing files that changed from the base of the PR and between d93652d and 81a09e9.

Files selected for processing: 15

  • internal/api/handlers/watch_tonight_cards.go
  • internal/api/handlers/watch_tonight_progress_test.go
  • internal/recommendations/cowatch.go
  • internal/recommendations/defaultrows_postgres_test.go
  • internal/recommendations/diversity.go
  • internal/recommendations/diversity_test.go
  • internal/recommendations/hnsw_ef_search_db_test.go
  • internal/recommendations/holdout_eval_postgres_test.go
  • internal/recommendations/personal.go
  • internal/recommendations/ranking_postgres_test.go
  • internal/recommendations/relevance_postgres_test.go
  • internal/recommendations/relevance_test.go
  • internal/recommendations/repo.go
  • internal/recommendations/similar.go
  • scripts/ci/db-contracts.txt

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/recommendations/repo.go Resolved
Quick104 and others added 3 commits November 23, 2026 05:25
… scan

The candidate query's outer ORDER BY distance could reuse the relaxed
iterative scan's order through the inlined CTE on PostgreSQL 17 and later,
leaving its small inversions in place; the genre-first sort this branch
removed had hidden that. The CTE is now materialized and the sort is on
distance + 0, as pgvector documents for relaxed ordering.

The MMR test's quadratic oracle now follows the same rules as applyMMR (a
zero vector counts as missing, relevance is scaled by the largest
magnitude), and its random pools include zero vectors and all-negative
scores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#5176)

The row builder read each candidate pool's embeddings, media types, added
dates and quality ratings in four further queries after its HNSW scan, for
every main-row anchor, cluster row, type supplement and Because You Watched
pool. The taste candidate scan now returns those columns
(FindTasteProfileCandidatesWithDetails), the Similar scan and the co-watch
details read add type, added date and quality rating, and the row builder
ranks from them. The per-ID lookups GetItemAddedDates, GetItemMediaTypes and
GetItemQualityRatings lose their last callers and go; Watch Tonight keeps
the genres-only FindTasteProfileCandidates, so its pools of up to 500
candidates do not carry embeddings.

Measured on the holdout evaluation's four measured personas, five traced
refreshes each:

- statements per refresh: 146 before, 114 after (-32, -22%); the focused
  persona alone: 145 before, 114 after
- removed reads, before: 32 statements, about 59 ms of database time per
  refresh (about 8% of a 760 ms refresh)
- wall time per refresh, four interleaved A/B runs on a loaded host:
  before 710-856 ms (median ~826), after 729-843 ms (median ~780); database
  time median ~448 ms before, ~413 ms after. The time gain is within the
  host's noise; the statement cut is exact.

The evaluation's metrics table is byte-identical before and after, and the
cached rows hold the same titles in the same order with the same reasons.
Scores of the persona with Not interested marks differ below 1e-7, as they
do between two runs of the old code: the aversion decays by wall-clock time.

TestProfileRefreshStatementBudgetPostgres pins the focused persona's refresh
at 114 statements (145 on the parent commit) in scripts/ci/db-pins.txt.
TestGetItemQualityRatingsPostgres becomes TestCandidateQualityRatingsPostgres
and reads the ratings from the candidate details.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@silo-triage silo-triage Bot added size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. and removed size/XL 500–999 added + deleted lines (all files); change volume, not priority. labels Nov 23, 2026
@Quick104
Quick104 merged commit 4b440a6 into test/recs-eval-harness Nov 23, 2026
4 checks passed
@Quick104
Quick104 deleted the fix/recs-ranking branch November 23, 2026 15:04
Quick104 added a commit that referenced this pull request Nov 23, 2026
…es in one pass, and measure both (#5174)

* test(recommendations): add a temporal-holdout evaluation of personal rows

TestRecommendationHoldoutEvalPostgres seeds the toy catalog plus titles for
four ranking cases (multi-genre decoys, unembedded titles, obscure
high-rated titles, non-unit embeddings), writes each persona's signals up to
a cutoff, and holds out the titles it enjoys afterwards. The real refresh
builds the rows, and the test logs Recall@20, NDCG@20 and intra-list
diversity per persona for the main, cluster, Because You Watched and
Similar Users rows, so later ranking changes can be compared before and
after. The run is the same every time.

It fails when a held-out title reaches the engine's input, a row holds a
title its persona engaged with before the cutoff, or the focused persona's
main-row recall drops below 0.25. It is listed in the database contracts.

The toy catalog's vector construction moves into toyVector so the
evaluation builds its extra titles in the same space; the catalog it builds
is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(recommendations): make the holdout evaluation fail on missing rows and stale data

A run cut short left its accounts, with their ratings and watches, and the
next run reused the same title IDs, so old activity could count toward peer
and co-watch thresholds. The fixture now clears the evaluation's accounts
too. The test also failed only on leaks and the focused main-row floor, so a
refresh that stopped writing cluster, Because You Watched or Similar Users
rows passed; every measured persona must now build every row kind, and a row
serving a title twice fails rather than inflating recall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(recommendations): vacuum embeddings after the holdout evaluation

The evaluation writes and then deletes about a thousand embeddings. Deleted
vectors stay in the HNSW graph until a vacuum, and on a reused database they
lowered the next run's recall enough that
TestFindSimilarAppliesAccessLimitsInSQLPostgres failed about one run in
three (main passed every run). The fixture now vacuums the table after its
delete; eight consecutive full-package runs passed afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(recommendations): spell neighbor the way the linter expects

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): stop distant, obscure and unembedded titles crowding personal rows (#5175)

* fix(recommendations): keep genre-constrained taste candidates in distance order

FindTasteProfileCandidates fetched limit×5 nearest neighbours when genres
were given and then ordered them by how many selected genres each shared
before distance. A distant title matching every dominant genre pushed close
matches out of the limited pool, so cluster rows filled with off-taste
titles. The genre constraint now only filters (mi.genres && $genres) and the
pool is the nearest limit titles in distance order; the limit×5 over-fetch
had no purpose left and is gone.

Watch Tonight cards still order their pool genre-first through
FilterAndRankGenreMatches; their pool is now the nearest titles sharing a
selected genre.

Holdout evaluation (seeded data), before -> after:
  clusters R@20 0.117 -> 0.145, N@20 0.107 -> 0.124
  focused clusters R@20 0.119 -> 0.190, decoys in window 5.3 -> 1.3
  page recall 0.907 -> 0.921
  main, byw, similar unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): give MMR candidates without embeddings a neutral penalty

applyMMR scored a candidate without an embedding by its normalized
relevance alone, with no lambda and no redundancy penalty, while every
embedded candidate scored lambda × relevance minus (1-lambda) × its
similarity to the picks. An unembedded title therefore beat embedded ones
of noticeably higher relevance: in Similar Users, peer-loved titles from
relevance positions 15-31 landed at positions 2-8.

Such a candidate now scores lambda × relevance minus (1-lambda) × the mean
similarity of the embedded candidates still in the pool, the round's typical
redundancy, so it ranks near its relevance position. An empty embedding
counts as missing everywhere; before, an empty slice was treated as an
embedding with zero similarity. With no embedded candidates left, the
penalty is zero and the order stays relevance order. defaultMMRLambda is
unchanged.

Holdout evaluation (seeded data), before -> after:
  similar N@20 0.132 -> 0.175 (R@20 0.143 unchanged)
  focused similar N@20 0.530 -> 0.700
  unembedded titles in the similar window 6.0 -> 1.5 (the other personas'
  peer-loved titles now sit at positions 22-33, about where relevance puts
  them, instead of 2-8)
  main, clusters, byw unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): read quality-prior ratings for notable titles only

The quality prior read catalogRatingSQL for every candidate, while the
rating-led rows order through catalogRatingOrderSQL, which puts notable
titles (a logo and at least five keywords) first. An obscure title rated
8.8 to 9.4 on a handful of votes got the prior's full lift and pushed
well-known neighbours out of the window. itemQualityRatingsQuery now applies
notableSQL, so a title that is not notable reads as unrated; applyQualityPrior
leaves an unrated candidate's score as it is and keeps it out of the
pool's rating statistics, so the gate is neutral, not a penalty.

Holdout evaluation (seeded data), before -> after:
  main R@20 0.443 -> 0.502, N@20 0.472 -> 0.521 (obscure in window 5.0 -> 2.5)
  focused main R@20 0.429 -> 0.500, N@20 0.425 -> 0.586
  clusters R@20 0.145 -> 0.177, N@20 0.124 -> 0.163
  byw R@20 0.253 -> 0.270, N@20 0.247 -> 0.288
  page recall 0.921 -> 0.939
  similar unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): score co-watch-only neighbors by their similarity too

Because You Watched and "More like this" blend 0.7 × embedding similarity
with 0.3 × co-watch Jaccard. A co-watch neighbor the embedding search did not
return, because nearer titles filled its limit, got the co-watch share alone,
so it ranked below every title the search found however often the two were
watched together, even though its embedding was loaded right afterwards for
MMR (and, in "More like this", validation).

Both paths now read those embeddings before blending, and
withCowatchSimilarity adds each such neighbor with its cosine similarity to
the source, on the same scale as the search's candidates. A neighbor without
an embedding keeps its co-watch share alone, as the blendScores comment now
says. Neither path issues an extra query: Because You Watched reads the
embeddings once for blending, aversion and MMR, and "More like this" reads
the co-watch details before blending instead of after. Marked titles leave
the co-watch map before that read, which is equivalent to removing them
after the blend.

Holdout evaluation (seeded data), before -> after: unchanged
  byw R@20 0.270, N@20 0.288; similar R@20 0.143, N@20 0.175
  The evaluation's co-watched titles have no embedding, so it cannot show
  this; the new database test does, and fails without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): log co-watch neighbor read failures

Because You Watched and "More like this" discarded the error from
GetCowatchNeighbors, so a failing co-watch read silently turned both into
embedding-only rankings. They now log it at warn and drop any partial result,
keeping the embedding-only fallback.

Holdout evaluation (seeded data): unchanged (no read fails there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): validate Because You Watched candidates like Similar

rankSimilar runs applyValidation (a genre gate and a remake/title-overlap
penalty) on every candidate; becauseYouWatched never did, and no history
shows that was intended. Because You Watched now validates its blended
candidates against the source too.

To read what validation needs without extra queries, it takes the source's
embedding and metadata from GetSimilarSource (one read instead of
GetEmbedding plus GetItemMetadata, whose error it ignored and could leave the
metadata nil), the candidates' details from FindSimilarCandidates, and the
co-watch neighbors' details from GetCandidateDetails, which replaces its
GetBatchEmbeddings read. The co-watch detail read and the embedding map are
shared with rankSimilar (addCowatchDetails, candidateEmbeddings).
applyValidation returns its candidates unchanged without source metadata, so
a nil source can no longer be dereferenced. GetItemMetadata has no caller
left and is removed.

Trade-off: a co-watched title sharing no genre with the source is now dropped
from Because You Watched, as from "More like this". The relevance test whose
co-watched movie was of another genre now uses one of the source's genre; it
checks the media-type rule, not cross-genre co-watch.

Holdout evaluation (seeded data), before -> after:
  byw R@20 0.270 -> 0.270, N@20 0.288 -> 0.289
  everything else unchanged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(recommendations): describe the holdout cases by the rule each guards

The case notes described how the ranking misbehaved before the fixes on
this branch. They now say what each set of titles checks, so they stay true
as the ranking changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): keep Watch Tonight cards reading past their pool for genres

The taste candidate query now returns the nearest titles sharing a selected
genre in distance order, without its old five-fold over-fetch, so the cards'
genre-first ranking only saw the pool's nearest titles. A title matching
every selected genre a little further out could no longer lead. With genres
selected the cards read five times the pool, up to 2000, rank by genre
matches as before and keep the pool's worth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): keep MMR and the remake penalty right for odd scores

MMR scaled relevance by the highest score, which reverses a pool whose
scores are all negative, and treated a zero vector as an embedding similar
to nothing, so it escaped the redundancy penalty a missing one takes. It now
scales by the largest magnitude and counts a zero vector as missing, as
co-watch blending also does. The remake penalty halved a score, which
raises a negative one; it now always lowers it. The holdout evaluation's
numbers are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): leave Because You Watched unvalidated

Running "More like this" validation in Because You Watched dropped every
candidate sharing no genre with the source. On a small library few of the
nearest titles do, so rows came back with a handful of titles or not at
all, and the row left Home on a test library of a few dozen titles. The
holdout evaluation gained almost nothing from it (Because You Watched NDCG@20
0.288 -> 0.289), so the row goes back to unvalidated candidates; co-watched
titles of another genre are kept, and the relevance test checks that again.
It still reads the source and candidate details in one query each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): sort taste candidates exactly after the relaxed scan

The candidate query's outer ORDER BY distance could reuse the relaxed
iterative scan's order through the inlined CTE on PostgreSQL 17 and later,
leaving its small inversions in place; the genre-first sort this branch
removed had hidden that. The CTE is now materialized and the sort is on
distance + 0, as pgvector documents for relaxed ordering.

The MMR test's quadratic oracle now follows the same rules as applyMMR (a
zero vector counts as missing, relevance is scaled by the largest
magnitude), and its random pools include zero vectors and all-negative
scores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(recommendations): read candidate details with the candidate scans (#5176)

The row builder read each candidate pool's embeddings, media types, added
dates and quality ratings in four further queries after its HNSW scan, for
every main-row anchor, cluster row, type supplement and Because You Watched
pool. The taste candidate scan now returns those columns
(FindTasteProfileCandidatesWithDetails), the Similar scan and the co-watch
details read add type, added date and quality rating, and the row builder
ranks from them. The per-ID lookups GetItemAddedDates, GetItemMediaTypes and
GetItemQualityRatings lose their last callers and go; Watch Tonight keeps
the genres-only FindTasteProfileCandidates, so its pools of up to 500
candidates do not carry embeddings.

Measured on the holdout evaluation's four measured personas, five traced
refreshes each:

- statements per refresh: 146 before, 114 after (-32, -22%); the focused
  persona alone: 145 before, 114 after
- removed reads, before: 32 statements, about 59 ms of database time per
  refresh (about 8% of a 760 ms refresh)
- wall time per refresh, four interleaved A/B runs on a loaded host:
  before 710-856 ms (median ~826), after 729-843 ms (median ~780); database
  time median ~448 ms before, ~413 ms after. The time gain is within the
  host's noise; the statement cut is exact.

The evaluation's metrics table is byte-identical before and after, and the
cached rows hold the same titles in the same order with the same reasons.
Scores of the persona with Not interested marks differ below 1e-7, as they
do between two runs of the old code: the aversion decays by wall-clock time.

TestProfileRefreshStatementBudgetPostgres pins the focused persona's refresh
at 114 statements (145 on the parent commit) in scripts/ci/db-pins.txt.
TestGetItemQualityRatingsPostgres becomes TestCandidateQualityRatingsPostgres
and reads the ratings from the candidate details.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recommendations): cut the Watch Tonight card pool after shown titles leave it

The cards cut their genre-ranked pool to its size before removing the
titles the client already showed. The cold-start rows are not filtered for
those titles, so when the top Popular titles had all been shown, the cut
kept only them and the page came back empty. The pool is now cut after
they leave it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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 priority: P2 Limited scope, workaround exists, or polish size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. stacked Base is another open PR; merge in stack order named in the body

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant