From e556a651fa868c96d43ad4bf510be7332af8d700 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:44:09 +0800 Subject: [PATCH 1/4] fix(update): roll back both archive runtime launchers Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/product/release-readiness.md | 21 +-- loopx/self_update.py | 129 +++++++++++++------ tests/test_self_update_runtime_activation.py | 89 ++++++++++++- 3 files changed, 193 insertions(+), 46 deletions(-) diff --git a/docs/product/release-readiness.md b/docs/product/release-readiness.md index 8f94298765..27dcb42698 100644 --- a/docs/product/release-readiness.md +++ b/docs/product/release-readiness.md @@ -47,15 +47,18 @@ activation, and enabled-extension readiness into one "installed" claim. The names the readback and recovery command for each layer. For a pip or pipx distribution, apply delegates to that owner. For an archive -snapshot, apply uses the public `stable` ref by default and preserves atomic -snapshot rollback. Before replacing the launcher, `loopx update --rollback -previous` checks that the selected release can read the current authoritative -Todos for registered local File and SQLite Goals. If it cannot verify the read, -the running version and Goal state stay in place. Both the registry's configured -runtime and an explicit runtime override participate in this check. Rollback -holds the installer's existing promotion lock through Todo checks, activation, -Doctor and recovery. Recovery restores only the launcher installed by that -operation, preserving a later replacement. Use a release with a matching state +snapshot, apply uses the public `stable` ref by default. Before replacing the +launchers, `loopx update --rollback previous` checks that the selected release +can read the current authoritative Todos for registered local File and SQLite +Goals. Both the registry's configured runtime and an explicit runtime override +participate in this check. Rollback switches `loopx` and an archive-managed +`loopx-apply-rrule` to the selected release under the installer's promotion lock. +A selected release must provide an executable scheduler helper if the helper +is managed by that archive installation. The lock covers Todo checks, both +replacements, Doctor and recovery. On a failed switch or failed core Doctor, +recovery restores the links still owned by the rollback and preserves any +later replacement. A failed extension Doctor leaves the selected release +active so the extension can be repaired. Use a release with a matching state backup if older code cannot read the current data. Use `loopx update plan --ref main` and `loopx update apply --ref main` only for maintainer/dev archive qualification. Re-running the curl installer remains a repair path when an diff --git a/loopx/self_update.py b/loopx/self_update.py index f6653c7720..a09ec11bba 100644 --- a/loopx/self_update.py +++ b/loopx/self_update.py @@ -10,6 +10,7 @@ import subprocess import sys import time +from tempfile import TemporaryDirectory import zipimport from typing import Any from urllib.parse import quote @@ -1450,6 +1451,22 @@ def _verify_rollback_todos( raise RuntimeError(refusal) +def _managed_rollback_helper_target(helper: Path, releases_dir: Path) -> str | None: + if not helper.is_symlink(): + return None + previous = os.readlink(helper) + # Allow a prior partial rollback: either release can own this sibling. + # Check the archive launcher path even if that release was pruned. + script = helper.parent / previous + if ( + script.name == helper.name + and script.parent.name == "scripts" + and script.parent.parent.parent.resolve() == releases_dir.resolve() + ): + return previous + return None + + def execute_rollback_plan( payload: dict[str, Any], *, @@ -1479,6 +1496,10 @@ def execute_rollback_plan( route_arguments = _runtime_route_arguments(registry_path, runtime_root) loopx_bin = _user_loopx_bin(home) previous_link_target = os.readlink(loopx_bin) if loopx_bin.is_symlink() else None + primary_was_absent = previous_link_target is None and not os.path.lexists(loopx_bin) + previous_targets = {loopx_bin: previous_link_target} + target_scripts = {loopx_bin: target_script} + helper = loopx_bin.with_name("loopx-apply-rrule") execution: dict[str, Any] = { "target_script": str(target_script), "loopx_command": str(loopx_bin), @@ -1486,9 +1507,14 @@ def execute_rollback_plan( "restored_previous_on_failure": False, } updated = dict(payload) - switched = False + promoted: dict[Path, os.stat_result] = {} + temporary: TemporaryDirectory[str] | None = None promotion_guard = None try: + previous_helper = _managed_rollback_helper_target(helper, release_root.parent) + if previous_helper is not None: + previous_targets[helper] = previous_helper + target_scripts[helper] = target_script.with_name(helper.name) compatible = subprocess.run( [str(target_script), *route_arguments, "--format", "json", "authority-archive", "upgrade", "--all-known", "--require-current"], @@ -1517,17 +1543,35 @@ def execute_rollback_plan( time.sleep(min(0.1, remaining)) if registry_path is not None: _verify_rollback_todos(target_script, registry_path, runtime_root, timeout_seconds=timeout_seconds) - observed_link = os.readlink(loopx_bin) if loopx_bin.is_symlink() else None - if observed_link != previous_link_target: - raise RuntimeError("LoopX launcher changed during rollback checks. Read it back before retrying.") + if previous_helper is not None: + helper_script = target_scripts[helper] + if not helper_script.is_file() or not os.access(helper_script, os.X_OK): + raise RuntimeError( + "Rollback target lacks an executable loopx-apply-rrule. " + "Choose a release containing both managed launchers." + ) + if previous_link_target is None and not primary_was_absent: + raise RuntimeError( + "Cannot roll back the managed launcher pair over a regular loopx command." + ) loopx_bin.parent.mkdir(parents=True, exist_ok=True) - temp_link = loopx_bin.with_name(f".{loopx_bin.name}.rollback.{os.getpid()}") - if temp_link.exists() or temp_link.is_symlink(): - temp_link.unlink() - temp_link.symlink_to(target_script) - promoted_link_stat = temp_link.lstat() - os.replace(temp_link, loopx_bin) - switched = True + temporary = TemporaryDirectory(prefix=".loopx-rollback-", dir=loopx_bin.parent) + staging = Path(temporary.name) + for launcher, script in target_scripts.items(): + observed_link = os.readlink(launcher) if launcher.is_symlink() else None + if observed_link != previous_targets[launcher] or ( + launcher == loopx_bin and primary_was_absent and os.path.lexists(launcher) + ): + raise RuntimeError( + f"LoopX launcher changed during rollback checks ({launcher.name}). " + "Read it back before retrying." + ) + (staging / launcher.name).symlink_to(script) + for launcher in target_scripts: + staged = staging / launcher.name + staged_stat = staged.lstat() + os.replace(staged, launcher) + promoted[launcher] = staged_stat doctor_result = subprocess.run( [str(loopx_bin), *route_arguments, "--format", "json", "doctor"], text=True, encoding="utf-8", errors="replace", @@ -1574,37 +1618,48 @@ def execute_rollback_plan( updated["ok"] = False if doctor_result.returncode != 0: raise RuntimeError("Rollback target failed runtime checks; inspect the Doctor output.") - except Exception as exc: + for launcher, staged_stat in promoted.items(): + if not os.path.samestat(staged_stat, launcher.lstat()): + raise RuntimeError(f"LoopX launcher changed during rollback validation ({launcher.name}).") + except BaseException as exc: execution["error"] = str(exc) updated["ok"] = False - if switched and previous_link_target: - restore_link = loopx_bin.with_name( - f".{loopx_bin.name}.rollback.restore.{os.getpid()}" - ) - try: - if os.path.samestat(promoted_link_stat, loopx_bin.lstat()): - if restore_link.exists() or restore_link.is_symlink(): - restore_link.unlink() - restore_link.symlink_to(previous_link_target) - os.replace(restore_link, loopx_bin) - execution["restored_previous_on_failure"] = True - except Exception as restore_exc: - execution["restore_error"] = str(restore_exc) + restore_errors = [] + if temporary is not None: + for launcher, staged_stat in reversed(promoted.items()): + try: + if not os.path.samestat(staged_stat, launcher.lstat()): + continue + previous = previous_targets[launcher] + if previous is not None: + staged = Path(temporary.name) / launcher.name + staged.symlink_to(previous) + os.replace(staged, launcher) + if launcher == loopx_bin: + execution["restored_previous_on_failure"] = True + elif primary_was_absent: + launcher.unlink() + except OSError as restore_exc: + restore_errors.append(f"{launcher.name}: {restore_exc}") + if restore_errors: + execution["restore_error"] = "\n".join(restore_errors) + if not isinstance(exc, Exception): + raise finally: - if "temp_link" in locals() and (temp_link.exists() or temp_link.is_symlink()): - temp_link.unlink() - if "restore_link" in locals() and ( - restore_link.exists() or restore_link.is_symlink() - ): - restore_link.unlink() - if promotion_guard is not None: - promotion_guard.close() + try: + if temporary is not None: + temporary.cleanup() + finally: + if promotion_guard is not None: + promotion_guard.close() updated["execution"] = execution if updated["ok"]: updated["recommended_action"] = "rollback complete; review doctor output" - elif execution.get("doctor_returncode") == 0 and execution.get( - "extension_doctor_returncode" - ) not in {None, 0}: + elif ( + "error" not in execution + and execution.get("doctor_returncode") == 0 + and execution.get("extension_doctor_returncode") not in {None, 0} + ): updated["recommended_action"] = ( "rollback activated, but one or more enabled extensions remain fail " "closed; repair the provider and run `loopx extension doctor " @@ -1660,6 +1715,8 @@ def render_update_plan_markdown(payload: dict[str, Any]) -> str: lines.extend(["", f"### {label} {stream}", "", "```text", str(output), "```"]) if execution.get("error"): lines.extend(["", f"Error: {execution['error']}"]) + if execution.get("restore_error"): + lines.extend(["", f"Recovery error: {execution['restore_error']}"]) return "\n".join(lines) + "\n" source = payload.get("source") if isinstance(payload.get("source"), dict) else {} diff --git a/tests/test_self_update_runtime_activation.py b/tests/test_self_update_runtime_activation.py index b1647c2e97..380eaa5695 100644 --- a/tests/test_self_update_runtime_activation.py +++ b/tests/test_self_update_runtime_activation.py @@ -980,9 +980,10 @@ def run(command, **kwargs): @pytest.mark.skipif(os.name == "nt", reason="POSIX snapshot rollback") +@pytest.mark.parametrize("with_helper", [False, True]) @pytest.mark.parametrize("failed_stage", [None, "compatibility", "doctor", "extensions"]) def test_rollback_cli_preserves_selected_route_and_failure_boundaries( - tmp_path, monkeypatch, capsys, failed_stage, + tmp_path, monkeypatch, capsys, failed_stage, with_helper, ): from loopx.cli import main from loopx.self_update import render_update_plan_markdown @@ -999,6 +1000,13 @@ def test_rollback_cli_preserves_selected_route_and_failure_boundaries( launcher = tmp_path / "bin/loopx" launcher.parent.mkdir() launcher.symlink_to(current / "scripts/loopx") + helper = launcher.with_name("loopx-apply-rrule") + if with_helper: + for release in (current, target): + script = release / "scripts" / helper.name + script.write_text("#!/bin/sh\nexit 0\n") + script.chmod(0o755) + helper.symlink_to(current / "scripts" / helper.name) monkeypatch.setattr("loopx.self_update._user_loopx_bin", lambda *_: launcher) monkeypatch.setattr("loopx.self_update._user_releases_dir", lambda *_: releases) snapshot = doctor_payload() @@ -1013,6 +1021,8 @@ def run(command, **kwargs): stage = ("compatibility" if "authority-archive" in command else "extensions" if "extension" in command else "doctor") calls.append((stage, command)) + if with_helper and stage != "compatibility": + assert helper.resolve() == target / "scripts" / helper.name passed = stage != failed_stage return subprocess.CompletedProcess( command, 0 if passed else 1, @@ -1053,6 +1063,83 @@ def run(command, **kwargs): assert "cannot read current authority formats" not in rendered expected_release = current if failed_stage in {"compatibility", "doctor"} else target assert launcher.resolve() == expected_release / "scripts/loopx" + if with_helper: + assert helper.resolve() == expected_release / "scripts" / helper.name + else: + assert not os.path.lexists(helper) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX snapshot rollback") +@pytest.mark.parametrize( + "scenario", ["missing_helper", "switch_failure", "later_writer", "interrupted", "foreign", "split"] +) +def test_rollback_reconciles_only_managed_helpers(tmp_path, monkeypatch, scenario): + from loopx.self_update import execute_rollback_plan + + releases = tmp_path / ".local/share/loopx/releases" + current, target, other = (releases / name for name in ("current", "target", "other")) + launcher = tmp_path / ".local/bin/loopx" + helper = launcher.with_name("loopx-apply-rrule") + launcher.parent.mkdir(parents=True) + for release in (current, target, other): + (release / "scripts").mkdir(parents=True) + for command in (launcher, helper): + script = release / "scripts" / command.name + if release == target and command == helper and scenario == "missing_helper": + continue + script.write_text("#!/bin/sh\nexit 0\n") + script.chmod(0o755) + first_helper = ( + tmp_path / "custom-helper" if scenario == "foreign" + else (other if scenario == "split" else current) / "scripts" / helper.name + ) + if scenario == "foreign": + first_helper.touch() + launcher.symlink_to(current / "scripts" / launcher.name) + helper.symlink_to(os.path.relpath(first_helper, helper.parent)) + before = (os.readlink(launcher), os.readlink(helper)) + replace_file = os.replace + + def replace(source, destination): + if scenario == "switch_failure" and destination == helper: + raise OSError("synthetic helper switch failure") + replace_file(source, destination) + + def run(command, **_kwargs): + if scenario == "interrupted" and command[-1] == "doctor": + raise KeyboardInterrupt + if scenario == "later_writer" and command[-1] == "doctor": + replacement = helper.with_name("newer-helper") + replacement.symlink_to(other / "scripts" / helper.name) + replace_file(replacement, helper) + return subprocess.CompletedProcess(command, 1, '{"ok":false}', "") + return subprocess.CompletedProcess(command, 0, '{"ok":true}', "") + + monkeypatch.setattr("loopx.self_update.os.replace", replace) + monkeypatch.setattr("loopx.self_update.subprocess.run", run) + payload = {"ok": True, "plan": {"selected_release_root": str(target)}} + if scenario == "interrupted": + with pytest.raises(KeyboardInterrupt): + execute_rollback_plan(payload, home=tmp_path) + assert (os.readlink(launcher), os.readlink(helper)) == before + return + result = execute_rollback_plan(payload, home=tmp_path) + + if scenario in {"missing_helper", "switch_failure", "later_writer"}: + assert not result["ok"] + assert result["execution"]["restored_previous_on_failure"] is (scenario != "missing_helper") + assert os.readlink(launcher) == before[0] + if scenario == "later_writer": + assert helper.resolve() == other / "scripts" / helper.name + else: + assert os.readlink(helper) == before[1] + else: + assert result["ok"] + assert launcher.resolve() == target / "scripts" / launcher.name + if scenario == "foreign": + assert os.readlink(helper) == before[1] + else: + assert helper.resolve() == target / "scripts" / helper.name @pytest.mark.skipif(os.name == "nt", reason="POSIX snapshot rollback") From 9dda43fae454b598685fba66b4fab627c0a12df8 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:52:28 +0800 Subject: [PATCH 2/4] fix(update): recover archive launcher renames on interrupt Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/product/release-readiness.md | 11 +++---- loopx/self_update.py | 24 +++++++++------ tests/test_self_update_runtime_activation.py | 31 +++++++++++++++----- 3 files changed, 45 insertions(+), 21 deletions(-) diff --git a/docs/product/release-readiness.md b/docs/product/release-readiness.md index 27dcb42698..04b61d407d 100644 --- a/docs/product/release-readiness.md +++ b/docs/product/release-readiness.md @@ -55,11 +55,12 @@ participate in this check. Rollback switches `loopx` and an archive-managed `loopx-apply-rrule` to the selected release under the installer's promotion lock. A selected release must provide an executable scheduler helper if the helper is managed by that archive installation. The lock covers Todo checks, both -replacements, Doctor and recovery. On a failed switch or failed core Doctor, -recovery restores the links still owned by the rollback and preserves any -later replacement. A failed extension Doctor leaves the selected release -active so the extension can be repaired. Use a release with a matching state -backup if older code cannot read the current data. Use `loopx update plan +replacements, Doctor and recovery. When a switch fails, is interrupted during +either replacement, or fails core Doctor, recovery restores the links still +owned by the rollback and preserves any later replacement. A failed extension +Doctor leaves the selected release active so the extension can be repaired. +Use a release with a matching state backup if older code cannot read the +current data. Use `loopx update plan --ref main` and `loopx update apply --ref main` only for maintainer/dev archive qualification. Re-running the curl installer remains a repair path when an archive wrapper is too broken to run its own updater. diff --git a/loopx/self_update.py b/loopx/self_update.py index a09ec11bba..1ee4d0e71c 100644 --- a/loopx/self_update.py +++ b/loopx/self_update.py @@ -1507,7 +1507,7 @@ def execute_rollback_plan( "restored_previous_on_failure": False, } updated = dict(payload) - promoted: dict[Path, os.stat_result] = {} + staged_launchers: dict[Path, os.stat_result] = {} temporary: TemporaryDirectory[str] | None = None promotion_guard = None try: @@ -1566,12 +1566,12 @@ def execute_rollback_plan( f"LoopX launcher changed during rollback checks ({launcher.name}). " "Read it back before retrying." ) - (staging / launcher.name).symlink_to(script) - for launcher in target_scripts: staged = staging / launcher.name - staged_stat = staged.lstat() - os.replace(staged, launcher) - promoted[launcher] = staged_stat + staged.symlink_to(script) + staged_launchers[launcher] = staged.lstat() + # A signal can arrive immediately after the rename. Record ownership first. + for launcher in staged_launchers: + os.replace(staging / launcher.name, launcher) doctor_result = subprocess.run( [str(loopx_bin), *route_arguments, "--format", "json", "doctor"], text=True, encoding="utf-8", errors="replace", @@ -1618,7 +1618,7 @@ def execute_rollback_plan( updated["ok"] = False if doctor_result.returncode != 0: raise RuntimeError("Rollback target failed runtime checks; inspect the Doctor output.") - for launcher, staged_stat in promoted.items(): + for launcher, staged_stat in staged_launchers.items(): if not os.path.samestat(staged_stat, launcher.lstat()): raise RuntimeError(f"LoopX launcher changed during rollback validation ({launcher.name}).") except BaseException as exc: @@ -1626,9 +1626,15 @@ def execute_rollback_plan( updated["ok"] = False restore_errors = [] if temporary is not None: - for launcher, staged_stat in reversed(promoted.items()): + for launcher, staged_stat in reversed(staged_launchers.items()): try: - if not os.path.samestat(staged_stat, launcher.lstat()): + try: + current_stat = launcher.lstat() + except FileNotFoundError: + if launcher == loopx_bin and primary_was_absent: + continue + raise + if not os.path.samestat(staged_stat, current_stat): continue previous = previous_targets[launcher] if previous is not None: diff --git a/tests/test_self_update_runtime_activation.py b/tests/test_self_update_runtime_activation.py index 380eaa5695..2e12835bab 100644 --- a/tests/test_self_update_runtime_activation.py +++ b/tests/test_self_update_runtime_activation.py @@ -4,6 +4,7 @@ import os from pathlib import Path import plistlib +import signal import subprocess import sys import threading @@ -1071,7 +1072,10 @@ def run(command, **kwargs): @pytest.mark.skipif(os.name == "nt", reason="POSIX snapshot rollback") @pytest.mark.parametrize( - "scenario", ["missing_helper", "switch_failure", "later_writer", "interrupted", "foreign", "split"] + "scenario", [ + "missing_helper", "switch_failure", "switch_failure_without_cli", + "signal_after_cli", "signal_after_helper", "later_writer", "interrupted", "foreign", "split", + ], ) def test_rollback_reconciles_only_managed_helpers(tmp_path, monkeypatch, scenario): from loopx.self_update import execute_rollback_plan @@ -1095,17 +1099,24 @@ def test_rollback_reconciles_only_managed_helpers(tmp_path, monkeypatch, scenari ) if scenario == "foreign": first_helper.touch() - launcher.symlink_to(current / "scripts" / launcher.name) + if scenario != "switch_failure_without_cli": + launcher.symlink_to(current / "scripts" / launcher.name) helper.symlink_to(os.path.relpath(first_helper, helper.parent)) - before = (os.readlink(launcher), os.readlink(helper)) + before = (os.readlink(launcher) if launcher.is_symlink() else None, os.readlink(helper)) + fail_before = {"switch_failure": helper, "switch_failure_without_cli": launcher}.get(scenario) + interrupt_after = {"signal_after_cli": launcher, "signal_after_helper": helper}.get(scenario) replace_file = os.replace def replace(source, destination): - if scenario == "switch_failure" and destination == helper: - raise OSError("synthetic helper switch failure") + if destination == fail_before: + raise OSError("synthetic launcher switch failure") replace_file(source, destination) + if destination == interrupt_after and destination.resolve() == target / "scripts" / destination.name: + signal.raise_signal(signal.SIGINT) def run(command, **_kwargs): + if interrupt_after is not None: + assert "authority-archive" in command if scenario == "interrupted" and command[-1] == "doctor": raise KeyboardInterrupt if scenario == "later_writer" and command[-1] == "doctor": @@ -1118,14 +1129,20 @@ def run(command, **_kwargs): monkeypatch.setattr("loopx.self_update.os.replace", replace) monkeypatch.setattr("loopx.self_update.subprocess.run", run) payload = {"ok": True, "plan": {"selected_release_root": str(target)}} - if scenario == "interrupted": + if scenario == "interrupted" or interrupt_after is not None: with pytest.raises(KeyboardInterrupt): execute_rollback_plan(payload, home=tmp_path) assert (os.readlink(launcher), os.readlink(helper)) == before return result = execute_rollback_plan(payload, home=tmp_path) - if scenario in {"missing_helper", "switch_failure", "later_writer"}: + if scenario == "switch_failure_without_cli": + assert not result["ok"] + assert not result["execution"]["restored_previous_on_failure"] + assert "restore_error" not in result["execution"] + assert not os.path.lexists(launcher) + assert os.readlink(helper) == before[1] + elif scenario in {"missing_helper", "switch_failure", "later_writer"}: assert not result["ok"] assert result["execution"]["restored_previous_on_failure"] is (scenario != "missing_helper") assert os.readlink(launcher) == before[0] From 26aedee3d4624d1fdf2ebbcba91ba5e388b44329 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:49:54 +0800 Subject: [PATCH 3/4] fix(update): preserve launchers changed during archive rollback Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/product/release-readiness.md | 9 ++-- loopx/self_update.py | 49 ++++++++++++++----- tests/test_self_update_runtime_activation.py | 51 ++++++++++++++++++++ 3 files changed, 92 insertions(+), 17 deletions(-) diff --git a/docs/product/release-readiness.md b/docs/product/release-readiness.md index 04b61d407d..ff892c7698 100644 --- a/docs/product/release-readiness.md +++ b/docs/product/release-readiness.md @@ -55,10 +55,11 @@ participate in this check. Rollback switches `loopx` and an archive-managed `loopx-apply-rrule` to the selected release under the installer's promotion lock. A selected release must provide an executable scheduler helper if the helper is managed by that archive installation. The lock covers Todo checks, both -replacements, Doctor and recovery. When a switch fails, is interrupted during -either replacement, or fails core Doctor, recovery restores the links still -owned by the rollback and preserves any later replacement. A failed extension -Doctor leaves the selected release active so the extension can be repaired. +replacements, Doctor and recovery. Rollback verifies each destination against +its original inode immediately before replacing it. A changed destination, +an interrupted or failed switch, or a failed core Doctor triggers recovery +only for links still owned by the rollback. A failed extension Doctor leaves +the selected release active so the extension can be repaired. Use a release with a matching state backup if older code cannot read the current data. Use `loopx update plan --ref main` and `loopx update apply --ref main` only for maintainer/dev archive diff --git a/loopx/self_update.py b/loopx/self_update.py index 1ee4d0e71c..ea7d27a8d9 100644 --- a/loopx/self_update.py +++ b/loopx/self_update.py @@ -7,6 +7,7 @@ import os import re import shlex +import stat import subprocess import sys import time @@ -1451,8 +1452,30 @@ def _verify_rollback_todos( raise RuntimeError(refusal) -def _managed_rollback_helper_target(helper: Path, releases_dir: Path) -> str | None: - if not helper.is_symlink(): +def _rollback_launcher_stat(launcher: Path) -> os.stat_result | None: + try: + return launcher.lstat() + except FileNotFoundError: + return None + + +def _verify_rollback_launcher(launcher: Path, original: os.stat_result | None) -> None: + current = _rollback_launcher_stat(launcher) + if original is None: + unchanged = current is None + else: + unchanged = current is not None and os.path.samestat(original, current) + if not unchanged: + raise RuntimeError( + f"LoopX launcher changed during rollback checks ({launcher.name}). " + "Read it back before retrying." + ) + + +def _managed_rollback_helper_target( + helper: Path, releases_dir: Path, original: os.stat_result | None, +) -> str | None: + if original is None or not stat.S_ISLNK(original.st_mode): return None previous = os.readlink(helper) # Allow a prior partial rollback: either release can own this sibling. @@ -1495,8 +1518,12 @@ def execute_rollback_plan( target_script = _release_script(release_root) route_arguments = _runtime_route_arguments(registry_path, runtime_root) loopx_bin = _user_loopx_bin(home) - previous_link_target = os.readlink(loopx_bin) if loopx_bin.is_symlink() else None - primary_was_absent = previous_link_target is None and not os.path.lexists(loopx_bin) + primary_stat = _rollback_launcher_stat(loopx_bin) + previous_link_target = ( + os.readlink(loopx_bin) if primary_stat is not None and stat.S_ISLNK(primary_stat.st_mode) else None + ) + primary_was_absent = primary_stat is None + original_launchers = {loopx_bin: primary_stat} previous_targets = {loopx_bin: previous_link_target} target_scripts = {loopx_bin: target_script} helper = loopx_bin.with_name("loopx-apply-rrule") @@ -1511,8 +1538,10 @@ def execute_rollback_plan( temporary: TemporaryDirectory[str] | None = None promotion_guard = None try: - previous_helper = _managed_rollback_helper_target(helper, release_root.parent) + helper_stat = _rollback_launcher_stat(helper) + previous_helper = _managed_rollback_helper_target(helper, release_root.parent, helper_stat) if previous_helper is not None: + original_launchers[helper] = helper_stat previous_targets[helper] = previous_helper target_scripts[helper] = target_script.with_name(helper.name) compatible = subprocess.run( @@ -1558,19 +1587,13 @@ def execute_rollback_plan( temporary = TemporaryDirectory(prefix=".loopx-rollback-", dir=loopx_bin.parent) staging = Path(temporary.name) for launcher, script in target_scripts.items(): - observed_link = os.readlink(launcher) if launcher.is_symlink() else None - if observed_link != previous_targets[launcher] or ( - launcher == loopx_bin and primary_was_absent and os.path.lexists(launcher) - ): - raise RuntimeError( - f"LoopX launcher changed during rollback checks ({launcher.name}). " - "Read it back before retrying." - ) + _verify_rollback_launcher(launcher, original_launchers[launcher]) staged = staging / launcher.name staged.symlink_to(script) staged_launchers[launcher] = staged.lstat() # A signal can arrive immediately after the rename. Record ownership first. for launcher in staged_launchers: + _verify_rollback_launcher(launcher, original_launchers[launcher]) os.replace(staging / launcher.name, launcher) doctor_result = subprocess.run( [str(loopx_bin), *route_arguments, "--format", "json", "doctor"], diff --git a/tests/test_self_update_runtime_activation.py b/tests/test_self_update_runtime_activation.py index 2e12835bab..7109ad4eaa 100644 --- a/tests/test_self_update_runtime_activation.py +++ b/tests/test_self_update_runtime_activation.py @@ -1159,6 +1159,57 @@ def run(command, **_kwargs): assert helper.resolve() == target / "scripts" / helper.name +@pytest.mark.skipif(os.name == "nt", reason="POSIX archive rollback") +@pytest.mark.parametrize("same_target", [False, True]) +def test_rollback_preserves_helper_replaced_between_renames(tmp_path, monkeypatch, same_target): + from loopx.self_update import execute_rollback_plan + + releases = tmp_path / ".local/share/loopx/releases" + current, target = releases / "current", releases / "target" + launcher = tmp_path / ".local/bin/loopx" + helper = launcher.with_name("loopx-apply-rrule") + launcher.parent.mkdir(parents=True) + for release in (current, target): + scripts = release / "scripts" + scripts.mkdir(parents=True) + for name in (launcher.name, helper.name): + script = scripts / name + script.write_text("#!/bin/sh\nexit 0\n") + script.chmod(0o755) + launcher.symlink_to(current / "scripts" / launcher.name) + helper.symlink_to(current / "scripts" / helper.name) + replacement_target = (current / "scripts" / helper.name if same_target + else tmp_path / "independent-rrule") + replacement_stat = None + replace_file = os.replace + + def replace(source, destination): + nonlocal replacement_stat + replace_file(source, destination) + if destination == launcher and launcher.resolve() == target / "scripts" / launcher.name: + new_helper = helper.with_name("newer-helper") + new_helper.symlink_to(replacement_target) + replace_file(new_helper, helper) + replacement_stat = helper.lstat() + elif destination == helper and helper.resolve() == target / "scripts" / helper.name: + raise OSError("synthetic interruption after the helper rename") + + def run(command, **_kwargs): + assert "authority-archive" in command + return subprocess.CompletedProcess(command, 0, '{"ok":true}', "") + + monkeypatch.setattr("loopx.self_update.os.replace", replace) + monkeypatch.setattr("loopx.self_update.subprocess.run", run) + result = execute_rollback_plan( + {"ok": True, "plan": {"selected_release_root": str(target)}}, home=tmp_path, + ) + assert not result["ok"] and result["execution"]["restored_previous_on_failure"] + assert launcher.resolve() == current / "scripts" / launcher.name + assert replacement_stat is not None and os.path.samestat(helper.lstat(), replacement_stat) + assert helper.resolve() == replacement_target + assert f"launcher changed during rollback checks ({helper.name})" in result["execution"]["error"] + + @pytest.mark.skipif(os.name == "nt", reason="POSIX snapshot rollback") @pytest.mark.parametrize( "target_read", ["compatible", "rejected", "other_revision", "legacy_fallback", "launcher_changed"], From 52efe8d251249df82c54434d3ff32ab95492fe03 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:13:14 +0800 Subject: [PATCH 4/4] fix(update): preserve concurrent launchers during rollback recovery Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/self_update.py | 4 ++ tests/test_self_update_runtime_activation.py | 43 +++++++++++++++----- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/loopx/self_update.py b/loopx/self_update.py index ea7d27a8d9..c947396c44 100644 --- a/loopx/self_update.py +++ b/loopx/self_update.py @@ -1663,6 +1663,10 @@ def execute_rollback_plan( if previous is not None: staged = Path(temporary.name) / launcher.name staged.symlink_to(previous) + # Preparing the restore link can overlap another publisher. + current_stat = _rollback_launcher_stat(launcher) + if current_stat is None or not os.path.samestat(staged_stat, current_stat): + continue os.replace(staged, launcher) if launcher == loopx_bin: execution["restored_previous_on_failure"] = True diff --git a/tests/test_self_update_runtime_activation.py b/tests/test_self_update_runtime_activation.py index 7109ad4eaa..ade9d01b96 100644 --- a/tests/test_self_update_runtime_activation.py +++ b/tests/test_self_update_runtime_activation.py @@ -1161,7 +1161,8 @@ def run(command, **_kwargs): @pytest.mark.skipif(os.name == "nt", reason="POSIX archive rollback") @pytest.mark.parametrize("same_target", [False, True]) -def test_rollback_preserves_helper_replaced_between_renames(tmp_path, monkeypatch, same_target): +@pytest.mark.parametrize("during_restore", [False, True], ids=["activation", "recovery"]) +def test_rollback_preserves_concurrent_helper_replacement(tmp_path, monkeypatch, same_target, during_restore): from loopx.self_update import execute_rollback_plan releases = tmp_path / ".local/share/loopx/releases" @@ -1178,28 +1179,44 @@ def test_rollback_preserves_helper_replaced_between_renames(tmp_path, monkeypatc script.chmod(0o755) launcher.symlink_to(current / "scripts" / launcher.name) helper.symlink_to(current / "scripts" / helper.name) - replacement_target = (current / "scripts" / helper.name if same_target - else tmp_path / "independent-rrule") + owner_release = target if during_restore else current + replacement_target = ( + owner_release / "scripts" / helper.name if same_target else tmp_path / "independent-rrule" + ) replacement_stat = None replace_file = os.replace + create_symlink = Path.symlink_to - def replace(source, destination): + def replace_helper(): nonlocal replacement_stat + new_helper = helper.with_name("newer-helper") + new_helper.symlink_to(replacement_target) + replace_file(new_helper, helper) + replacement_stat = helper.lstat() + + def replace(source, destination): replace_file(source, destination) + if during_restore: + return if destination == launcher and launcher.resolve() == target / "scripts" / launcher.name: - new_helper = helper.with_name("newer-helper") - new_helper.symlink_to(replacement_target) - replace_file(new_helper, helper) - replacement_stat = helper.lstat() + replace_helper() elif destination == helper and helper.resolve() == target / "scripts" / helper.name: raise OSError("synthetic interruption after the helper rename") + def symlink_to(link, link_target, target_is_directory=False): + create_symlink(link, link_target, target_is_directory=target_is_directory) + if during_restore and link.name == helper.name and Path(link_target) == current / "scripts" / helper.name: + replace_helper() + def run(command, **_kwargs): - assert "authority-archive" in command - return subprocess.CompletedProcess(command, 0, '{"ok":true}', "") + if "authority-archive" in command: + return subprocess.CompletedProcess(command, 0, '{"ok":true}', "") + assert during_restore and command[-1] == "doctor" + return subprocess.CompletedProcess(command, 1, '{"ok":false}', "") monkeypatch.setattr("loopx.self_update.os.replace", replace) monkeypatch.setattr("loopx.self_update.subprocess.run", run) + monkeypatch.setattr(Path, "symlink_to", symlink_to) result = execute_rollback_plan( {"ok": True, "plan": {"selected_release_root": str(target)}}, home=tmp_path, ) @@ -1207,7 +1224,11 @@ def run(command, **_kwargs): assert launcher.resolve() == current / "scripts" / launcher.name assert replacement_stat is not None and os.path.samestat(helper.lstat(), replacement_stat) assert helper.resolve() == replacement_target - assert f"launcher changed during rollback checks ({helper.name})" in result["execution"]["error"] + error = result["execution"]["error"] + if during_restore: + assert "failed runtime checks" in error + else: + assert f"launcher changed during rollback checks ({helper.name})" in error @pytest.mark.skipif(os.name == "nt", reason="POSIX snapshot rollback")