"""Original content only: independent native read-back, never factory sequence fixtures.""" import shutil import uuid import xml.etree.ElementTree as ET from collections.abc import Iterator from pathlib import Path from unittest.mock import Mock import pytest from pydantic import ValidationError from riff_groove_builder.articulations import compile_score from riff_groove_builder.errors import ( NativeFormatUnavailableError, OutputExistsError, OutputIOError, SerializationError, ) from riff_groove_builder.formats.agp import ( check_riffer_capability, validate_riffer_file, write_riffer, ) from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry, parse_profile from riff_groove_builder.schemas import ( ControlChangeEvent, EventPlan, MusicalIntent, NoteOffEvent, Part, PitchedNote, PositiveBeat, ProfileSelection, RationalBeat, Score, ScoreTrack, TimeSignature, ) ROOT = Path(__file__).resolve().parents[2] def target(part: Part) -> InstrumentProfile: identifier = "ample.ame.4.0.1.riffer.v1" if part == "lead" else "ample.amr.4.1.0.riffer.v1" return load_profile_registry().select([part], ProfileSelection(**{part: identifier}))[part] def original_plan(part: Part, *, ppq: int = 960) -> tuple[EventPlan, InstrumentProfile]: assert part in ("lead", "bass") profile = target(part) assert profile.playable_range is not None low = profile.playable_range.low high = profile.playable_range.high score = Score( intent=MusicalIntent( description="Original codec verification chord and palm mute, not a factory sequence.", parts=[part], tempo_bpm=123.5, bars=1, time_signature=TimeSignature(numerator=4, denominator=4), key="C minor", seed=17, ), start=RationalBeat(numerator=0), end=RationalBeat(numerator=4), tracks=[ ScoreTrack( part=part, notes=[ PitchedNote( part=part, pitch=pitch, start=RationalBeat(numerator=start), duration=PositiveBeat(numerator=1), intensity=intensity, articulation=articulation, ) for pitch, start, intensity, articulation in ( (low, 0, 0.0, "normal"), (high, 0, 1.0, "normal"), (low + 2, 2, 0.5, "palm_mute"), ) ], ) ], ) plan = compile_score(score, {part: profile}, ppq=ppq) for tick, value in ((0, 0), (ppq, 120), (ppq * 3, 0)): plan.tracks[0].events.append( ControlChangeEvent( tick=tick, part=part, channel=profile.channel, priority=10, sequence=100 + tick, controller=1, value=value, ) ) plan.tracks[0].events.sort(key=lambda e: e.ordering_key) for event in plan.tracks[0].events: if isinstance(event, NoteOffEvent) and event.role == "musical_note": event.velocity = 45 return plan, profile @pytest.fixture def workspace() -> Iterator[Path]: path = ROOT / ".test-artifacts" / f"riffer-{uuid.uuid4().hex}" path.mkdir(parents=True) try: yield path finally: shutil.rmtree(path) @pytest.mark.parametrize("part", ["lead", "bass"]) def test_target_profiles_are_real_default_subsets(part: Part) -> None: profile = target(part) assert profile.default assert profile.provenance.status == "verified_subset" assert profile.summary.native_available and profile.summary.midi_available assert check_riffer_capability(part, profile).available assert profile.riffer is not None assert profile.riffer.layout_version == "2.1" assert profile.summary.native_format == profile.riffer.extension assert parse_profile(profile.model_dump_json()) == profile assert load_profile_registry().select([part], ProfileSelection())[part].summary.native_available assert all( "\\" not in source.reference and not source.reference.startswith(("C:", "D:")) for source in profile.provenance.sources ) @pytest.mark.parametrize("part", ["lead", "bass"]) @pytest.mark.parametrize("intensity", [0.0, 0.25, 0.5, 0.75, 1.0]) def test_evidenced_keyswitches_and_velocity_bands(part: Part, intensity: float) -> None: profile = target(part) for name, switch in (("normal", 24), ("palm_mute", 26 if part == "lead" else 24)): art = profile.resolve_articulation(name) assert art.actions[0].kind == "keyswitch" and art.actions[0].note == switch bounds = (64, 126) if name == "normal" else ((1, 127) if part == "lead" else (32, 63)) assert art.velocity(intensity) == round(bounds[0] + (bounds[1] - bounds[0]) * intensity) @pytest.mark.parametrize( "mutation", [ "version", "layout", "ppq", "ppq_bool", "extension", "instrument", "order", "tuning", "frets", "controller", "controller_bool", "articulation", "default_type", "range", "provenance", "policy", "velocity", "switch", "lead", "gate", "normal", ], ) def test_native_subset_settings_are_strict(mutation: str) -> None: data = target("lead").model_dump() native = data["riffer"] if mutation == "version": data["summary"]["product_version"] = data["provenance"]["product_version"] = "4.0.2" elif mutation == "layout": native["layout_version"] = "2.2" elif mutation == "ppq": native["ppq"] = 960 elif mutation == "ppq_bool": native["ppq"] = True elif mutation == "extension": native["extension"] = "briff" elif mutation == "instrument": native["instrument"] = "AMR" elif mutation == "order": native["strings"].reverse() elif mutation == "tuning": native["strings"][0]["open_note"] = 37 elif mutation == "frets": native["strings"][0]["max_fret"] = 23 elif mutation == "controller": native["controllers"] = [2] elif mutation == "controller_bool": native["controllers"] = [True] elif mutation == "articulation": native["articulations"]["normal"] = "PM" elif mutation == "default_type": data["default"] = "yes" elif mutation == "range": data["playable_range"]["high"] = 100 elif mutation == "provenance": data["provenance"]["status"] = "standard_midi" elif mutation == "policy": data["provenance"]["sources"].pop() elif mutation == "velocity": data["articulations"][0]["layers"][0]["velocity_low"] = 2 elif mutation == "switch": data["articulations"][0]["actions"][0]["note"] = 25 elif mutation == "lead": data["articulations"][0]["actions"][0]["lead"]["numerator"] = 1 elif mutation == "gate": data["articulations"][0]["actions"][0]["gate"]["denominator"] = 64 else: data["normal_articulation"] = "palm_mute" with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) @pytest.mark.parametrize("part", ["lead", "bass"]) @pytest.mark.parametrize("ppq", [480, 960, 1920]) def test_real_xml_writer_and_independent_readback(workspace: Path, part: Part, ppq: int) -> None: plan, profile = original_plan(part, ppq=ppq) path = workspace / f"original.{profile.summary.native_format}" before = plan.model_dump() assert write_riffer(path, plan, part, profile) == path result = validate_riffer_file(path, plan, part, profile) assert len(result.notes) == 3 and result.end_tick == 1920 assert result.cc1 == ((0, 0), (480, 120), (1440, 0)) assert {n.articulation for n in result.notes} == {"Sus", "PM" if part == "lead" else "PMP"} assert {n.off_velocity for n in result.notes} == {45} assert all(n.begin in (0, 960) and n.end in (480, 1440) for n in result.notes) root = ET.parse(path).getroot() assert root.tag == "Riff" and root.get("Inst") == ("AME" if part == "lead" else "AMR") assert root.get("Ver") == "2.1" and root.get("PPQBase") == "480" assert plan.model_dump() == before assert list(workspace.iterdir()) == [path] @pytest.mark.parametrize( "mutation", [ "version", "ppq", "target", "tempo", "meter", "key", "bars", "loop", "pitch", "fret", "begin", "end", "velocity", "off_velocity", "articulation", "legato", "muted", "string", "delete_note", "extra_note", "extra_child", "cc_value", "cc_tick", "cc_curve", "cc_delete", "cc_duplicate", "root_text", "note_text", "doctype", ], ) def test_saved_file_validator_detects_corruption_independently( workspace: Path, mutation: str ) -> None: plan, profile = original_plan("lead") path = workspace / "original.griff" write_riffer(path, plan, "lead", profile) tree = ET.parse(path) root = tree.getroot() string = root.find("String") note = root.find("String/Note") point = root.find("cc-1.Mod/p") assert string is not None and note is not None and point is not None header_changes = { "version": ("Ver", "2.2"), "ppq": ("PPQBase", "960"), "target": ("Inst", "AMR"), "tempo": ("Tempo", "121"), "meter": ("Time-Signature", "3/4"), "key": ("Key", "Am"), "bars": ("Measures", "2"), "loop": ("loopEnd", "100"), } note_changes = { "pitch": ("NoteID", "37"), "fret": ("Fret", "1"), "begin": ("Begin", "1"), "end": ("End", "479"), "velocity": ("Velocity", "2"), "off_velocity": ("Off-Velocity", "44"), "articulation": ("Articulation", "PM"), "legato": ("Legato", "Legato Slide"), "muted": ("Muted", "True"), } if mutation in header_changes: root.set(*header_changes[mutation]) elif mutation in note_changes: note.set(*note_changes[mutation]) elif mutation == "string": string.set("ID", "1") elif mutation == "delete_note": string.remove(note) elif mutation == "extra_note": ET.SubElement(string, "Note", note.attrib) elif mutation == "extra_child": ET.SubElement(root, "Chord") elif mutation == "cc_value": point.set("value", "1") elif mutation == "cc_tick": point.set("tick", "2") elif mutation == "cc_curve": point.set("curveType", "curve") elif mutation == "cc_delete": root.remove(root[-1]) elif mutation == "cc_duplicate": ET.SubElement(root[-1], "p", point.attrib) elif mutation == "root_text": root.text = "unexpected content" elif mutation == "note_text": note.text = "unexpected content" tree.write(path, encoding="utf-8", xml_declaration=True) if mutation == "doctype": path.write_bytes(b']>' + path.read_bytes()) with pytest.raises(SerializationError) as error: validate_riffer_file(path, plan, "lead", profile) assert error.value.details["reason"] == "invalid_saved_riffer" @pytest.mark.parametrize( "mutation", ["preroll", "tail", "note_missing", "switch_missing", "wrong_channel", "cc2", "cc_same_tick"], ) def test_unsupported_or_mismatched_plan_is_not_silently_dropped( workspace: Path, mutation: str ) -> None: plan, profile = original_plan("lead") if mutation == "preroll": plan.musical_start_tick += 2 plan.musical_end_tick += 2 plan.end_tick += 2 for event in plan.tracks[0].events: event.tick += 2 elif mutation == "tail": plan.end_tick += 2 elif mutation in ("note_missing", "switch_missing"): role = "musical_note" if mutation == "note_missing" else "keyswitch" pitch = 36 if mutation == "note_missing" else 24 plan.tracks[0].events = [ e for e in plan.tracks[0].events if not (e.kind != "control_change" and e.role == role and e.note == pitch) ] elif mutation == "wrong_channel": for event in plan.tracks[0].events: event.channel = 3 else: point = next(e for e in plan.tracks[0].events if isinstance(e, ControlChangeEvent)) if mutation == "cc2": point.controller = 2 else: duplicate = point.model_copy(update={"sequence": 999}) plan.tracks[0].events.append(duplicate) path = workspace / "must-not-exist.griff" with pytest.raises(SerializationError): write_riffer(path, plan, "lead", profile) assert not path.exists() @pytest.mark.parametrize("suffix", [".agp", ".mid", ".briff", ".GRIFF", ""]) def test_wrong_suffix_fails_before_io(workspace: Path, suffix: str) -> None: plan, profile = original_plan("lead") path = workspace / "never-created" / ("wrong" + suffix) with pytest.raises(SerializationError) as error: write_riffer(path, plan, "lead", profile) assert error.value.details["reason"] == "wrong_native_suffix" assert not path.parent.exists() def test_writer_exclusive_creation_and_no_parent_creation(workspace: Path) -> None: plan, profile = original_plan("lead") path = workspace / "existing.griff" path.write_bytes(b"operator-owned") with pytest.raises(OutputExistsError): write_riffer(path, plan, "lead", profile) assert path.read_bytes() == b"operator-owned" with pytest.raises(OutputIOError): write_riffer(workspace / "absent" / "original.griff", plan, "lead", profile) assert list(workspace.iterdir()) == [path] def test_no_codec_from_standard_profile_and_no_io(workspace: Path) -> None: plan, _ = original_plan("lead") profile = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1"))[ "lead" ] with pytest.raises(NativeFormatUnavailableError): write_riffer(workspace / "original.griff", plan, "lead", profile) assert not list(workspace.iterdir()) def test_no_fake_success_if_serializer_loses_notes( workspace: Path, monkeypatch: pytest.MonkeyPatch ) -> None: plan, profile = original_plan("lead") monkeypatch.setattr("riff_groove_builder.formats.agp._serialize", Mock(return_value=b"")) with pytest.raises(SerializationError): write_riffer(workspace / "broken.griff", plan, "lead", profile) def test_rational_grid_rejected_instead_of_rounded(workspace: Path) -> None: plan, profile = original_plan("lead", ppq=6720) plan.score.tracks[0].notes[2].start = RationalBeat(numerator=13, denominator=7) # The logical score compiles exactly at 6720 PPQ, but not at native PPQ 480. plan = compile_score(plan.score, {"lead": profile}, ppq=6720) with pytest.raises(SerializationError) as error: write_riffer(workspace / "off-grid.griff", plan, "lead", profile) assert error.value.details["reason"] == "off_grid_beats" @pytest.mark.parametrize("impossible", [False, True]) def test_physical_assignment_backtracks_or_rejects_without_dropping( workspace: Path, impossible: bool ) -> None: plan, profile = original_plan("lead") notes = plan.score.tracks[0].notes assert isinstance(notes[0], PitchedNote) and isinstance(notes[1], PitchedNote) notes[0].pitch = 36 if impossible else 62 notes[0].duration = PositiveBeat(numerator=2) notes[1].pitch = 37 if impossible else 84 notes[1].start = RationalBeat(numerator=1) notes.pop() plan = compile_score(plan.score, {"lead": profile}) path = workspace / "assignment.griff" if impossible: with pytest.raises(SerializationError) as error: write_riffer(path, plan, "lead", profile) assert error.value.details["reason"] == "no_physical_string_assignment" assert not path.exists() else: write_riffer(path, plan, "lead", profile) readback = validate_riffer_file(path, plan, "lead", profile) assert len(readback.notes) == 2 assert next(n for n in readback.notes if n.pitch == 62).string != 1 assert next(n for n in readback.notes if n.pitch == 84).string == 1 assert readback.cc1 == () @pytest.mark.parametrize("empty", [False, True]) def test_exact_triplets_score_origin_and_empty_score(workspace: Path, empty: bool) -> None: plan, profile = original_plan("bass") plan.score.start = RationalBeat(numerator=8) plan.score.end = RationalBeat(numerator=12) for note in plan.score.tracks[0].notes: note.start.numerator += 8 if empty: plan.score.tracks[0].notes.clear() else: plan.score.tracks[0].notes.pop() for note in plan.score.tracks[0].notes: note.start = RationalBeat(numerator=25, denominator=3) note.duration = PositiveBeat(numerator=1, denominator=3) plan = compile_score(plan.score, {"bass": profile}) path = workspace / "triplets.briff" write_riffer(path, plan, "bass", profile) readback = validate_riffer_file(path, plan, "bass", profile) assert len(readback.notes) == (0 if empty else 2) assert all((n.begin, n.end) == (160, 320) for n in readback.notes) assert readback.end_tick == 1920 def test_saved_reader_rejects_physical_overlap_even_with_all_musical_notes( workspace: Path, ) -> None: plan, profile = original_plan("lead") notes = plan.score.tracks[0].notes assert isinstance(notes[0], PitchedNote) notes[0].pitch = 62 notes[0].duration = PositiveBeat(numerator=2) notes[1].start = RationalBeat(numerator=1) notes.pop() plan = compile_score(plan.score, {"lead": profile}) path = workspace / "overlap.griff" write_riffer(path, plan, "lead", profile) tree = ET.parse(path) strings = tree.getroot().findall("String") moved: ET.Element | None = None for string in strings[:-1]: for note in list(string): if note.get("NoteID") == "62": string.remove(note) note.set("Fret", "0") moved = note assert moved is not None strings[-1].insert(0, moved) tree.write(path, encoding="utf-8", xml_declaration=True) with pytest.raises(SerializationError) as error: validate_riffer_file(path, plan, "lead", profile) assert error.value.details["reason"] == "invalid_saved_riffer"