feat(reco): common/recent split + round-robin + 48h results cache + toast

Owner-directed polish on the Recommendations tab to make it richer + faster +
non-repetitive.

- Common vs Recent split: the single "Recommended Artists" row over-represented a
  recent soundtrack binge (a live preview showed "The Newton Brothers" flooding
  the row with 8 film composers while the core metal was buried). Split into two
  rows seeded from DIFFERENT periods: "More like the artists you love" (overall
  top) and "Based on what you've been into lately" (1-month top) — so recent
  one-offs never pollute the core taste. = 7 rows now.
- Round-robin per seed inside each artist row (re-added from the v1 engine; the
  rework had dropped it) + per-seed cap, so no single seed floods the carousel.
- Results cache (48h TTL): caches the FULL built rows (serialized
  ExternalCarousels) per-user, keyed by connected sources. Tab open within 48h =
  INSTANT paint from cache, zero fetch; stale/missing = build + store. Rebuilds
  every 48h (fresh rotation) so it's never "eternally the same" and opens stop
  being slow. Distinct from the rec->Qobuz resolution cache (30d/7d).
- Toast on a real fetch (cache miss/stale): "Generating recommendations…" so the
  wait is communicated; the skeleton stays; no toast on a cache hit.

cargo check -p qbz green (6m44s).

cc
This commit is contained in:
vicrodh committed 2026-06-27 09:13:05 -06:00
1 parent 0347e333a8
commit c6b4906a6b
8 files changed
+266 -70

No files matched your search

