Repository navigation
feat(recommendations): make recommendations more accurate and relevant - #1967
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configuration
You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1d72191d71
ℹ️ 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".
| // "More like this" list keeps to the item's type. | ||
| // | ||
| //nolint:goconst // The list is data: media types as media_items.type stores them. | ||
| var recommendableMediaTypes = []string{"movie", "series"} |
There was a problem hiding this comment.
Restore beta books to recommendation surfaces
Keep audiobook and ebook in the supported recommendation types. This list now gates every personal/global row, Because You Watched anchor, read-time cache filter, and the taste-seed picker, so existing beta book users lose recommendation behavior that the previous queries explicitly supported. The repository requires these beta features to remain available in their current state rather than being narrowed to the 1.0 movie/series scope.
AGENTS.md reference: AGENTS.md:L30-L36
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Deliberate, by maintainer decision: recommendations offer movies and series only for 1.0, while books stay a beta feature everywhere else. All recommendation rows and the picker read one list, recommendableMediaTypes, so adding books back is a one-line change. The Risks section lists it as a client-visible change. Leaving this thread open for the maintainer, since it differs from the AGENTS.md rule not to gate beta books for 1.0.
|
32 cases examined; most severe classification: major change. All six recommendation task tables currently say
Suggested corrected line: Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed. Posted via Macroscope — v1 validation impact |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f5502f4096
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dea87be759
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6dfc2bc6ff
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ee18c31457
ℹ️ 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".
Quick104
left a comment
There was a problem hiding this comment.
Four additional confirmed findings, rechecked on ee18c31457e991e46e147b01ff0fce0e433723f9 against base c4af6aad20c101310fa3342571467c21e560a560:
-
P1 — Unbounded allocation from
itemLimit— handlers_recommendations.go:239. The handler accepts any positiveitemLimitand uses it as the response slice capacity, although the Reader returns at most 50 items. An authenticated request withitemLimit=1000000reserves 1,096,000,000 bytes (about 1.02 GiB) per eligible category, based on the compiled DTO layout. Bound the allocation by the available items or clamp the parameter. -
P2 — Dislikes are filtered after the default-row limit — reader.go:640. The query excludes watched and favorited IDs, applies its limit, and only then does the Reader remove ratings of 1 or 2. If the leading 60 candidates are disliked without watch/favorite records, the default shelf disappears despite eligible titles deeper in the catalog; smaller section limits underfill sooner. Include disliked IDs before limiting or refill after filtering.
-
P2 — Daily rotation exceeds the genre cap (disclosed) — rotation.go:66. Rotation draws from the deeper tail without preserving the genre cap. An algorithm reproduction with a capped first 20 of 10 Action and 10 Comedy titles, followed by 10 Action titles, serves 15 Action and 5 Comedy while Comedy alternatives remain. The Risks section already acknowledges this behavior; the served window still violates the stated cap.
-
P2 — Anchor query failures become successful partial refreshes — anchors.go:187. If one anchor query fails transiently while the refresh context remains live and another anchor succeeds, the failure is logged and skipped. The nonempty partial row bypasses fallback, overwrites the previous main row, and can clear the stale marker when later steps succeed. Propagate anchor failures into refresh failure accounting so an incomplete rebuild is retried or preserves the previous row.
The Jellyfin Similar access/limit finding is already tracked in this review thread.
These mechanisms were confirmed through source tracing; the allocation size and rotation example have the measurements described above. Focused recommendation, section, API v2 and API handler tests passed on earlier reviewed heads. A Jellyfin playback-ordering test also failed on the earlier base. Database tests were skipped, and browser/device verification was unavailable.
Validation tasks: unavailable — passed-case enumeration was blocked by missing read:project. Directly read recommendation tasks record all cases as Not run.
AI disclosure: gpt-6.1-sol in T3 Code using the Codex provider.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8de87b3f41
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 87ab40cb62
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7c238e247d
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b8f97b18a6
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dcd66f2547
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1d6ccc1c5c
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 190b0af3cd
ℹ️ 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".
| if slices.ContainsFunc(itemGenres, func(g string) bool { return counts[g] >= maxPerGenre }) { | ||
| skipped = append(skipped, item) | ||
| continue |
There was a problem hiding this comment.
Enforce the cap across multi-genre candidates
Reconsider earlier selections when every remaining candidate conflicts with a saturated genre. For a four-item window containing two leading A+B titles followed by two A+C and two B+D titles, this loop accepts the first pair, skips everything else, and then appends the skipped titles unchanged; the served window becomes A+B, A+B, A+C, A+C, making genre A occupy 100% even though A+C, A+C, B+D, B+D satisfies the 50% cap. The new greedy pass therefore does not enforce the documented cap for common multi-genre metadata.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The counterexample is right: the pass is greedy in rank order and never revisits a title it let in, so two leading A+B titles fill genre A's share and a different set would meet the cap. I am keeping the greedy pass on purpose. Reconsidering earlier picks turns this into a combinatorial search over the window, and it would demote the highest-ranked titles to satisfy the cap, which costs relevance in exactly the rows where the top results share genres. 18affed corrects the comment and the architecture doc, which overstated it as a guarantee: the cap is now described as a greedy limit that keeps the higher-ranked titles. Leaving this open in case a maintainer wants a stricter pass.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4e6ecc12f7
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4a3b62d8a1
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4da7f3e4c0
ℹ️ 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".
|
Silo's pull request guidance changed today (#2016). A PR that changes what a user sees now needs before-and-after evidence in its Evidence section, and a PR with no visible change says Missing here: Before-and-after screenshots of the web For You page for the same profiles (an established one and a new one) showing the new rows, titles and labels, plus the TasteSeed flow. The rules are in Show visible changes, and the PR template shows the Evidence section layout. I've converted this PR to draft for now. Mark it ready for review once the Evidence section is filled in. Generated by Claude Code |
There was a problem hiding this comment.
💡 Codex Review
silo-server/internal/recommendations/worker.go
Lines 890 to 891 in b55bc8f
If a partial earlier build or an upgrade leaves only an unexpired genre sampler or the now-unused cached top_rated row, HasGlobalRecommendationCache still returns true and this startup path skips rebuilding. Popular and Recently Added can then remain absent from cold-start home and Watch Tonight reads until the next scheduled recommendations job, even though the unrelated surviving row cannot serve those paths; check for the required row types or rebuild missing rows instead of treating any global entry as sufficient.
ℹ️ 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".
| func genreRowLabel(genre string) string { | ||
| return "Top " + genre |
There was a problem hiding this comment.
Preserve the frozen v1 genre labels
When a bridge client calls /api/v1/recommendations/discover, this shared helper renames warm Discover rows from Popular in <genre> to Top <genre>, so existing v1 clients receive changed display values even though this is recommendation feature work rather than a critical bridge fix. Keep the previous label for v1 or apply the new labeling only on v2.
AGENTS.md reference: AGENTS.md:L226-L238
Useful? React with 👍 / 👎.
50fd195 to
bb2de76
Compare
b55bc8f to
494fd2c
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 207f925ce3
ℹ️ 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".
| genre, loaded, fresh := c.genre, c.loaded, time.Now().Before(c.expires) | ||
| c.mu.Unlock() | ||
| if fresh { |
There was a problem hiding this comment.
Recheck the top-genre cache inside singleflight
When request B observes a missing or expired entry and is descheduled until request A finishes loading, A's singleflight call may already have been removed before B reaches DoChan; B then starts another full-catalog GetTopGenres scan because this callback never rechecks the cache. Under concurrent cold-start or expiry traffic, requests that straddle completion can therefore repeat the expensive scan this cache is intended to coalesce; check for a fresh cached value inside the callback before calling load.
AGENTS.md reference: AGENTS.md:L13-L18
Useful? React with 👍 / 👎.
…rately - The taste vector averages only titles with positive weight; dislikes and abandoned titles still count in signal_counts but no longer pull the vector away from them. - A 3-star rating is half credit: it adds no explicit weight and halves the title's watch and intent weight, so a 3-star completion counts less than an unrated one. - A series quiet for more than 30 days is scaled by how much of it the profile watched, so a sampled or dropped pilot weighs far less than a show watched through. - Cold-start levels count positive titles behind the vector (stored as signal_counts.positive_titles and left out of the taste summary), with thresholds 3 and 10. A profile with three taste-seed picks now opens on its own row. Watchlist-only titles do not raise the level, and favorites and watchlist entries count once per title. - A read requests a refresh for a profile with positive signals but no personal rows, so picks embedded after the last refresh are picked up. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…y what is served - The main For You row of a profile with 10 or more titles is composed from its taste clusters: each interest gets slots in proportion to its weight (at least 3), its own nearest neighbors ranked by MMR, interleaved by weighted round-robin. One averaged vector used to hand the row to the heaviest interest or to titles between interests. - Diversification now reaches the 20 titles clients show: the genre pass is a stable reorder over MMR order that admits at most 10 titles of one genre into the served 20, deletes nothing, and keeps cached rows at 60. The recency boost no longer re-sorts. - Per-type supplements sit after the served 20 so library sections of the minority type still fill, and their queries skip types the viewer cannot see. - Cluster rows leave out the main row's served 20; a row thinned to empty is cached as built, not missing. - A mild quality prior nudges candidates by their public rating (IMDb, else TMDB below 9.5), at most half a standard deviation of the pool's scores and standardized per media type, so a well-rated title wins near-ties. - relevance_test.go adds a persona harness (movie buff, series binger, kid, new profile, mixed taste, lapsed) asserting variety, interest shares and placement thresholds. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… rows
- Submitting taste-seed picks refreshes the profile on the spot, waiting
up to 5 seconds (at most 4 at once per server; the refresh finishes in
the background on timeout). First-run Done opens the For You page, and
the web refetches recommendations after 3 and 15 seconds as a fallback.
- Jellyfin /Movies/Recommendations sends only rows Jellyfin can label
truthfully: up to two Because You Watched rows (SimilarToRecentlyPlayed,
named after the anchor title, dropped when the viewer cannot see it) and
cluster rows (SimilarToLikedItem, named after the bare cluster label),
each with its own category id. It no longer shows "Because you watched
For You" or "Popular on This Server".
- Jellyfin /Items/{id}/Similar uses the recommender when recommendations
are enabled, filtered to what the session can see.
- Add docs/architecture/recommendations-evaluation.md (metric definitions
for #1139, no thresholds), scripts/recs-probe/capture.sh (read-only v2
capture with per-metric summaries), and Postgres rubric tests for
leakage, cross-profile overlap and new-profile rows.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… by quality
- Discover and its section pages serve two live, access-scoped default rows
that need no viewing history: "Highly Rated in Your Library" (IMDb-first
rating of at least 7.0, movies and series in proportion to what the
viewer can see) and "Recently Added" (by the later of the title's or its
newest episode's added date, no window). They show even when
recommendations are disabled, and Top Rated is served by the live query.
- The cached Recently Added row uses the same query, so a new profile on a
quiet server always gets a row on home, For You, Watch Tonight and
Jellyfin.
- Popular needs viewing by at least two accounts over 90 days and is
ordered by accounts, so one household's viewing is not shown as popular.
- Genre rows are rating-led ("Top <genre>"), the genre menu grows from 8 to
16, and Discover dedupes only against items a row actually shows.
- The taste-seed picker interleaves genres on its first pages.
- Non-personal rows and the picker offer movies and series only for 1.0,
through one recommendableMediaTypes list.
- The web For You page shows the default rows for a profile with no
history and no longer claims they come from its viewing history.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The pass keeps relevance order and never revisits a title it let in, so multi-genre titles can leave a genre above half of the window when only a different set of titles would meet the cap. The comment and the architecture doc claimed a guarantee the pass does not give. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A submission that arrives while a refresh reads makes that refresh run once more, so the picks can land after two refresh timeouts, past the page's last refetch at 125 seconds. One more refetch now runs at 245 seconds. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Favorites and watchlist entries resolve to their canonical title, so favoriting several episodes of a series added the series' favorite weight once per episode while the count recorded one title, letting the series dominate the taste vector. Each title now weighs once, at its newest entry. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…, recheck title counts Watch Tonight decided it was warm before filtering its cached personal candidates, so a cache holding only titles that can no longer be served, such as books cached before they left personal rows, answered an empty list instead of Popular and Recently Added. It now filters first and falls back when nothing survives. The title-count cache was checked only before singleflight, so a request that missed just as another finished counting started a second full count. The shared call now checks the cache again first. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…title counts The per-type title counts only set how Highly Rated mixes movies and series, yet a failed or slow count failed the whole Discover read, and every read after an expiry waited on a full count. Expired counts now serve the read while a background count refreshes them, a read with no counts yet stops waiting when its request ends, and a failed count falls back to the scope's last counts, or equal weights, retrying after a minute. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ot per render A "Top Picks Today" section with no genre and no matching cluster asked for the top genre on every render, which scans the whole catalog and the whole watch history for a result that is the same for every viewer. Each server now reuses it for 10 minutes, serving an expired genre while one background read refreshes it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hin row A main-row anchor whose candidate query failed was logged and dropped, and embedding read errors were ignored, so one transient error cached for a day a main row missing a whole interest (the others took its slots) or ranked without MMR. Such failures now fail the main row, and a cluster row whose embeddings cannot be read counts as failed like a failed candidate query; the cached rows stay and the refresh is retried. A failed main row also keeps the cluster rows cached, since rebuilt against no main row they would repeat its cached titles. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rows were built leaving out only watched and favorited titles, so a title rated 4 or 5 stars without enough progress, which weighs most in the taste vector, led its own row, and a show dropped early stayed recommendable. Similar Users already left out every rated title. Rows the engine builds now leave out every title the profile rated and every title it abandoned (progress under 15% untouched for 14 days, the taste profile's own dislike signal), and a read drops every rated title from cached rows, not only those rated 2 stars or lower. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…very limit Reads rotated personal rows for a window of the caller's limit, while a row's see-all page and Discover rotate for 20 items, so a page read at limit 10 served rank order and one at 15 or 30 drew a different tail: the see-all page opened in an order the row was never served in. The window is now ServedRowSize at every limit, so a shorter page is a prefix of the rotation and a longer one continues it, and the cluster-repeat check sees the same window everywhere. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rated title Reads now drop every title the profile rated, so the live default rows, which left only titles rated 2 stars or lower out of their query, lost liked titles to the filter afterwards and came back short. They now leave every rated title out in the query, and Watch Tonight's own filter drops every rated title as the rows do. The v2 because-watched description says so. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ts exclusions once Watch Tonight's cold-start fallback read the cached Recently Added row, which nothing rebuilds while recommendations are disabled, so about a day after an admin disabled them the fallback came back empty while Discover, reading the row live, still filled. The fallback now reads Recently Added live. Each of its two filtering passes also loaded the profile's exclusion set, and the handler's filter read the watched set a third time; the passes now share one read, and the handler shares the watched set with them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ommendations are off Discover-mode Watch Tonight cards ranked a profile's stored taste profile against the library even with recommendations disabled, though every other read serves only the global rows then. They now skip the taste profile while the engine is unavailable. Their cold-start candidates also kept only titles the viewer could see, so a book cached in a global row before books left the rows could still become a card; they now keep only the types the rows offer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… cannot be checked A failed access check on the co-watch neighbors failed the whole Similar list, though co-watch only adds a 30% blend to the embedding candidates, which were already filtered for the viewer. The list now leaves the neighbors out and logs the failure, as it did before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s to the anchor's type The row's embedding candidates keep to the anchor's media type, but its co-watch neighbors were kept only to movies and series, so a movie's row could take series its viewers also watched, contrary to the row's own rule. Its co-watch neighbors now keep to the anchor's type, as More Like This already does; both share the rule. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… carry A cluster's label always named its most common genre, however few of its titles carried it, so a cluster of twelve titles in twelve genres was titled after a genre on one of them. The most common genre is now named only when at least 40% of the cluster carries it, the floor distinctive genres already meet; a cluster no genre describes is titled "Picked from your history". Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ifies When no seeding left every cluster at 3 titles or more, the fallback ran k-means again from the same seed as the first restart, doubling the work for the same partition on large profiles, which get one restart and refresh on every signal change. It now merges the first seeding's small clusters. The doc also gave the single-restart threshold as 800 titles; the budget gives one restart from 401. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ns in a row A refresh rerun for each change made while it ran, with no limit, so a stream of changes to one profile kept its refresh looping: on the queue's single goroutine that delayed every other profile, and in the stale sweep it held the cluster-wide sweep lock for as long as the stream lasted. After three runs in a row a profile still changing is now left to the stale sweep; every signal change marked it stale before asking. Co-Authored-By: Claude Opus 5.5 <[email protected]>
After a taste-seed submission each of five delayed refetches also bumped Home's refresh signal, which reloads every Home section, and the timers kept firing after a profile switch and stacked on a second submission. The delayed refetches now reload only the recommendation reads, Home is bumped on success and with the last refetch, a new submission replaces the schedule, and a profile or account switch cancels what is left. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…filterItemIDs ApplySectionAccessFilter already leaves out filter.ExcludedMediaTypes, so the hand-written predicate after it added the same condition a second time with its own parameter. Co-Authored-By: Claude Opus 5.5 <[email protected]>
207f925 to
bbe0059
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bbe00593d9
ℹ️ 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".
| if _, rated := ratings[item.MediaItemID]; rated { | ||
| continue |
There was a problem hiding this comment.
Preserve the v1 low-rating filter
Keep the previous 1–2-star-only behavior for the v1 handlers. Because filterRecommendations is shared by /api/v1/recommendations/because-watched, Watch Tonight, and Watch Tonight Cards, a profile that rated an otherwise eligible title 3–5 stars now loses it from those frozen bridge responses, whereas the parent implementation removed only low-rated titles. Apply the all-rated exclusion only to v2/new read paths or retain the old filter for v1.
AGENTS.md reference: AGENTS.md:L226-L227
Useful? React with 👍 / 👎.
| return ForYouRow{}, err | ||
| } | ||
| if rr.excludedIDs == nil { | ||
| rated, err := rr.reader.repo.ListRatedItemIDs(ctx, rr.userID, rr.profileID) |
There was a problem hiding this comment.
Canonicalize episode ratings before querying default rows
When a profile rates an episode, ListRatedItemIDs returns the leaf episode ID while the live default rows contain the parent series ID. Passing those raw IDs into the SQL exclusion means the series survives the LIMIT, and the later rating filter also checks only the series candidate ID, so Discover and Watch Tonight can recommend a series that the profile rated through an episode even though built personal rows canonicalize the same rating in BuildExclusionSet. Resolve rated IDs to their canonical titles before constructing this exclusion list.
Useful? React with 👍 / 👎.
…the default rows The live default rows left out the profile's rated titles by the IDs it rated, but they hold series, so a profile that rated an episode was still offered its series in Highly Rated and Recently Added on Discover and in Watch Tonight's fallback. The rated IDs now resolve to their series first, as they already do for the rows the worker builds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 83b55b378c
ℹ️ 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".
| def more(p): "\(p.items | length)\(if p.page.has_more then "+" else "" end)"; | ||
| ([$h[0].items[] | select(.watch.completed == true) | .content_id] | unique) as $finished | ||
| | ([$f[0].items[].content_id] | unique) as $favorites | ||
| | ([$r[0].items[] | select(.rating <= 2) | .item_id] | unique) as $low |
There was a problem hiding this comment.
Measure every rated title in the leakage probe
Count all entries from the ratings page, not only ratings of 1–2. The new read path removes any title present in rated, and the v2 contract now says recommendations exclude what the profile has rated, so a regression that serves a 3–5-star title is currently reported as zero rated_low leakage and can give QA a false pass. Either replace $low with an all-rated set or report a separate all-rated leakage metric, and align the evaluation document with that invariant.
AGENTS.md reference: AGENTS.md:L109-L116
Useful? React with 👍 / 👎.
| // such as books cached before they left them. | ||
| var err error | ||
| candidates, err = h.keepAccessible(ctx, h.buildColdStartDiscoverCandidates(ctx), filter) | ||
| candidates, err = keepRecommendable(ctx, repo, h.buildColdStartDiscoverCandidates(ctx, repo), filter) |
There was a problem hiding this comment.
Use a live fallback when recommendation caches are absent
When recommendations are disabled, no worker is created to build or renew the global Popular and Recently Added caches; after existing entries expire, or on a fresh installation, this fallback therefore returns no discover-mode Watch Tonight cards even when the viewer has eligible movies or series. The regular Watch Tonight path avoids this by querying a live Recently Added default row. Give this cards path the same live fallback instead of relying exclusively on caches that cannot be populated in this configuration.
Useful? React with 👍 / 👎.
Rows now leave out every title a profile rated, but the probe's leakage check counted only titles rated 1 or 2, so a regression serving a 3-to-5-star title would read as no leakage. It now counts every rated title, and the evaluation doc describes the metric that way. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… Added row Discover-mode cards with no taste profile, or with recommendations disabled, fell back only to the cached Popular and Recently Added rows, which nothing builds or renews while recommendations are disabled, so the cards came back empty on a fresh server and once the caches expired. The fallback now reads Recently Added live, as Watch Tonight's own fallback does, leaving out the titles the client already showed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ca5344b34d
ℹ️ 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".
| recommendations.RecTypeRecentlyAdded, | ||
| "", | ||
| ) | ||
| recentlyAdded, err := repo.ListDefaultRowItems(ctx, filter, recommendations.RecTypeRecentlyAdded, mapKeys(excludeIDs), limit) |
There was a problem hiding this comment.
Pass profile exclusions into the cards fallback query
When discover-mode cards fall back to Recently Added, this query excludes only the client-supplied IDs of cards already swiped. Watched and rated titles are removed later by filterRecommendations, after the SQL LIMIT, while favorites are not removed at all. A cold profile whose newest candidates were already watched, rated, or favorited can therefore receive a short page, an empty page despite eligible older titles, or a favorite as a recommendation. Build the canonical profile exclusion set before this query and pass it to ListDefaultRowItems so the limited result is already eligible.
Useful? React with 👍 / 👎.
| ([$h[0].items[] | select(.watch.completed == true) | .content_id] | unique) as $finished | ||
| | ([$f[0].items[].content_id] | unique) as $favorites | ||
| | ([$r[0].items[].item_id] | unique) as $rated | ||
| | " leakage: finished=\([.[] | select(.card.content_id | IN($finished[]))] | length)" | ||
| + " favorited=\([.[] | select(.card.content_id | IN($favorites[]))] | length)" | ||
| + " rated=\([.[] | select(.card.content_id | IN($rated[]))] | length)" |
There was a problem hiding this comment.
Canonicalize episode signals before leakage comparisons
When a profile completed, favorited, or rated an episode, recommendation rows hold the parent series ID, but these leakage checks compare that series ID directly with the leaf IDs returned by history, favorites, and ratings. The user_state fallback does not repair this generally—a series is marked played only when all episodes are complete, and episode favorites/ratings do not mark the series—so the probe can report zero leakage even while recommending a series excluded by an episode signal. Resolve captured leaf IDs to their canonical series IDs before computing these metrics.
Useful? React with 👍 / 👎.
…ted and observable (#1966) * fix(search): keep the embedding API key out of search diagnostics Gemini embedding requests put the API key in the URL query string. A transport error quotes the request URL, and semantic search copied the provider error into search_diagnostics.fallback_reason, which every signed-in user receives. Send the key in the x-goog-api-key header, and return a fixed fallback reason while logging the detail server-side. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * refactor(recommendations): remove dead code and no-op settings - Delete Engine.EmbedItem, ExcludeWatchedItems, jaccardSimilarity, CleanOldCacheTypes and GetItemGenres, which had no callers or duplicated GetItemAllGenres. - Replace the five per-type MMR lambda constants with one mmrLambda(): the diversity_lambda setting already overrode every one of them. - Stop seeding recommendations.embedding_provider; the legacy read stays. - Use the co-watch Default* constants instead of repeated literals. - Web: delete the Watch Tonight dialog and swipe UI, six recommendation hooks and their adapters, none of which were mounted or imported. The server endpoints and v2 operations are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): run each job on one server and record its outcome Every API node ran every recommendation job, and each job body was duplicated across cron and manual-trigger wrappers that logged success even when work failed. - One runJob path takes the in-process guard and a per-job Postgres advisory lock for cron runs and manual triggers alike, so each job runs on one server at a time. Triggers report whether the job is busy here or on another server. The stale-profile sweep takes its own lock. - Job bodies return counts and errors. Per-profile build failures, global row failures and taste refresh failures are logged and counted, and a run that hit them logs "completed with errors". Each finished run is recorded in task_executions under recommendations.* keys. - The nightly cache job processes the least recently cached profiles first and checks its deadline. Cache rows live 26 hours, past the next daily run, and a global row whose rebuild fails keeps its last good version. - Cluster seeding uses item IDs only, so decaying weights no longer reshuffle clusters every night, and a cached cluster row keeps the title of the build that produced it. - The worker builds the global rows at startup when none are cached, so cold-start rows exist before the first nightly run. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): refresh profiles whenever their signals change Recommendation refreshes were requested only from a few API handlers, and a change that landed while a profile was refreshing was cleared with it. - A refresh records the database time it started, stores the taste profile with that time, and clears only stale marks set before it. Marking a profile stale always moves the mark forward, and a failed refresh marks the profile stale again so the sweep retries it. - Worker.NotifySignalsChanged marks the profile stale and queues a refresh. API and jellycompat handlers use it, and so do history imports (once per run, including failed runs that already wrote records), watch-provider syncs (once per run that changed local state) and media-server webhooks (unplayed, favorites, and progress that marks an item played). - Catalog merges and splits mark the profiles with signals on the affected items stale. - With the SQLite user store, the nightly taste job also finds profiles whose history lives only in that store. - The For You page requests a refresh for a profile that has signals but no taste profile yet, so a lost first refresh recovers. Refreshes requested by reads are limited to one per profile per 15 minutes on each server. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): make the embedding backfill fail safely and catch up - Provider responses must carry one non-empty vector per input. A vector that is empty or wider than 3072 dimensions ends the run before the embedding lock is read or written, so an unusable model can no longer pin the installation. A run that stored nothing fails instead of succeeding. - Rejected credentials, a wrong model or URL (401/403/404) and unreachable hosts end the run at once with "embedding provider unavailable"; so do three single-item failures in a row. Inputs the provider refuses at every length count as skipped and never stop the run on their own. - The OpenAI-compatible client waits through ctx, stops on insufficient_quota and on Retry-After beyond the cap, and reports persistent 429s as limits, matching the Gemini client. - Texts a local model rejects are retried at 600 and 300 runes, and the full text is stored as canonical text so the item is not re-embedded nightly. - The text-staleness pass compares people in byte order, matching Go, and pages past rows that only look stale in SQL. - A catch-up pass embeds newly matched items every 15 minutes under the embeddings job's claim, and startup resumes an interrupted backfill. - Catalog seed imports keep only embeddings from the locked (or configured) model and report the rest as embeddings_skipped. An admin merge keeps the source item's embedding when the target has none. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): stop recommending against or back to a profile's taste - A profile with no positive signal no longer gets an "anti-taste" row: the Reader serves level-0 profiles cold-start rows only, and a refresh that finds no positive weight clears the taste vector (now nullable), clusters and cached personal rows in one transaction while keeping the row and its signal counts. - Personal rows leave out the profile's favorites, including taste-seed picks, as well as watched titles, canonicalized episode to series, both when rows are built and when cached rows are read. Watchlist titles stay recommendable. - A series' implicit weight now decays by its most recent signal, as a movie's does; decay inside the season shares cancelled out. - signal_counts count each canonical title once, so one long series no longer makes a profile look fully personalized. - Progress below 15% counts as abandonment only after 14 days. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * feat(recommendations): let admins reset embeddings and see job health - Add POST /api/v2/admin/recommendations/embeddings/reset. It holds the embedding, taste and cache job claims and the stale-sweep lock, deletes the embedding lock, item embeddings, taste profiles, clusters and per-profile cached rows in one transaction, and queues search updates so indexed vectors are dropped. A server pinned to an unusable or abandoned model can now recover without SQL. The admin page gains a confirmed "Reset embeddings" action. - The connection check fails when the provider returns no vector or more than 3072 dimensions, reports the dimension count, and reports a stored lock that conflicts with the settings. - Admin status adds lock_conflict, each job's last run (status, times, masked error, counts) and when the cache was last refreshed, and the admin taste profile count skips cleared profiles. - The Ollama preset uses qwen3-embedding:0.6b (1024 dimensions); the :latest tag is the 8B model, whose 4096-dimension vectors cannot be stored. - Search indexes only vectors from the active embedding model, gives the query embedding 2 seconds, and skips the provider for a minute on a node after a failure. Semantic readiness uses one 85% coverage threshold instead of a per-process latch, so every node answers the same. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): fill library rows and keep reads cheap and honest - Library-scoped recommendation sections read the whole cached pool (up to 60), scope it to the library, then trim to the section size, so a TV or second movie library is no longer left with the few items that happened to be in the global top 20. Hide-watched widening works the same way. - The public Reader limit caps at 50, the v2 maximum; v1 for-you and similar-users endpoints keep 20 in the handler. - Per-section home and library item endpoints return 500 when a section fails to load instead of an empty 200, so clients can show a retry. - Because You Watched skips anchors whose row is empty in the section's libraries and anchors that were deleted or merged away, and does not request a refresh it cannot fill. - Co-watch ignores deleted items and prunes pairs a run did not rewrite. - The watched set pages by keyset, Reader paths read clusters without their embeddings, and a request loads the exclusion set once. Handlers share the SignalReader's watched set. - MMR updates each candidate's similarity against the newest pick only; co-watch keeps a bounded top-N per item and checks cancellation; HNSW ef_search is clamped to pgvector's 1000. - Web home and library pages apply avoid_duplicates across sections in layout order, as the aggregate endpoint does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): build and serve rows under each viewer's real access - The four v1 list endpoints (similar, because-watched, popular, recently-added) drop titles the viewer cannot access, and similar and because-watched answer an inaccessible anchor like an unknown one on v1, v2 and Jellyfin Similar. - Cached rows are built under the scope the API resolves (access groups, account and profile libraries, hidden libraries, maturity limits), failing closed when it cannot be resolved. Profile restriction, hidden library, account and access group changes trigger a rebuild; group-wide changes mark the affected profiles stale in one statement. - Because You Watched and Similar Users apply access in the candidate query or before ranking, so restricted profiles get full rows instead of rows filtered down after selection. - Jellyfin /Movies/Recommendations reads the cached rows with the session's access filter and returns 500 on failure; the live For You pipeline it used is deleted. - Deleting a profile purges its ratings, taste profile, clusters and cached rows on both user-store backends; a migration removes existing orphans for Postgres-backed accounts. - Similar Users needs at least 3 peer accounts and 2 supporting accounts per title, so one other household's ratings are never shown on their own. - The taste-seed picker applies access in SQL and the web keeps paging past pages that hydrate empty. - Watch Tonight filters cold-start candidates for access before trimming, attaches each card's own cast, computes has_more from hydrated cards and returns 500 when hydration fails. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * docs(recommendations): record how embeddings, refresh and access work Add docs/architecture/recommendations.md with the invariants the code now relies on: job locks and recorded runs, the embedding lock and its reset, backfill stop rules, signal refresh semantics, the NULL taste vector, the exclusion set, Similar Users floors, build-time access resolution, and read limits. Note in the admin API doc that the embeddings kind covers the 15-minute catch-up pass. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * docs(recommendations): note idle startup builds and live list endpoints Live verification showed the startup global-row build writes nothing on an idle server, and that the popular and recently-added endpoints read the catalog live. Say both. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(recommendations): run the new database contracts in CI List the recommendation DB tests this branch adds in scripts/ci/db-contracts.txt so the Go DB pins job runs them instead of letting them skip. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): drop global rows that rebuild empty A global row whose rebuild succeeded with no items was neither rewritten nor deleted, so it kept serving its old items until it expired, up to 26 hours later. The same held for a genre row whose genre left the menu. The cache job now deletes both; a row whose rebuild fails still keeps its last good version. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(settings): send the saved embedding token only to its own base URL The embedding connection check laid the draft over the stored settings, so a draft that only changed the base URL was checked with the saved embedding token (or the legacy OpenAI key) sent to that new server. The AI checks already held saved keys back when the endpoint changed. The embedding check now does the same: when the draft's base URL differs from the saved one in scheme, host or port, directly or through the legacy provider setting, it uses only a token the draft carries itself. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * refactor(recommendations): simplify the quality fixes Tidies code this branch changed, with no behavior change: early returns in place of empty switch cases, one exclusion check in the Similar Users loop, a named lazy exclusion-set loader, a shadowed variable renamed, the global row write folded into one switch, a stale-mark wrapper removed, the admin status counts passed directly, and the home and library pages' shared section de-duplication moved into one hook. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): address review findings on the quality fixes - A refresh no longer creates a taste row for a profile deleted while it was queued; it only clears one left behind, and the nightly taste job skips deleted Postgres-backed profiles. - A personal row that rebuilds empty (main, cluster or Because You Watched) is deleted instead of serving its old titles until it expires; a row whose build fails keeps its old version. - An input the embedding provider refuses is skipped, not counted as a provider failure, so refused neighbours no longer stop every run. Each server remembers refused inputs by their text, so the catch-up pass does not resend them every 15 minutes or record a failed run; the nightly run retries them once. A refusal before anything is stored is checked with a probe text, so a bad key still stops the run. - Media-server webhook stops notify a signal change at any position, as the native player does, not only when the title is played. - A read checks the refresh throttle before querying a new profile's signals. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * refactor(recommendations): name the cluster row type Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): address Kody review on the quality fixes - An embedding provider's error body is quoted with credential assignments masked, since it reaches logs, job results and search diagnostics. - An item the provider refuses no longer uses the text-refresh quota, so refused items at the front of the walk cannot starve the rest. - A history import that wrote progress or history for a record before a later step failed counts the write, so a run that then fails still reports the signal change. - Catalog merges mark stale the profiles whose ebook reading progress points at the merged titles. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(recommendations): walk the text-refresh pass past refused rows Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(recommendations): cover a nested secret in a provider error body Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): address Codex review on the quality fixes - Jellyfin /Movies/Recommendations gets no reader while recommendations are disabled, so it answers an empty list instead of rows cached before. - Signal and access-scope notifications detach from the request that made the change, so a canceled request no longer drops the stale mark and refresh of a change already committed. - A failed delete of an empty global row counts as a failed step, so the run is not recorded as clean while the row keeps serving. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): rank similar items among the titles the viewer can see The similar-items list ranked the nearest titles across the whole catalog and the handlers then dropped those the viewer cannot see, so a restricted profile could get a short or empty list while accessible titles sat further down. The viewer's access filter now applies to the candidate search. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): fill live popular and recently added lists for the viewer The v1 popular and recently added lists, and their v2 cards, read the server-wide top rows and only then dropped the titles the viewer cannot see, so a restricted profile could get a short or empty list while visible titles ranked just below. The lists now read deeper, up to 1,000 rows, until the limit is filled with titles the viewer can see and has not watched, or the list runs out. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): retry embeddings shortened only when length may be the cause A long item that failed for any reason, such as a provider still down after its retries or a malformed response, was retried at 600 and 300 runes. A provider that recovered meanwhile then had a shortened vector stored under the full text, which the text-refresh pass never repairs, and a provider still down repeated its retries for nothing. Shortened retries now follow only a refused input or a local model's over-context-length error. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): address Codex review on access and search fallbacks - Similar items keep co-watch neighbors to those the viewer can see before ranking, so hidden ones no longer take the list's places. - The access-group member lookup that follows a committed library change no longer uses the request's context, so a canceled request still marks the members' rows for rebuild. - A search query the embedding provider refuses no longer starts the node-wide semantic-search cooldown; only provider failures do. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(jellycompat): cap the recommendation limits before they size anything /Movies/Recommendations accepted any positive categoryLimit and itemLimit and used them as slice capacities, so one request with a huge value could exhaust the server's memory. categoryLimit is now capped at 20 and itemLimit at a cached row's 60 titles. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): report a storage-width lock conflict without a probe The admin status passes no source dimensions, so a lock that recorded vectors stored at another width than this server's 3072 reported no conflict while every embedding write failed. The stored width is now checked on its own. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): rebuild rows after policy changes and hold resets until a restart A custom scope policy can widen or narrow every account's scope, but policy changes never marked recommendation profiles stale, so rows kept the old scope until the nightly job. The policy system now runs a hook after a change it applied, and the recommendations worker marks every taste profile stale for the stale sweep to rebuild. An embeddings reset while saved embedding settings waited for a restart let this server re-embed with the old model and lock it again. The reset now refuses with 409 until the saved model and base URL are the ones the server runs with. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): refresh a profile on one server at a time Two servers could refresh the same profile at once, and a refresh that read older signals could finish last and overwrite the newer one's taste profile, clusters and rows after the newer one cleared the stale mark. A refresh now takes a cluster-wide advisory lock for the profile before it reads the database time. When another server holds it, the refresh marks the profile stale and stops; the holder clears only marks older than its start, so the stale sweep runs the profile again. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * docs(recommendations): record the refresh lock, policy rebuilds and reset refusal Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): purge a profile deleted while its refresh wrote A refresh checks that its profile exists before writing, but a deletion between that check and the writes, purged before the writes landed, left the deleted profile's taste row, clusters and rows behind, and the vector kept feeding Similar Users. Profiles may live outside Postgres, so the check cannot share the writes' transaction; refreshes and the nightly taste job now check again after their last write and purge what they wrote when the profile is gone. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(policy): announce a policy change on every node that loads it The recommendation rebuild after a policy change ran only on the node that made the change, and only when its synchronous reload succeeded. A failed local reload never rebuilt the rows, and a peer's stale sweep could rebuild a profile under the old policy before that peer reloaded, clearing the mark. The change hook now runs on every node each time it loads a newer policy generation, from any reload path, so the last node to apply the change marks the profiles stale after it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): apply excluded media types when filtering rows The reader's access filter applied content, library and maturity limits but not the filter's excluded media types, so Jellyfin rows trimmed to their read depth could fill with audiobooks and podcasts that the item load then dropped, leaving short or missing categories while movies waited further down the cached row. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): keep a stale mark made before a profile's first build MarkProfileStale only updated an existing taste row, so a change during a profile's first build marked nothing, and the build stored a profile from the signals it read before the change with no mark left for the stale sweep. The mark now creates a vectorless row updated at the epoch, which the build fills and whose mark outlives the build's clear. The new Postgres tests from this round join the database contracts CI runs. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): serialize embeddings resets with catalog imports A catalog import read the embedding lock early in its transaction and inserted embeddings much later, so a reset that committed in between left vectors with no lock describing them. The reset now takes an advisory lock exclusively in its transaction and refuses with 409 while an import holds it shared; an import that starts during a reset waits for it before reading the embedding lock. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(api): rebuild access group members on every library save The library comparison read the group before the update's writer lock, so overlapping updates could restore an earlier set unnoticed and leave members' rows built for the wrong scope. Any update that sets the group's libraries now rebuilds its members. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * chore(api): regenerate the v2 contract for the reset refusal Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(jellycompat): cap recommendation item limits at what a row read returns The handler accepted itemLimit up to a cached row's 60 titles and read twice that, but row reads return at most 50 items, so larger limits were cut silently. Both the item limit and the read depth now stop at the reader's maximum. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): hold the profile lock in the scheduled taste and cache jobs The nightly taste and cache jobs wrote taste profiles and cached rows without the per-profile refresh lock, so a job that read a profile before a signal change could overwrite the newer refresh's rows after that refresh cleared the stale mark. Both jobs now take the lock per profile and skip, counting as busy, a profile another server is refreshing. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): mark profiles stale when their titles get embeddings A refresh that ran before a title had a vector left it out of the taste vector and cleared the stale mark, and storing the vector later did not mark anything, so the profile waited for the nightly taste run. The embedding backfill now marks stale the profiles with signals on the items it stored, every 500 items and when the run ends. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): keep taste rows through an embeddings reset The reset deleted every taste profile, so neither the stale sweep nor the cache job had a profile to rebuild after re-embedding, and personal rows stayed empty until the nightly taste run. The reset now clears the taste vectors and keeps the rows; the embedding job marks them stale as it stores their titles' vectors, and the stale sweep rebuilds them. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * chore(api): regenerate the v2 contract for the reset's taste profile count Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(policy): serialize policy reloads so a generation never goes back The origin's synchronous reload and the event or poll reload could run at once, and the engine installs whatever generation it is handed, so an older snapshot could replace a newer one after the newer one was announced; a stale sweep under the older policy could then clear marks with no announcement to follow. Reloads now run one at a time, each loading the store's current snapshot, and the change hook runs after the reload lock is released. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): skip an input a local model refuses for its length An Ollama-style provider answers an over-long input with a 500 naming the context length. The shortened retries recognised it, but when they failed too the item counted as a provider failure, and as the first item of a run it stopped the run and was never remembered as refused. It is now skipped as a refused input after the provider probe passes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(api): keep the frozen v1 section reads answering an empty section This branch made a failed single-section fetch answer 500 on both API versions, but /api/v1 is frozen, and its home and library section item endpoints answered such a section with no items. The v1 handlers now keep that behavior; the services the v2 adapter calls still answer the error. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(catalog): keep a local model's context-length error out of the vector cooldown A search query an Ollama-style vectorizer refused for its length came back as a 500 naming the context length, which only the embedding backfill treated as a refused input; search started its node-wide vector cooldown and sent every query to keyword search for a minute. The classification moves to embeddings.InputRefused, which both use. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(api): rebuild a profile's rows whenever an update sets its scope The scope comparison read the profile before the update's writer lock, so an update sending the original restrictions back could look unchanged while an overlapping update changed and it then restored them, leaving rows built for the wrong scope. Any update that sets a scope field now rebuilds the profile's recommendations; it is one profile. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): mark every profile stale after embedding on a SQLite user store The stale mark after storing embeddings finds profiles through the Postgres signal tables, but a user store outside Postgres keeps favorites, watchlist and progress elsewhere, so those profiles kept an incomplete or, after a reset, empty taste vector until the nightly run. On such a store the backfill marks every profile stale instead; it is the single-node setup with few profiles. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): spread Similar Users peers across accounts The row read the ten nearest profiles, so one or two households of near-identical profiles could fill them and leave the row under its three-account floor while other accounts sat just below the cut. It now reads forty and keeps up to ten with at most two from any one account. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): write the embedding lock for imported embeddings A catalog import accepts embeddings from the configured model but never writes the lock, and when every item already has a vector no run stores one to write it from, so the active model stayed empty and semantic search stayed off. A run that finds such vectors and no lock now embeds the probe text once and writes the lock from it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): leave no stale change behind a profile's first build or a busy job Marking profiles stale for items only updated existing taste rows, so a first build that read an item before its embedding was stored could miss the backfill's mark. Live Postgres profiles with no taste row now get a vectorless one, as MarkProfileStale gives them. A scheduled taste or cache job that skips a profile another server holds now marks it stale: the holder may be the other scheduled job, which rebuilds only its own stage, and the stale sweep then runs a full refresh. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(apiv2): regenerate fixture request ids after rebasing onto main Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(api): update the profile scope test as the household primary Main now refuses household management to a profile-less admin once any profile is limited, so the test acts as the primary profile. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): take a job's further locks on its own connection Each advisory lock pinned its own pooled connection, so the taste and cache jobs and the stale sweep used a second connection for every profile lock, and an embeddings reset pinned four. Under API load the profile lock's 10-second acquire could then time out and count the profile as failed. Profile locks, the reset's extra job claims and its sweep lock now go on the first lock's session through pglock.Lock.AcquireAlso, and a new ReleaseAlso unlocks each profile's key as soon as its profile is done. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): keep partial runs from hiding a failed full run The 15-minute embedding catch-up and the startup global-row build were recorded under the nightly jobs' task keys, so admin status showed a fresh "completed" minutes after a failed nightly run. They now record under recommendations.embeddings.catch_up and recommendations.cache.global_rows, and the v2 status reports them as a new last_partial_run beside last_run, which now always means the last full run. The admin page shows both. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): stop an embedding run whose key is revoked mid-run The probe that tells refused inputs from a provider refusing everything ran only before the first stored vector. A key revoked mid-run (Gemini answers it with 400) made every remaining item cost three calls, count as skipped, and be held back by the catch-up pass until the next nightly run. The run now probes again after three refusals in a row, and when the probe fails the refusals since the last stored vector or probe count as failures and are not remembered as refused. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): keep a stale mark pending past the nightly taste job The stale sweep took only profiles whose mark was newer than updated_at, and the nightly taste job sets updated_at to its start without rebuilding cached rows. A mark it passed over, such as one from an access change, stopped counting, and the rows built under the old scope stayed until the cache job. The sweep now takes every marked profile; only a full refresh clears a mark. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): count co-watch pairs' shared watchers by account A co-watch pair needed 3 shared watchers, counted by profile, so one account whose 3 profiles watched both titles created a pair that every other household then saw in Because You Watched and similar-title rows. The shared floor now counts distinct accounts, as the per-item floor already did; the Jaccard score still treats profiles as watchers. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): purge cache rows the job wrote for a deleted profile The cache job built a profile's rows without checking afterwards that the profile still existed, unlike a refresh and the taste job. A profile deleted after the build's access check, and purged before its writes, kept orphan rows until they expired about 26 hours later. The job now checks again after its last write and purges them. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): retry refused embedding inputs after a reset Each server remembers the inputs its provider refused so the catch-up pass does not resend them, and only a full embedding run cleared that record. After an embeddings reset, for example one made for a dimension conflict, every server kept skipping those items until the nightly run. The record now notes the embedding lock it was made under, and a run that finds a different lock, or none after a reset, clears it first. This works on every server, not just the one that ran the reset. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(web): stop labeling the newest cached row as the cache refresh The admin page showed cache_refreshed_at as "Cache refreshed N ago", which reads like the cache job's health. It is the newest row's write time, and profile refreshes keep it recent while the nightly job fails. The page now says "Newest cached row written N ago", and the v2 field's documentation points to recommendations.last_run for job health. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): record stale sweeps and report the stale backlog The stale sweep and the refreshes it ran left no record: a profile whose rebuild always failed was retried every five minutes with only an error log, and a policy change that marked every profile stale drained with no visible progress. A sweep that refreshed or failed a profile is now recorded under recommendations.stale_sweep with its counts, and the v2 status reports a new stale_sweep object with the pending backlog and the last sweep, which the admin page shows on the taste profile card. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): warn when the startup global-row build cannot start Any error from claiming the cache job for the startup build of the global rows was logged at Info, including a database failure while taking the job's lock. A busy job stays at Info; any other failure is now a warning with the error. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): mark profiles stale once per policy change Every server marked every taste profile stale when it loaded a new policy generation, so a policy save cost one full-table update per server. The repeat marks were what kept a server that rebuilt a profile under the old policy from clearing the change's mark. Now a refresh, the only thing that clears marks, first checks that its server has loaded the stored generation (policy.System.Current) and otherwise leaves the profile pending. With that check one mark per generation is enough: the first server to announce it claims the generation in server_settings in the same statement as the mark, and the others mark nothing. The policy hook now receives the generation it announces. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): rebuild rows when the unrated-content setting changes Rows of profiles with a content-rating ceiling are built under the access.unrated_content decision, but changing it marked nothing stale. Turning it to allow left those rows without the newly allowed titles until the nightly jobs. Saving the setting now marks every profile stale, and marks again after the other servers' 10-second cache of the setting has expired, so a refresh that still saw the old value cannot clear the mark. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(recommendations): drop the HNSW clamp test main already has Main's TestFindTasteProfileCandidatesWithGenresAboveEfSearchMaximumDB covers the same hnsw.ef_search clamp end to end, so the branch's narrower copy and its database-contracts entry go. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(recommendations): scope Because You Watched rows with LibraryScope scopeToLibraries repeated the library intersection that main now keeps in catalog.AccessFilter.LibraryScope. It now calls LibraryScope and keeps only its own rule that an empty section scope allows nothing, which LibraryScope reads as every library. The result also leaves out a library the profile hid, which the filter already excluded. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): apply the content scope through AppendContentScope The read gate every recommendation row passes, FilterAccessibleItemIDs, checked the access filter's content allow-list by hand and ignored its name prefix. It now uses catalog.AppendContentScope, as main's discovery queries do, so both apply the way the catalog query executor applies them. Builds need no change: profileAccessFilter never sets a content scope, and section and API callers do not set one on recommendation reads today. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(api): expect a failed single section to answer an error Main's deleted-collection test expected HomeSectionItems to answer an unrelated fetch failure with an empty row. On this branch the single-section service, which v2 calls, answers a real failure with a 500 and only v1 keeps the empty row; a deleted collection still shows an empty row on both. Co-Authored-By: Claude Opus 5.5 <[email protected]> * style(recommendations): satisfy lint on the sweep and lock changes Log the profile-lock release failure with a context, check the sweep refresh's error in its test, and stop the sweep loop at shutdown without an early nil return. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(recommendations): make recommendations more accurate and relevant (#1967) * feat(recommendations): weigh taste signals and new profiles more accurately - The taste vector averages only titles with positive weight; dislikes and abandoned titles still count in signal_counts but no longer pull the vector away from them. - A 3-star rating is half credit: it adds no explicit weight and halves the title's watch and intent weight, so a 3-star completion counts less than an unrated one. - A series quiet for more than 30 days is scaled by how much of it the profile watched, so a sampled or dropped pilot weighs far less than a show watched through. - Cold-start levels count positive titles behind the vector (stored as signal_counts.positive_titles and left out of the taste summary), with thresholds 3 and 10. A profile with three taste-seed picks now opens on its own row. Watchlist-only titles do not raise the level, and favorites and watchlist entries count once per title. - A read requests a refresh for a profile with positive signals but no personal rows, so picks embedded after the last refresh are picked up. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * feat(recommendations): compose the main row per interest and diversify what is served - The main For You row of a profile with 10 or more titles is composed from its taste clusters: each interest gets slots in proportion to its weight (at least 3), its own nearest neighbors ranked by MMR, interleaved by weighted round-robin. One averaged vector used to hand the row to the heaviest interest or to titles between interests. - Diversification now reaches the 20 titles clients show: the genre pass is a stable reorder over MMR order that admits at most 10 titles of one genre into the served 20, deletes nothing, and keeps cached rows at 60. The recency boost no longer re-sorts. - Per-type supplements sit after the served 20 so library sections of the minority type still fill, and their queries skip types the viewer cannot see. - Cluster rows leave out the main row's served 20; a row thinned to empty is cached as built, not missing. - A mild quality prior nudges candidates by their public rating (IMDb, else TMDB below 9.5), at most half a standard deviation of the pool's scores and standardized per media type, so a well-rated title wins near-ties. - relevance_test.go adds a persona harness (movie buff, series binger, kid, new profile, mixed taste, lapsed) asserting variety, interest shares and placement thresholds. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * feat(recommendations): show taste-seed picks at once and fix Jellyfin rows - Submitting taste-seed picks refreshes the profile on the spot, waiting up to 5 seconds (at most 4 at once per server; the refresh finishes in the background on timeout). First-run Done opens the For You page, and the web refetches recommendations after 3 and 15 seconds as a fallback. - Jellyfin /Movies/Recommendations sends only rows Jellyfin can label truthfully: up to two Because You Watched rows (SimilarToRecentlyPlayed, named after the anchor title, dropped when the viewer cannot see it) and cluster rows (SimilarToLikedItem, named after the bare cluster label), each with its own category id. It no longer shows "Because you watched For You" or "Popular on This Server". - Jellyfin /Items/{id}/Similar uses the recommender when recommendations are enabled, filtered to what the session can see. - Add docs/architecture/recommendations-evaluation.md (metric definitions for #1139, no thresholds), scripts/recs-probe/capture.sh (read-only v2 capture with per-metric summaries), and Postgres rubric tests for leakage, cross-profile overlap and new-profile rows. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * feat(recommendations): always offer default rows and rank global rows by quality - Discover and its section pages serve two live, access-scoped default rows that need no viewing history: "Highly Rated in Your Library" (IMDb-first rating of at least 7.0, movies and series in proportion to what the viewer can see) and "Recently Added" (by the later of the title's or its newest episode's added date, no window). They show even when recommendations are disabled, and Top Rated is served by the live query. - The cached Recently Added row uses the same query, so a new profile on a quiet server always gets a row on home, For You, Watch Tonight and Jellyfin. - Popular needs viewing by at least two accounts over 90 days and is ordered by accounts, so one household's viewing is not shown as popular. - Genre rows are rating-led ("Top <genre>"), the genre menu grows from 8 to 16, and Discover dedupes only against items a row actually shows. - The taste-seed picker interleaves genres on its first pages. - Non-personal rows and the picker offer movies and series only for 1.0, through one recommendableMediaTypes list. - The web For You page shows the default rows for a profile with no history and no longer claims they come from its viewing history. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * feat(recommendations): rotate personal rows daily and title rows honestly - Because You Watched never anchors on a title the profile rated 2 stars or lower; the worker, the Reader and Watch Tonight share one anchor helper and one disliked-rating threshold. - Cluster labels name at most two genres that most of the cluster carries and that stand out against the profile's own titles, always including the cluster's most common genre, joined with ", ". A cluster with no genres is titled "Picked from your history". Same-titled rows are hidden when they mostly overlap, otherwise told apart by another genre. - Default-titled For You and taste-match sections take the served row's title when that row is a shared row (Popular, Recently Added, Highly Rated, a genre row); admin-set titles are never replaced. Row titles live in one place. - The taste card's genres come from the clusters, heaviest first, and the web "N signals" label is gone. - Personal rows rotate daily: the top 10 stay, the rest of the served 20 is drawn from the next 20 by rank, seeded by profile, row and server-local date so every node serves the same rotation. - The freshness boost (1.05 over 14 days) applies before selection, and is skipped when more than a quarter of a candidate pool is new. - docs/architecture/recommendations.md gains a Ranking section. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(recommendations): run the ranking database contracts in CI List the recommendation DB tests this branch adds in scripts/ci/db-contracts.txt so the Go DB pins job runs them. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): serve no personal rows while recommendations are off With recommendations disabled, cached personal rows (For You, clusters, Because You Watched, Similar Users) kept serving until they expired. The Reader now serves the global and default rows only when recommendations are disabled, for native reads, sections and Jellyfin. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): offer only movies and series in personal rows Books are deferred for 1.0, but only the shared rows and the taste-seed picker followed recommendableMediaTypes; For You, cluster rows, type supplements, Because You Watched (anchors and co-watch neighbors) and Similar Users still recommended audiobooks. All of them now use the same list, and the Reader's per-request access check also drops titles of other types, so rows cached before the change stop showing them at once. Books still shape the taste vector, an audiobook's own similar rail is unchanged, and a title's co-watch neighbors now match its type like its embedding neighbors. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * perf(recommendations): read Discover's default rows from per-type indexes Highly Rated in Your Library and Recently Added scanned and sorted every movie and series on each Discover read: about 0.6 s on a 190,000-title catalog. Each media type is now read from its own index only as deep as the row needs, each read is planned for its own exclusion set, and the per-type title counts Highly Rated interleaves by are reused per access scope for 10 minutes. Discover also reads the profile's watched set once per request instead of again for the airings blend. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): rank rating-led rows by notable titles and trusted ratings On a large catalog, Highly Rated in Your Library and the Top <genre> rows were led by obscure titles rated 10.0: most titles carry no vote count, their ratings rest on a handful of votes, and metadata files copy a TMDB score into the IMDb field. Rating-led rows (Highly Rated, genre rows, the taste-seed picker) now put notable titles first, those with a logo and at least five keywords, and no longer trust an IMDb rating of 9.6 or more, as TMDB ratings of 9.5 or more already were. The quality prior reads the same ratings. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): rerun a profile refresh for changes made while it ran A refresh request that arrived while the profile's refresh was running was dropped, leaving the change to the stale sweep up to 5 minutes later, so a burst of ratings showed a half-updated row in the meantime. The running refresh now runs once more as soon as it ends; a request made while the refresh is only queued is read by it and adds no run. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(jellycompat): keep Movies/Recommendations to movies and the ParentId library /Movies/Recommendations returned series in most categories, anchored "Because you watched" on series, and ignored ParentId, which jellyfin-web sends for the movie library whose Suggestions tab it fills. Jellyfin answers it with movies only. The endpoint now reads the rows with series excluded, so a series anchor gives way to the next movie one, and a library ParentId keeps the titles to that library; any other parent gets []. The recommendation row filter now applies an access filter's excluded media types, which native callers do not set. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): title a cluster's see-all page as Discover does Discover can rename a cluster row to tell it apart from the profile's other cluster rows ("Because you enjoy Drama, Comedy"), but the row's see-all page kept the cached title ("Because you enjoy Drama"). A cluster section now takes the title Discover gives the row today; a row Discover hides keeps its own. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): fill a library's For You row from the other personal rows A library's "Recommended for You" row showed only the main For You row's titles in that library. The main row ranks everything the profile can see, so a library with a small share of the catalog came back nearly empty or empty (an anime or international TV library: 0 of 20) even when the profile's cluster or Because You Watched rows held titles there. When the main row leaves a library short, the row now continues with the library's titles from the profile's cluster rows, heaviest first, then Because You Watched and Similar Users, filtered like every row. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): keep each distinct taste in its own cluster Taste clustering ran k-means from one k-means++ seeding. When both seeds landed in one interest, the sliver cluster was merged away and the profile collapsed to one cluster: a horror and romantic-comedy profile that added three westerns lost its romcom row and got almost no westerns. Main rows then fell back to the averaged taste whenever two cluster centres were more than 0.9 cosine-similar, which on a real server held for most pairs of different-genre clusters. Each cluster count now tries up to 8 fixed seedings and keeps the tightest one with no cluster under 3 titles. A profile under 200 titles may get more clusters than its size rule, up to 5, when that partition separates better (silhouette at least 0.1). Every cluster anchors the main row, which follows the clusters' weights rather than the genre cap. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(apiv2): reject a recommendation section key that cannot name a section GET /api/v2/recommendations/section/cluster?key=abc, a negative index, or a genre key that is not valid text answered 500 internal_error. Such keys are now a 422 validation_failed problem on query.key, as a missing key already was. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * refactor(recommendations): simplify the relevance changes Tidies code this branch changed, with no behavior change: one helper for the heaviest-first cluster order and one for cluster sizes, a plain comparator for the rotation draw, the genre menu's eligibility predicate reused rather than copied, clearer names for the per-genre cap and the row builder, and three reflowed doc comments. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): address review findings on the relevance changes - Highly Rated no longer divides by a title count cached as 0 when that type's titles arrive within the 10-minute cache, which made Discover fail. - A refresh request that arrives as a refresh finishes is no longer lost: claiming the refresh or asking it to run again is one locked step. - Cluster rows leave out every title the main row's daily rotation can serve (its first 30), not only its first 20. - A main or cluster row's "see all" page opens with the order the row was served in, not the unrotated cache. - Jellyfin /Movies/Recommendations reads the profile's watched set once per request. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(recommendations): match the stacked empty-row rules on composed rows The main row is composed from the taste clusters here, so an unreadable cluster fails it too and both keep their cached rows; a cluster row that rebuilds empty is cached empty rather than deleted, as reads count an empty cluster row as built. A cleared taste row records no positive titles. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): address Codex review on the relevance changes - The genre limit scales to a row shorter than the served window, so a 12-title row serves at most 6 of one genre while others are available. - Reads that miss the title-count cache for one access scope at the same time share a single count instead of each counting the catalog. - Jellyfin /Movies/Recommendations reads every anchor's Because You Watched row, so with categoryLimit=1 a series anchor gives way to a movie one. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): check the shared title count's type and spelling Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): serve no personal rows in Watch Tonight while disabled Watch Tonight merged the cached For You, Because You Watched and Similar Users rows even with recommendations disabled, until they expired. It now uses only the cold-start rows then, as every other read does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): pick Discover's genre rows without taste while disabled Discover left out the genres of a profile's cached taste clusters when it picked the day's genre rows, even with recommendations disabled. It now reads the clusters only when personal rows are served. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): rotate personal rows by the UTC date The daily rotation was seeded with each server's local date, so replicas in different time zones, or crossing their local midnight at different moments, served different windows to the same profile. It now uses the UTC date. The probe script also leaves 3-star ratings and the positive-title total out of its positive-signal sum, as the recommender does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): fill default rows and Jellyfin categories past removed titles - The default rows leave out the titles the profile rated 1 or 2 stars in their query, as they already left out watched and favorited titles, so a "see all" page is no longer short when such titles rank near the top. - Jellyfin reads each category's row deep enough to fill it after the categories before it took their titles (categoryLimit × itemLimit, up to a cached row's 60), so a later cluster is no longer dropped when its first titles were already shown. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(jellycompat): cap the recommendation limits before they size anything Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(web): refetch taste-seed rows until the server refresh can end A profile refresh can run for two minutes, but the page stopped refetching 15 seconds after a taste-seed submission, so a slow refresh left the old rows on screen for the five-minute stale time. Two more refetches now run, the last after the server's refresh timeout. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * docs(recommendations): state the bound on the silhouette distance matrix Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): keep a taste-seed refresh after the request ends RefreshProfileNow marked the profile stale and, on a busy server, queued the refresh with the request's context, so a request canceled after its picks were committed could leave neither a stale mark nor a queued refresh. Both now use a detached context, as NotifySignalsChanged does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * docs(recommendations): describe the genre pass as greedy in rank order The pass keeps relevance order and never revisits a title it let in, so multi-genre titles can leave a genre above half of the window when only a different set of titles would meet the cap. The comment and the architecture doc claimed a guarantee the pass does not give. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(web): refetch taste-seed rows through a refresh's rerun A submission that arrives while a refresh reads makes that refresh run once more, so the picks can land after two refresh timeouts, past the page's last refetch at 125 seconds. One more refetch now runs at 245 seconds. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): weigh a favorited or watchlisted title once Favorites and watchlist entries resolve to their canonical title, so favoriting several episodes of a series added the series' favorite weight once per episode while the count recorded one title, letting the series dominate the taste vector. Each title now weighs once, at its newest entry. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): choose Watch Tonight's fallback after filtering, recheck title counts Watch Tonight decided it was warm before filtering its cached personal candidates, so a cache holding only titles that can no longer be served, such as books cached before they left personal rows, answered an empty list instead of Popular and Recently Added. It now filters first and falls back when nothing survives. The title-count cache was checked only before singleflight, so a request that missed just as another finished counting started a second full count. The shared call now checks the cache again first. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(recommendations): never fail or stall Discover on Highly Rated's title counts The per-type title counts only set how Highly Rated mixes movies and series, yet a failed or slow count failed the whole Discover read, and every read after an expiry waited on a full count. Expired counts now serve the read while a background count refreshes them, a read with no counts yet stops waiting when its request ends, and a failed count falls back to the scope's last counts, or equal weights, retrying after a minute. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(recommendations): read the server's top genre once per server, not per render A "Top Picks Today" section with no genre and no matching cluster asked for the top genre on every render, which scans the whole catalog and the whole watch history for a result that is the same for every viewer. Each server now reuses it for 10 minutes, serving an expired genre while one background read refreshes it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): fail a personal row build rather than cache a thin row A main-row anchor whose candidate query failed was logged and dropped, and embedding read errors were ignored, so one transient error cached for a day a main row missing a whole interest (the others took its slots) or ranked without MMR. Such failures now fail the main row, and a cluster row whose embeddings cannot be read counts as failed like a failed candidate query; the cached rows stay and the refresh is retried. A failed main row also keeps the cluster rows cached, since rebuilt against no main row they would repeat its cached titles. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): leave rated and abandoned titles out of built rows Rows were built leaving out only watched and favorited titles, so a title rated 4 or 5 stars without enough progress, which weighs most in the taste vector, led its own row, and a show dropped early stayed recommendable. Similar Users already left out every rated title. Rows the engine builds now leave out every title the profile rated and every title it abandoned (progress under 15% untouched for 14 days, the taste profile's own dislike signal), and a read drops every rated title from cached rows, not only those rated 2 stars or lower. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): rotate personal rows for one served window at every limit Reads rotated personal rows for a window of the caller's limit, while a row's see-all page and Discover rotate for 20 items, so a page read at limit 10 served rank order and one at 15 or 30 drew a different tail: the see-all page opened in an order the row was never served in. The window is now ServedRowSize at every limit, so a shorter page is a prefix of the rotation and a longer one continues it, and the cluster-repeat check sees the same window everywhere. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): fill default rows and Watch Tonight past every rated title Reads now drop every title the profile rated, so the live default rows, which left only titles rated 2 stars or lower out of their query, lost liked titles to the filter afterwards and came back short. They now leave every rated title out in the query, and Watch Tonight's own filter drops every rated title as the rows do. The v2 because-watched description says so. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): keep Watch Tonight's fallback filled and read its exclusions once Watch Tonight's cold-start fallback read the cached Recently Added row, which nothing rebuilds while recommendations are disabled, so about a day after an admin disabled them the fallback came back empty while Discover, reading the row live, still filled. The fallback now reads Recently Added live. Each of its two filtering passes also loaded the profile's exclusion set, and the handler's filter read the watched set a third time; the passes now share one read, and the handler shares the watched set with them. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(recommendations): serve no personal Watch Tonight cards while recommendations are off Discover-mode Watch Tonight cards ranked a profile's stored taste profile against the library even with recommendations disabled, though every other read serves only the global rows then. They now skip the taste profile while the engine is unavailable. Their cold-start candidates also kept only titles the viewer could see, so a book cached in a global row before books left the rows could still become a card; they now keep only the types the rows offer. Co-Authored-By: Claude Opus 5.5 <noreply@anthro…
Title: feat(recommendations): make recommendations more accurate and relevant
Problem
Related issue: #1139
Validation tasks: changes #1145 C1, C2, C3, C4, C5 and #1146 C1, C2, C3, C4, C5 (all Not run)
Stacked on #1966 (
fix/recs-quality); review that first.With the pipeline fixed, recommendations still fall short of the 1.0
criteria: a personalized, varied set per profile, sensible choices for a new
profile, and a default row instead of an empty shelf. This PR changes what
the rows hold and how they are ranked. Today:
needs other accounts' viewing, ratings, or titles added in the last 14 days.
After three taste-seed picks it still opens on Popular, and its own row
comes last.
vector, so a profile with two tastes (horror and romantic comedies) gets one
of them, or titles that fit neither. Taste clustering runs k-means from one
random start, so a profile with distinct tastes can collapse into a single
cluster: on a test server, a horror and romcom profile that watched three
westerns lost its romcom titles and got almost no westerns.
over 60 cached items and then re-sorted by score, so the served row was the
raw nearest neighbors (one persona's top genre was over-represented by 40
points against its history).
3-star rating counted for more than an unrated completion, and a sampled or
dropped series weighed as much as one watched through.
rows were led by a housemate's watching, and the taste-seed picker offered
books. Cluster labels like "Thriller & Horror & Action" named genres most of
the row did not have, and an idle profile saw the same 20 titles every day.
that library, so a library with a small share of the catalog (anime or
international TV) shows nothing.
/Movies/Recommendationsreturned series and ignoredParentId.sweep, and a malformed section key (
/section/cluster?key=abc) answered500.
Approach
default rows that need no history, "Highly Rated in Your Library" and
"Recently Added". They show even when recommendations are disabled. The
cached Recently Added row uses the same query, so home, Watch Tonight and
Jellyfin always have a row. Cold-start levels count the positive titles
behind the taste vector, with thresholds 3 and 10, so three taste-seed picks
put the profile's own row first. Submitting picks refreshes the profile on
the spot (waiting up to 5 seconds), and first-run setup opens For You.
credit; a series quiet for 30 days is scaled by how much of it was watched.
tightest with no cluster under 3 titles; a profile under 200 titles may get
more clusters, up to 5, when they separate better (silhouette at least 0.1).
taste clusters, each with slots in proportion to its weight and its own
nearest neighbors. Rows built from the averaged vector, and cluster rows,
get a stable genre pass that admits at most 10 titles of one genre into the
served 20 and deletes nothing. A mild quality prior nudges near-ties by
public rating, at most half a standard deviation of the pool's scores, per
media type. Cluster rows leave out every title the main row can serve (its
first 30). Personal rows rotate daily below a pinned top 10, seeded by
profile and UTC date so every node serves the same rotation, and
a row's "see all" page opens in the order the row was served. A small
freshness boost applies before selection, skipped for bulk imports.
Highly Rated and the picker rank by catalog rank: notable titles first (a
logo and at least five keywords), then a trusted rating (IMDb below 9.6,
else TMDB below 9.5). Most titles carry no vote count, so on a large catalog
the best-rated titles are otherwise obscure ones rated 10.0. The picker
interleaves genres. Every row, personal or not, and the picker offer movies
and series only for 1.0, through one list (
recommendableMediaTypes), soadding a type later is a one-line change; reads also drop other types still
cached from before.
short, it continues with that library's titles from the profile's cluster
rows, Because You Watched and Similar Users.
rows, never personal rows still cached from before.
a cluster's see-all page takes the title Discover gives the row,
default-titled sections take the served row's real title, the taste card
takes its genres from the clusters, and Because You Watched never anchors on
a title the profile rated 2 stars or lower.
/Movies/Recommendationssends only movies, in Because YouWatched rows anchored on a movie and cluster rows named after their genres;
a library
ParentIdkeeps them to that library./Items/{id}/Similarusesthe recommender.
makes it run once more as soon as it ends. A section key that cannot name a
section answers 422
validation_failed.as the row needs, and Discover reads the profile's watched set once per
request instead of twice.
docs/architecture/recommendations.mdgains a Ranking section, anddocs/architecture/recommendations-evaluation.mddefines the metrics for the#1139 rubric;
scripts/recs-probe/capture.shmeasures them read-only throughthe v2 API.
Validation
make test-go, web lint/format/build/budget,make test-web, and everycontract, fixture, migration and path check).
make test-db-pinsagainst a fresh migrated pgvector database: all 107query-budget pins and all 138 database contracts pass, including the new
recommendation DB tests and a pin that both default rows walk their
indexes.
relevance_test.go) asserts variety, interest shares,placement, label coverage and rotation thresholds.
(two established profiles on one account, a kid profile, a new profile, a
second account and two library-restricted profiles), all ten cases pass
against a written rubric. They ran on this branch before its final review
fixes; the final branch then ran on the same server, where a spot check of
Discover, "see all" order, the kid profile's ceiling and the 422 key check
passed:
(share 0.90 and 0.95, lift 2.1 and 3.3), with no watched, favorited or
disliked titles and no repeats across Discover rows. One profile's
history is all comedy, so its row is too.
of the profile; after this branch's refresh change, a burst of changes
applies at once.
the next read, with none of the picks in it.
library only; one with no accessible titles gets empty 200s, distinct from
the 422 a bad key now answers.
account's profile is refused, and a PG profile gets nothing above PG
across every recommendation surface.
new profile's id, refreshed rows show after a reload, and the default and
restricted cases render as on the server.
identical, and every cached row expires after the next nightly rebuild.
Risks
media_items, built concurrently. NoAPI field changes. Client-visible, on
/api/v1too: row titles ("Top", "Highly Rated in Your Library", "Profiles Like You Enjoyed",
cluster labels joined with ", ", "Picked from your history"); Popular is
absent below two accounts; books leave every row and the picker;
positions 11 to 20 of personal rows change daily; main rows change for
profiles whose clusters merged before; the v1 and v2 taste-seed POST can
take up to 5 seconds; Jellyfin movie suggestions no longer include series.
shares, rotation window, silhouette floor, notable test) were tuned on
synthetic personas and one dev catalog with one embedding model.
re-applying the genre limit, so a row whose candidates lean on one genre
can serve more than 10 of it (15 of 20 for one test profile). "Notable
first" is a stand-in for vote counts; Rank rating-led recommendation rows by a vote-weighted rating #1961 and
Send TMDB vote counts as a per-source rating silo-plugin-metadata-tmdb#24 track ranking by a vote-weighted
rating.
15 ms each on a large catalog. Highly Rated mixes media types by
per-type title counts that each server reuses for 10 minutes, so the mix
can lag a library change by that long.
Checklist
AI Disclosure
a Sonnet simplicity-and-risk judge, whose required changes are folded in,
and the validation cases were walked on a dev server against a written
rubric. A high-effort Claude Code review of the finished branch reported 10
candidate findings: 5 are fixed here (a stale zero title count failing
Discover, a refresh request lost as a refresh finished, cluster rows
repeating titles the main row's rotation serves, "see all" pages in cached
order, Jellyfin reading the watched set twice). The other 5, four query
costs and a repeat-refresh case, are left as follow-ups. Codex's review of
the PR raised 21 more: 17 are fixed (unbounded Jellyfin limits sizing
allocations, a genre limit that did not scale to
short rows, concurrent title-count misses each counting the catalog,
Jellyfin missing a movie anchor behind a series one, Watch Tonight serving
personal rows and Discover's genre rows following taste while disabled,
the rotation seeded by each server's local date, the probe counting
3-star ratings as positive, default rows limited before dropping disliked
titles, Jellyfin categories read too shallow to refill, taste-seed rows
refetched too briefly to catch a slow refresh, a taste-seed stale mark
tied to the request's context, a Jellyfin item limit above what a row read
returns, taste-seed refetches ending before a refresh's rerun, a series' favorite
weight added once per favorited episode, Watch Tonight choosing its
fallback before filtering, a title count repeated after a cache miss), one repeats a finding
already fixed in fix(recommendations): make the recommendation pipeline correct, isolated and observable #1966, one (an unbounded silhouette distance matrix) is
already bounded at under 200 titles, the greedy genre pass is kept and
its docs corrected (left open for a stricter pass), and the movies-and-series-only scope is kept by
maintainer decision.
🤖 Generated with Claude Code
Note
Improve recommendation relevance, personalization, and default-row serving
recommendableMediaTypesin repo.go, adds trusted IMDb/TMDB catalog-rating ordering, genre round-robin taste-seed candidates, and a title-count cache.Top <genre>labels (thePopular inform is no longer recognized in recommendations.go);GetTopRatedItemsis removed in favor ofListDefaultRowItems;WeightRated3andGenreCapPercentconstants are removed; a new index migration 20261004161912_index_default_recommendation_rows.sql runs concurrently (non-transactional).Macroscope summarized b55bc8f.