Match imported entries against the local library and known federated tracks

Add the matcher and the first two resolver stages of the library import.
The matcher is pure: titles are split into a core, featured artists and
version tags, taken from the album title too, so a remaster or concert
album counts like a marker in the track title. Hard tags (live, remix,
edit and similar) must be equal; remaster, mono, stereo, explicit and
clean never match automatically. A match without a comparable duration
needs the same album, and a single candidate is not a match by itself.
Collaborations are split only into known artists, so "Tyler, The Creator"
stays one artist.

The resolve_local phase matches pending entries by artist group against
the library, then against federated tracks this server already knows from
searches and from the owner's synced likes and playlists, and stores
matched, ambiguous (with up to five candidates) or unmatched decisions
under the lease. A local match without a cached content id is hashed with
ensure_local_content_id from agent_storage_dir, so local imports are
publishable with federation disabled. The network is reached only through
a FederationAccess trait and only with the user's consent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-26 16:55:27 +02:00
1 parent ff87d9110d
commit 0a258a3e05
12 files changed
+3134 -17

No files matched your search

+146
View File
@@ -775,6 +775,152 @@ pub async fn resume_after_reauth(
Ok(outcome)
}
// ---------------------------------------------------------------------------
// Worker: resolution
// ---------------------------------------------------------------------------
/// An entry waiting for the resolver.
#[derive(Debug, Clone)]
pub struct PendingEntry {
pub id: i64,
pub artist_key: Option<String>,
pub metadata: Value,
}
/// 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
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)
.fetch_all(pool)
.await?;
Ok(rows
.into_iter()
.map(|row| PendingEntry {
id: row.get(0),
artist_key: row.get(1),
metadata: row.get(2),
})
.collect())
}
/// The resolver's decision for one entry.
#[derive(Debug, Clone, PartialEq)]
pub struct Resolution {
pub item_id: i64,
pub status: ResolutionStatus,
pub note: Option<String>,
/// `local` or `federation` for a match.
pub origin: Option<&'static str>,
pub score: Option<f32>,
pub content_id: Option<String>,
pub track_id: Option<i64>,
/// `SyncedFedTrack` of a federated match.
pub fed: Option<Value>,
pub candidates: Option<Value>,
pub publication: PublicationStatus,
}
impl Resolution {
/// A decision without a match and without a note.
pub fn new(item_id: i64, status: ResolutionStatus) -> Self {
Self {
item_id,
status,
note: None,
origin: None,
score: None,
content_id: None,
track_id: None,
fed: None,
candidates: None,
publication: PublicationStatus::NotReady,
}
}
/// An entry that could not be processed; Resync tries it again.
pub fn failed(item_id: i64, note: &str) -> Self {
Self {
note: Some(note.to_owned()),
..Self::new(item_id, ResolutionStatus::Failed)
}
}
}
/// Stores decisions for pending entries in one transaction and refreshes the
/// counters. Entries that are no longer pending keep their state. `false`
/// when the worker no longer owns the import.
pub async fn store_resolutions(
pool: &PgPool,
import_id: i64,
run_id: i64,
resolutions: &[Resolution],
) -> sqlx::Result<bool> {
let mut tx = pool.begin().await?;
let owned: Option<i64> = sqlx::query_scalar(
"SELECT id FROM furumusic__library_import
WHERE id = $1 AND lease_owner = $2 AND status = 'running' FOR SHARE",
)
.bind(import_id)
.bind(run_id)
.fetch_optional(&mut *tx)
.await?;
if owned.is_none() {
return Ok(false);
}
for chunk in resolutions.chunks(INSERT_CHUNK) {
let ids: Vec<i64> = chunk.iter().map(|r| r.item_id).collect();
let statuses: Vec<&str> = chunk.iter().map(|r| r.status.as_str()).collect();
let notes: Vec<Option<&str>> = chunk.iter().map(|r| r.note.as_deref()).collect();
let origins: Vec<Option<&str>> = chunk.iter().map(|r| r.origin).collect();
let scores: Vec<Option<f32>> = chunk.iter().map(|r| r.score).collect();
let content_ids: Vec<Option<&str>> =
chunk.iter().map(|r| r.content_id.as_deref()).collect();
let track_ids: Vec<Option<i64>> = chunk.iter().map(|r| r.track_id).collect();
let fed: Vec<Option<&Value>> = chunk.iter().map(|r| r.fed.as_ref()).collect();
let candidates: Vec<Option<&Value>> = chunk.iter().map(|r| r.candidates.as_ref()).collect();
let publication: Vec<&str> = chunk.iter().map(|r| r.publication.as_str()).collect();
sqlx::query(
"UPDATE furumusic__library_import_item i
SET resolution_status = r.status, resolution_note = r.note,
match_origin = r.origin,
match_method = CASE WHEN r.status = 'matched' THEN 'auto' END,
match_score = r.score, matched_content_id = r.content_id,
matched_track_id = r.track_id, matched_fed = r.fed,
candidates = r.candidates, publication_status = r.publication,
last_attempt_at = now(), attempt_count = i.attempt_count + 1
FROM UNNEST($2::int8[], $3::text[], $4::text[], $5::text[], $6::float4[],
$7::text[], $8::int8[], $9::jsonb[], $10::jsonb[], $11::text[])
AS r(id, status, note, origin, score, content_id, track_id, fed,
candidates, publication),
furumusic__library_import_playlist p
WHERE i.id = r.id AND p.id = i.import_playlist_id AND p.import_id = $1
AND i.resolution_status = 'pending'",
)
.bind(import_id)
.bind(&ids)
.bind(&statuses)
.bind(&notes)
.bind(&origins)
.bind(&scores)
.bind(&content_ids)
.bind(&track_ids)
.bind(&fed)
.bind(&candidates)
.bind(&publication)
.execute(&mut *tx)
.await?;
}
refresh_statistics(&mut tx, import_id).await?;
tx.commit().await?;
Ok(true)
}
// ---------------------------------------------------------------------------
// Owner requests
// ---------------------------------------------------------------------------