"""Service policy, defensive contracts and ownership/failure boundaries.""" import os import shutil import uuid from collections.abc import Iterator from pathlib import Path from unittest.mock import patch import pytest from pydantic import ValidationError from riff_groove_builder.description import resolve_description from riff_groove_builder.errors import ( DomainError, InvalidRequestError, NativeFormatUnavailableError, OutputExistsError, OutputIOError, SerializationError, UnsupportedArticulationError, ) from riff_groove_builder.formats import NativeCapability from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry from riff_groove_builder.schemas import GenerateMusicRequest, Part, ProfileSelection from riff_groove_builder.service import GenerationService, _Stage, validate_output_root ROOT = Path(__file__).resolve().parents[2] @pytest.fixture def workspace() -> Iterator[Path]: path = ROOT / ".test-artifacts" / f"service-unit-{uuid.uuid4().hex}" path.mkdir(parents=True) try: yield path finally: shutil.rmtree(path) def request(**updates: object) -> GenerateMusicRequest: job = GenerateMusicRequest.model_validate( {"description": "lead bass drums 1 bar quarter", "basename": "music", **updates} ) if job.profiles is None: parts = resolve_description(job).intent.parts job.profiles = ProfileSelection( **{ part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" for part in parts } ) return job @pytest.mark.parametrize( ("parts", "formats", "fallback"), [ (["lead"], None, ["lead"]), (["bass"], None, ["bass"]), (["drums"], None, ["drums"]), (["lead", "bass", "drums"], None, ["lead", "bass", "drums"]), (["drums", "lead", "bass"], ["mid"], []), (["lead", "bass", "drums"], ["agp"], ["lead", "bass"]), (["lead", "bass", "drums"], ["sdp"], ["drums"]), (["lead", "bass", "drums"], ["mid", "agp"], ["lead", "bass"]), (["lead", "bass", "drums"], ["sdp", "agp"], ["lead", "bass", "drums"]), ], ) def test_formats_status_warning_and_artifact_coverage( workspace: Path, parts: list[Part], formats: list[str] | None, fallback: list[Part] ) -> None: result = GenerationService(workspace).generate_music(request(parts=parts, formats=formats)) assert result.status == ("midi_fallback" if fallback else "complete") assert result.resolved.parts == parts assert result.resolved.musical_start_tick == 0 assert result.resolved.musical_end_tick == 3840 assert result.resolved.ticks_per_quarter == 960 assert len(result.artifacts) == 1 artifact = result.artifacts[0] assert ( artifact.format == "mid" and artifact.parts == parts and artifact.fallback_for == fallback ) assert artifact.profile_ids == [result.resolved.profile_ids.selected()[part] for part in parts] assert artifact.path == str(workspace / "music" / "music.mid") assert artifact.size_bytes == Path(artifact.path).stat().st_size > 0 assert [ warning.part for warning in result.warnings if warning.code == "STANDARD_MIDI_MAPPING" ] == (parts) assert [ warning.part for warning in result.warnings if warning.code == "NATIVE_FORMAT_UNAVAILABLE" ] == fallback assert list(workspace.iterdir()) == [workspace / "music"] @pytest.mark.parametrize( "updates", [ {"description": "drums only", "formats": ["agp"]}, {"description": "lead only", "formats": ["sdp"]}, {"description": "lead only", "profiles": {"drums": "standard.gm-drums.v1"}}, ], ) def test_resolved_parts_cannot_bypass_associations( workspace: Path, updates: dict[str, object] ) -> None: with pytest.raises(InvalidRequestError) as error: GenerationService(workspace).generate_music(request(**updates)) assert error.value.details["reason"] == "resolved_part_association" issues = error.value.details["issues"] assert isinstance(issues, list) and len(issues) == 1 assert isinstance(issues[0], dict) expected_field = "profiles" if "profiles" in updates else "formats" assert issues[0]["field"] == expected_field assert issues[0]["correction"] assert not list(workspace.iterdir()) @pytest.mark.parametrize("part", ["lead", "bass", "drums"]) def test_no_fallback_means_exact_native_error_without_stage(workspace: Path, part: Part) -> None: service = GenerationService(workspace) with ( patch.object(service, "_new_stage", side_effect=AssertionError("Must preflight")), pytest.raises(NativeFormatUnavailableError) as captured, ): service.generate_music(request(parts=[part], allow_midi_fallback=False)) native = {"drums": "sd3p", "lead": "griff", "bass": "briff"}[part] assert captured.value.details == { "part": part, "format": native, "reason": ( "sdp_profile_not_supported" if part == "drums" else "riffer_profile_not_supported" ), } assert not list(workspace.iterdir()) def test_explicit_midi_disables_native_preflight_and_needs_no_fallback(workspace: Path) -> None: with ( patch("riff_groove_builder.service.check_agp_capability", side_effect=AssertionError), patch("riff_groove_builder.service.check_sdp_capability", side_effect=AssertionError), ): result = GenerationService(workspace).generate_music( request(formats=["mid"], allow_midi_fallback=False) ) assert result.status == "complete" assert result.artifacts[0].fallback_for == [] @pytest.mark.parametrize( ("part", "formats"), [("lead", ["griff"]), ("bass", ["briff"]), ("drums", ["sd3p"])], ) def test_actual_suffix_requests_preserve_default_midi_fallback( workspace: Path, part: Part, formats: list[str] ) -> None: result = GenerationService(workspace).generate_music(request(parts=[part], formats=formats)) assert result.status == "midi_fallback" assert result.artifacts[0].format == "mid" assert result.artifacts[0].fallback_for == [part] @pytest.mark.parametrize("output_format", ["agp", "griff"]) def test_explicit_native_target_is_service_wired(workspace: Path, output_format: str) -> None: result = GenerationService(workspace).generate_music( request( parts=["lead"], formats=[output_format], profiles={"lead": "ample.ame.4.0.1.riffer.v1"}, ) ) assert result.status == "complete" assert len(result.artifacts) == 1 assert result.artifacts[0].format == "griff" assert Path(result.artifacts[0].path).read_bytes().startswith(b" None: result = GenerationService(workspace).generate_music( request( description="drums only 1 bar quarter", parts=["drums"], formats=["mid"], profiles={"drums": "toontrack.sd3.3.4.4.core.v1"}, allow_midi_fallback=False, ) ) assert result.status == "complete" assert result.artifacts[0].profile_ids == ["toontrack.sd3.3.4.4.core.v1"] assert result.artifacts[0].format == "mid" assert [(warning.code, warning.part) for warning in result.warnings] == [ ("VERIFIED_SUBSET_LIMITS", "drums") ] def test_sd3_native_service_preflight_requires_optional_template_without_staging( workspace: Path, ) -> None: with pytest.raises(NativeFormatUnavailableError) as error: GenerationService(workspace).generate_music( request( description="drums only 1 bar quarter", parts=["drums"], formats=["sd3p"], profiles={"drums": "toontrack.sd3.3.4.4.core.v1"}, allow_midi_fallback=False, ) ) assert error.value.details["reason"] == "sdp_template_required" assert not list(workspace.iterdir()) def test_profile_listing_is_real_defensive_and_honest(workspace: Path) -> None: service = GenerationService(workspace) profiles = service.list_instrument_profiles().profiles assert {profile.id for profile in profiles} == { "ample.ame.4.0.1.riffer.v1", "ample.amr.4.1.0.riffer.v1", "standard.lead.v1", "standard.bass.v1", "standard.gm-drums.v1", "toontrack.sd3.3.4.4.core.v1", } assert all( profile.mapping_kind == "standard_midi" and profile.midi_available and not profile.native_available and profile.supported_articulations == ["normal"] and "NOT verified Eclips/Ray/SD3" in profile.limitations[0] for profile in profiles if profile.id.startswith("standard.") ) assert all( p.native_available and p.supported_articulations == ( ["normal", "palm_mute", "pinch_harmonic"] if p.part == "lead" else ["normal", "palm_mute"] ) for p in profiles if p.id.startswith("ample.") ) profiles[0].limitations.clear() assert service.list_instrument_profiles().profiles[0].limitations assert not list(workspace.iterdir()) def test_wrong_profile_id_for_part_is_not_fallback(workspace: Path) -> None: with pytest.raises(DomainError) as error: GenerationService(workspace).generate_music( request(parts=["lead"], profiles={"lead": "standard.bass.v1"}) ) assert error.value.code == "PROFILE_REQUIRED" assert error.value.details["reason"] == "wrong_part" assert not list(workspace.iterdir()) @pytest.mark.parametrize("formats", [None, ["mid"], ["agp"]]) def test_palm_mute_is_never_dropped(workspace: Path, formats: list[str] | None) -> None: with pytest.raises(UnsupportedArticulationError): GenerationService(workspace).generate_music( request(description="lead only palm mute", formats=formats) ) assert not list(workspace.iterdir()) @pytest.mark.parametrize( "updates", [ {"basename": "../escape"}, {"basename": "NUL"}, {"parts": ["lead", "lead"]}, {"bars": True}, {"time_signature": {"numerator": 4, "denominator": 4.0}}, {"profiles": {"drums": "wrong"}, "parts": ["lead"]}, ], ) def test_unchecked_request_copies_are_revalidated( workspace: Path, updates: dict[str, object] ) -> None: bad = request().model_copy(update=updates) with pytest.raises(InvalidRequestError): GenerationService(workspace).generate_music(bad) assert not list(workspace.iterdir()) def test_deep_request_mutation_is_revalidated(workspace: Path) -> None: bad = request(time_signature={"numerator": 4, "denominator": 4}) assert bad.time_signature is not None bad.time_signature.numerator = 99 with pytest.raises(InvalidRequestError): GenerationService(workspace).generate_music(bad) assert not list(workspace.iterdir()) def test_corrupt_map_is_error_not_fallback(workspace: Path) -> None: registry = load_profile_registry() original = registry.select def corrupt(parts: list[Part], selection: ProfileSelection) -> dict[Part, InstrumentProfile]: selected = original(parts, selection) selected[parts[0]].channel = 99 return selected with ( patch.object(registry, "select", side_effect=corrupt), pytest.raises(SerializationError), ): GenerationService(workspace, registry=registry).generate_music(request()) assert not list(workspace.iterdir()) @pytest.mark.parametrize("call", ["check_agp_capability", "check_sdp_capability"]) @pytest.mark.parametrize( "failure", [SerializationError(details={"reason": "corrupt_map"}), RuntimeError("private-bug")], ) def test_only_known_unavailability_can_fallback( workspace: Path, call: str, failure: Exception ) -> None: with ( patch(f"riff_groove_builder.service.{call}", side_effect=failure), pytest.raises(type(failure)), ): GenerationService(workspace).generate_music(request()) assert not list(workspace.iterdir()) def test_future_capability_flag_cannot_create_fake_native_success(workspace: Path) -> None: with ( patch( "riff_groove_builder.service.check_agp_capability", return_value=NativeCapability( part="lead", format="agp", available=True, reason="test_flag_not_a_codec" ), ), pytest.raises(NativeFormatUnavailableError) as error, ): GenerationService(workspace).generate_music(request(parts=["lead"])) assert error.value.details["reason"] == "riffer_profile_not_supported" assert not list(workspace.iterdir()) def test_event_budget_failure_does_not_stage(workspace: Path) -> None: with pytest.raises(SerializationError): GenerationService(workspace).generate_music( request(description="lead bass drums 256 bars 16/1 sixteenth", formats=["mid"]) ) assert not list(workspace.iterdir()) @pytest.mark.parametrize("existing", ["empty", "nonempty", "file"]) def test_destinations_are_never_replaced(workspace: Path, existing: str) -> None: destination = workspace / "music" if existing == "file": destination.write_bytes(b"operator sentinel") else: destination.mkdir() if existing == "nonempty": (destination / "sentinel").write_bytes(b"operator sentinel") before = destination.stat() with pytest.raises(OutputExistsError): GenerationService(workspace).generate_music(request()) after = destination.stat() assert (before.st_ino, before.st_mtime_ns) == (after.st_ino, after.st_mtime_ns) assert not list(workspace.glob(".riff-stage-*")) if existing == "file": assert destination.read_bytes() == b"operator sentinel" elif existing == "nonempty": assert (destination / "sentinel").read_bytes() == b"operator sentinel" else: assert not list(destination.iterdir()) def test_root_replacement_is_rejected_without_touching_replacement(workspace: Path) -> None: root = workspace / "outputs" root.mkdir() service = GenerationService(root) root.rename(workspace / "original") root.mkdir() sentinel = root / "sentinel" sentinel.write_bytes(b"preserved") with pytest.raises(OutputIOError) as error: service.generate_music(request()) assert error.value.details["reason"] == "output_root_changed" assert list(root.iterdir()) == [sentinel] def test_ancestor_replacement_is_rejected(workspace: Path) -> None: parent = workspace / "parent" root = parent / "outputs" root.mkdir(parents=True) service = GenerationService(root) parent.rename(workspace / "original-parent") root.mkdir(parents=True) with pytest.raises(OutputIOError) as error: service.generate_music(request()) assert error.value.details["reason"] == "output_root_changed" assert not list(root.iterdir()) def test_cleanup_refuses_changed_directory_identity(workspace: Path) -> None: service = GenerationService(workspace) stage = service._new_stage("music") stage.path.rename(workspace / "moved-owned-stage") stage.path.mkdir() sentinel = stage.path / stage.filenames[0] sentinel.write_bytes(b"unowned") with pytest.raises(OutputIOError, match="permissions") as error: service._cleanup(stage) assert error.value.details == {"reason": "stage_cleanup_failed"} assert sentinel.read_bytes() == b"unowned" def test_cleanup_rejects_unrelated_stage_content(workspace: Path) -> None: service = GenerationService(workspace) stage = service._new_stage("music") sentinel = stage.path / "unrelated" sentinel.write_bytes(b"unowned") with pytest.raises(OutputIOError): service._cleanup(stage) assert sentinel.read_bytes() == b"unowned" def test_cleanup_refuses_path_outside_root(workspace: Path) -> None: root = workspace / "outputs" root.mkdir() sentinel = workspace / "music.mid" sentinel.write_bytes(b"preserved") info = workspace.stat() stage = _Stage(workspace, (info.st_dev, info.st_ino), ("music.mid",)) with pytest.raises(OutputIOError): GenerationService(root)._cleanup(stage) assert sentinel.read_bytes() == b"preserved" def test_root_reparse_detection_does_not_depend_only_on_symlink_mode(workspace: Path) -> None: with patch("riff_groove_builder.service._linked", return_value=True): with pytest.raises(ValueError, match="existing local directory"): validate_output_root(str(workspace)) @pytest.mark.parametrize("basename", ["CON", "a.mid", "a/b", "a\\b", "..", "a.", "a ", "x:y"]) def test_safe_basename_contract(workspace: Path, basename: str) -> None: with pytest.raises(ValidationError): request(basename=basename) assert not list(workspace.iterdir()) def test_unimplemented_portable_publication_is_explicit(workspace: Path) -> None: service = GenerationService(workspace) with ( patch("riff_groove_builder.service.os.name", "posix"), pytest.raises(OutputIOError) as error, ): service.generate_music(request(formats=["mid"])) assert error.value.details["reason"] == "no_replace_publication_requires_windows" assert not list(workspace.iterdir()) def test_bounded_stage_name_attempts(workspace: Path) -> None: service = GenerationService(workspace) with patch.object(Path, "mkdir", side_effect=FileExistsError) as mkdir: with pytest.raises(OutputIOError) as error: service.generate_music(request()) assert error.value.details["reason"] == "stage_name_collisions" assert mkdir.call_count == 3 assert not list(workspace.iterdir()) def test_directory_creation_failure_is_named(workspace: Path) -> None: service = GenerationService(workspace) with patch.object(Path, "mkdir", side_effect=PermissionError): with pytest.raises(OutputIOError) as error: service.generate_music(request()) assert error.value.details["reason"] == "stage_create_failed" assert not list(workspace.iterdir()) @pytest.mark.skipif(os.name != "nt", reason="Windows local volume classification") @pytest.mark.parametrize("drive_type", [0, 1, 4, 5]) def test_nonlocal_or_unusable_volumes_are_rejected(workspace: Path, drive_type: int) -> None: with patch( "riff_groove_builder.service.ctypes.windll.kernel32.GetDriveTypeW", return_value=drive_type, ): with pytest.raises(ValueError, match="existing local directory"): validate_output_root(str(workspace)) def test_incomplete_constructed_request_is_rejected(workspace: Path) -> None: with pytest.raises(InvalidRequestError): GenerationService(workspace).generate_music(GenerateMusicRequest.model_construct()) assert not list(workspace.iterdir()) @pytest.mark.skipif(os.name != "nt", reason="Windows no-replace directory rename contract") def test_real_publish_refuses_existing_empty_directory(workspace: Path) -> None: service = GenerationService(workspace) stage = service._new_stage("music") destination = workspace / "music" destination.mkdir() with pytest.raises(OutputExistsError): service._publish(stage, destination) assert destination.is_dir() and not list(destination.iterdir()) assert stage.path.is_dir() service._cleanup(stage)