Просмотр исходного кода

better handle pipewire restart

Johan Le Baut 2 недель назад
Родитель
Сommit
4aba1be0d0

+ 1 - 0
AGENTS.md

@@ -13,6 +13,7 @@ The current target is Debian GNU/Linux 13 on AArch64 with a Behringer UMC404HD 1
 - `scripts/validate_desired_state.py` checks the YAML's four-source/physical-input model, single four-channel looper, source-to-channel assignments, mix declaration, and prohibition on routing looper returns back to looper inputs.
 - `scripts/observe_pipewire.py` validates the state and managed endpoint declarations, reads `pw-link -l`, and compares observed links against explicitly managed ports and links. Without `--reconcile-once`, it is read-only; one-shot reconciliation and the separately deployed timer create only declared missing links and remove only declared stale links.
 - `scripts/configure_mod_host.py` loads the YAML-declared NAM and LSP IR instances and guitar links for the user service `config/systemd/user/rigforge-mod-host.service.in`.
+- `scripts/wait_mod_host_ports.py` waits for declared hardware and mixer endpoints before the mod-host process starts, avoiding startup races after PipeWire restarts.
 - `config/systemd/user/rigforge-pipewire-reconcile.service.in` and `.timer.in` define periodic reconciliation for the whole YAML-managed graph.
 - `scripts/deploy.sh` dispatches scoped user-level install/uninstall/reload actions for YAML-declared PipeWire, LV2 bundles, the mod-host service, and the separate graph-reconcile timer through `scripts/deploy.py`. `mod-host` and `reconcile` are explicit targets, not part of `all`.
 - `tests/` contains Python `unittest` tests for state validation, observation/reconciliation, mixer configuration, mod-host startup configuration, and simulated deployment operations. These validate repository-level invariants, not live audio behavior.

+ 8 - 4
README.md

@@ -126,7 +126,7 @@ For LSP and Dragonfly Reverb, the YAML declares tags and release URLs, and the i
 
 `install mod-host` is an explicit target and is deliberately not included in `install all`: it activates the guitar processing chain. It requires the ARM64 artifact under `artifacts/mod-host/arm64/current/`, the NAM and LSP bundles already installed, the tracked `amp_emul/` assets, and the runtime packages in the target preparation list. It installs and enables only the `systemd --user` mod-host service; it does not use `sudo` or directly restart PipeWire/WirePlumber. The unit refers to the repository checkout from which `deploy.sh` was run, so keep that checkout at that path or uninstall/reinstall after moving it.
 
-At service startup, `scripts/configure_mod_host.py` waits for the control socket, loads the declared NAM and LSP mono-IR instances, sets their model/IR paths and the conservative NAM output level, then creates the PipeWire links. The desired chain is capture AUX0 → `Vox_AC15CH_Crunch_TB.nam` → `VOX_AC30_1964_celestion.wav` → guitar mixer input AUX0. The direct capture-to-mixer bypass is removed. Review the model and IR redistribution terms before using these assets in a public image or package.
+Before starting mod-host, `scripts/wait_mod_host_ports.py` waits up to 45 seconds for the guitar capture, mixer input, and hardware playback ports. This avoids launching `pw-jack` while PipeWire's hardware ports are still appearing after a service restart. Then `scripts/configure_mod_host.py` waits for the control socket, loads the declared NAM and LSP mono-IR instances, sets their model/IR paths and the conservative NAM output level, then creates the PipeWire links. The desired chain is capture AUX0 → `Vox_AC15CH_Crunch_TB.nam` → `VOX_AC30_1964_celestion.wav` → guitar mixer input AUX0. The direct capture-to-mixer bypass is removed. Review the model and IR redistribution terms before using these assets in a public image or package.
 
 `reload mod-host` restarts the service and rebuilds the plugin graph, briefly interrupting the processed guitar path. `PartOf=` couples mod-host restarts to PipeWire, WirePlumber, and `filter-chain.service` restarts; its startup configurator then rebuilds the NAM/IR chain. The mod-host control socket uses TCP port 5555 and this build listens on `0.0.0.0` without authentication. This is retained for the current test by owner request and must be restricted before treating the setup as hardened.
 
