fix(cd-audio): keep case-distinct track files apart and register a move that outlives a cancel

- A sheet naming both Track.bin and TRACK.BIN read both tracks from one
  file on a case-sensitive filesystem, since neither was checked by its
  exact name. An exact match now wins over the case-insensitive one.
- Cancelling while a finished track was moving into place left the
  FLAC on disk but unregistered. The move now finishes before the
  cancel propagates, and a track it landed is registered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017hbFZXXaYLy9ApWatJ5WCV
This commit is contained in:
Sam Dornan
2026-09-30 20:54:22 +00:00
committed by Claude
parent 36cdbe80d6
commit bcc278a118
2 changed files with 79 additions and 5 deletions

View File

@@ -138,9 +138,13 @@ def _locate_files(folder: Path, names: set[str]) -> dict[str, Path]:
if folded[name.casefold()] == 1 and (folder / name).is_file()
}
if missing := names - located.keys():
by_folded = {e.name.casefold(): e for e in folder.iterdir() if e.is_file()}
entries = [e for e in folder.iterdir() if e.is_file()]
# An exact name wins, so a case-sensitive folder keeps distinct files apart.
by_name = {e.name: e for e in entries}
by_folded = {e.name.casefold(): e for e in entries}
for name in missing:
if (entry := by_folded.get(name.casefold())) is not None:
entry = by_name.get(name) or by_folded.get(name.casefold())
if entry is not None:
located[name] = entry
return located
@@ -487,9 +491,19 @@ async def _write_track(
destination = await prepare_upload_destination(rom, folder, track.file_name)
staged = staging_path(destination.location)
await encode_track(track.source, staged, rom.name)
await asyncio.to_thread(
move_into_place, destination.location, staged, overwrite=False
move = asyncio.ensure_future(
asyncio.to_thread(
move_into_place, destination.location, staged, overwrite=False
)
)
try:
await asyncio.shield(move)
except asyncio.CancelledError:
# The thread can't be stopped, so a track it lands is still registered.
await asyncio.wait([move])
if not move.cancelled() and move.exception() is None:
result.extracted.append(track.file_name)
raise
except UploadConflictException:
# Already extracted, or a concurrent extraction got there first.
result.skipped.append(track.file_name)

View File

@@ -12,7 +12,7 @@ import pytest
from tests.factories import make_rom
from exceptions.fs_exceptions import RomListedByPlaylistException
from handler import cd_audio
from handler import cd_audio, rom_upload
from handler.cd_audio import (
CdAudioEncodeException,
CdAudioNeedsFolderException,
@@ -531,6 +531,32 @@ async def test_starts_no_track_after_a_failure(
assert _soundtrack_metas(cd_rom.id) == {}
async def test_registers_a_track_whose_move_finished_after_a_cancel(
cd_rom: Rom, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(cd_audio, "ENCODE_CONCURRENCY", 1)
real_move = rom_upload.move_into_place
moving = threading.Event()
release = threading.Event()
def slow_move(location: Path, staged: Path, *, overwrite: bool) -> None:
moving.set()
release.wait(5)
real_move(location, staged, overwrite=overwrite)
monkeypatch.setattr(cd_audio, "move_into_place", slow_move)
task = asyncio.create_task(cd_audio.extract_cd_audio(cd_rom))
await asyncio.to_thread(moving.wait, 5)
task.cancel()
await asyncio.sleep(0.05)
release.set()
with pytest.raises(asyncio.CancelledError):
await task
assert set(_soundtrack_metas(cd_rom.id)) == {"Disc - Track 02.flac"}
async def test_asks_for_a_scan_when_the_tracks_cannot_be_registered(
cd_rom: Rom, real_library: Path, monkeypatch: pytest.MonkeyPatch
):
@@ -739,6 +765,40 @@ async def test_reads_a_file_named_in_several_cases_once(
)
async def test_keeps_files_differing_only_in_case_apart(
admin_user: User, platform: Platform, real_library: Path
):
sheet = (
'FILE "Track.bin" BINARY\n TRACK 02 AUDIO\n INDEX 01 00:00:00\n'
'FILE "TRACK.BIN" BINARY\n TRACK 03 AUDIO\n INDEX 01 00:00:00\n'
)
rom = _add_sheet_rom(
admin_user,
platform,
real_library,
{
"Disc.cue": sheet.encode(),
"Track.bin": _tone(TRACK_2_SECTORS),
"TRACK.BIN": _tone(TRACK_3_SECTORS),
},
)
if len(list((real_library / rom.full_path).iterdir())) < 3:
pytest.skip("the library is on a case-insensitive filesystem")
await cd_audio.extract_cd_audio(rom)
metas = _soundtrack_metas(rom.id)
durations = {
name: meta.duration_seconds for name, meta in metas.items() if meta is not None
}
assert durations["Disc - Track 02.flac"] == pytest.approx(
TRACK_2_SECTORS / SECTORS_PER_SECOND, abs=0.02
)
assert durations["Disc - Track 03.flac"] == pytest.approx(
TRACK_3_SECTORS / SECTORS_PER_SECOND, abs=0.02
)
async def test_takes_each_gdi_track_file_and_number_once(
admin_user: User, platform: Platform, real_library: Path
):