Browse Source

manage unexpected links

Johan Le Baut 2 weeks ago
parent
commit
c9d79fe0f0

+ 1 - 1
AGENTS.md

@@ -48,7 +48,7 @@ The observer invokes `pw-link -l` itself. It never creates or removes links. A c
 - 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. The current effect allowlist is limited to the declared `effect_0` NAM and `effect_1` IR ports.
 - 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`.
 - Deployment declarations belong in `config/desired-state.yaml`. The deploy helper must remain scoped to declared user paths, preserve and restore prior files, refuse destructive actions after local modifications, and never restart the main PipeWire or WirePlumber service as a generic update.
-- 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.
+- Keep observation as the default. Explicit `--reconcile-once` may create declared missing links and remove only exact links listed in `routing.managed_unlinks`; it must defer removals until all desired managed links are present, must not alter other connections, and must not restart services. Retain tests for simulated repair, safe removal, deferral, 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

+ 3 - 3
README.md

@@ -56,15 +56,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 default command only reports missing or unexpected project links and never changes the graph.
+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`. Exact obsolete edges that may be removed by explicit reconciliation must be separately listed under `routing.managed_unlinks`. The current YAML declares the three guitar NAM/cabinet edges, the voice mixer edge, the mixer output edge, and the obsolete direct guitar bypass for removal. WirePlumber's unrelated hardware links remain outside project management. The default command only reports differences and never changes the graph; declared removals appear as `would-unlink`, while all other unexpected links remain `would-review`.
 