+36 -1
View File
@@ -14,6 +14,10 @@ use std::time::{SystemTime, UNIX_EPOCH};
const FOUND_TTL_SECS: i64 = 30 * 24 * 60 * 60;
/// TTL for negative (not-on-Qobuz) entries — 7 days.
const MISS_TTL_SECS: i64 = 7 * 24 * 60 * 60;
/// TTL for the cached BUILT result rows — 48 hours (fast opens + rotation: the
/// tab paints instantly from cache within the window, and rebuilds every 48h so
/// the content is never "eternally the same").
const RESULTS_TTL_SECS: i64 = 48 * 60 * 60;
/// A cache lookup outcome.
pub enum CacheLookup {
@@ -47,7 +51,12 @@ impl RecoCache {
fetched_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_reco_qobuz_cache_fetched
ON reco_qobuz_cache(fetched_at);",
ON reco_qobuz_cache(fetched_at);
CREATE TABLE IF NOT EXISTS reco_results (
key TEXT PRIMARY KEY,
data TEXT NOT NULL,
built_at INTEGER NOT NULL
);",
)
.map_err(|e| format!("Failed to init reco cache schema: {}", e))?;
Ok(Self { conn })
@@ -101,6 +110,32 @@ impl RecoCache {
);
}
/// Get the cached BUILT result rows (JSON of `ExternalCarousels`) for `key`,
/// IF still within the 48h TTL. `None` -> the caller must rebuild.
pub fn get_results(&self, key: &str) -> Option<String> {
let row: Option<(String, i64)> = self
.conn
.query_row(
"SELECT data, built_at FROM reco_results WHERE key = ?",
params![key],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.unwrap_or(None);
match row {
Some((data, built_at)) if Self::now() - built_at <= RESULTS_TTL_SECS => Some(data),
_ => None,
}
}
/// Store the built result rows (JSON) for `key`, stamped now.
pub fn put_results(&self, key: &str, data: &str) {
let _ = self.conn.execute(
"INSERT OR REPLACE INTO reco_results (key, data, built_at) VALUES (?, ?, ?)",
params![key, data, Self::now()],
);
}
/// Drop expired rows (both regimes). Safe to call opportunistically.
pub fn cleanup_expired(&self) -> usize {
let now = Self::now();
+70 -35
View File
@@ -4,7 +4,7 @@
//! arazzo workflow): top artists -> artist.getSimilar -> top albums. There is no
//! recommendation endpoint, so recommendations are replicated from similarity.
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::sync::Mutex;
use futures_util::stream::{self, StreamExt};
@@ -144,15 +144,44 @@ pub async fn gather_history(inputs: &RecoInputs<'_>) -> ExtHistory {
}
}
// ── Recommended Artists (Last.fm similar of recent top, not heard) ──────────
// ── Recommended Artists — common (overall top) vs recent (1-month top) ──────
//
// Split so a recent one-off binge (e.g. a soundtrack) can't pollute the core
// taste row, and so the user gets more, better-targeted rows. Round-robin per
// seed inside each row so no single seed floods the carousel.
pub async fn build_rec_artists(inputs: &RecoInputs<'_>, history: &ExtHistory) -> Vec<ArtistReco> {
const PER_SEED_CAP: usize = 8;
/// Interleave per-seed candidate lists round-robin (fair representation).
fn round_robin<T>(groups: Vec<Vec<T>>) -> Vec<T> {
let mut iters: Vec<std::vec::IntoIter<T>> = groups.into_iter().map(|g| g.into_iter()).collect();
let mut out = Vec::new();
loop {
let mut any = false;
for it in iters.iter_mut() {
if let Some(x) = it.next() {
out.push(x);
any = true;
}
}
if !any {
break;
}
}
out
}
async fn similar_artist_row(
inputs: &RecoInputs<'_>,
history: &ExtHistory,
period: &str,
) -> Vec<ArtistReco> {
let Some(lf) = &inputs.lastfm else {
return Vec::new();
};
let seeds: Vec<String> = lf
.client
.get_top_artists(&lf.username, "1month", 12)
.get_top_artists(&lf.username, period, 12)
.await
.unwrap_or_default()
.into_iter()
@@ -177,48 +206,54 @@ pub async fn build_rec_artists(inputs: &RecoInputs<'_>, history: &ExtHistory) ->
.collect()
.await;
// Aggregate candidate -> the seeds that surfaced it (for the subtitle).
let mut agg: HashMap<String, (String, Vec<String>, f32)> = HashMap::new();
// One candidate list per seed, deduped globally (first seed wins), capped so
// one seed cannot dominate; then round-robin interleaved.
let mut seen_global: HashSet<String> = HashSet::new();
let mut groups: Vec<Vec<ArtistCandidate>> = Vec::new();
for (seed, sims) in sim_results {
let mut list: Vec<ArtistCandidate> = Vec::new();
for s in sims {
let nk = normalize(&s.name);
if nk.is_empty() || history.artist_names.contains(&nk) || seeds_norm.contains(&nk) {
if nk.is_empty()
|| history.artist_names.contains(&nk)
|| seeds_norm.contains(&nk)
|| !seen_global.insert(nk)
{
continue;
}
let e = agg.entry(nk).or_insert((s.name.clone(), Vec::new(), 0.0));
if !e.1.contains(&seed) {
e.1.push(seed.clone());
}
e.2 = e.2.max(s.match_score as f32);
}
}
let mut candidates: Vec<ArtistCandidate> = agg
.into_values()
.map(|(name, seeds, score)| {
let subtitle = if seeds.is_empty() {
String::new()
} else {
format!(
"Similar to {}",
seeds.iter().take(2).cloned().collect::<Vec<_>>().join(", ")
)
};
ArtistCandidate {
name,
list.push(ArtistCandidate {
name: s.name,
source: RecoSource::LastFm,
score,
subtitle,
score: s.match_score as f32,
subtitle: format!("Similar to {}", seed),
});
if list.len() >= PER_SEED_CAP {
break;
}
})
.collect();
candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
candidates.truncate(45);
}
groups.push(list);
}
let candidates: Vec<ArtistCandidate> = round_robin(groups).into_iter().take(45).collect();
let pool = validate_artist_pool(inputs.catalog, inputs.cache, candidates).await;
rotate_take(pool, inputs.rotation_seed, DISPLAY_CAP)
}
/// "More like the artists you love" — your COMMON taste (overall top).
pub async fn build_rec_artists_common(
inputs: &RecoInputs<'_>,
history: &ExtHistory,
) -> Vec<ArtistReco> {
similar_artist_row(inputs, history, "overall").await
}
/// "Based on what you've been into lately" — your RECENT taste (1-month top).
pub async fn build_rec_artists_recent(
inputs: &RecoInputs<'_>,
history: &ExtHistory,
) -> Vec<ArtistReco> {
similar_artist_row(inputs, history, "1month").await
}
// ── Recommended Albums (Last.fm: your artists' top albums, not scrobbled) ───
pub async fn build_rec_albums(inputs: &RecoInputs<'_>, history: &ExtHistory) -> Vec<AlbumReco> {
+24 -5
View File
@@ -87,8 +87,17 @@ pub async fn gather_history(inputs: &RecoInputs<'_>) -> ExtHistory {
// ── Per-row builders (progressive: the frontend paints each as it resolves) ──
pub async fn build_rec_artists(inputs: &RecoInputs<'_>, history: &ExtHistory) -> Vec<ArtistReco> {
carousels::build_rec_artists(inputs, history).await
pub async fn build_rec_artists_common(
inputs: &RecoInputs<'_>,
history: &ExtHistory,
) -> Vec<ArtistReco> {
carousels::build_rec_artists_common(inputs, history).await
}
pub async fn build_rec_artists_recent(
inputs: &RecoInputs<'_>,
history: &ExtHistory,
) -> Vec<ArtistReco> {
carousels::build_rec_artists_recent(inputs, history).await
}
pub async fn build_rec_albums(inputs: &RecoInputs<'_>, history: &ExtHistory) -> Vec<AlbumReco> {
carousels::build_rec_albums(inputs, history).await
@@ -122,8 +131,17 @@ pub async fn build_external_carousels(inputs: RecoInputs<'_>) -> ExternalCarouse
};
}
let history = gather_history(&inputs).await;
let (rec_artists, rec_albums, fresh_releases, weekly_exploration, weekly_jams, deep_cut_albums) = tokio::join!(
build_rec_artists(&inputs, &history),
let (
rec_artists_common,
rec_artists_recent,
rec_albums,
fresh_releases,
weekly_exploration,
weekly_jams,
deep_cut_albums,
) = tokio::join!(
build_rec_artists_common(&inputs, &history),
build_rec_artists_recent(&inputs, &history),
build_rec_albums(&inputs, &history),
build_fresh_releases(&inputs),
build_weekly_exploration(&inputs),
@@ -132,7 +150,8 @@ pub async fn build_external_carousels(inputs: RecoInputs<'_>) -> ExternalCarouse
);
ExternalCarousels {
editorial_fallback: false,
rec_artists,
rec_artists_common,
rec_artists_recent,
rec_albums,
fresh_releases,
weekly_exploration,
+5 -3
View File
@@ -98,12 +98,14 @@ pub struct TrackReco {
///
/// Empty vecs self-hide their row in the view, so partial population is always
/// safe — the controller paints each row independently as it resolves.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ExternalCarousels {
/// No connected external source -> editorial fallback regime.
pub editorial_fallback: bool,
/// Recommended artists (Last.fm similar, not heard).
pub rec_artists: Vec<ArtistReco>,
/// Recommended artists from your COMMON taste (overall top -> similar, not heard).
pub rec_artists_common: Vec<ArtistReco>,
/// Recommended artists from your RECENT taste (1-month top -> similar, not heard).
pub rec_artists_recent: Vec<ArtistReco>,
/// Recommended albums (Last.fm artist top-albums, not scrobbled).
pub rec_albums: Vec<AlbumReco>,
/// Fresh releases (ListenBrainz, from artists you follow).
@@ -21,7 +21,8 @@ export component ExternalRecoView inherits VerticalLayout {
callback play-track(string);
property <bool> any-content:
ExternalRecoState.rec-artists.length > 0
ExternalRecoState.rec-artists-common.length > 0
|| ExternalRecoState.rec-artists-recent.length > 0
|| ExternalRecoState.rec-albums.albums.length > 0
|| ExternalRecoState.fresh-releases.albums.length > 0
|| ExternalRecoState.weekly-exploration.length > 0
@@ -35,10 +36,22 @@ export component ExternalRecoView inherits VerticalLayout {
if ExternalRecoState.loading && !root.any-content: HomeSkeleton { }
// Recommended Artists (Last.fm similar, not heard) — with "Similar to…".
if ExternalRecoState.rec-artists.length > 0: ArtistCarousel {
title: @tr("Recommended Artists");
artists: ExternalRecoState.rec-artists;
// More like the artists you love (COMMON taste — overall top).
if ExternalRecoState.rec-artists-common.length > 0: ArtistCarousel {
title: @tr("More like the artists you love");
artists: ExternalRecoState.rec-artists-common;
artist-clicked(id) => {
root.open-artist(id);
}
media-action(kind, id, action) => {
root.media-action(kind, id, action);
}
}
// Based on what you've been into lately (RECENT taste — 1-month top).
if ExternalRecoState.rec-artists-recent.length > 0: ArtistCarousel {
title: @tr("Based on what you've been into lately");
artists: ExternalRecoState.rec-artists-recent;
artist-clicked(id) => {
root.open-artist(id);
}
+4 -2
View File
@@ -338,8 +338,10 @@ export global ExternalRecoState {
// True when no external source is connected: the editorial fallback
// (top-albums + top-artists) shows instead of the personalized rows.
in property <bool> editorial-fallback: false;
// Recommended artists (Last.fm similar, not heard). subtitle = "Similar to…".
in property <[SlimItem]> rec-artists: [];
// Recommended artists from your COMMON taste (overall top -> similar).
in property <[SlimItem]> rec-artists-common: [];
// Recommended artists from your RECENT taste (1-month top -> similar).
in property <[SlimItem]> rec-artists-recent: [];
// Recommended albums (Last.fm artist top-albums, not scrobbled).
in property <DiscoverSection> rec-albums;
// Fresh releases (ListenBrainz, from artists you follow).
+11 -3
View File
@@ -164,7 +164,8 @@ pub enum ArtworkTarget {
/// A card in ForYouState.rediscover.albums[index].
ForYouRediscover { index: usize },
/// 4th-tab "Recommendations" rows (external-reco engine).
ExtRecoRecArtist { index: usize },
ExtRecoRecArtistCommon { index: usize },
ExtRecoRecArtistRecent { index: usize },
ExtRecoTopArtist { index: usize },
ExtRecoRecAlbum { index: usize },
ExtRecoFreshAlbum { index: usize },
@@ -1293,8 +1294,15 @@ fn apply_artwork(
model.set_row_data(index, item);
}
}
ArtworkTarget::ExtRecoRecArtist { index } => {
let model = window.global::<crate::ExternalRecoState>().get_rec_artists();
ArtworkTarget::ExtRecoRecArtistCommon { index } => {
let model = window.global::<crate::ExternalRecoState>().get_rec_artists_common();
if let Some(mut item) = model.row_data(index) {
item.artwork = image;
model.set_row_data(index, item);
}
}
ArtworkTarget::ExtRecoRecArtistRecent { index } => {
let model = window.global::<crate::ExternalRecoState>().get_rec_artists_recent();
if let Some(mut item) = model.row_data(index) {
item.artwork = image;
model.set_row_data(index, item);
+98 -16
View File
@@ -17,9 +17,9 @@ use async_trait::async_trait;
use qbz_app::shell::AppRuntime;
use qbz_external_reco::{
build_deep_cut_albums, build_editorial, build_fresh_releases, build_rec_albums,
build_rec_artists, build_weekly_exploration, build_weekly_jams, gather_history, is_cold_start,
AlbumReco, ArtistReco, LastFmHandle, ListenBrainzHandle, LocalHistory, RecoCache, RecoCatalog,
RecoInputs, TrackReco,
build_rec_artists_common, build_rec_artists_recent, build_weekly_exploration, build_weekly_jams,
gather_history, is_cold_start, AlbumReco, ArtistReco, ExternalCarousels, LastFmHandle,
ListenBrainzHandle, LocalHistory, RecoCache, RecoCatalog, RecoInputs, TrackReco,
};
use qbz_integrations::{LastFmClient, ListenBrainzClient, MusicBrainzClient};
use qbz_models::{Album, Artist, Track};
@@ -193,53 +193,133 @@ fn spawn(
rotation_seed: rotation_seed(),
};
let source_key = format!(
"results:lf={}:lb={}",
inputs.lastfm.is_some(),
inputs.listenbrainz.is_some()
);
// 1. Results cache: paint INSTANTLY if a fresh (<48h) build is cached.
if let Some(cache_mutex) = inputs.cache {
let cached = cache_mutex.lock().ok().and_then(|g| g.get_results(&source_key));
if let Some(json) = cached {
if let Ok(result) = serde_json::from_str::<ExternalCarousels>(&json) {
apply_all(&weak, &image_cache, result);
latch_loaded(&weak);
return;
}
}
}
// 2. Cache miss / stale: tell the user we're working, then build.
crate::toast::info_weak(&weak, qbz_i18n::t("Generating recommendations…"));
let collector: Arc<Mutex<ExternalCarousels>> = Arc::new(Mutex::new(ExternalCarousels::default()));
if is_cold_start(&inputs) {
let (albums, artists) = build_editorial(&inputs).await;
if let Ok(mut g) = collector.lock() {
g.editorial_fallback = true;
g.top_albums = albums.clone();
g.top_artists = artists.clone();
}
apply_albums(&weak, &image_cache, albums, AlbumRow::TopAlbums);
apply_artists(&weak, &image_cache, artists, ArtistRow::TopArtists);
} else {
let history = gather_history(&inputs).await;
// Progressive: each branch paints its row the moment it resolves.
let b_artists = async {
let r = build_rec_artists(&inputs, &history).await;
apply_artists(&weak, &image_cache, r, ArtistRow::RecArtists);
let col = &collector;
// Progressive: each branch paints its row AND collects it for the cache.
let b_common = async {
let r = build_rec_artists_common(&inputs, &history).await;
if let Ok(mut g) = col.lock() {
g.rec_artists_common = r.clone();
}
apply_artists(&weak, &image_cache, r, ArtistRow::RecArtistsCommon);
};
let b_recent = async {
let r = build_rec_artists_recent(&inputs, &history).await;
if let Ok(mut g) = col.lock() {
g.rec_artists_recent = r.clone();
}
apply_artists(&weak, &image_cache, r, ArtistRow::RecArtistsRecent);
};
let b_albums = async {
let r = build_rec_albums(&inputs, &history).await;
if let Ok(mut g) = col.lock() {
g.rec_albums = r.clone();
}
apply_albums(&weak, &image_cache, r, AlbumRow::RecAlbums);
};
let b_fresh = async {
let r = build_fresh_releases(&inputs).await;
if let Ok(mut g) = col.lock() {
g.fresh_releases = r.clone();
}
apply_albums(&weak, &image_cache, r, AlbumRow::FreshReleases);
};
let b_explore = async {
let r = build_weekly_exploration(&inputs).await;
if let Ok(mut g) = col.lock() {
g.weekly_exploration = r.clone();
}
apply_tracks(&weak, &image_cache, r, TrackRow::WeeklyExploration);
};
let b_jams = async {
let r = build_weekly_jams(&inputs).await;
if let Ok(mut g) = col.lock() {
g.weekly_jams = r.clone();
}
apply_tracks(&weak, &image_cache, r, TrackRow::WeeklyJams);
};
let b_deep = async {
let r = build_deep_cut_albums(&inputs).await;
if let Ok(mut g) = col.lock() {
g.deep_cut_albums = r.clone();
}
apply_albums(&weak, &image_cache, r, AlbumRow::DeepCuts);
};
tokio::join!(b_artists, b_albums, b_fresh, b_explore, b_jams, b_deep);
tokio::join!(b_common, b_recent, b_albums, b_fresh, b_explore, b_jams, b_deep);
}
let _ = weak.upgrade_in_event_loop(|w| {
let s = w.global::<ExternalRecoState>();
s.set_loading(false);
s.set_loaded(true);
});
// 3. Store the built result for instant future opens (48h TTL).
if let Some(cache_mutex) = inputs.cache {
let json = collector.lock().ok().and_then(|g| serde_json::to_string(&*g).ok());
if let (Ok(guard), Some(json)) = (cache_mutex.lock(), json) {
guard.put_results(&source_key, &json);
}
}
latch_loaded(&weak);
});
}
fn latch_loaded(weak: &slint::Weak<AppWindow>) {
let _ = weak.upgrade_in_event_loop(|w| {
let s = w.global::<ExternalRecoState>();
s.set_loading(false);
s.set_loaded(true);
});
}
/// Paint every row from a cached result (empty rows self-hide).
fn apply_all(weak: &slint::Weak<AppWindow>, cache: &ImageCache, r: ExternalCarousels) {
apply_artists(weak, cache, r.rec_artists_common, ArtistRow::RecArtistsCommon);
apply_artists(weak, cache, r.rec_artists_recent, ArtistRow::RecArtistsRecent);
apply_albums(weak, cache, r.rec_albums, AlbumRow::RecAlbums);
apply_albums(weak, cache, r.fresh_releases, AlbumRow::FreshReleases);
apply_tracks(weak, cache, r.weekly_exploration, TrackRow::WeeklyExploration);
apply_tracks(weak, cache, r.weekly_jams, TrackRow::WeeklyJams);
apply_albums(weak, cache, r.deep_cut_albums, AlbumRow::DeepCuts);
apply_albums(weak, cache, r.top_albums, AlbumRow::TopAlbums);
apply_artists(weak, cache, r.top_artists, ArtistRow::TopArtists);
}
// ── Per-row apply (models built on the UI thread; slint::Image is !Send) ────
#[derive(Clone, Copy)]
enum ArtistRow {
RecArtists,
RecArtistsCommon,
RecArtistsRecent,
TopArtists,
}
#[derive(Clone, Copy)]
@@ -308,7 +388,8 @@ fn apply_artists(
.map(|(i, a)| ArtworkJob {
url: a.image_url.clone(),
target: match which {
ArtistRow::RecArtists => ArtworkTarget::ExtRecoRecArtist { index: i },
ArtistRow::RecArtistsCommon => ArtworkTarget::ExtRecoRecArtistCommon { index: i },
ArtistRow::RecArtistsRecent => ArtworkTarget::ExtRecoRecArtistRecent { index: i },
ArtistRow::TopArtists => ArtworkTarget::ExtRecoTopArtist { index: i },
},
})
@@ -320,7 +401,8 @@ fn apply_artists(
));
let s = w.global::<ExternalRecoState>();
match which {
ArtistRow::RecArtists => s.set_rec_artists(model),
ArtistRow::RecArtistsCommon => s.set_rec_artists_common(model),
ArtistRow::RecArtistsRecent => s.set_rec_artists_recent(model),
ArtistRow::TopArtists => s.set_top_artists(model),
}
});