From b21697fb0c625603199e79abfbd950e2d38e8e0e Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Thu, 3 Dec 2026 18:07:49 +0800 Subject: [PATCH 1/2] Verify the pip target before updating an installed monolith Signed-off-by: lusendong.6789 --- loopx/cli_commands/update_source.py | 61 ++++++++++++++++++++ loopx/self_update.py | 44 ++++++++++++-- tests/test_chat_runtime_activation.py | 1 + tests/test_self_update_runtime_activation.py | 55 +++++++++++++++++- 4 files changed, 154 insertions(+), 7 deletions(-) diff --git a/loopx/cli_commands/update_source.py b/loopx/cli_commands/update_source.py index 4112c81bb7..0369a0eaf4 100644 --- a/loopx/cli_commands/update_source.py +++ b/loopx/cli_commands/update_source.py @@ -7,10 +7,71 @@ from __future__ import annotations +import json +import re +import subprocess from typing import Any +from urllib.parse import urlsplit from .update_artifact import resolve_artifact, target_direction from ..activation_qualification import runtime_activation_qualification +from ..python_install_owner import SPLIT_UPDATE_GUIDANCE + + +def pin_pip_update_target( + command: list[str], *, installed_version: object, timeout_seconds: int, +) -> str: + """Resolve the real pip target and return an immutable install requirement.""" + result = subprocess.run( + [*command[:-1], "--dry-run", "--quiet", "--disable-pip-version-check", "--report", "-", command[-1]], + text=True, encoding="utf-8", errors="replace", capture_output=True, timeout=timeout_seconds, + ) + if result.returncode: + raise ValueError("pip could not resolve the in-place update target. Inspect the pip installation source.") + + unverified = "pip could not verify the exact LoopX package for an in-place update." + try: + report = json.loads(result.stdout) + if report["version"] not in {"0", "1"} or not isinstance(report["install"], list): + raise ValueError + packages = { + re.sub(r"[-_.]+", "-", item["metadata"]["name"].lower()): item + for item in report["install"] + } + if len(packages) != len(report["install"]): + raise ValueError + except (AttributeError, KeyError, TypeError, ValueError): + raise ValueError(unverified) from None + + target = packages.get("loopx") + requirements = target["metadata"].get("requires_dist", []) if target is not None else [] + if not isinstance(requirements, list) or not all(isinstance(item, str) for item in requirements): + raise ValueError(unverified) + if "loopx-core" in packages or any( + re.match(r"^\s*loopx[-_.]+core(?=$|[\s\[(;@<>=!~])", item, re.IGNORECASE) + for item in requirements + ): + raise ValueError(f"The selected LoopX package changes file ownership to the split layout. {SPLIT_UPDATE_GUIDANCE}") + + if target is None: + # Keep the existing distribution selected while preserving pip's normal + # dependency handling and the runtime's post-install validation. + if not isinstance(installed_version, str) or not re.fullmatch(r"[0-9A-Za-z.!+_-]+", installed_version): + raise ValueError(unverified) + return f"loopx=={installed_version}" + try: + download = target["download_info"] + url = download["url"].partition("#")[0] + archive = download["archive_info"] + legacy = re.fullmatch(r"sha256=([0-9a-fA-F]{64})", archive.get("hash", "")) + digest = archive.get("hashes", {}).get("sha256") or (legacy[1] if legacy else "") + if urlsplit(url).scheme not in {"https", "http", "file"} or any(character.isspace() for character in url): + raise ValueError + if not re.fullmatch(r"[0-9a-fA-F]{64}", digest): + raise ValueError + except (AttributeError, KeyError, TypeError, ValueError): + raise ValueError(unverified) from None + return f"loopx @ {url}#sha256={digest}" def prepare_target(payload: dict[str, Any], *, freshness: dict, resolve_remote: bool, diff --git a/loopx/self_update.py b/loopx/self_update.py index 1b64976f47..ae0d21cf6d 100644 --- a/loopx/self_update.py +++ b/loopx/self_update.py @@ -1105,13 +1105,45 @@ def _execute_python_distribution_update( previous_identity = release_runtime_identity(Path(__file__).resolve().parents[1]) installed_identity: dict[str, Any] = {} results: dict[str, subprocess.CompletedProcess[str]] = {} + pinned_artifact = "" + if driver == "python_pip": + from .cli_commands.update_source import pin_pip_update_target + + progress("Checking the Python package selected by pip") + try: + requirement = pin_pip_update_target( + install_command, installed_version=previous_identity.get("package_version") + or payload.get("current", {}).get("current_version"), + timeout_seconds=timeout_seconds, + ) + except ValueError as exc: + reason = str(exc) + return { + **payload, "ok": False, "changes_applied": False, + "error": reason, "recommended_action": reason, + "plan": {**payload.get("plan", {}), "apply_supported": False, + "blocked_reason": reason, "mutates_release_install": False}, + "next_action": {"kind": "review_update_target", "command": None, + "mutating": False, "requires_explicit_approval": False, "reason": reason}, + } + install_command = [*install_command[:-1], requirement] + pinned_artifact = requirement.partition(" @ ")[2].partition("#")[0] progress("Updating CLI through its Python package manager") - results["install"] = subprocess.run( - commands["install"], - text=True, encoding="utf-8", errors="replace", - capture_output=True, - timeout=timeout_seconds, - ) + try: + results["install"] = subprocess.run( + install_command, + text=True, encoding="utf-8", errors="replace", + capture_output=True, + timeout=timeout_seconds, + ) + except subprocess.TimeoutExpired as exc: + raise subprocess.TimeoutExpired(commands["install"], exc.timeout) from None + if pinned_artifact: + # pip can mention a signed download URL in its output. Keep it out of + # the persisted operation receipt. + result = results["install"] + result.stdout = result.stdout.replace(pinned_artifact, "") + result.stderr = result.stderr.replace(pinned_artifact, "") if results["install"].returncode == 0: for step in ("installation_readback", *host_steps): progress(f"Validating updated runtime: {step}") diff --git a/tests/test_chat_runtime_activation.py b/tests/test_chat_runtime_activation.py index 65e6128636..c855966817 100644 --- a/tests/test_chat_runtime_activation.py +++ b/tests/test_chat_runtime_activation.py @@ -687,6 +687,7 @@ def test_update_keeps_install_readback_but_does_not_claim_deferred_service_is_se "scope": "installation_only", "service_runtime_identity": installed}), "") with ( mock.patch("loopx.self_update.release_runtime_identity", return_value=previous), + mock.patch("loopx.cli_commands.update_source.pin_pip_update_target", return_value="loopx==2.4.0"), mock.patch( "loopx.self_update.run_archive_installer", return_value=(passed, {}) ), diff --git a/tests/test_self_update_runtime_activation.py b/tests/test_self_update_runtime_activation.py index 57027067b7..5b298f3295 100644 --- a/tests/test_self_update_runtime_activation.py +++ b/tests/test_self_update_runtime_activation.py @@ -38,6 +38,11 @@ def identity(fingerprint): "package_version": __version__, "package_fingerprint": "sha256:" + fingerprint * 64} monkeypatch.setattr("loopx.self_update.release_runtime_identity", lambda *_: identity("1")) + # These lifecycle tests start after pip has checked a same-layout target. + monkeypatch.setattr( + "loopx.cli_commands.update_source.pin_pip_update_target", + lambda _command, **_: f"loopx=={__version__}", + ) def doctor(fingerprint="2"): body = {"ok": True, "scope": "installation_only", "service_runtime_identity": identity(fingerprint)} @@ -505,7 +510,7 @@ def test_python_distribution_apply_uses_the_owning_interpreter_pip(python_packag "pip", "install", "--upgrade", - "loopx", + f"loopx=={__version__}", ] assert run.call_args_list[1].args[0][-2:] == ["doctor", "--installation-only"] assert run.call_args_list[2].args[0][-4:] == ["authority-archive", "upgrade", "--all-known", "--execute"] @@ -622,6 +627,54 @@ def test_real_windows_console_refuses_before_starting_installer(tmp_path: Path) assert "loopx.entrypoint" in refusal["next_action"]["command"] +@pytest.mark.parametrize("core_already_present", [False, True]) +def test_pip_apply_refuses_split_target_before_starting_install(monkeypatch, core_already_present): + rows = [{ + "metadata": {"name": "loopx", "requires_dist": ["LoopX_Core (==2.4.2rc1)"]}, + }] + if not core_already_present: + rows.append({"metadata": {"name": "loopx-core"}}) + report = subprocess.CompletedProcess([], 0, json.dumps({"version": "1", "install": rows}), "") + run = mock.Mock(return_value=report) + monkeypatch.setattr("loopx.self_update.subprocess.run", run) + + result = execute_update_plan(apply_plan_for_driver("python_pip")) + + run.assert_called_once() + assert "--dry-run" in run.call_args.args[0] + assert result["ok"] is False and result["changes_applied"] is False + assert result["plan"]["mutates_release_install"] is False + assert result["execution"] is None + assert result["next_action"]["kind"] == "review_update_target" + assert "separate environment" in result["error"] + + +@pytest.mark.parametrize("legacy_report", [False, True]) +def test_pip_update_installs_the_verified_artifact_and_redacts_its_url(monkeypatch, legacy_report): + version = __version__ + artifact = f"https://packages.example.invalid/loopx-{version}-py3-none-any.whl?access=fixture" + digest = "a" * 64 + archive = {"hash": "sha256=" + digest} if legacy_report else {"hashes": {"sha256": digest}} + target = {"metadata": {"name": "loopx", "version": version}, + "download_info": {"url": artifact, "archive_info": archive}} + report_version = "0" if legacy_report else "1" + report = subprocess.CompletedProcess([], 0, json.dumps({"version": report_version, "install": [target]}), "") + # Failing at the package-manager boundary isolates the next command and its + # error receipt from the unrelated post-install reconciliation steps. + refused = subprocess.CompletedProcess([], 1, "", f"File changed at {artifact}#sha256={digest}") + run = mock.Mock(side_effect=[report, refused]) + monkeypatch.setattr("loopx.self_update.subprocess.run", run) + monkeypatch.setattr("loopx.self_update.restart_services_for_runtime_activation", lambda **_: {}) + + result = execute_update_plan(apply_plan_for_driver("python_pip")) + + assert run.call_count == 2 + assert run.call_args.args[0][-1] == f"loopx @ {artifact}#sha256={digest}" + assert result["ok"] is False and result["changes_applied"] is False + assert artifact not in json.dumps(result) + assert "" in result["execution"]["install_stderr_tail"] + + def test_pipx_distribution_apply_preserves_the_pipx_environment(python_package_readback) -> None: doctor = doctor_payload() doctor["package"] = {"install_kind": "python_distribution"} From ba5f59cc41b0bba7c7ba4ee61ad321fe561189e6 Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Thu, 3 Dec 2026 18:15:25 +0800 Subject: [PATCH 2/2] Preserve package preflight refusals through prompt reconciliation Signed-off-by: lusendong.6789 --- loopx/cli_commands/update_source.py | 41 ++++++++++++++++ .../heartbeat/installed_prompt_update.py | 2 +- loopx/self_update.py | 47 ++++--------------- .../test_automation_prompt_upgrade.py | 3 +- 4 files changed, 52 insertions(+), 41 deletions(-) diff --git a/loopx/cli_commands/update_source.py b/loopx/cli_commands/update_source.py index 0369a0eaf4..66f1b8035e 100644 --- a/loopx/cli_commands/update_source.py +++ b/loopx/cli_commands/update_source.py @@ -7,6 +7,7 @@ from __future__ import annotations +from collections.abc import Callable import json import re import subprocess @@ -74,6 +75,46 @@ def pin_pip_update_target( return f"loopx @ {url}#sha256={digest}" +def install_python_package( + payload: dict[str, Any], command: list[str], *, installed_version: object, + timeout_seconds: int, progress: Callable[[str], None], +) -> subprocess.CompletedProcess[str] | dict[str, Any]: + """Apply the owning package manager command after validating a pip target.""" + install_command = command + artifact_url = "" + if payload["install_lifecycle"]["execution_driver"] == "python_pip": + progress("Checking the Python package selected by pip") + try: + requirement = pin_pip_update_target(command, installed_version=installed_version, timeout_seconds=timeout_seconds) + except ValueError as exc: + reason = str(exc) + return { + **payload, "ok": False, "changes_applied": False, "execution": None, + "error": reason, "recommended_action": reason, + "plan": {**payload.get("plan", {}), "apply_supported": False, + "blocked_reason": reason, "mutates_release_install": False}, + "next_action": {"kind": "review_update_target", "command": None, + "mutating": False, "requires_explicit_approval": False, "reason": reason}, + } + install_command = [*command[:-1], requirement] + artifact_url = requirement.partition(" @ ")[2].partition("#")[0] + progress("Updating CLI through its Python package manager") + try: + result = subprocess.run( + install_command, text=True, encoding="utf-8", errors="replace", + capture_output=True, timeout=timeout_seconds, + ) + except subprocess.TimeoutExpired as exc: + if artifact_url: + raise subprocess.TimeoutExpired(command, exc.timeout) from None + raise + if artifact_url: + # The retained worker output must not expose a signed artifact URL. + result.stdout = result.stdout.replace(artifact_url, "") + result.stderr = result.stderr.replace(artifact_url, "") + return result + + def prepare_target(payload: dict[str, Any], *, freshness: dict, resolve_remote: bool, allow_downgrade: bool) -> dict[str, Any]: if payload["install_lifecycle"]["owner"] != "loopx_release_snapshot" or not payload["install_lifecycle"]["loopx_apply_supported"]: diff --git a/loopx/control_plane/heartbeat/installed_prompt_update.py b/loopx/control_plane/heartbeat/installed_prompt_update.py index 57080add20..557aa3bf12 100644 --- a/loopx/control_plane/heartbeat/installed_prompt_update.py +++ b/loopx/control_plane/heartbeat/installed_prompt_update.py @@ -158,7 +158,7 @@ def update_with_prompts(payload: dict, *, registry: Path, runtime_root: str | No # Do not strand managed prompts after a successful install + core doctor, # but preserve the failed aggregate result and its original repair action. runtime_ready = bool(updated.get("ok")) - execution = updated.get("execution", {}) + execution = updated.get("execution") or {} installed = runtime_ready or ((updated.get("changes_applied") is True or execution.get("package_identity_verified") is True) and execution.get("install_returncode") == 0 diff --git a/loopx/self_update.py b/loopx/self_update.py index ae0d21cf6d..66ee8a7cf0 100644 --- a/loopx/self_update.py +++ b/loopx/self_update.py @@ -1105,45 +1105,14 @@ def _execute_python_distribution_update( previous_identity = release_runtime_identity(Path(__file__).resolve().parents[1]) installed_identity: dict[str, Any] = {} results: dict[str, subprocess.CompletedProcess[str]] = {} - pinned_artifact = "" - if driver == "python_pip": - from .cli_commands.update_source import pin_pip_update_target - - progress("Checking the Python package selected by pip") - try: - requirement = pin_pip_update_target( - install_command, installed_version=previous_identity.get("package_version") - or payload.get("current", {}).get("current_version"), - timeout_seconds=timeout_seconds, - ) - except ValueError as exc: - reason = str(exc) - return { - **payload, "ok": False, "changes_applied": False, - "error": reason, "recommended_action": reason, - "plan": {**payload.get("plan", {}), "apply_supported": False, - "blocked_reason": reason, "mutates_release_install": False}, - "next_action": {"kind": "review_update_target", "command": None, - "mutating": False, "requires_explicit_approval": False, "reason": reason}, - } - install_command = [*install_command[:-1], requirement] - pinned_artifact = requirement.partition(" @ ")[2].partition("#")[0] - progress("Updating CLI through its Python package manager") - try: - results["install"] = subprocess.run( - install_command, - text=True, encoding="utf-8", errors="replace", - capture_output=True, - timeout=timeout_seconds, - ) - except subprocess.TimeoutExpired as exc: - raise subprocess.TimeoutExpired(commands["install"], exc.timeout) from None - if pinned_artifact: - # pip can mention a signed download URL in its output. Keep it out of - # the persisted operation receipt. - result = results["install"] - result.stdout = result.stdout.replace(pinned_artifact, "") - result.stderr = result.stderr.replace(pinned_artifact, "") + from .cli_commands.update_source import install_python_package + installation = install_python_package( + payload, commands["install"], installed_version=previous_identity.get("package_version") + or payload.get("current", {}).get("current_version"), timeout_seconds=timeout_seconds, progress=progress, + ) + if isinstance(installation, dict): + return installation + results["install"] = installation if results["install"].returncode == 0: for step in ("installation_readback", *host_steps): progress(f"Validating updated runtime: {step}") diff --git a/tests/control_plane/test_automation_prompt_upgrade.py b/tests/control_plane/test_automation_prompt_upgrade.py index 54f1ffbdc1..3c662152ec 100644 --- a/tests/control_plane/test_automation_prompt_upgrade.py +++ b/tests/control_plane/test_automation_prompt_upgrade.py @@ -377,7 +377,8 @@ def forbidden(*args, **kwargs): raise AssertionError("failed installer must not invoke prompt writer") monkeypatch.setattr(lifecycle.subprocess, "run", forbidden) result = lifecycle.update_with_prompts({}, registry=registry, runtime_root=None, - timeout_seconds=1, runtime_update=lambda payload, **_: {"ok": False}) + timeout_seconds=1, + runtime_update=lambda payload, **_: {"ok": False, "changes_applied": False, "execution": None}) assert result["automation_prompt_upgrade"]["status"] == "skipped_runtime_update_failed" assert path.read_bytes() == original