-An explicit one-shot mode can create missing declared links, after checking that the source and destination ports currently exist:
+An explicit one-shot mode can create missing declared links after checking that the source and destination ports exist, then remove only present links explicitly declared in `routing.managed_unlinks`:
 
 ```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. Unit tests use simulated `pw-link` results.
+This mode never removes an unlisted link, changes undeclared connections, or restarts services. It attempts declared additions first and removes explicitly listed stale links only after every desired managed link is visible; if any desired link remains missing, removals are deferred. It then re-reads the graph and reports remaining differences. Use it only during a safe test window: repaired or removed links can immediately change audible routing. Unit tests use simulated `pw-link` results.
 
 On 2026-11-18, the target owner deliberately removed the managed AUX2 capture-to-mixer link during a safe test. Observation reported that single link as missing. After updating `rigforge` to commit `83fb0a7`, `--reconcile-once` requested the link, and the final check reported `differences: []`. A subsequent read-only observation also reported no differences, the microphone was confirmed audible again, and all 20 unit tests passed on the target. In a later target test, restarting `filter-chain.service` removed all three managed links; explicit `--reconcile-once` requested all three, and the final observer again reported `differences: []`. Audio audibility after this later repair was not reported. These tests verify one-shot repair on the current target, not continuous reconciliation or recovery when ports are unavailable. After any filter-chain service restart, run the read-only observer and, during a safe test window, explicitly reconcile if links are missing.
 

+ 4 - 0
config/desired-state.yaml

@@ -205,6 +205,10 @@ routing:
     - from: rigforge.direct-mix.output:capture_FL
       to: alsa_output.hw_U192k_0:playback_AUX0
       status: observed
+  managed_unlinks:
+    - from: alsa_input.hw_U192k_0:capture_AUX0
+      to: rigforge.direct-mix.input:playback_AUX0
+      status: observed
   monitoring:
     hardware_monitoring: verify-on-target
     software_monitoring: verify-on-target

+ 120 - 2
scripts/observe_pipewire.py

@@ -73,6 +73,53 @@ def validate_managed_links(state):
             errors.append(f"routing.managed_links[{index}] cannot link a port to itself")
         if link.get("status") not in {"planned", "observed"}:
             errors.append(f"routing.managed_links[{index}].status must be planned or observed")
+
+    managed_unlinks = routing.get("managed_unlinks")
+    if not isinstance(managed_unlinks, list):
+        errors.append("routing.managed_unlinks must be a list")
+        managed_unlinks = []
+    unlink_edges = set()
+    for index, link in enumerate(managed_unlinks):
+        if not isinstance(link, dict):
+            errors.append(f"routing.managed_unlinks[{index}] must be a mapping")
+            continue
+        source = link.get("from")
+        destination = link.get("to")
+        if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
+            errors.append(
+                f"routing.managed_unlinks[{index}].from is not an approved observed Rigforge or UMC port"
+            )
+        if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
+            errors.append(
+                f"routing.managed_unlinks[{index}].to is not an approved observed Rigforge or UMC port"
+            )
+        if (
+            isinstance(source, str)
+            and isinstance(destination, str)
+            and (source not in managed_ports or destination not in managed_ports)
+        ):
+            errors.append(
+                f"routing.managed_unlinks[{index}] endpoints must be listed in routing.managed_ports"
+            )
+        if source == destination:
+            errors.append(f"routing.managed_unlinks[{index}] cannot unlink a port from itself")
+        if link.get("status") not in {"planned", "observed"}:
+            errors.append(f"routing.managed_unlinks[{index}].status must be planned or observed")
+        if isinstance(source, str) and isinstance(destination, str):
+            edge = (source, destination)
+            if edge in unlink_edges:
+                errors.append(f"duplicate managed unlink: {source} -> {destination}")
+            unlink_edges.add(edge)
+
+    managed_edges = {
+        (link.get("from"), link.get("to"))
+        for link in managed_links
+        if isinstance(link, dict)
+        and isinstance(link.get("from"), str)
+        and isinstance(link.get("to"), str)
+    }
+    for source, destination in sorted(unlink_edges & managed_edges):
+        errors.append(f"link cannot be both managed and scheduled for removal: {source} -> {destination}")
     return errors
 
 
@@ -103,6 +150,11 @@ def observe(state, links):
         for link in state["routing"]["managed_links"]
         if link["status"] in {"planned", "observed"}
     }
+    managed_unlinks = {
+        (link["from"], link["to"])
+        for link in state["routing"]["managed_unlinks"]
+        if link["status"] in {"planned", "observed"}
+    }
     observed_managed = {
         link
         for link in links
@@ -112,7 +164,8 @@ def observe(state, links):
     for source, destination in sorted(managed - observed_managed):
         reports.append({"kind": "missing", "from": source, "to": destination, "action": "would-link"})
     for source, destination in sorted(observed_managed - managed):
-        reports.append({"kind": "unexpected", "from": source, "to": destination, "action": "would-review"})
+        action = "would-unlink" if (source, destination) in managed_unlinks else "would-review"
+        reports.append({"kind": "unexpected", "from": source, "to": destination, "action": action})
     return reports
 
 
@@ -177,6 +230,67 @@ def reconcile_once(state, runner=subprocess.run):
                     }
                 )
 
+    # Remove only explicitly declared stale edges, and only after every
+    # desired managed link is present. This avoids disconnecting an old path
+    # when its replacement could not be established.
+    if missing_links:
+        before_unlink_result = runner(
+            ["pw-link", "-l"],
+            check=True,
+            capture_output=True,
+            text=True,
+        )
+        before_unlink_links = parse_pw_link_output(before_unlink_result.stdout)
+    else:
+        before_unlink_links = initial_links
+    remaining_missing = [
+        report
+        for report in observe(state, before_unlink_links)
+        if report["kind"] == "missing"
+    ]
+    managed_ports = set(state["routing"]["managed_ports"])
+    scheduled_unlinks = [
+        (link["from"], link["to"])
+        for link in state["routing"]["managed_unlinks"]
+        if link["from"] in managed_ports
+        and link["to"] in managed_ports
+        and (link["from"], link["to"]) in before_unlink_links
+    ]
+    if remaining_missing:
+        for source, destination in scheduled_unlinks:
+            actions.append(
+                {
+                    "kind": "unlink-deferred",
+                    "from": source,
+                    "to": destination,
+                    "result": "desired managed links are still missing",
+                }
+            )
+    else:
+        for source, destination in scheduled_unlinks:
+            try:
+                runner(
+                    ["pw-link", "-d", source, destination],
+                    check=True,
+                    capture_output=True,
+                    text=True,
+                )
+                actions.append(
+                    {"kind": "unlink", "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": "unlink-failed",
+                        "from": source,
+                        "to": destination,
+                        "result": detail,
+                    }
+                )
+
     final_result = runner(
         ["pw-link", "-l"],
         check=True,
@@ -187,6 +301,7 @@ def reconcile_once(state, runner=subprocess.run):
     return {
         "mode": "reconcile-once",
         "managed_links": len(state["routing"]["managed_links"]),
+        "managed_unlinks": len(state["routing"]["managed_unlinks"]),
         "actions": actions,
         "differences": observe(state, final_links),
     }
@@ -202,7 +317,10 @@ def main(argv=None):
     parser.add_argument(
         "--reconcile-once",
         action="store_true",
-        help="create missing declared links once; never remove links or restart services",
+        help=(
+            "create missing declared links and remove only explicitly declared "
+            "managed_unlinks once; never alter other links or restart services"
+        ),
     )
     args = parser.parse_args(argv)
     try:

+ 11 - 0
scripts/validate_desired_state.py

@@ -112,6 +112,17 @@ def validate_mod_host_chain(routing, source_by_id):
             bypass_edge = (bypass.get("from"), bypass.get("to"))
             if all(isinstance(endpoint, str) for endpoint in bypass_edge) and bypass_edge in actual_edges:
                 errors.append("the guitar capture-to-mix bypass must not be a managed link")
+            managed_unlinks = routing.get("managed_unlinks")
+            unlink_edges = {
+                (item.get("from"), item.get("to"))
+                for item in managed_unlinks
+                if isinstance(item, dict)
+            } if isinstance(managed_unlinks, list) else set()
+            if (
+                all(isinstance(endpoint, str) for endpoint in bypass_edge)
+                and bypass_edge not in unlink_edges
+            ):
+                errors.append("the guitar capture-to-mix bypass must be declared in routing.managed_unlinks")
     return errors
 
 

+ 15 - 0
tests/test_desired_state.py

@@ -60,6 +60,14 @@ class DesiredStateValidationTests(unittest.TestCase):
                 for link in self.state["routing"]["managed_links"]
             },
         )
+        self.assertIn(
+            {
+                "from": chain["bypass_link"]["from"],
+                "to": chain["bypass_link"]["to"],
+                "status": "observed",
+            },
+            self.state["routing"]["managed_unlinks"],
+        )
 
         state = copy.deepcopy(self.state)
         state["routing"]["mod_host_chains"]["guitar"]["processors"][0]["asset_path"] = "../../outside.nam"
@@ -83,6 +91,13 @@ class DesiredStateValidationTests(unittest.TestCase):
         state["routing"]["managed_links"].pop(0)
         self.assertTrue(any("mod-host guitar chain link must be declared" in error for error in validate_state(state)))
 
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_unlinks"] = []
+        self.assertIn(
+            "the guitar capture-to-mix bypass must be declared in routing.managed_unlinks",
+            validate_state(state),
+        )
+
         state = copy.deepcopy(self.state)
         state["routing"]["mod_host_chains"]["guitar"]["processors"][0]["parameters"]["output_level"] = 30
         self.assertIn("NAM output_level must be between -20 and 20 dB", validate_state(state))

+ 161 - 0
tests/test_pipewire_observer.py

@@ -138,6 +138,28 @@ class PipeWireObserverTests(unittest.TestCase):
             ],
         )
 
+    def test_reports_declared_stale_link_as_would_unlink(self):
+        links = {
+            (CAPTURE_0, AMP_INPUT),
+            (AMP_OUTPUT, CAB_INPUT),
+            (CAB_OUTPUT, MIX_INPUT_0),
+            (CAPTURE_2, MIX_INPUT_2),
+            (MIX_OUTPUT, PLAYBACK_0),
+            (CAPTURE_0, MIX_INPUT_0),
+        }
+
+        self.assertEqual(
+            observe(self.state, links),
+            [
+                {
+                    "kind": "unexpected",
+                    "from": CAPTURE_0,
+                    "to": MIX_INPUT_0,
+                    "action": "would-unlink",
+                }
+            ],
+        )
+
     def test_reconcile_once_is_noop_when_all_managed_links_exist(self):
         calls = []
 
@@ -196,6 +218,133 @@ class PipeWireObserverTests(unittest.TestCase):
         self.assertEqual(result["differences"], [])
         self.assertIn(["pw-link", CAPTURE_2, MIX_INPUT_2], calls)
 
+    def test_reconcile_once_unlinks_only_declared_stale_edge_after_replacement_exists(self):
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_ports"].append(CAPTURE_3)
+        stale_link = (CAPTURE_0, MIX_INPUT_0)
+        unrelated_link = (CAPTURE_3, MIX_INPUT_2)
+        links = {
+            stale_link,
+            unrelated_link,
+            (CAPTURE_2, MIX_INPUT_2),
+            (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"{AMP_OUTPUT}\n{CAB_OUTPUT}\n{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n"
+                ))
+            if command == ["pw-link", "-i"]:
+                return SimpleNamespace(stdout=(
+                    f"{AMP_INPUT}\n{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
+                ))
+            if len(command) == 3 and command[0] == "pw-link":
+                edge = (command[1], command[2])
+                if edge in {
+                    (CAPTURE_0, AMP_INPUT),
+                    (AMP_OUTPUT, CAB_INPUT),
+                    (CAB_OUTPUT, MIX_INPUT_0),
+                }:
+                    links.add(edge)
+                    return SimpleNamespace(stdout="")
+            if len(command) == 4 and command[:2] == ["pw-link", "-d"]:
+                links.discard((command[2], command[3]))
+                return SimpleNamespace(stdout="")
+            self.fail(f"unexpected command: {command}")
+
+        result = reconcile_once(state, runner)
+
+        self.assertEqual(
+            result["actions"],
+            [
+                {"kind": "link", "from": CAPTURE_0, "to": AMP_INPUT, "result": "requested"},
+                {"kind": "link", "from": AMP_OUTPUT, "to": CAB_INPUT, "result": "requested"},
+                {"kind": "link", "from": CAB_OUTPUT, "to": MIX_INPUT_0, "result": "requested"},
+                {"kind": "unlink", "from": CAPTURE_0, "to": MIX_INPUT_0, "result": "requested"},
+            ],
+        )
+        self.assertNotIn(stale_link, links)
+        self.assertIn(unrelated_link, links)
+        self.assertEqual(
+            result["differences"],
+            [
+                {
+                    "kind": "unexpected",
+                    "from": CAPTURE_3,
+                    "to": MIX_INPUT_2,
+                    "action": "would-review",
+                }
+            ],
+        )
+        self.assertIn(["pw-link", "-d", CAPTURE_0, MIX_INPUT_0], calls)
+        self.assertNotIn(["pw-link", "-d", CAPTURE_3, MIX_INPUT_2], calls)
+
+    def test_reconcile_once_defers_unlink_until_all_desired_links_exist(self):
+        links = {
+            (CAPTURE_0, MIX_INPUT_0),
+            (CAPTURE_2, MIX_INPUT_2),
+            (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"{AMP_OUTPUT}\n{CAB_OUTPUT}\n{CAPTURE_0}\n{CAPTURE_2}\n{MIX_OUTPUT}\n"
+                ))
+            if command == ["pw-link", "-i"]:
+                return SimpleNamespace(stdout=(
+                    f"{CAB_INPUT}\n{MIX_INPUT_0}\n{MIX_INPUT_2}\n{PLAYBACK_0}\n"
+                ))
+            if command == ["pw-link", AMP_OUTPUT, CAB_INPUT]:
+                links.add((AMP_OUTPUT, CAB_INPUT))
+                return SimpleNamespace(stdout="")
+            if command == ["pw-link", CAB_OUTPUT, MIX_INPUT_0]:
+                links.add((CAB_OUTPUT, MIX_INPUT_0))
+                return SimpleNamespace(stdout="")
+            self.fail(f"unexpected command: {command}")
+
+        result = reconcile_once(self.state, runner)
+
+        self.assertEqual(
+            result["actions"],
+            [
+                {
+                    "kind": "unavailable-port",
+                    "from": CAPTURE_0,
+                    "to": AMP_INPUT,
+                    "result": "not-linked",
+                },
+                {"kind": "link", "from": AMP_OUTPUT, "to": CAB_INPUT, "result": "requested"},
+                {"kind": "link", "from": CAB_OUTPUT, "to": MIX_INPUT_0, "result": "requested"},
+                {
+                    "kind": "unlink-deferred",
+                    "from": CAPTURE_0,
+                    "to": MIX_INPUT_0,
+                    "result": "desired managed links are still missing",
+                },
+            ],
+        )
+        self.assertIn((CAPTURE_0, MIX_INPUT_0), links)
+        self.assertFalse(any(command[:2] == ["pw-link", "-d"] for command in calls))
+
     def test_reconcile_once_restores_all_managed_links_after_service_restart(self):
         links = set()
         calls = []
@@ -357,6 +506,18 @@ class PipeWireObserverTests(unittest.TestCase):
         ]
         self.assertTrue(any("endpoints must be listed" in error for error in validate_managed_links(state)))
 
+    def test_managed_link_cannot_also_be_scheduled_for_removal(self):
+        state = copy.deepcopy(self.state)
+        state["routing"]["managed_links"].append(
+            {"from": CAPTURE_0, "to": MIX_INPUT_0, "status": "planned"}
+        )
+        self.assertTrue(
+            any(
+                "link cannot be both managed and scheduled for removal" in error
+                for error in validate_managed_links(state)
+            )
+        )
+
 
 if __name__ == "__main__":
     unittest.main()