Extended Rekordbox support

This commit is contained in:
patben8 committed 2026-09-18 12:59:44 +02:00
1 parent 010f67cd2d
commit 43e712afbd
17 files changed
+837 -100

No files matched your search

+73 -27
View File
@@ -5,14 +5,17 @@ Mirrors `adapters.traktor.adapter`. It holds:
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
* a ``TrackIndex`` — the generic READ projection built from it.
**Read-only milestone.** Every mutating command raises `Unsupported`, and
`capabilities()` reports nothing as editable, so a correct UI never offers one
in the first place; the raise is the backstop, not the mechanism.
**Track metadata and playlists are writable; cues and the beatgrid are not
yet.** Those two are separate native stores (two DB tables kept consistent, and
the per-track ANLZ analysis files), so they keep refusing until milestone 3 —
and `capabilities.cues.editable` / `grid.editable` say so, which is what the UI
actually gates on. The raise is the backstop, not the mechanism.
Writes are refused for a second, permanent reason on a cloud-synced library:
Writes are refused entirely, and permanently, on a **cloud-synced** library:
propagating a bad sync state to the user's other machines is not something
version history can undo. That check lives here so it cannot be bypassed by a
future command path forgetting it.
version history can undo — especially here, where there is no version history at
all. That check lives at the top of every command path so no future command can
forget it.
"""
from __future__ import annotations
@@ -48,6 +51,25 @@ class RekordboxAdapter:
]
)
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale.
Every mutating command must end in this — a forgotten refresh is a
silently stale projection that no byte- or row-level test would catch.
"""
counts = self._store.cue_counts()
row = self._store.content(track_id)
self._index.replace(projection.to_track(row, counts.get(str(row.ID), (0, 0))))
def close(self) -> None:
"""Release the database connection.
Rekordbox's library is a live SQLite file, not a document parsed into
memory: leaving the connection open keeps a file handle (and possibly a
`-wal`) around, so an adapter that is being replaced must be closed.
"""
self._store.close()
def reload(self) -> None:
self._store._load()
self._cloud_synced = self._store.cloud_synced
@@ -55,7 +77,11 @@ class RekordboxAdapter:
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(self.path, cloud_synced=self._cloud_synced)
return caps.capabilities_for(
self.path,
cloud_synced=self._cloud_synced,
editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS),
)
@property
def cloud_synced(self) -> bool:
@@ -107,6 +133,7 @@ class RekordboxAdapter:
rows = self._store.playlists()
folder = int(tables.PlaylistType.FOLDER)
smart = int(tables.PlaylistType.SMART_PLAYLIST)
writable = not self._cloud_synced
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
@@ -122,10 +149,13 @@ class RekordboxAdapter:
children=[],
# A smart playlist has no static entry list; a folder has no tracks.
selectable=kind == "playlist",
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
# Rekordbox's own working lists are filtered out by the store, so
# everything reaching here is the user's and may be edited — as
# long as the library itself is writable at all.
can_add_tracks=writable and kind == "playlist",
can_reorder=writable and kind == "playlist",
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
)
parent = str(r.ParentID or "root")
@@ -184,13 +214,38 @@ class RekordboxAdapter:
def remap_locations(self, mapping: PathMapping) -> int:
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- commands: track metadata ----------------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._require_writable("Editing track metadata")
self._store.set_track_metadata(track_id, fields)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return False
return self._store.dirty
def save(self):
raise Unsupported(self._readonly_reason("Saving"))
self._require_writable("Saving")
return self._store.save()
def snapshot(self) -> bytes:
"""The library's bytes, for version history.
@@ -216,20 +271,11 @@ class RekordboxAdapter:
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists")
def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists")
def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists")
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._refuse("Editing playlists")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata")
def _require_writable(self, what: str) -> None:
"""Every write passes through here, so the cloud-sync refusal cannot be
forgotten by a command added later."""
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -1,10 +1,14 @@
"""What a Rekordbox library can persist.
**Milestone 1 reports everything as read-only.** The spike verified that
Rekordbox accepts writes that maintain its USN columns (see the handoff's
Findings), but the write path is not built yet, and the capability system exists
precisely so the UI never offers an edit that will not persist. Every flag here
is therefore false/empty until milestone 2 turns them on one at a time.
**Track metadata and playlists are writable; cues and the beatgrid are not.**
The spike verified that Rekordbox accepts writes which maintain its USN columns
(see the handoff's Findings), and those two write paths use `pyrekordbox`, which
maintains them. Cues and the grid are separate hand-written stores and stay
false until milestone 3 — the capability system exists precisely so the UI never
offers an edit that will not persist.
A **cloud-synced** library reports `writable=False` regardless: Konduktor will
not write one at all.
Two facts are already known and encoded, because getting them wrong later would
be a silent data bug rather than a missing feature:
@@ -35,7 +39,11 @@ HOTCUE_SLOTS = 8
def capabilities_for(
path, version: str | None = None, *, cloud_synced: bool = False
path,
version: str | None = None,
*,
cloud_synced: bool = False,
editable_fields: list[str] | None = None,
) -> Capabilities:
# A cloud-synced library is refused PERMANENTLY, not pending a milestone:
# a local edit the server did not issue could propagate a broken sync state
@@ -43,9 +51,12 @@ def capabilities_for(
return Capabilities(
platform="rekordbox",
version=version,
writable=False,
readonly_cause="cloud_synced" if cloud_synced else "platform_incomplete",
writable=not cloud_synced,
readonly_cause="cloud_synced" if cloud_synced else None,
cues=CueCapabilities(
# Milestone 3: the cue store is hand-written (djmdCue rows plus the
# contentCue JSON mirror, kept consistent) and does not exist yet.
editable=False,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# Rekordbox is the only platform with memory cues, so they are
@@ -61,12 +72,15 @@ def capabilities_for(
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
editable_fields=[], # read-only in this milestone
# Narrower than Traktor's: `producer` and `mix` have no Rekordbox
# column (its Composer is a different field), so they are absent
# rather than mapped onto something approximate.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio"],
artwork=False,
artwork_note=None,
),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=False),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
save=SaveCapabilities(
app_name="Rekordbox",
library_label="master.db",
+187 -3
View File
@@ -3,8 +3,16 @@
This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted
SQLCipher session, the ANLZ analysis files, and the caches the projection reads.
**Read-only in this milestone.** The write path is deliberately absent rather
than stubbed: a store that cannot write cannot half-write.
**Writes cover track metadata and playlists.** Cues and the beatgrid are
deliberately absent rather than stubbed — they are separate stores (two DB tables
kept consistent, and the ANLZ analysis files) and a store that cannot write them
cannot half-write them.
Edits accumulate in the SQLAlchemy session and are only made permanent by
`save()`, which maps exactly onto Konduktor's "edit in memory, Save writes to
disk" model. `pyrekordbox`'s `commit()` is what assigns Rekordbox's update
sequence numbers, and a real Rekordbox was verified to accept and continue from
the result — see the handoff's Findings.
Two things here are not obvious and are load-bearing:
@@ -24,7 +32,8 @@ from pathlib import Path
from sqlalchemy import func, select, text
from sqlalchemy.orm import joinedload
from ...core.adapter import LibraryNotSupported, NotFound
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.pathmap import PathMapping
log = logging.getLogger(__name__)
@@ -37,6 +46,7 @@ class RekordboxStore:
self.path = Path(path)
self._mapping = PathMapping()
self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {}
self._journal = EditJournal()
self._load()
# ---- open ------------------------------------------------------------
@@ -54,10 +64,22 @@ class RekordboxStore:
self._by_id: dict[str, object] | None = None
def close(self) -> None:
"""Release the session AND the pooled connection.
`pyrekordbox`'s own `close()` only closes the SQLAlchemy session, which
returns the connection to the engine's pool — the OS file handle stays
open. Disposing the engine is what actually releases `master.db`, and
without it the file cannot be replaced (a restore, or a test copying a
fresh library over it) on any platform that locks open files.
"""
try:
self._db.close()
except Exception: # noqa: BLE001 — closing must never raise
pass
try:
self._db.engine.dispose()
except Exception: # noqa: BLE001
pass
# ---- identity --------------------------------------------------------
@property
@@ -253,3 +275,165 @@ class RekordboxStore:
return [
str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None)
]
# ---- writes: track metadata -----------------------------------------
#
# Deliberately NOT editable: the file path (it is the track's identity),
# BPM and key (audio/grid territory), and Rekordbox's own read-only
# bookkeeping. `producer` and `mix` are Traktor concepts with no Rekordbox
# column — Rekordbox has a Composer, which is not the same field — so they
# are simply absent from the set rather than mapped to something close.
_DIRECT_FIELDS = {
"title": "Title",
"comment": "Commnt",
"release_date": "ReleaseDate",
}
# Fields stored as a foreign key into a lookup table, which must be
# found-or-created: `add_*` in pyrekordbox RAISES on an existing name.
_LOOKUP_FIELDS = {
"artist": ("DjmdArtist", "ArtistID", "add_artist"),
"album": ("DjmdAlbum", "AlbumID", "add_album"),
"genre": ("DjmdGenre", "GenreID", "add_genre"),
"label": ("DjmdLabel", "LabelID", "add_label"),
# A remixer IS an artist in Rekordbox — same table, different column.
"remixer": ("DjmdArtist", "RemixerID", "add_artist"),
}
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating"}
def _lookup_id(self, table_name: str, adder: str, name: str) -> str | None:
"""The id of the lookup row called `name`, creating it if needed."""
if not name:
return None
table = getattr(self._tables, table_name)
existing = self._db.session.query(table).filter_by(Name=name).first()
if existing is not None:
return str(existing.ID)
row = getattr(self._db, adder)(name)
return str(row.ID)
def set_track_metadata(self, track_id: str, fields: dict) -> None:
row = self.content(track_id)
for key, value in fields.items():
if key not in self.EDITABLE_FIELDS:
continue # unknown/!safe fields are ignored, never guessed at
if key == "rating":
try:
stars = int(value or 0)
except (TypeError, ValueError):
raise InvalidCommand(f"Rating must be a number, got {value!r}") from None
if not 0 <= stars <= 5:
raise InvalidCommand(f"Rating must be 0-5, got {stars}")
before, new = row.Rating, stars
row.Rating = stars
elif key in self._DIRECT_FIELDS:
column = self._DIRECT_FIELDS[key]
before = getattr(row, column)
new = (value or None) if isinstance(value, str) else value
setattr(row, column, new)
else:
table_name, column, adder = self._LOOKUP_FIELDS[key]
before = getattr(row, column)
new = self._lookup_id(table_name, adder, (value or "").strip())
setattr(row, column, new)
self._journal.record("track", "set", track_id, key, before, new)
# Artist/album/genre/label are FOREIGN KEYS. Setting the id does not move
# the ORM's cached relationship, so re-projecting the row immediately
# would read the OLD name back and report a successful edit as a no-op.
# Flush pushes the ids into the transaction; expiring the row makes the
# next attribute access reload the joined rows with them.
self._db.flush()
self._db.session.expire(row)
# ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str):
t = self._tables
row = (
self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.ID == str(node_id))
.first()
)
if row is None:
raise NotFound(f"No playlist {node_id!r}")
return row
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
name = (name or "").strip()
if not name:
raise InvalidCommand("A playlist needs a name")
parent = self._playlist(parent_id) if parent_id else None
if parent is not None and int(parent.Attribute or 0) != int(
self._tables.PlaylistType.FOLDER
):
raise InvalidCommand("A playlist can only be created inside a folder")
row = self._db.create_playlist(name, parent=parent)
self._journal.record("playlist", "create", name)
return str(row.ID)
def rename_playlist(self, node_id: str, name: str) -> None:
name = (name or "").strip()
if not name:
raise InvalidCommand("A playlist needs a name")
row = self._playlist(node_id)
self._db.rename_playlist(row, name)
self._journal.record("playlist", "rename", name)
def delete_playlist(self, node_id: str) -> None:
row = self._playlist(node_id)
name = row.Name
self._db.delete_playlist(row)
self._journal.record("playlist", "delete", name)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in the given order.
Rekordbox keys order by `DjmdSongPlaylist.TrackNo`, and there is no
bulk reorder — so this clears the list and re-adds it. `add_to_playlist`
is used one row at a time because it is what maintains Rekordbox's own
USN ordering for these rows.
"""
t = self._tables
playlist = self._playlist(node_id)
if int(playlist.Attribute or 0) != int(t.PlaylistType.PLAYLIST):
raise InvalidCommand("Only a plain playlist has an editable track list")
known = {tid for tid in track_ids if self._by_id and str(tid) in self._by_id}
unknown = [tid for tid in track_ids if tid not in known]
if unknown:
raise NotFound(f"Unknown track(s): {', '.join(map(str, unknown[:3]))}")
existing = (
self._db.session.query(t.DjmdSongPlaylist)
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
.all()
)
for song in existing:
self._db.remove_from_playlist(playlist, song)
for n, track_id in enumerate(track_ids, start=1):
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
return len(track_ids)
# ---- save --------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._journal.dirty
def edited_fields(self, track_id: str) -> set[str]:
return self._journal.fields_for(track_id)
def save(self) -> SaveOutcome:
"""Make the session's edits permanent.
`commit(autoinc=True)` is what assigns Rekordbox's update sequence
numbers — one increment per change, stamped onto each changed row. A real
Rekordbox was verified to accept a library written this way and to carry
on from the counter it was left at.
`snapshot` is None: a Rekordbox library is `master.db` plus its analysis
files plus a playlist XML, so there is no single blob to version, and
`capabilities.save.history` says so.
"""
summary = self._journal.summary()
self._db.commit(autoinc=True)
self._journal.clear()
# Reads go through the same session, so nothing needs re-projecting from
# scratch — but the grid cache is keyed by track and survives a save.
return SaveOutcome(summary=summary, snapshot=None, tag_results=[])
@@ -43,6 +43,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
version=nml_version(path),
writable=True,
cues=CueCapabilities(
editable=True,
hotcue_slots=8,
slot_labels="number",
# Traktor has no memory cues — every cue occupies a bank slot.
+1 -8
View File
@@ -42,7 +42,7 @@ from traktor_nml_utils.models.collection import (
)
from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import InvalidCommand
from ...core.adapter import InvalidCommand, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
@@ -73,13 +73,6 @@ class FileTagResult:
detail: str = ""
@dataclass
class SaveOutcome:
summary: str # human-readable edit summary, for the version-history message
snapshot: bytes # exactly the bytes written, for the version-history commit
tag_results: list[FileTagResult]
class TraktorStore:
def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path)
+20 -3
View File
@@ -39,6 +39,17 @@ class AppState:
# One parse: the adapter builds its read projection from the same object
# graph the commands mutate.
adapter = registry.open_library(path)
# Release the previous library first. A file-backed platform (Rekordbox
# holds master.db open) would otherwise leak a handle — and a lingering
# write-ahead log beside a file another process replaces is how a SQLite
# library gets corrupted. Only close once the new one has parsed, so a
# failed open leaves the current library intact.
previous = self.adapter
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
except Exception: # noqa: BLE001 — a failed close must not block the open
pass
# Apply this library's saved OS-path remapping (per-machine, keyed by the
# library's local path) so runtime translation is live on open.
saved = prefs.get_path_mapping(str(path))
@@ -58,9 +69,15 @@ class AppState:
"""
assert self.adapter is not None and self.path is not None
outcome = self.adapter.save()
commit = history.commit(
self.path, outcome.snapshot, outcome.summary, __version__
)
# Not every platform is versioned. A library that is more than one file
# has no single blob that IS the library, and it says so through its
# capabilities rather than this module knowing which platforms those are.
versioned = self.adapter.capabilities().save.history
commit = None
if versioned and outcome.snapshot is not None:
commit = history.commit(
self.path, outcome.snapshot, outcome.summary, __version__
)
return outcome, commit
+23
View File
@@ -18,6 +18,7 @@ Two rules keep this honest:
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol, runtime_checkable
@@ -26,6 +27,28 @@ from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping
@dataclass
class SaveOutcome:
"""What a save produced, in terms every platform can answer.
Promoted here once a second adapter needed it (the two-platform rule). The
fields are deliberately optional because platforms differ in kind, not just
in detail:
* `snapshot` is the exact bytes written, for the version-history commit —
and it is None on a platform Konduktor does not version. A Rekordbox
library is `master.db` plus ~200 analysis files plus a playlist XML, so
there is no single blob that *is* the library, and restoring the database
alone would roll back the app's own auth and sampler state.
* `tag_results` reports embedded audio-file tag writes, which only a
platform that does them will populate.
"""
summary: str # human-readable edit summary, for the version-history message
snapshot: bytes | None = None
tag_results: list = field(default_factory=list)
class AdapterError(Exception):
"""Base for every failure an adapter reports to the HTTP layer."""
+4
View File
@@ -29,6 +29,10 @@ PlaylistKind = Literal["folder", "playlist", "smart"]
class CueCapabilities(BaseModel):
# Whether cues can be CREATED/CHANGED. Symmetric with GridCapabilities —
# a platform can be writable overall while its cue store is not yet
# implemented, which is exactly the Rekordbox milestone-2 state.
editable: bool = False
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
slot_labels: Literal["number", "letter"] = "number"
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_phase3.py test_history.py; do
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+70 -16
View File
@@ -34,12 +34,28 @@ from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402
from konduktor.core import registry # noqa: E402
from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402
from konduktor.core.adapter import ( # noqa: E402
InvalidCommand,
LibraryAdapter,
NotFound,
Unsupported,
)
from konduktor.core.model import GridMarker # noqa: E402
failed = False
def _raises(fn, exc) -> bool:
"""True when `fn` raises exactly the expected adapter error."""
try:
fn()
except exc:
return True
except Exception: # noqa: BLE001 — the wrong error is still a failure
return False
return False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
@@ -195,13 +211,15 @@ with tempfile.TemporaryDirectory() as d:
print("== capabilities gate the UI ==")
caps = adapter.capabilities()
check("platform is rekordbox", caps.platform == "rekordbox")
# The distinction that makes the UI honest: "cannot be written at all" is
# not the same as every per-feature flag happening to be false.
check("the library reports itself as NOT writable", caps.writable is False)
check("and says why, as a fact the UI can word",
caps.readonly_cause == "platform_incomplete", str(caps.readonly_cause))
# Milestone 2: the library IS writable, but only for what is implemented.
# The library-level flag and the per-feature flags are separate gates on
# purpose — see the cue/grid refusals below.
check("a local library is writable", caps.writable is True)
check("with no read-only cause", caps.readonly_cause is None, str(caps.readonly_cause))
check("per-feature flags still describe what Rekordbox CAN do",
caps.cues.memory_cues and caps.grid.flexible)
check("cues are NOT editable yet (milestone 3)", caps.cues.editable is False)
check("the grid is NOT editable yet (milestone 3)", caps.grid.editable is False)
check("8 hot cue slots, labelled by letter",
caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter")
check("memory cues are supported", caps.cues.memory_cues)
@@ -212,19 +230,19 @@ with tempfile.TemporaryDirectory() as d:
check("cue colour is a palette, not free RGB", caps.cues.color == "palette")
check("the grid is flexible but not editable yet",
caps.grid.flexible and not caps.grid.editable)
check("no field is advertised as editable", caps.tracks.editable_fields == [])
check("the editable field set is advertised", bool(caps.tracks.editable_fields))
# Rekordbox has no column for these; Traktor does. Mapping them onto its
# Composer field would silently write the wrong thing.
check("producer/mix are absent rather than approximated",
"producer" not in caps.tracks.editable_fields
and "mix" not in caps.tracks.editable_fields)
check("version history is off (multi-artefact library)", caps.save.history is False)
check("the save warning says Rekordbox holds the library open",
caps.save.overwrite_risk == "while_running")
check("library label is master.db", caps.save.library_label == "master.db")
print("== every command is refused, with a reason ==")
print("== the unimplemented stores still refuse, with a reason ==")
commands = {
"set_track_metadata": lambda: adapter.set_track_metadata(sample.id, {"title": "x"}),
"create_playlist": lambda: adapter.create_playlist("x"),
"rename_playlist": lambda: adapter.rename_playlist("1", "x"),
"delete_playlist": lambda: adapter.delete_playlist("1"),
"set_playlist_entries": lambda: adapter.set_playlist_entries("1", []),
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
"set_cue": lambda: adapter.set_cue(sample.id, slot=1, start_sec=0.0, cue_type="cue"),
"set_cue_type": lambda: adapter.set_cue_type(sample.id, 1, "cue"),
@@ -239,7 +257,8 @@ with tempfile.TemporaryDirectory() as d:
"delete_grid": lambda: adapter.delete_grid(sample.id),
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None),
"save": lambda: adapter.save(),
# save() works now; snapshot() must not, because a Rekordbox library is
# more than one file and there is nothing to version.
"snapshot": lambda: adapter.snapshot(),
}
refused = []
@@ -251,8 +270,43 @@ with tempfile.TemporaryDirectory() as d:
pass
except Exception as ex: # noqa: BLE001 — anything else is the wrong error
refused.append(f"{name} ({type(ex).__name__})")
check("every mutating command raises Unsupported", not refused, ", ".join(refused))
check("the adapter is never dirty while read-only", adapter.dirty is False)
check("every cue/grid command still raises Unsupported", not refused, ", ".join(refused))
check("refusing a command leaves the adapter clean", adapter.dirty is False)
print("== metadata writes, including the foreign-key fields ==")
# artist/album/genre/label are FKs into lookup tables, not columns. Setting
# one must (a) find-or-create the lookup row — pyrekordbox's add_* RAISES on
# an existing name — and (b) return a projection that reflects the new value,
# which needs a flush+expire or the ORM reads the stale relationship back.
writable_target = adapter.tracks[0]
updated = adapter.set_track_metadata(
writable_target.id,
{"genre": "Konduktor Probe Genre", "artist": "Konduktor Probe Artist", "rating": 4},
)
check("the command returns the refreshed projection", updated is not None)
if updated:
check("a NEW lookup value is reflected immediately",
updated.genre == "Konduktor Probe Genre" and updated.artist == "Konduktor Probe Artist",
f"{updated.genre!r} / {updated.artist!r}")
check("a direct column is reflected immediately", updated.rating == 4, str(updated.rating))
check("the index holds the same refreshed track",
adapter.track(writable_target.id).genre == "Konduktor Probe Genre")
# Re-using an EXISTING lookup value must not try to create it again.
existing_genre = next(
(t.genre for t in adapter.tracks if t.genre and t.id != writable_target.id), None
)
if existing_genre:
again = adapter.set_track_metadata(writable_target.id, {"genre": existing_genre})
check("an existing lookup value is reused, not re-created",
again is not None and again.genre == existing_genre,
str(again.genre if again else None))
check("an out-of-range rating is rejected",
_raises(lambda: adapter.set_track_metadata(writable_target.id, {"rating": 9}),
InvalidCommand))
check("an unknown track is a NotFound",
_raises(lambda: adapter.set_track_metadata("nope", {"title": "x"}), NotFound))
check("unknown fields are ignored, never guessed at",
adapter.set_track_metadata(writable_target.id, {"not_a_field": "x"}) is not None)
print("== a cloud-synced library is refused permanently, not pending a milestone ==")
# The one failure mode version history cannot undo: a local edit the sync
+241
View File
@@ -0,0 +1,241 @@
"""Rekordbox's analogue of `test_save_fidelity.py`.
The project's core safety property is: **an edit changes only what it was
supposed to change.** For Traktor that is a byte diff of the whole file. A byte
diff is meaningless against SQLite — page layout, free lists and vacuuming move
bytes that carry no meaning — so the equivalent here is a **full table dump
before and after, compared row by row**.
Runs against a TEMP COPY of the local Rekordbox library, and skips cleanly when
no Rekordbox is installed.
Two things about the expected diff are NOT noise and must stay asserted:
* `agentRegistry.localUpdateCount` changes on every save. It is Rekordbox's
global update counter, and NOT bumping it is what would corrupt the library.
* the edited row's own `rb_local_usn` is stamped with that new counter value.
A real Rekordbox 7 was verified to accept a library written exactly this way,
display the edit, leave the row untouched, and carry on from the counter it was
left at — see the handoff's Findings section.
"""
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appdata-")
from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
# ---- the row-level dump/diff harness -----------------------------------
def dump(db_path: Path) -> dict:
"""Every row of every table, keyed by primary key."""
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.db6.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db_path))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
cur = con.cursor()
# Materialise the table list FIRST: reusing one cursor for the outer and the
# inner queries silently truncates the outer iteration to a single row.
names = [
r[0]
for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
).fetchall()
]
out: dict[str, dict] = {}
for table in names:
if table == "sqlite_sequence":
continue
cols = [r[1] for r in cur.execute(f'PRAGMA table_info("{table}")').fetchall()]
pk = "ID" if "ID" in cols else cols[0]
rows = {}
for r in cur.execute(f'SELECT * FROM "{table}"').fetchall():
d = dict(zip(cols, r))
rows[str(d.get(pk))] = d
out[table] = rows
con.close()
return out
def diff(before: dict, after: dict, ignore_columns=("updated_at", "created_at")) -> list:
"""(table, pk, kind, detail) for every row-level change."""
changes = []
for table in sorted(set(before) | set(after)):
rows_a, rows_b = before.get(table, {}), after.get(table, {})
for pk in sorted(set(rows_a) | set(rows_b)):
if pk not in rows_a:
changes.append((table, pk, "INSERT", rows_b[pk]))
elif pk not in rows_b:
changes.append((table, pk, "DELETE", rows_a[pk]))
else:
fields = {
k: (rows_a[pk][k], rows_b[pk].get(k))
for k in rows_a[pk]
if k not in ignore_columns and rows_a[pk][k] != rows_b[pk].get(k)
}
if fields:
changes.append((table, pk, "UPDATE", fields))
return changes
def describe(changes) -> str:
return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)"
def clean_copy(src: Path, dest: Path, *, closing=()) -> None:
"""Copy a library WITHOUT any stale write-ahead log.
A `-wal` left beside a replaced `.db` is replayed onto it by SQLite and
corrupts it. This cost real debugging time during the research spike.
`closing` is any adapters still holding the destination open: replacing a
SQLite file under a live connection is an I/O error at best.
"""
for adapter in closing:
adapter.close()
for ext in ("-wal", "-shm"):
stale = Path(str(dest) + ext)
if stale.exists():
stale.unlink()
shutil.copy2(src, dest)
found = discovery.detect_libraries()
if not found:
print("== SKIPPED: no Rekordbox library found on this machine ==")
print("\nRESULT: ALL PASSED")
sys.exit(0)
REAL = Path(found[0]["path"])
print(f"(using a temp copy of {REAL})")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "master.db"
clean_copy(REAL, work)
share = REAL.parent / "share"
if share.is_dir():
shutil.copytree(share, Path(d) / "share")
# ---- A: a no-op save changes nothing --------------------------------
print("== A: opening and saving without editing changes no row ==")
before = dump(work)
adapter = RekordboxAdapter(work)
check("a freshly opened library is not dirty", adapter.dirty is False)
adapter.save()
changes = diff(before, dump(work))
check("a no-op save changes zero rows", not changes, describe(changes))
# ---- B: one metadata edit touches one row + the counter --------------
print("== B: a single metadata edit is localized ==")
clean_copy(REAL, work, closing=[adapter])
before = dump(work)
adapter = RekordboxAdapter(work)
target = adapter.tracks[0]
original_title = target.title
adapter.set_track_metadata(target.id, {"title": "KONDUKTOR FIDELITY PROBE"})
check("the edit makes the adapter dirty", adapter.dirty is True)
check("the projection updates immediately",
adapter.track(target.id).title == "KONDUKTOR FIDELITY PROBE")
adapter.save()
check("saving clears dirty", adapter.dirty is False)
changes = diff(before, dump(work))
tables_touched = {t for t, _, _, _ in changes}
check("exactly two rows change", len(changes) == 2, describe(changes))
check("they are the track and the update counter",
tables_touched == {"djmdContent", "agentRegistry"}, str(tables_touched))
content = [c for c in changes if c[0] == "djmdContent"]
check("the changed track is the one edited",
len(content) == 1 and content[0][1] == target.id, describe(content))
if content:
fields = content[0][3]
check("only Title and the row's USN changed",
set(fields) == {"Title", "rb_local_usn"}, str(sorted(fields)))
check("Title holds the new value", fields.get("Title", (None, None))[1] == "KONDUKTOR FIDELITY PROBE")
registry = [c for c in changes if c[0] == "agentRegistry"]
check("the global update counter is the registry row that changed",
len(registry) == 1 and registry[0][1] == "localUpdateCount", describe(registry))
if registry:
old_usn, new_usn = registry[0][3]["int_1"]
check("the counter increments by exactly one edit", new_usn == old_usn + 1,
f"{old_usn} -> {new_usn}")
# This is the invariant Rekordbox itself relies on to notice the change.
if content:
check("the edited row is stamped with the new counter value",
content[0][3].get("rb_local_usn", (None, None))[1] == new_usn,
str(content[0][3].get("rb_local_usn")))
# ---- C: the edit survives a reopen ----------------------------------
print("== C: the edit is really on disk ==")
reopened = RekordboxAdapter(work)
check("the new title is there after reopening",
reopened.track(target.id).title == "KONDUKTOR FIDELITY PROBE",
str(reopened.track(target.id).title))
check("the original title is gone", original_title != "KONDUKTOR FIDELITY PROBE")
# ---- D: an unsaved edit is not on disk ------------------------------
print("== D: edits are held until save, like every other platform ==")
clean_copy(REAL, work, closing=[adapter, reopened])
before = dump(work)
adapter = RekordboxAdapter(work)
adapter.set_track_metadata(adapter.tracks[0].id, {"title": "NEVER SAVED"})
changes = diff(before, dump(work))
check("an unsaved edit has written nothing to disk", not changes, describe(changes))
# ---- E: playlist edits -----------------------------------------------
print("== E: a playlist round-trips ==")
clean_copy(REAL, work, closing=[adapter])
adapter = RekordboxAdapter(work)
before_tree = adapter.playlist_tree()
ids = [t.id for t in adapter.tracks[:3]]
node_id = adapter.create_playlist("Konduktor Test Playlist")
adapter.set_playlist_entries(node_id, ids)
adapter.save()
reopened = RekordboxAdapter(work)
names = {n.name for n in reopened.playlist_tree()}
check("the playlist exists after a reopen", "Konduktor Test Playlist" in names, str(names))
check("its entries are the tracks added, in order",
reopened.playlist_entries(node_id) == ids,
f"{reopened.playlist_entries(node_id)} vs {ids}")
tracks = reopened.playlist_tracks(node_id)
check("and they resolve to real projected tracks",
tracks is not None and [t.id for t in tracks] == ids)
reopened.rename_playlist(node_id, "Konduktor Renamed")
reopened.save()
again = RekordboxAdapter(work)
check("a rename round-trips",
"Konduktor Renamed" in {n.name for n in again.playlist_tree()})
again.delete_playlist(node_id)
again.save()
final = RekordboxAdapter(work)
check("a delete round-trips",
"Konduktor Renamed" not in {n.name for n in final.playlist_tree()})
check("the rest of the tree is untouched",
len(final.playlist_tree()) == len(before_tree),
f"{len(final.playlist_tree())} vs {len(before_tree)}")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)