Skip to content
25 changes: 15 additions & 10 deletions docs/product/release-readiness.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,21 @@ 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
backup if older code cannot read the current data. Use `loopx update plan
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. 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
qualification. Re-running the curl installer remains a repair path when an
archive wrapper is too broken to run its own updater.
Expand Down
164 changes: 127 additions & 37 deletions loopx/self_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
import os
import re
import shlex
import stat
import subprocess
import sys
import time
from tempfile import TemporaryDirectory
import zipimport
from typing import Any
from urllib.parse import quote
Expand Down Expand Up @@ -1450,6 +1452,44 @@ def _verify_rollback_todos(
raise RuntimeError(refusal)


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.
# 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],
*,
Expand Down Expand Up @@ -1478,17 +1518,32 @@ 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_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")
execution: dict[str, Any] = {
"target_script": str(target_script),
"loopx_command": str(loopx_bin),
"previous_link_target": previous_link_target,
"restored_previous_on_failure": False,
}
updated = dict(payload)
switched = False
staged_launchers: dict[Path, os.stat_result] = {}
temporary: TemporaryDirectory[str] | None = None
promotion_guard = None
try:
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(
[str(target_script), *route_arguments, "--format", "json", "authority-archive", "upgrade",
"--all-known", "--require-current"],
Expand Down Expand Up @@ -1517,17 +1572,29 @@ 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():
_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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 第二次 rename 前复检 helper 的当前归属。 这里使用的是暂存时的观察。实际切换主 CLI 后,让独立程序替换尚未写过的 helper。下一次 rename 覆盖了较新的 inode,随后 SIGINT 使恢复写回早先捕获的链接。File 和 SQLite 都可复现。请在每个入口自己的 rename 前复检原观察,发现变化时中止并只恢复本次仍拥有的写入。

doctor_result = subprocess.run(
[str(loopx_bin), *route_arguments, "--format", "json", "doctor"],
text=True, encoding="utf-8", errors="replace",
Expand Down Expand Up @@ -1574,37 +1641,58 @@ 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 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:
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(staged_launchers.items()):
try:
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:
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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 请在恢复暂存链接后再次核对目标 inode。File 和 SQLite 上,核心 Doctor 失败后,回退先读到自己发布的助手 inode 并暂存旧链接。此时独立进程原子替换现行助手,随后这次 rename 又覆盖了较新的 inode。请将第二次归属校验放在恢复写入前,并补上这个恢复窗口的测试。

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 "
Expand Down Expand Up @@ -1660,6 +1748,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 {}
Expand Down
Loading
Loading