Šarūnas Nejus 2cf20aa60c discogs: refactor _coalesce_tracks around more specific track types (#6818)
- `beetsplug/discogs/types.py` now models Discogs tracklist entries as
distinct shapes: `AudioTrack`, `IndexTrack`, and `HeadingTrack`. This
shifts the plugin from "guessing by `position`" to handling each entry
by its declared `type_`.

- `beetsplug/discogs/__init__.py` refactors `_coalesce_tracks()` into
smaller helpers for flat subtracks and index tracks. The normalization
flow is now type-driven, which makes the rules for "one physical track"
vs "many physical tracks" more explicit.

- `beetsplug/discogs/states.py` now advances track state only for real
audio entries (`type_ == "track"`), so structural entries no longer
affect track counting through indirect `position` checks.

- Tests now use dedicated Discogs track factories and add coverage for
logical index tracks. This gives the refactor a clearer test model and
protects the new coalescing behavior.

- High-level impact: Discogs imports should now treat headings, index
containers, and subtracks more consistently, especially for releases
where one displayed work contains multiple logical parts but maps to a
single playable track.

### This change is based on the following research (thanks, Codex!):

# Discogs track coalescing

`DiscogsPlugin._coalesce_tracks()` handles three distinct notions all
called
"subtracks." This is the main source of its complexity.

Discogs distinguishes:

- `track`: an audio entry.
- `index`: a titled container whose `sub_tracks` are parts or movements.
- `heading`: descriptive text applying to following tracks.

That distinction is documented in the current
[Discogs tracklisting
guidelines](https://support.discogs.com/hc/en-us/articles/360005055373-Database-Guidelines-12-Tracklisting).
Positions such as `3.1`, `3.2` or `3a`, `3b` separately indicate
multiple
musical pieces inside one physical track.

## Observed input shapes

| Case | API shape | Current result | Example |
|---|---|---|---|
| Normal track | `type_="track"`, nonempty position | Passed through |
Most releases |
| Flat virtual subtracks | Multiple top-level `track` entries with
`1.1`, `1.2` or `22a`, `22b` | Merged into a copy of the first track |
[This Is Not](https://www.discogs.com/release/7117597), [Eclectic Beatz
8](https://www.discogs.com/release/2885582) |
| Nested logical subtracks | `index` with nested children sharing one
physical position | Parent index becomes the physical track; children
discarded | [Defqon.1 Weekend
Festival](https://www.discogs.com/release/7168134) |
| Nested physical subtracks | `index` with children numbered as
independent tracks | Index discarded; children promoted | [Classical
Hollywood III](https://www.discogs.com/release/3647530) |
| Heading | `heading`, empty position, no `sub_tracks` | Passed through
as structural metadata | Defqon.1 CD headings |
| Ambiguous/nonstandard index | `index` with positions the regex cannot
classify | Usually promoted incorrectly as separate tracks | [King
Crimson - Lizard](https://www.discogs.com/release/1156598) |

### Flat virtual subtracks

`This Is Not` returns nine top-level entries:

```python
{"type_": "track", "position": "1.1", "title": "Intro", "duration": "1:49"}
{"type_": "track", "position": "1.2", "title": "Untitled", "duration": "6:31"}
# ...
{"type_": "track", "position": "1.9", "title": "2 Bad ...", "duration": "10:18"}
```

There is no index container. `_coalesce_tracks()` detects the suffixes
and
`_add_merged_subtracks()` produces:

```python
{
    "type_": "track",
    "position": "1.1",
    "title": "Intro / Untitled / ... / 2 Bad ...",
    "duration": "1:49",
    "artists": ["Unknown Artist"],
}
```

It copies all metadata from the first entry and only combines titles.
This
explains the incorrect duration and artist.

`Eclectic Beatz 8` has the same flat shape:

```python
{"type_": "track", "position": "22a", "title": "Amplifier", "artists": ["Fedde Le Grand"]}
{"type_": "track", "position": "22b", "title": "Autograph ...", "artists": ["Hatiras", "MC Flipside"]}
```

Those become one track, retaining only the first artist.

### Nested logical subtracks

Defqon.1 contains:

```python
{
    "type_": "index",
    "position": "",
    "title": "Eat This / God! What The Hell!",
    "duration": "3:06",
    "sub_tracks": [
        {"type_": "track", "position": "2-20A", "title": "Eat This"},
        {"type_": "track", "position": "2-20B", "title": "God! What The Hell!"},
    ],
}
```

Because `2-20A` has a parsed subindex, the helper changes the parent to:

```python
{
    "type_": "index",
    "position": "2-20",
    "title": "Eat This / God! What The Hell!",
    "duration": "3:06",
}
```

The children disappear. Downstream code treats this as audio solely
because
its position is now nonempty. It never checks that `type_` remains
`"index"`.

### Nested physical subtracks

`Classical Hollywood III` contains index containers such as:

```python
{
    "type_": "index",
    "position": "",
    "title": "Auld Lang Syne Variations For Piano Quartet",
    "sub_tracks": [
        {"type_": "track", "position": "1", "title": "Eine Kleine Nichtmusik ..."},
        {"type_": "track", "position": "2", "title": "L.V.B. - Adagio"},
        {"type_": "track", "position": "3", "title": "Chaconne ..."},
        {"type_": "track", "position": "4", "title": "Homage ..."},
    ],
}
```

Because position `1` has no subindex:

- the index container is removed;
- its children become top-level physical tracks;
- parent artists are copied to children missing artists;
- when `index_tracks` is enabled, the parent title prefixes every child
title.

This behavior was added for
[issue #2318](https://github.com/beetbox/beets/issues/2318) by
[PR #2355](https://github.com/beetbox/beets/pull/2355).

### Headings

Defqon.1 also contains:

```python
{
    "type_": "heading",
    "position": "",
    "title": "CD2  Mixed By Partyraiser",
    "duration": "",
}
```

This is not coalesced. It passes through, but `TracklistState`
subsequently
treats every positionless object as structural metadata without checking
`type_`.

The code therefore cannot distinguish:

```python
position == "" and type_ == "heading"
position == "" and type_ == "index"
```

Worse, `_add_merged_subtracks()` identifies a parent using only:

```python
tracklist and not tracklist[-1]["position"]
```

A heading can therefore theoretically be mistaken for an index parent.

## History

- [Issue #1543](https://github.com/beetbox/beets/issues/1543) reported
flat
  positions such as `22a` and `22b` representing one CD track.
- [PR #2222](https://github.com/beetbox/beets/pull/2222) added both flat
and
nested subtrack support. Its author explicitly noted that `type_` might
  identify index tracks robustly, but avoided the larger refactor.
- [Issue #2318](https://github.com/beetbox/beets/issues/2318)
demonstrated that
  nested `sub_tracks` can instead be independent physical tracks.
- PR #2355 added the current heuristic:
  - parsed child subindex means logical fragments of one physical track;
  - no parsed child subindex means independent physical tracks.
- That PR documented the heuristic as imperfect. `Lizard`, with `Ba`,
`Bb`,
  `Bc`, and related positions, was already a known failure.

## Test data does not match the API shapes

The current test helper always creates:

```python
"type_": "track"
```

Consequently, test inputs such as:

```python
_track("TRACK GROUP TITLE", sub_tracks=[...])
```

are not realistic. Real API data uses:

```python
"type_": "index"
```

Likewise, test medium titles are manufactured as positionless `track`
objects
rather than `heading` or `index` objects.

## Recommended direction

Before refactoring production code, introduce accurate input types and
factories:

```python
TrackEntry = AudioTrack | IndexTrack | HeadingTrack
```

With approximate shapes:

```python
class AudioTrack(TypedDict):
    type_: Literal["track"]
    position: str
    title: str
    duration: str
    artists: NotRequired[list[Artist]]


class IndexTrack(TypedDict):
    type_: Literal["index"]
    position: Literal[""]
    title: str
    duration: str
    sub_tracks: list[AudioTrack]
    artists: NotRequired[list[Artist]]


class HeadingTrack(TypedDict):
    type_: Literal["heading"]
    position: Literal[""]
    title: str
    duration: str
```

Then test using `_track()`, `_index()`, and `_heading()` factories.

The eventual normalization can dispatch structurally:

1. `track` without subindex: pass through.
2. Flat subindexed `track` group: apply the flat-fragment policy.
3. `index`: normalize its children as logical or physical.
4. `heading`: preserve as structural metadata.
5. Never infer an index merely from `position == ""`.

This removes the most dangerous ambiguity while preserving the
positional
heuristic where Discogs genuinely requires it.
2026-07-16 12:02:00 +01:00
2026-06-30 12:44:21 +01:00
2025-08-10 16:25:04 +01:00
2023-09-22 15:29:39 -04:00
2026-03-06 11:28:29 +00:00
2026-06-30 12:44:24 +01:00
2015-12-30 15:42:06 +00:00
2026-03-06 11:28:29 +00:00
2026-03-06 11:28:29 +00:00
2021-12-22 09:34:41 -08:00
2026-06-04 12:57:19 +01:00
2026-06-30 12:44:24 +01:00

.. image:: https://img.shields.io/pypi/v/beets.svg
    :target: https://pypi.python.org/pypi/beets

.. image:: https://img.shields.io/codecov/c/github/beetbox/beets.svg
    :target: https://app.codecov.io/github/beetbox/beets

.. image:: https://img.shields.io/github/actions/workflow/status/beetbox/beets/ci.yaml
    :target: https://github.com/beetbox/beets/actions

.. image:: https://repology.org/badge/tiny-repos/beets.svg
    :target: https://repology.org/project/beets/versions

beets
=====

Beets is the media library management system for obsessive music geeks.

The purpose of beets is to get your music collection right once and for all. It
catalogs your collection, automatically improving its metadata as it goes. It
then provides a suite of tools for manipulating and accessing your music.

Here's an example of beets' brainy tag corrector doing its thing:

::

    $ beet import ~/music/ladytron
    Tagging:
        Ladytron - Witching Hour
    (Similarity: 98.4%)
     * Last One Standing      -> The Last One Standing
     * Beauty                 -> Beauty*2
     * White Light Generation -> Whitelightgenerator
     * All the Way            -> All the Way...

Because beets is designed as a library, it can do almost anything you can
imagine for your music collection. Via plugins_, beets becomes a panacea:

- Fetch or calculate all the metadata you could possibly need: `album art`_,
  lyrics_, genres_, tempos_, ReplayGain_ levels, or `acoustic fingerprints`_.
- Get metadata from MusicBrainz_, Discogs_, and Beatport_. Or guess metadata
  using songs' filenames or their acoustic fingerprints.
- `Transcode audio`_ to any format you like.
- Check your library for `duplicate tracks and albums`_ or for `albums that are
  missing tracks`_.
- Clean up crufty tags left behind by other, less-awesome tools.
- Embed and extract album art from files' metadata.
- Browse your music library graphically through a Web browser and play it in any
  browser that supports `HTML5 Audio`_.
- Analyze music files' metadata from the command line.
- Listen to your library with a music player that speaks the MPD_ protocol and
  works with a staggering variety of interfaces.

If beets doesn't do what you want yet, `writing your own plugin`_ is shockingly
simple if you know a little Python.

.. _acoustic fingerprints: https://beets.readthedocs.org/page/plugins/chroma.html

.. _album art: https://beets.readthedocs.org/page/plugins/fetchart.html

.. _albums that are missing tracks: https://beets.readthedocs.org/page/plugins/missing.html

.. _beatport: https://www.beatport.com

.. _discogs: https://www.discogs.com/

.. _duplicate tracks and albums: https://beets.readthedocs.org/page/plugins/duplicates.html

.. _genres: https://beets.readthedocs.org/page/plugins/lastgenre.html

.. _html5 audio: https://html.spec.whatwg.org/multipage/media.html#the-audio-element

.. _lyrics: https://beets.readthedocs.org/page/plugins/lyrics.html

.. _mpd: https://www.musicpd.org/

.. _musicbrainz: https://musicbrainz.org/

.. _musicbrainz music collection: https://musicbrainz.org/doc/Collections/

.. _plugins: https://beets.readthedocs.org/page/plugins/

.. _replaygain: https://beets.readthedocs.org/page/plugins/replaygain.html

.. _tempos: https://beets.readthedocs.org/page/plugins/acousticbrainz.html

.. _transcode audio: https://beets.readthedocs.org/page/plugins/convert.html

.. _writing your own plugin: https://beets.readthedocs.org/page/dev/plugins/index.html

Install
-------

You can install beets by typing ``pip install beets`` or directly from Github
(see details here_). Beets has also been packaged in the `software
repositories`_ of several distributions. Check out the `Getting Started`_ guide
for more information.

.. _getting started: https://beets.readthedocs.org/page/guides/main.html

.. _here: https://beets.readthedocs.io/en/latest/faq.html#run-the-latest-source-version-of-beets

.. _software repositories: https://repology.org/project/beets/versions

Contribute
----------

Thank you for considering contributing to ``beets``! Whether you're a programmer
or not, you should be able to find all the info you need at CONTRIBUTING.rst_.

.. _contributing.rst: https://github.com/beetbox/beets/blob/master/CONTRIBUTING.rst

Read More
---------

Learn more about beets at `its Web site`_. Follow `@b33ts`_ on Mastodon for news
and updates.

.. _@b33ts: https://fosstodon.org/@beets

.. _its web site: https://beets.io/

Contact
-------

- Encountered a bug you'd like to report? Check out our `issue tracker`_!

  - If your issue hasn't already been reported, please `open a new ticket`_ and
    we'll be in touch with you shortly.
  - If you'd like to vote on a feature/bug, simply give a :+1: on issues you'd
    like to see prioritized over others.
  - Need help/support, would like to start a discussion, have an idea for a new
    feature, or would just like to introduce yourself to the team? Check out
    `GitHub Discussions`_!

.. _github discussions: https://github.com/beetbox/beets/discussions

.. _issue tracker: https://github.com/beetbox/beets/issues

.. _open a new ticket: https://github.com/beetbox/beets/issues/new/choose

Authors
-------

Beets is by `Adrian Sampson`_ with a supporting cast of thousands.

.. _adrian sampson: https://www.cs.cornell.edu/~asampson/
Description
music library manager and MusicBrainz tagger
Readme MIT 560 MiB
Languages
Python 96.4%
JavaScript 3.1%
Shell 0.3%
HTML 0.1%
CSS 0.1%