From ee29aec54ba220586d1b8023da8794a4c263ca98 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Tue, 15 Sep 2026 12:08:05 -0700 Subject: [PATCH] test(update): trim launchd salvage to two invariant tests Keep one kill-path test for the reporter's scenario (a detached copy of a loaded launchd job is kickstarted through launchd, never respawned; a failed kickstart is unrecovered with the manual command; an unrelated loaded job leaves the manual respawn intact) and one host-independent pure-function test for the plist scan and PID attribution (platform forced to darwin so it runs on Linux CI too, instead of the macos_only marker that would have skipped it here). The other nine tests from #111690 asserted the same paths per branch; the salvage bar is 1-2 invariant tests proven red on base, and both of these error on origin/main (no _loaded_launchd_backend_jobs / _launchd_job_owning_backend). --- .../hermes_cli/test_update_stale_dashboard.py | 168 ++++-------------- 1 file changed, 37 insertions(+), 131 deletions(-) diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.py index 4239fbc8fb..238010f258 100644 --- a/tests/hermes_cli/test_update_stale_dashboard.py +++ b/tests/hermes_cli/test_update_stale_dashboard.py @@ -942,7 +942,7 @@ class TestPostUpdateStaleModuleReload: class TestLaunchdSupervisedBackends: - """macOS: a backend supervised by a launchd job must come back through launchd. Respawning + """macOS (#111689): a backend supervised by a launchd job must come back through launchd. Respawning its argv detached leaves a copy holding the job's port, so every KeepAlive restart of the job fails with "port already in use" and the backend that IS running is no longer supervised.""" @@ -951,16 +951,13 @@ class TestLaunchdSupervisedBackends: "dashboard", "--host", "0.0.0.0", "--port", "9119", "--no-open", "--skip-build", ] - def _live(self): - return main_dashboard - @staticmethod def _fake_kill(pid, sig): if sig == 0: raise ProcessLookupError - def _run(self, pid, jobs, *, restart_ok=True, restart_managed=True, ancestors=()): - live = self._live() + def _run(self, pid, jobs, *, restart_ok=True, restart_managed=True): + live = main_dashboard with patch.object(main_dashboard, "_restart_managed_dashboard_service", return_value=False), \ patch.object(live, "_find_stale_dashboard_pids", return_value=[pid]), \ patch.object(main_dashboard, "_get_pid_cgroup_path", return_value=None), \ @@ -968,7 +965,7 @@ class TestLaunchdSupervisedBackends: patch.object(main_dashboard, "_dashboard_cmdline_for_pid", return_value=list(self.ARGV)), \ patch.object(main_dashboard, "_loaded_launchd_backend_jobs", return_value=jobs), \ patch.object(main_dashboard, "_restart_launchd_job", return_value=restart_ok) as restart, \ - patch("hermes_cli.dashboard_procs._process_ancestors", return_value=list(ancestors)), \ + patch("hermes_cli.dashboard_procs._process_ancestors", return_value=[]), \ patch("hermes_cli.dashboard_procs._hermes_home_for_pid", return_value=None), \ patch.object(live, "_respawn_dashboard_processes", return_value=[]) as respawn, \ patch("os.kill", side_effect=self._fake_kill), \ @@ -977,137 +974,43 @@ class TestLaunchdSupervisedBackends: return result, restart, respawn @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn") - def test_launchd_owned_pid_is_restarted_through_launchd_not_respawned(self, capsys): - """launchd reports the PID as the job's live process → restart the job, never respawn.""" - result, restart, respawn = self._run(9101, [("system", "ai.hermes.dashboard", list(self.ARGV), 9101)]) - + def test_launchd_owned_backend_restarts_through_launchd_never_as_a_detached_respawn(self, capsys): + """The reporter's state: the job is loaded but has no live process (it keeps failing on the + port) and a detached copy runs its exact ProgramArguments. The copy is stopped and the JOB + is kickstarted; an argv respawn would recreate the port conflict. A failed kickstart counts + the PID as unrecovered and prints the manual command; a loaded job with a different argv + and PID leaves the manual-backend respawn untouched (control).""" + job = ("system", "ai.hermes.dashboard", list(self.ARGV), None) + result, restart, respawn = self._run(9102, [job]) respawn.assert_not_called() - restart.assert_called_once_with("system", "ai.hermes.dashboard", 9101) - assert result["killed"] == [9101] - assert result["unrecovered"] == [] + restart.assert_called_once_with("system", "ai.hermes.dashboard", None) + assert result["killed"] == [9102] and result["unrecovered"] == [] out = capsys.readouterr().out assert "✓ restarted launchd job system/ai.hermes.dashboard" in out assert "when you're ready" not in out - @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn") - def test_detached_copy_of_a_launchd_job_is_not_respawned(self, capsys): - """The state an earlier respawn leaves behind: the job is loaded but has no live process - (it fails on the port), and a detached copy runs its exact ProgramArguments. Killing the - copy hands the port back to the job; respawning it would recreate the conflict.""" - result, restart, respawn = self._run(9102, [("system", "ai.hermes.dashboard", list(self.ARGV), None)]) - + result, restart, respawn = self._run(9103, [("gui/501", "ai.hermes.dashboard", list(self.ARGV), 9103)], + restart_ok=False) respawn.assert_not_called() - restart.assert_called_once_with("system", "ai.hermes.dashboard", None) - assert result["unrecovered"] == [] - assert "✓ restarted launchd job system/ai.hermes.dashboard" in capsys.readouterr().out - - @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn") - def test_wrapper_plist_child_is_attributed_through_its_ancestors(self, capsys): - """A plist that runs ``/bin/sh -c "… hermes dashboard …"`` without exec: launchd's live - PID is the shell, the stale backend PID is its child. Ownership follows the parent chain.""" - wrapper_argv = ["/bin/sh", "-c", "exec-less wrapper: hermes dashboard --port 9119"] - result, restart, respawn = self._run( - 9105, [("gui/501", "com.example.hermes-dashboard", wrapper_argv, 777)], ancestors=[777, 1]) - - respawn.assert_not_called() - restart.assert_called_once_with("gui/501", "com.example.hermes-dashboard", 777) - assert result["unrecovered"] == [] - - @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn") - def test_launchd_restart_failure_reports_the_manual_command(self, capsys): - result, restart, respawn = self._run( - 9103, [("gui/501", "ai.hermes.dashboard", list(self.ARGV), 9103)], restart_ok=False) - - respawn.assert_not_called() - restart.assert_called_once_with("gui/501", "ai.hermes.dashboard", 9103) assert result["unrecovered"] == [9103] - out = capsys.readouterr().out - assert "launchctl kickstart -k gui/501/ai.hermes.dashboard" in out - assert "Restart anything not auto-restarted" in out - - @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn") - def test_unrelated_launchd_job_does_not_claim_a_manual_backend(self, capsys): - """A loaded job with a different PID and different argv leaves the manual respawn intact.""" - other_argv = ["hermes", "dashboard", "--port", "8300"] - result, restart, respawn = self._run(9104, [("gui/501", "ai.hermes.dashboard", other_argv, 777)]) + assert "launchctl kickstart -k gui/501/ai.hermes.dashboard" in capsys.readouterr().out + other = ("gui/501", "ai.hermes.other", ["hermes", "dashboard", "--port", "8300"], 777) + result, restart, respawn = self._run(9104, [other]) restart.assert_not_called() respawn.assert_called_once_with([list(self.ARGV)]) assert result["unrecovered"] == [] - @pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn") - def test_stop_says_a_keepalive_job_will_undo_the_stop(self, capsys): - """``hermes dashboard --stop`` on a launchd-owned backend: no respawn, no "restart it - yourself" hint — the job comes back on its own; print how to keep it down instead.""" - result, restart, respawn = self._run( - 9106, [("system", "ai.hermes.dashboard", list(self.ARGV), 9106)], restart_managed=False) - - restart.assert_not_called() - respawn.assert_not_called() - assert result["killed"] == [9106] - out = capsys.readouterr().out - assert "launchctl bootout system/ai.hermes.dashboard" in out - assert "when you're ready" not in out - - def test_owning_job_matches_by_live_pid_ancestor_or_exact_argv(self): - jobs = [ - ("gui/501", "ai.hermes.dashboard", ["hermes", "dashboard", "--port", "8300"], 4242), - ("system", "ai.hermes.serve", ["hermes", "serve", "--port", "8301"], None), - ] - owning = main_dashboard._launchd_job_owning_backend - assert owning(4242, ["something", "else"], jobs) == ("gui/501", "ai.hermes.dashboard", 4242) - assert owning(9999, ["python"], jobs, ancestors=[4242, 1]) == ("gui/501", "ai.hermes.dashboard", 4242) - assert owning(9999, ["hermes", "serve", "--port", "8301"], jobs) == ("system", "ai.hermes.serve", None) - assert owning(9999, ["hermes", "serve", "--port", "8302"], jobs) is None - assert owning(9999, None, jobs) is None - assert owning(4242, None, []) is None - - def test_process_ancestors_walks_to_init_and_stops_on_cycles(self): - parents = {900: 800, 800: 700, 700: 1} - with patch("hermes_cli.dashboard_procs._process_ppid", side_effect=lambda p: parents.get(p)): - assert dashboard_procs._process_ancestors(900) == [800, 700] - looped = {900: 800, 800: 900} - with patch("hermes_cli.dashboard_procs._process_ppid", side_effect=lambda p: looped.get(p)): - assert dashboard_procs._process_ancestors(900) == [800] - with patch("hermes_cli.dashboard_procs._process_ppid", return_value=None): - assert dashboard_procs._process_ancestors(900) == [] - - def test_restart_launchd_job_requires_a_fresh_supervised_pid(self): - """kickstart returning 0 is only "restart requested": success needs launchd to report a - PID other than the one that was stopped.""" - kickstarts: list[list[str]] = [] - - def fake_probe(cmd, *, timeout): - kickstarts.append(cmd) - return MagicMock(returncode=0) - - with patch.object(main_dashboard, "_run_probe", side_effect=fake_probe), \ - patch("hermes_cli.gateway._wait_for_launchd_service_pid", return_value=True) as wait: - assert main_dashboard._restart_launchd_job("system", "ai.hermes.dashboard", 4242) is True - assert kickstarts == [["launchctl", "kickstart", "system/ai.hermes.dashboard"]] - wait.assert_called_once_with("ai.hermes.dashboard", old_pid=4242, timeout=15.0, domain="system") - - with patch.object(main_dashboard, "_run_probe", side_effect=fake_probe), \ - patch("hermes_cli.gateway._wait_for_launchd_service_pid", return_value=False): - assert main_dashboard._restart_launchd_job("system", "ai.hermes.dashboard", 4242) is False - - with patch.object(main_dashboard, "_run_probe", return_value=MagicMock(returncode=1)), \ - patch("hermes_cli.gateway._wait_for_launchd_service_pid") as wait: - assert main_dashboard._restart_launchd_job("gui/501", "x", None) is False - wait.assert_not_called() - - with patch.object(main_dashboard, "_run_probe", side_effect=FileNotFoundError("launchctl")): - assert main_dashboard._restart_launchd_job("gui/501", "x", None) is False - - @pytest.mark.macos_only - def test_loaded_backend_jobs_scans_plists_and_probes_only_backend_labels(self, tmp_path, _no_real_launchd_jobs): - """Only LOADED jobs whose ProgramArguments are a dashboard/serve backend are returned: - gateway jobs are never probed, unloaded backends are dropped, unreadable plists skipped, - and LaunchDaemons resolve to the system domain.""" + def test_loaded_backend_jobs_scans_plists_and_attributes_pids_host_independently( + self, tmp_path, monkeypatch, _no_real_launchd_jobs): + """Pure plist scan + attribution, runnable off macOS (platform forced): only LOADED jobs whose + ProgramArguments are a dashboard/serve backend are returned (gateway plists are never probed, + unloaded backends dropped, unreadable plists skipped, LaunchDaemons resolve to the system + domain); a PID is attributed by launchd's live PID, by a live-PID ancestor (exec-less + ``/bin/sh -c`` wrapper plist) or by exact argv (the detached copy), never otherwise.""" import plistlib - agents = tmp_path / "LaunchAgents" - daemons = tmp_path / "LaunchDaemons" + agents, daemons = tmp_path / "LaunchAgents", tmp_path / "LaunchDaemons" agents.mkdir() daemons.mkdir() backend_argv = ["/opt/hermes/venv/bin/python", "-m", "hermes_cli.main", "dashboard", "--port", "9119"] @@ -1123,7 +1026,7 @@ class TestLaunchdSupervisedBackends: plistlib.dump({"Label": label, "ProgramArguments": argv}, f) (agents / "broken.plist").write_bytes(b"not a plist") - uid = os.getuid() + uid = 501 probed: list[tuple[str, str]] = [] def fake_print(domain, label): @@ -1134,6 +1037,8 @@ class TestLaunchdSupervisedBackends: return (True, None) return (False, None) + monkeypatch.setattr(main_dashboard.sys, "platform", "darwin") + monkeypatch.setattr(main_dashboard.os, "getuid", lambda: uid, raising=False) with patch("hermes_cli.gateway._launchd_print_service_pid", side_effect=fake_print): jobs = _no_real_launchd_jobs([("agent", agents), ("daemon", daemons)]) @@ -1141,13 +1046,14 @@ class TestLaunchdSupervisedBackends: (f"user/{uid}", "ai.hermes.dashboard", backend_argv, 4242), ("system", "ai.hermes.serve", serve_argv, None), ] - assert ("gui/501", "ai.hermes.gateway") not in probed assert not any(label == "ai.hermes.gateway" for _domain, label in probed) - # An agent label is probed gui first, then user; a daemon only in system. assert probed[:2] == [(f"gui/{uid}", "ai.hermes.dashboard"), (f"user/{uid}", "ai.hermes.dashboard")] - assert ("system", "ai.hermes.serve") in probed assert not any(domain == "system" and label != "ai.hermes.serve" for domain, label in probed) - @pytest.mark.linux_only - def test_loaded_backend_jobs_is_empty_off_macos(self, tmp_path): - assert main_dashboard._loaded_launchd_backend_jobs([("agent", tmp_path)]) == [] + owning = main_dashboard._launchd_job_owning_backend + assert owning(4242, ["something", "else"], jobs) == (f"user/{uid}", "ai.hermes.dashboard", 4242) + assert owning(9999, ["python"], jobs, ancestors=[4242, 1]) == (f"user/{uid}", "ai.hermes.dashboard", 4242) + assert owning(9999, serve_argv, jobs) == ("system", "ai.hermes.serve", None) + assert owning(9999, serve_argv[:-1] + ["8643"], jobs) is None + assert owning(9999, None, jobs) is None + assert owning(4242, None, []) is None