"""Synthetic mechanics and registry-policy tests, never production mapping evidence.""" import json from pathlib import Path from typing import Any from unittest.mock import Mock import pytest from pydantic import ValidationError from riff_groove_builder.errors import ProfileNotFoundError, ProfileRequiredError from riff_groove_builder.profiles import ( AmbiguousProfileError, InstrumentProfile, InvalidProfileError, ProfilePartMismatchError, ProfileRegistry, ProfileRegistryError, checked_profile, load_profile_registry, normalize_name, parse_profile, ) from riff_groove_builder.schemas import Part, ProfileSelection FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" def payload(part: str = "lead") -> dict[str, Any]: data: dict[str, Any] = json.loads((FIXTURES / f"synthetic-{part}.json").read_text()) return data def attested(identifier: str = "fixture.one", *, default: bool = False) -> InstrumentProfile: """In-memory policy fixture only: this attestation is NOT real mapping evidence.""" data = payload() data["id"] = data["summary"]["id"] = identifier data["summary"]["product_name"] = "In-memory registry policy fixture" data["provenance"]["status"] = "verified" data["provenance"]["sources"] = [ { "kind": "lawful_local", "reference": "TEST-HARNESS-NOT-VENDOR-EVIDENCE", "aspects": [ "identity", "range_or_voices", "channels", "actions", "state_reset", "timing", "velocity", ], } ] data["default"] = default return InstrumentProfile.model_validate(data) @pytest.mark.parametrize("part", ["lead", "bass", "drums"]) def test_synthetic_json_roundtrip(part: str) -> None: profile = parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) assert profile.provenance.status == "test_only" assert profile.summary.product_name.startswith("SYNTHETIC ") assert not profile.summary.native_available assert parse_profile(profile.model_dump_json()) == profile with pytest.raises(ProfileRegistryError, match="resources failed"): ProfileRegistry([profile]) @pytest.mark.parametrize( "document", [ "{", "null", "[]", '{"schema_version":"1","schema_version":"2"}', b"\xff", ], ) def test_bad_documents(document: str | bytes) -> None: with pytest.raises(InvalidProfileError) as error: parse_profile(document) assert error.value.details == {"reason": "invalid_profile_document"} @pytest.mark.parametrize( ("field", "value"), [ ("schema_version", "2"), ("schema_version", 1), ("schema_version", True), ("channel", 16), ("channel", -1), ("channel", True), ("channel", 2.0), ("default", "false"), ("id", "../bad"), ("id", "bad\n"), ("unknown", 1), ("playable_range", None), ("normal_articulation", "undeclared"), ], ) def test_strict_profile_fields(field: str, value: object) -> None: data = payload() data[field] = value with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) @pytest.mark.parametrize( ("section", "field", "value"), [ ("summary", "id", "wrong"), ("summary", "part", "bass"), ("summary", "midi_available", False), ("summary", "native_available", True), ("summary", "product_version", "different"), ("summary", "mapping_version", "other"), ("summary", "supported_articulations", ["normal"]), ("summary", "limitations", []), ("provenance", "status", "verified"), ("provenance", "target_build", ""), ("provenance", "mapping_preset", ""), ("provenance", "limitations", []), ], ) def test_inconsistent_identity_and_provenance(section: str, field: str, value: object) -> None: data = payload() data[section][field] = value with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) def test_no_accidental_test_promotion() -> None: data = payload() data["default"] = True with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) policy_fixture = attested().model_dump() policy_fixture["id"] = policy_fixture["summary"]["id"] = "test.promoted" with pytest.raises(ValidationError): InstrumentProfile.model_validate(policy_fixture) data = payload() data["provenance"]["sources"] = attested().provenance.model_dump()["sources"] with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) @pytest.mark.parametrize("name", ["Palm Mute", "PALM-MUTE", " palm__mute ", "palm_mute"]) def test_alias_normalization(name: str) -> None: profile = InstrumentProfile.model_validate(payload()) assert normalize_name(name) == "palm_mute" assert profile.resolve_articulation(name).name == "palm_mute" @pytest.mark.parametrize("alias", ["NORMAL", "palm mute", "PM", "bad\tname", "é", ""]) def test_alias_collisions_and_bad_names(alias: str) -> None: data = payload() data["articulations"][0]["aliases"].append(alias) with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) @pytest.mark.parametrize( ("field", "value"), [ ("note", -1), ("note", 128), ("velocity", 0), ("velocity", True), ("behavior", "unknown"), ("gate", {"numerator": 0}), ("lead", {"numerator": -1}), ("release_offset", {"numerator": 1}), ], ) def test_switch_validation(field: str, value: object) -> None: data = payload() data["articulations"][0]["actions"][0][field] = value with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) @pytest.mark.parametrize( ("field", "value"), [ ("controller", 128), ("value", -1), ("reset_value", 0), ("release_offset", {"numerator": 1}), ], ) def test_latched_cc_validation(field: str, value: object) -> None: data = payload() data["articulations"][0]["actions"][1][field] = value with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) def test_controls_and_state_validation() -> None: data = payload("bass") data["articulations"][1]["actions"][1]["reset_value"] = None with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) data = payload() data["articulations"][0]["actions"].append(data["articulations"][0]["actions"][0]) with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) data = payload() data["articulations"][0]["actions"] = [] with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) data = payload() data["articulations"][1]["actions"] = data["articulations"][1]["actions"][:1] with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) @pytest.mark.parametrize( ("index", "field", "value"), [ (0, "low", 0.1), (1, "high", 0.9), (0, "high", 0.6), (0, "high", 0.4), (0, "high", 0.0), (0, "velocity_low", 0), (0, "velocity_high", 128), (0, "velocity_low", 60), (0, "velocity_high", 90), (0, "velocity_high", 80), ], ) def test_layer_gaps_overlap_and_ranges(index: int, field: str, value: object) -> None: data = payload() data["articulations"][1]["layers"][index][field] = value with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) @pytest.mark.parametrize( ("intensity", "velocity"), [ (0.0, 30), (0.25, 40), (0.499999, 50), (0.5, 80), (0.75, 90), (1.0, 100), ], ) def test_layer_endpoints(intensity: float, velocity: int) -> None: art = InstrumentProfile.model_validate(payload()).resolve_articulation("pm") assert art.velocity(intensity) == velocity @pytest.mark.parametrize(("intensity", "expected"), [(0.25, 32), (0.75, 96)]) def test_velocity_rounds_complete_interpolation_ties_to_even( intensity: float, expected: int, ) -> None: art = InstrumentProfile.model_validate(payload()).resolve_articulation("normal") assert art.velocity(intensity) == expected @pytest.mark.parametrize("intensity", [-1.0, 1.01, float("inf"), float("nan"), True]) def test_invalid_intensities(intensity: float) -> None: art = InstrumentProfile.model_validate(payload()).resolve_articulation("pm") with pytest.raises(InvalidProfileError): art.velocity(intensity) def test_ranges_voices_and_switch_collisions() -> None: data = payload() data["playable_range"] = {"low": 90, "high": 48} with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) data["playable_range"] = {"low": 1, "high": 84} with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) drums = InstrumentProfile.model_validate(payload("drums")) assert drums.resolve_voice("LOW") == 36 for field, value in [("aliases", ["high"]), ("note", 40), ("note", 128)]: data = payload("drums") data["drum_voices"][0][field] = value with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) data = payload("drums") data["drum_voices"] = [] with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) def test_registry_selection_and_copies() -> None: registry = ProfileRegistry([attested(default=True), attested("fixture.two")]) assert registry.select(["lead"], ProfileSelection())["lead"].id == "fixture.one" assert registry.select(["lead"], ProfileSelection(lead="fixture.two"))["lead"].id == ( "fixture.two" ) summaries = registry.summaries() assert [p.id for p in summaries] == ["fixture.one", "fixture.two"] summaries[0].product_name = "modified outside registry" assert registry.summaries()[0].product_name != summaries[0].product_name with pytest.raises(ProfileNotFoundError): registry.select(["lead"], ProfileSelection(lead="test.lead.v1")) with pytest.raises(ProfilePartMismatchError): registry.select(["bass"], ProfileSelection(bass="fixture.one")) with pytest.raises(ProfilePartMismatchError): registry.select(["bass"], ProfileSelection(lead="fixture.one")) with pytest.raises(ProfileRequiredError) as error: registry.select(["drums"], ProfileSelection()) assert error.value.details["reason"] == "verified_mapping_required" def test_ambiguous_and_duplicate_registry_entries() -> None: for entries, reason in [ ([attested(), attested()], "duplicate_profile_id"), ([attested(default=True), attested("fixture.two", default=True)], "duplicate_default"), ]: with pytest.raises(ProfileRegistryError) as error: ProfileRegistry(entries) assert error.value.details["reason"] == reason for entries in [[attested()], [attested(), attested("fixture.two")]]: with pytest.raises(AmbiguousProfileError) as ambiguous: ProfileRegistry(entries).select(["lead"], ProfileSelection()) assert ambiguous.value.details["available_ids"] == [p.id for p in entries] invalid_parts: list[list[Part]] = [[], ["lead", "lead"]] for parts in invalid_parts: with pytest.raises(ProfilePartMismatchError): ProfileRegistry([]).select(parts, ProfileSelection()) def test_mutated_models_revalidated() -> None: profile = InstrumentProfile.model_validate(payload()) profile.channel = 99 with pytest.raises(InvalidProfileError): checked_profile(profile) with pytest.raises(InvalidProfileError): ProfileRegistry([profile]) @pytest.mark.parametrize( "missing_aspect", [ "identity", "range_or_voices", "channels", "actions", "state_reset", "timing", "velocity", ], ) def test_verified_attestation_requires_complete_coverage(missing_aspect: str) -> None: data = attested().model_dump() data["provenance"]["sources"][0]["aspects"].remove(missing_aspect) with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) def test_source_identity_cannot_satisfy_native_gate() -> None: data = attested().model_dump() data["summary"]["native_available"] = True with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) data = attested().model_dump() source = data["provenance"]["sources"][0] source["kind"], source["reference"] = "official_public", "http://example.invalid" with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) source["reference"] = "https://example.invalid/TEST-ONLY-NOT-EVIDENCE" source["aspects"].append("timing") with pytest.raises(ValidationError): InstrumentProfile.model_validate(data) def test_packaged_registry_has_target_defaults_and_explicit_standard_fallbacks() -> None: registry = load_profile_registry() assert [summary.id for summary in registry.summaries()] == [ "ample.ame.4.0.1.riffer.v1", "ample.amr.4.1.0.riffer.v1", "standard.bass.v1", "standard.gm-drums.v1", "standard.lead.v1", "toontrack.sd3.3.4.4.core.v1", ] assert [summary.mapping_kind for summary in registry.summaries()] == [ "instrument", "instrument", "standard_midi", "standard_midi", "standard_midi", "instrument", ] selected = registry.select(["lead", "bass", "drums"], ProfileSelection()) assert {part: p.channel for part, p in selected.items()} == {"lead": 0, "bass": 1, "drums": 9} for part, profile in selected.items(): assert profile.default and profile.provenance.status == "verified_subset" assert profile.summary.native_available assert registry.select([part], ProfileSelection(**{part: profile.id}))[part] == profile standard_id = "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" standard = registry.select([part], ProfileSelection(**{part: standard_id}))[part] assert not standard.default and standard.provenance.status == "standard_midi" assert not standard.summary.native_available assert "NOT a verified" in standard.summary.product_name with pytest.raises(ProfileNotFoundError): registry.select(["lead"], ProfileSelection(lead="test.lead.v1")) with pytest.raises(ProfilePartMismatchError): registry.select(["bass"], ProfileSelection(bass="standard.lead.v1")) @pytest.mark.parametrize("declared", [("missing.json",), ("../bad.json",), ("x.json", "x.json")]) def test_missing_and_invalid_resource_manifests(declared: tuple[str, ...]) -> None: with pytest.raises(ProfileRegistryError): load_profile_registry(declared=declared) def test_resource_access_failure_is_not_empty(monkeypatch: pytest.MonkeyPatch) -> None: with pytest.raises(ProfileRegistryError) as error: load_profile_registry(package="riff_groove_builder.no_such_package") assert error.value.details["reason"] == "profile_resource_load_failed" monkeypatch.setattr("riff_groove_builder.profiles.resources.files", Mock(side_effect=OSError)) with pytest.raises(ProfileRegistryError): load_profile_registry() def test_loaded_resources_corrupt_or_synthetic(monkeypatch: pytest.MonkeyPatch) -> None: root = Mock() root.iterdir.return_value = [Mock(name="entry")] root.iterdir.return_value[0].name = "fixture.json" monkeypatch.setattr("riff_groove_builder.profiles.resources.files", lambda _: root) with pytest.raises(ProfileRegistryError) as error: load_profile_registry() assert error.value.details["reason"] == "resource_manifest_mismatch" root.joinpath.return_value.read_bytes.return_value = b"{" with pytest.raises(InvalidProfileError): load_profile_registry(declared=("fixture.json",)) root.joinpath.return_value.read_bytes.return_value = ( FIXTURES / "synthetic-lead.json" ).read_bytes() with pytest.raises(ProfileRegistryError) as error: load_profile_registry(declared=("fixture.json",)) assert error.value.details["reason"] == "synthetic_production_leakage"