Johan Le Baut 1 неделя назад
Родитель
Сommit
6a674e6e00

+ 2 - 2
README.md

@@ -43,7 +43,7 @@ This records the preparation already performed on `rigforge` and is a starting p
 - `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, pedalboard generation, MIDI WebSocket control, the mod-ui/PipeWire boundary bridge, and deployment operations.
 - `artifacts/sooperlooper/arm64/`, `artifacts/mod-host/arm64/`, and `artifacts/mod-ui/arm64/`: generated binaries or runtime bundle, dependency reports, and build provenance; commit after reviewing licensing and repository size.
 
-The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. This runtime value has not yet been made persistent or measured under sustained load; apply it temporarily on the target with `pw-metadata -n settings 0 clock.force-quantum 128` and return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. The target has the working one-channel guitar NAM→IR setup and MIDI model switching. The proposed four-channel mod-ui boundaries described below are a local desired-state change and have not been deployed or tested on the target. Sustained stability, levels, and recovery after a restart still need verification.
+The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. The PipeWire deployment installs a user unit that reapplies this declared runtime quantum whenever `pipewire.service` starts or restarts. This unit is installed on the current target, but its behavior on a subsequent engine restart and sustained stability still need verification. To apply it manually, use `pw-metadata -n settings 0 clock.force-quantum 128`; return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. The target has the working one-channel guitar NAM→IR setup and MIDI model switching. The proposed four-channel mod-ui boundaries described below are a local desired-state change and have not been deployed or tested on the target. Sustained stability, levels, and recovery after a restart still need verification.
 
 Validate the desired-state file on the development PC with:
 
@@ -123,7 +123,7 @@ After a manual `git pull --ff-only`, run the deploy helper from any directory:
 
 The helper accepts `install|uninstall|reload` plus `reset mod-ui`, and targets `all|namlv2|lsp|dragonfly-reverb|pipewire|mod-host-ports|mod-host|mod-ui|reconcile|midi-bridge|sooperlooper|slweb`. `all` deliberately excludes the audio-host/UI/MIDI services, reconciliation, and SooperLooper services, which are opt-in. Install in dependency order: ports, mod-host, then mod-ui; the MIDI bridge follows mod-ui. Install SooperLooper before SLWeb. The ports service requires `/usr/bin/pw-loopback` from the target PipeWire tools; verify it exists before installation. It reads versions, paths, URLs, and settings from `config/desired-state.yaml`; its deployment registry is stored under `~/.local/state/rigforge/`, and any pre-existing unit backup is stored next to that unit. It does not use `sudo` or change files outside declared paths, adjacent backups, the dedicated mod-ui and SLWeb user-data directories, and the registry directory.
 
-For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum as a runtime setting, and restarts `filter-chain.service` only when the fragment changes. It never restarts `pipewire.service` or WirePlumber. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This restart removes the filter-chain nodes and their graph links; the fragment recreates ports but not links. Reconciliation is a separate explicit target; installing `mod-host` alone does not install its timer. After a PipeWire/filter restart, inspect with `python3 scripts/observe_pipewire.py`. Uninstall removes only the unchanged managed fragment, restores a file that was present before the first install, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded. Runtime quantum is not persistent across a PipeWire daemon restart.
+For PipeWire, install updates only the Rigforge filter fragment, applies the declared quantum, and installs/enables `rigforge-pipewire-quantum.service`. That oneshot is ordered after and tied to `pipewire.service`, so the desired quantum is reapplied at engine startup/restart without restarting PipeWire or WirePlumber during deployment. `filter-chain.service` is restarted only when its fragment changes. `reload pipewire` reapplies the quantum and restarts the filter-chain user service. This filter-chain restart removes its nodes and graph links; the fragment recreates ports but not links. Reconciliation is a separate explicit target; installing `mod-host` alone does not install its timer. After a PipeWire/filter restart, inspect with `python3 scripts/observe_pipewire.py`. Uninstall removes only unchanged managed files, restores prior files, disables the quantum unit, returns quantum selection to automatic, and reloads the filter service. Local edits to managed files stop removal or replacement rather than being discarded.
 
 For NAM LV2, `install namlv2` installs the tracked ARM64 bundle at `artifacts/nam-lv2/arm64/current/neural_amp_modeler.lv2` under `~/.lv2/`, verifies its build provenance, and records artifact and installed-tree fingerprints. Build it with the `nam-lv2` task documented below. The pinned source remains v0.2.3; the Raspberry Pi 5 release archive is retained as source metadata but is not installed because its statically linked C++ runtime crashed while loading the declared A2 model on this target. The replacement is built with Debian 13's GCC and dynamically links the system `libstdc++` and `libgcc_s`. The original bundle is preserved outside Lilv's search path at `~/.local/state/rigforge/namlv2-backups/neural_amp_modeler.lv2.rigforge-backup`, so it cannot shadow the active plugin; `uninstall namlv2` restores it. Legacy adjacent backups are migrated there by `install namlv2`. `reload namlv2` does nothing; restart `mod-host` after installing or removing the plugin.
 

+ 6 - 2
config/desired-state.yaml

@@ -157,6 +157,10 @@ deployment:
     fragment_source: config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
     fragment_destination: .config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf
     user_service: filter-chain.service
+    quantum_service_source: config/systemd/user/rigforge-pipewire-quantum.service.in
+    quantum_service_destination: .config/systemd/user/rigforge-pipewire-quantum.service
+    quantum_user_service: rigforge-pipewire-quantum.service
+    pw_metadata_path: /usr/bin/pw-metadata
 
 modes:
   live:
@@ -406,8 +410,8 @@ routing:
 parameters:
   sample_rate_hz: 48000
   quantum_frames: 128
-  quantum_status: initial-target-value-tested-temporarily
-  quantum_apply_method: PipeWire clock.force-quantum runtime setting
+  quantum_status: startup-service-installed; engine-restart-and-sustained-stability-verification-pending
+  quantum_apply_method: PipeWire clock.force-quantum runtime setting reapplied on pipewire.service start
   audio_test_level: low
   reconciliation_mode: observe-only
 

+ 13 - 0
config/systemd/user/rigforge-pipewire-quantum.service.in

@@ -0,0 +1,13 @@
+[Unit]
+Description=Apply Rigforge's declared PipeWire quantum
+Requires=pipewire.service
+After=pipewire.service
+PartOf=pipewire.service
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=@PW_METADATA@ -n settings 0 clock.force-quantum @QUANTUM_FRAMES@
+
+[Install]
+WantedBy=pipewire.service

+ 52 - 0
scripts/deploy.py

@@ -86,6 +86,18 @@ def load_deployment():
         errors.append("PipeWire fragment destination is invalid")
     if pipewire.get("user_service") != "filter-chain.service":
         errors.append("PipeWire user service is invalid")
+    if pipewire.get("quantum_service_source") != (
+        "config/systemd/user/rigforge-pipewire-quantum.service.in"
+    ):
+        errors.append("PipeWire quantum service source is invalid")
+    if pipewire.get("quantum_service_destination") != (
+        ".config/systemd/user/rigforge-pipewire-quantum.service"
+    ):
+        errors.append("PipeWire quantum service destination is invalid")
+    if pipewire.get("quantum_user_service") != "rigforge-pipewire-quantum.service":
+        errors.append("PipeWire quantum user service is invalid")
+    if pipewire.get("pw_metadata_path") != "/usr/bin/pw-metadata":
+        errors.append("PipeWire metadata executable path is invalid")
     if errors:
         raise ValueError("; ".join(errors))
     return deployment
@@ -241,6 +253,38 @@ def apply_quantum(frames):
     run(["pw-metadata", "-n", "settings", "0", "clock.force-quantum", str(frames)])
 
 
+def render_pipewire_quantum_service(config, quantum_frames):
+    service_template = ROOT / config["quantum_service_source"]
+    if not service_template.is_file():
+        raise RuntimeError(f"PipeWire quantum service template is missing: {service_template}")
+    content = service_template.read_text(encoding="utf-8")
+    replacements = {
+        "@PW_METADATA@": systemd_quote(config["pw_metadata_path"]),
+        "@QUANTUM_FRAMES@": str(quantum_frames),
+    }
+    for placeholder, replacement in replacements.items():
+        content = content.replace(placeholder, replacement)
+    if re.search(r"@[A-Z_]+@", content):
+        raise RuntimeError("unexpanded placeholder remains in PipeWire quantum service template")
+    return {
+        "name": config["quantum_user_service"],
+        "destination": Path.home() / config["quantum_service_destination"],
+        "content": content.encode("utf-8"),
+    }
+
+
+def deploy_pipewire_quantum_service(action, config, quantum_frames, registry):
+    unit = render_pipewire_quantum_service(config, quantum_frames)
+    deploy_single_user_service(
+        action,
+        "pipewire_quantum",
+        "pipewire",
+        "PipeWire quantum",
+        unit,
+        registry,
+    )
+
+
 def restart_filter_service(service):
     run(["systemctl", "--user", "restart", service])
     run(["systemctl", "--user", "is-active", "--quiet", service])
@@ -263,6 +307,7 @@ def deploy_pipewire(action, config, registry, quantum_frames):
     if action == "reload":
         if not source.is_file() or not destination.is_file():
             raise RuntimeError("PipeWire reload requires both the repository fragment and installed fragment")
+        deploy_pipewire_quantum_service("install", config, quantum_frames, registry)
         apply_quantum(quantum_frames)
         restart_filter_service(config["user_service"])
         print("PipeWire runtime quantum applied; filter-chain user service restarted.")
@@ -309,11 +354,16 @@ def deploy_pipewire(action, config, registry, quantum_frames):
             managed.pop("pending_reload", None)
             registry["pipewire"] = managed
             write_registry(registry)
+        deploy_pipewire_quantum_service("install", config, quantum_frames, registry)
         print(f"PipeWire fragment {'updated' if changed else 'already current'} at {destination}.")
         return
 
     if action == "uninstall":
         if managed is None:
+            quantum_service_managed = registry.get("pipewire_quantum") is not None
+            deploy_pipewire_quantum_service("uninstall", config, quantum_frames, registry)
+            if quantum_service_managed:
+                apply_quantum(0)
             print("No managed PipeWire fragment to uninstall.")
             return
         if managed.get("pending_uninstall"):
@@ -343,6 +393,7 @@ def deploy_pipewire(action, config, registry, quantum_frames):
                 os.replace(backup_path, destination)
             elif backup_path is not None:
                 raise RuntimeError(f"recorded backup is missing: {backup_path}")
+            deploy_pipewire_quantum_service("uninstall", config, quantum_frames, registry)
             registry.pop("pipewire")
             write_registry(registry)
             apply_quantum(0)
@@ -361,6 +412,7 @@ def deploy_pipewire(action, config, registry, quantum_frames):
             backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
             if backup_digest != managed.get("backup_sha256"):
                 raise RuntimeError(f"recorded backup changed locally: {backup_path}")
+        deploy_pipewire_quantum_service("uninstall", config, quantum_frames, registry)
         managed["pending_uninstall"] = True
         registry["pipewire"] = managed
         write_registry(registry)

+ 64 - 8
tests/test_deploy.py

@@ -99,11 +99,7 @@ class DeploymentTests(unittest.TestCase):
                 deploy.deploy_lv2_archives("install", component, config, deploy.read_registry())
 
     def pipewire_config(self):
-        return {
-            "fragment_source": "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
-            "fragment_destination": ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf",
-            "user_service": "filter-chain.service",
-        }
+        return deploy.load_deployment()["pipewire"]
 
     def mod_host_config(self):
         return deploy.load_deployment()["mod_host"]
@@ -182,16 +178,56 @@ class DeploymentTests(unittest.TestCase):
                 ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"],
                 ["systemctl", "--user", "restart", "filter-chain.service"],
                 ["systemctl", "--user", "is-active", "--quiet", "filter-chain.service"],
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-pipewire-quantum.service"],
+                ["systemctl", "--user", "restart", "rigforge-pipewire-quantum.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-pipewire-quantum.service"],
             ],
         )
         self.commands.clear()
         deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
         self.assertEqual(
             self.commands,
-            [["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"]],
+            [
+                ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"],
+                ["systemctl", "--user", "daemon-reload"],
+                ["systemctl", "--user", "enable", "rigforge-pipewire-quantum.service"],
+                ["systemctl", "--user", "start", "rigforge-pipewire-quantum.service"],
+                ["systemctl", "--user", "is-active", "--quiet", "rigforge-pipewire-quantum.service"],
+            ],
         )
         self.assertFalse(any("pipewire.service" in command for command in self.commands))
 
+    def test_pipewire_quantum_service_reapplies_desired_value_after_engine_restart(self):
+        unit = deploy.render_pipewire_quantum_service(self.pipewire_config(), 128)
+        content = unit["content"].decode("utf-8")
+        self.assertIn("After=pipewire.service", content)
+        self.assertIn("PartOf=pipewire.service", content)
+        self.assertIn("RemainAfterExit=yes", content)
+        self.assertIn(
+            'ExecStart="/usr/bin/pw-metadata" -n settings 0 clock.force-quantum 128',
+            content,
+        )
+        self.assertIn("WantedBy=pipewire.service", content)
+
+    def test_pipewire_reload_updates_quantum_service_without_restarting_engine(self):
+        config = self.pipewire_config()
+        deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
+        self.commands.clear()
+
+        deploy.deploy_pipewire("reload", config, deploy.read_registry(), 128)
+
+        self.assertIn(
+            ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "128"],
+            self.commands,
+        )
+        self.assertIn(
+            ["systemctl", "--user", "restart", "filter-chain.service"],
+            self.commands,
+        )
+        self.assertFalse(any(command[:4] == ["systemctl", "--user", "restart", "pipewire.service"]
+                             for command in self.commands))
+
     def test_pipewire_uninstall_restores_previous_file(self):
         config = self.pipewire_config()
         destination = self.home / config["fragment_destination"]
@@ -201,9 +237,23 @@ class DeploymentTests(unittest.TestCase):
         self.commands.clear()
         deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
         self.assertEqual(destination.read_text(encoding="utf-8"), "previous config")
-        self.assertEqual(self.commands[0][-1], "0")
-        self.assertEqual(self.commands[1], ["systemctl", "--user", "restart", "filter-chain.service"])
+        self.assertEqual(
+            self.commands[:2],
+            [
+                ["systemctl", "--user", "disable", "--now", "rigforge-pipewire-quantum.service"],
+                ["systemctl", "--user", "daemon-reload"],
+            ],
+        )
+        self.assertIn(
+            ["pw-metadata", "-n", "settings", "0", "clock.force-quantum", "0"],
+            self.commands,
+        )
+        self.assertIn(
+            ["systemctl", "--user", "restart", "filter-chain.service"],
+            self.commands,
+        )
         self.assertNotIn("pipewire", deploy.read_registry())
+        self.assertNotIn("pipewire_quantum", deploy.read_registry())
         self.assertFalse(deploy.read_registry().get("pipewire_pending_reload"))
 
     def test_pipewire_pending_uninstall_recovers_after_prior_file_restored(self):
@@ -247,9 +297,15 @@ class DeploymentTests(unittest.TestCase):
         deploy.deploy_pipewire("install", config, deploy.read_registry(), 128)
         destination = self.home / config["fragment_destination"]
         destination.write_text("local edit", encoding="utf-8")
+        self.commands.clear()
         with self.assertRaisesRegex(RuntimeError, "changed locally"):
             deploy.deploy_pipewire("uninstall", config, deploy.read_registry(), 128)
         self.assertEqual(destination.read_text(encoding="utf-8"), "local edit")
+        self.assertNotIn(
+            ["systemctl", "--user", "disable", "--now", "rigforge-pipewire-quantum.service"],
+            self.commands,
+        )
+        self.assertIn("pipewire_quantum", deploy.read_registry())
 
     def test_mod_host_install_renders_and_activates_user_service(self):
         config = self.mod_host_config()