Search peer catalogues for ambiguous import entries too

REQ §11 repeats the search in the library and the federation for both
unmatched and ambiguous entries, but only unmatched ones waited for the
network stage, so an entry with a weak local candidate (a remaster, a
compilation) never asked a peer, not even on Retry. With the user's
consent an ambiguous entry now waits too, with its candidates. A peer's
match decides it only when no stored candidate is Strong or Exact, as
deciding over both would; otherwise the catalogue candidates are added.
When the search fails, the node is off or the budget is used up, the
entry is ambiguous again with its candidates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-26 19:51:57 +02:00
1 parent 64cb868b54
commit e7d970c60d
5 files changed
+324 -15

No files matched your search

+2 -1
View File
@@ -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,
};
+24 -6
View File
@@ -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<String>,
/// The candidates of stages 1–2 of an entry waiting as ambiguous.
candidates: Option<Value>,
}
/// 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::<ItemMetadata>(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<Entry>> = Vec::new();
let mut current_key: Option<Option<String>> = 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()),
+191 -4
View File
@@ -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<Value> {
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<Value>) -> 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<String> {
@@ -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"));
+18 -4
View File
@@ -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<String>,
/// Local candidates of an entry that waits as ambiguous
/// ([`AMBIGUOUS_LOCAL`]).
pub candidates: Option<Value>,
}
/// `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<Vec<PendingEntry>> {
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<Vec<
artist_key: row.get(1),
metadata: row.get(2),
note: row.get(3),
candidates: row.get(4),
})
.collect())
}
@@ -995,7 +1005,8 @@ pub async fn store_resolutions(
/// Ends the wait of entries that stages 1–2 left pending for the network
/// stage: they become unmatched with `note`, or keep their own reason without
/// one. `false` when the worker no longer owns the import.
/// one, and ambiguous ones are ambiguous again with their stored candidates.
/// `false` when the worker no longer owns the import.
pub async fn finish_deferred(
pool: &PgPool,
import_id: i64,
@@ -1016,8 +1027,10 @@ pub async fn finish_deferred(
}
sqlx::query(
"UPDATE furumusic__library_import_item i
SET resolution_status = 'unmatched',
resolution_note = COALESCE($2, i.resolution_note),
SET resolution_status = CASE WHEN i.resolution_note = $3 THEN 'ambiguous'
ELSE 'unmatched' END,
resolution_note = CASE WHEN i.resolution_note = $3 THEN NULL
ELSE COALESCE($2, i.resolution_note) END,
publication_status = 'not_ready', last_attempt_at = now()
FROM furumusic__library_import_playlist p
WHERE p.id = i.import_playlist_id AND p.import_id = $1
@@ -1025,6 +1038,7 @@ pub async fn finish_deferred(
)
.bind(import_id)
.bind(note)
.bind(AMBIGUOUS_LOCAL)
.execute(&mut *tx)
.await?;
refresh_statistics(&mut tx, import_id).await?;
+89
View File
@@ -2370,6 +2370,95 @@ async fn library_import_network_search_needs_consent_a_running_node_and_budget()
fixture.drop().await;
}
/// REQ §11: ambiguous entries are searched in the federation too, on the
/// first pass and on Retry. A peer's better match decides them; otherwise
/// they stay ambiguous with the local candidates.
#[tokio::test]
#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"]
async fn library_import_searches_peers_for_ambiguous_entries() {
let _serial = SERIAL.lock().await;
let fixture = Fixture::new().await;
let pool = &fixture.pool;
seed_library(pool).await;
// The library has only the original; the remaster is a weak candidate.
let tracks = [timed(
0,
"Bohemian Rhapsody - Remastered 2011",
"Queen",
Some("A Night At The Opera (2011 Remaster)"),
Some(355),
)];
let remaster = catalog(
"Queen",
&[(
"A Night At The Opera (2011 Remaster)",
&[("Bohemian Rhapsody - Remastered 2011", '7', Some(355.0))],
)],
);
let local_only = |items: &[ItemRow]| {
assert_eq!(items[0].0, "ambiguous", "{items:?}");
assert_eq!(items[0].1, None);
assert_eq!(items[0].6, Some(1), "the local candidate is kept");
assert_eq!(items[0].7, "not_ready");
};
// No peer offers it: the local candidate stays to choose from.
let import_id = create_with_consent(pool, "ambiguous", &tracks, true).await;
let network = Arc::new(FakeNetwork::new());
let output = run_with(pool, 731, network.clone()).await;
assert!(
output.contains("1 entries locally (0 matched, 0 ambiguous, 0 unmatched, 0 failed, 1 left for the network)"),
"{output}"
);
assert!(
output.contains("1 entries: 0 matched, 1 ambiguous"),
"{output}"
);
assert_eq!(network.searches(), ["Queen"]);
local_only(&resolved_items(pool, import_id).await);
// A failing search, a stopped node or a used up budget give the local
// candidates back.
let failing = create_with_consent(pool, "failing", &tracks, true).await;
let mut network = FakeNetwork::new();
network.failing.insert(NameKey::new("Queen").key);
run_with(pool, 733, Arc::new(network)).await;
local_only(&resolved_items(pool, failing).await);
let stopped = create_with_consent(pool, "stopped", &tracks, true).await;
let mut network = FakeNetwork::new();
network.running = false;
run_with(pool, 734, Arc::new(network)).await;
local_only(&resolved_items(pool, stopped).await);
let budget = create_with_consent(pool, "budget", &tracks, true).await;
let mut network = FakeNetwork::new().peer("Queen", vec![remaster.clone()]);
network.limits.max_groups = 0;
run_with(pool, 735, Arc::new(network)).await;
local_only(&resolved_items(pool, budget).await);
// Retry asks the federation again, and a peer has the remaster. Once
// published it is a known federated track for later imports.
assert_eq!(
store::request_resync(pool, 1, import_id, None)
.await
.unwrap(),
ResyncOutcome::Queued
);
let network = Arc::new(FakeNetwork::new().peer("Queen", vec![remaster]));
run_with(pool, 732, network.clone()).await;
assert_eq!(network.searches(), ["Queen"]);
let items = resolved_items(pool, import_id).await;
assert_eq!(
(
items[0].0.as_str(),
items[0].2.as_deref(),
items[0].3.clone()
),
("matched", Some("federation"), Some(b3('7')))
);
assert_eq!(items[0].7, "published");
fixture.drop().await;
}
#[tokio::test]
#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"]
async fn library_import_cancel_stops_a_running_network_search() {