Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions loopx/cli_commands/update_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,112 @@

from __future__ import annotations

from collections.abc import Callable
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 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, "<verified LoopX package>")
result.stderr = result.stderr.replace(artifact_url, "<verified LoopX package>")
return result


def prepare_target(payload: dict[str, Any], *, freshness: dict, resolve_remote: bool,
Expand Down
2 changes: 1 addition & 1 deletion loopx/control_plane/heartbeat/installed_prompt_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 7 additions & 6 deletions loopx/self_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -1105,13 +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]] = {}
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,
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}")
Expand Down
3 changes: 2 additions & 1 deletion tests/control_plane/test_automation_prompt_upgrade.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions tests/test_chat_runtime_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, {})
),
Expand Down
55 changes: 54 additions & 1 deletion tests/test_self_update_runtime_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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 "<verified LoopX package>" 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"}
Expand Down