Skip to content

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.

Studio: install sd.cpp under the Studio home, not beside it (#8226)

Daniel Han8080c93c9e2b
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index 405f32aab42..a6c87b006b2 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -389,6 +389,57 @@ Environment:
} catch { }
}
+ # The Studio-managed subtrees underneath the reparse-point TARGET of each Studio home, for the
+ # stop scan only.
+ #
+ # A junction or directory symlink Studio home runs its native binaries out of the PHYSICAL
+ # path: the backend resolves the home (Path.resolve) before deriving <home>\stable-diffusion.cpp
+ # and launching sd-server there, while _CustomStudioRoots only normalizes the string --
+ # System.IO.Path.GetFullPath is lexical and never touches the filesystem, so it leaves a
+ # reparse point untouched. The prefix scan below reads Win32_Process.ExecutablePath, the real
+ # image path, so without the target the running server never matches and survives an uninstall
+ # that took its tree.
+ #
+ # The SUBTREES, never the bare target. The delete unlinks only the reparse point and leaves the
+ # target standing, so anything there that is not ours is neither locking nor being removed --
+ # a home relocated onto a directory that holds other software must not have those force-stopped.
+ # Homes only, for the same reason: the component dirs ($defaultNode, $defaultLlamaCpp, ...) can
+ # themselves be links onto a shared runtime, and resolving those would put every process out of
+ # it in scope.
+ #
+ # Stop scan only, deliberately. _RemoveRootRecordingDb and the deletes still refuse to chase a
+ # link out of the expected location -- following one to delete its target is exactly what the
+ # deny list exists to prevent. Ending our own process under the target is not destructive.
+ function _ManagedPathsUnderReparseTargets {
+ param([string[]]$Roots)
+ # Everything setup.ps1 / the prebuilt installers place inside a Studio home.
+ $managed = @(
+ "unsloth_studio", "share", "bin", "llama.cpp", "whisper.cpp", "node",
+ "stable-diffusion.cpp", ".cache", ".venv_t5_510", ".venv_t5_530", ".venv_t5_550"
+ )
+ $out = @()
+ foreach ($r in @($Roots | Where-Object { $_ })) {
+ try {
+ $item = Get-Item -LiteralPath $r -Force -ErrorAction SilentlyContinue
+ if (-not $item -or -not $item.Target) { continue }
+ $t = @($item.Target)[0]
+ if ([string]::IsNullOrWhiteSpace($t)) { continue }
+ # A symlink target may be relative; a junction's never is. Anchor it on the link's
+ # own parent, or GetFullPath would read it from the uninstaller's working directory.
+ if (-not [System.IO.Path]::IsPathRooted($t)) {
+ $t = Join-Path (Split-Path -LiteralPath $item.FullName -Parent) $t
+ }
+ $t = [System.IO.Path]::GetFullPath($t).TrimEnd('\', '/')
+ if (-not $t) { continue }
+ foreach ($sub in $managed) {
+ $p = (Join-Path $t $sub).TrimEnd('\', '/')
+ if ($out -notcontains $p) { $out += $p }
+ }
+ } catch { }
+ }
+ return $out
+ }
+
# Stop processes that would block deleting the paths we remove. Unlike
# _StopStudioProcesses (venv exe only), this also catches llama-server/llama-cli,
# the unsloth.exe shim, and orphaned mp workers under SYSTEM python holding a
@@ -535,9 +586,10 @@ Environment:
if ($defaultSdCpp -and (Test-Path -LiteralPath $defaultSdCpp) -and (Test-Path -LiteralPath (Join-Path $defaultSdCpp ".unsloth-studio-owned") -PathType Leaf)) {
$defaultSdCppToStop = $defaultSdCpp
}
- # Custom/env-mode sd.cpp builds sit BESIDE each custom root at <parent>\stable-diffusion.cpp,
- # outside $knownRoots. We delete those marker-owned dirs below, so add them to the handle scan
- # too, gated on the same owner marker.
+ # A custom/env-mode sd.cpp build now sits UNDER its root at <root>\stable-diffusion.cpp, which
+ # the $knownRoots prefix match below already covers. Older builds put it BESIDE the root at
+ # <parent>\stable-diffusion.cpp, outside $knownRoots. We delete those marker-owned dirs below,
+ # so add them to the handle scan too, gated on the same owner marker.
$customSdCppToStop = @()
foreach ($r in $customRoots) {
$sdc = Join-Path (Split-Path -LiteralPath $r -Parent) "stable-diffusion.cpp"
@@ -547,7 +599,8 @@ Environment:
}
# Also stop anything holding a handle on the exact paths we delete (llama-server,
# the CLI shim, an mp-fork python with a venv DLL) so the dir delete isn't refused.
- _StopProcessesLockingRoots -Roots (@($knownRoots) + @($defaultDataDir, $defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop))
+ $stopRoots = @($knownRoots) + @($defaultDataDir, $defaultLlamaCpp, $defaultCache, $defaultNode, $defaultWhisperCpp) + @($defaultSdCppToStop | Where-Object { $_ }) + @($customSdCppToStop)
+ _StopProcessesLockingRoots -Roots ($stopRoots + @(_ManagedPathsUnderReparseTargets $knownRoots))
# ── Remove custom-root install trees ──
_Step "Removing data and install directories..."
@@ -564,13 +617,14 @@ Environment:
continue
}
_RemoveRootRecordingDb $r
- # Native diffusion (stable-diffusion.cpp) for a custom/env-mode Studio installs beside
- # the root at <parent>\stable-diffusion.cpp -- find_sd_cpp_binary resolves it from
- # UNSLOTH_STUDIO_HOME.parent (sd_cpp_engine.py) -- so removing only the root leaves the
- # build behind. Only remove a sibling Studio installed: <parent> is a user-chosen dir
- # and "stable-diffusion.cpp" is exactly what a git clone of leejet/stable-diffusion.cpp
- # produces, so require our owner marker (written by install_sd_cpp_prebuilt) before rm,
- # and keep any unowned checkout. Guard the derived parent path the same way.
+ # Native diffusion (stable-diffusion.cpp) now installs UNDER the custom root, at
+ # <root>\stable-diffusion.cpp, so the removal above already took it. Older builds put it
+ # BESIDE the root at <parent>\stable-diffusion.cpp (find_sd_cpp_binary derived it from
+ # UNSLOTH_STUDIO_HOME.parent), and removing only the root would leave that build behind.
+ # Only remove a sibling Studio installed: <parent> is a user-chosen dir and
+ # "stable-diffusion.cpp" is exactly what a git clone of the upstream project produces, so
+ # require our owner marker (written by install_sd_cpp_prebuilt) before rm, and keep any
+ # unowned checkout. Guard the derived parent path the same way.
$customSdCpp = Join-Path (Split-Path -LiteralPath $r -Parent) "stable-diffusion.cpp"
if (_IsUnsafeRoot $customSdCpp) {
_Substep "refusing to remove unsafe path: $customSdCpp" "Yellow"
diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh
index 35d1bbb1678..a6764c6252d 100755
--- a/scripts/uninstall.sh
+++ b/scripts/uninstall.sh
@@ -75,19 +75,45 @@ _pkill_escape() {
printf '%s' "$1" | sed -e 's:[][\\.^$*+?{|}()/]:\\&:g'
}
-# Owned sd.cpp roots (default $HOME/.unsloth/stable-diffusion.cpp + each custom root's
-# <parent>/stable-diffusion.cpp sibling), each gated on the install-time owner marker so we never
-# stop a user-managed sd-server from an unrelated checkout at one of these paths.
+# sd.cpp roots whose sd-server has to be stopped: the default
+# $HOME/.unsloth/stable-diffusion.cpp, plus for each custom root both
+# <root>/stable-diffusion.cpp, where the install now lives, and the legacy
+# <parent>/stable-diffusion.cpp sibling an older build wrote. The nested one matters most: a
+# resident sd-server survives unlinking its binary, and the custom root is removed wholesale
+# below, so without it the tree goes and the server keeps running.
+# The owner marker gates the paths that SURVIVE when unowned (the default and the sibling), so an
+# unrelated checkout there keeps its server. It does not gate the nested path of a root this run
+# deletes: the current-root finder can select an unmarked binary there, and deleting the tree out
+# from under a live server is exactly what leaves it holding its port.
_owned_sd_cpp_roots() {
_default_sd="$HOME/.unsloth/stable-diffusion.cpp"
[ -f "$_default_sd/.unsloth-studio-owned" ] && printf '%s\n' "$_default_sd"
_custom_studio_roots 2>/dev/null | while IFS= read -r _root; do
+ [ -n "$_root" ] || continue
+ _sd_root="$_root/stable-diffusion.cpp"
+ if [ -f "$_sd_root/.unsloth-studio-owned" ] || _is_studio_root "$_root"; then
+ [ -d "$_sd_root" ] && printf '%s\n' "$_sd_root"
+ fi
+ done
+ _sd_cpp_sibling_bases 2>/dev/null | while IFS= read -r _root; do
[ -n "$_root" ] || continue
_sd_root="$(dirname "$_root")/stable-diffusion.cpp"
[ -f "$_sd_root/.unsloth-studio-owned" ] && printf '%s\n' "$_sd_root"
done
}
+# Every root an older build could have hung its sd.cpp sibling off: the canonicalized custom roots
+# and the lexical ones. They differ only when the Studio home is itself a symlink, and there the
+# lexical form is the one the old `dirname "$UNSLOTH_STUDIO_HOME"` produced, so canonicalizing
+# first looked beside the link's target and missed the tree entirely. Every use is gated on the
+# owner marker, which is what keeps an unrelated checkout at either path safe.
+_sd_cpp_sibling_bases() {
+ {
+ _custom_studio_roots 2>/dev/null
+ _custom_studio_roots lexical 2>/dev/null
+ } | awk '!seen[$0]++'
+}
+
# pkill resident sd-server / sd-cli under an owned sd.cpp root before that tree is removed (a live
# native server keeps running after its binary is unlinked). Anchored on the owned root.
_stop_owned_sd_cpp_processes() {
@@ -365,6 +391,9 @@ _custom_studio_data_dirs() {
# the install root is three dirnames up. Prints each discovered non-default
# root on its own line; the caller iterates and de-duplicates.
_custom_studio_roots() {
+ # $1 = "lexical": skip the canonicalization (see the legacy sd.cpp sibling below). Reset on
+ # every call, so a plain call is never affected by a preceding lexical one.
+ _studio_roots_lexical="${1:-}"
_seen=""
_emit() {
_r="$1"
@@ -379,9 +408,13 @@ _custom_studio_roots() {
esac
# Canonicalize so syntactic variants ($HOME/../$USER, trailing slash)
# resolve to the same path and hit the _is_unsafe_root deny list.
- # shellcheck disable=SC1007
- _canon=$(CDPATH= cd -P -- "$_r" 2>/dev/null && pwd -P)
- [ -n "$_canon" ] && _r="$_canon"
+ # Skipped for the lexical pass, which exists only to rebuild the path an
+ # older build derived with a plain dirname (see _sd_cpp_sibling_bases).
+ if [ "${_studio_roots_lexical:-}" != "lexical" ]; then
+ # shellcheck disable=SC1007
+ _canon=$(CDPATH= cd -P -- "$_r" 2>/dev/null && pwd -P)
+ [ -n "$_canon" ] && _r="$_canon"
+ fi
case "$_r" in "$HOME/.unsloth/studio"|/|"") return 0 ;; esac
case ":$_seen:" in *":$_r:"*) return 0 ;; esac
_seen="$_seen:$_r"
@@ -509,14 +542,15 @@ _unsloth_uninstall_main() {
continue
fi
_remove_root_recording_db "$_custom_root"
- # Native diffusion (stable-diffusion.cpp) for a custom/env-mode Studio installs beside
- # the root at <parent>/stable-diffusion.cpp -- find_sd_cpp_binary resolves it from
- # UNSLOTH_STUDIO_HOME.parent (sd_cpp_engine.py) -- so removing only the root leaves the
- # build behind. Only remove a sibling Studio installed: <parent> is a user-chosen dir
- # and "stable-diffusion.cpp" is exactly what `git clone` of leejet/stable-diffusion.cpp
- # produces, so require our owner marker (written by install_sd_cpp_prebuilt) before rm,
- # and keep any unowned checkout. A pre-marker Studio build is left behind, never a user
- # file deleted. Guard the derived parent path the same way.
+ # Native diffusion (stable-diffusion.cpp) now installs UNDER the custom root, at
+ # <root>/stable-diffusion.cpp, so the removal above already took it. Older builds put it
+ # BESIDE the root at <parent>/stable-diffusion.cpp (find_sd_cpp_binary derived it from
+ # UNSLOTH_STUDIO_HOME.parent), and removing only the root would leave that build behind.
+ # Only remove a sibling Studio installed: <parent> is a user-chosen dir and
+ # "stable-diffusion.cpp" is exactly what `git clone` of the upstream project produces, so
+ # require our owner marker (written by install_sd_cpp_prebuilt) before rm, and keep any
+ # unowned checkout. A pre-marker Studio build is left behind, never a user file deleted.
+ # Guard the derived parent path the same way.
_custom_sd_cpp="$(dirname "$_custom_root")/stable-diffusion.cpp"
if _is_unsafe_root "$_custom_sd_cpp"; then
echo " refusing to remove unsafe path: $_custom_sd_cpp" >&2
@@ -526,6 +560,31 @@ _unsloth_uninstall_main() {
_remove_path "$_custom_sd_cpp"
fi
done
+ # The lexical parent as well. A home that is itself a symlink has its old sd.cpp tree beside
+ # the LINK, and the loop above only saw the canonicalized root, so that tree survived. Marker
+ # only, with no "keeping" notice: an unmarked directory at this path is somebody's checkout
+ # and the canonical pass has already reported the one it looked at.
+ _custom_studio_roots lexical 2>/dev/null | while IFS= read -r _lex_root; do
+ [ -n "$_lex_root" ] || continue
+ # The same ownership check the canonical loop makes before it touches anything. A stale or
+ # mistyped UNSLOTH_STUDIO_HOME still reaches here (the lexical pass has no cd -P to filter
+ # a path that is not there), and without this "/parent/typo" would take the marked
+ # /parent/stable-diffusion.cpp of somebody else's Studio with it.
+ _is_studio_root "$_lex_root" || continue
+ _lex_sd_cpp="$(dirname "$_lex_root")/stable-diffusion.cpp"
+ [ -f "$_lex_sd_cpp/.unsloth-studio-owned" ] || continue
+ # The deny list is string-based, so it has to see the RESOLVED path: the lexical form can
+ # carry ".." or a symlinked ancestor and slip a protected tree ("/tmp/../usr/...") past it.
+ # Canonicalize a copy for the check only; the removal still uses the lexical path.
+ # shellcheck disable=SC1007
+ _lex_sd_canon=$(CDPATH= cd -P -- "$_lex_sd_cpp" 2>/dev/null && pwd -P)
+ [ -n "$_lex_sd_canon" ] || _lex_sd_canon="$_lex_sd_cpp"
+ if _is_unsafe_root "$_lex_sd_cpp" || _is_unsafe_root "$_lex_sd_canon"; then
+ echo " refusing to remove unsafe path: $_lex_sd_cpp" >&2
+ else
+ _remove_path "$_lex_sd_cpp"
+ fi
+ done
_remove_root_recording_db "$HOME/.unsloth/studio"
# Default-mode shared llama.cpp build + cache are siblings of studio (not removed
# by deleting it). No-op in env/custom mode (they nest under the custom root) and
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index a5eb83df74d..84335a9394c 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -73,6 +73,7 @@ from core.inference.sd_cpp_engine import (
find_sd_server_binary,
is_managed_binary,
managed_install_root,
+ owning_managed_root,
runtime_env,
)
from core.inference.sd_cpp_server import SdCppServer
@@ -470,7 +471,8 @@ def _accelerator_changed(binary: str, accelerator: str) -> bool:
the CPU build is wanted: unrecorded is unknown (GPU assets shipped before the record did), and
reinstalling every legacy install on a CPU target would redownload the bundle for the common
case, where the install almost certainly is the CPU one already."""
- if not is_managed_binary(binary):
+ root = owning_managed_root(binary)
+ if root is None:
return False
if _managed_tree_in_use():
return False # an install now would overwrite a running binary; the load retries after teardown
@@ -479,14 +481,57 @@ def _accelerator_changed(binary: str, accelerator: str) -> bool:
want = mod.accelerator_class(accelerator)
if want in _failed_accelerator_upgrades:
return False
- have = mod.installed_accelerator(managed_install_root())
- if want == "cpu":
- return have is not None and have != "cpu"
- return have != want
+ # From the root the binary is actually in, not the current default: an install an older
+ # build put beside the Studio home keeps its own record, and reading the wrong root would
+ # report it unrecorded and re-download a bundle that is already here.
+ return _record_mismatch(mod, root, want)
except Exception: # noqa: BLE001 -- cannot tell -> keep the existing binary, as before
return False
+def _record_mismatch(mod, root: Path, want: str) -> bool:
+ """True when ``root``'s install record names an accelerator other than ``want``. Unrecorded is
+ unknown, and on a CPU target unknown is left alone (see ``_accelerator_changed``)."""
+ have = mod.installed_accelerator(root)
+ if want == "cpu":
+ return have is not None and have != "cpu"
+ return have != want
+
+
+def _superseded_legacy_server(binary: Optional[str], accelerator: str) -> bool:
+ """True when ``binary`` is a MISMATCHED sd-server out of the tree an older build left beside
+ the Studio home, while the CURRENT managed root holds a completed install for ``accelerator``
+ whose bundle shipped no sd-server.
+
+ That install is the authoritative one, and the recorded fact that its bundle is serverless
+ makes "no server" the answer rather than "install again": otherwise the finder keeps handing
+ the legacy server back, ``_accelerator_changed`` keeps rejecting it as the wrong build, and
+ every single load reinstalls the bundle that is already on disk.
+
+ Both halves are required. A legacy server that MATCHES the wanted accelerator is a working
+ server and is still preferred over the one-shot CLI. And an install whose record does not say
+ ``ships_server: false`` -- an older record without the field, or a bundle that did ship one
+ whose binary was later deleted or removed by the runnability repair -- is NOT evidence of a
+ serverless bundle, so it must keep reinstalling, which is what repairs the missing server."""
+ root = owning_managed_root(binary)
+ if root is None:
+ return False
+ current = managed_install_root()
+ try:
+ if root.resolve() == current.resolve():
+ return False
+ except OSError:
+ return False
+ try:
+ mod = _installer_module()
+ want = mod.accelerator_class(accelerator)
+ if not _record_mismatch(mod, root, want) or _record_mismatch(mod, current, want):
+ return False
+ return mod.installed_ships_server(current) is False
+ except Exception: # noqa: BLE001 -- cannot tell -> leave the existing behavior alone
+ return False
+
+
def _installed_accelerator_of(binary: Optional[str]) -> Optional[str]:
"""The accelerator class recorded for the managed install ``binary`` belongs to.
@@ -499,10 +544,15 @@ def _installed_accelerator_of(binary: Optional[str]) -> Optional[str]:
failed, and a load that keeps a usable wrong-accelerator build on purpose would be refused by
it on every single load. What the load needs is narrower -- did the tree it resolved this
binary out of get replaced underneath it."""
- if not is_managed_binary(binary):
+ # From the root the binary is actually IN, not the current default. The finder also serves a
+ # tree an older build left beside the Studio home, and reading the current root for a binary
+ # out of that one reports "unrecorded" on both sides of the comparison, so a swap underneath
+ # this load reads as no change at all.
+ root = owning_managed_root(binary)
+ if root is None:
return None
try:
- return _installer_module().installed_accelerator(managed_install_root())
+ return _installer_module().installed_accelerator(root)
except Exception: # noqa: BLE001 -- cannot tell; the comparison sees None on both sides
return None
@@ -576,6 +626,12 @@ def ensure_sd_server_binary(
"""
found = find_sd_server_binary()
usable = bool(found) and _usable_or_discard_managed(found)
+ # Ahead of _accelerator_changed, which reports "unchanged" while the managed tree is in use
+ # (an install would overwrite a running binary) and would hand the mismatched legacy server to
+ # a load that has the matching serverless build right here. None IS the answer: the one-shot
+ # sd-cli of the right build runs, and the bundle is not downloaded again on every later load.
+ if usable and _superseded_legacy_server(found, accelerator):
+ return None
if usable and not _accelerator_changed(found, accelerator):
return found
if not allow_install:
@@ -583,6 +639,8 @@ def ensure_sd_server_binary(
with _install_lock:
found = find_sd_server_binary()
usable = bool(found) and _usable_or_discard_managed(found)
+ if usable and _superseded_legacy_server(found, accelerator):
+ return None
if usable and not _accelerator_changed(found, accelerator):
return found
# Keep a usable wrong-accelerator server if the matching one cannot be fetched.
@@ -610,7 +668,16 @@ def ensure_sd_server_binary(
if fallback is not None or find_sd_cpp_binary() is not None:
_note_failed_upgrade(accelerator)
return fallback
- return find_sd_server_binary() or fallback
+ installed = find_sd_server_binary()
+ # The finder also probes the tree an older build left beside the Studio home, so when the
+ # bundle just installed ships no sd-server the hit here can be that legacy server, built
+ # for a different accelerator. None, not the fallback: an install just completed, so the
+ # router's next step resolves the sd-cli it landed, and a one-shot run on the right build
+ # beats a resident server on the wrong one. The fallback stays for the failure path above,
+ # where no matching binary was fetched at all.
+ if installed and _accelerator_changed(installed, accelerator):
+ return None
+ return installed or fallback
@dataclass(frozen = True)
diff --git a/studio/backend/core/inference/sd_cpp_engine.py b/studio/backend/core/inference/sd_cpp_engine.py
index 28167083925..faa19f6ed08 100644
--- a/studio/backend/core/inference/sd_cpp_engine.py
+++ b/studio/backend/core/inference/sd_cpp_engine.py
@@ -235,11 +235,79 @@ def managed_install_root() -> Path:
Only a copy under this root may be reinstalled over: replacing anything else would delete
a build the user chose. Honors UNSLOTH_STUDIO_HOME / STUDIO_HOME like the installer, so
- side-by-side Studios stay isolated."""
- studio_home = os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME")
- if studio_home:
- return Path(studio_home).parent / "stable-diffusion.cpp"
- return Path.home() / ".unsloth" / "stable-diffusion.cpp"
+ side-by-side Studios stay isolated.
+
+ ``<studio home>/stable-diffusion.cpp``, which is where every other managed component lives
+ (``default_managed_llama_dir``, ``managed_whisper_dir``, ``managed_node_dir`` all place their
+ tree *under* the Studio home). The legacy default home ``~/.unsloth/studio`` keeps mapping to
+ ``~/.unsloth/stable-diffusion.cpp`` so existing installs are still found."""
+ return _studio_component_root("stable-diffusion.cpp")
+
+
+def _studio_component_root(name: str) -> Path:
+ """``<studio home>/<name>``, or the legacy ``~/.unsloth/<name>`` when no custom home is set
+ (or the home *is* the legacy ``~/.unsloth/studio``). The home is expanded and made absolute
+ first: a relative ``UNSLOTH_STUDIO_HOME`` must not leave the root relative, because the
+ process' working directory can change and would silently move the managed tree."""
+ home = (os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or "").strip()
+ legacy = Path.home() / ".unsloth" / name
+ if not home:
+ return legacy
+ root = Path(home).expanduser()
+ legacy_studio = Path.home() / ".unsloth" / "studio"
+ try:
+ root = root.resolve()
+ is_legacy = root == legacy_studio.resolve()
+ except (OSError, ValueError):
+ root = root.absolute()
+ is_legacy = root == legacy_studio
+ return legacy if is_legacy else root / name
+
+
+def legacy_sibling_install_root() -> Optional[Path]:
+ """The pre-fix managed root, ``<studio home>/../stable-diffusion.cpp``, or None.
+
+ Older builds derived the sd.cpp root from the *parent* of the Studio home, which put the tree
+ outside the Studio home entirely. Two problems: a relative ``UNSLOTH_STUDIO_HOME`` collapsed
+ that parent to the working directory, so an unrelated ``stable-diffusion.cpp`` checkout sitting
+ there became "the managed install" and the installer refused to run; and it disagreed with
+ every other component, which install under the home.
+
+ Kept only so a tree an older build really did install still resolves. Returned solely when it
+ carries the ownership marker, so a checkout that merely happens to sit next to the Studio home
+ is never adopted.
+
+ The LEXICAL parent first, because that is the one the old code took: ``Path(home).parent`` does
+ not resolve symlinks, so for a home under a symlinked directory the tree an older build really
+ created sits next to the link, not next to its target. Resolving first looked in the wrong
+ place, re-downloaded the bundle and left the old install orphaned from uninstall as well. The
+ resolved parent is still tried after it, for a home reached through a link the other way
+ around."""
+ home = (os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or "").strip()
+ if not home:
+ return None
+ current = managed_install_root()
+ for base in _legacy_sibling_bases(home):
+ root = base / "stable-diffusion.cpp"
+ try:
+ if root != current and (root / OWNER_MARKER).is_file():
+ return root
+ except OSError:
+ continue
+ return None
+
+
+def _legacy_sibling_bases(home: str) -> list[Path]:
+ """The directories an older build could have taken as ``<studio home>/..``, lexical first."""
+ bases: list[Path] = []
+ for candidate in (lambda p: p.absolute(), lambda p: p.resolve()):
+ try:
+ base = candidate(Path(home).expanduser()).parent
+ except (OSError, ValueError):
+ continue
+ if base not in bases:
+ bases.append(base)
+ return bases
def in_tree_install_root() -> Optional[Path]:
@@ -265,14 +333,34 @@ def is_managed_binary(binary: Optional[str]) -> bool:
Deleting out of an unmarked root would take a file we are then refused permission to reinstall:
the repair unlinks sd-server, install() rejects the now still-non-empty unmarked directory, and
the user is left with no binary at all and no way back."""
+ return owning_managed_root(binary) is not None
+
+
+def owning_managed_root(binary: Optional[str]) -> Optional[Path]:
+ """The installer-owned root ``binary`` lives under, or None when it is not ours.
+
+ Both locations are checked, current first, because a tree an older build installed beside the
+ Studio home is still discovered by the finder. Callers that read per-install state (the
+ accelerator record) must read it from the root the binary is actually in: reading the current
+ root while the binary came from the legacy one reports "unrecorded", which a GPU target treats
+ as a mismatch and answers by re-downloading a bundle that is already installed."""
if not binary:
- return False
- root = managed_install_root()
- try:
- Path(binary).resolve().relative_to(root.resolve())
- return (root / OWNER_MARKER).is_file()
- except (OSError, ValueError):
- return False
+ return None
+ roots = [managed_install_root()]
+ legacy = legacy_sibling_install_root()
+ if legacy is not None:
+ roots.append(legacy)
+ for root in roots:
+ try:
+ Path(binary).resolve().relative_to(root.resolve())
+ except (OSError, ValueError):
+ continue
+ try:
+ if (root / OWNER_MARKER).is_file():
+ return root
+ except OSError:
+ continue
+ return None
def _find_binary(
@@ -296,12 +384,19 @@ def _find_binary(
if hit:
return hit
- # 3. Default install root. Honors UNSLOTH_STUDIO_HOME / STUDIO_HOME like the installer so side-by-side Studios stay isolated; else ~/.unsloth/....
+ # 3. Default install root: <studio home>/stable-diffusion.cpp (honors UNSLOTH_STUDIO_HOME / STUDIO_HOME like the installer so side-by-side Studios stay isolated), else ~/.unsloth/....
default_root = managed_install_root()
hit = _first_file(_layout_candidates(default_root, layout_stem))
if hit:
return hit
+ # 3b. A tree an older build installed beside the Studio home. Marker-gated (see legacy_sibling_install_root), so only a real previous install is picked up here.
+ legacy_root = legacy_sibling_install_root()
+ if legacy_root is not None:
+ hit = _first_file(_layout_candidates(legacy_root, layout_stem))
+ if hit:
+ return hit
+
# 4. In-tree developer build: <repo_root>/stable-diffusion.cpp.
in_tree = in_tree_install_root()
if in_tree is not None:
diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.py
index ff73d226dab..a0e20afc545 100644
--- a/studio/backend/tests/test_sd_cpp_install.py
+++ b/studio/backend/tests/test_sd_cpp_install.py
@@ -395,12 +395,95 @@ def test_find_sd_cpp_binary_honors_studio_home(tmp_path, monkeypatch):
monkeypatch.delenv("UNSLOTH_SD_CPP_PATH", raising = False)
studio_home = tmp_path / "studio_root"
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(studio_home))
- binary = tmp_path / "stable-diffusion.cpp" / "build" / "bin" / "sd-cli"
+ binary = studio_home / "stable-diffusion.cpp" / "build" / "bin" / "sd-cli"
binary.parent.mkdir(parents = True)
binary.write_bytes(b"x")
assert eng.find_sd_cpp_binary() == str(binary)
+def test_managed_root_is_under_the_studio_home_like_every_other_component(tmp_path, monkeypatch):
+ """The sd.cpp tree installs *under* the Studio home, not beside it.
+
+ llama.cpp (``default_managed_llama_dir``), whisper.cpp and node all place their tree at
+ ``<studio home>/<component>``. sd.cpp used the home's *parent*, which put the tree outside the
+ home the user chose."""
+ from core.inference import sd_cpp_engine as eng
+
+ studio_home = tmp_path / "sxs" / "studio_a"
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(studio_home))
+ monkeypatch.delenv("STUDIO_HOME", raising = False)
+ assert default_install_dir() == studio_home / "stable-diffusion.cpp"
+ # The installer and the engine must agree, or one installs where the other never looks.
+ assert eng.managed_install_root() == default_install_dir()
+
+
+def test_a_relative_studio_home_does_not_put_the_install_in_the_working_directory(
+ tmp_path, monkeypatch
+):
+ """A relative ``UNSLOTH_STUDIO_HOME`` used to collapse to the working directory.
+
+ ``Path("home").parent`` is ``Path(".")``, so the managed root became ``./stable-diffusion.cpp``
+ -- exactly the name ``git clone`` of the upstream project produces. A checkout sitting in the
+ working directory then shadowed the managed install and the installer refused to run, because
+ the target was a pre-existing non-empty directory without the ownership marker."""
+ from core.inference import sd_cpp_engine as eng
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "stable-diffusion.cpp").mkdir()
+ (tmp_path / "stable-diffusion.cpp" / "README.md").write_text("someone else's checkout")
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", "relative_home")
+ monkeypatch.delenv("STUDIO_HOME", raising = False)
+
+ for root in (default_install_dir(), eng.managed_install_root()):
+ assert root.is_absolute(), "a relative home must not leave the root relative"
+ assert root == (tmp_path / "relative_home" / "stable-diffusion.cpp").resolve()
+ assert root != (tmp_path / "stable-diffusion.cpp").resolve()
+
+
+def test_the_legacy_sibling_tree_is_adopted_only_when_it_carries_the_marker(tmp_path, monkeypatch):
+ """An install an older build really made is still found; a bare checkout is not.
+
+ Back-compat is marker-gated on purpose: the old location is ``<home>/../stable-diffusion.cpp``,
+ which for a relative home is the working directory, so an unmarked match there is far more
+ likely to be someone's clone than a previous Studio install."""
+ from core.inference import sd_cpp_engine as eng
+
+ monkeypatch.delenv("SD_CLI_PATH", raising = False)
+ monkeypatch.delenv("UNSLOTH_SD_CPP_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ sibling = tmp_path / "stable-diffusion.cpp"
+ binary = sibling / "build" / "bin" / "sd-cli"
+ binary.parent.mkdir(parents = True)
+ binary.write_bytes(b"x")
+
+ # Unmarked: not ours, so neither discovered nor treated as replaceable.
+ assert eng.legacy_sibling_install_root() is None
+ assert eng.find_sd_cpp_binary() is None
+ assert eng.is_managed_binary(str(binary)) is False
+
+ # Marked by a previous install: found again, and still replaceable.
+ (sibling / eng.OWNER_MARKER).touch()
+ assert eng.legacy_sibling_install_root() == sibling
+ assert eng.find_sd_cpp_binary() == str(binary)
+ assert eng.is_managed_binary(str(binary)) is True
+
+
+def test_the_legacy_default_studio_home_keeps_its_install_dir(tmp_path, monkeypatch):
+ """``UNSLOTH_STUDIO_HOME=~/.unsloth/studio`` is the documented default, not a custom home:
+ it must keep resolving to ``~/.unsloth/stable-diffusion.cpp`` rather than moving the tree to
+ ``~/.unsloth/studio/stable-diffusion.cpp`` and orphaning every existing install."""
+ from core.inference import sd_cpp_engine as eng
+
+ fake_home = tmp_path / "home"
+ (fake_home / ".unsloth" / "studio").mkdir(parents = True)
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(fake_home / ".unsloth" / "studio"))
+ monkeypatch.delenv("STUDIO_HOME", raising = False)
+ expected = fake_home / ".unsloth" / "stable-diffusion.cpp"
+ assert default_install_dir() == expected
+ assert eng.managed_install_root() == expected
+
+
# ── Unsloth mirror: default source + the CPU/Apple asset set it publishes ─────
# The shipped pin, not a copy of it: a hardcoded tag here silently stops describing what users
@@ -1020,6 +1103,38 @@ def test_a_cpu_install_is_reinstalled_when_cuda_is_requested(tmp_path, monkeypat
assert len(installs) == 1
+def test_a_legacy_sibling_install_is_read_from_its_own_root(tmp_path, monkeypatch):
+ """The accelerator record belongs to the tree the binary is in.
+
+ A tree an older build installed BESIDE the Studio home is still found by the finder, but the
+ current managed root is now under the home and holds nothing. Reading the record from there
+ reports the install as unrecorded, and unrecorded reads as a mismatch for a GPU target: the
+ matching CUDA bundle already on disk would be downloaded again on every load."""
+ import core.inference.sd_cpp_backend as bk
+
+ home = tmp_path / "sd-home" / "studio"
+ home.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ legacy = tmp_path / "sd-home" / "stable-diffusion.cpp" # where the old build put it
+ (legacy / "sd-bin").mkdir(parents = True)
+ (legacy / ".unsloth-studio-owned").touch()
+ sdmod._write_install_record(legacy, accelerator = "cuda", repo = "r", tag = "t")
+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear() # the record must be read off disk, not memoised
+
+ server = legacy / "sd-bin" / "sd-server"
+ server.write_bytes(b"cuda-build")
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(server))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ installs: list = []
+ monkeypatch.setattr(sdmod, "install", lambda **kw: installs.append(kw))
+
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert (
+ installs == []
+ ), "the CUDA build recorded in the legacy root is already what was asked for"
+
+
def test_asking_for_the_cpu_build_never_reinstalls(tmp_path, monkeypatch):
"""Only an upgrade reinstalls. A CPU/auto request must reuse whatever is there, including an
install predating the record, or every CPU host would re-download on its next load."""
@@ -1757,6 +1872,7 @@ def test_an_unwritable_record_does_not_cost_the_install_or_repeat_it(tmp_path, m
root.mkdir()
(root / sdmod.INSTALL_RECORD).mkdir() # a directory where the record file goes: open() fails
sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
sdmod._write_install_record(root, accelerator = "cuda", repo = "r", tag = "t")
assert sdmod.read_install_record(root) == {} # nothing on disk, as expected
@@ -1772,6 +1888,7 @@ def test_a_stale_unwritable_record_does_not_outrank_what_was_just_installed(tmp_
with open(root / sdmod.INSTALL_RECORD, "w", encoding = "utf-8") as f:
json.dump({"accelerator": "cpu", "repo": "r", "tag": "old"}, f)
sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
real_open = builtins.open
@@ -2352,3 +2469,217 @@ def test_a_superseded_load_unpublishes_the_server_it_stops(tmp_path, monkeypatch
assert backend._pending_server is None
assert backend._stopping_servers == 0
assert not bk._tree_in_use(backend)
+
+
+def test_the_legacy_lookup_uses_the_lexical_parent_of_a_symlinked_home(tmp_path, monkeypatch):
+ """The old code took Path(home).parent, which does not resolve symlinks. For a home that IS a
+ link, the tree an older build created sits next to the LINK, so resolving first looked in the
+ wrong place: a needless re-download, and the old install left orphaned from uninstall too."""
+ import core.inference.sd_cpp_engine as eng
+
+ target = tmp_path / "elsewhere" / "studio"
+ target.mkdir(parents = True)
+ home = tmp_path / "studio-home"
+ home.symlink_to(target, target_is_directory = True)
+ legacy = tmp_path / "stable-diffusion.cpp" # beside the LINK, where the old build put it
+ legacy.mkdir()
+ (legacy / ".unsloth-studio-owned").touch()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+
+ # Resolving first lands in <tmp>/elsewhere, which holds nothing.
+ assert not (tmp_path / "elsewhere" / "stable-diffusion.cpp").exists()
+ assert eng.legacy_sibling_install_root() == legacy
+
+
+def test_a_serverless_install_does_not_fall_back_to_the_legacy_server(tmp_path, monkeypatch):
+ """The finder also probes the tree beside the Studio home, so when the bundle just installed
+ ships no sd-server the hit can be the legacy one, built for another accelerator. Returning it
+ ran a forced CUDA load on the old CPU build instead of the one-shot CLI."""
+ import core.inference.sd_cpp_backend as bk
+
+ home = tmp_path / "sd-home" / "studio"
+ home.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ legacy = tmp_path / "sd-home" / "stable-diffusion.cpp"
+ (legacy / "sd-bin").mkdir(parents = True)
+ (legacy / ".unsloth-studio-owned").touch()
+ sdmod._write_install_record(legacy, accelerator = "cpu", repo = "r", tag = "t")
+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
+ old_server = legacy / "sd-bin" / "sd-server"
+ old_server.write_bytes(b"cpu-build")
+
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(old_server))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ # The install "succeeds" but ships only the CLI, so the finder still sees the legacy server.
+ monkeypatch.setattr(sdmod, "install", lambda **_kw: None)
+
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") is None
+
+
+def test_a_serverless_install_is_not_downloaded_again_on_every_later_load(tmp_path, monkeypatch):
+ """Rejecting the legacy server is only half the answer. The tree beside the Studio home keeps
+ that mismatched server, so the next load found it again, judged the accelerator changed and
+ reinstalled the bundle already sitting in the current root -- once per model load, forever.
+ The completed matching install in that root is the authoritative one: serverless, not stale."""
+ import core.inference.sd_cpp_backend as bk
+
+ home = tmp_path / "sd-home" / "studio"
+ home.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ legacy = tmp_path / "sd-home" / "stable-diffusion.cpp"
+ (legacy / "sd-bin").mkdir(parents = True)
+ (legacy / ".unsloth-studio-owned").touch()
+ sdmod._write_install_record(legacy, accelerator = "cpu", repo = "r", tag = "t")
+ old_server = legacy / "sd-bin" / "sd-server"
+ old_server.write_bytes(b"cpu-build")
+ # The current root already holds the cuda bundle, and that bundle shipped no sd-server.
+ current = home / "stable-diffusion.cpp"
+ current.mkdir()
+ (current / ".unsloth-studio-owned").touch()
+ sdmod._write_install_record(current, accelerator = "cuda", repo = "r", tag = "t", ships_server = False)
+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
+
+ installs: list[dict] = []
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(old_server))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ monkeypatch.setattr(sdmod, "install", lambda **kw: installs.append(kw))
+
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") is None
+ assert installs == [] # the bundle is already here; nothing to download
+ # ... and with installs switched off the answer is the same, not the wrong-build server.
+ assert bk.ensure_sd_server_binary(accelerator = "cuda", allow_install = False) is None
+ # ... and while the managed tree is busy, where _accelerator_changed reports "unchanged"
+ # because an install would overwrite a running binary.
+ monkeypatch.setattr(bk, "_managed_tree_in_use", lambda: True)
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") is None
+ assert installs == []
+
+
+def test_a_matching_legacy_server_is_still_preferred_over_the_one_shot_cli(tmp_path, monkeypatch):
+ """The serverless guard must fire only on a MISMATCHED legacy server. One built for the
+ accelerator being asked for is a working resident server, and dropping to the one-shot CLI
+ would re-run the model load on every single generation."""
+ import core.inference.sd_cpp_backend as bk
+
+ home = tmp_path / "sd-home" / "studio"
+ home.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ legacy = tmp_path / "sd-home" / "stable-diffusion.cpp"
+ (legacy / "sd-bin").mkdir(parents = True)
+ (legacy / ".unsloth-studio-owned").touch()
+ sdmod._write_install_record(legacy, accelerator = "cpu", repo = "r", tag = "t")
+ server = legacy / "sd-bin" / "sd-server"
+ server.write_bytes(b"cpu-build")
+ current = home / "stable-diffusion.cpp"
+ current.mkdir()
+ (current / ".unsloth-studio-owned").touch()
+ sdmod._write_install_record(current, accelerator = "cpu", repo = "r", tag = "t", ships_server = False)
+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
+
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(server))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+
+ assert bk.ensure_sd_server_binary(accelerator = "cpu") == str(server)
+
+
+def test_a_deleted_server_still_reinstalls_rather_than_reading_as_serverless(tmp_path, monkeypatch):
+ """A missing sd-server is not proof the bundle never had one: the runnability repair unlinks a
+ broken managed server precisely so the next load puts it back. Only a record that positively
+ says the bundle shipped none may suppress that reinstall, so an install predating the field
+ keeps repairing itself."""
+ import core.inference.sd_cpp_backend as bk
+
+ home = tmp_path / "sd-home" / "studio"
+ home.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ legacy = tmp_path / "sd-home" / "stable-diffusion.cpp"
+ (legacy / "sd-bin").mkdir(parents = True)
+ (legacy / ".unsloth-studio-owned").touch()
+ sdmod._write_install_record(legacy, accelerator = "cpu", repo = "r", tag = "t")
+ old_server = legacy / "sd-bin" / "sd-server"
+ old_server.write_bytes(b"cpu-build")
+ current = home / "stable-diffusion.cpp"
+ current.mkdir()
+ (current / ".unsloth-studio-owned").touch()
+ # A record from before ships_server existed: the bundle's server capability is unknown.
+ sdmod._write_install_record(current, accelerator = "cuda", repo = "r", tag = "t")
+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
+ assert sdmod.installed_ships_server(current) is None
+
+ installs: list[dict] = []
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(old_server))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ monkeypatch.setattr(sdmod, "install", lambda **kw: installs.append(kw))
+
+ bk.ensure_sd_server_binary(accelerator = "cuda")
+ assert [kw["accelerator"] for kw in installs] == ["cuda"]
+
+
+def test_install_records_that_the_bundle_shipped_no_server(tmp_path, monkeypatch):
+ """The capability comes off the archive member list during install(), so a later load reads it
+ as fact. Without it, "no sd-server in the tree" is indistinguishable from one that was deleted
+ and the reinstall that would repair it gets suppressed."""
+ zb = _zip_with_sd_cli() # sd-cli only
+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())
+ install(install_dir = tmp_path)
+ assert sdmod.installed_ships_server(tmp_path) is False
+
+
+def test_install_records_that_the_bundle_shipped_a_server(tmp_path, monkeypatch):
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("build/bin/sd-cli", b"#!/bin/sh\necho sd-cli\n")
+ zf.writestr("build/bin/sd-server", b"#!/bin/sh\necho sd-server\n")
+ zb = buf.getvalue()
+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())
+ install(install_dir = tmp_path)
+ assert sdmod.installed_ships_server(tmp_path) is True
+
+
+def test_an_unwritable_record_still_remembers_the_server_capability(tmp_path):
+ """Memoised alongside the accelerator or not at all. With only half of it remembered, an
+ unwritable record leaves a serverless install looking server-capable to the very guard the
+ accelerator memo exists to serve, and the load keeps re-downloading the bundle."""
+ root = tmp_path / "sd"
+ root.mkdir()
+ (root / sdmod.INSTALL_RECORD).mkdir() # a directory where the record file goes: open() fails
+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
+
+ sdmod._write_install_record(root, accelerator = "cuda", repo = "r", tag = "t", ships_server = False)
+ assert sdmod.read_install_record(root) == {} # nothing on disk, as expected
+ assert sdmod.installed_accelerator(root) == "cuda"
+ assert sdmod.installed_ships_server(root) is False # ... and not "unknown"
+
+
+def test_a_stale_record_does_not_outrank_the_server_capability_just_installed(tmp_path):
+ """The readable-but-unreplaceable shape: an older record saying the bundle shipped a server
+ must not survive an install of one that does not."""
+ root = tmp_path / "sd"
+ root.mkdir()
+ with open(root / sdmod.INSTALL_RECORD, "w", encoding = "utf-8") as f:
+ json.dump({"accelerator": "cpu", "repo": "r", "tag": "old", "ships_server": True}, f)
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO.clear()
+ sdmod._INSTALLED_SHIPS_SERVER_MEMO[str(root)] = False
+ assert sdmod.installed_ships_server(root) is False
+
+
+def test_the_install_record_remembers_whether_the_bundle_shipped_a_server(tmp_path):
+ """Read off the archive member list at install time, so no later load has to guess."""
+ root = tmp_path / "sd"
+ root.mkdir()
+ sdmod._write_install_record(root, accelerator = "cpu", repo = "r", tag = "t")
+ assert sdmod.installed_ships_server(root) is None # unrecorded stays unknown
+ sdmod._write_install_record(root, accelerator = "cpu", repo = "r", tag = "t", ships_server = True)
+ assert sdmod.installed_ships_server(root) is True
+ sdmod._write_install_record(root, accelerator = "cpu", repo = "r", tag = "t", ships_server = False)
+ assert sdmod.installed_ships_server(root) is False
+ assert sdmod.installed_accelerator(root) == "cpu"
diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.py
index c3bffc97122..765abecc1ee 100644
--- a/studio/install_sd_cpp_prebuilt.py
+++ b/studio/install_sd_cpp_prebuilt.py
@@ -132,17 +132,53 @@ def _raw_install_record(root: Path) -> Optional[str]:
except Exception: # noqa: BLE001 -- absent / unreadable / a directory: all "cannot tell"
return None
+# The same, for the bundle's sd-server capability. Memoised alongside the accelerator or not at
+# all: with only half of it remembered, an unwritable record leaves a serverless install looking
+# server-capable, and the load that finds a mismatched legacy server keeps reinstalling.
+_INSTALLED_SHIPS_SERVER_MEMO: dict[str, bool] = {}
-def _write_install_record(root: Path, *, accelerator: str, repo: str, tag: Optional[str]) -> None:
+
+def installed_ships_server(root: Path) -> Optional[bool]:
+ """Whether the bundle installed in ``root`` carried an sd-server, or None when unrecorded.
+
+ None is the honest answer for every install that predates this field, and callers must treat
+ it as "unknown" rather than "serverless": a missing sd-server is otherwise indistinguishable
+ from one a bundle never shipped, and suppressing the reinstall on a guess would strand a tree
+ whose server was deleted (by hand, or by the runnability repair) on the one-shot CLI forever.
+
+ The memo WINS over the file, for the same reason ``installed_accelerator``'s does: it is only
+ set by an install that completed in this process, and the case it exists for is a record that
+ could not be written, where the file is stale or absent."""
+ memo = _INSTALLED_SHIPS_SERVER_MEMO.get(str(root))
+ val = memo if memo is not None else read_install_record(root).get("ships_server")
+ return val if isinstance(val, bool) else None
+
+
+def _write_install_record(
+ root: Path,
+ *,
+ accelerator: str,
+ repo: str,
+ tag: Optional[str],
+ ships_server: Optional[bool] = None,
+) -> None:
"""Record what this install is, so a later ensure_* can tell a CPU bundle from a GPU one.
The write itself stays best-effort -- a metadata failure must not throw away binaries that
extracted correctly -- but the answer is memoised either way, so this process never re-installs
what it just installed."""
klass = accelerator_class(accelerator)
+ rec: dict = {"accelerator": klass, "repo": repo, "tag": tag}
+ if ships_server is not None:
+ rec["ships_server"] = ships_server
+ _INSTALLED_SHIPS_SERVER_MEMO[str(root)] = ships_server
+ else:
+ # An install that did not report the capability must not leave an older memo standing in
+ # for this one -- the tree is now whatever this bundle put there.
+ _INSTALLED_SHIPS_SERVER_MEMO.pop(str(root), None)
try:
with open(root / INSTALL_RECORD, "w", encoding = "utf-8") as f:
- json.dump({"accelerator": klass, "repo": repo, "tag": tag}, f)
+ json.dump(rec, f)
except OSError as exc:
# Remember it, pinned to the record we could not replace.
_INSTALLED_ACCELERATOR_MEMO[str(root)] = (klass, _raw_install_record(root))
@@ -336,12 +372,34 @@ def _verify_sha256(path: Path, expected_digest: Optional[str]) -> None:
def default_install_dir() -> Path:
- """``~/.unsloth/stable-diffusion.cpp`` (or under ``UNSLOTH_STUDIO_HOME`` /
- ``STUDIO_HOME`` if set), the sibling of the llama.cpp install the finder
- probes."""
- home = os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME")
- base = Path(home).parent if home else Path.home() / ".unsloth"
- return base / "stable-diffusion.cpp"
+ """``<UNSLOTH_STUDIO_HOME>/stable-diffusion.cpp``, else the legacy
+ ``~/.unsloth/stable-diffusion.cpp``.
+
+ The same placement ``install_llama_prebuilt.default_managed_llama_dir`` uses for
+ llama.cpp, and the whisper.cpp / node installs use for theirs: the tree goes
+ *under* the Studio home, so side-by-side Studios stay isolated and nothing outside
+ the home is ever claimed. The legacy default home ``~/.unsloth/studio`` still maps
+ to ``~/.unsloth/stable-diffusion.cpp`` so an existing install is reused.
+
+ Kept byte-identical in meaning to ``sd_cpp_engine.managed_install_root``; the two
+ are separate because this script must run standalone, before the backend package is
+ importable.
+
+ Derived from an absolute home: a relative ``UNSLOTH_STUDIO_HOME`` must not leave the
+ install dir relative to whatever the working directory happens to be."""
+ home = (os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or "").strip()
+ legacy = Path.home() / ".unsloth" / "stable-diffusion.cpp"
+ if not home:
+ return legacy
+ root = Path(home).expanduser()
+ legacy_studio = Path.home() / ".unsloth" / "studio"
+ try:
+ root = root.resolve()
+ is_legacy = root == legacy_studio.resolve()
+ except (OSError, ValueError):
+ root = root.absolute()
+ is_legacy = root == legacy_studio
+ return legacy if is_legacy else root / "stable-diffusion.cpp"
def _make_executable(path: Path) -> None:
@@ -748,6 +806,11 @@ def install(
accelerator = accelerator,
repo = used_repo,
tag = release.get("tag_name"),
+ # Read off the archive's MEMBER LIST, so "this bundle is serverless" is recorded fact
+ # rather than something a later load has to infer from an sd-server not being there.
+ # A leftover server from an earlier bundle is indistinguishable on disk, which is the
+ # whole confusion the record exists to settle.
+ ships_server = any(p.name == _binary_names()[1] for p in supplied),
)
# The ownership marker was written before extraction, so a crashed partial install is still recognised as ours.
return sd_cli
diff --git a/tests/sh/test_uninstall_sd_cpp_custom_root.sh b/tests/sh/test_uninstall_sd_cpp_custom_root.sh
index 1b6fb917993..69258e016cb 100755
--- a/tests/sh/test_uninstall_sd_cpp_custom_root.sh
+++ b/tests/sh/test_uninstall_sd_cpp_custom_root.sh
@@ -35,18 +35,30 @@ HELPERS_FILE=$(mktemp -p "$_TMP_ROOT")
# fragment dies with "command not found" and every assertion below is vacuous.
sed -n '/^_set_marker() {/,/^}/p' "$UNINSTALL_SH"
sed -n '/^_remove_root_recording_db() {/,/^}/p' "$UNINSTALL_SH"
+ # The owned-root lister that decides which sd-servers are pkilled before a tree is deleted.
+ sed -n '/^_owned_sd_cpp_roots() {/,/^}/p' "$UNINSTALL_SH"
+ # ... and the sibling-base lister it asks for the legacy <parent>/stable-diffusion.cpp paths.
+ sed -n '/^_sd_cpp_sibling_bases() {/,/^}/p' "$UNINSTALL_SH"
} > "$HELPERS_FILE"
+grep -q '_owned_sd_cpp_roots' "$HELPERS_FILE" || { echo "FAIL: helpers missing _owned_sd_cpp_roots"; exit 1; }
+grep -q '_sd_cpp_sibling_bases() {' "$HELPERS_FILE" || { echo "FAIL: helpers missing _sd_cpp_sibling_bases"; exit 1; }
# Both blocks sit inside the main removal function, so they are indented: anchor on optional
# leading whitespace, never on column 0, or the range matches nothing and every assertion below
# passes or fails vacuously against a fragment that was never extracted.
LOOP_FILE=$(mktemp -p "$_TMP_ROOT")
sed -n '/^[[:space:]]*_custom_studio_roots | while IFS= read -r _custom_root; do/,/^[[:space:]]*done/p' "$UNINSTALL_SH" > "$LOOP_FILE"
+# The follow-up block that clears the legacy sibling hanging off the LEXICAL parent.
+LEXICAL_FILE=$(mktemp -p "$_TMP_ROOT")
+sed -n '/^[[:space:]]*_custom_studio_roots lexical 2>\/dev\/null | while IFS= read -r _lex_root; do/,/^[[:space:]]*done/p' "$UNINSTALL_SH" > "$LEXICAL_FILE"
+# The real root resolver, for the symlinked-home cases at the end (the others stub it).
+REAL_ROOTS_FILE=$(mktemp -p "$_TMP_ROOT")
+sed -n '/^_custom_studio_roots() {/,/^}/p' "$UNINSTALL_SH" > "$REAL_ROOTS_FILE"
# The real default-mode ~/.unsloth/stable-diffusion.cpp removal block (marker-guarded).
DEFAULT_FILE=$(mktemp -p "$_TMP_ROOT")
sed -n '/^[[:space:]]*_default_sd_cpp="\$HOME\/\.unsloth\/stable-diffusion\.cpp"/,/^[[:space:]]*fi/p' "$UNINSTALL_SH" > "$DEFAULT_FILE"
# A silently empty extraction is what made this suite vacuous, so fail loudly instead.
-for _f in "$HELPERS_FILE" "$LOOP_FILE" "$DEFAULT_FILE"; do
+for _f in "$HELPERS_FILE" "$LOOP_FILE" "$DEFAULT_FILE" "$LEXICAL_FILE" "$REAL_ROOTS_FILE"; do
[ -s "$_f" ] || { echo "FAIL: extracted an empty fragment from $UNINSTALL_SH"; exit 1; }
done
grep -q '_remove_path' "$LOOP_FILE" || { echo "FAIL: loop fragment missing _remove_path"; exit 1; }
@@ -74,6 +86,10 @@ run_default_removal() {
# shellcheck disable=SC1090
. "$DEFAULT_FILE"
}
+run_lexical_removal() {
+ # shellcheck disable=SC1090
+ . "$LEXICAL_FILE"
+}
# 1. Single custom root -> root AND its sibling stable-diffusion.cpp both removed.
p1="$_TMP_ROOT/inst1"
@@ -134,6 +150,151 @@ mkdir -p "$HOME/.unsloth/stable-diffusion.cpp"
run_default_removal
assert_dir "default-mode unowned sd.cpp kept" "$HOME/.unsloth/stable-diffusion.cpp"
+
+# ── _owned_sd_cpp_roots: which sd-servers get stopped before their tree is deleted ────────────
+#
+# The install now lands at <root>/stable-diffusion.cpp, inside the custom root, and the custom
+# root is removed wholesale by the loop above. A resident sd-server survives unlinking its
+# binary, so if that nested path is not listed here the tree disappears while the server keeps
+# running and holding its port. The legacy <parent>/stable-diffusion.cpp sibling an older build
+# wrote still has to be listed too, since it is deleted separately.
+assert_lists() {
+ _l="$1"; _want="$2"
+ if _owned_sd_cpp_roots | grep -qxF "$_want"; then
+ echo " PASS: $_l"; PASS=$((PASS+1))
+ else
+ echo " FAIL: $_l (not listed: $_want)"; FAIL=$((FAIL+1))
+ fi
+}
+assert_not_lists() {
+ _l="$1"; _want="$2"
+ if _owned_sd_cpp_roots | grep -qxF "$_want"; then
+ echo " FAIL: $_l (listed anyway: $_want)"; FAIL=$((FAIL+1))
+ else
+ echo " PASS: $_l"; PASS=$((PASS+1))
+ fi
+}
+
+# 7. The nested install under the custom root is listed, so its sd-server is stopped first.
+p7="$_TMP_ROOT/inst7/studioE"
+mkdir -p "$p7/stable-diffusion.cpp/build/bin"
+: > "$p7/stable-diffusion.cpp/build/bin/sd-server"
+: > "$p7/stable-diffusion.cpp/.unsloth-studio-owned"
+_custom_studio_roots() { printf '%s\n' "$p7"; }
+assert_lists "nested <root>/stable-diffusion.cpp is stopped before removal" "$p7/stable-diffusion.cpp"
+
+# 8. A root this run does NOT delete (no Studio sentinels) keeps its unowned nested build running.
+p8="$_TMP_ROOT/inst8/studioF"
+mkdir -p "$p8/stable-diffusion.cpp/build/bin"
+: > "$p8/stable-diffusion.cpp/build/bin/sd-server" # no owner marker: the user's own build
+_custom_studio_roots() { printf '%s\n' "$p8"; }
+assert_not_lists "unowned nested build under a non-Studio root is left running" "$p8/stable-diffusion.cpp"
+
+# 8b. But under a real Studio root, which the loop deletes wholesale, the unmarked nested build is
+# stopped anyway: the current-root finder can select it without a marker, and deleting the tree
+# around a live server just leaves it holding its port.
+p8b="$_TMP_ROOT/inst8b/studioF2"
+mkdir -p "$p8b/share" "$p8b/stable-diffusion.cpp/build/bin"
+: > "$p8b/share/studio.conf"
+: > "$p8b/stable-diffusion.cpp/build/bin/sd-server" # no owner marker
+_custom_studio_roots() { printf '%s\n' "$p8b"; }
+assert_lists "unmarked nested build under a doomed Studio root is stopped" "$p8b/stable-diffusion.cpp"
+
+# 9. The legacy sibling an older build installed is still listed (it is still deleted).
+p9="$_TMP_ROOT/inst9"
+mkdir -p "$p9/studioG" "$p9/stable-diffusion.cpp"
+: > "$p9/stable-diffusion.cpp/.unsloth-studio-owned"
+_custom_studio_roots() { printf '%s\n' "$p9/studioG"; }
+assert_lists "legacy <parent>/stable-diffusion.cpp still stopped" "$p9/stable-diffusion.cpp"
+
+# 10. Both locations at once: neither shadows the other.
+p10="$_TMP_ROOT/inst10"
+mkdir -p "$p10/studioH/stable-diffusion.cpp" "$p10/stable-diffusion.cpp"
+: > "$p10/studioH/stable-diffusion.cpp/.unsloth-studio-owned"
+: > "$p10/stable-diffusion.cpp/.unsloth-studio-owned"
+_custom_studio_roots() { printf '%s\n' "$p10/studioH"; }
+assert_lists "both locations: nested listed" "$p10/studioH/stable-diffusion.cpp"
+assert_lists "both locations: sibling listed" "$p10/stable-diffusion.cpp"
+
+# 11. The nested tree goes away with the root it lives in.
+p11="$_TMP_ROOT/inst11"
+make_studio "$p11/studioI"
+mkdir -p "$p11/studioI/stable-diffusion.cpp/build/bin"
+: > "$p11/studioI/stable-diffusion.cpp/build/bin/sd-cli"
+: > "$p11/studioI/stable-diffusion.cpp/.unsloth-studio-owned"
+_custom_studio_roots() { printf '%s\n' "$p11/studioI"; }
+run_loop
+assert_nodir "nested stable-diffusion.cpp removed with its root" "$p11/studioI/stable-diffusion.cpp"
+assert_nodir "its custom root removed" "$p11/studioI"
+
+
+# ── A Studio home that is itself a symlink ────────────────────────────────────────────────────
+#
+# The old build derived the sd.cpp root with a plain `dirname "$UNSLOTH_STUDIO_HOME"`, so for
+# UNSLOTH_STUDIO_HOME=<link> the tree it installed sits beside the LINK. _custom_studio_roots
+# canonicalizes the home before this code takes its parent, which points every legacy consumer
+# beside the link's TARGET instead: the tree beside the link was never stopped and never deleted.
+# The real resolver from here on, since a stub cannot express the link at all.
+# shellcheck disable=SC1090
+. "$REAL_ROOTS_FILE"
+unset STUDIO_HOME
+
+# 12. The legacy sibling beside the link is listed, so its sd-server is stopped before removal.
+p12="$_TMP_ROOT/inst12"
+mkdir -p "$p12/real/studioJ/share" "$p12/stable-diffusion.cpp"
+: > "$p12/real/studioJ/share/studio.conf"
+ln -s "$p12/real/studioJ" "$p12/link"
+: > "$p12/stable-diffusion.cpp/sd-server"
+: > "$p12/stable-diffusion.cpp/.unsloth-studio-owned"
+UNSLOTH_STUDIO_HOME="$p12/link"
+export UNSLOTH_STUDIO_HOME
+assert_lists "symlinked home: sd.cpp beside the link is stopped" "$p12/stable-diffusion.cpp"
+
+# 13. ... and removed.
+run_lexical_removal
+assert_nodir "symlinked home: sd.cpp beside the link removed" "$p12/stable-diffusion.cpp"
+
+# 14. An unowned checkout beside the link is kept, exactly like the canonical pass keeps one.
+p14="$_TMP_ROOT/inst14"
+mkdir -p "$p14/real/studioK/share" "$p14/stable-diffusion.cpp"
+: > "$p14/real/studioK/share/studio.conf"
+ln -s "$p14/real/studioK" "$p14/link"
+: > "$p14/stable-diffusion.cpp/main.cpp" # the user's own checkout, no owner marker
+UNSLOTH_STUDIO_HOME="$p14/link"
+run_lexical_removal
+assert_dir "symlinked home: unowned sd.cpp beside the link kept" "$p14/stable-diffusion.cpp"
+assert_not_lists "symlinked home: unowned sd.cpp beside the link is left running" "$p14/stable-diffusion.cpp"
+
+# 14b. A stale or mistyped home is not a Studio root, and the lexical pass must apply the same
+# ownership check the canonical loop does: "<parent>/typo" must not take the marked
+# <parent>/stable-diffusion.cpp belonging to a different, valid install.
+p14b="$_TMP_ROOT/inst14b"
+mkdir -p "$p14b/other/share" "$p14b/stable-diffusion.cpp"
+: > "$p14b/other/share/studio.conf" # somebody else's Studio, sharing the parent
+: > "$p14b/stable-diffusion.cpp/sd-cli"
+: > "$p14b/stable-diffusion.cpp/.unsloth-studio-owned"
+UNSLOTH_STUDIO_HOME="$p14b/typo" # never existed
+run_lexical_removal
+assert_dir "a mistyped home does not take a neighbour's legacy sd.cpp" "$p14b/stable-diffusion.cpp"
+
+# 15. The deny list is a string match, so the lexical path has to be canonicalized before it is
+# applied: a home carrying ".." (or a symlinked ancestor) otherwise produces a sibling that
+# misses the pattern while resolving straight into a protected tree. $HOME's parent is on that
+# list, so point HOME inside the fixture to get a deterministic denied target.
+p15="$_TMP_ROOT/inst15"
+mkdir -p "$p15/sub" "$p15/studioL/share" "$p15/stable-diffusion.cpp"
+: > "$p15/studioL/share/studio.conf"
+: > "$p15/stable-diffusion.cpp/sd-cli"
+: > "$p15/stable-diffusion.cpp/.unsloth-studio-owned"
+_HOME_BEFORE="$HOME"
+HOME="$p15/stable-diffusion.cpp/home" # so dirname "$HOME" is the denied path
+mkdir -p "$HOME"
+UNSLOTH_STUDIO_HOME="$p15/sub/../studioL" # lexical parent "$p15/sub/.." -> misses the raw match
+run_lexical_removal
+assert_dir "lexical sibling resolving into a denied tree is refused" "$p15/stable-diffusion.cpp"
+HOME="$_HOME_BEFORE"
+unset UNSLOTH_STUDIO_HOME
+
echo ""
echo "Results: $PASS passed, $FAIL failed"
[ "$FAIL" = 0 ]
diff --git a/tests/studio/test_uninstall_reparse_stop_roots.ps1 b/tests/studio/test_uninstall_reparse_stop_roots.ps1
new file mode 100644
index 00000000000..7e47f8605af
--- /dev/null
+++ b/tests/studio/test_uninstall_reparse_stop_roots.ps1
@@ -0,0 +1,84 @@
+#!/usr/bin/env pwsh
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# A junction / directory-symlink Studio home must have its PHYSICAL path in the stop scan.
+#
+# The backend resolves UNSLOTH_STUDIO_HOME (Path.resolve) before deriving
+# <home>\stable-diffusion.cpp, so sd-server's real image path is under the reparse TARGET.
+# _CustomStudioRoots only runs System.IO.Path.GetFullPath, which is lexical and leaves the link
+# path as-is, and _StopProcessesLockingRoots matches Win32_Process.ExecutablePath by prefix -- so
+# without the target the server is never stopped, its tree is deleted around it and it keeps
+# holding its port. _ManagedPathsUnderReparseTargets supplies the target for the stop scan only.
+#
+# The uninstaller body kills processes and writes to the registry, so it cannot be executed here;
+# the helper is lifted out of the script by AST and exercised on its own.
+#
+# Run: pwsh -NoProfile -File tests/studio/test_uninstall_reparse_stop_roots.ps1
+
+$ErrorActionPreference = "Stop"
+$repoRoot = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path
+$ps1Path = [System.IO.Path]::Combine($repoRoot, "scripts", "uninstall.ps1")
+
+$failures = 0
+function Check($name, $cond) {
+ if ($cond) { Write-Host " PASS $name" }
+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }
+}
+
+$tokens = $null; $errors = $null
+$ast = [System.Management.Automation.Language.Parser]::ParseFile($ps1Path, [ref]$tokens, [ref]$errors)
+Check "uninstall.ps1 parses" ($null -eq $errors -or $errors.Count -eq 0)
+
+# Lift the helper out. A silently empty extraction is what makes a suite like this vacuous.
+$fn = $ast.FindAll({
+ param($n)
+ $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq "_ManagedPathsUnderReparseTargets"
+ }, $true) | Select-Object -First 1
+if (-not $fn) {
+ Write-Host " FAIL _ManagedPathsUnderReparseTargets not found in uninstall.ps1" -ForegroundColor Red
+ exit 1
+}
+. ([scriptblock]::Create($fn.Extent.Text))
+
+# The stop-scan call site has to actually pass the targets, or the helper is dead code.
+$ps1Text = Get-Content -LiteralPath $ps1Path -Raw
+Check "the stop scan is given the managed paths under the target" `
+ ($ps1Text -match '_StopProcessesLockingRoots -Roots \(\$stopRoots \+ @\(_ManagedPathsUnderReparseTargets \$knownRoots\)\)')
+
+$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-reparse-" + [System.Guid]::NewGuid().ToString("N"))
+New-Item -ItemType Directory -Path $tmp -Force | Out-Null
+try {
+ $target = Join-Path $tmp "physical"
+ New-Item -ItemType Directory -Path (Join-Path $target "stable-diffusion.cpp") -Force | Out-Null
+ $link = Join-Path $tmp "studio-home"
+ New-Item -ItemType SymbolicLink -Path $link -Target $target -ErrorAction Stop | Out-Null
+
+ $phys = [System.IO.Path]::GetFullPath($target).TrimEnd('\', '/')
+ $got = @(_ManagedPathsUnderReparseTargets @($link))
+ Check "a linked root yields the sd.cpp tree under its physical target" `
+ ($got -contains (Join-Path $phys "stable-diffusion.cpp"))
+ Check "... and the venv under it" ($got -contains (Join-Path $phys "unsloth_studio"))
+ # Never the bare target: the delete leaves it standing, so anything else there is not ours.
+ Check "the bare physical target is NOT in scope" (-not ($got -contains $phys))
+
+ # A plain directory contributes nothing, so the scan does not widen for ordinary installs.
+ $plain = Join-Path $tmp "plain"
+ New-Item -ItemType Directory -Path $plain -Force | Out-Null
+ Check "a plain root adds nothing" (@(_ManagedPathsUnderReparseTargets @($plain)).Count -eq 0)
+
+ # Neither does a path that is not there at all, or an empty entry.
+ Check "a missing root adds nothing" (@(_ManagedPathsUnderReparseTargets @((Join-Path $tmp "nope"), "", $null)).Count -eq 0)
+
+ # Deduplicated: two links onto one target must not stack.
+ $link2 = Join-Path $tmp "studio-home-2"
+ New-Item -ItemType SymbolicLink -Path $link2 -Target $target -ErrorAction Stop | Out-Null
+ $both = @(_ManagedPathsUnderReparseTargets @($link, $link2))
+ Check "two links onto one target do not duplicate its subtrees" ($both.Count -eq $got.Count)
+}
+finally {
+ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue
+}
+
+Write-Host ""
+if ($failures -gt 0) { Write-Host "$failures check(s) failed" -ForegroundColor Red; exit 1 }
+Write-Host "All checks passed" -ForegroundColor Green