diff --git a/src/library_import/matcher/mod.rs b/src/library_import/matcher/mod.rs index 3823897..e5855bd 100644 --- a/src/library_import/matcher/mod.rs +++ b/src/library_import/matcher/mod.rs @@ -14,5 +14,6 @@ pub use normalize::{ KnownArtists, NameKey, artist_name_variants, folded, parse_title, split_artists, }; pub use score::{ - Candidate, Decision, Origin, PreparedCandidate, PreparedSource, Ranked, Source, decide, + Candidate, Decision, MAX_CANDIDATES, NOT_FOUND, Origin, PreparedCandidate, PreparedSource, + Ranked, Source, decide, }; diff --git a/src/library_import/resolver.rs b/src/library_import/resolver.rs index c41804d..7bd33bc 100644 --- a/src/library_import/resolver.rs +++ b/src/library_import/resolver.rs @@ -20,7 +20,7 @@ use super::matcher::{ Ranked, Source, }; use super::model::{ItemMetadata, PublicationStatus, ResolutionStatus}; -use super::store::{PendingEntry, Resolution}; +use super::store::{AMBIGUOUS_LOCAL, PendingEntry, Resolution}; use crate::federation::client::CatalogStream; mod federated; @@ -109,8 +109,11 @@ pub struct Entry { pub id: i64, raw: Source, source: PreparedSource, - /// Why stages 1–2 found nothing, for an entry waiting for the network. + /// Why stages 1–2 found nothing, for an entry waiting for the network, + /// or [`AMBIGUOUS_LOCAL`]. note: Option, + /// The candidates of stages 1–2 of an entry waiting as ambiguous. + candidates: Option, } /// Entries of one resolver pass, grouped by their main artist. @@ -166,7 +169,12 @@ impl Resolver { for entry in entries { match serde_json::from_value::(entry.metadata) { Ok(metadata) if !metadata.title.trim().is_empty() => { - parsed.push((entry.id, entry.artist_key, entry.note, metadata)); + parsed.push(( + entry.id, + entry.artist_key, + (entry.note, entry.candidates), + metadata, + )); } _ => invalid.push(Resolution::failed(entry.id, "invalid_metadata")), } @@ -233,7 +241,7 @@ impl Resolver { let mut groups: Vec> = Vec::new(); let mut current_key: Option> = None; - for (id, artist_key, note, metadata) in parsed { + for (id, artist_key, (note, candidates), metadata) in parsed { let raw = Source { title: metadata.title, artists: metadata.artists, @@ -255,6 +263,7 @@ impl Resolver { raw, source, note, + candidates, }); } Ok(Prepared { @@ -305,7 +314,8 @@ impl Resolver { /// Decides every entry of a group: the local library first (stage 1), /// then together with the known federated tracks (stage 2). With /// `defer_unmatched` an entry without a match stays pending with its - /// reason for the network stage. + /// reason for the network stage, and an ambiguous one with its candidates + /// (REQ §11: Retry searches the federation for both). pub async fn resolve_group( &self, pool: &PgPool, @@ -392,7 +402,15 @@ impl Resolver { .map(|ranked| candidate_json(ranked, chosen(ranked.index))) .collect(), )), - ..Resolution::new(entry.id, ResolutionStatus::Ambiguous) + note: defer_unmatched.then(|| AMBIGUOUS_LOCAL.to_owned()), + ..Resolution::new( + entry.id, + if defer_unmatched { + ResolutionStatus::Pending + } else { + ResolutionStatus::Ambiguous + }, + ) }, Decision::Unmatched { reason } => Resolution { note: Some(reason.to_owned()), diff --git a/src/library_import/resolver/federated.rs b/src/library_import/resolver/federated.rs index 7484d11..2770081 100644 --- a/src/library_import/resolver/federated.rs +++ b/src/library_import/resolver/federated.rs @@ -22,10 +22,10 @@ use super::{ }; use crate::federation::client::CatalogError; use crate::library_import::matcher::{ - self, Candidate, Decision, NameKey, Origin, PreparedCandidate, PreparedSource, + self, Candidate, Decision, MAX_CANDIDATES, NameKey, Origin, PreparedCandidate, PreparedSource, }; use crate::library_import::model::{PublicationStatus, ResolutionStatus}; -use crate::library_import::store::Resolution; +use crate::library_import::store::{AMBIGUOUS_LOCAL, Resolution}; /// Artist groups searched at once by all imports of this process. static GROUPS: Semaphore = Semaphore::const_new(2); @@ -270,7 +270,13 @@ impl<'a> NetworkSearch<'a> { let resolutions = if found.is_empty() && (failed || timed_out) { group .iter() - .map(|entry| Resolution::failed(entry.id, FEDERATION_ERROR)) + .map(|entry| { + if is_ambiguous(entry) { + still_ambiguous(entry, Vec::new()) + } else { + Resolution::failed(entry.id, FEDERATION_ERROR) + } + }) .collect() } else { self.decide(group, &found) @@ -417,7 +423,11 @@ impl<'a> NetworkSearch<'a> { indexes.iter().map(|index| &tracks[*index]).collect(); let prepared: Vec<&PreparedCandidate> = candidates.iter().map(|track| &track.prepared).collect(); - match matcher::decide(&source, &prepared) { + let decision = matcher::decide(&source, &prepared); + if is_ambiguous(entry) { + return decide_ambiguous(entry, decision, &candidates); + } + match decision { Decision::Matched(ranked) => federated_match( Resolution { score: Some(ranked.score), @@ -451,6 +461,99 @@ impl<'a> NetworkSearch<'a> { } } +fn is_ambiguous(entry: &Entry) -> bool { + entry.note.as_deref() == Some(AMBIGUOUS_LOCAL) +} + +/// An entry stages 1–2 found ambiguous, decided as if its stored candidates +/// and the catalogue tracks were decided together: only Strong and Exact +/// candidates make a match, so the network decides it only when none of the +/// stored candidates is Strong or Exact. Otherwise it stays ambiguous with +/// the catalogue candidates added. +fn decide_ambiguous(entry: &Entry, decision: Decision, found: &[&KnownTrack]) -> Resolution { + let stored_decides = stored_candidates(entry) + .iter() + .any(|candidate| level_rank(candidate) >= STRONG); + let added = match decision { + Decision::Matched(ranked) if !stored_decides => { + return federated_match( + Resolution { + score: Some(ranked.score), + publication: PublicationStatus::Pending, + ..Resolution::new(entry.id, ResolutionStatus::Matched) + }, + found[ranked.index], + ); + } + Decision::Matched(ranked) => vec![ranked], + Decision::Ambiguous(ranked) => ranked, + Decision::Unmatched { .. } => Vec::new(), + }; + still_ambiguous( + entry, + added + .iter() + .map(|ranked| candidate_json(ranked, Chosen::Federated(found[ranked.index]))) + .collect(), + ) +} + +fn stored_candidates(entry: &Entry) -> Vec { + entry + .candidates + .as_ref() + .and_then(Value::as_array) + .cloned() + .unwrap_or_default() +} + +/// Stored candidates and new ones not offered yet, best first. +fn still_ambiguous(entry: &Entry, added: Vec) -> Resolution { + let mut candidates = stored_candidates(entry); + for candidate in added { + let content_id = candidate.get("content_id").and_then(Value::as_str); + let offered = content_id.is_some_and(|content_id| { + candidates + .iter() + .any(|known| known.get("content_id").and_then(Value::as_str) == Some(content_id)) + }); + if !offered { + candidates.push(candidate); + } + } + if candidates.is_empty() { + return Resolution { + note: Some(matcher::NOT_FOUND.to_owned()), + ..Resolution::new(entry.id, ResolutionStatus::Unmatched) + }; + } + let score = |candidate: &Value| candidate.get("score").and_then(Value::as_f64); + candidates.sort_by(|a, b| { + level_rank(b) + .cmp(&level_rank(a)) + .then_with(|| score(b).unwrap_or(0.0).total_cmp(&score(a).unwrap_or(0.0))) + }); + candidates.truncate(MAX_CANDIDATES); + Resolution { + score: candidates.first().and_then(score).map(|score| score as f32), + candidates: Some(Value::Array(candidates)), + ..Resolution::new(entry.id, ResolutionStatus::Ambiguous) + } +} + +/// [`level_rank`] of a Strong candidate. +const STRONG: u8 = 2; + +/// The match level a stored candidate was given. +fn level_rank(candidate: &Value) -> u8 { + match candidate.get("level").and_then(Value::as_str) { + Some("exact") => 3, + Some("strong") => STRONG, + Some("weak") => 1, + _ => 0, + } +} + /// The artist name a group is looked up by: the first credited artist as the /// source spells it. fn group_artist(group: &[Entry]) -> Option { @@ -502,6 +605,7 @@ fn stronger_note<'a>(local: Option<&'a str>, network: &'a str) -> &'a str { #[cfg(test)] mod tests { use music_dht::catalog::{CatalogAppearance, CatalogRelease}; + use serde_json::json; use super::*; @@ -560,6 +664,89 @@ mod tests { assert_eq!(found.names, ["Кино", "Кино"]); } + #[test] + fn ambiguous_entries_take_a_network_match_only_over_weak_candidates() { + let fed = SyncedFedTrack { + item_id: "item-1".into(), + owner: "peer-1".into(), + title: "Группа крови".into(), + artist_names: vec!["Кино".into()], + featured_artist_names: Vec::new(), + year: None, + duration_seconds: Some(285), + content_id: b3('a'), + release_title: Some("Группа крови".into()), + track_number: None, + disc_number: None, + }; + let candidate = Candidate { + origin: Origin::Federation, + title: fed.title.clone(), + artists: fed.artist_names.clone(), + featured_artists: Vec::new(), + album: fed.release_title.clone(), + duration_seconds: Some(285.0), + content_id: Some(fed.content_id.clone()), + owners: 1, + }; + let prepared = PreparedCandidate::new(&candidate, &Default::default()); + let track = KnownTrack { + fed, + candidate, + prepared, + }; + let raw = matcher::Source { + title: "Группа крови".into(), + artists: vec!["Кино".into()], + album: Some("Группа крови".into()), + duration_ms: Some(285_000), + }; + let entry = |stored: Value| Entry { + id: 7, + source: PreparedSource::new(&raw, &Default::default()), + raw: raw.clone(), + note: Some(AMBIGUOUS_LOCAL.into()), + candidates: Some(stored), + }; + let decision = || matcher::decide(&entry(json!([])).source, &[&track.prepared]); + assert!(matches!(decision(), Decision::Matched(_))); + let local = |level: &str, digit: char| json!({"origin": "local", "level": level, "score": 0.6, "content_id": b3(digit), "track_id": 1}); + + // Weak local candidates give way to a network match. + let matched = decide_ambiguous(&entry(json!([local("weak", 'b')])), decision(), &[&track]); + assert_eq!(matched.status, ResolutionStatus::Matched); + assert_eq!(matched.content_id, Some(b3('a'))); + // A strong local candidate of another recording keeps the choice open. + let open = decide_ambiguous( + &entry(json!([local("weak", 'c'), local("strong", 'b')])), + decision(), + &[&track], + ); + assert_eq!(open.status, ResolutionStatus::Ambiguous); + let candidates = open.candidates.unwrap(); + let ids: Vec<&str> = candidates + .as_array() + .unwrap() + .iter() + .map(|candidate| candidate["content_id"].as_str().unwrap()) + .collect(); + assert_eq!(ids.len(), 3); + assert_eq!(ids[2], b3('c'), "best level first"); + assert!(ids.contains(&b3('a').as_str())); + // A candidate already offered is not added twice; nothing found keeps the rest. + let same = decide_ambiguous(&entry(json!([local("strong", 'a')])), decision(), &[&track]); + assert_eq!(same.candidates.unwrap().as_array().unwrap().len(), 1); + let nothing = decide_ambiguous( + &entry(json!([local("weak", 'b')])), + Decision::Unmatched { + reason: "not_found", + }, + &[], + ); + assert_eq!(nothing.status, ResolutionStatus::Ambiguous); + assert_eq!(nothing.candidates.unwrap().as_array().unwrap().len(), 1); + } + #[test] fn only_latin_diacritics_are_folded_for_the_network() { assert_eq!(latin_folded("Beyoncé").as_deref(), Some("beyonce")); diff --git a/src/library_import/store.rs b/src/library_import/store.rs index 7fa1dbb..ac80672 100644 --- a/src/library_import/store.rs +++ b/src/library_import/store.rs @@ -856,18 +856,27 @@ pub struct PendingEntry { pub metadata: Value, /// Set by stages 1–2 on an entry that waits for the network stage. pub note: Option, + /// Local candidates of an entry that waits as ambiguous + /// ([`AMBIGUOUS_LOCAL`]). + pub candidates: Option, } +/// `resolution_note` of a pending entry that stages 1–2 found ambiguous; it +/// waits for the network stage with its candidates. +pub const AMBIGUOUS_LOCAL: &str = "ambiguous_local"; + /// Pending entries of an import, grouped by their main artist. pub async fn pending_entries(pool: &PgPool, import_id: i64) -> sqlx::Result> { let rows = sqlx::query( - "SELECT i.id, i.artist_key, i.metadata, i.resolution_note + "SELECT i.id, i.artist_key, i.metadata, i.resolution_note, + CASE WHEN i.resolution_note = $2 THEN i.candidates END FROM furumusic__library_import_item i JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id WHERE p.import_id = $1 AND i.resolution_status = 'pending' ORDER BY i.artist_key NULLS LAST, i.id", ) .bind(import_id) + .bind(AMBIGUOUS_LOCAL) .fetch_all(pool) .await?; Ok(rows @@ -877,6 +886,7 @@ pub async fn pending_entries(pool: &PgPool, import_id: i64) -> sqlx::Result