diff --git a/changelog.md b/changelog.md index 96a5af2..68bf38d 100644 --- a/changelog.md +++ b/changelog.md @@ -15,6 +15,14 @@ sustained stretch without a correction. ## Unreleased +### CorOS 4.1 can duplicate a setlist with one firmware-side copy + +`QuadCortex41.duplicate_setlist()` sends the sparse folder `COPY` extracted from +Cortex Control 4.1 exactly once, then confirms the firmware-created destination +with stable folder generations and two identical complete 256-slot inventories. +A contributed CorOS 4.1.0 hardware run on 2026-09-11 confirmed a two-preset copy +in 49.878 seconds. The CorOS 4.0.1 base refuses this unmeasured command and points +callers to the older, measured `copy_preset()` recall-and-save composition. ### Rename the unit, drive undo/redo, and read inhibited modules `set_device_name()` sends a sparse Version update. `undo()` and `redo()` drive diff --git a/docs/api.md b/docs/api.md index 6752c66..0a462a8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -73,7 +73,7 @@ already read and need no connection; calling them as methods raises | **I/O ports** | `io_settings()`, `set_input_port()`, `set_output_port()`, `set_usb_port()`, `set_midi_thru()`, `set_output_pairing()` | | **Tuner and Looper** | `tuner()`, `show_tuner()`, `set_tuner_input()`, `set_tuner_reference()`, `set_tuner_mute()`, `looper()` (states named by `LooperState`) | | **List parameters** | `set_param_option(cell, param, option, source)`, `protocol.param_options(preset, ...)`, including a block's side-chain `SOURCE` | -| **Setlists** | `create_setlist(name)`, `delete_setlist(name)`, `duplicate_setlist(src, dest)`, `list_folders()` | +| **Setlists** | `create_setlist(name)`, `delete_setlist(name)`, `duplicate_setlist(source)`, `list_folders()`; on CorOS 4.1 duplication is one firmware-side COPY and the device chooses the destination name. The CorOS 4.0.1 profile refuses that unmeasured command and points to `copy_preset()` | | **Copying** | `copy_preset(from_setlist, position, to_setlist)`: recall plus save, so it loads each source | | **Device list** | `pin_model()`, `unpin_model()`, `pinned_models()`, `master_volume()` | | **Neural Captures** | `captures()` and `list_irs()` to browse the library, `set_capture(cell, entry)` to place one. Creating a capture is the unit's own wizard; disconnect first, since a connected client suppresses it | diff --git a/docs/manual-coverage.md b/docs/manual-coverage.md index d9b17a4..73c6f9e 100644 --- a/docs/manual-coverage.md +++ b/docs/manual-coverage.md @@ -111,7 +111,7 @@ settled is in [capture.md](capture.md). | User folders / additional setlists | yes | `create_setlist()` makes them and `list_folders()` finds them; `list_presets()` accepts any key. MIDI CC#32's "User folders" 2 to 12 are created, not built in | | Create a folder, nested navigation | yes | `create_setlist(name)`. Setlists are siblings under `/media/p4/Presets`, not children of My Presets | | Favorites and Recents | yes | `recents()` and `favorites()` read the two lists. The request's `is_favorites` flag selects which; the reply never sets it, so correlate on `request_id`. `add_favorite()` and `remove_favorite()` write one entry at a time. Only presets can be favourited | -| Bulk actions | partly | no host-drivable bulk copy; `BulkOperation` only narrates progress. `copy_preset()` and `duplicate_setlist()` do it by recall plus save, a few seconds per preset | +| Bulk actions | partly | On the measured CorOS 4.1 profile, `duplicate_setlist()` sends Cortex Control's single firmware-side folder COPY, then verifies the asynchronously created destination without replaying the write; the CorOS 4.0.1 profile refuses and points to `copy_preset()`. `BulkOperation` only narrates progress | | Search | no | candidate `RecentSearches` | | Sort | n/a | client-side once a listing is in hand | | Neural Captures: list | yes | `captures()` browses the library, over 2000 entries. Not the catalog, which does not grow when a capture is saved | diff --git a/docs/protocol.md b/docs/protocol.md index c75a37e..4463dde 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1409,14 +1409,17 @@ does. So the MIDI documentation's "User folders" at bank-select LSB 2 to 12 are folders a player creates. **Deleting a setlist** is `File{DELETE, folder{key, name}}` against the setlist's own key. -**There is no host-drivable copy.** The unit's duplicate action sends a `File` -`CREATE` for the destination and then narrates itself through `BulkOperation` -(`"Duplicating, please wait."`, a progress fraction, `finished`); doing the same -from the host creates an empty destination. The unit's per-preset paste -announces the same shape as a Save As pointed at another folder. So copying a -preset is recall then save, and duplicating a setlist is that per preset, which is -what `copy_preset()` and `duplicate_setlist()` do. Each one recalls the source on -the unit. +On CorOS 4.0.1, the unit's duplicate action sends a `File` `CREATE` and narrates +progress through `BulkOperation`; replaying that `CREATE` from the host produced +an empty destination. `copy_preset()` retains the measured recall-and-save +fallback on that profile. + +On CorOS 4.1, Cortex Control sends one host-drivable sparse +`File{COPY, type: 0, folder{key: , is_factory: false}}`. Firmware chooses +the collision-safe destination and performs the copy asynchronously. +`duplicate_setlist()` sends `COPY` exactly once and uses read-only polling until +two complete, identical 256-slot destination generations match the source. +A contributed 4.1.0 hardware run verified a two-preset copy in 49.878 seconds. ### 10.4 Recents and Favorites @@ -2163,6 +2166,7 @@ wire, with no independent read-back. | `delete_setlist` | `File{DELETE, folder{key, name}}` | read-back | removes the setlist and its contents | | `create_setlist` | `File{CREATE, folder{key: "/media/p4/Presets/", name}}` | read-back + on-unit | setlists are siblings under the presets root | | `copy_preset` / `duplicate_setlist` | recall then `File{CREATE}` per preset | read-back | compositions; each recalls the source on the unit | +| `duplicate_setlist` (CorOS 4.1) | `File{COPY, folder{key: , is_factory: false}}` | Cortex Control 4.1 binary + contributed hardware read-back | sends once, then stabilizes folder and complete 256-slot preset listings; CorOS 4.0.1 refuses because this shape has not been measured there | | `set_split_mute` | `Grid{UPDATE, preset{chains{row, splitBypass{bypass}}}}` | read-back | reported back in `mixBypass`; one write sets all eight scenes | | `set_stomp_assignment` / `clear_stomp_assignment` | `Grid{DELETE, stomp_mode_assignments{row, column}}` then `Grid{UPDATE, ...{stomp_index}}` | read-back + on-unit | the unit's own two-message sequence | | `set_stomp_momentary` | `Grid{UPDATE, preset{stomp_is_momentary{key, value}}}` | read-back + on-unit | keyed by footswitch; lands only on a switch driving exactly one block | diff --git a/pyquadcortex/protocol/client.py b/pyquadcortex/protocol/client.py index 39f7298..fd13f94 100644 --- a/pyquadcortex/protocol/client.py +++ b/pyquadcortex/protocol/client.py @@ -920,12 +920,15 @@ def list_presets(self, setlist: str = Setlist.USER, timeout: float = 25.0, device push a folder listing per setlist, so this sends that READ and waits for the listing whose key matches ``setlist``. - A listing that arrives is COMPLETE - five READs against an 18-preset setlist - each produced a full listing, and no short one has been observed. But a READ - does not reliably produce one promptly: two of those five saw nothing for - that setlist within 8 s, delivery being lazy. So treat a timeout as "ask - again", which is what :meth:`wait_for_listing` does, rather than as an - answer about the setlist's contents. + On CorOS 4.0.1, five READs against an 18-preset setlist each produced a + complete listing, although two produced nothing within 8 s. A contributed + CorOS 4.1.0 run on 2026-09-11 also observed transient one-slot and blank + generations before the eventual 256-slot user-setlist listing. This returns the first + matching non-empty broadcast, so a workflow that needs an authoritative + user-setlist inventory must require and stabilize all 256 slot indices, as + :meth:`duplicate_setlist` does. Treat a timeout as "ask again", which is + what :meth:`wait_for_listing` does, rather than as an answer about the + setlist's contents. Note the trailing-slash asymmetry the match has to absorb: recalls need the factory path WITH its trailing slash (Cortex Control sends it that @@ -3704,36 +3707,174 @@ def copy_preset(self, from_setlist: str, position, to_setlist: str, name or source_name or "copy", instrument=instrument, confirm=True) - def duplicate_setlist(self, source_name: str, dest_name: str, - limit: int | None = None): - """Copy a whole setlist into a new one, preset by preset. + def duplicate_setlist(self, source_name: str, *, confirm: bool = True, + timeout: float | None = None, + interval: float = 2.0): + """Refuse firmware-native duplication on the CorOS 4.0.1 profile.""" + raise ControlNotDrivable( + "duplicate_setlist", + "firmware-native File COPY was measured on CorOS 4.1.0, not on " + "the CorOS 4.0.1 base profile", + "copy presets individually with copy_preset(), or use a measured " + "CorOS 4.1 profile", + ) - Also a composition rather than a device operation. The unit's own - duplicate action broadcasts a ``BulkOperation`` narrating its progress - - ``"Duplicating, please wait."``, then a progress fraction, then - ``finished`` - but that is the device REPORTING: replaying it copies - nothing, and no host-drivable duplicate exists. So this creates the - destination and copies each preset with :meth:`copy_preset`. + def _duplicate_setlist_41(self, source_name: str, *, confirm: bool = True, + timeout: float | None = None, + interval: float = 2.0): + """Ask firmware to duplicate a complete user setlist exactly once. - Which means it is SLOW - a recall and a save per preset, several seconds - each - and it recalls every one of them on the unit as it goes. ``limit`` - caps how many are copied, for trying it out on a large setlist. + Cortex Control sends one sparse ``File{COPY}`` containing only the + source folder key and explicit ``is_factory: false``. Firmware chooses + the collision-safe destination name and key and copies the inventory + asynchronously; no destination identity or per-preset writes belong on + the wire. - Returns the list of names stored in the destination. + With ``confirm=True`` (the default), this takes a fresh folder and source + inventory baseline before the write, then performs read-only polling + until exactly one new folder has the source's complete + position/name/instrument inventory. The COPY is never replayed. Firmware + has taken more than 80 seconds for 74 presets, so the default deadline is + ``90 + 2 * occupied_presets`` seconds, capped at ten minutes. A 2026-09-11 + CorOS 4.1.0 run confirmed a disposable two-preset copy in 49.878 seconds. + That run also received partial ``File`` broadcasts before complete ones, + so both inventories require two identical generations containing every + user-setlist slot index before they are trusted. + + Returns the device-created :class:`Folder` when confirmed. With + ``confirm=False``, returns the immediate File reply if one arrives, + otherwise ``None``; that mode does not prove completion. """ - dest_key = self.create_setlist(dest_name) - time.sleep(3.0) source_key = (source_name if source_name.startswith("/") else f"{USER_SETLIST_ROOT}/{source_name}") - entries = self.list_presets(source_key) - if limit is not None: - entries = entries[:limit] - stored = [] - for i, entry in enumerate(entries): - stored.append(self.copy_preset(source_key, entry.index, dest_key, - to_position=i, name=entry.name, - instrument=entry.instrument)) - return stored + if not _is_user_setlist_key(source_key): + raise ValueError( + f"source {source_key!r} is not a direct user setlist") + if confirm: + before = self._stable_folder_listing(timeout=120.0, + interval=interval) + before_keys = {folder.key for folder in before} + if source_key not in before_keys: + raise ValueError(f"source setlist {source_key!r} is not in the fresh catalog") + expected = self._stable_complete_user_setlist( + source_key, timeout=120.0, interval=interval + ) + if timeout is None: + timeout = _setlist_copy_timeout(len(expected)) + + msg = pa.FileMessage(action=pa.MessageAction.COPY, type=0) + msg.folder.key = source_key + msg.folder.is_factory = False + reply = self._file_operation(msg) + if not confirm: + return reply + + assert timeout is not None + deadline = time.monotonic() + timeout + previous_destination = None + previous_folders = None + while True: + remaining = max(0.1, deadline - time.monotonic()) + folders = self.list_folders(seconds=min(20.0, remaining)) + folder_generation = tuple( + (f.key, f.name, f.slots, f.occupied, f.is_factory) + for f in folders) + if folder_generation != previous_folders: + previous_folders = folder_generation + if time.monotonic() >= deadline: + raise TimeoutError( + f"setlist COPY was sent once but did not publish a complete " + f"matching destination within {timeout}s; it was not replayed") + time.sleep(interval) + continue + created = [ + folder for folder in folders + if folder.key not in before_keys + and _is_user_setlist_key(folder.key) + ] + if len(created) > 1: + raise RuntimeError( + "more than one folder appeared during duplicate verification; " + "the device-created destination is ambiguous" + ) + if created: + destination = created[0] + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError( + f"setlist COPY was sent once but did not publish a complete " + f"matching destination within {timeout}s; it was not replayed") + try: + listing = self.list_presets( + destination.key, + timeout=min(25.0, remaining), + include_empty=True, + ) + except TimeoutError: + listing = [] + actual = _complete_user_setlist_inventory(listing) + if actual == expected: + if previous_destination == actual: + return destination + previous_destination = actual + else: + previous_destination = None + if time.monotonic() >= deadline: + raise TimeoutError( + f"setlist COPY was sent once but did not publish a complete " + f"matching destination within {timeout}s; it was not replayed" + ) + time.sleep(interval) + + def _stable_folder_listing(self, *, timeout: float, + interval: float) -> list: + """Return two identical folder generations inside one deadline.""" + deadline = time.monotonic() + timeout + previous_identity = None + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError( + f"no stable folder listing arrived within {timeout}s") + folders = self.list_folders(seconds=min(20.0, remaining)) + identity = tuple( + (f.key, f.name, f.slots, f.occupied, f.is_factory) + for f in folders) + if identity == previous_identity: + return folders + previous_identity = identity + time.sleep(interval) + + def _stable_complete_user_setlist(self, key: str, *, timeout: float, + interval: float) -> tuple: + """Return two identical complete 256-slot generations for ``key``.""" + deadline = time.monotonic() + timeout + previous = None + listings_seen = 0 + while True: + remaining = max(0.1, deadline - time.monotonic()) + try: + listing = self.list_presets( + key, + timeout=min(25.0, remaining), + include_empty=True, + ) + except TimeoutError: + listing = [] + actual = _complete_user_setlist_inventory(listing) + if actual is not None: + listings_seen += 1 + if previous == actual: + return actual + previous = actual + else: + previous = None + if time.monotonic() >= deadline: + raise TimeoutError( + f"no stable complete 256-slot listing arrived for {key!r} " + f"within {timeout}s ({listings_seen} complete generation(s) seen)" + ) + time.sleep(interval) #: How many parameters each Global EQ band occupies, and the offset of each #: control within a band. See :meth:`set_global_eq`. @@ -4344,6 +4485,38 @@ def field_present(message, field: str) -> bool: return False +def _preset_inventory(entries) -> tuple: + """Stable occupied-inventory identity used for setlist COPY verification.""" + return tuple(sorted( + ( + entry.index, + entry.name, + entry.instrument if field_present(entry, "instrument") else 0, + ) + for entry in entries + if field_present(entry, "name") and entry.name + )) + + +def _complete_user_setlist_inventory(entries) -> tuple | None: + """Occupied identity only when a user-setlist generation has all 256 slots.""" + positions = [entry.index for entry in entries if field_present(entry, "index")] + if len(entries) != 256 or set(positions) != set(range(256)): + return None + return _preset_inventory(entries) + + +def _is_user_setlist_key(key: str) -> bool: + """Whether ``key`` is a direct setlist child of the user preset root.""" + prefix = f"{USER_SETLIST_ROOT}/" + return key.startswith(prefix) and "/" not in key[len(prefix):] + + +def _setlist_copy_timeout(occupied_presets: int) -> float: + """Measured 4.1 COPY allowance, capped at ten minutes.""" + return min(600.0, 90.0 + 2.0 * occupied_presets) + + def blocks(p: preset.BinaryPreset) -> list: """The OCCUPIED grid cells of ``p``, as :class:`Block` entries. diff --git a/pyquadcortex/protocol/profiles.py b/pyquadcortex/protocol/profiles.py index 0a3dd76..6e9053c 100644 --- a/pyquadcortex/protocol/profiles.py +++ b/pyquadcortex/protocol/profiles.py @@ -43,11 +43,19 @@ class QuadCortex41(QuadCortex): MEASURED_ON = ("4.1.0",) EVIDENCE = Evidence.CONTRIBUTED - VERIFIED = frozenset({"create_local_backup", "set_device_name"}) + VERIFIED = frozenset({ + "create_local_backup", "duplicate_setlist", "set_device_name"}) models = NoSnapshot("coros_4_1_0") params = NoSnapshot("coros_4_1_0") options = NoSnapshot("coros_4_1_0") + def duplicate_setlist(self, source_name: str, *, confirm: bool = True, + timeout: float | None = None, + interval: float = 2.0): + """Duplicate a setlist with the CorOS 4.1 firmware-side COPY.""" + return self._duplicate_setlist_41( + source_name, confirm=confirm, timeout=timeout, interval=interval) + class QuadCortexMini(QuadCortex): """Quad Cortex Mini - recognised, not supported, and here to be finished. diff --git a/tests/hardware/test_duplicate_setlist.py b/tests/hardware/test_duplicate_setlist.py new file mode 100644 index 0000000..b75864d --- /dev/null +++ b/tests/hardware/test_duplicate_setlist.py @@ -0,0 +1,133 @@ +"""Read/write hardware coverage for firmware-native setlist duplication.""" + +import time +import uuid + +import pytest + + +def _stable_folders(qc, *, timeout=120.0): + # The firmware can publish partial generations. Use the same convergence + # rule as duplicate_setlist before making inventory or cleanup decisions. + return qc._stable_folder_listing(timeout=timeout, interval=1.0) + + +def _folder(qc, key): + return next((item for item in _stable_folders(qc) + if item.key.rstrip("/") == key.rstrip("/")), None) + + +def _wait_for_folder(qc, key, *, present, timeout=90.0): + deadline = time.monotonic() + timeout + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + state = "appear" if present else "disappear" + raise AssertionError( + f"test-owned setlist {key!r} did not {state} within {timeout}s") + result = next((item for item in _stable_folders( + qc, timeout=remaining) + if item.key.rstrip("/") == key.rstrip("/")), None) + if (result is not None) is present: + return result + remaining = deadline - time.monotonic() + time.sleep(min(2.0, remaining)) + + +@pytest.mark.verifies("duplicate_setlist") +def test_duplicate_setlist_copies_a_disposable_empty_setlist(qc, profile): + """Exercise one native COPY without exposing any user preset to deletion. + + The source is a fresh empty setlist. Cleanup is limited to its exact key and + a returned or uniquely token-named destination, and only while each still + reads empty. The COPY is sent once by the library; this test never retries + it after an uncertain result. + """ + from pyquadcortex.protocol.client import ( + QuadCortex, USER_SETLIST_ROOT, _is_user_setlist_key, + ) + + if profile.duplicate_setlist is QuadCortex.duplicate_setlist: + pytest.skip( + f"native duplicate_setlist is unavailable on {profile.__name__}") + + token = uuid.uuid4().hex[:12] + source_name = f"QCdup-{token}" + source_key = f"{USER_SETLIST_ROOT}/{source_name}" + assert _folder(qc, source_key) is None, ( + f"random disposable source already exists; refusing to touch {source_key!r}") + + create_attempted = False + copy_attempted = False + destination = None + copy_baseline: set[str] = set() + try: + # CREATE may have committed before a reply/readback problem, so cleanup + # owns the exact generated name from immediately before the call. + create_attempted = True + assert qc.create_setlist(source_name) == source_key + source = _wait_for_folder(qc, source_key, present=True) + assert source is not None and source.name == source_name + assert source.occupied == 0, ( + f"new disposable source unexpectedly contains presets: {source!r}; " + "refusing to duplicate or delete it") + + copy_baseline = {item.key for item in _stable_folders(qc)} + assert source_key in copy_baseline, ( + "source disappeared before COPY preflight; refusing to send") + + copy_attempted = True + destination = qc.duplicate_setlist( + source_name, timeout=180.0, interval=1.0) + assert destination.key not in copy_baseline + assert not destination.is_factory + assert destination.occupied == 0, ( + f"duplicate of an empty source is unexpectedly occupied: {destination!r}") + finally: + if create_attempted: + folders = _stable_folders(qc) + source_key_normalized = source_key.rstrip("/") + destination_key = (destination.key.rstrip("/") + if destination is not None else None) + owned = [item for item in folders + if item.key.rstrip("/") == source_key_normalized + or (destination_key is not None + and item.key.rstrip("/") == destination_key) + or (copy_attempted and token in (item.name + item.key) + and not item.is_factory + and _is_user_setlist_key(item.key) + and item.key not in copy_baseline)] + unidentified = [item for item in folders + if copy_attempted + and item.key not in copy_baseline + and item.key.rstrip("/") != source_key_normalized + and (destination_key is None + or item.key.rstrip("/") != destination_key) + and token not in (item.name + item.key) + and _is_user_setlist_key(item.key) + and not item.is_factory] + + deleted_keys = set() + for item in reversed(owned): + if item.occupied != 0: + pytest.fail( + f"test-owned setlist {item.key!r} unexpectedly contains " + f"{item.occupied} presets; left untouched for manual review") + # Do not replay DELETE if read-back is uncertain; report the + # exact empty test folder still present instead. + qc.delete_setlist(item.name) + deleted_keys.add(item.key.rstrip("/")) + if deleted_keys: + remaining = {item.key.rstrip("/") + for item in _stable_folders(qc)} + leftovers = sorted(deleted_keys & remaining) + if leftovers: + pytest.fail( + "DELETE was not confirmed for disposable test folders " + f"{leftovers!r}; none was sent a second time") + if unidentified: + names = ", ".join( + f"{item.name!r} ({item.key!r})" for item in unidentified) + pytest.fail( + "COPY may have created a folder without the unique source " + f"token, so it was left untouched for manual review: {names}") diff --git a/tests/test_client.py b/tests/test_client.py index 5b35eda..0ee09b0 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -13,7 +13,7 @@ import pytest -from pyquadcortex.protocol import catalog, client +from pyquadcortex.protocol import catalog, client, profiles from pyquadcortex.protocol.enums import (Footswitch, Input, Instrument, MidiSource, Output, SceneBypassBehavior, Setlist, TempoMode) from pyquadcortex.protocol.proto import ProductionAutomation_pb2 as pa @@ -32,6 +32,7 @@ def __init__(self, canned=None): self.canned = canned or {} self.broadcast = None self.last_match = None # the predicate the last type-matched read passed (read_preset, version) + self.last_timeout = None self.listeners = [] self._ids = itertools.count(1) @@ -47,6 +48,7 @@ def next_request_id(self): def await_broadcast(self, expected_class, trigger, timeout=40.0, match=None): self.last_match = match + self.last_timeout = timeout trigger() return self.broadcast @@ -147,6 +149,23 @@ def test_list_presets_omits_empty_slots_by_default(): assert [pd.index for pd in full] == [0, 1, 2, 3] +def test_list_presets_exposes_the_complete_256_slot_generation_on_request(): + listing = pa.FileMessage() + listing.folder.key = str(Setlist.USER) + for index in range(256): + listing.folder.files.add().index = index + listing.folder.files[17].name = "Occupied without relying on key" + fake = FakeTransport() + fake.broadcast = listing + + entries = client.QuadCortex(fake).list_presets( + Setlist.USER, timeout=3.0, include_empty=True) + + assert len(entries) == 256 + assert [entry.index for entry in entries] == list(range(256)) + assert fake.last_timeout == 3.0 + + def test_list_presets_matches_the_factory_listing_despite_the_trailing_slash(): # Setlist.FACTORY carries a trailing slash because RECALLS require it, but the # device reports that same folder's LISTING key without one. A naive @@ -3308,6 +3327,181 @@ def test_copy_preset_does_recall_the_source_which_changes_the_grid(): assert any(isinstance(m, pa.SetlistPositionMessage) for m in qc._t.sent) +def test_duplicate_setlist_sends_the_exact_cortex_folder_copy(): + qc = profiles.QuadCortex41(FakeTransport()) + qc.duplicate_setlist("Live", confirm=False) + sent = qc._t.sent[-1] + assert sent.SerializeToString() == bytes.fromhex( + "08 05 18 00 22 1a 0a 16 2f 6d 65 64 69 61 2f 70 34 2f 50 72 65 73 " + "65 74 73 2f 4c 69 76 65 20 00" + ) + assert not sent.HasField("request_id") # Transport.request assigns it later. + assert not sent.HasField("to_folder") + assert len(sent.folder.files) == 0 + + +def test_duplicate_setlist_sends_once_and_waits_for_matching_inventory(monkeypatch): + root = "/media/p4/Presets" + source_key = f"{root}/Live" + destination_key = f"{root}/Live 2" + before = [client.Folder(source_key, "Live", 256, 2, False)] + after = before + [client.Folder(destination_key, "Live 2", 256, 2, False)] + + def complete(first_name="One", second_name="Two"): + entries = [pa.ProductData(index=index) for index in range(256)] + entries[1].name = first_name + entries[1].key = "key-one" + entries[1].instrument = 1 + entries[7].name = second_name + entries[7].key = "key-two" + entries[7].instrument = 2 + return entries + + source = complete() + destination_partial = [source[1]] + destination_wrong = complete(second_name="Still copying") + destination_complete = complete() + + fake = FakeTransport() + qc = profiles.QuadCortex41(fake) + folder_generations = iter((before, before, after, after, after, after, after)) + source_generations = iter((source, source)) + destination_generations = iter(( + destination_partial, + destination_wrong, + destination_complete, + destination_complete, + )) + qc.list_folders = lambda seconds=20.0: next(folder_generations) + + def list_presets(key, *args, **kwargs): + if key == source_key: + return next(source_generations) + assert key == destination_key + return next(destination_generations) + + qc.list_presets = list_presets + monkeypatch.setattr(client.time, "sleep", lambda seconds: None) + + created = qc.duplicate_setlist("Live", timeout=5.0, interval=0.0) + + assert created.key == destination_key + copies = [ + message for message in fake.sent + if isinstance(message, pa.FileMessage) + and message.action == pa.MessageAction.COPY + ] + assert len(copies) == 1, "polling must never replay a persistent COPY" + + +def test_duplicate_setlist_never_baselines_a_partial_source_listing(monkeypatch): + root = "/media/p4/Presets" + source_key = f"{root}/Live" + folders = [client.Folder(source_key, "Live", 256, 1, False)] + partial = [pa.ProductData(index=0, name="Only", key="one", instrument=1)] + complete = [pa.ProductData(index=index) for index in range(256)] + complete[0].name = "Only" + complete[0].key = "one" + complete[0].instrument = 1 + + fake = FakeTransport() + qc = profiles.QuadCortex41(fake) + qc.list_folders = lambda seconds=20.0: folders + generations = iter((partial, complete, complete)) + qc.list_presets = lambda *args, **kwargs: next(generations) + monkeypatch.setattr(client.time, "sleep", lambda seconds: None) + + # Exercise the authoritative preflight directly so the test cannot create a + # persistent COPY merely to prove that a partial generation was rejected. + inventory = qc._stable_complete_user_setlist( + source_key, timeout=5.0, interval=0.0 + ) + assert inventory == ((0, "Only", 1),) + assert fake.sent == [] + + +def test_coros_4_0_1_refuses_unmeasured_native_setlist_copy(): + fake = FakeTransport() + qc = client.QuadCortex(fake) + with pytest.raises(ControlNotDrivable) as caught: + qc.duplicate_setlist("Live", confirm=False) + assert caught.value.control == "duplicate_setlist" + assert "4.1.0" in caught.value.evidence + assert "copy_preset" in caught.value.workaround + assert fake.sent == [] + + +def test_duplicate_setlist_rejects_a_factory_source_before_sending(): + fake = FakeTransport() + qc = profiles.QuadCortex41(fake) + with pytest.raises(ValueError, match="direct user setlist"): + qc.duplicate_setlist(str(Setlist.FACTORY), confirm=False) + assert fake.sent == [] + + +def test_duplicate_setlist_confirm_false_returns_the_immediate_reply(): + reply = pa.FileMessage(action=pa.MessageAction.UPDATE) + fake = FakeTransport({"FileMessage": reply}) + qc = profiles.QuadCortex41(fake) + assert qc.duplicate_setlist("Live", confirm=False) is reply + + +def test_duplicate_setlist_preflight_rejects_a_missing_source_before_copy( + monkeypatch): + folders = [client.Folder("/media/p4/Presets/Other", "Other", 256, 0, False)] + fake = FakeTransport() + qc = profiles.QuadCortex41(fake) + qc.list_folders = lambda **kwargs: folders + monkeypatch.setattr(client.time, "sleep", lambda seconds: None) + with pytest.raises(ValueError, match="not in the fresh catalog"): + qc.duplicate_setlist("Missing") + assert fake.sent == [] + + +def test_duplicate_setlist_rejects_an_ambiguous_new_folder(monkeypatch): + root = "/media/p4/Presets" + source_key = f"{root}/Live" + before = [client.Folder(source_key, "Live", 256, 1, False)] + after = before + [ + client.Folder(f"{root}/Live 2", "Live 2", 256, 1, False), + client.Folder(f"{root}/Other", "Other", 256, 0, False), + ] + full = [pa.ProductData(index=index) for index in range(256)] + full[0].name = "One" + fake = FakeTransport() + qc = profiles.QuadCortex41(fake) + folders = iter((before, before, after, after)) + qc.list_folders = lambda **kwargs: next(folders) + qc.list_presets = lambda *args, **kwargs: full + monkeypatch.setattr(client.time, "sleep", lambda seconds: None) + with pytest.raises(RuntimeError, match="more than one folder"): + qc.duplicate_setlist("Live", timeout=5.0, interval=0.0) + assert sum(isinstance(m, pa.FileMessage) and + m.action == pa.MessageAction.COPY for m in fake.sent) == 1 + + +def test_duplicate_setlist_timeout_never_replays_copy(monkeypatch): + root = "/media/p4/Presets" + source_key = f"{root}/Live" + before = [client.Folder(source_key, "Live", 256, 1, False)] + full = [pa.ProductData(index=index) for index in range(256)] + full[0].name = "One" + fake = FakeTransport() + qc = profiles.QuadCortex41(fake) + qc.list_folders = lambda **kwargs: before + qc.list_presets = lambda *args, **kwargs: full + monkeypatch.setattr(client.time, "sleep", lambda seconds: None) + with pytest.raises(TimeoutError, match="was not replayed"): + qc.duplicate_setlist("Live", timeout=0.0, interval=0.0) + assert sum(isinstance(m, pa.FileMessage) and + m.action == pa.MessageAction.COPY for m in fake.sent) == 1 + + +def test_duplicate_setlist_default_deadline_scales_and_caps(): + assert client._setlist_copy_timeout(2) == 94.0 + assert client._setlist_copy_timeout(256) == 600.0 + + # -- Global EQ by band, not by wire index -------------------------------------- # 5 parameters per band at offsets GAIN 0, FREQUENCY 1, Q 2, TYPE 3. Established by # changing each of band 1's controls and seeing which index moved, then checked diff --git a/tests/test_hardware_markers.py b/tests/test_hardware_markers.py index c8b4db5..77475d9 100644 --- a/tests/test_hardware_markers.py +++ b/tests/test_hardware_markers.py @@ -37,7 +37,6 @@ "wait_for_listing": "no hardware test yet; it is the polling wrapper round list_presets and says nothing until a write changes a listing", "create_setlist": "no hardware test yet; it adds a folder to the owner's Directory that a failed run would leave behind", "delete_setlist": "no hardware test yet; it deletes a folder and everything in it, which is the one preset-library mistake nothing can undo", - "duplicate_setlist": "no hardware test yet; it copies a whole setlist preset by preset, so a failed run leaves a partial folder behind", # -- library listings whose CONTENT belongs to the owner ------------------- # Each returns whatever this unit happens to hold, so a test can assert the diff --git a/tests/test_profiles.py b/tests/test_profiles.py index 98ef98d..17025c8 100644 --- a/tests/test_profiles.py +++ b/tests/test_profiles.py @@ -253,13 +253,14 @@ def test_the_4_1_profile_exposes_only_operations_with_contributed_evidence(): assert issubclass(cls, client.QuadCortex) assert cls.MEASURED_ON == ("4.1.0",) assert cls.EVIDENCE is support.Evidence.CONTRIBUTED - assert cls.VERIFIED == frozenset({"create_local_backup", "set_device_name"}) + assert cls.VERIFIED == frozenset({ + "create_local_backup", "duplicate_setlist", "set_device_name"}) assert cls.CC_VERSION == "4.0.1", "inherited: the contributor's runs announced 4.0.1" assert isinstance(cls.models, support.NoSnapshot) with pytest.raises(AttributeError, match="coros_4_1_0"): cls.models.Delay assert cls(FakeTransport()).unverified_operations == ( - client.QuadCortex.operations() - {"create_local_backup", "set_device_name"} + client.QuadCortex.operations() - cls.VERIFIED )