@@ -172,16 +172,20 @@ SooperLooper's tagged source does not define ARM64 atomics in `libs/pbd/pbd/atom
 
 The filter-chain fragment is installed in the user configuration on `rigforge`, and `filter-chain.service` was restarted to load it. The user confirmed guitar and microphone are audible together through the filter. The guitar now has a tested NAM → cabinet-IR chain before mixer AUX0; the owner reported a pleasing crunch and no crackle during the initial listening test. The direct guitar bypass link is absent while the mod-host chain is connected. This is not a sustained load, dropout, headroom, or unattended-startup test. A brief mod-host CPU-load reading was about 42%; one `pw-top` snapshot showed no reported errors but does not establish stability.
 
-The next target checks are:
+The graph-wide `rigforge-pipewire-reconcile.timer` was subsequently enabled on the target. On 2026-11-20, its logs showed the UMC ports disappear during unplug and the missing AUX0/AUX2/playback links were requested again after reconnect; the final observer was clean. This verifies topology recovery in that test, not audible recovery or a signal-quality check.
+
+A PipeWire restart on the same date propagated to mod-host through `PartOf=`, but the first mod-host launch failed with `no jack playback ports`. A later systemd retry started mod-host and configured the NAM/IR chain; subsequent reconciliation runs were clean. This demonstrates eventual recovery with a startup race and an audio interruption. `scripts/wait_mod_host_ports.py` has since been added locally to wait for hardware/mixer ports before launching mod-host; that guard is not yet deployed or target-verified.
+
+The remaining target checks are:
 
 1. The read-only observer and one-shot repair have been tested on `rigforge`. Repairing one missing link restored the audible microphone path; after a later filter-chain service restart, reconciliation requested all three missing links and the observer reported no differences. The observer now also tracks the three guitar NAM/cabinet links. Do not run one-shot reconciliation against an older checkout: it could restore the dry guitar bypass.
 2. Later, test inputs 2 and 4 with sources when available; they are included in the mixer but not verified with instruments.
 3. Measure sustained stability and headroom at 48 kHz / 128 frames with all active sources; the current `ERR = 0` observation was brief.
-4. Verify the `rigforge-mod-host.service` and reconciliation timer on the target, including reboot with lingering enabled, PipeWire/service restart propagation, USB unplug/replug recovery, resource limits, and recovery when an LV2 plugin fails to load.
+4. Re-test mod-host startup after installing the new port-readiness guard, then verify reboot with lingering enabled, startup resource limits, and recovery when an LV2 plugin fails to load.
 5. Verify FCB1010 MIDI messages and the supplied bindings with the eventual SooperLooper build. Verify OSC port readiness and the effect and persistence of `discrete_prefader 0` separately.
 
 Do not treat planned packages, commands, ports, or service settings as target-validated until these checks have been performed.
 
 ## Deployment and rollback
 
-Deployment is manual: inspect and test a change, then use `git pull` on `rigforge` only when the change is ready. No CI/CD or auto-pull is configured. The mod-host service unit and deploy commands are now declared in the repository, but installation/activation, logs, diagnostics, and rollback remain unverified on the target. Keep the last known working revision available; do not apply unverified audio or service changes during live use.
+Deployment is manual: inspect and test a change, then use `git pull` on `rigforge` only when the change is ready. No CI/CD or auto-pull is configured. The mod-host service and separate reconciliation timer have been installed on the target; the new mod-host port-readiness guard and its updated service template remain local and unverified there. Keep the last known working revision available; do not apply unverified audio or service changes during live use.

+ 2 - 0
config/desired-state.yaml

