diff --git a/CLAUDE.md b/CLAUDE.md index 25e5941..aac7e91 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -533,7 +533,13 @@ Two independent apps that talk over HTTP: "Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss. - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data dir). Last-opened collection (global AND per-platform), library column - layout, prep-deck zoom, import destination. Best-effort. + layout, prep-deck zoom, import destination. Best-effort, but **every + read-modify-write holds `_LOCK` and every write is atomic** + (`paths.write_json`): the UI sends several PATCHes at once on launch, and + unlocked, with a truncating write, a reader caught the file empty and wrote + back only its own key — wiping every pref, the column layout included. A + file that will not parse is moved to `userprefs.json.corrupt`, never + silently overwritten. New helpers that read then write must take the lock. - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. - `main.py` — thin FastAPI routes (all under `/api`), talking only to the adapter. Starts **unloaded**; the library is chosen at runtime via @@ -842,7 +848,11 @@ Two independent apps that talk over HTTP: via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against defaults so newly-added columns still appear). The prep deck's main-waveform zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the - shared `['prefs']` query). + shared `['prefs']` query). Continuously-changing prefs (columns, zoom, + `beatSize`) are written through ONE debounced writer, `lib/prefs.ts` + (`usePrefsWriter` / `queuePrefs`): changes merge into one PATCH, sent in + order, and the queue outlives unmounts; `QuitGuard` calls `flushPrefs()` + before quitting. Do not give a new pref its own timer. ## Commands @@ -1071,6 +1081,11 @@ serialization path.** It enforces: as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the answer, and prefs are redirected to a temp file so a test can never rewrite the user's last-opened library. +- `test_prefs.py` — `userprefs.json` under concurrent writes: 200 bursts of + simultaneous patches (plus a reader) keep every key and every patch; the + last-collection and path-mapping helpers lose nothing either; an unreadable + file is moved aside, not overwritten. Against the old unlocked code it fails + on the first trial. - `test_exports.py` — export sets against a temp copy of the real collection. Pins the things that would fail SILENTLY: a live reference picks up a playlist edited AFTER curation; contents dedupe across playlists and loose tracks; a diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py index f7d70aa..fb4cd6b 100644 --- a/backend/konduktor/prefs.py +++ b/backend/konduktor/prefs.py @@ -3,10 +3,19 @@ A self-contained JSON file in the app's per-OS user-writable data dir (see ``paths.app_data_dir``) so it survives a frozen/packaged build and works the same on every platform. Best-effort: any I/O error degrades to "no prefs". + +**Every read-modify-write holds ``_LOCK`` and every write is atomic.** FastAPI +runs ``PATCH /api/prefs`` on a thread pool, and the UI sends several at once on +launch. Unlocked, with ``write_text`` truncating before it wrote, a reader could +catch the file empty, take it for "no prefs" and write back only its own key — +wiping everything else (measured: 249 of 300 trials of three concurrent patches). +A file that exists but will not parse is moved aside before it is replaced, so +it is never silently overwritten. """ from __future__ import annotations import json +import threading from pathlib import Path from . import paths @@ -16,6 +25,9 @@ from . import paths _PREFS_PATH = paths.app_data_dir() / "userprefs.json" _LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json" +# Reentrant: the helpers below read and write inside one critical section. +_LOCK = threading.RLock() + def _migrate_legacy() -> None: """One-time: if the new file is absent but a legacy package-relative one @@ -27,29 +39,52 @@ def _migrate_legacy() -> None: pass -def load_prefs() -> dict: +def _read(*, for_write: bool) -> dict: + """The stored prefs, or {} if there are none or they cannot be read. + + With ``for_write``, a file that exists but is not a JSON object is renamed + to ``userprefs.json.corrupt`` first, since the caller is about to replace it. + """ try: _migrate_legacy() - data = json.loads(_PREFS_PATH.read_text()) - return data if isinstance(data, dict) else {} - except (OSError, ValueError): + text = _PREFS_PATH.read_text() + except OSError: return {} + try: + data = json.loads(text) + if isinstance(data, dict): + return data + except ValueError: + pass + if for_write: + try: + _PREFS_PATH.replace(_PREFS_PATH.with_name(_PREFS_PATH.name + ".corrupt")) + except OSError: + pass + return {} + + +def load_prefs() -> dict: + with _LOCK: + return _read(for_write=False) def save_prefs(prefs: dict) -> None: - try: - _PREFS_PATH.write_text(json.dumps(prefs, indent=2)) - except OSError: - pass # non-fatal — prefs are a convenience, not a requirement + with _LOCK: + try: + paths.write_json(_PREFS_PATH, prefs) + except OSError: + pass # non-fatal — prefs are a convenience, not a requirement def update_prefs(patch: dict) -> dict: """Shallow-merge `patch` into the stored prefs and persist. Returns the full updated prefs dict.""" - prefs = load_prefs() - prefs.update(patch) - save_prefs(prefs) - return prefs + with _LOCK: + prefs = _read(for_write=True) + prefs.update(patch) + save_prefs(prefs) + return prefs def get_path_mapping(collection_path: str) -> dict | None: @@ -69,16 +104,17 @@ def set_path_mapping( collection_path: str, from_prefix: str | None, to_prefix: str | None ) -> None: """Persist (or, when either prefix is blank, clear) a collection's mapping.""" - prefs = load_prefs() - mappings = prefs.get("path_mappings") - if not isinstance(mappings, dict): - mappings = {} - if from_prefix and to_prefix: - mappings[collection_path] = {"from": from_prefix, "to": to_prefix} - else: - mappings.pop(collection_path, None) - prefs["path_mappings"] = mappings - save_prefs(prefs) + with _LOCK: + prefs = _read(for_write=True) + mappings = prefs.get("path_mappings") + if not isinstance(mappings, dict): + mappings = {} + if from_prefix and to_prefix: + mappings[collection_path] = {"from": from_prefix, "to": to_prefix} + else: + mappings.pop(collection_path, None) + prefs["path_mappings"] = mappings + save_prefs(prefs) def get_last_collection(platform: str | None = None) -> str | None: @@ -105,12 +141,13 @@ def get_last_collection(platform: str | None = None) -> str | None: def set_last_collection(path: str, platform: str | None = None) -> None: """Record a library as the last opened, globally and for its platform.""" - prefs = load_prefs() - prefs["last_collection"] = path - if platform: - by_platform = prefs.get("last_collection_by_platform") - if not isinstance(by_platform, dict): - by_platform = {} - by_platform[platform] = path - prefs["last_collection_by_platform"] = by_platform - save_prefs(prefs) + with _LOCK: + prefs = _read(for_write=True) + prefs["last_collection"] = path + if platform: + by_platform = prefs.get("last_collection_by_platform") + if not isinstance(by_platform, dict): + by_platform = {} + by_platform[platform] = path + prefs["last_collection_by_platform"] = by_platform + save_prefs(prefs) diff --git a/backend/run_tests.sh b/backend/run_tests.sh index b2da4bb..c694d17 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -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_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do +for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_prefs.py b/backend/test_prefs.py new file mode 100644 index 0000000..b80c757 --- /dev/null +++ b/backend/test_prefs.py @@ -0,0 +1,104 @@ +"""userprefs.json under concurrent writes. + +The UI sends several `PATCH /api/prefs` at once on launch (column layout, deck +zoom, loop size), and FastAPI runs them on a thread pool. Before the lock and +the atomic write, a reader could catch the file truncated mid-write, take it for +"no prefs" and write back only its own key — the column layout, and with it +every other pref, vanished between sessions (249 of 300 trials of the burst +below lost the other keys). Nothing failed; the app just forgot. + +Prefs are redirected to a temp file — a test must never rewrite the user's own. +""" +import tempfile +import threading +from pathlib import Path + +from konduktor import prefs + +_TMP = tempfile.TemporaryDirectory() +prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json" +prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json" + +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 + + +BASE = {"columns": {"order": ["a", "b"]}, "autoCueTemplate": [1, 2, 3], "beatSize": 4} +PATCHES = [ + {"columns": {"order": ["b", "a"]}}, + {"mainZoomSec": 16}, + {"beatSize": 8}, + {"stemDevice": "cpu"}, +] + +# The launch burst, many times over: every patch lands and nothing else is lost. +TRIALS = 200 +bad = [] +for i in range(TRIALS): + prefs.save_prefs(BASE) + go = threading.Barrier(len(PATCHES) + 1) + + def write(p): + go.wait() + prefs.update_prefs(p) + + def read(): + go.wait() + for _ in range(20): + if "autoCueTemplate" not in prefs.load_prefs(): + bad.append(f"trial {i}: a reader saw no prefs") + return + + threads = [threading.Thread(target=write, args=(p,)) for p in PATCHES] + threads.append(threading.Thread(target=read)) + for t in threads: + t.start() + for t in threads: + t.join() + got = prefs.load_prefs() + want = {**BASE, **{k: v for p in PATCHES for k, v in p.items()}} + if got != want: + bad.append(f"trial {i}: {got}") +check(f"{TRIALS} concurrent bursts keep every key and every patch", not bad, + bad[0] if bad else "") + +# The path-specific helpers share the lock: a burst of them loses nothing either. +prefs.save_prefs({"autoCueTemplate": [1]}) +threads = [threading.Thread(target=prefs.set_last_collection, args=(f"/lib/{p}", p)) + for p in ("traktor", "rekordbox", "onelibrary")] +threads += [threading.Thread(target=prefs.set_path_mapping, args=(f"/c{n}", "X:", "/Volumes/X")) + for n in range(3)] +for t in threads: + t.start() +for t in threads: + t.join() +got = prefs.load_prefs() +check("concurrent last-collection writes keep every platform", + set(got.get("last_collection_by_platform", {})) == {"traktor", "rekordbox", "onelibrary"}, + str(got)) +check("concurrent path mappings keep every collection", + set(got.get("path_mappings", {})) == {"/c0", "/c1", "/c2"}, str(got)) +check("and the unrelated key survives", got.get("autoCueTemplate") == [1]) + +# A file that will not parse is moved aside, never silently overwritten. +prefs._PREFS_PATH.write_text('{"columns": {"order": ["a"') +check("an unreadable file reads as no prefs", prefs.load_prefs() == {}) +check("reading leaves it in place", prefs._PREFS_PATH.read_text().startswith('{"columns"')) +prefs.update_prefs({"beatSize": 2}) +corrupt = prefs._PREFS_PATH.with_name("userprefs.json.corrupt") +check("writing over it keeps the old bytes beside it", + corrupt.exists() and corrupt.read_text() == '{"columns": {"order": ["a"') +check("and the new file holds the patch", prefs.load_prefs() == {"beatSize": 2}) + +check("no temp file is left behind", + not [p for p in Path(_TMP.name).iterdir() if ".tmp" in p.name]) + +print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) +_TMP.cleanup() +raise SystemExit(1 if failed else 0) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 591e923..39b1eb6 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -31,6 +31,7 @@ import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog' import { ConvertStemsDialog } from './components/ConvertStemsDialog' import { StemReportDialog } from './components/StemReportDialog' import { Icon } from './lib/icons' +import { usePrefsWriter } from './lib/prefs' function applyFilters(tracks: Track[], f: Filters): Track[] { const q = f.search.trim().toLowerCase() @@ -117,7 +118,7 @@ export default function App() { const [columnSizing, setColumnSizing] = useState({}) const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const hydratedRef = useRef(false) - const saveTimer = useRef(null) + const writePrefs = usePrefsWriter() const resetColumns = useCallback(() => { setColumnVisibility(DEFAULT_COLUMN_VISIBILITY) @@ -148,22 +149,14 @@ export default function App() { } }, [prefsQuery.data]) - // Persist layout changes (debounced), but not before hydration so we never - // clobber saved prefs with the initial defaults. + // Persist layout changes (debounced, via the shared prefs writer), but not + // before hydration so we never clobber saved prefs with the initial defaults. useEffect(() => { if (!hydratedRef.current) return - if (saveTimer.current) window.clearTimeout(saveTimer.current) - saveTimer.current = window.setTimeout(() => { - api - .patchPrefs({ - columns: { visibility: columnVisibility, order: columnOrder, sizing: columnSizing }, - }) - .catch(() => {}) - }, 500) - return () => { - if (saveTimer.current) window.clearTimeout(saveTimer.current) - } - }, [columnVisibility, columnOrder, columnSizing]) + writePrefs({ + columns: { visibility: columnVisibility, order: columnOrder, sizing: columnSizing }, + }) + }, [columnVisibility, columnOrder, columnSizing, writePrefs]) const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) const loaded = collection.data?.loaded ?? false diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 4871ece..679de93 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -33,6 +33,7 @@ import { HotcueBar } from './HotcueBar' import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls' import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform' import { OverviewWaveform } from './OverviewWaveform' +import { usePrefsWriter } from '../lib/prefs' /** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */ const STEM_KEYS = ['KeyQ', 'KeyW', 'KeyE', 'KeyR'] @@ -165,11 +166,11 @@ export function PrepStrip({ // Main-waveform zoom persists to userprefs.json so it survives track switches // (MainWaveform unmounts during each load) and app restarts. Hydrate once from - // the shared ['prefs'] query, then persist changes debounced (mirrors the - // column-layout prefs flow in App). + // the shared ['prefs'] query, then persist changes through the shared, + // debounced prefs writer (as App's column layout does). const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const zoomHydratedRef = useRef(false) - const zoomSaveTimer = useRef(null) + const writePrefs = usePrefsWriter() useEffect(() => { if (zoomHydratedRef.current || !prefsQuery.data) return zoomHydratedRef.current = true @@ -180,20 +181,13 @@ export function PrepStrip({ }, [prefsQuery.data]) useEffect(() => { if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration - if (zoomSaveTimer.current) window.clearTimeout(zoomSaveTimer.current) - zoomSaveTimer.current = window.setTimeout(() => { - api.patchPrefs({ mainZoomSec: secPerView }).catch(() => {}) - }, 500) - return () => { - if (zoomSaveTimer.current) window.clearTimeout(zoomSaveTimer.current) - } - }, [secPerView]) + writePrefs({ mainZoomSec: secPerView }) + }, [secPerView, writePrefs]) // The loop/jump size persists the same way (survives track switches + // restarts). `beatJumpBeats` is its name from when only beat jump had a size; // it is read once so an upgrade keeps the user's choice. const sizeHydratedRef = useRef(false) - const sizeSaveTimer = useRef(null) useEffect(() => { if (sizeHydratedRef.current || !prefsQuery.data) return sizeHydratedRef.current = true @@ -203,14 +197,8 @@ export function PrepStrip({ }, [prefsQuery.data]) useEffect(() => { if (!sizeHydratedRef.current) return // don't clobber saved prefs pre-hydration - if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current) - sizeSaveTimer.current = window.setTimeout(() => { - api.patchPrefs({ beatSize }).catch(() => {}) - }, 500) - return () => { - if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current) - } - }, [beatSize]) + writePrefs({ beatSize }) + }, [beatSize, writePrefs]) const getCtx = (): AudioContext => { if (!audioCtxRef.current) { diff --git a/frontend/src/components/QuitGuard.tsx b/frontend/src/components/QuitGuard.tsx index 6ccd5d9..982b6c2 100644 --- a/frontend/src/components/QuitGuard.tsx +++ b/frontend/src/components/QuitGuard.tsx @@ -2,6 +2,7 @@ import { createPortal } from 'react-dom' import { useEffect, useRef, useState } from 'react' import { useQuery } from '@tanstack/react-query' import { api } from '../api' +import { flushPrefs } from '../lib/prefs' /** * Ask before quitting with unsaved changes: Save · Discard · Cancel. @@ -46,6 +47,7 @@ export function QuitGuard() { .then((s) => s.dirty) .catch(() => false) // no library loaded: nothing to lose if (!unsaved) { + await flushPrefs(1000) await invoke('quit_now') return } @@ -73,6 +75,7 @@ export function QuitGuard() { }, [dirty]) const quit = async () => { + await flushPrefs(1000) // a layout change made just before quitting still lands const { invoke } = await import('@tauri-apps/api/core') await invoke('quit_now') } diff --git a/frontend/src/lib/prefs.ts b/frontend/src/lib/prefs.ts new file mode 100644 index 0000000..b625b6a --- /dev/null +++ b/frontend/src/lib/prefs.ts @@ -0,0 +1,65 @@ +import { useCallback } from 'react' +import { useQueryClient, type QueryClient } from '@tanstack/react-query' +import { api } from '../api' + +/** + * The one debounced writer for prefs that change continuously (column layout, + * deck zoom, loop size). + * + * Each of those used to own a 500 ms timer. All of them hydrate from the same + * ['prefs'] fetch on launch, so their timers fired together and sent several + * PATCHes at once, which is the burst that once wiped userprefs.json (the + * backend now serialises them too). Here every change is merged into one + * pending patch, sent as ONE request after a quiet 500 ms, and requests go out + * strictly in order, so an older response can never overwrite a newer cache. + * + * The queue is module-level, so a component unmounting does not cancel its + * pending write; `flushPrefs()` sends it at once (QuitGuard calls it before + * quitting). + * + * One-off writes from a dialog may still call `api.patchPrefs` directly. + */ +const DEBOUNCE_MS = 500 + +let pending: Record = {} +let timer: number | null = null +let client: QueryClient | null = null +let chain: Promise = Promise.resolve() + +export function queuePrefs(qc: QueryClient, patch: Record): void { + client = qc + Object.assign(pending, patch) + if (timer !== null) window.clearTimeout(timer) + timer = window.setTimeout(() => void flushPrefs(), DEBOUNCE_MS) +} + +/** + * Send anything queued now. Resolves once every write so far has landed, or + * after `timeoutMs` if given — quitting must not wait on a hung backend. + */ +export function flushPrefs(timeoutMs?: number): Promise { + if (timer !== null) { + window.clearTimeout(timer) + timer = null + } + if (Object.keys(pending).length) { + const patch = pending + pending = {} + chain = chain.then(() => + api + .patchPrefs(patch) + .then((p) => { + client?.setQueryData(['prefs'], p) + }) + .catch(() => {}), + ) + } + if (timeoutMs === undefined) return chain + return Promise.race([chain, new Promise((r) => window.setTimeout(r, timeoutMs))]) +} + +/** `queuePrefs` bound to this tree's QueryClient. */ +export function usePrefsWriter(): (patch: Record) => void { + const qc = useQueryClient() + return useCallback((patch) => queuePrefs(qc, patch), [qc]) +}