Ver Fonte

add link repair

Johan Le Baut há 2 semanas atrás
pai
commit
83fb0a79f6
4 ficheiros alterados com 233 adições e 3 exclusões
  1. 1 1
      AGENTS.md
  2. 9 1
      README.md
  3. 86 0
      scripts/observe_pipewire.py
  4. 137 1
      tests/test_pipewire_observer.py

+ 1 - 1
AGENTS.md

@@ -45,7 +45,7 @@ The observer invokes `pw-link -l` itself. It never creates or removes links. A c
 - The mix must declare an output and include looper returns. Looper returns must not feed any looper input; the explicit forbidden connection is policy documentation, not an active route.
 - A managed link's endpoints must both be declared in `routing.managed_ports`, and names must match the observer's approved endpoint pattern. Use concrete observed PipeWire ports rather than logical aliases.
 - Link status values used by the observer are `planned` and `observed`; both are compared against the current graph. Only declare real target observations as `observed`.
-- Keep reconciliation observe-only. Do not add automatic repair or alter target links as a side effect of validation or observation.
+- Keep observation as the default. Explicit `--reconcile-once` may create only declared missing links after confirming both ports exist; it must not remove links, alter unrelated connections, or restart services. Retain tests for simulated repair and post-check behavior.
 - Mixer gain `0.2` is an initial conservative value, not a calibrated level or clipping guarantee. Test summed sources and loop returns on hardware before live use.
 
 ## Working conventions and gotchas

+ 9 - 1
README.md