@@ -64,6 +64,8 @@ deployment:
     service_destination: .config/systemd/user/rigforge-mod-host.service
     user_service: rigforge-mod-host.service
     configure_script: scripts/configure_mod_host.py
+    readiness_script: scripts/wait_mod_host_ports.py
+    port_wait_timeout_seconds: 45
     socket_port: 5555
     pw_jack_path: /usr/bin/pw-jack
     python_path: /usr/bin/python3

+ 2 - 1
config/systemd/user/rigforge-mod-host.service.in

@@ -6,11 +6,12 @@ PartOf=pipewire.service wireplumber.service filter-chain.service
 
 [Service]
 Type=simple
+ExecStartPre=@PYTHON@ @READINESS_SCRIPT@ --state @DESIRED_STATE@ --timeout @PORT_WAIT_TIMEOUT_SECONDS@
 ExecStart=@PW_JACK@ @MOD_HOST_BINARY@ -n -p @SOCKET_PORT@
 ExecStartPost=@PYTHON@ @CONFIGURE_SCRIPT@ --state @DESIRED_STATE@ --repo-root @REPOSITORY_ROOT@
 Restart=on-failure
 RestartSec=5
-TimeoutStartSec=60
+TimeoutStartSec=90
 TimeoutStopSec=10
 
 [Install]

+ 7 - 1
scripts/deploy.py

@@ -804,6 +804,7 @@ def render_mod_host_service(config):
     binary = ROOT / config["binary_source"]
     service_template = ROOT / config["service_source"]
     configure_script = ROOT / config["configure_script"]
+    readiness_script = ROOT / config["readiness_script"]
     state_file = ROOT / "config" / "desired-state.yaml"
     if not binary.is_file() or not os.access(binary, os.X_OK):
         raise RuntimeError(f"ARM64 mod-host artifact is missing or not executable: {binary}")
@@ -811,11 +812,15 @@ def render_mod_host_service(config):
         raise RuntimeError(f"mod-host service template is missing: {service_template}")
     if not configure_script.is_file():
         raise RuntimeError(f"mod-host startup configurator is missing: {configure_script}")
+    if not readiness_script.is_file():
+        raise RuntimeError(f"mod-host PipeWire readiness checker is missing: {readiness_script}")
     replacements = {
         "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
         "@MOD_HOST_BINARY@": systemd_quote(binary.resolve()),
         "@SOCKET_PORT@": str(config["socket_port"]),
         "@PYTHON@": systemd_quote(config["python_path"]),
+        "@READINESS_SCRIPT@": systemd_quote(readiness_script.resolve()),
+        "@PORT_WAIT_TIMEOUT_SECONDS@": str(config["port_wait_timeout_seconds"]),
         "@CONFIGURE_SCRIPT@": systemd_quote(configure_script.resolve()),
         "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
         "@REPOSITORY_ROOT@": systemd_quote(ROOT.resolve()),
@@ -1119,13 +1124,14 @@ def deploy_reconcile(action, config, registry):
 def mod_host_runtime_digest(config):
     state_path = ROOT / "config" / "desired-state.yaml"
     script_path = ROOT / config["configure_script"]
+    readiness_script = ROOT / config["readiness_script"]
     validator_path = ROOT / "scripts" / "validate_desired_state.py"
     binary_path = ROOT / config["binary_source"]
     with state_path.open(encoding="utf-8") as stream:
         state = yaml.safe_load(stream)
     guitar_chain = state["routing"]["mod_host_chains"]["guitar"]
     mod_host_config = state["deployment"]["mod_host"]
-    files = [script_path, validator_path, binary_path]
+    files = [script_path, readiness_script, validator_path, binary_path]
     for processor in guitar_chain["processors"]:
         asset_path = PurePosixPath(processor["asset_path"])
         if asset_path.is_absolute() or ".." in asset_path.parts:

+ 10 - 0
scripts/validate_desired_state.py

@@ -373,6 +373,7 @@ def validate_state(state):
                 ("service_destination", ".config/systemd/user/rigforge-mod-host.service"),
                 ("user_service", "rigforge-mod-host.service"),
                 ("configure_script", "scripts/configure_mod_host.py"),
+                ("readiness_script", "scripts/wait_mod_host_ports.py"),
                 ("pw_jack_path", "/usr/bin/pw-jack"),
                 ("python_path", "/usr/bin/python3"),
             ):
