Ver código fonte

create reset engine script

Johan Le Baut 1 semana atrás
pai
commit
f54e3fdb5b
5 arquivos alterados com 610 adições e 12 exclusões
  1. 12 0
      README.md
  2. 16 12
      scripts/deploy.py
  3. 327 0
      scripts/reset_engine.py
  4. 16 0
      tests/test_deploy.py
  5. 239 0
      tests/test_reset_engine.py

+ 12 - 0
README.md

@@ -226,6 +226,18 @@ systemctl --user status rigforge-mod-host-ports.service rigforge-mod-ui.service
 journalctl --user -u rigforge-mod-ui.service -b
 ```
 
+### Full engine reset
+
+For recovery testing, `scripts/reset_engine.py` performs an explicit full reset of the logged-in user's audio engine. It restarts `pipewire.service` and `wireplumber.service`, which drops the current PipeWire graph, and then restarts Rigforge services that were enabled or active, along with any required dependencies. It preserves service enablement choices and starts components in dependency order. If mod-ui is deployment-managed, it restores the generated reference pedalboard and preserves the previous default board and last-state file, when present, as adjacent `.rigforge-reset-backup` files.
+
+Run it on the target from the Rigforge checkout:
+
+```sh
+python3 scripts/reset_engine.py
+```
+
+The command refuses to run unless the machine hostname matches the desired-state target, and prompts before interrupting audio; `--yes` skips the prompt. It pauses the reconciliation timer during the reset, waits for dependent services through their readiness checks, reconciles the declared links once, and checks the resulting graph before restarting the timer. If a reset step fails, it exits nonzero, leaves the timer stopped, and may leave services stopped for inspection. It does not enable or disable units, alter unrelated link policy, or manually remove arbitrary links. Restarting PipeWire nevertheless drops all graph links; clients outside Rigforge must reconnect themselves. SooperLooper's in-memory recordings/playback may be lost. A clean graph check verifies topology only, not audible signal or stability. This is an intentionally disruptive recovery tool and has not been verified on the target.
+
 On the target, `install pipewire` initially applied quantum 128 and reported that the installed fragment was already current; the following observer reported no differences. A later `reload pipewire` applied the quantum and restarted the filter-chain service, after which observation found all three managed links missing. One-shot reconciliation requested each link, and the subsequent observer reported `differences: []`. This confirms the graph links were present after reconciliation, not that audio was audible. On 2026-11-24, the owner selected 256 frames as the desired quantum after a temporary runtime test. A short `pw-top` sample at 256 showed about 1.4 ms WAIT and no ERR-counter increase between the sampled updates; sustained stability, headroom, and long-term listening comparison remain unverified. `install all` and `uninstall all` attempt all four targets and report an overall failure if any action fails. `reload all` restarts the filter-chain service and prints no-op messages for the LV2 plugins. Check the target afterwards with `python3 scripts/validate_desired_state.py`, `python3 -m unittest discover -s tests -v`, and `python3 scripts/observe_pipewire.py`.
 
 ## Development PC

+ 16 - 12
scripts/deploy.py

@@ -2041,7 +2041,7 @@ def prepare_mod_ui_reference_bundle(
     return tree_sha256(destination)
 
 
-def reset_mod_ui_reference(config, registry):
+def reset_mod_ui_reference(config, registry, manage_services=True):
     managed = registry.get("mod_ui")
     if managed is None:
         raise RuntimeError("mod-ui is not managed; install mod-ui before resetting it")
@@ -2092,7 +2092,8 @@ def reset_mod_ui_reference(config, registry):
         raise RuntimeError(f"reset staging path already exists: {staged}")
     default_board.parent.mkdir(parents=True, exist_ok=True)
     shutil.copytree(reference, staged, symlinks=False)
-    run(["systemctl", "--user", "stop", config["user_service"]])
+    if manage_services:
+        run(["systemctl", "--user", "stop", config["user_service"]])
     board_backed_up = False
     state_backed_up = False
     reference_installed = False
@@ -2105,16 +2106,18 @@ def reset_mod_ui_reference(config, registry):
             state_backed_up = True
         os.replace(staged, default_board)
         reference_installed = True
-        run(["systemctl", "--user", "start", config["user_service"]])
-        run(["systemctl", "--user", "is-active", "--quiet", config["user_service"]])
-        if "midi_bridge" in registry:
-            run(["systemctl", "--user", "start", "rigforge-midi-bridge.service"])
-            run(["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"])
+        if manage_services:
+            run(["systemctl", "--user", "start", config["user_service"]])
+            run(["systemctl", "--user", "is-active", "--quiet", config["user_service"]])
+            if "midi_bridge" in registry:
+                run(["systemctl", "--user", "start", "rigforge-midi-bridge.service"])
+                run(["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"])
     except (OSError, subprocess.CalledProcessError):
-        try:
-            run(["systemctl", "--user", "stop", config["user_service"]])
-        except subprocess.CalledProcessError:
-            pass
+        if manage_services:
+            try:
+                run(["systemctl", "--user", "stop", config["user_service"]])
+            except subprocess.CalledProcessError:
+                pass
         if staged.exists():
             shutil.rmtree(staged)
         if reference_installed and default_board.exists():
@@ -2123,7 +2126,8 @@ def reset_mod_ui_reference(config, registry):
             os.replace(backup_board, default_board)
         if state_backed_up and backup_state.exists():
             os.replace(backup_state, last_state)
-        run(["systemctl", "--user", "start", config["user_service"]])
+        if manage_services:
+            run(["systemctl", "--user", "start", config["user_service"]])
         raise
 
     print(

+ 327 - 0
scripts/reset_engine.py

@@ -0,0 +1,327 @@
+#!/usr/bin/env python3
+"""Perform an explicit full restart of the Rigforge user audio engine."""
+
+import argparse
+import json
+import socket
+import subprocess
+import sys
+from pathlib import Path
+
+import yaml
+
+import deploy
+from validate_desired_state import validate_state
+
+
+ROOT = Path(__file__).resolve().parents[1]
+PIPEWIRE_UNIT = "pipewire.service"
+WIREPLUMBER_UNIT = "wireplumber.service"
+
+
+def load_state():
+    state_path = ROOT / "config" / "desired-state.yaml"
+    with state_path.open(encoding="utf-8") as stream:
+        state = yaml.safe_load(stream)
+    errors = validate_state(state)
+    if errors:
+        raise ValueError("invalid desired state: " + "; ".join(errors))
+    return state
+
+
+def call_systemctl(unit, verb, runner=subprocess.run):
+    return runner(
+        ["systemctl", "--user", verb, "--quiet", unit],
+        check=False,
+        capture_output=True,
+        text=True,
+    )
+
+
+def inspect_unit(unit, runner=subprocess.run):
+    result = runner(
+        ["systemctl", "--user", "show", "--property=LoadState", "--value", unit],
+        check=False,
+        capture_output=True,
+        text=True,
+    )
+    if result.returncode:
+        detail = result.stderr.strip() or result.stdout.strip()
+        raise RuntimeError(f"cannot inspect {unit}: {detail or 'systemd user manager failed'}")
+    if result.stdout.strip() == "not-found":
+        return {"present": False, "active": False, "enabled": False}
+
+    active = call_systemctl(unit, "is-active", runner).returncode == 0
+    enabled = call_systemctl(unit, "is-enabled", runner).returncode == 0
+    return {"present": True, "active": active, "enabled": enabled}
+
+
+def checked_command(command, runner=subprocess.run):
+    result = runner(command, check=False, capture_output=True, text=True)
+    if result.returncode:
+        detail = result.stderr.strip() or result.stdout.strip()
+        raise RuntimeError(
+            f"command failed ({result.returncode}): {' '.join(command)}"
+            + (f"\n{detail}" if detail else "")
+        )
+    if result.stdout.strip():
+        print(result.stdout.rstrip())
+    return result
+
+
+def unit_map(deployment):
+    return {
+        "filter_chain": deployment["pipewire"]["user_service"],
+        "quantum": deployment["pipewire"]["quantum_user_service"],
+        "ports": deployment["mod_host_ports"]["user_service"],
+        "mod_host": deployment["mod_host"]["user_service"],
+        "mod_ui": deployment["mod_ui"]["user_service"],
+        "midi_bridge": deployment["midi_bridge"]["user_service"],
+        "sooperlooper": deployment["sooperlooper"]["user_service"],
+        "slweb": deployment["slweb"]["user_service"],
+        "reconcile_service": deployment["reconcile"]["user_service"],
+        "reconcile_timer": deployment["reconcile"]["user_timer"],
+    }
+
+
+def selected_roles(units, statuses):
+    selected = {
+        role
+        for role, unit in units.items()
+        if role in {
+            "filter_chain",
+            "ports",
+            "mod_host",
+            "mod_ui",
+            "midi_bridge",
+            "sooperlooper",
+            "slweb",
+        }
+        and statuses[unit]["present"]
+        and (statuses[unit]["active"] or statuses[unit]["enabled"])
+    }
+
+    dependencies = {
+        "ports": ("filter_chain",),
+        "sooperlooper": ("filter_chain",),
+        "mod_host": ("ports", "filter_chain"),
+        "mod_ui": ("mod_host", "ports", "filter_chain"),
+        "midi_bridge": ("mod_ui", "mod_host", "ports", "filter_chain"),
+        "slweb": ("sooperlooper",),
+    }
+    pending = list(selected)
+    while pending:
+        role = pending.pop()
+        for dependency in dependencies.get(role, ()):
+            unit = units[dependency]
+            if not statuses[unit]["present"]:
+                raise RuntimeError(
+                    f"{units[role]} is enabled or active but its required unit "
+                    f"{unit} is not installed"
+                )
+            if dependency not in selected:
+                selected.add(dependency)
+                pending.append(dependency)
+    return selected
+
+
+def reset_engine(deployment, registry, runner=subprocess.run):
+    units = unit_map(deployment)
+    all_units = {PIPEWIRE_UNIT, WIREPLUMBER_UNIT, *units.values()}
+    statuses = {unit: inspect_unit(unit, runner) for unit in sorted(all_units)}
+    for unit in (PIPEWIRE_UNIT, WIREPLUMBER_UNIT):
+        if not statuses[unit]["present"]:
+            raise RuntimeError(f"required audio service is not installed: {unit}")
+
+    if not statuses[units["mod_host"]]["active"] and any(
+        deploy.mod_host_port_is_open(port)
+        for port in (
+            deployment["mod_host"]["socket_port"],
+            deployment["mod_host"]["feedback_port"],
+        )
+    ):
+        raise RuntimeError(
+            "mod-host ports are open while the managed service is inactive; "
+            "stop the unmanaged/manual process before resetting"
+        )
+    if (
+        not statuses[units["mod_ui"]]["active"]
+        and deploy.mod_ui_port_is_open(
+            deployment["mod_ui"]["websocket_host"],
+            deployment["mod_ui"]["websocket_port"],
+        )
+    ):
+        raise RuntimeError(
+            "the mod-ui web port is open while its managed service is inactive; "
+            "stop the unmanaged/manual process before resetting"
+        )
+
+    roles = selected_roles(units, statuses)
+    if "mod_ui" in roles and "mod_ui" not in registry:
+        raise RuntimeError(
+            "mod-ui is enabled or active but not deployment-managed; refusing to reset "
+            "its pedalboard state"
+        )
+    timer_unit = units["reconcile_timer"]
+    restore_timer = statuses[timer_unit]["present"] and (
+        statuses[timer_unit]["active"] or statuses[timer_unit]["enabled"]
+    )
+
+    print("Stopping the reconciliation timer and Rigforge audio services.")
+    for unit in (units["reconcile_timer"], units["reconcile_service"]):
+        if statuses[unit]["present"]:
+            checked_command(["systemctl", "--user", "stop", unit], runner)
+
+    stop_order = (
+        "slweb",
+        "midi_bridge",
+        "mod_ui",
+        "mod_host",
+        "sooperlooper",
+        "ports",
+        "filter_chain",
+    )
+    for role in stop_order:
+        if role in roles:
+            checked_command(["systemctl", "--user", "stop", units[role]], runner)
+
+    if "mod_ui" in registry:
+        print("Restoring the generated mod-ui pedalboard; existing board state is backed up.")
+        deploy.reset_mod_ui_reference(
+            deployment["mod_ui"], registry, manage_services=False
+        )
+    else:
+        print("mod-ui is not managed by Rigforge; skipping pedalboard-file reset.")
+
+    print("Restarting PipeWire, then bringing WirePlumber back on its graph.")
+    checked_command(["systemctl", "--user", "stop", WIREPLUMBER_UNIT], runner)
+    checked_command(["systemctl", "--user", "restart", PIPEWIRE_UNIT], runner)
+    checked_command(["systemctl", "--user", "is-active", "--quiet", PIPEWIRE_UNIT], runner)
+    checked_command(["systemctl", "--user", "start", WIREPLUMBER_UNIT], runner)
+    checked_command(["systemctl", "--user", "is-active", "--quiet", WIREPLUMBER_UNIT], runner)
+
+    quantum_unit = units["quantum"]
+    quantum_status = statuses[quantum_unit]
+    if quantum_status["present"] and (
+        quantum_status["active"] or quantum_status["enabled"]
+    ):
+        checked_command(["systemctl", "--user", "start", quantum_unit], runner)
+
+    start_order = (
+        "filter_chain",
+        "ports",
+        "sooperlooper",
+        "mod_host",
+        "mod_ui",
+        "midi_bridge",
+        "slweb",
+    )
+    print("Starting enabled or previously active Rigforge services in dependency order.")
+    for role in start_order:
+        if role in roles:
+            checked_command(["systemctl", "--user", "start", units[role]], runner)
+
+    observer = ROOT / deployment["reconcile"]["observer_script"]
+    python = sys.executable
+    print("Rebuilding the declared PipeWire links.")
+    checked_command(
+        [
+            python,
+            str(observer),
+            "--state",
+            str(ROOT / "config" / "desired-state.yaml"),
+            "--reconcile-once",
+        ],
+        runner,
+    )
+    print("Checking the resulting PipeWire graph.")
+    graph_report = checked_command(
+        [python, str(observer), "--state", str(ROOT / "config" / "desired-state.yaml")],
+        runner,
+    )
+    try:
+        differences = json.loads(graph_report.stdout)["differences"]
+    except (json.JSONDecodeError, KeyError, TypeError) as error:
+        raise RuntimeError(
+            f"could not validate the final PipeWire graph report: {error}"
+        ) from error
+    if differences:
+        raise RuntimeError(
+            "the final PipeWire graph still differs from desired state: "
+            + json.dumps(differences, sort_keys=True)
+        )
+
+    for role in start_order:
+        if role in roles:
+            checked_command(
+                ["systemctl", "--user", "is-active", "--quiet", units[role]], runner
+            )
+
+    if restore_timer:
+        checked_command(["systemctl", "--user", "start", timer_unit], runner)
+        checked_command(["systemctl", "--user", "is-active", "--quiet", timer_unit], runner)
+    print("Rigforge engine reset completed.")
+
+
+def confirm_reset(yes):
+    print(
+        "WARNING: this interrupts audio, restarts PipeWire and WirePlumber, "
+        "and restarts enabled Rigforge audio services. In-memory SooperLooper "
+        "recordings may be lost. The current mod-ui board and last state will "
+        "be backed up before restoring the generated reference board."
+    )
+    if yes:
+        return True
+    if not sys.stdin.isatty():
+        print("Refusing non-interactive reset without --yes.", file=sys.stderr)
+        return False
+    return input("Continue with full engine reset? [y/N] ").strip().lower() in {
+        "y",
+        "yes",
+    }
+
+
+def main(argv=None):
+    parser = argparse.ArgumentParser(
+        description="Fully restart Rigforge's PipeWire audio engine and managed services."
+    )
+    parser.add_argument(
+        "--yes",
+        action="store_true",
+        help="skip the interactive confirmation prompt",
+    )
+    args = parser.parse_args(argv)
+
+    try:
+        state = load_state()
+        target = state["system"]["target"]["hostname"]
+        actual_host = socket.gethostname().split(".", 1)[0]
+        if actual_host != target:
+            raise RuntimeError(
+                f"refusing to reset on host {actual_host!r}; desired-state target is {target!r}"
+            )
+        deployment = deploy.load_deployment()
+        registry = deploy.read_registry()
+        if not confirm_reset(args.yes):
+            return 1
+        reset_engine(deployment, registry)
+    except (
+        OSError,
+        RuntimeError,
+        ValueError,
+        KeyError,
+        yaml.YAMLError,
+        subprocess.CalledProcessError,
+    ) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        print(
+            "Reset did not complete. The reconciliation timer may remain stopped; "
+            "inspect user-service status and journals before restarting it.",
+            file=sys.stderr,
+        )
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 16 - 0
tests/test_deploy.py

@@ -1060,6 +1060,22 @@ class DeploymentTests(unittest.TestCase):
             ],
         )
 
+    def test_mod_ui_reset_can_restore_board_without_managing_service_lifecycle(self):
+        registry = {
+            "mod_host_ports": {},
+            "mod_host": {},
+        }
+        config = deploy.load_deployment()["mod_ui"]
+        deploy.deploy_mod_ui("install", config, registry)
+        registry = deploy.read_registry()
+        self.commands.clear()
+
+        deploy.reset_mod_ui_reference(config, registry, manage_services=False)
+
+        self.assertEqual(self.commands, [])
+        board = self.home / config["pedalboards_directory"] / "default.pedalboard"
+        self.assertTrue((board / "rigforge-guitar.ttl").is_file())
+
     def test_mod_host_install_refuses_an_existing_control_socket(self):
         self.install_mod_host_ports_prerequisite()
         with patch.object(deploy, "mod_host_port_is_open", return_value=True):

+ 239 - 0
tests/test_reset_engine.py

@@ -0,0 +1,239 @@
+import json
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+import deploy
+import reset_engine
+
+
+class FakeSystemd:
+    def __init__(self, units, observer_result=0, final_differences=None):
+        self.units = {
+            name: {
+                "present": True,
+                "active": active,
+                "enabled": enabled,
+            }
+            for name, active, enabled in units
+        }
+        self.commands = []
+        self.observer_result = observer_result
+        self.final_differences = final_differences or []
+
+    def __call__(self, command, check=False, capture_output=False, text=False):
+        self.commands.append(command)
+        if command[:3] == ["systemctl", "--user", "show"]:
+            unit = command[-1]
+            state = self.units.get(unit, {"present": False})
+            output = "loaded\n" if state["present"] else "not-found\n"
+            return subprocess.CompletedProcess(command, 0, output, "")
+        if command[:3] == ["systemctl", "--user", "is-active"]:
+            active = self.units.get(command[-1], {}).get("active", False)
+            return subprocess.CompletedProcess(command, 0 if active else 3, "", "")
+        if command[:3] == ["systemctl", "--user", "is-enabled"]:
+            enabled = self.units.get(command[-1], {}).get("enabled", False)
+            return subprocess.CompletedProcess(command, 0 if enabled else 1, "", "")
+        if command[:3] == ["systemctl", "--user", "stop"]:
+            self.units.setdefault(command[-1], {})["active"] = False
+            return subprocess.CompletedProcess(command, 0, "", "")
+        if command[:3] == ["systemctl", "--user", "start"]:
+            self.units.setdefault(command[-1], {})["active"] = True
+            return subprocess.CompletedProcess(command, 0, "", "")
+        if command[:3] == ["systemctl", "--user", "restart"]:
+            self.units.setdefault(command[-1], {})["active"] = True
+            return subprocess.CompletedProcess(command, 0, "", "")
+        if command and command[0] == sys.executable:
+            is_reconcile = "--reconcile-once" in command
+            return subprocess.CompletedProcess(
+                command,
+                self.observer_result if is_reconcile else 0,
+                (
+                    '{"differences": []}\n'
+                    if is_reconcile
+                    else json.dumps({"differences": self.final_differences}) + "\n"
+                ),
+                "",
+            )
+        return subprocess.CompletedProcess(command, 0, "", "")
+
+
+class ResetEngineTests(unittest.TestCase):
+    def setUp(self):
+        self.deployment = deploy.load_deployment()
+        patch.object(deploy, "mod_host_port_is_open", return_value=False).start()
+        patch.object(deploy, "mod_ui_port_is_open", return_value=False).start()
+        self.addCleanup(patch.stopall)
+        self.registry = {}
+
+    def all_engine_units(self, timer_active=True):
+        units = [
+            ("pipewire.service", True, True),
+            ("wireplumber.service", True, True),
+            ("filter-chain.service", True, True),
+            ("rigforge-pipewire-quantum.service", True, True),
+            ("rigforge-mod-host-ports.service", True, True),
+            ("rigforge-mod-host.service", True, True),
+            ("rigforge-mod-ui.service", True, True),
+            ("rigforge-midi-bridge.service", True, True),
+            ("rigforge-sooperlooper.service", True, True),
+            ("rigforge-slweb.service", True, True),
+            ("rigforge-pipewire-reconcile.service", False, False),
+            ("rigforge-pipewire-reconcile.timer", timer_active, True),
+        ]
+        return units
+
+    def test_resets_services_in_order_restores_pedalboard_and_timer(self):
+        runner = FakeSystemd(self.all_engine_units())
+        with patch.object(reset_engine.deploy, "reset_mod_ui_reference") as reset_board:
+            reset_engine.reset_engine(
+                self.deployment, {"mod_ui": {}}, runner=runner
+            )
+
+        commands = runner.commands
+        stop_timer = commands.index(
+            ["systemctl", "--user", "stop", "rigforge-pipewire-reconcile.timer"]
+        )
+        stop_slweb = commands.index(
+            ["systemctl", "--user", "stop", "rigforge-slweb.service"]
+        )
+        stop_wireplumber = commands.index(
+            ["systemctl", "--user", "stop", "wireplumber.service"]
+        )
+        restart_pipewire = commands.index(
+            ["systemctl", "--user", "restart", "pipewire.service"]
+        )
+        start_wireplumber = commands.index(
+            ["systemctl", "--user", "start", "wireplumber.service"]
+        )
+        start_filter_chain = commands.index(
+            ["systemctl", "--user", "start", "filter-chain.service"]
+        )
+        start_ports = commands.index(
+            ["systemctl", "--user", "start", "rigforge-mod-host-ports.service"]
+        )
+        start_looper = commands.index(
+            ["systemctl", "--user", "start", "rigforge-sooperlooper.service"]
+        )
+        start_mod_host = commands.index(
+            ["systemctl", "--user", "start", "rigforge-mod-host.service"]
+        )
+        start_mod_ui = commands.index(
+            ["systemctl", "--user", "start", "rigforge-mod-ui.service"]
+        )
+        start_midi = commands.index(
+            ["systemctl", "--user", "start", "rigforge-midi-bridge.service"]
+        )
+        reconcile = next(
+            index for index, command in enumerate(commands)
+            if command and command[0] == sys.executable and "--reconcile-once" in command
+        )
+        start_timer = commands.index(
+            ["systemctl", "--user", "start", "rigforge-pipewire-reconcile.timer"]
+        )
+
+        self.assertLess(stop_timer, stop_slweb)
+        self.assertLess(stop_wireplumber, restart_pipewire)
+        self.assertLess(restart_pipewire, start_wireplumber)
+        self.assertLess(start_wireplumber, start_filter_chain)
+        self.assertLess(start_filter_chain, start_ports)
+        self.assertLess(start_ports, start_looper)
+        self.assertLess(start_looper, start_mod_host)
+        self.assertLess(start_mod_host, start_mod_ui)
+        self.assertLess(start_mod_ui, start_midi)
+        self.assertLess(start_midi, reconcile)
+        self.assertLess(reconcile, start_timer)
+        reset_board.assert_called_once_with(
+            self.deployment["mod_ui"], {"mod_ui": {}}, manage_services=False
+        )
+        self.assertFalse(any("disable" in command for command in commands))
+
+    def test_fails_without_resuming_reconciliation_if_graph_repair_fails(self):
+        runner = FakeSystemd(self.all_engine_units(), observer_result=1)
+        with patch.object(reset_engine.deploy, "reset_mod_ui_reference"):
+            with self.assertRaisesRegex(RuntimeError, "command failed"):
+                reset_engine.reset_engine(
+                    self.deployment, {"mod_ui": {}}, runner=runner
+                )
+
+        self.assertFalse(
+            any(
+                command == [
+                    "systemctl",
+                    "--user",
+                    "start",
+                    "rigforge-pipewire-reconcile.timer",
+                ]
+                for command in runner.commands
+            )
+        )
+
+    def test_fails_if_read_only_post_check_reports_graph_differences(self):
+        runner = FakeSystemd(
+            self.all_engine_units(),
+            final_differences=[{"kind": "missing", "from": "a", "to": "b"}],
+        )
+        with patch.object(reset_engine.deploy, "reset_mod_ui_reference"):
+            with self.assertRaisesRegex(RuntimeError, "final PipeWire graph still differs"):
+                reset_engine.reset_engine(
+                    self.deployment, {"mod_ui": {}}, runner=runner
+                )
+
+        self.assertFalse(
+            any(
+                command == [
+                    "systemctl",
+                    "--user",
+                    "start",
+                    "rigforge-pipewire-reconcile.timer",
+                ]
+                for command in runner.commands
+            )
+        )
+
+    def test_only_enabled_or_active_services_are_restarted(self):
+        runner = FakeSystemd(
+            [
+                ("pipewire.service", True, True),
+                ("wireplumber.service", True, True),
+                ("filter-chain.service", False, False),
+                ("rigforge-pipewire-quantum.service", False, False),
+                ("rigforge-mod-host-ports.service", False, False),
+                ("rigforge-mod-host.service", False, False),
+                ("rigforge-mod-ui.service", False, False),
+                ("rigforge-midi-bridge.service", False, False),
+                ("rigforge-sooperlooper.service", False, False),
+                ("rigforge-slweb.service", False, False),
+                ("rigforge-pipewire-reconcile.service", False, False),
+                ("rigforge-pipewire-reconcile.timer", False, False),
+            ]
+        )
+        with patch.object(reset_engine.deploy, "reset_mod_ui_reference"):
+            reset_engine.reset_engine(self.deployment, {}, runner=runner)
+        self.assertIn(
+            ["systemctl", "--user", "restart", "pipewire.service"], runner.commands
+        )
+        self.assertFalse(
+            any(
+                command[:3] == ["systemctl", "--user", "start"]
+                and command[-1].startswith("rigforge-")
+                for command in runner.commands
+            )
+        )
+
+    def test_refuses_to_reset_an_unmanaged_active_mod_ui(self):
+        runner = FakeSystemd(self.all_engine_units())
+        with self.assertRaisesRegex(RuntimeError, "not deployment-managed"):
+            reset_engine.reset_engine(self.deployment, {}, runner=runner)
+        self.assertFalse(
+            any(command[:3] == ["systemctl", "--user", "stop"] for command in runner.commands)
+        )
+
+
+if __name__ == "__main__":
+    unittest.main()