Skip to content

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

Merged
Quick104 merged 2 commits into
fix/recs-rankingfrom
perf/recs-candidate-hydration
Nov 23, 2026
Merged

Quick104 merged 2 commits into
fix/recs-rankingfrom
perf/recs-candidate-hydration

Conversation

@Quick104

@Quick104 Quick104 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5175 (and #5174 below it); review those first.

Problem

Related issue: N/A
Validation tasks: none

A profile refresh reads each candidate pool, then reads the same candidates' embeddings, added dates, quality ratings and media types in separate queries. On the holdout evaluation's personas that is 32 of a refresh's 146 statements.

This reads those columns with the candidate scans and drops the separate lookups, with no change to the rows.

Approach

  • FindTasteProfileCandidatesWithDetails returns each candidate's embedding, type, added date and quality rating from the candidate query; the main row, cluster rows and type supplements rank from those details.
  • FindSimilarCandidates and GetCandidateDetails return the same details, so Because You Watched and Similar use them too.
  • Watch Tonight cards keep FindTasteProfileCandidates, which returns genres only, so pools of up to 2000 titles do not carry embeddings.
  • GetItemAddedDates, GetItemMediaTypes and GetItemQualityRatings lose their last callers and are removed.
  • Two failure paths go away with their reads: a cluster row or type supplement whose embedding read failed.

Statements per refresh drop from 146 to 114. Database time per refresh fell by about 8% and wall time by about 5% in local runs, on a busy host, so treat the timing as indicative.

Validation

  • Recommendations package with the race detector, and the API handler package, against a migrated database: pass.
  • Holdout evaluation: identical tables and cached rows before and after.
  • New pin TestProfileRefreshStatementBudgetPostgres in scripts/ci/db-pins.txt holds a refresh at 114 statements; it fails on the base branch.
  • Go pre-PR gate on this stack's tip: build, vet, lint and the contract and hygiene checks: pass. Full Go suite: one failure in a playback handler test (TestStartPlaybackV2DoesNotWaitForSessionSync), which this stack does not touch and which passed five of five reruns. The suite ran before the last commit below this one, which only removes validation from Because You Watched; the recommendations package passed with the race detector after it. verify-settings-bindings-all not run to completion here: the web toolchain is not installed in these worktrees, and this change touches no settings. go mod tidy -diff checked through the Go module proxy: no diff.

Evidence

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

Risks

None identified. Rows are unchanged; the candidate queries return wider rows.

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
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated, directed by a maintainer; maintainer review pending
  • Adversarial review: n/a

Note

Return candidate details from candidate scans in recommendations engine

  • Merges the separate store lookups for embeddings, media types, added dates, and quality ratings into one CandidateDetails result produced by the candidate queries in repo.go. The shared candidateDetailColumns selection, candidateDetailDest scan helper, and new Repo.FindTasteProfileCandidatesWithDetails power this.
  • Ranking paths (rowBuilder.mainRow, clusterRows, anchoredRow, addTypeSupplements, becauseYouWatched) now read quality, recency, embedding, and media-type data from the assembled details instead of issuing extra store queries. The quality-prior rating uses qualityRatingSQL, which returns a rating only for notable titles.
  • Removes the dedicated lookups Repo.GetItemAddedDates, Repo.GetItemQualityRatings, and Repo.GetItemMediaTypes, and shrinks the rowStore interface to a single candidate-details query.
  • Adds a statementLog tracer and TestProfileRefreshStatementBudgetPostgres, which pins a focused-persona profile refresh at exactly evalFocusedRefreshStatements (114) statements. Registers the test in db-pins.txt.
  • Risk: behavioral change — the rowStore interface in personal.go loses its per-field methods, so out-of-tree stores must implement the new candidate-details query; the quality-rating contract test is renamed in db-contracts.txt, and the 114-statement budget will fail CI if future changes add candidate-detail reads.

Macroscope summarized f57deab.

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>
@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-23T05:40:28.332518Z f57deab New commits
🔒 Security Review ✅ Completed 2026-11-23T05:42:41.983805Z f57deab 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.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Candidate queries now return details that include embeddings, media types, genres, added dates, and nullable quality ratings. Recommendation ranking uses these details instead of separate metadata and embedding lookups. PostgreSQL tests check the focused profile refresh statement count.

Changes: Candidate detail retrieval and ranking

Layer / File(s) Summary
Candidate detail contract and queries
internal/recommendations/repo.go
CandidateDetails and candidate queries now include added dates and nullable quality ratings alongside existing candidate fields. The separate added-date, quality-rating, and media-type getters are removed.
Use candidate details in recommendation ranking
internal/recommendations/anchors.go, internal/recommendations/personal.go, internal/recommendations/quality.go, internal/recommendations/similar.go
Anchored, cluster, aggregated, and media-type supplement rows use returned details for embeddings and ranking adjustments. Anchored rows carry details for retained candidates.
PostgreSQL and ranking validation
internal/recommendations/*_test.go, scripts/ci/db-contracts.txt, scripts/ci/db-pins.txt
Tests use candidate details for metadata and quality assertions. PostgreSQL coverage checks that a focused profile refresh sends exactly 114 statements. The database contract list and pins are updated.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Suggested reviewers: rhainland

Merge Risk: Minimal · up to f57de

This change reduces database queries during recommendation profile refresh by returning candidate details with the candidate scan. It reports unchanged ranking output. No concrete defect was identified, so the merge risk is minimal.

Security architecture risk: Minimal · up to f57de

Recommendations now fetch ranking details with the candidate list while keeping the same library and maturity restrictions. Some read errors can prevent a row from refreshing instead of merely changing its ranking, but failed refreshes still preserve the affected cached rows. The reviewed change does not establish a new security or rollback risk.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The wider read affects the inspected callers that rank existing catalog candidates. It does not widen the eligible library scope or add the raw details to the inspected recommendation outputs.

Trust Boundaries and Controls

  • observed — The ID-only details lookup does not enforce viewer scope itself. In the inspected Similar and Because You Watched flows, scope is applied to co-watch neighbors before their missing details are fetched. This ordering predates the PR.

Resilience and Maintainability Implications

  • observed — The unchanged cache writer preserves the main and dependent cluster rows when the main row fails. It also leaves an individually failed cluster's cached row in place, while a successful empty result can replace the prior row.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "perf(recommendations): read candidate details with the candidate scans" matches the main change. The changeset merges separate per-ID lookups for embeddings, media types, added dates, and q…
Description check Passed The description states the problem (separate per-pool lookups for embeddings, added dates, quality ratings, and media types), the approach (candidate queries return details; ranking uses them; three g…
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.
Full details: Title check

Explanation

The title "perf(recommendations): read candidate details with the candidate scans" matches the main change. The changeset merges separate per-ID lookups for embeddings, media types, added dates, and quality ratings into the candidate scan queries via CandidateDetails and FindTasteProfileCandidatesWithDetails, and removes GetItemAddedDates, GetItemQualityRatings, and GetItemMediaTypes. The title is specific and concise. It follows a conventional commit style.

Full details: Description check

Explanation

The description states the problem (separate per-pool lookups for embeddings, added dates, quality ratings, and media types), the approach (candidate queries return details; ranking uses them; three getters removed), validation, and risks. These match the changeset, including the new TestProfileRefreshStatementBudgetPostgres pin and db-pins.txt entry. It is related to the changeset in detail.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent 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: 4f3b719f-10c5-40be-8d83-6c981cce770b
Commits

Reviewing files that changed from the base of the PR and between 0ded3a0 and f57deab.

Files selected for processing: 14

  • internal/recommendations/anchors.go
  • internal/recommendations/aversion_test.go
  • internal/recommendations/defaultrows_postgres_test.go
  • internal/recommendations/holdout_eval_postgres_test.go
  • internal/recommendations/personal.go
  • internal/recommendations/quality.go
  • internal/recommendations/ranking_postgres_test.go
  • internal/recommendations/relevance_postgres_test.go
  • internal/recommendations/relevance_test.go
  • internal/recommendations/repo.go
  • internal/recommendations/repo_test.go
  • internal/recommendations/similar.go
  • scripts/ci/db-contracts.txt
  • scripts/ci/db-pins.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.

@silo-triage silo-triage Bot added size/XL 500–999 added + deleted lines (all files); change volume, not priority. 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
…-candidate-hydration

# Conflicts:
#	internal/recommendations/repo.go
@Quick104
Quick104 merged commit 6541f5a into fix/recs-ranking Nov 23, 2026
17 checks passed
@Quick104
Quick104 deleted the perf/recs-candidate-hydration branch November 23, 2026 15:04
Quick104 added a commit that referenced this pull request Nov 23, 2026
…wding 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>
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

go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/XL 500–999 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