prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  mbsync: Deal with albums that have multiple copies of the same recording
  the current way mbsync plugin used to obtain track mapping list is to use the MusicBrainz recoding ID from each track, it's a workaround to handle "missing or extra tracks". This method is based on an assumption that for each MB release, there are no multiple tracks with same MB recording ID. It usually works, and in my case, only 4 out of 700+ albums disobey this assumption. But for this four albums, I have to fix them by tag track number by hand and re-import.
  
  Considering it's called "mbsync", Why not make an assumption that track number in metadata is not corrupt and use it if possible, or fallback to MB recording ID way if it's corrupted(missing or extra track detected)
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `beetsplug/mbsync.py`
  Content:
  ```
  1 # This file is part of beets.
  2 # Copyright 2014, Jakob Schnitzer.
  3 #
  4 # Permission is hereby granted, free of charge, to any person obtaining
  5 # a copy of this software and associated documentation files (the
  6 # "Software"), to deal in the Software without restriction, including
  7 # without limitation the rights to use, copy, modify, merge, publish,
  8 # distribute, sublicense, and/or sell copies of the Software, and to
  9 # permit persons to whom the Software is furnished to do so, subject to
  10 # the following conditions:
  11 #
  12 # The above copyright notice and this permission notice shall be
  13 # included in all copies or substantial portions of the Software.
  14 
  15 """Update library's tags using MusicBrainz.
  16 """
  17 import logging
  18 
  19 from beets.plugins import BeetsPlugin
  20 from beets import autotag, library, ui, util
  21 from beets.autotag import hooks
  22 from beets import config
  23 
  24 log = logging.getLogger('beets')
  25 
  26 
  27 def mbsync_singletons(lib, query, move, pretend, write):
  28     """Retrieve and apply info from the autotagger for items matched by
  29     query.
  30     """
  31     for item in lib.items(query + ['singleton:true']):
  32         if not item.mb_trackid:
  33             log.info(u'Skipping singleton {0}: has no mb_trackid'
  34                      .format(item.title))
  35             continue
  36 
  37         # Get the MusicBrainz recording info.
  38         track_info = hooks.track_for_mbid(item.mb_trackid)
  39         if not track_info:
  40             log.info(u'Recording ID not found: {0}'.format(item.mb_trackid))
  41             continue
  42 
  43         # Apply.
  44         with lib.transaction():
  45             autotag.apply_item_metadata(item, track_info)
  46             apply_item_changes(lib, item, move, pretend, write)
  47 
  48 
  49 def mbsync_albums(lib, query, move, pretend, write):
  50     """Retrieve and apply info from the autotagger for albums matched by
  51     query and their items.
  52     """
  53     # Process matching albums.
  54     for a in lib.albums(query):
  55         if not a.mb_albumid:
  56             log.info(u'Skipping album {0}: has no mb_albumid'.format(a.id))
  57             continue
  58 
  59         items = list(a.items())
  60 
  61         # Get the MusicBrainz album information.
  62         album_info = hooks.album_for_mbid(a.mb_albumid)
  63         if not album_info:
  64             log.info(u'Release ID not found: {0}'.format(a.mb_albumid))
  65             continue
  66 
  67         # Construct a track mapping according to MBIDs. This should work
  68         # for albums that have missing or extra tracks.
  69         mapping = {}
  70         for item in items:
  71             for track_info in album_info.tracks:
  72                 if item.mb_trackid == track_info.track_id:
  73                     mapping[item] = track_info
  74                     break
  75 
  76         # Apply.
  77         with lib.transaction():
  78             autotag.apply_metadata(album_info, mapping)
  79             changed = False
  80             for item in items:
  81                 item_changed = ui.show_model_changes(item)
  82                 changed |= item_changed
  83                 if item_changed:
  84                     apply_item_changes(lib, item, move, pretend, write)
  85 
  86             if not changed:
  87                 # No change to any item.
  88                 continue
  89 
  90             if not pretend:
  91                 # Update album structure to reflect an item in it.
  92                 for key in library.Album.item_keys:
  93                     a[key] = items[0][key]
  94                 a.store()
  95 
  96                 # Move album art (and any inconsistent items).
  97                 if move and lib.directory in util.ancestry(items[0].path):
  98                     log.debug(u'moving album {0}'.format(a.id))
  99                     a.move()
  100 
  101 
  102 def apply_item_changes(lib, item, move, pretend, write):
  103     """Store, move and write the item according to the arguments.
  104     """
  105     if not pretend:
  106         # Move the item if it's in the library.
  107         if move and lib.directory in util.ancestry(item.path):
  108             item.move(with_album=False)
  109 
  110         if write:
  111             item.try_write()
  112         item.store()
  113 
  114 
  115 def mbsync_func(lib, opts, args):
  116     """Command handler for the mbsync function.
  117     """
  118     move = opts.move
  119     pretend = opts.pretend
  120     write = opts.write
  121     query = ui.decargs(args)
  122 
  123     mbsync_singletons(lib, query, move, pretend, write)
  124     mbsync_albums(lib, query, move, pretend, write)
  125 
  126 
  127 class MBSyncPlugin(BeetsPlugin):
  128     def __init__(self):
  129         super(MBSyncPlugin, self).__init__()
  130 
  131     def commands(self):
  132         cmd = ui.Subcommand('mbsync',
  133                             help='update metadata from musicbrainz')
  134         cmd.parser.add_option('-p', '--pretend', action='store_true',
  135                               help='show all changes but do nothing')
  136         cmd.parser.add_option('-M', '--nomove', action='store_false',
  137                               default=True, dest='move',
  138                               help="don't move files in library")
  139         cmd.parser.add_option('-W', '--nowrite', action='store_false',
  140                               default=config['import']['write'], dest='write',
  141                               help="don't write updated metadata to files")
  142         cmd.func = mbsync_func
  143         return [cmd]
  144
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py
  --- a/beetsplug/mbsync.py
  +++ b/beetsplug/mbsync.py
  @@ -64,13 +64,29 @@
               log.info(u'Release ID not found: {0}'.format(a.mb_albumid))
               continue
   
  +        # Construct an hash mapping recording MBIDs to their information. A
  +        # release can have recording MBIDs that appear multiple times in the
  +        # same release.
  +        track_index = {}
  +        for track_info in album_info.tracks:
  +            if track_info.track_id in track_index:
  +                track_index[track_info.track_id].append(track_info)
  +            else:
  +                track_index[track_info.track_id] = [track_info]
  +
           # Construct a track mapping according to MBIDs. This should work
  -        # for albums that have missing or extra tracks.
  +        # for albums that have missing or extra tracks. If a mapping is
  +        # ambiguous, the items' disc and track number need to match in order
  +        # for an item to be mapped.
           mapping = {}
           for item in items:
  -            for track_info in album_info.tracks:
  -                if item.mb_trackid == track_info.track_id:
  -                    mapping[item] = track_info
  +            candidates = track_index.get(item.mb_trackid, [])
  +            if len(candidates) == 1:
  +                mapping[item] = candidates[0]
  +                continue
  +            for c in candidates:
  +                if c.medium_index == item.track and c.medium == item.disc:
  +                    mapping[item] = c
                       break
   
           # Apply.
  
verification_info: {"golden_diff": "diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py\n--- a/beetsplug/mbsync.py\n+++ b/beetsplug/mbsync.py\n@@ -64,13 +64,29 @@\n             log.info(u'Release ID not found: {0}'.format(a.mb_albumid))\n             continue\n \n+        # Construct an hash mapping recording MBIDs to their information. A\n+        # release can have recording MBIDs that appear multiple times in the\n+        # same release.\n+        track_index = {}\n+        for track_info in album_info.tracks:\n+            if track_info.track_id in track_index:\n+                track_index[track_info.track_id].append(track_info)\n+            else:\n+                track_index[track_info.track_id] = [track_info]\n+\n         # Construct a track mapping according to MBIDs. This should work\n-        # for albums that have missing or extra tracks.\n+        # for albums that have missing or extra tracks. If a mapping is\n+        # ambiguous, the items' disc and track number need to match in order\n+        # for an item to be mapped.\n         mapping = {}\n         for item in items:\n-            for track_info in album_info.tracks:\n-                if item.mb_trackid == track_info.track_id:\n-                    mapping[item] = track_info\n+            candidates = track_index.get(item.mb_trackid, [])\n+            if len(candidates) == 1:\n+                mapping[item] = candidates[0]\n+                continue\n+            for c in candidates:\n+                if c.medium_index == item.track and c.medium == item.disc:\n+                    mapping[item] = c\n                     break\n \n         # Apply.\n", "issue": "mbsync: Deal with albums that have multiple copies of the same recording\nthe current way mbsync plugin used to obtain track mapping list is to use the MusicBrainz recoding ID from each track, it's a workaround to handle \"missing or extra tracks\". This method is based on an assumption that for each MB release, there are no multiple tracks with same MB recording ID. It usually works, and in my case, only 4 out of 700+ albums disobey this assumption. But for this four albums, I have to fix them by tag track number by hand and re-import.\n\nConsidering it's called \"mbsync\", Why not make an assumption that track number in metadata is not corrupt and use it if possible, or fallback to MB recording ID way if it's corrupted(missing or extra track detected)\n\n", "before_files": [{"content": "# This file is part of beets.\n# Copyright 2014, Jakob Schnitzer.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n\"\"\"Update library's tags using MusicBrainz.\n\"\"\"\nimport logging\n\nfrom beets.plugins import BeetsPlugin\nfrom beets import autotag, library, ui, util\nfrom beets.autotag import hooks\nfrom beets import config\n\nlog = logging.getLogger('beets')\n\n\ndef mbsync_singletons(lib, query, move, pretend, write):\n    \"\"\"Retrieve and apply info from the autotagger for items matched by\n    query.\n    \"\"\"\n    for item in lib.items(query + ['singleton:true']):\n        if not item.mb_trackid:\n            log.info(u'Skipping singleton {0}: has no mb_trackid'\n                     .format(item.title))\n            continue\n\n        # Get the MusicBrainz recording info.\n        track_info = hooks.track_for_mbid(item.mb_trackid)\n        if not track_info:\n            log.info(u'Recording ID not found: {0}'.format(item.mb_trackid))\n            continue\n\n        # Apply.\n        with lib.transaction():\n            autotag.apply_item_metadata(item, track_info)\n            apply_item_changes(lib, item, move, pretend, write)\n\n\ndef mbsync_albums(lib, query, move, pretend, write):\n    \"\"\"Retrieve and apply info from the autotagger for albums matched by\n    query and their items.\n    \"\"\"\n    # Process matching albums.\n    for a in lib.albums(query):\n        if not a.mb_albumid:\n            log.info(u'Skipping album {0}: has no mb_albumid'.format(a.id))\n            continue\n\n        items = list(a.items())\n\n        # Get the MusicBrainz album information.\n        album_info = hooks.album_for_mbid(a.mb_albumid)\n        if not album_info:\n            log.info(u'Release ID not found: {0}'.format(a.mb_albumid))\n            continue\n\n        # Construct a track mapping according to MBIDs. This should work\n        # for albums that have missing or extra tracks.\n        mapping = {}\n        for item in items:\n            for track_info in album_info.tracks:\n                if item.mb_trackid == track_info.track_id:\n                    mapping[item] = track_info\n                    break\n\n        # Apply.\n        with lib.transaction():\n            autotag.apply_metadata(album_info, mapping)\n            changed = False\n            for item in items:\n                item_changed = ui.show_model_changes(item)\n                changed |= item_changed\n                if item_changed:\n                    apply_item_changes(lib, item, move, pretend, write)\n\n            if not changed:\n                # No change to any item.\n                continue\n\n            if not pretend:\n                # Update album structure to reflect an item in it.\n                for key in library.Album.item_keys:\n                    a[key] = items[0][key]\n                a.store()\n\n                # Move album art (and any inconsistent items).\n                if move and lib.directory in util.ancestry(items[0].path):\n                    log.debug(u'moving album {0}'.format(a.id))\n                    a.move()\n\n\ndef apply_item_changes(lib, item, move, pretend, write):\n    \"\"\"Store, move and write the item according to the arguments.\n    \"\"\"\n    if not pretend:\n        # Move the item if it's in the library.\n        if move and lib.directory in util.ancestry(item.path):\n            item.move(with_album=False)\n\n        if write:\n            item.try_write()\n        item.store()\n\n\ndef mbsync_func(lib, opts, args):\n    \"\"\"Command handler for the mbsync function.\n    \"\"\"\n    move = opts.move\n    pretend = opts.pretend\n    write = opts.write\n    query = ui.decargs(args)\n\n    mbsync_singletons(lib, query, move, pretend, write)\n    mbsync_albums(lib, query, move, pretend, write)\n\n\nclass MBSyncPlugin(BeetsPlugin):\n    def __init__(self):\n        super(MBSyncPlugin, self).__init__()\n\n    def commands(self):\n        cmd = ui.Subcommand('mbsync',\n                            help='update metadata from musicbrainz')\n        cmd.parser.add_option('-p', '--pretend', action='store_true',\n                              help='show all changes but do nothing')\n        cmd.parser.add_option('-M', '--nomove', action='store_false',\n                              default=True, dest='move',\n                              help=\"don't move files in library\")\n        cmd.parser.add_option('-W', '--nowrite', action='store_false',\n                              default=config['import']['write'], dest='write',\n                              help=\"don't write updated metadata to files\")\n        cmd.func = mbsync_func\n        return [cmd]\n", "path": "beetsplug/mbsync.py"}], "after_files": [{"content": "# This file is part of beets.\n# Copyright 2014, Jakob Schnitzer.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n\"\"\"Update library's tags using MusicBrainz.\n\"\"\"\nimport logging\n\nfrom beets.plugins import BeetsPlugin\nfrom beets import autotag, library, ui, util\nfrom beets.autotag import hooks\nfrom beets import config\n\nlog = logging.getLogger('beets')\n\n\ndef mbsync_singletons(lib, query, move, pretend, write):\n    \"\"\"Retrieve and apply info from the autotagger for items matched by\n    query.\n    \"\"\"\n    for item in lib.items(query + ['singleton:true']):\n        if not item.mb_trackid:\n            log.info(u'Skipping singleton {0}: has no mb_trackid'\n                     .format(item.title))\n            continue\n\n        # Get the MusicBrainz recording info.\n        track_info = hooks.track_for_mbid(item.mb_trackid)\n        if not track_info:\n            log.info(u'Recording ID not found: {0}'.format(item.mb_trackid))\n            continue\n\n        # Apply.\n        with lib.transaction():\n            autotag.apply_item_metadata(item, track_info)\n            apply_item_changes(lib, item, move, pretend, write)\n\n\ndef mbsync_albums(lib, query, move, pretend, write):\n    \"\"\"Retrieve and apply info from the autotagger for albums matched by\n    query and their items.\n    \"\"\"\n    # Process matching albums.\n    for a in lib.albums(query):\n        if not a.mb_albumid:\n            log.info(u'Skipping album {0}: has no mb_albumid'.format(a.id))\n            continue\n\n        items = list(a.items())\n\n        # Get the MusicBrainz album information.\n        album_info = hooks.album_for_mbid(a.mb_albumid)\n        if not album_info:\n            log.info(u'Release ID not found: {0}'.format(a.mb_albumid))\n            continue\n\n        # Construct an hash mapping recording MBIDs to their information. A\n        # release can have recording MBIDs that appear multiple times in the\n        # same release.\n        track_index = {}\n        for track_info in album_info.tracks:\n            if track_info.track_id in track_index:\n                track_index[track_info.track_id].append(track_info)\n            else:\n                track_index[track_info.track_id] = [track_info]\n\n        # Construct a track mapping according to MBIDs. This should work\n        # for albums that have missing or extra tracks. If a mapping is\n        # ambiguous, the items' disc and track number need to match in order\n        # for an item to be mapped.\n        mapping = {}\n        for item in items:\n            candidates = track_index.get(item.mb_trackid, [])\n            if len(candidates) == 1:\n                mapping[item] = candidates[0]\n                continue\n            for c in candidates:\n                if c.medium_index == item.track and c.medium == item.disc:\n                    mapping[item] = c\n                    break\n\n        # Apply.\n        with lib.transaction():\n            autotag.apply_metadata(album_info, mapping)\n            changed = False\n            for item in items:\n                item_changed = ui.show_model_changes(item)\n                changed |= item_changed\n                if item_changed:\n                    apply_item_changes(lib, item, move, pretend, write)\n\n            if not changed:\n                # No change to any item.\n                continue\n\n            if not pretend:\n                # Update album structure to reflect an item in it.\n                for key in library.Album.item_keys:\n                    a[key] = items[0][key]\n                a.store()\n\n                # Move album art (and any inconsistent items).\n                if move and lib.directory in util.ancestry(items[0].path):\n                    log.debug(u'moving album {0}'.format(a.id))\n                    a.move()\n\n\ndef apply_item_changes(lib, item, move, pretend, write):\n    \"\"\"Store, move and write the item according to the arguments.\n    \"\"\"\n    if not pretend:\n        # Move the item if it's in the library.\n        if move and lib.directory in util.ancestry(item.path):\n            item.move(with_album=False)\n\n        if write:\n            item.try_write()\n        item.store()\n\n\ndef mbsync_func(lib, opts, args):\n    \"\"\"Command handler for the mbsync function.\n    \"\"\"\n    move = opts.move\n    pretend = opts.pretend\n    write = opts.write\n    query = ui.decargs(args)\n\n    mbsync_singletons(lib, query, move, pretend, write)\n    mbsync_albums(lib, query, move, pretend, write)\n\n\nclass MBSyncPlugin(BeetsPlugin):\n    def __init__(self):\n        super(MBSyncPlugin, self).__init__()\n\n    def commands(self):\n        cmd = ui.Subcommand('mbsync',\n                            help='update metadata from musicbrainz')\n        cmd.parser.add_option('-p', '--pretend', action='store_true',\n                              help='show all changes but do nothing')\n        cmd.parser.add_option('-M', '--nomove', action='store_false',\n                              default=True, dest='move',\n                              help=\"don't move files in library\")\n        cmd.parser.add_option('-W', '--nowrite', action='store_false',\n                              default=config['import']['write'], dest='write',\n                              help=\"don't write updated metadata to files\")\n        cmd.func = mbsync_func\n        return [cmd]\n", "path": "beetsplug/mbsync.py"}]}