youpipe: overhaul recommender core with IDF, freshness floor, provenance, user controls, and UCB exploration
- Commit
8f60e05fba6f6a97113115bbfd0716f0dd213b34- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-09 17:02 UTC (5 months ago)
- Parents
70eef91
Diff
youpipe/src/main/java/com/vayunmathur/youpipe/util/Recommender.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/Recommender.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/Recommender.ktindex 062e423a8d..20c6632f74 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/Recommender.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/Recommender.kt@@ -1,9 +1,11 @@ package com.vayunmathur.youpipe.util import com.vayunmathur.youpipe.data.HistoryVideo+import com.vayunmathur.youpipe.data.RecommendationPreferences import com.vayunmathur.youpipe.ui.VideoInfo import kotlin.math.exp import kotlin.math.ln+import kotlin.math.roundToInt import kotlin.time.Instant /** Where a recommendation candidate originated. */@@ -12,34 +14,133 @@ enum class RecSource { RELATED, TRENDING, SUBSCRIPTION, TOP_CHANNEL, SEARCH } /** * A recommendation candidate plus its provenance. [sourceWatchedAt] is the time * the source video was watched and is only meaningful for [RecSource.RELATED].+ * [sourceLabel] is a human-readable origin (the source-video title for RELATED,+ * the channel name for TOP_CHANNEL) used to build the feed's "why" reason. */ data class Candidate( val video: VideoInfo, val source: RecSource, val sourceWatchedAt: Instant? = null,+ val sourceLabel: String? = null,+)++/** A ranked feed item: the video, the source that won dedup, and a display reason. */+data class RankedVideo(+ val video: VideoInfo,+ val source: RecSource,+ val reason: String,+)++/** A per-channel recommendation override, keyed by lowercased author name. */+data class ChannelPref(+ val multiplier: Double = 1.0,+ val blocked: Boolean = false,+ val pinned: Boolean = false,+)++/** Hard content filters applied before ranking. All default to no-op. */+data class ContentFilters(+ /** Drop videos with a duration in (0, 60) seconds. */+ val hideShorts: Boolean = false,+ /** Drop videos with unknown/zero duration (treated as live). */+ val hideLive: Boolean = false,+ val minDurationSec: Long = 0,+ val maxDurationSec: Long = 0,+)++/** Aggregate impression stats for a channel, used for the exploration bonus. */+data class ChannelImpressionStat(+ val shownCount: Int,+ /** Whether any recommended video from this channel was later watched. */+ val watched: Boolean, ) /** * All ranking tunables in one place, replacing the scattered magic numbers of the- * previous inline scorer.+ * previous inline scorer. New fields default so that the previous behavior is+ * reproduced exactly (idf off, freshness floor 0, single half-life, UCB off). */ data class RecommendationWeights( val authorAffinityWeight: Double = 2.0, val authorAffinityCap: Double = 10.0, val sourceRecencyWeight: Double = 5.0, val keywordWeight: Double = 4.0,+ /** Upper bound on the keyword term so distinctive tokens can't dwarf others. */+ val keywordScoreCap: Double = 8.0, val uploadFreshnessDecay: Double = 0.03,+ /**+ * Additive floor in [0, 1] applied to the freshness multiplier so old but+ * relevant videos are not zeroed out. 0 reproduces the pure multiplier.+ */+ val freshnessFloor: Double = 0.0, val explorationBase: Double = 0.5,+ /** Weight of the per-channel UCB-style exploration bonus. 0 disables it. */+ val explorationUcbWeight: Double = 0.0,+ /** Multiplier applied to the exploration bonus of channels shown but never watched. */+ val unwatchedExplorationDecay: Double = 0.3, val mmrLambda: Double = 0.7, val perAuthorCap: Int = 3, val subscriptionDamping: Double = 0.5, val maxSubscriptionFraction: Double = 0.3, val maxResults: Int = 50,- /** Half-life (days) for down-weighting older watches when building the profile. */+ /** Half-life (days) for down-weighting older watches when [shortTermBlend] is 0. */ val recencyHalfLifeDays: Double = 14.0,+ /** Short-term interest half-life (days), used when [shortTermBlend] > 0. */+ val shortTermHalfLifeDays: Double = 3.0,+ /** Long-term interest half-life (days), used when [shortTermBlend] > 0. */+ val longTermHalfLifeDays: Double = 45.0,+ /** Blend weight of the short-term half-life in [0, 1]. 0 = single half-life. */+ val shortTermBlend: Double = 0.0, /** Completion assumed for history items without a known duration (e.g. imports). */ val neutralCompletion: Double = 0.5,-)+ /**+ * Watch-time (minutes) at which absolute engagement saturates to 1.0, blended+ * with fractional completion so meaningful watch time on long videos counts.+ * 0 disables the absolute term (pure fractional completion).+ */+ val watchTimeSaturationMinutes: Double = 0.0,+ /** Recent-window (hours) within which already-shown low-relevance videos are suppressed. 0 = off. */+ val recentSuppressionWindowHours: Double = 0.0,+ /** Normalized-relevance above which a recently-shown video is kept anyway. */+ val recentSuppressionRelevanceThreshold: Double = 0.8,+) {+ companion object {+ /**+ * Maps user-facing [RecommendationPreferences] dials onto ranking weights.+ * Each dial is a float in [0, 1]; 0.5 reproduces the balanced defaults.+ */+ fun fromPreferences(prefs: RecommendationPreferences): RecommendationWeights {+ val d = prefs.discoveryFamiliar.toDouble().coerceIn(0.0, 1.0)+ val f = prefs.freshEvergreen.toDouble().coerceIn(0.0, 1.0)+ val x = prefs.focusedDiverse.toDouble().coerceIn(0.0, 1.0)+ return RecommendationWeights(+ subscriptionDamping = lerp(0.8, 0.2, d),+ maxSubscriptionFraction = lerp(0.5, 0.1, d),+ explorationBase = lerp(0.1, 0.9, d),+ explorationUcbWeight = lerp(0.0, 1.0, d),+ uploadFreshnessDecay = lerp(0.01, 0.05, f),+ freshnessFloor = lerp(0.6, 0.0, f),+ mmrLambda = lerp(0.95, 0.45, x),+ perAuthorCap = lerp(5.0, 1.0, x).roundToInt().coerceAtLeast(1),+ shortTermBlend = 0.35,+ watchTimeSaturationMinutes = 15.0,+ recentSuppressionWindowHours = 12.0,+ )+ }+ }+}++/** A named bundle of the three feed-mix dials. */+enum class RecommendationPreset(+ val discoveryFamiliar: Float,+ val freshEvergreen: Float,+ val focusedDiverse: Float,+) {+ DISCOVER_MORE(0.9f, 0.65f, 0.85f),+ BALANCED(0.5f, 0.5f, 0.5f),+ MOSTLY_SUBSCRIPTIONS(0.15f, 0.5f, 0.35f),+ DEEP_DIVES(0.4f, 0.1f, 0.15f),+} /** Learned interest signals derived from watch history. */ data class InterestProfile(@@ -53,18 +154,44 @@ private val STOPWORDS = setOf( "but", "all", "can", "will", "into", "out", "new", "get", "got", ) +private fun lerp(a: Double, b: Double, t: Double): Double = a + (b - a) * t+ /** Lowercases, strips punctuation, splits on whitespace, and drops stopwords / short tokens. */ fun tokenize(title: String): List<String> = title.lowercase() .split(Regex("[^a-z0-9]+")) .filter { it.length >= 3 && it !in STOPWORDS } +/**+ * Whether a channel search hit [hitName] is a close enough match to the [author]+ * being resolved: case-insensitive equality or one normalized name containing the+ * other. Guards against homonym channels polluting the top-channel source.+ */+fun channelNameMatches(hitName: String, author: String): Boolean {+ val a = hitName.trim().lowercase()+ val b = author.trim().lowercase()+ if (a.isEmpty() || b.isEmpty()) return false+ return a == b || a.contains(b) || b.contains(a)+}++/** Recency decay for a watch [ageDays] old, honoring the single/dual half-life blend. */+private fun recencyDecay(ageDays: Double, weights: RecommendationWeights): Double {+ if (weights.shortTermBlend <= 0.0) {+ return exp(-ln(2.0) / weights.recencyHalfLifeDays * ageDays)+ }+ val shortTerm = exp(-ln(2.0) / weights.shortTermHalfLifeDays * ageDays)+ val longTerm = exp(-ln(2.0) / weights.longTermHalfLifeDays * ageDays)+ return (1 - weights.shortTermBlend) * longTerm + weights.shortTermBlend * shortTerm+}+ /** * Builds an [InterestProfile] from watch history. *- * Author affinity is engagement-weighted (watch completion) and recency-weighted,- * so channels the user actually finishes recently outrank channels merely opened- * long ago. Keyword weights are a recency-weighted term frequency over watched titles.+ * Author affinity is engagement-weighted (fractional completion blended with a+ * saturating absolute-watch-time term) and recency-weighted (single or dual+ * half-life), so channels the user actually finishes recently outrank channels+ * merely opened long ago. Keyword weights are a recency-weighted term frequency+ * over watched titles. */ fun buildInterestProfile( history: List<HistoryVideo>,@@ -73,17 +200,12 @@ fun buildInterestProfile( ): InterestProfile { val authorWeights = HashMap<String, Double>() val keywordWeights = HashMap<String, Double>()- val halfLife = ln(2.0) / weights.recencyHalfLifeDays for (h in history) { val v = h.videoItem- val completion = if (v.duration > 0) {- (h.progress.toDouble() / (v.duration * 1000)).coerceIn(0.0, 1.0)- } else {- weights.neutralCompletion- }+ val completion = completionScore(h, weights) val ageDays = (now - h.timestamp).inWholeDays.toDouble().coerceAtLeast(0.0)- val recency = exp(-halfLife * ageDays)+ val recency = recencyDecay(ageDays, weights) val contribution = completion * recency val author = v.author.lowercase()@@ -97,24 +219,85 @@ fun buildInterestProfile( return InterestProfile(authorWeights, keywordWeights) } +/** Engagement score for a watched item: fractional completion blended with saturating watch time. */+private fun completionScore(h: HistoryVideo, weights: RecommendationWeights): Double {+ val v = h.videoItem+ val fractional = if (v.duration > 0) {+ (h.progress.toDouble() / (v.duration * 1000)).coerceIn(0.0, 1.0)+ } else {+ weights.neutralCompletion+ }+ if (weights.watchTimeSaturationMinutes <= 0.0) return fractional+ val saturationMs = weights.watchTimeSaturationMinutes * 60_000.0+ val absolute = (h.progress.toDouble() / saturationMs).coerceIn(0.0, 1.0)+ return maxOf(fractional, absolute)+}++/**+ * Inverse document frequency of title tokens across [videos]. Tokens appearing in+ * many candidates get a low weight; distinctive tokens get a high one. Empty when+ * there are no videos (callers treat a missing token as idf 1.0).+ */+fun computeIdf(videos: List<VideoInfo>): Map<String, Double> {+ if (videos.isEmpty()) return emptyMap()+ val df = HashMap<String, Int>()+ for (v in videos) {+ for (token in tokenize(v.name).toSet()) {+ df[token] = (df[token] ?: 0) + 1+ }+ }+ val n = videos.size+ return df.mapValues { (_, count) -> ln((n + 1.0) / count) }+}+ /**- * Scores a single candidate. Relevance terms (author affinity, keyword overlap,- * source recency, and an exploration base so zero-affinity candidates can still- * surface) are summed, then scaled by upload freshness — mirroring the shape of- * the original scorer.+ * Per-channel exploration bonus. Rarely-shown channels score higher; channels+ * shown often but never watched are faded via [RecommendationWeights.unwatchedExplorationDecay].+ * Returns 0 when [RecommendationWeights.explorationUcbWeight] is 0.+ */+fun explorationBonus(+ channelKey: String,+ channelStats: Map<String, ChannelImpressionStat>,+ weights: RecommendationWeights,+): Double {+ if (weights.explorationUcbWeight <= 0.0) return 0.0+ val stat = channelStats[channelKey] ?: return weights.explorationUcbWeight+ val familiarity = 1.0 / (1.0 + stat.shownCount)+ val ignoredPenalty = if (stat.watched) 1.0 else weights.unwatchedExplorationDecay+ return weights.explorationUcbWeight * familiarity * ignoredPenalty+}++/** Human-readable "why this was recommended" line. */+fun reasonFor(candidate: Candidate): String = when (candidate.source) {+ RecSource.RELATED -> candidate.sourceLabel?.let { "Because you watched $it" } ?: "Because of your history"+ RecSource.TOP_CHANNEL -> candidate.sourceLabel?.let { "From $it" } ?: "From a channel you watch"+ RecSource.TRENDING -> "Trending"+ RecSource.SUBSCRIPTION -> "From your subscriptions"+ RecSource.SEARCH -> "Matches your interests"+}++/**+ * Scores a single candidate. Relevance terms (author affinity, IDF-weighted and+ * capped keyword overlap, source recency, an exploration base, and an optional+ * per-channel exploration bonus) are summed, then scaled by an additive-floored+ * upload freshness that can be attenuated per-source. */ fun scoreCandidate( candidate: Candidate, profile: InterestProfile, now: Instant, weights: RecommendationWeights = RecommendationWeights(),+ idf: Map<String, Double> = emptyMap(),+ explorationBonus: Double = 0.0,+ freshnessSourceFactors: Map<RecSource, Double> = emptyMap(), ): Double { val v = candidate.video val affinity = profile.authorWeights[v.author.lowercase()] ?: 0.0 val authorScore = minOf(affinity * weights.authorAffinityWeight, weights.authorAffinityCap) - val keywordScore = tokenize(v.name)- .sumOf { profile.keywordWeights[it] ?: 0.0 } * weights.keywordWeight+ val keywordRaw = tokenize(v.name)+ .sumOf { (profile.keywordWeights[it] ?: 0.0) * (idf[it] ?: 1.0) }+ val keywordScore = minOf(keywordRaw * weights.keywordWeight, weights.keywordScoreCap) val sourceRecencyScore = if (candidate.source == RecSource.RELATED && candidate.sourceWatchedAt != null) { val hoursAgo = (now - candidate.sourceWatchedAt).inWholeHours.toDouble()@@ -124,19 +307,22 @@ fun scoreCandidate( } val uploadAgeDays = (now - v.uploadDate).inWholeDays.toDouble().coerceAtLeast(0.0)- val freshness = exp(-weights.uploadFreshnessDecay * uploadAgeDays)+ val decay = weights.uploadFreshnessDecay * (freshnessSourceFactors[candidate.source] ?: 1.0)+ val rawFreshness = exp(-decay * uploadAgeDays)+ val freshness = weights.freshnessFloor + (1 - weights.freshnessFloor) * rawFreshness - return (authorScore + keywordScore + sourceRecencyScore + weights.explorationBase) * freshness+ return (authorScore + keywordScore + sourceRecencyScore + weights.explorationBase + explorationBonus) * freshness } /** * Ranks candidates into the final feed. *- * Steps: dedup by video id keeping the max score across sources; drop videos- * already watched >=90%; demote (not exclude) subscription-authored videos via- * [RecommendationWeights.subscriptionDamping]; then greedily select with MMR to- * balance relevance against diversity, enforcing a per-author cap and a- * subscription-fraction quota on the final feed.+ * Steps: apply hard filters (blocked channels, muted keywords, content filters);+ * dedup by video id keeping the max score across sources; drop videos already+ * watched >=90%; apply per-channel multipliers and subscription damping; suppress+ * recently-shown low-relevance videos; then greedily select with MMR (plus optional+ * refresh noise) to balance relevance against diversity, enforcing a per-author cap+ * and a subscription-fraction soft quota that backfills to a full feed. */ fun rankRecommendations( candidates: List<Candidate>,@@ -144,30 +330,61 @@ fun rankRecommendations( subNames: Set<String>, now: Instant, weights: RecommendationWeights = RecommendationWeights(),-): List<VideoInfo> {+ channelPrefs: Map<String, ChannelPref> = emptyMap(),+ mutedKeywords: Set<String> = emptySet(),+ contentFilters: ContentFilters = ContentFilters(),+ channelStats: Map<String, ChannelImpressionStat> = emptyMap(),+ recentlyShown: Map<Long, Instant> = emptyMap(),+ noise: (VideoInfo) -> Double = { 0.0 },+): List<RankedVideo> { val profile = buildInterestProfile(history, now, weights) val historyById = history.associateBy { it.id } + val eligible = candidates.filter { passesHardFilters(it.video, channelPrefs, mutedKeywords, contentFilters) }+ val idf = computeIdf(eligible.map { it.video }.distinctBy { it.videoID })+ val best = HashMap<Long, Scored>()- for (c in candidates) {+ for (c in eligible) { val v = c.video val h = historyById[v.videoID] if (h != null && v.duration > 0 && h.progress.toDouble() / (v.duration * 1000) >= 0.9) continue - val isSub = v.author.lowercase() in subNames- var score = scoreCandidate(c, profile, now, weights)+ val author = v.author.lowercase()+ val pref = channelPrefs[author]+ val isSub = author in subNames+ val bonus = explorationBonus(author, channelStats, weights)+ var score = scoreCandidate(c, profile, now, weights, idf, bonus) if (isSub) score *= weights.subscriptionDamping+ if (pref != null) score *= pref.multiplier val existing = best[v.videoID] if (existing == null || score > existing.score) {- best[v.videoID] = Scored(v, score, tokenize(v.name).toSet(), isSub)+ best[v.videoID] = Scored(+ video = v,+ score = score,+ tokens = tokenize(v.name).toSet(),+ isSub = isSub,+ pinned = pref?.pinned == true,+ source = c.source,+ reason = reasonFor(c),+ ) } } if (best.isEmpty()) return emptyList() - val pool = best.values.sortedByDescending { it.score }.toMutableList()- val maxScore = pool.first().score.takeIf { it > 0.0 } ?: 1.0+ val maxScore = best.values.maxOf { it.score }.takeIf { it > 0.0 } ?: 1.0++ val pool = best.values.filter { scored ->+ if (scored.pinned) return@filter true+ val shownAt = recentlyShown[scored.video.videoID] ?: return@filter true+ if (weights.recentSuppressionWindowHours <= 0.0) return@filter true+ val hoursAgo = (now - shownAt).inWholeHours.toDouble()+ val relevance = scored.score / maxScore+ !(hoursAgo < weights.recentSuppressionWindowHours && relevance < weights.recentSuppressionRelevanceThreshold)+ }.sortedByDescending { it.score }.toMutableList()++ if (pool.isEmpty()) return emptyList() val resultLimit = minOf(pool.size, weights.maxResults) val subQuota = (weights.maxResults * weights.maxSubscriptionFraction).toInt()@@ -176,33 +393,59 @@ fun rankRecommendations( val authorCount = HashMap<String, Int>() var subCount = 0 - while (selected.size < resultLimit && pool.isNotEmpty()) {- var bestIdx = -1- var bestMmr = Double.NEGATIVE_INFINITY- for (i in pool.indices) {- val cand = pool[i]- val author = cand.video.author.lowercase()- if ((authorCount[author] ?: 0) >= weights.perAuthorCap) continue- if (cand.isSub && subCount >= subQuota) continue-- val maxSim = selected.maxOfOrNull { similarity(cand, it) } ?: 0.0- val relevance = cand.score / maxScore- val mmr = weights.mmrLambda * relevance - (1 - weights.mmrLambda) * maxSim- if (mmr > bestMmr) {- bestMmr = mmr- bestIdx = i+ // First pass respects the subscription soft cap; a second backfill pass drops+ // it so the feed is never shortened just because only sub items remain.+ for (enforceSubQuota in listOf(true, false)) {+ while (selected.size < resultLimit && pool.isNotEmpty()) {+ var bestIdx = -1+ var bestMmr = Double.NEGATIVE_INFINITY+ for (i in pool.indices) {+ val cand = pool[i]+ val author = cand.video.author.lowercase()+ if ((authorCount[author] ?: 0) >= weights.perAuthorCap) continue+ if (enforceSubQuota && cand.isSub && subCount >= subQuota) continue++ val maxSim = selected.maxOfOrNull { similarity(cand, it) } ?: 0.0+ var relevance = cand.score / maxScore + noise(cand.video)+ if (cand.pinned) relevance += PINNED_RELEVANCE_BOOST+ val mmr = weights.mmrLambda * relevance - (1 - weights.mmrLambda) * maxSim+ if (mmr > bestMmr) {+ bestMmr = mmr+ bestIdx = i+ } }- }- if (bestIdx < 0) break+ if (bestIdx < 0) break - val chosen = pool.removeAt(bestIdx)- selected.add(chosen)- val a = chosen.video.author.lowercase()- authorCount[a] = (authorCount[a] ?: 0) + 1- if (chosen.isSub) subCount+++ val chosen = pool.removeAt(bestIdx)+ selected.add(chosen)+ val a = chosen.video.author.lowercase()+ authorCount[a] = (authorCount[a] ?: 0) + 1+ if (chosen.isSub) subCount+++ }+ if (selected.size >= resultLimit) break } - return selected.map { it.video }+ return selected.map { RankedVideo(it.video, it.source, it.reason) }+}++private const val PINNED_RELEVANCE_BOOST = 1_000.0++private fun passesHardFilters(+ v: VideoInfo,+ channelPrefs: Map<String, ChannelPref>,+ mutedKeywords: Set<String>,+ filters: ContentFilters,+): Boolean {+ if (channelPrefs[v.author.lowercase()]?.blocked == true) return false+ if (mutedKeywords.isNotEmpty() && tokenize(v.name).any { it in mutedKeywords }) return false+ val d = v.duration+ if (filters.hideLive && d <= 0) return false+ if (filters.hideShorts && d in 1 until 60) return false+ if (d > 0) {+ if (filters.minDurationSec > 0 && d < filters.minDurationSec) return false+ if (filters.maxDurationSec > 0 && d > filters.maxDurationSec) return false+ }+ return true } private data class Scored(@@ -210,6 +453,9 @@ private data class Scored( val score: Double, val tokens: Set<String>, val isSub: Boolean,+ val pinned: Boolean,+ val source: RecSource,+ val reason: String, ) private fun similarity(a: Scored, b: Scored): Double {
youpipe/src/test/java/com/vayunmathur/youpipe/util/RecommenderTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/RecommenderTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/RecommenderTest.ktindex 595507b1a8..0f92fe52d8 100644--- a/youpipe/src/test/java/com/vayunmathur/youpipe/util/RecommenderTest.kt+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/RecommenderTest.kt@@ -1,12 +1,14 @@ package com.vayunmathur.youpipe.util import com.vayunmathur.youpipe.data.HistoryVideo+import com.vayunmathur.youpipe.data.RecommendationPreferences import com.vayunmathur.youpipe.ui.VideoInfo import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import kotlin.time.Duration.Companion.days+import kotlin.time.Duration.Companion.hours import kotlin.time.Instant class RecommenderTest {@@ -61,6 +63,24 @@ class RecommenderTest { assertEquals(0.5, profile.authorWeights.getValue("imported"), 1e-9) } + @Test+ fun `completion saturation counts partial watch of a long video`() {+ // 20 minutes watched of a 3-hour video: fractional completion is tiny, but+ // absolute watch time saturates, so the author still earns strong affinity.+ val longVideo = video(1, author = "LongForm", duration = 3 * 3600)+ val h = history(longVideo, progress = 20 * 60 * 1000L)++ val plain = buildInterestProfile(listOf(h), now).authorWeights.getValue("longform")+ val saturated = buildInterestProfile(+ listOf(h),+ now,+ RecommendationWeights(watchTimeSaturationMinutes = 15.0),+ ).authorWeights.getValue("longform")++ assertTrue(saturated > plain)+ assertEquals(1.0, saturated, 1e-9)+ }+ // ===================== tokenize ===================== @Test@@ -75,6 +95,34 @@ class RecommenderTest { assertFalse(tokens.contains("to")) } + // ===================== IDF =====================++ @Test+ fun `idf down-weights common tokens`() {+ val videos = listOf(+ video(1, name = "kotlin news"),+ video(2, name = "python news"),+ video(3, name = "rust news"),+ )+ val idf = computeIdf(videos)++ // "news" appears in every document, distinctive tokens appear once.+ assertTrue(idf.getValue("news") < idf.getValue("kotlin"))+ }++ @Test+ fun `idf lowers keyword score of common tokens in scoreCandidate`() {+ val profile = InterestProfile(emptyMap(), mapOf("news" to 1.0, "kotlin" to 1.0))+ val commonCand = Candidate(video(1, name = "news"), RecSource.TRENDING)+ val distinctiveCand = Candidate(video(2, name = "kotlin"), RecSource.TRENDING)+ val idf = mapOf("news" to 0.1, "kotlin" to 2.0)++ val common = scoreCandidate(commonCand, profile, now, idf = idf)+ val distinctive = scoreCandidate(distinctiveCand, profile, now, idf = idf)++ assertTrue(distinctive > common)+ }+ // ===================== scoreCandidate ===================== @Test@@ -101,6 +149,22 @@ class RecommenderTest { assertTrue(scoreCandidate(relevant, profile, now) > scoreCandidate(irrelevant, profile, now)) } + @Test+ fun `keyword score is capped`() {+ val bigProfile = InterestProfile(+ emptyMap(),+ (1..20).associate { "tok$it" to 100.0 },+ )+ val name = (1..20).joinToString(" ") { "tok$it" }+ val cand = Candidate(video(1, name = name), RecSource.TRENDING)+ val weights = RecommendationWeights(keywordScoreCap = 8.0)++ // Freshness is 1.0 at now; exploration base adds 0.5.+ val score = scoreCandidate(cand, bigProfile, now, weights)++ assertTrue(score <= weights.keywordScoreCap + weights.explorationBase + 1e-9)+ }+ @Test fun `freshness decays with upload age`() { val profile = InterestProfile(emptyMap(), emptyMap())@@ -110,6 +174,18 @@ class RecommenderTest { assertTrue(scoreCandidate(fresh, profile, now) > scoreCandidate(stale, profile, now)) } + @Test+ fun `freshness floor keeps an old high-relevance item alive`() {+ val profile = InterestProfile(mapOf("evergreen" to 5.0), emptyMap())+ val oldRelevant = Candidate(video(1, author = "Evergreen", uploadDate = now - 400.days), RecSource.TRENDING)++ val noFloor = scoreCandidate(oldRelevant, profile, now, RecommendationWeights(freshnessFloor = 0.0))+ val withFloor = scoreCandidate(oldRelevant, profile, now, RecommendationWeights(freshnessFloor = 0.5))++ assertTrue(noFloor < 0.5) // nearly zeroed by pure multiplier+ assertTrue(withFloor > noFloor)+ }+ @Test fun `exploration base keeps zero affinity candidates above zero`() { val profile = InterestProfile(emptyMap(), emptyMap())@@ -121,6 +197,28 @@ class RecommenderTest { assertEquals(weights.explorationBase, score, 1e-9) } + // ===================== exploration bonus (UCB) =====================++ @Test+ fun `exploration bonus favors rarely shown channels`() {+ val weights = RecommendationWeights(explorationUcbWeight = 1.0)+ val stats = mapOf(+ "rare" to ChannelImpressionStat(shownCount = 1, watched = false),+ "frequent" to ChannelImpressionStat(shownCount = 50, watched = false),+ )++ val rare = explorationBonus("rare", stats, weights)+ val frequent = explorationBonus("frequent", stats, weights)++ assertTrue(rare > frequent)+ }++ @Test+ fun `exploration bonus is zero when disabled`() {+ val stats = mapOf("x" to ChannelImpressionStat(1, false))+ assertEquals(0.0, explorationBonus("x", stats, RecommendationWeights()), 1e-9)+ }+ // ===================== rankRecommendations ===================== @Test@@ -143,7 +241,7 @@ class RecommenderTest { val ranked = rankRecommendations(candidates, history, emptySet(), now) - assertTrue(ranked.none { it.videoID == 1L })+ assertTrue(ranked.none { it.video.videoID == 1L }) } @Test@@ -159,12 +257,32 @@ class RecommenderTest { now, ) - assertTrue(ranked.any { it.videoID == 1L }) // sub not excluded- assertTrue(ranked.indexOfFirst { it.videoID == 2L } < ranked.indexOfFirst { it.videoID == 1L })+ assertTrue(ranked.any { it.video.videoID == 1L }) // sub not excluded+ assertTrue(ranked.indexOfFirst { it.video.videoID == 2L } < ranked.indexOfFirst { it.video.videoID == 1L })+ }++ @Test+ fun `subscription soft quota is respected when non-subs are available`() {+ val weights = RecommendationWeights(maxResults = 10, maxSubscriptionFraction = 0.3, perAuthorCap = 3)+ val subCandidates = (1L..10L).map {+ Candidate(video(it, author = "Sub$it", uploadDate = now), RecSource.SUBSCRIPTION)+ }+ // Exactly enough non-subs to fill (maxResults - subQuota) slots, so the+ // sub soft cap binds while the feed still fills to maxResults.+ val nonSub = (11L..17L).map {+ Candidate(video(it, author = "Free$it", uploadDate = now), RecSource.TRENDING)+ }+ val subNames = (1L..10L).map { "sub$it" }.toSet()++ val ranked = rankRecommendations(subCandidates + nonSub, emptyList(), subNames, now, weights)++ assertEquals(10, ranked.size)+ val subCount = ranked.count { it.video.author.lowercase().startsWith("sub") }+ assertEquals(3, subCount) // floor(10 * 0.3) } @Test- fun `subscription fraction quota is respected`() {+ fun `subscription quota backfills when only subs remain`() { val weights = RecommendationWeights(maxResults = 10, maxSubscriptionFraction = 0.3, perAuthorCap = 3) val subCandidates = (1L..10L).map { Candidate(video(it, author = "Sub$it", uploadDate = now), RecSource.SUBSCRIPTION)@@ -173,7 +291,8 @@ class RecommenderTest { val ranked = rankRecommendations(subCandidates, emptyList(), subNames, now, weights) - assertEquals(3, ranked.size) // floor(10 * 0.3)+ // Never shorten the feed just because only sub items are eligible.+ assertEquals(10, ranked.size) } @Test@@ -188,6 +307,169 @@ class RecommenderTest { val ranked = rankRecommendations(dominant + others, emptyList(), emptySet(), now, weights) - assertEquals(3, ranked.count { it.author == "Loud" })+ assertEquals(3, ranked.count { it.video.author == "Loud" })+ }++ // ===================== user-control filters =====================++ @Test+ fun `blocked channel is hard filtered`() {+ val candidates = listOf(+ Candidate(video(1, author = "Blocked", uploadDate = now), RecSource.TRENDING),+ Candidate(video(2, author = "Allowed", uploadDate = now), RecSource.TRENDING),+ )+ val prefs = mapOf("blocked" to ChannelPref(blocked = true))++ val ranked = rankRecommendations(candidates, emptyList(), emptySet(), now, channelPrefs = prefs)++ assertTrue(ranked.none { it.video.videoID == 1L })+ assertTrue(ranked.any { it.video.videoID == 2L })+ }++ @Test+ fun `muted keyword is hard filtered`() {+ val candidates = listOf(+ Candidate(video(1, name = "spoiler review", uploadDate = now), RecSource.TRENDING),+ Candidate(video(2, name = "cooking video", uploadDate = now), RecSource.TRENDING),+ )++ val ranked = rankRecommendations(candidates, emptyList(), emptySet(), now, mutedKeywords = setOf("spoiler"))++ assertTrue(ranked.none { it.video.videoID == 1L })+ }++ @Test+ fun `hide shorts content filter drops short videos`() {+ val candidates = listOf(+ Candidate(video(1, author = "A", duration = 30, uploadDate = now), RecSource.TRENDING),+ Candidate(video(2, author = "B", duration = 600, uploadDate = now), RecSource.TRENDING),+ )+ val filters = ContentFilters(hideShorts = true)++ val ranked = rankRecommendations(candidates, emptyList(), emptySet(), now, contentFilters = filters)++ assertTrue(ranked.none { it.video.videoID == 1L })+ assertTrue(ranked.any { it.video.videoID == 2L })+ }++ @Test+ fun `boost and demote multipliers reorder equal candidates`() {+ val candidates = listOf(+ Candidate(video(1, author = "Boosted", uploadDate = now), RecSource.TRENDING),+ Candidate(video(2, author = "Demoted", uploadDate = now), RecSource.TRENDING),+ )+ val prefs = mapOf(+ "boosted" to ChannelPref(multiplier = 5.0),+ "demoted" to ChannelPref(multiplier = 0.1),+ )++ val ranked = rankRecommendations(candidates, emptyList(), emptySet(), now, channelPrefs = prefs)++ assertTrue(ranked.indexOfFirst { it.video.videoID == 1L } < ranked.indexOfFirst { it.video.videoID == 2L })+ }++ @Test+ fun `pinned channel outranks an equally relevant channel`() {+ val candidates = listOf(+ Candidate(video(1, author = "Normal", uploadDate = now), RecSource.TRENDING),+ Candidate(video(2, author = "Pinned", uploadDate = now), RecSource.TRENDING),+ )+ val prefs = mapOf("pinned" to ChannelPref(pinned = true))++ val ranked = rankRecommendations(candidates, emptyList(), emptySet(), now, channelPrefs = prefs)++ assertEquals(2L, ranked.first().video.videoID)+ }++ // ===================== recent-impression suppression =====================++ @Test+ fun `recently shown low relevance videos are suppressed`() {+ val weights = RecommendationWeights(+ recentSuppressionWindowHours = 24.0,+ recentSuppressionRelevanceThreshold = 2.0, // force everything below threshold+ )+ val candidates = listOf(+ Candidate(video(1, author = "A", uploadDate = now), RecSource.TRENDING),+ Candidate(video(2, author = "B", uploadDate = now), RecSource.TRENDING),+ )+ val recentlyShown = mapOf(1L to now - 1.hours)++ val ranked = rankRecommendations(+ candidates, emptyList(), emptySet(), now, weights, recentlyShown = recentlyShown,+ )++ assertTrue(ranked.none { it.video.videoID == 1L })+ assertTrue(ranked.any { it.video.videoID == 2L })+ }++ // ===================== determinism & provenance =====================++ @Test+ fun `ranking is deterministic with zero noise`() {+ val candidates = (1L..10L).map {+ Candidate(video(it, author = "A$it", name = "video $it", uploadDate = now), RecSource.TRENDING)+ }++ val first = rankRecommendations(candidates, emptyList(), emptySet(), now).map { it.video.videoID }+ val second = rankRecommendations(candidates, emptyList(), emptySet(), now).map { it.video.videoID }++ assertEquals(first, second)+ }++ @Test+ fun `reason reflects provenance`() {+ val related = Candidate(video(1, uploadDate = now), RecSource.RELATED, now, sourceLabel = "Cool Video")+ val trending = Candidate(video(2, uploadDate = now), RecSource.TRENDING)+ val topChannel = Candidate(video(3, uploadDate = now), RecSource.TOP_CHANNEL, sourceLabel = "My Channel")++ val ranked = rankRecommendations(listOf(related, trending, topChannel), emptyList(), emptySet(), now)+ val byId = ranked.associateBy { it.video.videoID }++ assertEquals("Because you watched Cool Video", byId.getValue(1L).reason)+ assertEquals("Trending", byId.getValue(2L).reason)+ assertEquals("From My Channel", byId.getValue(3L).reason)+ }++ // ===================== fromPreferences =====================++ @Test+ fun `fromPreferences maps dial extremes`() {+ val discovery = RecommendationWeights.fromPreferences(+ RecommendationPreferences(discoveryFamiliar = 1.0f, freshEvergreen = 0.5f, focusedDiverse = 0.5f),+ )+ val familiar = RecommendationWeights.fromPreferences(+ RecommendationPreferences(discoveryFamiliar = 0.0f, freshEvergreen = 0.5f, focusedDiverse = 0.5f),+ )+ assertTrue(discovery.explorationBase > familiar.explorationBase)+ assertTrue(discovery.maxSubscriptionFraction < familiar.maxSubscriptionFraction)++ val fresh = RecommendationWeights.fromPreferences(+ RecommendationPreferences(freshEvergreen = 1.0f),+ )+ val evergreen = RecommendationWeights.fromPreferences(+ RecommendationPreferences(freshEvergreen = 0.0f),+ )+ assertTrue(fresh.uploadFreshnessDecay > evergreen.uploadFreshnessDecay)+ assertTrue(evergreen.freshnessFloor > fresh.freshnessFloor)++ val diverse = RecommendationWeights.fromPreferences(+ RecommendationPreferences(focusedDiverse = 1.0f),+ )+ val focused = RecommendationWeights.fromPreferences(+ RecommendationPreferences(focusedDiverse = 0.0f),+ )+ assertTrue(focused.mmrLambda > diverse.mmrLambda)+ assertTrue(focused.perAuthorCap > diverse.perAuthorCap)+ }++ // ===================== channelNameMatches =====================++ @Test+ fun `channel name match accepts close names and rejects homonyms`() {+ assertTrue(channelNameMatches("Veritasium", "veritasium"))+ assertTrue(channelNameMatches("Veritasium Official", "Veritasium"))+ assertFalse(channelNameMatches("Some Other Channel", "Veritasium"))+ assertFalse(channelNameMatches("", "Veritasium")) } }