Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep the working llama.cpp install when a prebuilt update can't move it aside (#9221)
Nilay80484ef6107c
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 535115a80b2..a807c3eaa8a 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -4172,11 +4172,87 @@ def unique_install_side_path(install_dir: Path, label: str) -> Path:return candidate+def replace_with_busy_retry(+ src: Path,+ dst: Path,+ *,+ attempts: int = 8,+) -> None:+ """``os.replace``, retried against transient Windows sharing violations.++ WinError 5/32/145 means a scanner still holds a handle inside the tree,+ which clears in a second or two; without a backoff that turns an update+ into a failure, and on the aside-move of the *existing* install that is the+ failure this installer most needs to avoid. Mirrors the Node installer's+ ``_replace_with_retry``. Other errors raise at once, and POSIX never+ retries because EACCES/EBUSY there mean a permission or mount problem no+ amount of waiting clears.+ """+ if attempts < 1:+ raise ValueError("replace_with_busy_retry needs at least one attempt")+ delay = 0.25+ for attempt in range(attempts):+ try:+ os.replace(src, dst)+ return+ except OSError as exc:+ transient = os.name == "nt" and getattr(exc, "winerror", None) in (5, 32, 145)+ if not transient or attempt == attempts - 1:+ raise+ log(+ f"rename {src.name} -> {dst.name} blocked ({exc.winerror}), retrying in "+ f"{delay:.2f}s -- a scanner is likely still holding the install open"+ )+ time.sleep(delay)+ delay = min(delay * 2, 4.0)++def remove_tree(path: Path | None) -> None:if path and path.exists():shutil.rmtree(path, ignore_errors = True)+def _clear_readonly_and_retry(func: Callable[[str], Any], path: str, excinfo: Any) -> None:+ """``shutil.rmtree`` handler that clears the read-only bit and retries.++ Straight out of the shutil docs' rmtree example. Windows refuses to unlink+ a read-only file, and a llama.cpp tree picks that attribute up from its+ archive or a security product, so one read-only DLL would abort a cleanup+ that leaves the install neither replaced nor restored. Two cases are+ refused rather than retried, because the retry does more damage than the+ original error:++ - ``rmtree`` routes ``lstat``/``open``/``scandir``/``islink``/``close``+ failures through this hook too, and none takes a lone path: ``func(path)``+ would raise ``TypeError`` over the real error, or for ``scandir`` return+ an unconsumed iterator and report success for a subtree still on disk.+ - ``os.chmod`` follows symlinks and junctions, so chmod-ing a linked root+ (whose refusal ``rmtree`` also reports here) would repermission a tree+ this installer does not own.+ """+ error = excinfo[1] if isinstance(excinfo, tuple) else excinfo+ if func not in (os.unlink, os.remove, os.rmdir):+ raise error+ if _is_link_or_junction(Path(path)):+ raise error+ os.chmod(path, stat.S_IWRITE)+ func(path)+++def _rmtree_handler_kwargs() -> dict[str, Any]:+ # Windows only: it is the one platform where a read-only entry blocks its+ # own removal. On POSIX the unlink permission lives on the parent, so a+ # chmod of the entry cannot help, and S_IWRITE is an assignment rather than+ # a bit clear, leaving the directory at 0o200 and harder to delete by hand.+ if os.name != "nt":+ return {}+ # onexc replaced the now-deprecated onerror in 3.12; both pass+ # (function, path, error), so one handler covers the 3.9 floor.+ if sys.version_info >= (3, 12):+ return {"onexc": _clear_readonly_and_retry}+ return {"onerror": _clear_readonly_and_retry}++def remove_tree_logged(path: Path | None, label: str) -> None:if not path:return@@ -4185,7 +4261,7 @@ def remove_tree_logged(path: Path | None, label: str) -> None:returnlog(f"removing {label} at {path}")try:- shutil.rmtree(path)+ shutil.rmtree(path, **_rmtree_handler_kwargs())except Exception as exc:log(f"failed to remove {label} at {path}: {exc}")raise@@ -4217,6 +4293,72 @@ def cleanup_install_side_paths(raise RuntimeError("cleanup failed for " + "; ".join(cleanup_failures))+# The tail unique_install_side_path appends after "<name>.<label>-":+# 14 digit UTC timestamp, pid, optional collision counter.+_INSTALL_SIDE_PATH_TAIL = re.compile(r"\d{14}-\d+(?:-\d+)?")+++def _install_side_path_candidates(install_dir: Path, label: str) -> list[Path]:+ root = install_dir.parent / INSTALL_STAGING_ROOT_NAME+ if not root.is_dir():+ return []+ # glob.escape because the install directory name reaches here from+ # UNSLOTH_LLAMA_CPP_PATH, and an unescaped bracket in it would match the+ # side paths of a *different* install in the same parent, holding a+ # different install lock.+ prefix = f"{install_dir.name}.{label}-"+ pattern = f"{glob.escape(install_dir.name)}.{label}-*"+ # escape only neutralises * ? and [; the trailing * can still run past the+ # end of this install's name into a sibling called "<name>.rollback-<sfx>",+ # whose side paths share this staging root, so an update here could delete+ # the last retained copy of an install whose lock we do not hold. Hence the+ # tail check rather than a per-install staging namespace: rehoming the+ # staging root would strand every tree a shipped version already parked+ # there. Only our own tail shape matches; a sibling's carries its own+ # ".<label>-" separator. Link roots are excluded: rmtree refuses them, and+ # a linked side path points at a tree this installer did not create.+ return sorted(+ path+ for path in root.glob(pattern)+ if _INSTALL_SIDE_PATH_TAIL.fullmatch(path.name[len(prefix) :])+ and path.is_dir()+ and not _is_link_or_junction(path)+ )+++def prune_stale_install_side_paths(install_dir: Path, *, keep: Iterable[Path | None] = ()) -> int:+ """Drop rollback and failed trees earlier updates parked under the staging root.++ ``activate_install_tree`` retains an unrestored rollback tree on purpose:+ when it gives up, that tree is the only llama.cpp left. Nothing else ever+ removes those paths, so without a sweep every failed update parks another+ multi-gigabyte copy for good. They are only safe to drop where the caller+ can show they are no longer the last copy, hence the explicit ``keep``.+ """+ kept: set[Path] = set()+ for path in keep:+ if not path:+ continue+ try:+ kept.add(path.resolve())+ except OSError:+ continue+ removed = 0+ for label in ("rollback", "failed"):+ for candidate in _install_side_path_candidates(install_dir, label):+ try:+ if candidate.resolve() in kept:+ continue+ except OSError:+ continue+ try:+ remove_tree_logged(candidate, f"stale {label} path from an earlier update")+ removed += 1+ except Exception as exc:+ log(f"could not remove stale {label} path {candidate}: {exc}")+ return removed++def confirm_install_tree(install_dir: Path, host: HostInfo) -> None:if host.is_windows:expected = [@@ -4241,6 +4383,48 @@ def confirm_install_tree(install_dir: Path, host: HostInfo) -> None:raise RuntimeError("activated install was missing expected files: " + ", ".join(missing))+def _install_tree_is_usable(path: Path, host: HostInfo) -> bool:+ """Whether ``path`` holds a tree ``confirm_install_tree`` would accept.++ Structural only (a handful of ``exists`` checks), so it is cheap enough to+ run on the failure path where the alternative is guessing.+ """+ try:+ confirm_install_tree(path, host)+ except Exception:+ return False+ return True+++def newest_usable_install_side_path(+ install_dir: Path,+ host: HostInfo,+ *,+ exclude: Path | None = None,+) -> Path | None:+ """The most recent retained rollback tree that is still a usable install.++ Candidates sort by the timestamp ``unique_install_side_path`` embeds, so the+ last usable one is the newest. ``failed`` trees are never considered: they+ are the trees that failed confirmation in the first place.+ """+ skip: set[Path] = set()+ if exclude:+ try:+ skip.add(exclude.resolve())+ except OSError:+ pass+ for candidate in reversed(_install_side_path_candidates(install_dir, "rollback")):+ try:+ if candidate.resolve() in skip:+ continue+ except OSError:+ continue+ if _install_tree_is_usable(candidate, host):+ return candidate+ return None++def activate_staged_dir(staging_dir: Path, dst: Path) -> None:"""Move a freshly extracted ``staging_dir`` onto ``dst``.@@ -4273,11 +4457,15 @@ def activate_staged_dir(staging_dir: Path, dst: Path) -> None:def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo) -> None:rollback_dir: Path | None = Nonefailed_dir: Path | None = None+ had_existing = False+ moved_aside = Falsetry:if install_dir.exists():+ had_existing = Truerollback_dir = unique_install_side_path(install_dir, "rollback")log(f"moving existing install to rollback path {rollback_dir}")- os.replace(install_dir, rollback_dir)+ replace_with_busy_retry(install_dir, rollback_dir)+ moved_aside = Truelog(f"moved existing install to rollback path {rollback_dir.name}")log(f"activating staged install {staging_dir} -> {install_dir}")@@ -4288,11 +4476,39 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)log(f"activated install tree confirmed at {install_dir}")except Exception as exc:log(f"activation failed for staged install: {exc}")+ if had_existing and not moved_aside:+ # The aside-move never ran, so install_dir still holds the working+ # install; it must not be moved or cleaned up.+ log("existing install could not be moved aside; leaving it in place")+ if is_busy_lock_error(exc):+ raise BusyInstallConflict(+ "staged prebuilt validation passed but the existing install could not be "+ "moved aside because llama.cpp appears to still be in use; previous install "+ f"left in place ({textwrap.shorten(str(exc), width = 200, placeholder = '...')})"+ ) from exc+ raise PrebuiltFallback(+ "staged prebuilt validation passed but the existing install could not be "+ "moved aside; previous install left in place "+ f"({textwrap.shorten(str(exc), width = 200, placeholder = '...')})"+ ) from exc+ restore_attempted = False+ restored = False+ recovery_error: BaseException | None = Nonetry:if install_dir.exists():failed_dir = unique_install_side_path(install_dir, "failed")log(f"moving failed active install to {failed_dir}")- os.replace(install_dir, failed_dir)+ try:+ os.replace(install_dir, failed_dir)+ except Exception as failed_move_exc:+ failed_dir = None+ log(f"failed active install could not be moved aside: {failed_move_exc}")+ if rollback_dir is None:+ raise+ # install_dir holds the unvalidated staged tree while the+ # only copy of the previous install waits in rollback_dir,+ # so drop it rather than give up on the restore.+ remove_tree_logged(install_dir, "failed active install path")elif staging_dir.exists():failed_dir = staging_dirstaging_dir = None@@ -4300,7 +4516,49 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)if rollback_dir and rollback_dir.exists():log(f"restoring rollback path {rollback_dir} -> {install_dir}")- os.replace(rollback_dir, install_dir)+ restore_attempted = True+ try:+ replace_with_busy_retry(rollback_dir, install_dir)+ except OSError as restore_exc:+ # The rename is the one-step restore; when it cannot run,+ # the rollback tree is the sole remaining llama.cpp, so a+ # copy (slower, needs the space twice) beats handing the+ # user an empty install path. A copy that dies partway+ # leaves install_dir where a bare rename failure would+ # have, and the cleanup below removes it while the rollback+ # tree stays retained.+ if _is_link_or_junction(rollback_dir):+ # The aside-move renamed a link, not a tree. copytree+ # honours symlinks *inside* what it copies but always+ # follows the root, so this would replace a user's+ # --with-llama-cpp-dir link with a real duplicate of a+ # checkout the installer does not own.+ log("previous install is a link; not copying it back")+ raise+ log(+ f"rollback rename failed ({restore_exc}); copying the previous install "+ f"back to {install_dir}"+ )+ try:+ # symlinks = True so a link inside the install is never+ # dereferenced into a real tree; dirs_exist_ok stays off+ # so a leftover tree at install_dir is never merged into+ # a half-and-half install confirm_install_tree accepts.+ shutil.copytree(rollback_dir, install_dir, symlinks = True)+ except Exception as copy_exc:+ log(f"copying the previous install back also failed: {copy_exc}")+ raise restore_exc from copy_exc+ log(f"copied the previous install back to {install_dir}")+ # The install is live again, so the source the copy left+ # behind is dead weight, not the last copy. Failing to+ # remove it costs disk; the next activation sweeps it up.+ try:+ remove_tree_logged(rollback_dir, "copied rollback path")+ except Exception as duplicate_exc:+ log(+ f"non-fatal: the copied rollback path could not be removed: {duplicate_exc}"+ )+ restored = Truelog(f"restored previous install from rollback path {rollback_dir.name}")if is_busy_lock_error(exc):raise BusyInstallConflict(@@ -4315,17 +4573,60 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)except (BusyInstallConflict, PrebuiltFallback):raiseexcept Exception as rollback_exc:- log(f"rollback after failed activation also failed: {rollback_exc}")-- log(- "rollback restoration failed; cleaning staging, install, and rollback paths before source build fallback"- )+ # Kept past the handler: `except` unbinds the name, and the raise+ # below is chained from the activation error, so without this the+ # recovery failure leaves the causal chain entirely.+ recovery_error = rollback_exc+ if restore_attempted:+ log(f"rollback after failed activation also failed: {rollback_exc}")+ else:+ log(f"recovering from the failed activation also failed: {rollback_exc}")++ # An unrestored rollback path is the only copy of the previous install+ # left, so it is kept: cleaning it up would leave no llama.cpp at all+ # on the in-app update path, which has no source build behind it.+ keep_rollback = not restored and rollback_dir is not None and rollback_dir.exists()+ retained_dir = rollback_dir+ if keep_rollback:+ # The tree kept here is whatever sat at install_dir, and after an+ # earlier failed update that can be a partial tree the cleanup below+ # could not remove. Pruning on the strength of an unconfirmed tree+ # would trade the last known-good install for a broken one, so an+ # older rollback that still passes confirm_install_tree wins over a+ # newer one that does not.+ if not _install_tree_is_usable(rollback_dir, host):+ known_good = newest_usable_install_side_path(+ install_dir, host, exclude = rollback_dir+ )+ if known_good is not None:+ log(+ f"rollback path {rollback_dir.name} is not a usable install; keeping the "+ f"known-good {known_good.name} from an earlier failed update instead"+ )+ retained_dir = known_good+ log(f"previous install kept at rollback path {retained_dir}")+ # Cap retention at one: every other tree an earlier failed update+ # left is superseded by the one kept here, and keeping them all+ # turns repeated failure into an unbounded pile. Exactly one tree is+ # ever exempt, so switching which one it is does not grow the cap.+ superseded = prune_stale_install_side_paths(+ install_dir, keep = (retained_dir, failed_dir)+ )+ if superseded:+ log(f"removed {superseded} superseded install tree(s) from earlier failed updates")+ log(+ "rollback restoration failed; cleaning staging, install, and failed paths before source build fallback"+ )+ else:+ log(+ "rollback restoration failed; cleaning staging, install, and rollback paths before source build fallback"+ )cleanup_error: Exception | None = Nonetry:cleanup_install_side_paths(install_dir,staging_dir = staging_dir,- rollback_dir = rollback_dir,+ rollback_dir = None if keep_rollback else rollback_dir,failed_dir = failed_dir,active_dir = install_dir,)@@ -4333,15 +4634,31 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)cleanup_error = cleanup_exclog(f"cleanup after rollback failure also failed: {cleanup_exc}")details = textwrap.shorten(str(exc), width = 200, placeholder = "...")+ kept = f"; previous install kept at {retained_dir}" if keep_rollback else ""+ # The recovery is the first step here that needs free space -- everything+ # before it renames or deletes -- so a disk-full it hits is not implied by+ # the activation error and is often the only place the full disk shows up.+ # _causal_chain follows __cause__ ahead of __context__, so chaining from+ # the activation error alone hides that from _environment_fatal_reason and+ # the caller starts a source build that needs far more room than the copy+ # that just failed. Only the disk-full case swaps the cause; every other+ # failure still surfaces the activation error the message already quotes.+ cause: BaseException = exc+ if (+ recovery_error is not None+ and _environment_fatal_reason(exc) is None+ and _environment_fatal_reason(recovery_error) is not None+ ):+ cause = recovery_errorif cleanup_error is not None:raise PrebuiltFallback("staged prebuilt validation passed but activation and rollback failed; "- f"cleanup also reported errors ({details}; cleanup={cleanup_error})"- ) from exc+ f"cleanup also reported errors ({details}; cleanup={cleanup_error}){kept}"+ ) from causeraise PrebuiltFallback("staged prebuilt validation passed but activation and rollback failed; "- f"cleaned install state for fresh source build ({details})"- ) from exc+ f"cleaned install state for fresh source build ({details}){kept}"+ ) from causeelse:if rollback_dir:try:@@ -4350,6 +4667,12 @@ def activate_install_tree(staging_dir: Path, install_dir: Path, host: HostInfo)log(f"non-fatal: rollback cleanup failed after successful activation: {cleanup_exc}")+ # confirm_install_tree just passed, so anything retained under the+ # staging root is provably no longer the last copy of anything and can+ # go. This is the only point where that is true.+ stale = prune_stale_install_side_paths(install_dir, keep = (rollback_dir,))+ if stale:+ log(f"removed {stale} install tree(s) left behind by earlier failed updates")finally:remove_tree(failed_dir)remove_tree(staging_dir)diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 11e15331d71..8625ad5ef4e 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -25,6 +25,7 @@ sys.modules[SPEC.name] = INSTALL_LLAMA_PREBUILTSPEC.loader.exec_module(INSTALL_LLAMA_PREBUILT)PrebuiltFallback = INSTALL_LLAMA_PREBUILT.PrebuiltFallback+BusyInstallConflict = INSTALL_LLAMA_PREBUILT.BusyInstallConflictbinary_env = INSTALL_LLAMA_PREBUILT.binary_envis_secret_env_name = INSTALL_LLAMA_PREBUILT.is_secret_env_namescrub_env = INSTALL_LLAMA_PREBUILT.scrub_env@@ -39,6 +40,9 @@ validate_prebuilt_choice = INSTALL_LLAMA_PREBUILT.validate_prebuilt_choiceactivate_install_tree = INSTALL_LLAMA_PREBUILT.activate_install_treeactivate_staged_dir = INSTALL_LLAMA_PREBUILT.activate_staged_dircreate_install_staging_dir = INSTALL_LLAMA_PREBUILT.create_install_staging_dir+replace_with_busy_retry = INSTALL_LLAMA_PREBUILT.replace_with_busy_retry+remove_tree_logged = INSTALL_LLAMA_PREBUILT.remove_tree_logged+prune_stale_install_side_paths = INSTALL_LLAMA_PREBUILT.prune_stale_install_side_pathssha256_file = INSTALL_LLAMA_PREBUILT.sha256_filesource_archive_logical_name = INSTALL_LLAMA_PREBUILT.source_archive_logical_nameinstall_prebuilt = INSTALL_LLAMA_PREBUILT.install_prebuilt@@ -776,7 +780,7 @@ def test_activate_install_tree_preserves_symlink_to_resolved_target(assert not (linked_root / "old.txt").exists()-def test_activate_install_tree_cleans_all_paths_when_rollback_restore_fails(+def test_activate_install_tree_keeps_rollback_when_restore_fails(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]):install_dir = tmp_path / "llama.cpp"@@ -818,12 +822,884 @@ def test_activate_install_tree_cleans_all_paths_when_rollback_restore_fails(return original_replace(src, dst)monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)+ # A failed rename is retried by a copy, so retention is only reached once+ # the copy is out of the running too (no space, no permission).+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT.shutil,+ "copytree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ OSError(errno.ENOSPC, "No space left on device")+ ),+ )++ with pytest.raises(PrebuiltFallback, match = "previous install kept at") as excinfo:+ activate_install_tree(staging_dir, install_dir, host)++ assert "cleaned install state for fresh source build" in str(excinfo.value)+ assert not install_dir.exists()+ assert not staging_dir.exists()++ rollbacks = sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*"))+ assert len(rollbacks) == 1+ assert (rollbacks[0] / "old.txt").read_text() == "old install\n"++ captured = capsys.readouterr()+ output = captured.out + captured.err+ assert "rollback after failed activation also failed: restore failed" in output+ assert "previous install kept at rollback path" in output+ assert "cleaning staging, install, and failed paths before source build fallback" in output+ assert "removing failed install path" in output+ assert "removing rollback path" not in output+++def _fail_activation_then_restore_rename(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, copy_error: Exception+) -> tuple[Path, Path]:+ """Activation fails for a reason that is *not* disk-related, the restore rename+ then fails, and the copy back that follows raises ``copy_error``."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def flaky_replace(src, dst):+ if "rollback-" in Path(src).name and Path(dst) == install_dir:+ raise OSError(errno.EACCES, "Access is denied")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT.shutil,+ "copytree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(copy_error),+ )+ return install_dir, staging_dir+++ "make_copy_error",+ [+ # copytree propagates the raw OSError when the destination root itself+ # cannot be created; per-file failures arrive as Error(list-of-strings)+ # with errno and the chain already gone, which only the text carries.+ lambda: OSError(errno.ENOSPC, "No space left on device"),+ lambda: shutil.Error(+ [("src", "dst", "[Errno 28] No space left on device: 'llama-server'")]+ ),+ ],+ ids = ["oserror", "shutil_error"],+)+def test_activate_install_tree_reports_a_recovery_disk_full_as_out_of_space(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, make_copy_error+):+ """The copy back is the first step of this path that needs free space -- every+ step before it renames or deletes -- so a full disk can show up there and+ nowhere else. Dropping it would leave the caller starting a source build that+ needs far more room than the copy that just failed."""+ install_dir, staging_dir = _fail_activation_then_restore_rename(+ tmp_path, monkeypatch, make_copy_error()+ )++ with pytest.raises(PrebuiltFallback) as excinfo:+ activate_install_tree(staging_dir, install_dir, linux_host())++ assert INSTALL_LLAMA_PREBUILT._environment_fatal_reason(excinfo.value) == (+ "no space left on device"+ )+ # The point of the retention is unchanged: the previous install still exists.+ rollbacks = sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*"))+ assert len(rollbacks) == 1+ assert (rollbacks[0] / "old.txt").read_text() == "old install\n"+++def test_activate_install_tree_keeps_the_activation_error_as_the_cause_when_not_out_of_space(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ """Only a disk-full recovery failure replaces the cause: an ordinary one still+ reports the activation error, so the caller keeps its source build fallback."""+ install_dir, staging_dir = _fail_activation_then_restore_rename(+ tmp_path, monkeypatch, OSError(errno.EACCES, "Permission denied")+ )++ with pytest.raises(PrebuiltFallback) as excinfo:+ activate_install_tree(staging_dir, install_dir, linux_host())++ assert isinstance(excinfo.value.__cause__, RuntimeError)+ assert str(excinfo.value.__cause__) == "activation confirm failed"+ assert INSTALL_LLAMA_PREBUILT._environment_fatal_reason(excinfo.value) is None+++def test_activate_install_tree_copies_previous_install_back_when_restore_rename_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def flaky_replace(src, dst):+ if "rollback-" in Path(src).name and Path(dst) == install_dir:+ raise OSError(errno.EACCES, "Access is denied")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)++ with pytest.raises(PrebuiltFallback, match = "activation failed; restored previous install"):+ activate_install_tree(staging_dir, install_dir, linux_host())++ # A copy is attempted before giving up on the install path itself.+ assert (install_dir / "old.txt").read_text() == "old install\n"+ assert not (install_dir / "new.txt").exists()+ assert not staging_dir.exists()+ assert sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*")) == []++ output = "".join(capsys.readouterr())+ assert "copying the previous install back" in output+++def test_activate_install_tree_does_not_follow_a_symlink_out_of_the_install(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "precious.txt").write_text("precious\n")++ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")+ try:+ (install_dir / "link-out").symlink_to(outside, target_is_directory = True)+ except OSError as exc:+ pytest.skip(f"directory symlinks unavailable: {exc}")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def flaky_replace(src, dst):+ if "rollback-" in Path(src).name and Path(dst) == install_dir:+ raise OSError(errno.EACCES, "Access is denied")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)++ with pytest.raises(PrebuiltFallback):+ activate_install_tree(staging_dir, install_dir, linux_host())++ # Every removal and the copy fallback must treat the link as a link; one+ # dereference would wipe a directory outside the install.+ assert (outside / "precious.txt").read_text() == "precious\n"+ assert (install_dir / "link-out").is_symlink()+ assert (install_dir / "old.txt").read_text() == "old install\n"+++def test_replace_with_busy_retry_waits_out_a_transient_windows_lock(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ source = tmp_path / "src"+ source.mkdir()+ (source / "payload.txt").write_text("payload\n")+ destination = tmp_path / "dst"++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace+ attempts = {"count": 0}++ def sharing_violation(src, dst):+ attempts["count"] += 1+ if attempts["count"] < 3:+ exc = OSError(errno.EACCES, "The process cannot access the file")+ exc.winerror = 32+ raise exc+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "name", "nt")+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", sharing_violation)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.time, "sleep", lambda _seconds: None)++ replace_with_busy_retry(source, destination)++ assert attempts["count"] == 3+ assert (destination / "payload.txt").read_text() == "payload\n"+++def test_replace_with_busy_retry_does_not_retry_a_posix_permission_error(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ attempts = {"count": 0}++ def denied(src, dst):+ attempts["count"] += 1+ raise OSError(errno.EACCES, "Permission denied")++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "name", "posix")+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", denied)+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT.time,+ "sleep",+ lambda _seconds: pytest.fail("POSIX permission errors must not be waited out"),+ )++ with pytest.raises(OSError):+ replace_with_busy_retry(tmp_path / "src", tmp_path / "dst")++ assert attempts["count"] == 1+++def test_remove_tree_logged_clears_read_only_files(tmp_path: Path):+ tree = tmp_path / "tree"+ (tree / "nested").mkdir(parents = True)+ locked = tree / "nested" / "locked.bin"+ locked.write_bytes(b"locked")+ os.chmod(locked, stat.S_IRUSR)++ remove_tree_logged(tree, "read only tree")++ assert not tree.exists()+++def test_remove_tree_logged_refuses_a_symlinked_root_without_touching_the_target(tmp_path: Path):+ target = tmp_path / "outside"+ target.mkdir()+ (target / "precious.txt").write_text("precious\n")+ original_mode = stat.S_IMODE(os.stat(target).st_mode)++ link = tmp_path / "link"+ try:+ link.symlink_to(target, target_is_directory = True)+ except OSError as exc:+ pytest.skip(f"directory symlinks unavailable: {exc}")++ # rmtree reports its refusal to run on a link through the read-only+ # handler, which must not chmod or delete through it.+ with pytest.raises(OSError):+ remove_tree_logged(link, "symlinked tree")++ assert link.is_symlink()+ assert (target / "precious.txt").read_text() == "precious\n"+ assert stat.S_IMODE(os.stat(target).st_mode) == original_mode+++def test_activate_install_tree_leaves_a_symlinked_install_target_intact(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ target = tmp_path / "real-install-elsewhere"+ target.mkdir()+ (target / "old.txt").write_text("old install\n")+ original_mode = stat.S_IMODE(os.stat(target).st_mode)++ install_dir = tmp_path / "llama.cpp"+ try:+ install_dir.symlink_to(target, target_is_directory = True)+ except OSError as exc:+ pytest.skip(f"directory symlinks unavailable: {exc}")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", lambda *_args: None)++ activate_install_tree(staging_dir, install_dir, linux_host())++ # The link is renamed aside as a link, so the tree it points at, outside+ # anything this installer owns, must come through untouched.+ assert (install_dir / "new.txt").read_text() == "new install\n"+ assert (target / "old.txt").read_text() == "old install\n"+ assert stat.S_IMODE(os.stat(target).st_mode) == original_mode+++def test_successful_activation_reclaims_side_paths_from_earlier_failed_updates(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)+ stranded = staging_root / "llama.cpp.rollback-20200101000000-1"+ stranded.mkdir()+ (stranded / "old.txt").write_text("stranded\n")+ stale_failed = staging_root / "llama.cpp.failed-20200101000000-1"+ stale_failed.mkdir()+ (stale_failed / "junk.txt").write_text("junk\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", lambda *_args: None)++ activate_install_tree(staging_dir, install_dir, linux_host())++ # A confirmed install is the one moment where a retained copy is provably+ # not the last one, so that is where accumulated trees are reclaimed.+ assert (install_dir / "new.txt").read_text() == "new install\n"+ assert not stranded.exists()+ assert not stale_failed.exists()+ assert not (tmp_path / ".staging").exists()+++def test_failed_activation_does_not_reclaim_side_paths(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)+ stranded = staging_root / "llama.cpp.rollback-20200101000000-1"+ stranded.mkdir()+ (stranded / "old.txt").write_text("stranded\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )++ with pytest.raises(PrebuiltFallback):+ activate_install_tree(staging_dir, install_dir, linux_host())++ assert (install_dir / "old.txt").read_text() == "old install\n"+ assert (stranded / "old.txt").read_text() == "stranded\n"+++def _fail_restore_and_copy(monkeypatch: pytest.MonkeyPatch, install_dir: Path) -> None:+ """Force both ways of putting the previous install back to fail."""+ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def flaky_replace(src, dst):+ if "rollback-" in Path(src).name and Path(dst) == install_dir:+ raise OSError("restore failed")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT.shutil,+ "copytree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ OSError(errno.ENOSPC, "No space left on device")+ ),+ )+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )+++def test_repeated_retention_keeps_exactly_one_previous_install(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ install_dir = tmp_path / "llama.cpp"+ staging_root = tmp_path / ".staging"++ for attempt in range(3):+ install_dir.mkdir(parents = True, exist_ok = True)+ (install_dir / "old.txt").write_text(f"install {attempt}\n")+ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")+ _fail_restore_and_copy(monkeypatch, install_dir)+ with pytest.raises(PrebuiltFallback, match = "previous install kept at"):+ activate_install_tree(staging_dir, install_dir, linux_host())+ monkeypatch.undo()++ # Each retained tree supersedes the last, so repeated failure parks one+ # copy rather than one per attempt.+ rollbacks = sorted(staging_root.glob("llama.cpp.rollback-*"))+ assert len(rollbacks) == 1+ assert (rollbacks[0] / "old.txt").read_text() == "install 2\n"+ assert sorted(staging_root.glob("llama.cpp.failed-*")) == []+++def _write_usable_install(root: Path, marker: bytes) -> None:+ """A tree confirm_install_tree accepts, tagged with recognisable bytes."""+ (root / "build" / "bin").mkdir(parents = True, exist_ok = True)+ for name in ("llama-server", "llama-quantize"):+ (root / name).write_bytes(marker)+ (root / "build" / "bin" / name).write_bytes(marker)+ (root / "convert_hf_to_gguf.py").write_bytes(marker)+ (root / "gguf-py").mkdir(exist_ok = True)+ (root / "UNSLOTH_PREBUILT_INFO.json").write_text("{}\n", encoding = "utf-8")+++def test_retention_keeps_a_known_good_install_over_an_unvalidated_one(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ """Two failed updates in a row must not trade the last good install for a stub.++ Attempt 1 leaves a tree at install_dir that is not a usable install and that+ cleanup cannot remove, so attempt 2 moves exactly that tree into the new+ rollback path. Capping retention on the newer path alone would then delete+ the only llama.cpp the user still has.+ """+ good = b"GOOD-LLAMA-CPP\n"+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ _write_usable_install(install_dir, good)+ staging_root = tmp_path / ".staging"+ host = linux_host()++ real_confirm = INSTALL_LLAMA_PREBUILT.confirm_install_tree+ real_replace = INSTALL_LLAMA_PREBUILT.os.replace+ real_rmtree = INSTALL_LLAMA_PREBUILT.shutil.rmtree++ def confirm_bad_prebuilt(path, host_info, *args, **kwargs):+ # The staged prebuilt is the broken thing, not the check itself, so a+ # check of any other tree still reports the truth about that tree.+ if Path(path) == install_dir:+ raise RuntimeError("activation confirm failed")+ return real_confirm(Path(path), host_info, *args, **kwargs)++ def deny_failed_move(src, dst):+ if "failed-" in Path(dst).name:+ raise OSError(errno.EACCES, "Access is denied")+ return real_replace(src, dst)++ def deny_install_dir_rmtree(path, *args, **kwargs):+ if Path(path) == install_dir:+ raise OSError(errno.EACCES, "Access is denied")+ return real_rmtree(path, *args, **kwargs)++ # Attempt 1: the failed active install can be neither renamed aside nor+ # removed, so install_dir is left holding the unusable staged tree while+ # the working install waits in the rollback path.+ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", confirm_bad_prebuilt)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", deny_failed_move)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.shutil, "rmtree", deny_install_dir_rmtree)+ with pytest.raises(PrebuiltFallback, match = "previous install kept at"):+ activate_install_tree(staging_dir, install_dir, host)+ monkeypatch.undo()++ rollbacks = sorted(staging_root.glob("llama.cpp.rollback-*"))+ assert len(rollbacks) == 1+ real_confirm(rollbacks[0], host)+ with pytest.raises(RuntimeError):+ real_confirm(install_dir, host)++ # Attempt 2: that unusable tree becomes the new rollback path, and the+ # restore fails, which is where retention decides what to drop.+ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", confirm_bad_prebuilt)++ def deny_restore(src, dst):+ if "rollback-" in Path(src).name and Path(dst) == install_dir:+ raise OSError("restore failed")+ return real_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", deny_restore)+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT.shutil,+ "copytree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ OSError(errno.ENOSPC, "No space left on device")+ ),+ )+ with pytest.raises(PrebuiltFallback, match = "previous install kept at"):+ activate_install_tree(staging_dir, install_dir, host)+ monkeypatch.undo()++ survivors = [path for path in staging_root.rglob("llama-server") if path.read_bytes() == good]+ assert survivors, "the last known-good llama.cpp was deleted as superseded"+ # Still capped at one tree: which one is kept changed, not how many.+ rollbacks = sorted(staging_root.glob("llama.cpp.rollback-*"))+ assert len(rollbacks) == 1+ real_confirm(rollbacks[0], host)+ assert (rollbacks[0] / "llama-server").read_bytes() == good+++def test_retention_does_not_copy_a_linked_previous_install(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+):+ target = tmp_path / "user-checkout"+ target.mkdir()+ (target / "old.txt").write_text("user build\n")++ install_dir = tmp_path / "llama.cpp"+ try:+ install_dir.symlink_to(target, target_is_directory = True)+ except OSError as exc:+ pytest.skip(f"directory symlinks unavailable: {exc}")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )+ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def flaky_replace(src, dst):+ if "rollback-" in Path(src).name and Path(dst) == install_dir:+ raise OSError("restore failed")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)+ copied: list[tuple] = []+ original_copytree = INSTALL_LLAMA_PREBUILT.shutil.copytree+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT.shutil,+ "copytree",+ lambda *args, **kwargs: (copied.append(args), original_copytree(*args, **kwargs))[1],+ )++ with pytest.raises(PrebuiltFallback, match = "previous install kept at"):+ activate_install_tree(staging_dir, install_dir, linux_host())++ # copytree follows its source root even with symlinks = True, so copying a+ # linked install would replace the user's own checkout link with a real+ # duplicate of a tree the installer does not own.+ assert copied == []+ assert (target / "old.txt").read_text() == "user build\n"+ assert not (target / "new.txt").exists()+ assert "previous install is a link; not copying it back" in "".join(capsys.readouterr())+++def test_prune_stale_install_side_paths_ignores_another_installs_side_paths(tmp_path: Path):+ # The install directory name comes from UNSLOTH_LLAMA_CPP_PATH, so a glob+ # metacharacter in it must not reach through to a sibling.+ bracketed = tmp_path / "llama[1].cpp"+ bracketed.mkdir()+ sibling = tmp_path / "llama1.cpp"+ sibling.mkdir()+ staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(bracketed)+ victim = staging_root / "llama1.cpp.rollback-20240101000000-1"+ victim.mkdir()++ assert prune_stale_install_side_paths(bracketed) == 0++ assert victim.exists()+++def test_prune_stale_install_side_paths_ignores_a_sibling_named_like_a_side_path(tmp_path: Path):+ # Two installs in one parent share a .staging root but hold *different*+ # locks, since install_lock_path keys on the directory name. glob.escape+ # only neutralises * ? and [, so "<name>.rollback-*" can still run past the+ # end of <name> into a sibling called "<name>.rollback-special": updating+ # the first install would delete that sibling's retained rollback tree,+ # possibly its last copy, along with its live staging dir.+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ sibling = tmp_path / "llama.cpp.rollback-special"+ sibling.mkdir()+ staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)+ assert staging_root == INSTALL_LLAMA_PREBUILT.install_staging_root(sibling)++ own_stale = staging_root / "llama.cpp.rollback-20240101000000-1"+ own_stale.mkdir()+ own_stale_with_counter = staging_root / "llama.cpp.failed-20240101000000-1-2"+ own_stale_with_counter.mkdir()++ sibling_sole_copy = staging_root / "llama.cpp.rollback-special.rollback-20240102000000-2"+ sibling_sole_copy.mkdir()+ (sibling_sole_copy / "llama-server").write_text("the sibling's only llama.cpp\n")+ sibling_failed = staging_root / "llama.cpp.rollback-special.failed-20240102000000-2"+ sibling_failed.mkdir()+ sibling_live_staging = staging_root / "llama.cpp.rollback-special.staging-abcd1234"+ sibling_live_staging.mkdir()++ # Its own retained copies are still reclaimed, counter form included.+ assert prune_stale_install_side_paths(install_dir) == 2+ assert not own_stale.exists()+ assert not own_stale_with_counter.exists()++ assert sibling_sole_copy.exists()+ assert (sibling_sole_copy / "llama-server").read_text() == "the sibling's only llama.cpp\n"+ assert sibling_failed.exists()+ assert sibling_live_staging.exists()++ # And the sibling reclaims its own, without touching its staging dir.+ assert prune_stale_install_side_paths(sibling) == 2+ assert not sibling_sole_copy.exists()+ assert not sibling_failed.exists()+ assert sibling_live_staging.exists()+++def test_replace_with_busy_retry_rejects_a_zero_attempt_budget(tmp_path: Path):+ # Falling off the loop would report a move that never happened, the exact+ # failure the aside-move must never fake.+ with pytest.raises(ValueError):+ replace_with_busy_retry(tmp_path / "src", tmp_path / "dst", attempts = 0)+++def test_readonly_rmtree_handler_only_retries_the_removal_calls(tmp_path: Path):+ handler = INSTALL_LLAMA_PREBUILT._clear_readonly_and_retry+ victim = tmp_path / "victim"+ victim.mkdir()+ error = PermissionError(errno.EACCES, "Permission denied")++ # rmtree routes lstat/open/scandir/islink/close failures through the same+ # hook, and none of those takes a lone path.+ for rejected in (os.open, os.scandir, os.lstat):+ with pytest.raises(PermissionError):+ handler(rejected, str(victim), error)+ with pytest.raises(PermissionError):+ handler(os.open, str(victim), (type(error), error, None))++ assert victim.exists()+++def test_readonly_rmtree_handler_never_chmods_through_a_link(tmp_path: Path):+ target = tmp_path / "outside"+ target.mkdir()+ original_mode = stat.S_IMODE(os.stat(target).st_mode)+ link = tmp_path / "link"+ try:+ link.symlink_to(target, target_is_directory = True)+ except OSError as exc:+ pytest.skip(f"directory symlinks unavailable: {exc}")++ error = OSError("Cannot call rmtree on a symbolic link")+ with pytest.raises(OSError):+ INSTALL_LLAMA_PREBUILT._clear_readonly_and_retry(os.rmdir, str(link), error)++ assert link.is_symlink()+ assert stat.S_IMODE(os.stat(target).st_mode) == original_mode+++def test_remove_tree_logged_leaves_posix_directory_modes_alone(tmp_path: Path):+ if os.name == "nt":+ pytest.skip("the read-only handler is Windows only by design")+ tree = tmp_path / "tree"+ unreadable = tree / "unreadable"+ unreadable.mkdir(parents = True)+ (unreadable / "file.bin").write_bytes(b"x")+ os.chmod(unreadable, 0o500)+ if os.access(unreadable, os.W_OK): # pragma: no cover - root ignores the mode+ pytest.skip("cannot make the directory undeletable for this user")+ try:+ with pytest.raises(OSError):+ remove_tree_logged(tree, "unreadable tree")+ # S_IWRITE is an assignment, not a bit clear, so a handler here would+ # leave the directory at 0o200 and harder to delete by hand. On POSIX+ # the unlink permission lives on the parent anyway, so a chmod of this+ # entry could not have fixed anything.+ assert stat.S_IMODE(os.stat(unreadable).st_mode) == 0o500+ finally:+ if unreadable.exists():+ os.chmod(unreadable, 0o700)+++def test_prune_stale_install_side_paths_keeps_the_paths_it_is_told_to_keep(tmp_path: Path):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)+ keeper = staging_root / "llama.cpp.rollback-20250101000000-2"+ keeper.mkdir()+ doomed = staging_root / "llama.cpp.rollback-20200101000000-1"+ doomed.mkdir()++ assert prune_stale_install_side_paths(install_dir, keep = (keeper, None)) == 1++ assert keeper.exists()+ assert not doomed.exists()+++def test_activate_install_tree_keeps_existing_install_when_aside_move_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def cross_device_replace(src, dst):+ if Path(src) == install_dir:+ raise OSError(errno.EXDEV, "Invalid cross-device link")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", cross_device_replace)++ with pytest.raises(+ PrebuiltFallback,+ match = "could not be moved aside; previous install left in place",+ ):+ activate_install_tree(staging_dir, install_dir, linux_host())++ assert (install_dir / "old.txt").read_text() == "old install\n"+ assert not staging_dir.exists()+ assert not (tmp_path / ".staging").exists()++ captured = capsys.readouterr()+ output = captured.out + captured.err+ assert "existing install could not be moved aside; leaving it in place" in output+++def test_activate_install_tree_keeps_existing_install_when_aside_move_hits_busy_lock(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def busy_replace(src, dst):+ if Path(src) == install_dir:+ raise OSError(errno.EBUSY, "Device or resource busy")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", busy_replace)++ with pytest.raises(+ BusyInstallConflict,+ match = "appears to still be in use; previous install left in place",+ ):+ activate_install_tree(staging_dir, install_dir, linux_host())++ assert (install_dir / "old.txt").read_text() == "old install\n"+ assert not staging_dir.exists()+ assert not (tmp_path / ".staging").exists()+++def test_activate_install_tree_restores_previous_install_when_failed_move_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def flaky_replace(src, dst):+ if "failed-" in Path(dst).name:+ raise OSError(errno.EACCES, "Access is denied")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)++ with pytest.raises(+ PrebuiltFallback,+ match = "activation failed; restored previous install",+ ):+ activate_install_tree(staging_dir, install_dir, linux_host())++ assert (install_dir / "old.txt").read_text() == "old install\n"+ assert not (install_dir / "new.txt").exists()+ assert not staging_dir.exists()+ assert not (tmp_path / ".staging").exists()++ captured = capsys.readouterr()+ output = captured.out + captured.err+ assert "failed active install could not be moved aside" in output+ assert "removing failed active install path" in output+ assert "restored previous install from rollback path" in output+++def test_activate_install_tree_keeps_rollback_when_failed_install_cannot_be_removed(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ (install_dir / "old.txt").write_text("old install\n")++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )++ original_replace = INSTALL_LLAMA_PREBUILT.os.replace++ def flaky_replace(src, dst):+ if "failed-" in Path(dst).name:+ raise OSError(errno.EACCES, "Access is denied")+ return original_replace(src, dst)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)++ original_rmtree = INSTALL_LLAMA_PREBUILT.shutil.rmtree++ def flaky_rmtree(path, *args, **kwargs):+ if Path(path) == install_dir:+ raise OSError(errno.EACCES, "Access is denied")+ return original_rmtree(path, *args, **kwargs)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.shutil, "rmtree", flaky_rmtree)++ with pytest.raises(PrebuiltFallback, match = "previous install kept at"):+ activate_install_tree(staging_dir, install_dir, linux_host())++ rollbacks = sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*"))+ assert len(rollbacks) == 1+ assert (rollbacks[0] / "old.txt").read_text() == "old install\n"++ captured = capsys.readouterr()+ output = captured.out + captured.err+ assert "recovering from the failed activation also failed" in output+ assert "rollback after failed activation also failed" not in output+ assert "previous install kept at rollback path" in output+ assert "removing rollback path" not in output+++def test_activate_install_tree_cleans_install_when_no_previous_install_exists(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+):+ install_dir = tmp_path / "llama.cpp"++ staging_dir = create_install_staging_dir(install_dir)+ (staging_dir / "new.txt").write_text("new install\n")++ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "confirm_install_tree",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),+ )with pytest.raises(PrebuiltFallback,match = "activation and rollback failed; cleaned install state for fresh source build",):- activate_install_tree(staging_dir, install_dir, host)+ activate_install_tree(staging_dir, install_dir, linux_host())assert not install_dir.exists()assert not staging_dir.exists()@@ -831,10 +1707,8 @@ def test_activate_install_tree_cleans_all_paths_when_rollback_restore_fails(captured = capsys.readouterr()output = captured.out + captured.err- assert "rollback after failed activation also failed: restore failed" in output- assert "cleaning staging, install, and rollback paths before source build fallback" in output- assert "removing failed install path" in output- assert "removing rollback path" in output+ assert "leaving it in place" not in output+ assert "previous install kept at" not in outputdef test_activate_staged_dir_copies_when_replace_hits_busy_lock(