diff --git a/loopdy_plugin/plugin_update.py b/loopdy_plugin/plugin_update.py index 28d1ee8..ba1e53e 100644 --- a/loopdy_plugin/plugin_update.py +++ b/loopdy_plugin/plugin_update.py @@ -62,6 +62,17 @@ def _hermes_home_for_plugin(plugin_root: Path) -> Path: def _metadata_revision(plugin_root: Path) -> str: + """Revision of the plugin bytes actually installed at ``plugin_root``. + + A Git checkout identifies itself by HEAD. The installer's metadata record is + written only by ``hermes plugins install/update``, so it goes stale when the + checkout moves any other way (for example a fast-forward pull), and trusting + it would report and activate against a revision that is no longer on disk. + Archive-style installs carry no ``.git`` and rely on the metadata record. + """ + head = _git_head_revision(plugin_root) + if head: + return head home = _hermes_home_for_plugin(plugin_root) metadata_path = home / "plugins" / ".install-metadata.json" try: @@ -72,27 +83,29 @@ def _metadata_revision(plugin_root: Path) -> str: return revision except (OSError, ValueError, TypeError): pass - # A directly cloned standalone plugin can identify itself without metadata. - if (plugin_root / ".git").is_dir(): - try: - result = subprocess.run( - ["git", "rev-parse", "HEAD"], - cwd=str(plugin_root), - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - text=True, - timeout=5, - env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")}, - ) - revision = result.stdout.strip().lower() - if result.returncode == 0 and _REVISION.fullmatch(revision): - return revision - except (OSError, subprocess.TimeoutExpired): - pass return "" +def _git_head_revision(plugin_root: Path) -> str: + if not (plugin_root / ".git").is_dir(): + return "" + try: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=str(plugin_root), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + timeout=5, + env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")}, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + revision = result.stdout.strip().lower() + return revision if result.returncode == 0 and _REVISION.fullmatch(revision) else "" + + # These values are intentionally fixed at module import. Reading newly installed # files from an old gateway process must never masquerade as activation. LOADED_REVISION = _metadata_revision(_PLUGIN_ROOT) @@ -458,6 +471,29 @@ def _reconcile_completion(self, state: dict[str, Any], operation: dict[str, Any] operation["message"] = "The updated bighelp plugin is active and Link responded." operation["updated_at"] = int(time.time()) return True + active = str(runtime.get("revision") or "") + installed = _metadata_revision(self.plugin_root) + if ( + _REVISION.fullmatch(target) + and fresh + and _REVISION.fullmatch(active) + and active != target + and _REVISION.fullmatch(installed) + and installed != target + ): + # A gateway lifecycle newer than this operation is running other + # bytes, and the installation is positively known to hold other + # bytes too, so this target can never activate and no restart is in + # flight. Without this, the non-terminal phase would refuse every + # later update on this host forever. An unknown installation stays + # held: absence of evidence is not supersession. + operation["phase"] = "failed" + operation["message"] = _bounded_message( + "Superseded: the gateway restarted onto a different installed revision. " + "Start a new update if one is still needed." + ) + operation["updated_at"] = int(time.time()) + return True return False def _trim_operations(self, state: dict[str, Any]) -> None: diff --git a/tests/test_plugin_update_execution.py b/tests/test_plugin_update_execution.py index 260ee88..58cf8dd 100644 --- a/tests/test_plugin_update_execution.py +++ b/tests/test_plugin_update_execution.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path +import shutil import subprocess import sys import tempfile @@ -72,6 +73,44 @@ def test_ambiguous_timeout_does_not_authorize_a_second_update(self): with self.assertRaises(ValueError): self.manager.start("update_second_0123456789", self.device, True) + def test_git_checkout_revision_wins_over_a_stale_installer_record(self): + env = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull} + def git(*args): + return subprocess.run(["git", "-C", str(self.plugin), *args], check=True, capture_output=True, text=True, env=env).stdout.strip() + git("init", "-q") + git("add", ".") + git("-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "fixture") + head = git("rev-parse", "HEAD") + (self.root / "plugins" / ".install-metadata.json").write_text(json.dumps({"loopdy": {"pinned": True, "revision": "d" * 40, "source": "https://github.com/promptclickrun/loopdy-plugin"}})) + self.assertEqual(api._metadata_revision(self.plugin), head) + shutil.rmtree(self.plugin / ".git") + # Archive-style installs have no checkout and keep using the installer record. + self.assertEqual(api._metadata_revision(self.plugin), "d" * 40) + + def test_timeout_superseded_by_a_newer_runtime_on_other_bytes_releases_the_host(self): + target, other = "a" * 40, "c" * 40 + with patch.object(api, "LOADED_REVISION", "b" * 40), patch.object(api, "RUNTIME_ID", "runtime_started"): + self.manager.record_runtime_loaded() + self.begin() + self.manager._worker_transition(self.operation_id, "timed_out", "Waiting", target_revision=target, restart_requested_at=1) + with patch.object(api, "_metadata_revision", return_value=other): + # Same lifecycle that started the operation: still ambiguous, still held. + self.assertEqual(self.manager.status(self.operation_id, self.device)["phase"], "timed_out") + with patch.object(api, "LOADED_REVISION", other), patch.object(api, "RUNTIME_ID", "runtime_later"): + self.manager.record_runtime_loaded() + status = self.manager.status(self.operation_id, self.device) + self.assertEqual(status["phase"], "failed") + self.assertIn("Superseded", status["message"]) + self.assertEqual(self.manager.start("update_second_0123456789", self.device, True)["phase"], "accepted") + + def test_timeout_is_held_while_the_target_is_still_installed(self): + target = "a" * 40 + self.begin() + self.manager._worker_transition(self.operation_id, "timed_out", "Waiting", target_revision=target, restart_requested_at=1) + with patch.object(api, "_metadata_revision", return_value=target), patch.object(api, "LOADED_REVISION", "c" * 40), patch.object(api, "RUNTIME_ID", "runtime_later"): + self.manager.record_runtime_loaded() + self.assertEqual(self.manager.status(self.operation_id, self.device)["phase"], "timed_out") + def test_completion_requires_fresh_revision_and_authenticated_owner_response(self): revision = "a" * 40 with patch.object(api, "LOADED_REVISION", revision), patch.object(api, "RUNTIME_ID", "runtime_old"):