@@ -54,7 +54,15 @@ For an initial read-only graph observation on a system with `pw-link`, run:
 python3 scripts/observe_pipewire.py
 ```
 
-The observer reads `pw-link -l` and compares only connections whose endpoints are explicitly listed under `routing.managed_ports`; expected edges go in `routing.managed_links`. The current YAML lists the three tested guitar/microphone mixer links and only those exact observed UMC and filter-chain ports. WirePlumber's hardware links remain outside project management. The observer only reports missing or unexpected project links; it never creates or deletes links. No polling or automatic repair is enabled.
+The observer reads `pw-link -l` and compares only connections whose endpoints are explicitly listed under `routing.managed_ports`; expected edges go in `routing.managed_links`. The current YAML lists the three tested guitar/microphone mixer links and only those exact observed UMC and filter-chain ports. WirePlumber's hardware links remain outside project management. The default command only reports missing or unexpected project links and never changes the graph.
+
+An explicit one-shot mode can create missing declared links, after checking that the source and destination ports currently exist:
+
+```sh
+python3 scripts/observe_pipewire.py --reconcile-once
+```
+
+This mode never removes links, changes undeclared connections, or restarts services. It makes one attempt per missing managed link, then re-reads the graph and reports remaining differences. Use it only during a safe test window: a repaired link can immediately make audio audible. Do not disconnect a working link just to test repair during live use. If all desired links are already present, this mode is a no-op. This command has unit tests with simulated `pw-link` results, but has not yet been exercised on `rigforge`.
 
 ## Candidate direct mix test
 

+ 86 - 0
scripts/observe_pipewire.py

@@ -114,6 +114,82 @@ def observe(state, links):
     return reports
 
 
+def list_ports(runner, direction):
+    result = runner(
+        ["pw-link", direction],
+        check=True,
+        capture_output=True,
+        text=True,
+    )
+    return {line.strip() for line in result.stdout.splitlines() if line.strip()}
+
+
+def reconcile_once(state, runner=subprocess.run):
+    initial_result = runner(
+        ["pw-link", "-l"],
+        check=True,
+        capture_output=True,
+        text=True,
+    )
+    initial_links = parse_pw_link_output(initial_result.stdout)
+    initial_reports = observe(state, initial_links)
+    missing_links = [report for report in initial_reports if report["kind"] == "missing"]
+    actions = []
+
+    if missing_links:
+        outputs = list_ports(runner, "-o")
+        inputs = list_ports(runner, "-i")
+        for report in missing_links:
+            source = report["from"]
+            destination = report["to"]
+            if source not in outputs or destination not in inputs:
+                actions.append(
+                    {
+                        "kind": "unavailable-port",
+                        "from": source,
+                        "to": destination,
+                        "result": "not-linked",
+                    }
+                )
+                continue
+            try:
+                runner(
+                    ["pw-link", source, destination],
+                    check=True,
+                    capture_output=True,
+                    text=True,
+                )
+                actions.append(
+                    {"kind": "link", "from": source, "to": destination, "result": "requested"}
+                )
+            except (OSError, subprocess.CalledProcessError) as error:
+                detail = str(error)
+                if isinstance(error, subprocess.CalledProcessError) and error.stderr:
+                    detail = error.stderr.strip() or detail
+                actions.append(
+                    {
+                        "kind": "link-failed",
+                        "from": source,
+                        "to": destination,
+                        "result": detail,
+                    }
+                )
+
+    final_result = runner(
+        ["pw-link", "-l"],
+        check=True,
+        capture_output=True,
+        text=True,
+    )
+    final_links = parse_pw_link_output(final_result.stdout)
+    return {
+        "mode": "reconcile-once",
+        "managed_links": len(state["routing"]["managed_links"]),
+        "actions": actions,
+        "differences": observe(state, final_links),
+    }
+
+
 def main(argv=None):
     parser = argparse.ArgumentParser()
     parser.add_argument(
@@ -121,9 +197,19 @@ def main(argv=None):
         type=Path,
         default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
     )
+    parser.add_argument(
+        "--reconcile-once",
+        action="store_true",
+        help="create missing declared links once; never remove links or restart services",
+    )
     args = parser.parse_args(argv)
     try:
         state = load_state(args.state)
+        if args.reconcile_once:
+            result = reconcile_once(state)
+            print(json.dumps(result, indent=2))
+            return 0 if not result["differences"] else 1
+
         result = subprocess.run(
             ["pw-link", "-l"],
             check=True,

+ 137 - 1
tests/test_pipewire_observer.py

@@ -2,11 +2,18 @@ import copy
 import sys
 import unittest
 from pathlib import Path
+from types import SimpleNamespace
 
 ROOT = Path(__file__).resolve().parents[1]
 sys.path.insert(0, str(ROOT / "scripts"))
 
-from observe_pipewire import load_state, observe, parse_pw_link_output, validate_managed_links
+from observe_pipewire import (
+    load_state,
+    observe,
+    parse_pw_link_output,
+    reconcile_once,
+    validate_managed_links,
+)
 
 CAPTURE_0 = "alsa_input.hw_U192k_0:capture_AUX0"
 CAPTURE_2 = "alsa_input.hw_U192k_0:capture_AUX2"
@@ -121,6 +128,135 @@ class PipeWireObserverTests(unittest.TestCase):
             ],
         )
 
+    def test_reconcile_once_is_noop_when_all_managed_links_exist(self):
+        calls = []
+
+        def runner(command, **kwargs):
+            calls.append(command)
+            return SimpleNamespace(stdout=(
+                f"{CAPTURE_0}\n  |-> {MIX_INPUT_0}\n"
+                f"{CAPTURE_2}\n  |-> {MIX_INPUT_2}\n"
+                f"{MIX_OUTPUT}\n  |-> {PLAYBACK_0}\n"
+            ))
+
+        result = reconcile_once(self.state, runner)
+
+        self.assertEqual(result["actions"], [])
+        self.assertEqual(result["differences"], [])
+        self.assertEqual(calls, [["pw-link", "-l"], ["pw-link", "-l"]])
+
+    def test_reconcile_once_links_only_declared_missing_edges_and_verifies(self):
+        state = copy.deepcopy(self.state)
+        links = {
+            (CAPTURE_0, MIX_INPUT_0),
+            (MIX_OUTPUT, PLAYBACK_0),
+        }
+        calls = []
+
+        def render_links():
+            return "".join(f"{source}\n  |-> {destination}\n" for source, destination in sorted(links))
+
+        def runner(command, **kwargs):
+            calls.append(command)
+            if command == ["pw-link", "-l"]:
+                return SimpleNamespace(stdout=render_links())
+            if command == ["pw-link", "-o"]:
+                return SimpleNamespace(stdout=f"{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n")
+            if command == ["pw-link", "-i"]:
+                return SimpleNamespace(stdout=f"{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n")
+            if command == ["pw-link", CAPTURE_2, MIX_INPUT_2]:
+                links.add((CAPTURE_2, MIX_INPUT_2))
+                return SimpleNamespace(stdout="")
+            self.fail(f"unexpected command: {command}")
+
+        result = reconcile_once(state, runner)
+
+        self.assertEqual(
+            result["actions"],
+            [{"kind": "link", "from": CAPTURE_2, "to": MIX_INPUT_2, "result": "requested"}],
+        )
+        self.assertEqual(result["differences"], [])
+        self.assertIn(["pw-link", CAPTURE_2, MIX_INPUT_2], calls)
+
+    def test_reconcile_once_does_not_link_when_endpoint_is_unavailable(self):
+        state = copy.deepcopy(self.state)
+        links = {(CAPTURE_0, MIX_INPUT_0), (MIX_OUTPUT, PLAYBACK_0)}
+        calls = []
+
+        def render_links():
+            return "".join(f"{source}\n  |-> {destination}\n" for source, destination in sorted(links))
+
+        def runner(command, **kwargs):
+            calls.append(command)
+            if command == ["pw-link", "-l"]:
+                return SimpleNamespace(stdout=render_links())
+            if command == ["pw-link", "-o"]:
+                return SimpleNamespace(stdout=f"{CAPTURE_0}\n{MIX_OUTPUT}\n")
+            if command == ["pw-link", "-i"]:
+                return SimpleNamespace(stdout=f"{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n")
+            self.fail(f"unexpected command: {command}")
+
+        result = reconcile_once(state, runner)
+
+        self.assertEqual(
+            result["actions"],
+            [{
+                "kind": "unavailable-port",
+                "from": CAPTURE_2,
+                "to": MIX_INPUT_2,
+                "result": "not-linked",
+            }],
+        )
+        self.assertTrue(result["differences"])
+        self.assertFalse(any(command[:2] == ["pw-link", CAPTURE_2] for command in calls))
+
+    def test_reconcile_once_preserves_unexpected_managed_links(self):
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_ports"].append(CAPTURE_3)
+        links = {
+            (CAPTURE_0, MIX_INPUT_0),
+            (CAPTURE_2, MIX_INPUT_2),
+            (MIX_OUTPUT, PLAYBACK_0),
+            (CAPTURE_3, MIX_INPUT_2),
+        }
+        calls = []
+
+        def runner(command, **kwargs):
+            calls.append(command)
+            return SimpleNamespace(
+                stdout="".join(f"{source}\n  |-> {destination}\n" for source, destination in sorted(links))
+            )
+
+        result = reconcile_once(state, runner)
+
+        self.assertEqual(result["actions"], [])
+        self.assertEqual(len(result["differences"]), 1)
+        self.assertEqual(result["differences"][0]["kind"], "unexpected")
+        self.assertEqual(calls, [["pw-link", "-l"], ["pw-link", "-l"]])
+
+    def test_reconcile_once_reports_link_still_missing_after_request(self):
+        state = copy.deepcopy(self.state)
+        links = {(CAPTURE_0, MIX_INPUT_0), (MIX_OUTPUT, PLAYBACK_0)}
+
+        def render_links():
+            return "".join(f"{source}\n  |-> {destination}\n" for source, destination in sorted(links))
+
+        def runner(command, **kwargs):
+            if command == ["pw-link", "-l"]:
+                return SimpleNamespace(stdout=render_links())
+            if command == ["pw-link", "-o"]:
+                return SimpleNamespace(stdout=f"{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n")
+            if command == ["pw-link", "-i"]:
+                return SimpleNamespace(stdout=f"{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n")
+            if command == ["pw-link", CAPTURE_2, MIX_INPUT_2]:
+                return SimpleNamespace(stdout="")
+            self.fail(f"unexpected command: {command}")
+
+        result = reconcile_once(state, runner)
+
+        self.assertEqual(len(result["differences"]), 1)
+        self.assertEqual(result["differences"][0]["kind"], "missing")
+
     def test_managed_links_must_use_declared_ports(self):
         state = copy.deepcopy(self.state)
         state["routing"]["managed_ports"].remove(PLAYBACK_0)