@@ -385,6 +386,15 @@ def validate_state(state):
                 or not 1 <= socket_port <= 65535
             ):
                 errors.append("deployment.mod_host.socket_port must be a valid TCP port")
+            port_wait_timeout = mod_host.get("port_wait_timeout_seconds")
+            if (
+                not isinstance(port_wait_timeout, int)
+                or isinstance(port_wait_timeout, bool)
+                or not 5 <= port_wait_timeout <= 300
+            ):
+                errors.append(
+                    "deployment.mod_host.port_wait_timeout_seconds must be between 5 and 300"
+                )
 
         reconcile = deployment.get("reconcile")
         if not isinstance(reconcile, dict):

+ 112 - 0
scripts/wait_mod_host_ports.py

@@ -0,0 +1,112 @@
+import argparse
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import yaml
+
+from validate_desired_state import validate_state
+
+
+def required_ports(state):
+    routing = state["routing"]
+    chain = routing["mod_host_chains"]["guitar"]
+    mix = routing["mix"]
+    return (
+        {chain["source_port"]},
+        {chain["mix_input"], mix["output_port"]},
+    )
+
+
+def list_ports(direction, runner):
+    result = runner(
+        ["pw-link", direction],
+        check=True,
+        capture_output=True,
+        text=True,
+        timeout=2,
+    )
+    return {line.strip() for line in result.stdout.splitlines() if line.strip()}
+
+
+def wait_for_required_ports(
+    state,
+    timeout,
+    runner=subprocess.run,
+    sleeper=time.sleep,
+    clock=time.monotonic,
+):
+    required_outputs, required_inputs = required_ports(state)
+    deadline = clock() + timeout
+    last_error = None
+
+    while True:
+        try:
+            outputs = list_ports("-o", runner)
+            inputs = list_ports("-i", runner)
+            last_error = None
+            missing_outputs = required_outputs - outputs
+            missing_inputs = required_inputs - inputs
+            if not missing_outputs and not missing_inputs:
+                return
+        except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
+            last_error = str(error)
+            missing_outputs = required_outputs
+            missing_inputs = required_inputs
+
+        if clock() >= deadline:
+            details = (
+                f"missing outputs={sorted(missing_outputs)}, "
+                f"missing inputs={sorted(missing_inputs)}"
+            )
+            if last_error:
+                details += f"; last pw-link error: {last_error}"
+            raise RuntimeError(
+                "PipeWire ports required by mod-host did not become ready before "
+                f"the {timeout}s timeout ({details})"
+            )
+        sleeper(min(0.5, max(0.0, deadline - clock())))
+
+
+def main(argv=None):
+    root = Path(__file__).resolve().parents[1]
+    parser = argparse.ArgumentParser(
+        description="Wait until PipeWire exposes the hardware and mixer ports mod-host needs."
+    )
+    parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
+    parser.add_argument("--timeout", type=float)
+    args = parser.parse_args(argv)
+
+    try:
+        with args.state.open(encoding="utf-8") as stream:
+            state = yaml.safe_load(stream)
+        errors = validate_state(state)
+        if errors:
+            raise ValueError("invalid desired state: " + "; ".join(errors))
+        timeout = (
+            args.timeout
+            if args.timeout is not None
+            else state["deployment"]["mod_host"]["port_wait_timeout_seconds"]
+        )
+        if timeout <= 0:
+            raise ValueError("--timeout must be positive")
+        wait_for_required_ports(state, timeout)
+    except (
+        OSError,
+        RuntimeError,
+        ValueError,
+        TypeError,
+        KeyError,
+        yaml.YAMLError,
+        subprocess.CalledProcessError,
+    ) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 1
+
+    print("Required PipeWire ports are ready for mod-host.")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 4 - 0
tests/test_deploy.py

