From a803ffbba65f1f03f07d26d6d2e5ce26ce089038 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 30 Oct 2026 23:05:10 +0100 Subject: [PATCH] fix(packages): treat a pinned deb as a minimum version Cursor#0 (CI run 40979252521, debian host) installed the pinned cursor_3.27.6 deb on pass 1; its postinst registers Cursor's apt repo, so pass 2's dist-upgrade moved cursor to 3.27.22, and the plan's ansible.builtin.apt deb=<3.27.6> then failed with 'A later version is already installed': the apt module skips only an equal version and otherwise fails or, with allow_downgrade, downgrades. package_install now asks the target before such a call: dpkg-deb --field reads Package and Version from the checksum-verified deb, dpkg-query reads the fully installed version, and dpkg --compare-versions decides; at or above the pin the call is skipped with changed false, so the deploy-time upgrade may move vendor packages forward and the pin never pulls them back. Any query that cannot be read falls through to the apt install, which decides loudly. The dnf path already skips an older local rpm, so both families now behave alike. Co-Authored-By: Claude Opus 5.5 --- plugins/action/package_install.py | 41 +++++- .../test_package_install_deb_minimum.py | 95 ++++++++++++++ .../python/utils/packages/test_installed.py | 108 +++++++++++++++- tests/unit/python/utils/packages/test_plan.py | 20 ++- utils/packages/calls.py | 2 + utils/packages/installed.py | 120 +++++++++++++++++- utils/packages/sources.py | 3 +- 7 files changed, 381 insertions(+), 8 deletions(-) create mode 100644 tests/unit/python/plugins/action/test_package_install_deb_minimum.py diff --git a/plugins/action/package_install.py b/plugins/action/package_install.py index 60012326f1..7d8c410076 100755 --- a/plugins/action/package_install.py +++ b/plugins/action/package_install.py @@ -45,7 +45,16 @@ from utils.packages.calls import ( ModuleCall, ) from utils.packages.facts import distribution_and_family, read_fact -from utils.packages.installed import query_argv, state_holds +from utils.packages.installed import ( + deb_pin, + deb_pin_argv, + installed_version, + installed_version_argv, + minimum_argv, + minimum_reached, + query_argv, + state_holds, +) from utils.packages.outcome import aggregate from utils.packages.plan import build_plan, merge_plans from utils.packages.registry import build_registry, project_root_from_env, resolve @@ -122,6 +131,9 @@ class ActionModule(ActionBase): "msg": f"{', '.join(call.args['name'])} already {call.args['state']}", "module": call.module, } + reached = self._pin_reached(call, task_vars) + if reached is not None: + return {"changed": False, "msg": reached, "module": call.module} if call.retry is None: return self._tagged(call, task_vars, facts) result: dict[str, Any] = {} @@ -140,15 +152,36 @@ class ActionModule(ActionBase): argv = query_argv(call, pkg_mgr) if argv is None: return False + return state_holds(call, pkg_mgr, self._query(argv, task_vars)) + + def _pin_reached(self, call: ModuleCall, task_vars: dict[str, Any]) -> str | None: + argv = deb_pin_argv(call) + if argv is None: + return None + pin = deb_pin(self._query(argv, task_vars)) + if pin is None: + return None + package, pinned = pin + installed = installed_version( + self._query(installed_version_argv(package), task_vars) + ) + if installed is None: + return None + if not minimum_reached(self._query(minimum_argv(installed, pinned), task_vars)): + return None + return ( + f"{package} {installed} already installed, at or above the pinned {pinned}" + ) + + def _query(self, argv: list[str], task_vars: dict[str, Any]) -> dict[str, Any]: try: - result = self._execute_module( + return self._execute_module( module_name="ansible.builtin.command", module_args={"argv": argv, "expand_argument_vars": False}, task_vars=task_vars, ) except AnsibleError: - return False - return state_holds(call, pkg_mgr, result) + return {} def _tagged( self, call: ModuleCall, task_vars: dict[str, Any], facts: dict[str, Any] diff --git a/tests/unit/python/plugins/action/test_package_install_deb_minimum.py b/tests/unit/python/plugins/action/test_package_install_deb_minimum.py new file mode 100644 index 0000000000..9f89bc347f --- /dev/null +++ b/tests/unit/python/plugins/action/test_package_install_deb_minimum.py @@ -0,0 +1,95 @@ +import unittest +import unittest.mock as mock + +from plugins.action.package_install import ActionModule +from utils.packages.calls import DEB_INSTALL, ModuleCall +from utils.packages.outcome import aggregate + +QUERY = "ansible.builtin.command" +DEB = "/var/cache/infinito/packages/cursor_3.27.6_amd64.deb" +PINNED = "3.27.6-1792578269" +FIELDS = {"rc": 0, "stdout": f"Package: cursor\nVersion: {PINNED}\n", "stderr": ""} +MISSING = { + "rc": 1, + "stdout": "", + "stderr": "dpkg-query: no packages found matching cursor", + "failed": True, +} +REACHED = {"rc": 0, "stdout": "", "stderr": ""} +NOT_REACHED = {"rc": 1, "stdout": "", "stderr": "", "failed": True} + + +def _installed(version): + return {"rc": 0, "stdout": f"{version}\tii \n", "stderr": ""} + + +class TestDebPinIsAMinimum(unittest.TestCase): + def _attempt(self, installed, compared=None, fields=FIELDS): + answers = {"dpkg-deb": fields, "dpkg-query": installed, "dpkg": compared} + + def execute(module_name, module_args, **_kwargs): + if module_name != QUERY: + return {"changed": True} + return answers[module_args["argv"][0]] + + action = ActionModule.__new__(ActionModule) + action._task = mock.Mock(args={}) + action._connection = mock.Mock(become=None, transport="local") + action._execute_module = mock.Mock(side_effect=execute) + result = action._attempt( + ModuleCall(DEB_INSTALL, {"deb": DEB}), {}, {"pkg_mgr": "apt"} + ) + return action._execute_module, result + + def _argvs(self, execute): + return [ + call.kwargs["module_args"]["argv"] + for call in execute.call_args_list + if call.kwargs["module_name"] == QUERY + ] + + def _modules(self, execute): + return [call.kwargs["module_name"] for call in execute.call_args_list] + + def test_a_newer_installed_version_skips_the_deb(self): + execute, result = self._attempt(_installed("3.27.22-1793067078"), REACHED) + self.assertEqual(self._modules(execute), [QUERY, QUERY, QUERY]) + self.assertEqual( + self._argvs(execute)[-1], + ["dpkg", "--compare-versions", "3.27.22-1793067078", "ge", PINNED], + ) + self.assertFalse(result["changed"]) + self.assertEqual(result["module"], DEB_INSTALL) + self.assertIn("3.27.22-1793067078", result["msg"]) + self.assertNotIn("failed", aggregate([result], [], "debian")) + + def test_the_pinned_version_installed_skips_the_deb(self): + execute, result = self._attempt(_installed(PINNED), REACHED) + self.assertNotIn(DEB_INSTALL, self._modules(execute)) + self.assertFalse(result["changed"]) + + def test_an_older_installed_version_installs_the_deb(self): + execute, result = self._attempt(_installed("3.27.0-1790000000"), NOT_REACHED) + self.assertEqual(self._modules(execute), [QUERY, QUERY, QUERY, DEB_INSTALL]) + self.assertEqual(execute.call_args.kwargs["module_args"], {"deb": DEB}) + self.assertTrue(result["changed"]) + + def test_a_missing_package_installs_the_deb_without_comparing(self): + execute, result = self._attempt(MISSING) + self.assertEqual(self._modules(execute), [QUERY, QUERY, DEB_INSTALL]) + self.assertTrue(result["changed"]) + + def test_the_queries_run_without_variable_expansion(self): + execute, _result = self._attempt(_installed(PINNED), REACHED) + for call in execute.call_args_list: + self.assertFalse(call.kwargs["module_args"]["expand_argument_vars"]) + + def test_an_unreadable_deb_leaves_the_decision_to_apt(self): + execute, _result = self._attempt( + _installed(PINNED), REACHED, fields={"rc": 2, "stdout": "", "stderr": ""} + ) + self.assertEqual(self._modules(execute), [QUERY, DEB_INSTALL]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/packages/test_installed.py b/tests/unit/python/utils/packages/test_installed.py index 8e84634708..911ce7f8d8 100644 --- a/tests/unit/python/utils/packages/test_installed.py +++ b/tests/unit/python/utils/packages/test_installed.py @@ -1,13 +1,25 @@ import unittest from utils.packages.calls import ( + DEB_INSTALL, GENERIC_PACKAGE, STATE_ABSENT, STATE_PRESENT, ModuleCall, package_call, ) -from utils.packages.installed import query_argv, state_holds +from utils.packages.installed import ( + deb_pin, + deb_pin_argv, + installed_version, + installed_version_argv, + minimum_argv, + minimum_reached, + query_argv, + state_holds, +) + +DEB = "/var/cache/infinito/packages/cursor_3.27.6_amd64.deb" def _holds(pkg_mgr, names, state, rc, stdout="", stderr="", **extra): @@ -203,5 +215,99 @@ class TestDoubtRunsTheModule(unittest.TestCase): self.assertFalse(state_holds(call, "apt", {"failed": True, "msg": "boom"})) +class TestDebPinArgv(unittest.TestCase): + def test_a_local_deb_install_reads_its_control_fields(self): + argv = deb_pin_argv(ModuleCall(DEB_INSTALL, {"deb": DEB})) + self.assertEqual(argv, ["dpkg-deb", "--field", DEB, "Package", "Version"]) + + def test_a_deb_install_with_further_arguments_is_not_read(self): + call = ModuleCall(DEB_INSTALL, {"deb": DEB, "allow_downgrade": True}) + self.assertIsNone(deb_pin_argv(call)) + + def test_a_relative_deb_path_is_not_read(self): + self.assertIsNone(deb_pin_argv(ModuleCall(DEB_INSTALL, {"deb": "-x.deb"}))) + + def test_other_modules_are_not_read(self): + call = ModuleCall("ansible.builtin.dnf", {"deb": DEB}) + self.assertIsNone(deb_pin_argv(call)) + self.assertIsNone(deb_pin_argv(package_call(["cursor"], STATE_PRESENT))) + + +class TestDebPin(unittest.TestCase): + def _pin(self, stdout, rc=0): + return deb_pin({"rc": rc, "stdout": stdout, "stderr": ""}) + + def test_package_and_version_are_read_with_epoch_and_revision(self): + self.assertEqual( + self._pin("Package: cursor\nVersion: 1:3.27.6-1792578269\n"), + ("cursor", "1:3.27.6-1792578269"), + ) + + def test_a_missing_field_proves_nothing(self): + self.assertIsNone(self._pin("Package: cursor\n")) + self.assertIsNone(self._pin("Package: cursor\nVersion: \n")) + + def test_a_foreign_line_proves_nothing(self): + self.assertIsNone(self._pin("Package: cursor\nVersion: 3.27.6\nnoise\n")) + + def test_a_failing_read_proves_nothing(self): + self.assertIsNone(self._pin("Package: cursor\nVersion: 3.27.6\n", rc=2)) + self.assertIsNone(deb_pin({})) + + +class TestInstalledVersion(unittest.TestCase): + def _installed(self, stdout, rc=0, **extra): + return installed_version({"rc": rc, "stdout": stdout, "stderr": "", **extra}) + + def test_dpkg_query_reports_version_then_status_of_the_one_package(self): + argv = installed_version_argv("cursor") + self.assertEqual(argv[:2], ["dpkg-query", "--show"]) + self.assertEqual(argv[2], "--showformat=${Version}\t${db:Status-Abbrev}\n") + self.assertEqual(argv[-2:], ["--", "cursor"]) + + def test_a_fully_installed_package_reports_its_version(self): + self.assertEqual( + self._installed("3.27.22-1793067078\tii \n"), "3.27.22-1793067078" + ) + self.assertEqual( + self._installed("3.27.22-1793067078\thi "), "3.27.22-1793067078" + ) + + def test_a_missing_package_has_no_version(self): + self.assertIsNone(self._installed("", rc=1)) + + def test_a_package_not_fully_installed_has_no_version(self): + for stdout in ("3.27.6\trc ", "3.27.6\tiU ", "3.27.6\tiiR", "\tii "): + with self.subTest(stdout=stdout): + self.assertIsNone(self._installed(stdout)) + + def test_several_architectures_have_no_single_version(self): + self.assertIsNone(self._installed("3.27.6\tii \n3.27.6\tii \n")) + + def test_a_check_mode_skip_has_no_version(self): + self.assertIsNone(self._installed("3.27.6\tii ", skipped=True)) + + +class TestMinimum(unittest.TestCase): + def test_dpkg_compares_installed_against_the_pin(self): + self.assertEqual( + minimum_argv("3.27.22-1793067078", "3.27.6-1792578269"), + [ + "dpkg", + "--compare-versions", + "3.27.22-1793067078", + "ge", + "3.27.6-1792578269", + ], + ) + + def test_only_exit_zero_reaches_the_minimum(self): + self.assertTrue(minimum_reached({"rc": 0})) + self.assertFalse(minimum_reached({"rc": 1, "failed": True})) + self.assertFalse(minimum_reached({"rc": 2, "failed": True})) + self.assertFalse(minimum_reached({"rc": 0, "skipped": True})) + self.assertFalse(minimum_reached({})) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/packages/test_plan.py b/tests/unit/python/utils/packages/test_plan.py index aed8afb966..b3752bfb3d 100644 --- a/tests/unit/python/utils/packages/test_plan.py +++ b/tests/unit/python/utils/packages/test_plan.py @@ -2,6 +2,7 @@ import re import unittest from utils.packages.calls import STATE_ABSENT, STATE_PRESENT +from utils.packages.installed import deb_pin_argv from utils.packages.plan import build_plan, merge_plans from utils.packages.schema import ( SOURCE_AUR, @@ -248,7 +249,24 @@ class TestDownloadSource(unittest.TestCase): self.assertEqual( fetch.args["dest"], f"{DOWNLOAD_CACHE_DIR}/editor_1.2.3_amd64.deb" ) - self.assertEqual(install.args["deb"], fetch.args["dest"]) + self.assertEqual(install.args, {"deb": fetch.args["dest"]}) + + def test_the_deb_install_is_the_call_the_minimum_check_reads(self): + plan = build_plan( + PackageSpec(("editor",), source=SOURCE_DOWNLOAD, download=_DEB), + STATE_PRESENT, + ) + install = _only(plan, "ansible.builtin.apt") + self.assertEqual( + deb_pin_argv(install), + [ + "dpkg-deb", + "--field", + f"{DOWNLOAD_CACHE_DIR}/editor_1.2.3_amd64.deb", + "Package", + "Version", + ], + ) def test_the_rpm_is_installed_from_the_fetched_path(self): plan = build_plan( diff --git a/utils/packages/calls.py b/utils/packages/calls.py index 714183b574..15cc86ef3a 100644 --- a/utils/packages/calls.py +++ b/utils/packages/calls.py @@ -19,6 +19,8 @@ GENERIC_PACKAGE = "ansible.builtin.package" lives in Ansible's action plugin. The action plugin here executes modules directly, so it must swap this marker for the host's `ansible_facts.pkg_mgr`.""" +DEB_INSTALL = "ansible.builtin.apt" + @dataclass(frozen=True) class RetryPolicy: diff --git a/utils/packages/installed.py b/utils/packages/installed.py index 3765874367..67e50b0b7f 100644 --- a/utils/packages/installed.py +++ b/utils/packages/installed.py @@ -10,7 +10,13 @@ import re from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from utils.packages.calls import GENERIC_PACKAGE, STATE_PRESENT, STATES, ModuleCall +from utils.packages.calls import ( + DEB_INSTALL, + GENERIC_PACKAGE, + STATE_PRESENT, + STATES, + ModuleCall, +) if TYPE_CHECKING: from collections.abc import Callable @@ -29,6 +35,8 @@ C_LOCALE = ("env", "LC_ALL=C") """The not-found messages are translated; only the C locale makes them comparable.""" +DEB_FIELDS: tuple[str, ...] = ("Package", "Version") + def _dpkg_entry(line: str) -> tuple[str, str] | None: name, tab, abbrev = line.partition("\t") @@ -171,3 +179,113 @@ def _states( ): return None return {**states, **{name: set() for name in missing}} + + +def _succeeded_stdout(result: dict[str, Any]) -> list[str] | None: + stdout = result.get("stdout") + if result.get("skipped") or result.get("rc") != 0 or not isinstance(stdout, str): + return None + return stdout.splitlines() + + +def deb_pin_argv(call: ModuleCall) -> list[str] | None: + """ + Args: + call: one module call of a package plan. + + Returns: + the argv reading :data:`DEB_FIELDS` out of the deb *call* installs, or + None unless *call* installs one local deb file and nothing else. + """ + deb = call.args.get("deb") + if ( + call.module != DEB_INSTALL + or call.become_user is not None + or set(call.args) != {"deb"} + or not isinstance(deb, str) + or not deb.startswith("/") + ): + return None + return ["dpkg-deb", "--field", deb, *DEB_FIELDS] + + +def deb_pin(result: dict[str, Any]) -> tuple[str, str] | None: + """ + Args: + result: the ``ansible.builtin.command`` result of :func:`deb_pin_argv`. + + Returns: + ``(package, version)`` from the deb's control file, or None when the + answer cannot be read in full. + """ + lines = _succeeded_stdout(result) + if lines is None: + return None + fields = {key: value for key, _, value in (line.partition(": ") for line in lines)} + if ( + len(fields) != len(lines) + or set(fields) != set(DEB_FIELDS) + or not all(fields.values()) + ): + return None + return fields["Package"], fields["Version"] + + +def installed_version_argv(package: str) -> list[str]: + """ + Args: + package: the ``Package`` field of the pinned deb. + + Returns: + the argv asking dpkg for the installed version and status of *package*. + """ + return [ + "dpkg-query", + "--show", + "--showformat=${Version}\t${db:Status-Abbrev}\n", + "--", + package, + ] + + +def installed_version(result: dict[str, Any]) -> str | None: + """ + Args: + result: the ``ansible.builtin.command`` result of + :func:`installed_version_argv`. + + Returns: + the version of the one fully installed instance, or None when the + package is missing, half installed, installed for several + architectures, or the answer cannot be read. + """ + lines = _succeeded_stdout(result) + if lines is None or len(lines) != 1: + return None + entry = _dpkg_entry(lines[0]) + if entry is None or not entry[0] or entry[1] != INSTALLED: + return None + return entry[0] + + +def minimum_argv(installed: str, pinned: str) -> list[str]: + """ + Args: + installed: the version dpkg reports installed. + pinned: the version in the pinned deb's control file. + + Returns: + the argv that exits 0 when *installed* is at or above *pinned*. + """ + return ["dpkg", "--compare-versions", installed, "ge", pinned] + + +def minimum_reached(result: dict[str, Any]) -> bool: + """ + Args: + result: the ``ansible.builtin.command`` result of :func:`minimum_argv`. + + Returns: + True only when dpkg ran and exited 0. + """ + return not result.get("skipped") and result.get("rc") == 0 diff --git a/utils/packages/sources.py b/utils/packages/sources.py index ba54ccc0ad..a0e0c290cc 100644 --- a/utils/packages/sources.py +++ b/utils/packages/sources.py @@ -13,6 +13,7 @@ from urllib.parse import urlsplit from utils.packages.calls import ( AUR_FETCH, + DEB_INSTALL, EXTERNAL_FETCH, STATE_PRESENT, ModuleCall, @@ -124,7 +125,7 @@ def download_calls(names: list[str], download: dict[str, Any]) -> list[ModuleCal if artefact.suffix == ".deb": prerequisites = [package_call([DEB_CONTROL_TOOL], STATE_PRESENT)] - install = ModuleCall("ansible.builtin.apt", {"deb": dest}) + install = ModuleCall(DEB_INSTALL, {"deb": dest}) elif artefact.suffix == ".rpm": prerequisites = [] install = ModuleCall(