Cubase-MCP-GAJ3T.MusicGen.R.../tests/unit/test_cc_controls.py

248 lines
9.8 KiB
Python

"""Strict explicit CC requests and exact application; no vendor-effect inference."""
from fractions import Fraction
import pytest
from jsonschema import Draft202012Validator
from pydantic import ValidationError
from test_articulations import note, profile, score
from riff_groove_builder.articulations import apply_scheduled_controls, compile_score
from riff_groove_builder.compose import compose_score
from riff_groove_builder.description import resolve_description
from riff_groove_builder.errors import InvalidRequestError, SerializationError
from riff_groove_builder.formats.sdp import preflight_sdp
from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry
from riff_groove_builder.schemas import (
MAX_SCHEDULED_EVENTS,
ControlChangeEvent,
GenerateMusicRequest,
NoteOffEvent,
NoteOnEvent,
Part,
ProfileSelection,
RationalBeat,
ScheduledControl,
tool_input_schema,
)
def point(**updates: object) -> ScheduledControl:
return ScheduledControl.model_validate(
{"part": "lead", "beat": {"numerator": 0}, "controller": 1, "value": 73, **updates}
)
def request(**updates: object) -> GenerateMusicRequest:
return GenerateMusicRequest.model_validate(
{"description": "lead only 1 bar quarter", "basename": "controls", **updates}
)
@pytest.mark.parametrize(
("field", "value"),
[
("part", "guitar"),
("part", None),
("beat", 0.5),
("beat", "1/2"),
("beat", {"numerator": True}),
("beat", {"numerator": 1.0}),
("beat", {"numerator": -1}),
("beat", {"numerator": 1, "denominator": 0}),
("beat", {"numerator": 1, "denominator": False}),
("beat", {"numerator": 1, "extra": 2}),
("controller", True),
("controller", 1.0),
("controller", "1"),
("controller", -1),
("controller", 128),
("controller", None),
("value", False),
("value", 1.0),
("value", "1"),
("value", -1),
("value", 128),
("value", None),
("filename", "unsafe"),
("code", "unsafe"),
],
)
def test_strict_item(field: str, value: object) -> None:
with pytest.raises(ValidationError):
point(**{field: value})
def test_schema_optional_empty_normalized_and_boundaries() -> None:
assert request().cc_events == request(cc_events=[]).cc_events == []
invalid_values: list[object] = [None, {}, "cc", True]
for invalid in invalid_values:
with pytest.raises(ValidationError):
request(cc_events=invalid)
controls = [
point(beat={"numerator": 2, "denominator": 6}, controller=0, value=127),
point(controller=127, value=0),
]
model = request(cc_events=[cc.model_dump() for cc in controls])
assert model.cc_events[0].beat.value == Fraction(1, 3)
assert model.cc_events[0].beat.model_dump() == {"numerator": 1, "denominator": 3}
schema = tool_input_schema("generate_music")
Draft202012Validator.check_schema(schema)
Draft202012Validator(schema).validate(model.model_dump(mode="json"))
assert "cc_events" not in schema["required"]
assert schema["properties"]["cc_events"]["maxItems"] == MAX_SCHEDULED_EVENTS
assert schema["$defs"]["ScheduledControl"]["additionalProperties"] is False
assert set(schema["$defs"]["ScheduledControl"]["required"]) == {
"part",
"beat",
"controller",
"value",
}
assert GenerateMusicRequest.model_validate_json(model.model_dump_json()) == model
def test_duplicates_part_grid_and_input_budget() -> None:
for controls in (
[point().model_dump(), point(value=0).model_dump()],
[
point(beat={"numerator": 1, "denominator": 2}).model_dump(),
point(beat={"numerator": 2, "denominator": 4}).model_dump(),
],
[point(part="bass").model_dump()],
[point(beat={"numerator": 1, "denominator": 7}).model_dump()],
[point().model_dump()] * (MAX_SCHEDULED_EVENTS + 1),
):
with pytest.raises(ValidationError):
request(parts=["lead"], cc_events=controls)
def test_exact_offset_order_multiple_controllers_reset_and_unchanged_events() -> None:
selected: dict[Part, InstrumentProfile] = {"lead": profile()}
base = compile_score(score([note(7, art="pm")], origin=7), selected)
assert base.musical_start_tick == 120
controls = [
point(),
point(controller=74, value=127),
point(beat={"numerator": 1, "denominator": 3}, value=91),
point(beat={"numerator": 4}, value=0),
]
changed = apply_scheduled_controls(base, controls, selected)
original = [e.model_dump() for e in base.tracks[0].events]
assert [
e.model_dump() for e in changed.tracks[0].events if e.sequence < len(original)
] == original
added = [e for e in changed.tracks[0].events if e.sequence >= len(original)]
assert [
(e.tick, e.channel, e.controller, e.value)
for e in added
if isinstance(e, ControlChangeEvent)
] == [
(120, selected["lead"].channel, 1, 73),
(120, selected["lead"].channel, 74, 127),
(440, selected["lead"].channel, 1, 91),
(3960, selected["lead"].channel, 1, 0),
]
assert len({e.ordering_key for e in changed.tracks[0].events}) == len(original) + 4
at_start = [e for e in changed.tracks[0].events if e.tick == 120]
assert [e.kind for e in at_start] == ["control_change", "control_change", "note_on"]
assert changed.score == base.score
assert (changed.musical_start_tick, changed.musical_end_tick, changed.end_tick) == (
base.musical_start_tick,
base.musical_end_tick,
base.end_tick,
)
assert apply_scheduled_controls(base, [], selected) is base
no_reset = apply_scheduled_controls(base, [point()], selected)
assert len(no_reset.tracks[0].events) == len(original) + 1
def test_conflict_even_identical_value_is_actionable() -> None:
selected: dict[Part, InstrumentProfile] = {"lead": profile()}
for action in selected["lead"].articulations[0].actions:
if action.kind == "cc":
action.lead = RationalBeat(numerator=0)
base = compile_score(score([note(art="normal")]), selected)
existing = next(e for e in base.tracks[0].events if isinstance(e, ControlChangeEvent))
assert existing.tick == base.musical_start_tick
with pytest.raises(InvalidRequestError) as failure:
apply_scheduled_controls(
base, [point(controller=existing.controller, value=existing.value)], selected
)
assert failure.value.details == {
"field": "cc_events",
"reason": "articulation_control_conflict",
"part": "lead",
"tick": existing.tick,
"controller": existing.controller,
"action": "Remove or move this CC point; the articulation owns it.",
}
@pytest.mark.parametrize(
("cc", "reason"),
[
(point(part="drums"), "unselected_part"),
(point(beat={"numerator": 5}), "beat_after_musical_end"),
(point(beat={"numerator": 1, "denominator": 7}), "off_grid_beats"),
],
)
def test_application_validation(cc: ScheduledControl, reason: str) -> None:
selected: dict[Part, InstrumentProfile] = {"lead": profile()}
base = compile_score(score([note()]), selected)
with pytest.raises(InvalidRequestError) as failure:
apply_scheduled_controls(base, [cc], selected)
assert failure.value.details["reason"] == reason
with pytest.raises(InvalidRequestError, match="Correct"):
apply_scheduled_controls(base, [point(), point(value=0)], selected)
def test_real_combined_100000_event_budget() -> None:
selected: dict[Part, InstrumentProfile] = {"lead": profile()}
source = score([note()])
source.intent.bars = 256
source.end = RationalBeat(numerator=1024)
base = compile_score(source, selected)
# Exactly 100,000 explicit points are individually allowed, but notes/switches count too.
controls = [
point(beat={"numerator": tick, "denominator": 960}) for tick in range(MAX_SCHEDULED_EVENTS)
]
with pytest.raises(InvalidRequestError) as failure:
apply_scheduled_controls(base, controls, selected)
assert failure.value.details["reason"] == "event_budget_exceeded"
remaining = MAX_SCHEDULED_EVENTS - sum(len(t.events) for t in base.tracks)
assert len(apply_scheduled_controls(base, controls[:remaining], selected).tracks[0].events) == (
MAX_SCHEDULED_EVENTS
)
@pytest.mark.parametrize("corruption", ["none", "channel", "note", "role", "release"])
def test_sd3_precise_controller_limit_does_not_mask_corruption(corruption: str) -> None:
req = request(description="drums only 1 bar")
intent = resolve_description(req).intent
selected = load_profile_registry().select(intent.parts, req.profiles or ProfileSelection())
plan = apply_scheduled_controls(
compile_score(compose_score(intent, selected), selected), [point(part="drums")], selected
)
if corruption == "channel":
for e in plan.tracks[0].events:
e.channel = 8
elif corruption == "note":
for e in plan.tracks[0].events:
if isinstance(e, NoteOnEvent | NoteOffEvent):
e.note += 1
elif corruption == "role":
for e in plan.tracks[0].events:
if isinstance(e, NoteOnEvent | NoteOffEvent):
e.role = "keyswitch"
elif corruption == "release":
next(e for e in plan.tracks[0].events if isinstance(e, NoteOffEvent)).velocity = 1
with pytest.raises(SerializationError) as failure:
preflight_sdp(plan, "drums", selected["drums"])
assert failure.value.details["reason"] == (
"sd3_native_controller_not_supported"
if corruption == "none"
else "score_event_plan_mismatch"
if corruption == "note"
else "unsupported_sd3_event_semantics"
)