@@ -218,6 +218,10 @@ class DeploymentTests(unittest.TestCase):
         self.assertIn("WantedBy=default.target", content)
         self.assertIn("After=pipewire.service wireplumber.service filter-chain.service", content)
         self.assertIn("PartOf=pipewire.service wireplumber.service filter-chain.service", content)
+        self.assertIn("ExecStartPre=", content)
+        self.assertIn("wait_mod_host_ports.py", content)
+        self.assertIn("--timeout 45", content)
+        self.assertIn("TimeoutStartSec=90", content)
         self.assertIn("-n -p 5555", content)
         self.assertIn("configure_mod_host.py", content)
         self.assertEqual(

+ 7 - 0
tests/test_desired_state.py

@@ -161,6 +161,13 @@ class DesiredStateValidationTests(unittest.TestCase):
         state["deployment"]["mod_host"]["socket_port"] = 70000
         self.assertIn("deployment.mod_host.socket_port must be a valid TCP port", validate_state(state))
 
+        state = copy.deepcopy(self.state)
+        state["deployment"]["mod_host"]["port_wait_timeout_seconds"] = 500
+        self.assertIn(
+            "deployment.mod_host.port_wait_timeout_seconds must be between 5 and 300",
+            validate_state(state),
+        )
+
         state = copy.deepcopy(self.state)
         self.assertEqual(
             state["deployment"]["reconcile"]["user_timer"],

+ 70 - 0
tests/test_wait_mod_host_ports.py

@@ -0,0 +1,70 @@
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+from wait_mod_host_ports import required_ports, wait_for_required_ports
+
+
+class ModHostPortReadinessTests(unittest.TestCase):
+    @classmethod
+    def setUpClass(cls):
+        with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
+            cls.state = yaml.safe_load(stream)
+
+    def test_waits_until_hardware_and_mixer_ports_are_available(self):
+        required_outputs, required_inputs = required_ports(self.state)
+        now = [0.0]
+        snapshots = [0]
+
+        def runner(command, **_kwargs):
+            if command == ["pw-link", "-o"]:
+                snapshots[0] += 1
+                return SimpleNamespace(stdout="\n".join(sorted(required_outputs)) + "\n")
+            if command == ["pw-link", "-i"]:
+                ports = required_inputs if snapshots[0] >= 2 else set()
+                return SimpleNamespace(stdout="\n".join(sorted(ports)) + "\n")
+            self.fail(f"unexpected command: {command}")
+
+        wait_for_required_ports(
+            self.state,
+            timeout=2,
+            runner=runner,
+            sleeper=lambda duration: now.__setitem__(0, now[0] + duration),
+            clock=lambda: now[0],
+        )
+
+        self.assertEqual(snapshots[0], 2)
+
+    def test_timeout_names_missing_output_and_input_ports(self):
+        now = [0.0]
+
+        def runner(_command, **_kwargs):
+            return SimpleNamespace(stdout="")
+
+        with self.assertRaisesRegex(RuntimeError, "missing outputs=.*capture_AUX0"):
+            wait_for_required_ports(
+                self.state,
+                timeout=1,
+                runner=runner,
+                sleeper=lambda duration: now.__setitem__(0, now[0] + duration),
+                clock=lambda: now[0],
+            )
+
+        with self.assertRaisesRegex(RuntimeError, "missing inputs=.*playback_AUX0"):
+            wait_for_required_ports(
+                self.state,
+                timeout=0,
+                runner=runner,
+                sleeper=lambda _duration: None,
+                clock=lambda: 1,
+            )
+
+
+if __name__ == "__main__":
+    unittest.main()