From 335cdeea4b612c227daa9ff0e1485e92dc08fb6d Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Wed, 25 Nov 2026 17:08:25 -0700 Subject: [PATCH] Spend less on MusicBrainz and bound the catalog fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A single catalog candidate already decides the album, so the importer no longer waits a second on MusicBrainz for a tie-break it cannot change, and the MBID fallback now stops after the three best-ranked release groups. Generated with Codebuff 🤖 Co-Authored-By: Codebuff --- tests/test_music_mb_resolve.py | 62 ++++++++++++++++++++++++++++++++-- watch/music.py | 60 ++++++++++++++++++++++++-------- 2 files changed, 106 insertions(+), 16 deletions(-) diff --git a/tests/test_music_mb_resolve.py b/tests/test_music_mb_resolve.py index 94a271c..5150e38 100644 --- a/tests/test_music_mb_resolve.py +++ b/tests/test_music_mb_resolve.py @@ -27,14 +27,18 @@ def album_row( def group_row( - mbid: str, title: str, kind: str, tracks: list[str] + mbid: str, + title: str, + kind: str, + tracks: list[str], + secondary: list[str] | None = None, ) -> dict[str, Any]: """Build a MusicBrainz release group as the client returns it.""" return { "foreignAlbumId": mbid, "title": title, "albumType": kind, - "secondaryTypes": [], + "secondaryTypes": secondary or [], "releaseDate": "2013-06-25", "artist": {"artistName": "Avicii"}, "tracks": tracks, @@ -76,6 +80,7 @@ class FakeArr: self.catalog = catalog or {} self.added: list[dict[str, Any]] = [] self.searches: list[list[int]] = [] + self.lookups: list[str] = [] async def __call__(self, path: str, **kwargs: Any) -> Any: # noqa: ANN401 """Serve the handful of routes the importer uses.""" @@ -86,6 +91,7 @@ class FakeArr: return self.lookup if path == "album" and method == "GET": mbid = params.get("foreignAlbumId") + self.lookups.append(str(mbid)) row = self.catalog.get(mbid) if mbid else None return [row] if row else [] if path == "album" and method == "POST": @@ -213,6 +219,58 @@ async def test_a_dead_end_is_resolved_from_the_catalog_by_mbid() -> None: assert album_id == 3 +async def test_one_catalog_candidate_needs_no_musicbrainz() -> None: + """One release group leaves nothing for MusicBrainz to tie-break.""" + arr = FakeArr([album_row(1, "True", "Album", "rg-true")]) + brainz = FakeBrainz([]) + engine = await engine_with(arr, brainz) + + album_id, reason = await engine._album( + {"artist_checks": {}}, + {"title": "True", "artist": "Avicii"}, + ) + + assert reason == "" + assert album_id == 1 + assert brainz.asked == [] + + +async def test_the_catalog_fallback_stops_after_the_ranked_cap() -> None: + """Never query the catalog once per MusicBrainz group.""" + arr = FakeArr([]) + brainz = FakeBrainz( + [ + group_row("rg-single", "Levels", "Single", ["Levels"]), + group_row("rg-ep", "Levels", "EP", ["Levels"]), + group_row("rg-album", "Levels", "Album", ["Levels"]), + group_row( + "rg-comp", + "Levels", + "Album", + ["Levels"], + ["Compilation"], + ), + group_row( + "rg-live", + "Levels", + "Album", + ["Levels"], + ["Live"], + ), + ] + ) + engine = await engine_with(arr, brainz) + + album_id, reason = await engine._album( + {"artist_checks": {}}, + {"title": "Levels", "artist": "Avicii"}, + ) + + assert album_id is None + assert reason == "No unique artist/album match" + assert arr.lookups == ["rg-album", "rg-comp", "rg-live"] + + async def test_an_unreachable_musicbrainz_keeps_the_old_answer() -> None: """A MusicBrainz outage must not fail the import.""" arr = FakeArr([]) diff --git a/watch/music.py b/watch/music.py index 48555d3..6f45060 100644 --- a/watch/music.py +++ b/watch/music.py @@ -106,6 +106,39 @@ def release_rank(album: dict[str, Any]) -> tuple[int, int]: return (order, derivative) +# The catalog fallback costs one lookup per candidate, so it stops after the +# few best-ranked release groups. More than that is a catalogue problem, not a +# missing album, and the requester reviews it instead. +MAX_RELEASE_GROUP_LOOKUPS = 3 + + +def matching_albums( + source: dict[str, str], candidates: list[dict[str, Any]] +) -> list[dict[str, Any]]: + """Keep the release groups titled for this track by its artist.""" + return [ + a + for a in candidates + if appears_on(source["artist"], a) + and album_title(a["title"]) == album_title(source["title"]) + ] + + +def sole_album( + source: dict[str, str], candidates: list[dict[str, Any]] +) -> dict[str, Any] | None: + """Return the only release group the catalog offers, if any. + + One candidate leaves nothing to tie-break, so the caller can skip the + MusicBrainz lookup entirely and save its one-second spacing. + """ + unique = { + a["foreignAlbumId"]: a + for a in matching_albums(source, candidates) + } + return next(iter(unique.values())) if len(unique) == 1 else None + + def choose_album( source: dict[str, str], candidates: list[dict[str, Any]], @@ -119,12 +152,7 @@ def choose_album( edition. A tie between equally good candidates stays ambiguous so the requester chooses. """ - matches = [ - a - for a in candidates - if appears_on(source["artist"], a) - and album_title(a["title"]) == album_title(source["title"]) - ] + matches = matching_albums(source, candidates) if holding: # A release group MusicBrainz says holds the track beats # one that only outranks it on type. @@ -257,7 +285,9 @@ class MusicImporter: self, groups: list[dict[str, Any]] ) -> dict[str, Any] | None: """Find the release group MusicBrainz named in the catalog.""" - for group in sorted(groups, key=release_rank): + for group in sorted(groups, key=release_rank)[ + :MAX_RELEASE_GROUP_LOOKUPS + ]: found = await self.arr( "album", params={ @@ -280,13 +310,15 @@ class MusicImporter: candidates = await self.arr( "album/lookup", params={"term": source["title"]} ) - groups = await self._groups( - source["artist"], track_title or source["title"] - ) - holding = {g["foreignAlbumId"] for g in groups} - match = choose_album(source, candidates or [], holding) - if match is None and groups: - match = await self._catalog_album(groups) + match = sole_album(source, candidates or []) + if match is None: + groups = await self._groups( + source["artist"], track_title or source["title"] + ) + holding = {g["foreignAlbumId"] for g in groups} + match = choose_album(source, candidates or [], holding) + if match is None and groups: + match = await self._catalog_album(groups) if match is not None: return await self._ensure_album(job, match), "" if not await self._artist_known(job, source["artist"]):