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: set DYLD_LIBRARY_PATH for llama-server on macOS, and classify macOS startup failures (#8574)

Daniel Hance3f5c90ed05
diff --git a/.github/scripts/assert-llama-loads.sh b/.github/scripts/assert-llama-loads.sh
index 62ef80d364e..76dea3d6619 100755
--- a/.github/scripts/assert-llama-loads.sh
+++ b/.github/scripts/assert-llama-loads.sh
@@ -52,6 +52,58 @@ if ! "$SERVER" --version >/tmp/llama-server-version.txt 2>&1; then
fail "llama-server failed to launch on macOS $HOST_VER (dyld load / symbol error)"
fi
+# The launch above uses this shell's environment, not the one Studio builds for
+# its child. That one was Linux-shaped on macOS (LD_LIBRARY_PATH, which dyld
+# ignores) while the installer's own validation set DYLD_LIBRARY_PATH, so the
+# defect could not show up at install time (#8566). A unit test with a
+# monkeypatched sys.platform cannot prove the real thing; this can.
+# Resolve the interpreter from STUDIO_HOME first, not from PATH. The
+# clean-machine lane scrubs PATH down to system directories and puts the shim
+# under its own UNSLOTH_STUDIO_HOME, so `command -v unsloth` is empty there and
+# a PATH-only lookup would skip this assertion in the one lane whose whole
+# point is a clean install, while CI still reported success. The tauri delivery
+# nests its venv one level deeper (clean-machine-install-ci.yml checks
+# $HOME_DIR/studio/unsloth_studio), so both layouts are candidates.
+STUDIO_PY=""
+for candidate in \
+ "$UNSLOTH_HOME/unsloth_studio/bin/python" \
+ "$UNSLOTH_HOME/studio/unsloth_studio/bin/python" \
+ "$UNSLOTH_HOME/.venv/bin/python" \
+ "$HOME/.unsloth/unsloth_studio/bin/python"; do
+ [ -x "$candidate" ] && { STUDIO_PY="$candidate"; break; }
+done
+if [ -z "$STUDIO_PY" ]; then
+ for shim in "$UNSLOTH_HOME/bin/unsloth" "$(command -v unsloth || true)"; do
+ [ -n "$shim" ] && [ -x "$shim" ] || continue
+ candidate="$(head -1 "$shim" | sed 's/^#!//' | awk '{print $1}')"
+ [ -n "$candidate" ] && [ -x "$candidate" ] && { STUDIO_PY="$candidate"; break; }
+ done
+fi
+# Fail rather than skip: an install that produced a llama-server but no
+# reachable interpreter is itself a broken install, and a skip here is
+# indistinguishable from a pass.
+[ -n "$STUDIO_PY" ] || fail "no Unsloth interpreter found under $UNSLOTH_HOME or on PATH; cannot check the launch environment"
+if [ -n "$STUDIO_PY" ]; then
+ if ! PYTHONPATH=studio/backend "$STUDIO_PY" - "$SERVER" <<'PY'
+import os, sys
+from core.inference.llama_cpp import LlamaCppBackend, _llama_lib_dir
+
+binary = sys.argv[1]
+lib_dir = str(_llama_lib_dir(binary))
+env = LlamaCppBackend._llama_server_env_for_binary(binary)
+got = env.get("DYLD_LIBRARY_PATH", "")
+print(f"DYLD_LIBRARY_PATH: {got or '<unset>'}")
+if not got:
+ sys.exit("Studio would launch llama-server with no DYLD_LIBRARY_PATH; dyld ignores LD_LIBRARY_PATH")
+if got.split(os.pathsep)[0] != lib_dir:
+ sys.exit(f"expected {lib_dir} first on DYLD_LIBRARY_PATH, got {got}")
+print("child launch environment is correct for dyld")
+PY
+ then
+ fail "Studio's llama-server launch environment is wrong for macOS (see above)"
+ fi
+fi
+
echo "llama.cpp load validation passed on macOS $HOST_VER"
echo " server: $SERVER"
sed -n '1,4p' /tmp/llama-server-version.txt 2>/dev/null || true
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index d2c4c240753..1a478e0f3b7 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -42,6 +42,7 @@ from typing import (
NamedTuple,
NoReturn,
Optional,
+ Sequence,
Union,
)
@@ -3267,18 +3268,45 @@ def _apply_igpu_host_reserve_mib(free_mib: int, is_igpu: bool) -> int:
return max(0, free_mib - _IGPU_HOST_RESERVE_MIB)
-def _resolve_llama_binary(binary: str) -> Path:
- """Resolve a managed symlink or shell entrypoint to the real server."""
+def _resolve_llama_binary(binary: str, *, template_only: bool = False) -> Path:
+ """Resolve a managed symlink or shell entrypoint to the real server.
+
+ Follows a chain rather than one hop. A wrapper whose target is another
+ wrapper used to resolve to the intermediate script, which on macOS is the
+ same defect this is here to avoid (SIP drops DYLD_* through the shell) and
+ also gives _llama_lib_dir the wrong directory, so the loader path would
+ point at the wrapper's folder instead of the one holding the dylibs.
+ Bounded, and stops on a repeat, so a wrapper pair pointing at each other
+ cannot spin.
+
+ ``template_only`` stops at the first link that is not the installer's own
+ template. Two callers, two different questions. Finding the dylibs wants
+ the end of the chain whatever it is made of, because that is where they
+ sit. Choosing what to LAUNCH must not step over somebody's own script:
+ checking only the outer entrypoint meant an installer-shaped symlink whose
+ target was a hand-written wrapper had that wrapper's exports skipped, even
+ though running the symlink directly would have executed them.
+ """
resolved = Path(binary).resolve()
- try:
- with open(resolved, "rb") as _f:
- _head = _f.read(256)
- if _head.startswith(b"#!"):
- _m = re.search(r'exec "\$\(dirname "\$0"\)/([^"]+)"', _head.decode("utf-8", "ignore"))
- if _m:
- return (resolved.parent / _m.group(1)).resolve()
- except OSError:
- pass
+ seen = {resolved}
+ for _ in range(8):
+ try:
+ with open(resolved, "rb") as _f:
+ _head = _f.read(256)
+ except OSError:
+ break
+ if not _head.startswith(b"#!"):
+ break
+ _m = re.search(r'exec "\$\(dirname "\$0"\)/([^"]+)"', _head.decode("utf-8", "ignore"))
+ if not _m:
+ break
+ if template_only and not _is_installer_entrypoint(str(resolved)):
+ break
+ nxt = (resolved.parent / _m.group(1)).resolve()
+ if nxt in seen:
+ break
+ seen.add(nxt)
+ resolved = nxt
return resolved
@@ -3286,6 +3314,77 @@ def _llama_lib_dir(binary: str) -> Path:
return _resolve_llama_binary(binary).parent
+# install_llama_prebuilt.write_exec_wrapper emits exactly this and nothing else:
+# a shebang, one exec line, a trailing newline. Anything more is somebody's own
+# script, whose extra lines are the whole reason not to skip past it.
+_INSTALLER_WRAPPER_RE = re.compile(
+ r"\A#!/bin/sh\n" r'exec "\$\(dirname "\$0"\)/[^"\n]+" "\$@"\n?\Z'
+)
+
+
+def _is_installer_entrypoint(binary: str) -> bool:
+ """Is ``binary`` an entrypoint the installer itself wrote?
+
+ Symlinks and real executables qualify: neither carries setup that could be
+ lost by launching the target instead. A shell script only qualifies when it
+ matches the installer's template exactly, so a user's wrapper that exports
+ variables before its exec line is launched as written.
+
+ Kept separate from _resolve_llama_binary, which must keep resolving ANY
+ wrapper: _llama_lib_dir needs the directory holding the dylibs, and that is
+ the target's directory whoever wrote the wrapper.
+ """
+ try:
+ path = Path(binary)
+ if path.is_symlink():
+ return True
+ with open(path, "rb") as fh:
+ head = fh.read(4096)
+ except OSError:
+ return True
+ if not head.startswith(b"#!"):
+ return True
+ return bool(_INSTALLER_WRAPPER_RE.match(head.decode("utf-8", "ignore")))
+
+
+def _loader_path_var() -> str:
+ """The platform's shared-library search env var.
+
+ dyld ignores LD_LIBRARY_PATH entirely, so a macOS child launched with only
+ that variable set has no search path at all. Same mapping as the sibling
+ engines (sd_cpp_engine._lib_path_var, stt_ggml_sidecar) and as the
+ installer's own staged-binary validation.
+ """
+ if sys.platform == "darwin":
+ return "DYLD_LIBRARY_PATH"
+ if sys.platform == "win32":
+ return "PATH"
+ return "LD_LIBRARY_PATH"
+
+
+def _prepend_loader_dir(existing: str, lib_dir: str) -> str:
+ """``lib_dir`` first in a loader search path, with no repeats.
+
+ Deduplicates on the normalised spelling, so an inherited "/x/bin/" or
+ "/x/./bin" does not survive alongside the "/x/bin" being prepended and the
+ result is stable however many times it is fed back in. Purely textual:
+ realpath would touch the filesystem, and a dead network mount on an
+ inherited entry must not stall a model load. Entries keep the spelling they
+ arrived with, since that is what the loader is given.
+ """
+ out: list[str] = []
+ seen: set[str] = set()
+ for entry in (lib_dir, *existing.split(os.pathsep)):
+ if not entry:
+ continue
+ key = os.path.normcase(os.path.normpath(entry))
+ if key in seen:
+ continue
+ seen.add(key)
+ out.append(entry)
+ return os.pathsep.join(out)
+
+
_CPU_RUNTIME_OWNER_FILE = "UNSLOTH_OWNER_PID"
# GPU backends the staged CPU-only runtime must not carry over. Module level: compiled once.
@@ -3738,7 +3837,13 @@ class LlamaCppBackend:
"""Whether a different llama-server is installed than the live one was launched
from. False when either side is unreadable, so an install still in flight is not
read as a finished one; the next Apply asks again."""
- current = self._binary_revision(self._find_llama_server_binary())
+ # Same path space as the launch recorded: _binary_revision keys on the
+ # path string, and on macOS the launch resolves a managed entrypoint to
+ # its target, so comparing an unresolved discovery path against it would
+ # differ for the same unchanged file and reload the model on every Apply.
+ current = self._binary_revision(
+ self._exec_path_for_launch(self._find_llama_server_binary())
+ )
if not current or not self._launch_binary_revision:
return False
return current != self._launch_binary_revision
@@ -4717,7 +4822,11 @@ class LlamaCppBackend:
``--spec-draft-n-max`` post-rename, ``--draft-max`` on legacy.
``None`` means n_max cannot be set.
"""
- bin_path = binary or cls._find_llama_server_binary()
+ # Not only in load_model: startup, status and preflight probe directly,
+ # and a wrapper loses DYLD_* to SIP before reaching the real server. The
+ # inconclusive capabilities that follow clamp slots and disable
+ # DSpark/DFlash sizing on a server that supports both (#8566).
+ bin_path = cls._exec_path_for_launch(binary or cls._find_llama_server_binary())
if not bin_path or not Path(bin_path).is_file():
return {
"found": False,
@@ -5965,9 +6074,12 @@ class LlamaCppBackend:
# Let ggml apply GGML_VK_VISIBLE_DEVICES; Python sees compact ordinals.
if sys.platform != "win32":
# Let the loader resolve sibling ggml libs next to the binary.
- existing_ld = env.get("LD_LIBRARY_PATH", "")
- env["LD_LIBRARY_PATH"] = (
- f"{binary_dir}:{existing_ld}" if existing_ld else str(binary_dir)
+ # _loader_path_var keeps macOS off LD_LIBRARY_PATH, which dyld
+ # ignores (#8566).
+ _loader_var = _loader_path_var()
+ existing_ld = env.get(_loader_var, "")
+ env[_loader_var] = (
+ f"{binary_dir}{os.pathsep}{existing_ld}" if existing_ld else str(binary_dir)
)
probe_script = Path(__file__).with_name("_vulkan_probe.py")
try:
@@ -6336,6 +6448,14 @@ class LlamaCppBackend:
_rocblas_lib = os.path.join(_hip_path, "bin", "rocblas", "library")
if os.path.isdir(_rocblas_lib):
env.setdefault("ROCBLAS_TENSILE_LIBPATH", _rocblas_lib)
+ elif sys.platform == "darwin":
+ # dyld ignores LD_LIBRARY_PATH, so the Linux branch below left the
+ # child with no search path at all, while the installer's own
+ # validation sets DYLD_LIBRARY_PATH and so never saw it (#8566).
+ # A healthy prebuilt resolves via @loader_path and does not need
+ # this; one with wrong install names dies in dyld without it.
+ _dyld = _loader_path_var()
+ env[_dyld] = _prepend_loader_dir(env.get(_dyld, ""), binary_dir)
else:
# Linux: LD_LIBRARY_PATH for shared libs next to the binary plus
# CUDA runtime libs (libcudart, libcublas, etc.)
@@ -9687,7 +9807,8 @@ class LlamaCppBackend:
# Shared objects Unsloth ships itself, next to llama-server in build/bin
# (see runtime_payload_health_groups in install_llama_prebuilt.py, and
- # _llama_server_env_for_binary which puts that dir on LD_LIBRARY_PATH). No
+ # _llama_server_env_for_binary which puts that dir on the platform's
+ # loader search path -- DYLD_LIBRARY_PATH on macOS). No
# distro packages these, so a loader failure naming one means the managed
# runtime is incomplete or mismatched, not that something must be installed.
_BUNDLED_LIB_PREFIXES = ("libllama", "libggml", "libmtmd")
@@ -9709,6 +9830,33 @@ class LlamaCppBackend:
so telling the user to update Unsloth's runtime cannot repair it.
Unknown binary (callers that pass nothing) keeps the managed default.
"""
+ if not binary:
+ return True
+ try:
+ from utils.llama_cpp_update import (
+ _active_install_is_local_link,
+ _llama_install_root,
+ )
+
+ # A --with-llama-cpp-dir tree is the user's own checkout reached
+ # through a symlinked llama.cpp dir. The updater refuses to write
+ # through that link, so it cannot repair the binary either, and its
+ # entrypoint is theirs to keep.
+ if _active_install_is_local_link(binary):
+ return False
+ return _llama_install_root(binary) is not None
+ except Exception:
+ return True
+
+ @staticmethod
+ def _is_llama_install_tree(binary: Optional[str]) -> bool:
+ """Does ``binary`` sit in a llama.cpp tree Studio resolved for itself?
+
+ The pre-existing half of the question above, kept separate because the
+ two are not the same: a --with-llama-cpp-dir checkout IS the active
+ install (so anything that only needs to read or copy from it still
+ applies) while not being something the updater can replace.
+ """
if not binary:
return True
try:
@@ -9798,6 +9946,270 @@ class LlamaCppBackend:
"provides it, then load the model again."
)
+ @staticmethod
+ def _exec_path_for_launch(binary: Optional[str]) -> Optional[str]:
+ """The path to actually execute, resolving a managed macOS entrypoint.
+
+ SIP purges DYLD_* while starting the protected /bin/sh a shell
+ entrypoint runs under, so the loader path we build for the child would
+ not survive the wrapper's own exec (#8566). Only OUR entrypoint is
+ resolved: someone's own wrapper may export backend variables or do
+ other setup before its exec line, and skipping past it would silently
+ drop that.
+
+ The test is the wrapper's shape, not where it came from. Provenance is
+ not enough (_llama_install_root treats the directory named by
+ UNSLOTH_LLAMA_CPP_PATH as the active install with no marker file
+ needed, so somebody's own checkout reads as managed), and neither is an
+ explicit LLAMA_SERVER_PATH pin: pointing that at the installer's own
+ entrypoint is a supported configuration, and refusing to resolve it
+ just because it was named put the launch back through /bin/sh and
+ reproduced the very bug this fixes. An installer-template wrapper does
+ nothing but exec its target, so resolving past one is never a loss,
+ however it was reached.
+ """
+ if not binary or sys.platform != "darwin":
+ return binary
+ if not LlamaCppBackend._is_unsloth_managed_binary(binary):
+ return binary
+ if not _is_installer_entrypoint(binary):
+ return binary
+ # template_only: the outer entrypoint being ours says nothing about
+ # what it points at. Resolve only through links that are also ours.
+ return str(_resolve_llama_binary(binary, template_only = True))
+
+ @staticmethod
+ def _runtime_remedy(binary: Optional[str]) -> str:
+ """The repair advice for ``binary``, by provenance.
+
+ `unsloth studio update` cannot touch a pinned LLAMA_SERVER_PATH or a
+ llama-server found on PATH, so those owners get told to rebuild theirs.
+ """
+ return (
+ "run `unsloth studio update` to reinstall the llama.cpp runtime"
+ if LlamaCppBackend._is_unsloth_managed_binary(binary)
+ else "reinstall or rebuild that custom llama.cpp"
+ )
+
+ # A "tried:" list names every searched path, so the reason can run to
+ # kilobytes. The glibc branch is capped to one line; cap this one too.
+ _MACOS_REASON_CHARS = 300
+
+ # A dyld install name is a path, and macOS PATH_MAX is 1024. Double it and
+ # anything longer is not something the loader produced.
+ _DYLD_LIB_NAME_MAX_CHARS = 2048
+
+ @staticmethod
+ def _plain_dyld_lib_name(lib: str) -> str:
+ """Drop dyld's search directives from an install name.
+
+ ``@rpath/libllama.dylib`` is a lookup token, not a location, so passing
+ it through as a path makes _missing_library_message tell the user to
+ restore a file at a directory that does not exist. The soname is what
+ they can act on, and _is_bundled_llama_library already matches on it.
+ """
+ # Basename, not just the directive: "@loader_path/../Frameworks/x.dylib"
+ # still reads as an exact location to _is_library_path.
+ if lib.startswith(("@rpath/", "@loader_path/", "@executable_path/")):
+ lib = os.path.basename(lib)
+ # The name is quoted from untrusted output and lands in an HTTP error.
+ # A real install name is well under this; without the cap, a wrapper
+ # printing a 100000-character one turned a 200-character diagnosis into
+ # a 100000-character API response. PATH_MAX on macOS is 1024, so this
+ # only ever truncates something dyld could not have produced.
+ if len(lib) > LlamaCppBackend._DYLD_LIB_NAME_MAX_CHARS:
+ lib = lib[: LlamaCppBackend._DYLD_LIB_NAME_MAX_CHARS] + "..."
+ return lib
+
+ # Ten search paths at a long path each, with room to spare. Only ever cuts
+ # text a real dyld reason does not produce.
+ _DYLD_REASON_MAX_CHARS = 4000
+ # How far past "Library not loaded:" to look for its Reason at all. Four
+ # times the cap above, so a real reason preceded by a little noise is still
+ # found whole.
+ _DYLD_REASON_SCAN_CHARS = 16000
+ # Candidates read out of one "tried:" list. dyld searches a bounded set of
+ # paths; a list longer than this is not one it produced.
+ _DYLD_MAX_CANDIDATES = 128
+
+ # dyld announces itself at the start of a line: "dyld[1234]: ", the older
+ # "dyld: ", or a crash report's "Termination Reason: ... DYLD". Structural
+ # on purpose: "Referenced from:" and friends are words a wrapper or a GGUF
+ # metadata string can carry, and were accepted as framing before.
+ _DYLD_FRAMING_RE = re.compile(
+ r"(?im)^[ \t]*(?:dyld(?:\[\d+\])?:|termination reason:.*\bdyld\b)"
+ )
+
+ @staticmethod
+ def _dyld_reason_after(output: str, start: int) -> str:
+ """The ``Reason:`` belonging to a dyld error, flattened to one line.
+
+ Bounded to that line plus its indented continuations, and searched only
+ after the "Library not loaded:" it explains: an unrelated earlier
+ "Reason:" in llama.cpp's own output would otherwise be read as dyld's,
+ and an unbounded read would swallow everything printed afterwards.
+
+ Length-capped as well. dyld lists one candidate per search path, so a
+ real reason is a couple of KB at most, but the text is whatever the
+ child printed: a pathological one drives the candidate scan below into
+ quadratic backtracking (100KB of "'a' (" measured at 6.3s, against
+ 0.0s before this change), and that scan runs on the event loop.
+ """
+ # Windowed, not just capped afterwards: dyld prints the reason directly
+ # under the "Library not loaded:" line, so nothing useful lives further
+ # out, and matching against the whole remaining output would materialise
+ # a group as large as whatever the child printed (a 25MB reason was
+ # measured at ~366MB peak RSS through the flatten below).
+ window = output[start : start + LlamaCppBackend._DYLD_REASON_SCAN_CHARS]
+ match = re.compile(
+ r"reason:[ \t]*([^\r\n]*(?:\r?\n[ \t]+[^\r\n]*)*)",
+ re.IGNORECASE,
+ ).search(window)
+ if not match:
+ return ""
+ return " ".join(match.group(1)[: LlamaCppBackend._DYLD_REASON_MAX_CHARS].split())
+
+ @staticmethod
+ def _dyld_tried_verdict(reason: str, binary: Optional[str]) -> str:
+ """The verdict for the candidate that is ours, out of a "tried:" list.
+
+ dyld reports ``tried: '<path>' (<verdict>), '<path>' (<verdict>), ...``
+ over every search path, so the list routinely mixes "no such file" for
+ our own bundle with "incompatible architecture" for a leftover Intel
+ Homebrew copy. Prefer the candidate in the runtime's own lib dir, else
+ the first one; with no list at all the reason stands as its own verdict.
+ """
+ lib_dir = ""
+ if binary:
+ try:
+ lib_dir = str(_llama_lib_dir(binary))
+ except (OSError, ValueError):
+ lib_dir = ""
+ # finditer with a count, not findall: the reason is already capped, but
+ # a list built before the first useful match is work done for nothing.
+ first: Optional[str] = None
+ for index, match in enumerate(re.finditer(r"'([^']+)'\s*\(([^)]*)\)", reason)):
+ if index >= LlamaCppBackend._DYLD_MAX_CANDIDATES:
+ break
+ path, verdict = match.group(1), match.group(2)
+ if first is None:
+ first = verdict
+ if lib_dir and os.path.dirname(path) == lib_dir:
+ return verdict
+ return first if first is not None else reason
+
+ @staticmethod
+ def _classify_macos_loader_failure(output: str, binary: Optional[str]) -> Optional[str]:
+ """dyld / Mach-O startup failures, or None when the output has none.
+
+ Pure text matching on captured llama-server output, so this runs (and
+ is tested) on any host, not only Darwin. Kept ahead of the returncode
+ heuristics in the caller: a dyld diagnostic is a fact, while signal 9
+ is a guess that would otherwise blame memory (#8566).
+
+ Nothing here fires without dyld's own framing. llama.cpp echoes GGUF
+ metadata to stderr while loading, so "Library not loaded:" or "Symbol
+ not found" can be a model's own general.name; a bare match outranked
+ the status-127 and signal-15 branches and answered a diffusion-GGUF
+ load with library advice. Every branch is now gated on the same guard
+ rather than each carrying its own.
+ """
+ if not output:
+ return None
+ if not LlamaCppBackend._DYLD_FRAMING_RE.search(output):
+ return None
+ lowered = output.lower()
+
+ # Built for a newer macOS than the host. Same two markers as
+ # install_llama_prebuilt.looks_like_macos_incompatibility, so the
+ # installer and the runtime agree on the wording.
+ if ("built for macos" in lowered and "newer than running os" in lowered) or (
+ "symbol not found" in lowered and "mtlresidency" in lowered
+ ):
+ return (
+ "llama-server could not start: the installed llama.cpp runtime "
+ "was built for a newer version of macOS than this Mac is "
+ f"running. Update macOS, or {LlamaCppBackend._runtime_remedy(binary)} "
+ "to get a build that matches this OS."
+ )
+
+ # "Library not loaded: <path>", then the "Reason:" that belongs to it.
+ not_loaded = re.search(
+ r"library not loaded:[ \t]*([^\r\n]+)",
+ output,
+ re.IGNORECASE,
+ )
+ if not_loaded:
+ lib = LlamaCppBackend._plain_dyld_lib_name(not_loaded.group(1).strip())
+ reason = LlamaCppBackend._dyld_reason_after(output, not_loaded.end())
+ # dyld4 gives a per-path verdict for every path it searched, so
+ # judge ours. Scanning the flattened list would let a stale Intel
+ # /usr/local copy decide the diagnosis for a dylib simply absent.
+ verdict = LlamaCppBackend._dyld_tried_verdict(reason, binary)
+ verdict_l = verdict.lower()
+ # macOS refused the Mach-O itself. Unsigned or altered code is a
+ # hard SIGKILL on Apple Silicon, so never send the user hunting for
+ # a corrupt GGUF or for free memory.
+ if "code signature" in verdict_l or "not valid for use in process" in verdict_l:
+ return (
+ f"llama-server could not start: macOS rejected the code "
+ f"signature of {lib}. The file was modified or is "
+ f"incompletely signed, so {LlamaCppBackend._runtime_remedy(binary)}."
+ )
+ # dyld4 says "mach-o file, but is an incompatible architecture";
+ # the older wording is "mach-o, but wrong architecture".
+ if "incompatible architecture" in verdict_l or "wrong architecture" in verdict_l:
+ return (
+ f"llama-server could not start: {lib} was built for a "
+ "different CPU architecture than this Mac. Its install is "
+ f"for the wrong platform, so {LlamaCppBackend._runtime_remedy(binary)}."
+ )
+ # "no such file" (the modern per-path "tried:" list) and the older
+ # bare "image not found" both mean absent; anything else means dyld
+ # found it and refused it, where reinstalling a package is wrong.
+ if not verdict_l or "no such file" in verdict_l or "image not found" in verdict_l:
+ return LlamaCppBackend._missing_library_message(lib, binary)
+ return LlamaCppBackend._unloadable_library_message(
+ lib, verdict[: LlamaCppBackend._MACOS_REASON_CHARS], binary
+ )
+
+ # A symbol mismatch with no missing file. Where it was expected decides
+ # the remedy: a system framework means the build wants a newer macOS
+ # (reinstalling cannot make the OS export it); one of ours means our
+ # own files are from different builds.
+ # Only with dyld's own framing: "Symbol not found" is ordinary English
+ # any wrapper on any platform can print, and claiming it would also
+ # suppress the output tail the fallback carries.
+ if "symbol not found" in lowered and any(
+ marker in lowered for marker in ("dyld[", "dyld:", "referenced from:", "expected in:")
+ ):
+ expected = re.search(r"expected in:\s*(?:<[^>]*>\s*)?([^\r\n]+)", output, re.IGNORECASE)
+ # Newer dyld quotes the path. Unstripped, "'/System/..." fails the
+ # prefix test below and a too-new build is blamed on a mismatched
+ # install instead of on the OS.
+ expected_path = expected.group(1).strip().strip("'\"") if expected else ""
+ if expected_path.startswith(("/System/", "/usr/lib/")):
+ return (
+ "llama-server could not start: it needs a symbol this "
+ "version of macOS does not provide, so the installed "
+ "llama.cpp runtime was built for a newer macOS. Update "
+ f"macOS, or {LlamaCppBackend._runtime_remedy(binary)} to get "
+ "a build that matches this OS."
+ )
+ return (
+ "llama-server could not start: its llama.cpp libraries are from "
+ "a different build than the llama-server binary (a symbol it "
+ "needs is missing). The install is mismatched, so "
+ f"{LlamaCppBackend._runtime_remedy(binary)}."
+ )
+ return None
+
+ # The macOS shell's message for EBADARCH, printed with the offending path
+ # and typically exit 126. Never reaches dyld, so it carries no dyld framing
+ # and has to be matched on its own; the wording is macOS-specific enough
+ # (Linux says "cannot execute binary file") to be safe anywhere.
+ _BAD_CPU_TYPE_RE = re.compile(r"(?im)^.*:[ \t]*bad cpu type in executable[ \t]*$")
+
@staticmethod
def _classify_llama_start_failure(
output: str,
@@ -9805,6 +10217,44 @@ class LlamaCppBackend:
model_identifier: Optional[str],
returncode: Optional[int] = None,
binary: Optional[str] = None,
+ log_path: "Optional[Path | str]" = None,
+ secrets: Sequence[Optional[str]] = (),
+ ) -> str:
+ """Classify, then redact, whatever the classification quoted.
+
+ Redaction used to live only in the startup-diagnostics tail, so it
+ covered the fallback and nothing else. Every other branch also quotes
+ untrusted text -- a dyld message names the library it could not load,
+ and that name comes from the child -- so a credential appearing there
+ went out in the API error while the same credential in the tail was
+ starred out. One boundary for every branch, rather than one per
+ interpolation, which is the arrangement that let this through.
+
+ Scrubbing twice is harmless: a redacted value no longer matches, so
+ running the pass over an already-decorated message is a no-op.
+ """
+ return LlamaCppBackend._scrub_secret_values(
+ LlamaCppBackend._classify_start_failure_text(
+ output,
+ gguf_path,
+ model_identifier,
+ returncode,
+ binary,
+ log_path,
+ secrets,
+ ),
+ secrets,
+ )
+
+ @staticmethod
+ def _classify_start_failure_text(
+ output: str,
+ gguf_path: Optional[str],
+ model_identifier: Optional[str],
+ returncode: Optional[int] = None,
+ binary: Optional[str] = None,
+ log_path: "Optional[Path | str]" = None,
+ secrets: Sequence[Optional[str]] = (),
) -> str:
"""Explain *why* llama-server failed to start, from its output.
@@ -9813,6 +10263,16 @@ class LlamaCppBackend:
loaded as a chat model -- valid file, plenty of memory, but llama.cpp
has no such architecture, so the user is told to free memory that was
never the problem (#5842). Pick the most specific message we can.
+
+ ``output`` is the child's stdout and is never trusted, not even when it
+ looks like something this module wrote: the only guard on our own
+ framing is the one in _with_startup_diagnostics, which reads the
+ ``message`` we built ourselves. An earlier revision short-circuited here
+ when the *output* carried that framing, so a wrapper printing
+ "llama-server output:" as its first line had its stdout returned
+ verbatim: no redaction, no 2000-character cap, no log path (50067
+ characters with an environment dump's credentials intact, against 2136
+ scrubbed for the same bytes without the heading).
"""
lowered = (output or "").lower()
@@ -9861,6 +10321,22 @@ class LlamaCppBackend:
return LlamaCppBackend._missing_library_message(_lib, binary)
return LlamaCppBackend._unloadable_library_message(_lib, _reason, binary)
+ # macOS. dyld shares no wording with glibc, so every loader failure on
+ # Apple Silicon fell past the branch above into the generic GGUF/memory
+ # message, and none of them is about either (#8566).
+ macos_detail = LlamaCppBackend._classify_macos_loader_failure(output or "", binary)
+ if macos_detail:
+ return macos_detail
+
+ # The executable itself is for the wrong architecture, so the shell
+ # rejects it before dyld runs and there is no loader diagnostic at all.
+ if LlamaCppBackend._BAD_CPU_TYPE_RE.search(output or ""):
+ return (
+ "llama-server could not start: the executable was built for a "
+ "different CPU architecture than this Mac, so "
+ f"{LlamaCppBackend._runtime_remedy(binary)}."
+ )
+
# Tensor parallelism (--split-mode tensor) is arch-gated in llama.cpp;
# unsupported architectures abort the load with this marker. Point the
# user at the toggle instead of a generic invalid-GGUF/OOM message.
@@ -9976,6 +10452,23 @@ class LlamaCppBackend:
# SIGKILL with no diagnostic output is the OOM killer (e.g. a model too
# large for the WSL VM's RAM cap); name it actionably.
if returncode == -9:
+ # macOS also SIGKILLs an invalid code signature before the process
+ # can print, so memory is not the only reading there (#8566).
+ if sys.platform == "darwin":
+ # The log is often empty here, so name the likeliest cause and
+ # the macOS-specific one without claiming the two are the only
+ # ones: signal 9 is also a supervisor, or a plain `kill -9`.
+ return LlamaCppBackend._with_startup_diagnostics(
+ "llama-server was stopped by macOS (signal 9) before it "
+ "started. This is most often out of memory, so try a "
+ "smaller or more quantized GGUF, or lower the context "
+ "length. macOS also sends signal 9 when it refuses a "
+ "binary's code signature, so if memory is not the problem, "
+ f"{LlamaCppBackend._runtime_remedy(binary)}.",
+ output,
+ log_path,
+ secrets,
+ )
return (
"llama-server was stopped by the operating system (signal 9), "
"most likely out of memory. Try a smaller or more quantized "
@@ -10003,11 +10496,264 @@ class LlamaCppBackend:
)
# Fallback: genuinely unknown failure (OOM, missing binary ...).
- return (
+ # Nothing above recognised the output, so carry the evidence rather
+ # than drop it; without the tail and the log path a report of this
+ # message is unactionable and costs a round trip (#8566).
+ return LlamaCppBackend._with_startup_diagnostics(
"llama-server failed to start. "
- "Check that the GGUF file is valid and you have enough memory."
+ "Check that the GGUF file is valid and you have enough memory.",
+ output,
+ log_path,
+ secrets,
)
+ # Enough of the tail to carry a stack trace or a ggml assert, bounded so a
+ # chatty server cannot push an unreadable wall of text into an API error.
+ _STARTUP_TAIL_CHARS = 2000
+
+ # The labels _with_startup_diagnostics writes, so it can recognise its own
+ # output and stay idempotent. Kept next to the writer: a label edited on one
+ # side only would silently re-enable double appending.
+ _DIAGNOSTICS_MARKERS = ("llama-server output:", "Full log: ")
+
+ # Token shapes worth redacting on sight: a name-based list cannot cover a
+ # credential the child obtained elsewhere, or one held in a variable whose
+ # name says nothing (GITHUB_PAT, MY_THING).
+ _SECRET_VALUE_RES = (
+ re.compile(r"hf_[A-Za-z0-9]{20,}"),
+ re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
+ re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}"),
+ re.compile(r"sk-[A-Za-z0-9_\-]{20,}"),
+ # HTTP credentials, if a wrapper or a proxy echoes a request header.
+ # token68 is [A-Za-z0-9._~+/-]* with optional "=" padding (RFC 9110
+ # 11.2), so a narrower class leaves the tail of a base64 credential
+ # readable; Basic (RFC 7617) is a base64 user:password pair and belongs
+ # here for the same reason.
+ re.compile(r"(?i)(?:bearer|basic)\s+[A-Za-z0-9._~+/\-]+=*"),
+ # Our own --api-key, if a wrapper dumps its argv. token_urlsafe(32)
+ # matches no shape and is in no env var, so catch it by its flag, as
+ # _redacted_cmd_for_log already does for the log.
+ re.compile(r"(?<=--api-key )\S+"),
+ re.compile(r"(?<=--api-key=)\S+"),
+ # scheme://user:secret@host, which is what DATABASE_URL / REDIS_URL and
+ # a proxy variable carry. Keep the scheme, drop the userinfo.
+ re.compile(r"(?<=://)[^/@\s]+(?=@)"),
+ )
+
+ # NAME = value / "NAME": "value", in the three shapes an environment dump
+ # takes: shell-ish, JSON, and bare. The quoted arm ends on the delimiter it
+ # opened with, not on either quote character: a JSON value may legitimately
+ # contain an apostrophe, and rejecting both meant "DB_PASSWORD": "a' b"
+ # fell through to the bare arm, which stops at whitespace and left " b"
+ # standing in the API error. Escapes are consumed so a backslash-escaped
+ # delimiter does not end the value early. Both arms are unambiguous
+ # alternations of single characters, so matching stays linear; there is no
+ # nested quantifier for a crafted line to exploit.
+ # The name accepts the separators a config key uses, not only the ones a
+ # shell variable may: a child dumping its own configuration writes
+ # "db-password" or client.secret, and an identifier-only pattern never
+ # reached is_secret_env_name for either. The predicate still decides.
+ #
+ # Third value arm: a truncated line ends the output mid-value, so
+ # DB_PASSWORD="prefix supersecret has no closing delimiter. It cannot match
+ # the terminated arm, and the bare arm stops at whitespace, which left the
+ # rest of the credential in the API error. An opened-but-unclosed quote
+ # runs to the end of the line. Ordered after the terminated arm so a
+ # properly closed value still matches that one.
+ _SECRET_ASSIGNMENT_RE = re.compile(
+ r"""(?P<q>["']?)(?P<name>[A-Za-z_][A-Za-z0-9_.\-]{0,63})(?P=q)
+ (?P<sep>[ \t]*[=:][ \t]*)
+ (?:(?P<vq>["'])(?P<qval>(?:\\.|(?!(?P=vq))[^\\])*)(?P=vq)
+ | (?P<uq>["'])(?P<uval>[^\r\n]*)
+ | (?P<val>[^\s,;]+))""",
+ re.VERBOSE,
+ )
+
+ @staticmethod
+ def _redact_secret_assignments(text: str) -> str:
+ """Redact the value beside any secret-looking NAME, however encoded.
+
+ Positional, not literal: whatever follows the name is replaced, so
+ JSON escaping, shell quoting or URL encoding cannot smuggle a value
+ past the check the way a value-literal comparison allows.
+ """
+ try:
+ from utils.prebuilt.child_env import is_secret_env_name
+ except Exception: # noqa: BLE001 - redaction must never break a load error
+ return text
+
+ def sub(m: "re.Match[str]") -> str:
+ # A config key spells the same thing with a hyphen or a dot, and
+ # the predicate's markers are underscored (API_KEY, PRIVATE_KEY),
+ # so "api-key" missed while "api_key" matched. Normalise the
+ # separator before asking; the predicate stays the one place that
+ # decides what counts as a secret.
+ name = m.group("name")
+ if not is_secret_env_name(name.replace("-", "_").replace(".", "_")):
+ return m.group(0)
+ q, vq, uq = m.group("q"), m.group("vq"), m.group("uq")
+ if vq:
+ body = f"{vq}***{vq}"
+ elif uq:
+ # Unterminated: keep the opening delimiter, drop the rest of
+ # the line. Inventing a closing quote would misreport what the
+ # child printed.
+ body = f"{uq}***"
+ else:
+ body = "***"
+ return f"{q}{m.group('name')}{q}{m.group('sep')}{body}"
+
+ try:
+ return LlamaCppBackend._SECRET_ASSIGNMENT_RE.sub(sub, text)
+ except Exception: # noqa: BLE001
+ return text
+
+ @staticmethod
+ def _scrub_secret_values(text: str, extra: Sequence[Optional[str]] = ()) -> str:
+ """Redact credential-looking environment values out of ``text``.
+
+ llama-server inherits nearly all of Studio's environment, so a wrapper
+ script, a diagnostic build or a crash handler that echoes its env would
+ otherwise put an API key straight into the load error.
+
+ Two passes, because either alone has a hole. Matching the VALUE catches
+ a credential under a name we never heard of, but only if the child
+ printed it verbatim: a wrapper dumping its environment as JSON prints
+ pa"ss\\word as pa\\"ss\\\\word, which is a different string and was
+ reaching the API error fully reconstructible. Matching the NAME and
+ redacting whatever follows it is immune to how the value was encoded,
+ but only works for names that look like secrets. Doing both leaves a
+ gap only for an unrecognised name AND an escaped value.
+ """
+ if not text:
+ return text
+ cleaned = LlamaCppBackend._redact_secret_assignments(text)
+ # Secrets we minted and therefore know exactly: no pattern recognises
+ # a token_urlsafe blob. Gathered together with the environment's own
+ # values and replaced LONGEST FIRST, because two credentials can
+ # overlap: with TOKEN_A=abcdefgh and TOKEN_B="abcdefgh VERYSECRET",
+ # replacing the short one first rewrote the long one's only occurrence
+ # to "*** VERYSECRET", after which the long one no longer matched
+ # itself and its tail went out in the API error.
+ literals = {literal for literal in extra if literal and len(literal) >= 8}
+ # By name, reusing what decides which vars a managed server is denied,
+ # so the two cannot drift: what we withhold must not come back out of
+ # the child either. URL userinfo counts whatever it is named.
+ try:
+ from utils.prebuilt.child_env import URL_USERINFO_RE, is_secret_env_name
+ for name, value in os.environ.items():
+ if not value:
+ continue
+ secret_name = is_secret_env_name(name)
+ if len(value) < 8:
+ # Too short to replace globally ("1", "true", a port number
+ # would match everywhere), but a short password is still a
+ # password: redact it where it appears next to its name.
+ # The name and the value may each be quoted, because an env
+ # dump can be shell-ish (DB_PASSWORD='x'), JSON
+ # ({"DB_PASSWORD": "x"}), or bare, and only the bare form
+ # matched before.
+ if secret_name:
+ cleaned = re.sub(
+ rf"([\"']?{re.escape(name)}[\"']?\s*[=:]\s*)"
+ rf"([\"']?){re.escape(value)}\2",
+ r"\1\2***\2",
+ cleaned,
+ )
+ continue
+ if secret_name or URL_USERINFO_RE.search(value):
+ literals.add(value)
+ except Exception: # noqa: BLE001 - redaction must never break a load error
+ pass
+ for literal in sorted(literals, key = len, reverse = True):
+ cleaned = cleaned.replace(literal, "***")
+ # By shape, for credentials that are not in our environment to match on
+ # (a token the child read from its own config, a proxy's header echo).
+ for pattern in LlamaCppBackend._SECRET_VALUE_RES:
+ cleaned = pattern.sub("***", cleaned)
+ return cleaned
+
+ @staticmethod
+ def _has_startup_diagnostics(text: str) -> bool:
+ """Is ``text`` something _with_startup_diagnostics already produced?
+
+ Matches our own framing, not the bare words: a server that printed
+ "llama-server output:" itself must still get its tail attached.
+ """
+ return text.startswith(LlamaCppBackend._DIAGNOSTICS_MARKERS) or any(
+ f"\n\n{marker}" in text for marker in LlamaCppBackend._DIAGNOSTICS_MARKERS
+ )
+
+ # Ceiling on how far the tail window is widened for redaction. A real
+ # credential is far below this; the cap stops a pathological environment
+ # value from turning a bounded slice into a scan of everything the child
+ # ever printed.
+ _MAX_SECRET_SCAN_CHARS = 262144
+
+ @staticmethod
+ def _max_secret_len(extra: Sequence[Optional[str]] = ()) -> int:
+ """Longest value _scrub_secret_values could be asked to match, capped."""
+ longest = 0
+ for literal in extra:
+ if literal:
+ longest = max(longest, len(literal))
+ try:
+ from utils.prebuilt.child_env import URL_USERINFO_RE, is_secret_env_name
+ for name, value in os.environ.items():
+ if not value or len(value) <= longest:
+ continue
+ if is_secret_env_name(name) or URL_USERINFO_RE.search(value):
+ longest = len(value)
+ except Exception: # noqa: BLE001 - a narrower window still redacts most
+ pass
+ return min(longest, LlamaCppBackend._MAX_SECRET_SCAN_CHARS)
+
+ @staticmethod
+ def _with_startup_diagnostics(
+ message: str,
+ output: Optional[str],
+ log_path: "Optional[Path | str]",
+ extra_secrets: Sequence[Optional[str]] = (),
+ ) -> str:
+ """Append llama-server's output tail and log path to ``message``.
+
+ Returns ``message`` unchanged when there is neither, so the classified
+ messages and the no-output case keep their exact existing text.
+
+ Idempotent: a message that already carries a diagnostics block is
+ returned as is. Only one call site exists today, so this cannot fire
+ yet; it is here so a second caller (a retry that re-classifies an
+ already-decorated message, say) cannot silently double the tail.
+ """
+ if LlamaCppBackend._has_startup_diagnostics(message):
+ return message
+ parts = [message]
+ # Slice before filtering: _drain_stdout keeps an unterminated line
+ # whole, so a runaway progress line would otherwise be walked
+ # character by character just to throw all but the last 2000 away.
+ #
+ # Widened by the longest secret we could be asked to redact. The
+ # scrubber matches a whole value, so a credential longer than this
+ # window (a PEM key or a service-account blob dumped by a wrapper) was
+ # cut by the slice, and the surviving suffix matched neither the
+ # literal nor any token shape -- so it reached the API error. A shorter
+ # secret cannot straddle the boundary: if its end is inside a window
+ # wider than the secret, so is its start.
+ _window = LlamaCppBackend._STARTUP_TAIL_CHARS * 4 + LlamaCppBackend._max_secret_len(
+ extra_secrets
+ )
+ raw = (output or "")[-_window:]
+ # Control characters (progress bars, colour codes) would corrupt the
+ # API error; keep newlines and tabs, which carry the structure.
+ tail = "".join(ch for ch in raw if ch in "\n\t" or ch.isprintable()).strip()
+ if tail:
+ tail = LlamaCppBackend._scrub_secret_values(tail, extra_secrets)
+ tail = tail[-LlamaCppBackend._STARTUP_TAIL_CHARS :].lstrip()
+ parts.append(f"llama-server output:\n{tail}")
+ if log_path:
+ parts.append(f"Full log: {log_path}")
+ return "\n\n".join(parts)
+
def _plan_tensor_parallel(
self,
gpus: list[tuple[int, int]],
@@ -10756,7 +11502,7 @@ class LlamaCppBackend:
if cpu_binary is None:
return None
loader_env = self._llama_server_env_for_binary(cpu_binary)
- loader_path = "PATH" if sys.platform == "win32" else "LD_LIBRARY_PATH"
+ loader_path = _loader_path_var()
env[loader_path] = loader_env[loader_path]
replay[0] = cpu_binary
# Staging covers only the executable and libraries, so keep Studio's working
@@ -10768,8 +11514,15 @@ class LlamaCppBackend:
Backend loading precedes ``--device none``, so isolation prevents the
Vulkan plugin from loading first.
+
+ Gated on the install tree, not on _is_unsloth_managed_binary: that one
+ answers "would `unsloth studio update` replace this file", which is a
+ question about repair advice, and it now answers no for a
+ --with-llama-cpp-dir tree. Staging a CPU copy needs neither the updater
+ nor write access to the source, so those installs keep the fallback
+ they had on every platform.
"""
- if not binary or not self._is_unsloth_managed_binary(binary):
+ if not binary or not self._is_llama_install_tree(binary):
return None
source_binary = _resolve_llama_binary(binary)
source_stamp = self._binary_stamp(source_binary)
@@ -11203,6 +11956,18 @@ class LlamaCppBackend:
# Resolve llama-server now but defer a not-found error: a block-diffusion
# GGUF uses the diffusion runner, and its arch is only known after the header.
binary = self._find_llama_server_binary()
+ # macOS: launch the resolved server, never a shell entrypoint. SIP
+ # purges DYLD_* while starting the protected /bin/sh a wrapper
+ # entrypoint runs under, so the loader path built for the child
+ # would not survive the wrapper's own exec (#8566). The installer
+ # writes a wrapper only when it cannot symlink, and that wrapper
+ # does nothing but exec the target with "$@", so this is the same
+ # launch minus the shell hop. The resolved path stays inside the
+ # managed install, so provenance-aware advice is unaffected.
+ # Resolved here rather than at the later reset so every consumer of
+ # `binary` below (capability probe, revision stamp) shares one path
+ # space; `_binary_changed_since_launch` compares against this one.
+ binary = self._exec_path_for_launch(binary)
# Every capability answer shaping this launch, latching whether any was a
# guess. Accumulated, not sampled: the decisions straddle the whole load (slot
@@ -14576,6 +15341,8 @@ class LlamaCppBackend:
self._model_identifier,
cpu_rc,
binary,
+ self._llama_log_path,
+ (self._api_key,),
)
self._cleanup_failed_cpu_fallback()
self._vram_fraction_pending = None
@@ -15148,6 +15915,8 @@ class LlamaCppBackend:
self._model_identifier,
_retry_rc,
binary,
+ self._llama_log_path,
+ (self._api_key,),
)
_raise_terminal_load_failure(
self._mmproj_retry_failure_message(
@@ -15182,6 +15951,8 @@ class LlamaCppBackend:
self._model_identifier,
_crash_rc,
binary,
+ self._llama_log_path,
+ (self._api_key,),
)
)
diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.py
index 687b574bdfa..63c92a9c281 100644
--- a/studio/backend/core/rag/embed_llama_server.py
+++ b/studio/backend/core/rag/embed_llama_server.py
@@ -20,6 +20,7 @@ import atexit
import logging
import os
import subprocess
+import sys
import threading
import time
from functools import lru_cache
@@ -45,6 +46,48 @@ _TRANSPORT_ERRORS = (
)
+def _resolve_entrypoint(binary: str) -> str:
+ """The real executable behind a managed shell/symlink entrypoint.
+
+ macOS only matters here: SIP purges DYLD_* while starting the protected
+ /bin/sh a wrapper runs under, so probing or launching the wrapper loses the
+ loader path however carefully the environment was built (#8566). Shared
+ with the chat backend, which restricts this to OUR entrypoint so a user's
+ own wrapper keeps whatever setup it does before its exec.
+ """
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+ return LlamaCppBackend._exec_path_for_launch(binary) or binary
+ except Exception: # noqa: BLE001 - launch what we were given
+ return binary
+
+
+def _binary_lib_dir(binary: str) -> str:
+ """Directory holding ``binary``'s sibling libraries, through an entrypoint."""
+ try:
+ from core.inference.llama_cpp import _llama_lib_dir
+ return str(_llama_lib_dir(binary))
+ except Exception: # noqa: BLE001 - fall back to the plain parent
+ return str(Path(binary).parent)
+
+
+def _with_dyld_path(env: dict[str, str], lib_dir: str) -> dict[str, str]:
+ """``env`` with ``lib_dir`` first on the macOS loader search path.
+
+ Returns a new dict rather than editing in place: the caller's environment is
+ its own, and the chat backend's equivalent is a pure function too. Shares
+ that one's prepend so both dedupe the same way.
+ """
+ out = dict(env)
+ try:
+ from core.inference.llama_cpp import _prepend_loader_dir
+ out["DYLD_LIBRARY_PATH"] = _prepend_loader_dir(out.get("DYLD_LIBRARY_PATH", ""), lib_dir)
+ except Exception: # noqa: BLE001 - a search path is better than none
+ existing = [p for p in out.get("DYLD_LIBRARY_PATH", "").split(os.pathsep) if p]
+ out["DYLD_LIBRARY_PATH"] = os.pathsep.join(dict.fromkeys([lib_dir, *existing]))
+ return out
+
+
class LlamaServerBackend:
"""Manages a llama.cpp embedding subprocess and talks to it over HTTP."""
@@ -89,6 +132,9 @@ class LlamaServerBackend:
"llama-server. Install llama.cpp or set LLAMA_SERVER_PATH / "
"UNSLOTH_LLAMA_CPP_PATH."
)
+ # Before the probe, so the --help check and the spawn both run the real
+ # executable rather than an entrypoint that loses DYLD_* to SIP.
+ binary = _resolve_entrypoint(binary)
self._assert_embedding_support(binary)
self._binary = binary
return binary
@@ -97,7 +143,24 @@ class LlamaServerBackend:
@lru_cache(maxsize = 8)
def _help_text(binary: str) -> str:
"""`llama-server --help`, cached. Ignore exit code (some builds exit
- non-zero on --help)."""
+ non-zero on --help).
+
+ On macOS, runs under the same loader environment as the real launch.
+ Without it, a bundle that needs the search path dies in the loader
+ here, and its error text reads as help output with no ``--embedding``
+ in it, so the caller reports a build that lacks embeddings instead of a
+ load failure. Elsewhere the probe keeps inheriting this process's
+ environment exactly as it always has: the loader hole is macOS-only,
+ and a probe that answers "does this build do embeddings" has no reason
+ to run under a different environment than it did before.
+ """
+ probe_env = None
+ if sys.platform == "darwin":
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+ probe_env = LlamaCppBackend._llama_server_env_for_binary(binary)
+ except Exception: # noqa: BLE001 - probe with the inherited env
+ probe_env = None
try:
proc = subprocess.run(
[binary, "--help"],
@@ -106,6 +169,7 @@ class LlamaServerBackend:
encoding = "utf-8",
errors = "replace",
timeout = 30,
+ env = probe_env,
**windows_hidden_subprocess_kwargs(),
)
return (proc.stdout or "") + (proc.stderr or "")
@@ -269,7 +333,18 @@ class LlamaServerBackend:
def _build_env(self, binary: str, *, use_gpu: bool) -> dict[str, str]:
env = child_env_without_native_path_secret()
env["LLAMA_SET_ROWS"] = "1" # ggml set_rows fast path
- if use_gpu:
+ if sys.platform == "darwin":
+ # _llama_lib_dir, not Path(binary).parent: the managed install puts
+ # an entrypoint in front of the real server, and the dylibs sit
+ # next to the target, not next to the wrapper. Unconditional,
+ # unlike the CUDA branch below: a CPU start loads the same sibling
+ # dylibs (#8566).
+ env = _with_dyld_path(env, _binary_lib_dir(binary))
+ elif use_gpu:
+ # Path(binary).parent, unchanged. Resolving the entrypoint here too
+ # would be more correct in principle, but it moves the first
+ # LD_LIBRARY_PATH entry for every existing Linux GPU install whose
+ # llama-server is a symlink, and this change is not about them.
self._add_linux_cuda_libs(env, str(Path(binary).parent))
_pinned = self._arch_gated_gpu_ids(binary)
if _pinned:
@@ -281,7 +356,9 @@ class LlamaServerBackend:
env, ",".join(str(i) for i in _pinned), prefer_rocr = True
)
logger.info("pinning the embed server to arch-supported GPU(s) %s", _pinned)
- else:
+ # Not else: the darwin branch above is about dylibs, so a macOS CPU start
+ # still has to blank the devices, exactly as it did before that branch.
+ if not use_gpu:
# Blank devices so a CUDA build stays on CPU and reserves no VRAM.
env["CUDA_VISIBLE_DEVICES"] = ""
# HIP reads CUDA_VISIBLE_DEVICES only when HIP_VISIBLE_DEVICES is unset,
@@ -305,7 +382,6 @@ class LlamaServerBackend:
"""Best-effort LD_LIBRARY_PATH so the prebuilt binary finds CUDA libs."""
import glob
import platform
- import sys
if sys.platform == "win32":
return # Windows resolves CUDA via PATH in the inherited env.
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index ebc63e1e769..a7bcbe8b876 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -7204,10 +7204,29 @@ _NVFP4_INFERENCE_UNSUPPORTED_MESSAGE = (
)
+def _diagnosis_text(msg: str) -> str:
+ """``msg`` up to the startup-diagnostics block, which is not ours to read.
+
+ A llama-server failure now carries a tail of the child's own stdout and the
+ log path. That evidence is quoted verbatim from an untrusted process, so
+ matching a phrase inside it says nothing about the model: llama.cpp prints
+ lines like "device does not support 16-bit storage" for reasons that have
+ nothing to do with the checkpoint, and every phrase below would then rewrite
+ the diagnosis to "This model is not supported yet". Match on the part this
+ backend wrote. A message without the block is returned unchanged, so every
+ other error source behaves exactly as before.
+ """
+ for marker in ("\n\nllama-server output:", "\n\nFull log: "):
+ head, sep, _ = msg.partition(marker)
+ if sep:
+ msg = head
+ return msg
+
+
def _is_unsupported_nvfp4_inference_error(msg: str) -> bool:
"""Whether ``msg`` is the verbose MLX per-module metadata error emitted
while loading an NVFP4 checkpoint."""
- lower_msg = msg.lower()
+ lower_msg = _diagnosis_text(msg).lower()
return "nvfp4" in lower_msg and "per-module mlx quantization metadata" in lower_msg
@@ -7215,7 +7234,8 @@ def _maybe_unsupported_message(msg: str) -> str:
"""Rewrite a load/validate error into the friendly "not supported yet"
message when it matches a known unsupported-model signature; otherwise
return ``msg`` unchanged."""
- if any(h.lower() in msg.lower() for h in _NOT_SUPPORTED_HINTS):
+ hay = _diagnosis_text(msg).lower()
+ if any(h.lower() in hay for h in _NOT_SUPPORTED_HINTS):
return f"This model is not supported yet. Try a different model. (Original error: {msg})"
return msg
diff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.py
index 485febc2df7..2c164bbb4bc 100644
--- a/studio/backend/tests/test_gpu_init_crash_message.py
+++ b/studio/backend/tests/test_gpu_init_crash_message.py
@@ -73,6 +73,15 @@ def _managed_runtime(monkeypatch, tmp_path):
"_is_unsloth_managed_binary",
staticmethod(lambda _binary: True),
)
+ # _cpu_isolated_binary asks whether this is an install tree, which is not
+ # the same question as whether the updater can replace the file: a
+ # --with-llama-cpp-dir checkout is the active install while being the
+ # user's to maintain. Staging a CPU copy only reads, so it uses this one.
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_is_llama_install_tree",
+ staticmethod(lambda _binary: True),
+ )
monkeypatch.setattr(
llama_cpp,
"_swa_cache_path",
@@ -298,6 +307,9 @@ class TestPlatformMatrix:
monkeypatch.setattr(
LlamaCppBackend, "_is_unsloth_managed_binary", staticmethod(lambda _binary: True)
)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_llama_install_tree", staticmethod(lambda _binary: True)
+ )
monkeypatch.setattr(
llama_cpp, "_swa_cache_path", lambda: tmp_path / "studio" / "swa_cache.json"
)
@@ -860,6 +872,11 @@ class TestCpuIsolatedReplay:
"_is_unsloth_managed_binary",
staticmethod(lambda _binary: True),
)
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_is_llama_install_tree",
+ staticmethod(lambda _binary: True),
+ )
monkeypatch.setattr(
llama_cpp,
"_swa_cache_path",
diff --git a/studio/backend/tests/test_llama_cpp_darwin_loader_env.py b/studio/backend/tests/test_llama_cpp_darwin_loader_env.py
new file mode 100644
index 00000000000..d5084a52669
--- /dev/null
+++ b/studio/backend/tests/test_llama_cpp_darwin_loader_env.py
@@ -0,0 +1,613 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the llama-server child environment, per platform.
+
+_llama_server_env_for_binary used to branch win32 vs "everything else", and
+that else branch is Linux: WSL/ROCm probing, pip nvidia wheel globs, CUDA
+toolkit paths, and LD_LIBRARY_PATH. dyld ignores LD_LIBRARY_PATH, so on macOS
+llama-server was launched with no library search path at all, while the
+installer's own staged-binary validation sets DYLD_LIBRARY_PATH and therefore
+passed on a path the real launch never took (issue #8566).
+
+These tests pin the Darwin branch and, just as importantly, pin the Linux and
+Windows branches so the fix cannot change them.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import types as _types
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+# Match sibling tests' stubbing so the module imports without fastapi.
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
+sys.modules.setdefault("loggers", _loggers_stub)
+_structlog_stub = _types.ModuleType("structlog")
+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("structlog")
+sys.modules.setdefault("structlog", _structlog_stub)
+if not hasattr(sys.modules["structlog"], "get_logger"):
+ sys.modules["structlog"].get_logger = _structlog_stub.get_logger
+
+from core.inference import llama_cpp as llama_module # noqa: E402
+from core.inference.llama_cpp import LlamaCppBackend # noqa: E402
+
+
+def binary(tmp_path):
+ path = tmp_path / "llama.cpp" / "build" / "bin" / "llama-server"
+ path.parent.mkdir(parents = True)
+ path.write_text("")
+ return path
+
+
+def _env_for(binary_path):
+ return LlamaCppBackend._llama_server_env_for_binary(str(binary_path))
+
+
+def _no_linux_discovery(monkeypatch):
+ """Make the Linux-only helpers fatal, so entering that branch is caught."""
+
+ def _boom(*_a, **_k):
+ raise AssertionError("Linux discovery ran on a non-Linux platform")
+
+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", _boom)
+ monkeypatch.setattr(llama_module, "_native_linux_system_rocm_lib_dirs", _boom)
+
+
+class TestDarwin:
+ def test_binary_dir_lands_on_dyld_library_path(self, monkeypatch, binary):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.delenv("DYLD_LIBRARY_PATH", raising = False)
+ _no_linux_discovery(monkeypatch)
+ env = _env_for(binary)
+ assert env["DYLD_LIBRARY_PATH"].split(os.pathsep)[0] == str(binary.parent)
+
+ def test_inherited_dyld_entries_are_kept_after_ours(self, monkeypatch, binary):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setenv("DYLD_LIBRARY_PATH", "/opt/inherited")
+ _no_linux_discovery(monkeypatch)
+ entries = _env_for(binary)["DYLD_LIBRARY_PATH"].split(os.pathsep)
+ assert entries == [str(binary.parent), "/opt/inherited"]
+
+ def test_our_dir_is_not_duplicated(self, monkeypatch, binary):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setenv("DYLD_LIBRARY_PATH", f"{binary.parent}{os.pathsep}/opt/inherited")
+ _no_linux_discovery(monkeypatch)
+ entries = _env_for(binary)["DYLD_LIBRARY_PATH"].split(os.pathsep)
+ assert entries == [str(binary.parent), "/opt/inherited"]
+
+ def test_an_inherited_ld_library_path_is_left_alone(self, monkeypatch, binary):
+ # Repurposing it would be pointless (dyld ignores it) and would leak a
+ # llama.cpp dir into anything the user set it for.
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setenv("LD_LIBRARY_PATH", "/opt/sentinel")
+ _no_linux_discovery(monkeypatch)
+ assert _env_for(binary)["LD_LIBRARY_PATH"] == "/opt/sentinel"
+
+ def test_a_wrapper_entrypoint_resolves_to_the_real_bin_dir(self, monkeypatch, tmp_path):
+ # The managed install can put a shell entrypoint in front of the real
+ # binary; the dylibs sit next to the target, not next to the wrapper.
+ # The env dict alone is not enough on a Mac: SIP purges DYLD_* while
+ # starting the protected /bin/sh a wrapper runs under, so load_model
+ # launches the resolved target instead (see
+ # TestDarwinSpawnsTheResolvedBinary).
+ real_dir = tmp_path / "llama.cpp" / "build" / "bin"
+ real_dir.mkdir(parents = True)
+ (real_dir / "llama-server-real").write_text("")
+ wrapper = real_dir / "llama-server"
+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/llama-server-real" "$@"\n')
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.delenv("DYLD_LIBRARY_PATH", raising = False)
+ _no_linux_discovery(monkeypatch)
+ env = LlamaCppBackend._llama_server_env_for_binary(str(wrapper))
+ assert env["DYLD_LIBRARY_PATH"].split(os.pathsep)[0] == str(real_dir)
+
+ def test_loader_path_var_matches_the_sibling_engines(self, monkeypatch):
+ for platform, expected in (
+ ("darwin", "DYLD_LIBRARY_PATH"),
+ ("win32", "PATH"),
+ ("linux", "LD_LIBRARY_PATH"),
+ ):
+ monkeypatch.setattr(sys, "platform", platform)
+ assert llama_module._loader_path_var() == expected
+
+
+class TestLinuxUnchanged:
+ def test_binary_dir_still_lands_on_ld_library_path(self, monkeypatch, binary):
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)
+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: [])
+ monkeypatch.setattr(llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: [])
+ env = _env_for(binary)
+ # startswith, not split(":")[0]: the Linux branch joins with a literal
+ # ":" and this test simulates Linux on whatever host runs it, so on a
+ # Windows runner the first entry is "C:\..." and splitting yields "C".
+ assert env["LD_LIBRARY_PATH"].startswith(str(binary.parent))
+ assert "DYLD_LIBRARY_PATH" not in env
+
+ def test_inherited_entries_stay_last(self, monkeypatch, binary):
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setenv("LD_LIBRARY_PATH", "/opt/inherited")
+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: [])
+ monkeypatch.setattr(llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: [])
+ assert _env_for(binary)["LD_LIBRARY_PATH"].split(":")[-1] == "/opt/inherited"
+
+ def test_system_rocm_still_precedes_the_bundle(self, monkeypatch, binary):
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)
+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: ["/wsl/rocm"])
+ monkeypatch.setattr(llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: [])
+ env = _env_for(binary)
+ assert env["LD_LIBRARY_PATH"].split(":")[0] == "/wsl/rocm"
+ assert env.get("HSA_ENABLE_DXG_DETECTION") == "1"
+
+
+class TestWindowsUnchanged:
+ def test_path_is_semicolon_joined_and_no_unix_vars_appear(self, monkeypatch, binary):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setenv("PATH", "C:\\existing")
+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)
+ monkeypatch.delenv("DYLD_LIBRARY_PATH", raising = False)
+ _no_linux_discovery(monkeypatch)
+ env = _env_for(binary)
+ assert env["PATH"].startswith(f"{binary.parent};")
+ assert env["PATH"].endswith("C:\\existing")
+ assert "LD_LIBRARY_PATH" not in env
+ assert "DYLD_LIBRARY_PATH" not in env
+
+
+class TestDarwinSpawnsTheResolvedBinary:
+ """macOS SIP purges DYLD_* while starting the protected /bin/sh that a
+ wrapper entrypoint runs under, so the loader path we build would not
+ survive the wrapper's own exec. load_model resolves the entrypoint first."""
+
+ def test_resolve_llama_binary_follows_the_wrapper(self, tmp_path):
+ real_dir = tmp_path / "build" / "bin"
+ real_dir.mkdir(parents = True)
+ target = real_dir / "llama-server-real"
+ target.write_text("")
+ wrapper = real_dir / "llama-server"
+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/llama-server-real" "$@"\n')
+ assert llama_module._resolve_llama_binary(str(wrapper)) == target
+
+ def test_a_plain_binary_is_returned_unchanged(self, binary):
+ assert llama_module._resolve_llama_binary(str(binary)) == binary.resolve()
+
+
+class TestExecPathForLaunch:
+ """Only OUR entrypoint is resolved past. A user's LLAMA_SERVER_PATH wrapper
+ may export backend variables before its exec line, and jumping straight to
+ the target would silently drop that setup."""
+
+ def _wrapper(self, tmp_path):
+ real_dir = tmp_path / "llama.cpp" / "build" / "bin"
+ real_dir.mkdir(parents = True)
+ (real_dir / "llama-server-real").write_text("")
+ wrapper = real_dir / "llama-server"
+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/llama-server-real" "$@"\n')
+ return wrapper, real_dir / "llama-server-real"
+
+ def test_a_managed_entrypoint_is_resolved(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ wrapper, target = self._wrapper(tmp_path)
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_PATH", str(tmp_path / "llama.cpp"))
+ assert LlamaCppBackend._exec_path_for_launch(str(wrapper)) == str(target)
+
+ def test_a_pinned_custom_wrapper_is_launched_as_given(self, monkeypatch, tmp_path):
+ wrapper, _ = self._wrapper(tmp_path)
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setenv("LLAMA_SERVER_PATH", str(wrapper))
+ assert LlamaCppBackend._exec_path_for_launch(str(wrapper)) == str(wrapper)
+
+ def test_other_platforms_are_untouched(self, monkeypatch, tmp_path):
+ wrapper, _ = self._wrapper(tmp_path)
+ for platform in ("linux", "win32"):
+ monkeypatch.setattr(sys, "platform", platform)
+ assert LlamaCppBackend._exec_path_for_launch(str(wrapper)) == str(wrapper)
+
+ def test_no_binary_is_passed_through(self, monkeypatch):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ assert LlamaCppBackend._exec_path_for_launch(None) is None
+
+
+class TestBinaryRevisionPathSpace:
+ """_binary_revision keys on the path string, so both sides of the
+ changed-since-launch comparison must resolve the entrypoint the same way.
+ Otherwise every Apply on a macOS managed install looks like an update and
+ reloads the model."""
+
+ def _managed_wrapper(self, monkeypatch, tmp_path):
+ root = tmp_path / "llama.cpp"
+ real_dir = root / "build" / "bin"
+ real_dir.mkdir(parents = True)
+ (real_dir / "llama-server-real").write_text("real")
+ wrapper = root / "llama-server"
+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server-real" "$@"\n')
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_PATH", str(root))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ return wrapper
+
+ def test_an_unchanged_managed_install_does_not_look_updated(self, monkeypatch, tmp_path):
+ wrapper = self._managed_wrapper(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda **_k: str(wrapper))
+ )
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._launch_binary_revision = LlamaCppBackend._binary_revision(
+ LlamaCppBackend._exec_path_for_launch(str(wrapper))
+ )
+ assert backend._launch_binary_revision # the stamp is readable
+ assert backend._binary_changed_since_launch() is False
+
+ def test_a_real_update_is_still_detected(self, monkeypatch, tmp_path):
+ wrapper = self._managed_wrapper(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda **_k: str(wrapper))
+ )
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._launch_binary_revision = LlamaCppBackend._binary_revision(
+ LlamaCppBackend._exec_path_for_launch(str(wrapper))
+ )
+ target = tmp_path / "llama.cpp" / "build" / "bin" / "llama-server-real"
+ target.write_text("a different build entirely")
+ assert backend._binary_changed_since_launch() is True
+
+
+class TestLocalLinkInstalls:
+ """--with-llama-cpp-dir points the canonical llama.cpp dir at the user's own
+ checkout. The updater refuses to write through that link, so the install is
+ theirs: no updater advice, and no resolving past their entrypoint."""
+
+ def _local_link_tree(self, tmp_path, monkeypatch):
+ external = tmp_path / "my-llama-checkout"
+ bin_dir = external / "build" / "bin"
+ bin_dir.mkdir(parents = True)
+ (bin_dir / "llama-server-real").write_text("")
+ wrapper = external / "llama-server"
+ wrapper.write_text(
+ '#!/bin/sh\nexport MY_BACKEND=1\nexec "$(dirname "$0")/build/bin/llama-server-real" "$@"\n'
+ )
+ studio_root = tmp_path / "studio"
+ studio_root.mkdir()
+ link = studio_root / "llama.cpp"
+ link.symlink_to(external)
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_PATH", str(link))
+ return link / "llama-server"
+
+ def test_a_local_link_is_not_reported_as_managed(self, monkeypatch, tmp_path):
+ binary = self._local_link_tree(tmp_path, monkeypatch)
+ assert LlamaCppBackend._is_unsloth_managed_binary(str(binary)) is False
+
+ def test_the_users_entrypoint_is_launched_as_given(self, monkeypatch, tmp_path):
+ binary = self._local_link_tree(tmp_path, monkeypatch)
+ monkeypatch.setattr(sys, "platform", "darwin")
+ assert LlamaCppBackend._exec_path_for_launch(str(binary)) == str(binary)
+
+ def test_the_remedy_does_not_send_them_to_the_updater(self, monkeypatch, tmp_path):
+ binary = self._local_link_tree(tmp_path, monkeypatch)
+ remedy = LlamaCppBackend._runtime_remedy(str(binary))
+ assert "unsloth studio update" not in remedy
+ assert "custom llama.cpp" in remedy
+
+
+class TestTheLoaderPathPrependIsAFixedPoint:
+ """Repeat application must not grow the search path.
+
+ Building the child environment twice happens on any retry (CPU fallback,
+ the mmproj text-only replay), and a value that grew each time would end up
+ with the runtime dir listed once per attempt.
+ """
+
+ def test_the_binary_dir_comes_first(self):
+ assert llama_module._prepend_loader_dir("", "/x/bin") == "/x/bin"
+ assert llama_module._prepend_loader_dir("/a", "/x/bin") == f"/x/bin{os.pathsep}/a"
+
+ def test_repeating_it_changes_nothing(self):
+ once = llama_module._prepend_loader_dir("/a", "/x/bin")
+ assert llama_module._prepend_loader_dir(once, "/x/bin") == once
+ assert llama_module._prepend_loader_dir(once, "/x/bin") == once
+
+ @pytest.mark.parametrize("spelling", ["/x/bin/", "/x/./bin", "/x/y/../bin", "/x//bin"])
+ def test_the_same_dir_spelled_differently_is_not_kept_twice(self, spelling):
+ got = llama_module._prepend_loader_dir(spelling, "/x/bin")
+ assert got == "/x/bin"
+
+ def test_an_unrelated_entry_survives_with_its_own_spelling(self):
+ got = llama_module._prepend_loader_dir(f"/opt/other/{os.pathsep}/x/bin/", "/x/bin")
+ assert got == f"/x/bin{os.pathsep}/opt/other/"
+
+ def test_empty_segments_are_dropped(self):
+ got = llama_module._prepend_loader_dir(f"{os.pathsep}{os.pathsep}/a{os.pathsep}", "/x/bin")
+ assert got == f"/x/bin{os.pathsep}/a"
+
+ def test_building_the_env_twice_gives_the_same_value(self, monkeypatch, tmp_path):
+ binary = tmp_path / "build" / "bin" / "llama-server"
+ binary.parent.mkdir(parents = True)
+ binary.write_bytes(b"\xcf\xfa\xed\xfe")
+ monkeypatch.setattr(sys, "platform", "darwin")
+ first = LlamaCppBackend._llama_server_env_for_binary(str(binary))
+ monkeypatch.setenv("DYLD_LIBRARY_PATH", first["DYLD_LIBRARY_PATH"])
+ second = LlamaCppBackend._llama_server_env_for_binary(str(binary))
+ assert second["DYLD_LIBRARY_PATH"] == first["DYLD_LIBRARY_PATH"]
+
+
+class TestAnExplicitPinOutranksInferredOwnership:
+ """A wrapper the user named in LLAMA_SERVER_PATH is theirs.
+
+ Ownership is inferred from an install marker somewhere above the file, so a
+ wrapper pinned INSIDE a managed tree read as ours and was resolved past,
+ dropping whatever it exported before its exec line.
+ """
+
+ @staticmethod
+ def _managed_tree_with_a_pinned_wrapper(tmp_path):
+ root = tmp_path / "llama.cpp"
+ (root / "build" / "bin").mkdir(parents = True)
+ (root / "build" / "bin" / "llama-server").write_bytes(b"\xcf\xfa\xed\xfe")
+ for marker in (
+ "UNSLOTH_PREBUILT_INFO.json",
+ ".unsloth_llama_install",
+ "unsloth_install.json",
+ ):
+ (root / marker).write_text("{}")
+ wrapper = root / "my-wrapper"
+ wrapper.write_text(
+ '#!/bin/sh\nexport MY_TUNING=1\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n'
+ )
+ wrapper.chmod(0o755)
+ return wrapper
+
+ def test_the_pinned_wrapper_is_launched_not_its_target(self, monkeypatch, tmp_path):
+ wrapper = self._managed_tree_with_a_pinned_wrapper(tmp_path)
+ monkeypatch.setenv("LLAMA_SERVER_PATH", str(wrapper))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ assert LlamaCppBackend._exec_path_for_launch(str(wrapper)) == str(wrapper)
+
+ def test_the_managed_entrypoint_beside_it_is_still_resolved(self, monkeypatch, tmp_path):
+ wrapper = self._managed_tree_with_a_pinned_wrapper(tmp_path)
+ entry = wrapper.parent / "llama-server"
+ entry.write_text('#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n')
+ entry.chmod(0o755)
+ monkeypatch.setenv("LLAMA_SERVER_PATH", str(wrapper))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ got = LlamaCppBackend._exec_path_for_launch(str(entry))
+ assert got == str(wrapper.parent / "build" / "bin" / "llama-server")
+
+
+class TestTheCpuFallbackGateIsUnchangedForLinkedTrees:
+ """--with-llama-cpp-dir is not something `unsloth studio update` can fix.
+
+ Teaching _is_unsloth_managed_binary that also changed the gate on the
+ Vulkan CPU fallback, which needs only to read and copy the tree, so those
+ installs lost the fallback on Linux and Windows. The two questions are
+ asked separately now.
+ """
+
+ @staticmethod
+ def _linked_tree(tmp_path, monkeypatch):
+ external = tmp_path / "my-llama-checkout"
+ (external / "build" / "bin").mkdir(parents = True)
+ (external / "build" / "bin" / "llama-server").write_bytes(b"\xcf\xfa\xed\xfe")
+ studio_root = tmp_path / "studio"
+ studio_root.mkdir()
+ link = studio_root / "llama.cpp"
+ link.symlink_to(external)
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_PATH", str(link))
+ return str(link / "build" / "bin" / "llama-server")
+
+ def test_the_updater_cannot_repair_it(self, monkeypatch, tmp_path):
+ binary = self._linked_tree(tmp_path, monkeypatch)
+ assert LlamaCppBackend._is_unsloth_managed_binary(binary) is False
+
+ def test_but_it_is_still_an_install_tree_we_can_stage_from(self, monkeypatch, tmp_path):
+ binary = self._linked_tree(tmp_path, monkeypatch)
+ assert LlamaCppBackend._is_llama_install_tree(binary) is True
+
+
+class TestAWrapperChainIsFollowedToTheEnd:
+ """One hop was not enough.
+
+ A wrapper whose target is another wrapper resolved to the intermediate
+ script, so on macOS the launch still went through a shell (losing DYLD_* to
+ SIP) and _llama_lib_dir returned the wrapper's directory rather than the one
+ holding the dylibs.
+ """
+
+ @staticmethod
+ def _chain(tmp_path, depth):
+ real_dir = tmp_path / "build" / "bin"
+ real_dir.mkdir(parents = True)
+ real = real_dir / "llama-server"
+ real.write_bytes(b"\xcf\xfa\xed\xfe")
+ target = "build/bin/llama-server"
+ for i in range(depth):
+ name = f"hop{i}.sh" if i < depth - 1 else "llama-server"
+ p = tmp_path / name
+ p.write_text(f'#!/bin/sh\nexec "$(dirname "$0")/{target}" "$@"\n')
+ p.chmod(0o755)
+ target = name
+ return tmp_path / "llama-server", real
+
+ @pytest.mark.parametrize("depth", [1, 2, 3])
+ def test_the_real_binary_is_reached(self, tmp_path, depth):
+ entry, real = self._chain(tmp_path, depth)
+ assert llama_module._resolve_llama_binary(str(entry)) == real.resolve()
+ assert llama_module._llama_lib_dir(str(entry)) == real.parent.resolve()
+
+ def test_a_wrapper_loop_terminates(self, tmp_path):
+ a = tmp_path / "llama-server"
+ b = tmp_path / "other.sh"
+ a.write_text('#!/bin/sh\nexec "$(dirname "$0")/other.sh" "$@"\n')
+ b.write_text('#!/bin/sh\nexec "$(dirname "$0")/llama-server" "$@"\n')
+ a.chmod(0o755)
+ b.chmod(0o755)
+ got = llama_module._resolve_llama_binary(str(a))
+ assert got in (a.resolve(), b.resolve())
+
+
+class TestOnlyTheInstallersOwnEntrypointIsSkipped:
+ """UNSLOTH_LLAMA_CPP_PATH makes a user's checkout read as managed.
+
+ _llama_install_root treats the directory named by that variable as the
+ active install with no marker file needed, so provenance alone said "ours"
+ for a wrapper at the root of somebody's own tree, and its exports were lost.
+ The installer writes a fixed three-line wrapper; anything else is theirs.
+ """
+
+ @staticmethod
+ def _tree(tmp_path, wrapper_body):
+ root = tmp_path / "my-llama-checkout"
+ (root / "build" / "bin").mkdir(parents = True)
+ (root / "build" / "bin" / "llama-server").write_bytes(b"\xcf\xfa\xed\xfe")
+ entry = root / "llama-server"
+ entry.write_text(wrapper_body)
+ entry.chmod(0o755)
+ return root, entry
+
+ _INSTALLER = '#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n'
+ _USERS = '#!/bin/sh\nexport MY_TUNING=1\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n'
+
+ def test_a_users_wrapper_in_a_custom_dir_is_launched_as_written(self, monkeypatch, tmp_path):
+ root, entry = self._tree(tmp_path, self._USERS)
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_PATH", str(root))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ # It really does read as managed; the exemption is the wrapper shape.
+ assert LlamaCppBackend._is_unsloth_managed_binary(str(entry)) is True
+ assert LlamaCppBackend._exec_path_for_launch(str(entry)) == str(entry)
+
+ def test_the_installers_own_wrapper_is_still_resolved(self, monkeypatch, tmp_path):
+ root, entry = self._tree(tmp_path, self._INSTALLER)
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_PATH", str(root))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ got = LlamaCppBackend._exec_path_for_launch(str(entry))
+ assert got == str((root / "build" / "bin" / "llama-server").resolve())
+
+ def test_the_library_dir_still_comes_from_the_target(self, monkeypatch, tmp_path):
+ # _llama_lib_dir must keep resolving ANY wrapper: the dylibs sit beside
+ # the target whoever wrote the script.
+ root, entry = self._tree(tmp_path, self._USERS)
+ assert llama_module._llama_lib_dir(str(entry)) == (root / "build" / "bin").resolve()
+
+ def test_a_symlink_entrypoint_is_ours_to_resolve(self, monkeypatch, tmp_path):
+ root = tmp_path / "t"
+ (root / "build" / "bin").mkdir(parents = True)
+ real = root / "build" / "bin" / "llama-server"
+ real.write_bytes(b"\xcf\xfa\xed\xfe")
+ link = root / "llama-server"
+ link.symlink_to(real)
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_PATH", str(root))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ assert LlamaCppBackend._exec_path_for_launch(str(link)) == str(real.resolve())
+
+
+class TestPinningTheInstallersOwnEntrypoint:
+ """Pointing LLAMA_SERVER_PATH at our own wrapper is a supported setup.
+
+ An earlier fix made an exact pin short-circuit resolution outright, to
+ protect a custom wrapper's setup. That was too broad: pinning the
+ installer's own entrypoint then launched through /bin/sh, SIP dropped
+ DYLD_*, and #8566 came back for that configuration. The wrapper's shape
+ decides now, so a template wrapper resolves however it was reached and a
+ custom one is preserved however it was reached.
+ """
+
+ @staticmethod
+ def _managed_tree(tmp_path, body):
+ root = tmp_path / "llama.cpp"
+ (root / "build" / "bin").mkdir(parents = True)
+ (root / "build" / "bin" / "llama-server").write_bytes(b"\xcf\xfa\xed\xfe")
+ for marker in (
+ "UNSLOTH_PREBUILT_INFO.json",
+ ".unsloth_llama_install",
+ "unsloth_install.json",
+ ):
+ (root / marker).write_text("{}")
+ entry = root / "llama-server"
+ entry.write_text(body)
+ entry.chmod(0o755)
+ return root, entry
+
+ _INSTALLER = '#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n'
+ _CUSTOM = '#!/bin/sh\nexport MY_TUNING=1\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n'
+
+ def test_a_pinned_installer_wrapper_still_resolves(self, monkeypatch, tmp_path):
+ root, entry = self._managed_tree(tmp_path, self._INSTALLER)
+ monkeypatch.delenv("UNSLOTH_LLAMA_CPP_PATH", raising = False)
+ monkeypatch.setenv("LLAMA_SERVER_PATH", str(entry))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ got = LlamaCppBackend._exec_path_for_launch(str(entry))
+ assert got == str((root / "build" / "bin" / "llama-server").resolve())
+
+ def test_a_pinned_custom_wrapper_is_still_preserved(self, monkeypatch, tmp_path):
+ _root, entry = self._managed_tree(tmp_path, self._CUSTOM)
+ monkeypatch.delenv("UNSLOTH_LLAMA_CPP_PATH", raising = False)
+ monkeypatch.setenv("LLAMA_SERVER_PATH", str(entry))
+ monkeypatch.setattr(sys, "platform", "darwin")
+ assert LlamaCppBackend._exec_path_for_launch(str(entry)) == str(entry)
+
+
+class TestLaunchStopsAtSomebodyElsesWrapper:
+ """The outer entrypoint being ours says nothing about what it points at.
+
+ An installer-shaped entrypoint whose target is a hand-written wrapper had
+ that wrapper stepped over on macOS, so its exports never ran, even though
+ launching the entrypoint directly would have executed them. Resolving for
+ the LIBRARY DIRECTORY still follows the whole chain: that is where the
+ dylibs are, whoever wrote the links.
+ """
+
+ @staticmethod
+ def _tree(tmp_path, inner_body):
+ import json
+
+ root = tmp_path / ".unsloth" / "llama.cpp"
+ (root / "build" / "bin").mkdir(parents = True)
+ (root / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps({"tag": "b9415"}))
+ real = root / "build" / "bin" / "llama-server-real"
+ real.write_bytes(b"\x00\x00\x00\x00")
+ real.chmod(0o755)
+ inner = root / "build" / "bin" / "llama-server"
+ inner.write_text(inner_body)
+ inner.chmod(0o755)
+ outer = root / "llama-server"
+ outer.write_text('#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n')
+ outer.chmod(0o755)
+ return outer, inner, real
+
+ _CUSTOM = (
+ "#!/bin/sh\nexport GGML_METAL_PATH_RESOURCES=/custom\n"
+ 'exec "$(dirname "$0")/llama-server-real" "$@"\n'
+ )
+ _TEMPLATE = '#!/bin/sh\nexec "$(dirname "$0")/llama-server-real" "$@"\n'
+
+ def test_a_custom_inner_wrapper_is_launched_not_skipped(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ outer, inner, real = self._tree(tmp_path, self._CUSTOM)
+ assert LlamaCppBackend._exec_path_for_launch(str(outer)) == str(inner)
+
+ def test_an_all_template_chain_still_resolves_to_the_end(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ outer, inner, real = self._tree(tmp_path, self._TEMPLATE)
+ assert LlamaCppBackend._exec_path_for_launch(str(outer)) == str(real)
+
+ def test_the_library_directory_still_follows_the_whole_chain(self, tmp_path, monkeypatch):
+ """Stopping early for launch must not move the dylib search path."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ outer, inner, real = self._tree(tmp_path, self._CUSTOM)
+ assert llama_module._llama_lib_dir(str(outer)) == real.parent
diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.py
index bdd38d0adf1..4db0e62f73f 100644
--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py
+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py
@@ -884,6 +884,7 @@ def test_probe_server_capabilities_uses_binary_library_env(tmp_path, monkeypatch
"core.inference.llama_cpp.child_env_without_native_path_secret",
lambda: {
"LD_LIBRARY_PATH": "/already-there",
+ "DYLD_LIBRARY_PATH": "/already-inherited",
"LLAMA_ARG_DEVICE": "MTL0",
"LLAMA_ARG_OVERRIDE_TENSOR": ".*=MTL0",
},
@@ -908,9 +909,13 @@ def test_probe_server_capabilities_uses_binary_library_env(tmp_path, monkeypatch
assert captured["env"] is not None
assert captured["env"]["GGML_METAL_DEVICES"] == "0"
assert not any(name.startswith("LLAMA_ARG_") for name in captured["env"])
- ld_dirs = captured["env"]["LD_LIBRARY_PATH"].split(os.pathsep)
- assert str(fake.parent) in ld_dirs
- assert "/already-there" in ld_dirs
+ # macOS: the probe must go on DYLD_LIBRARY_PATH. dyld ignores
+ # LD_LIBRARY_PATH, so putting the dir there left the probe with no search
+ # path (#8566), and an inherited LD_LIBRARY_PATH is left as the user set it.
+ dyld_dirs = captured["env"]["DYLD_LIBRARY_PATH"].split(os.pathsep)
+ assert str(fake.parent) in dyld_dirs
+ assert "/already-inherited" in dyld_dirs
+ assert captured["env"]["LD_LIBRARY_PATH"] == "/already-there"
@_NEEDS_BASH
diff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
index 63bcb726286..625ea642e52 100644
--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py
+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
@@ -12,6 +12,7 @@ generic "invalid file or out of memory" message is misleading (issue
from __future__ import annotations
+import os
import sys
import types as _types
from pathlib import Path
@@ -198,11 +199,16 @@ class TestOsKillReturncode:
stays neutral; a recognized output still wins; a hard fault (-11) keeps the
generic fallback."""
- def test_sigkill_with_no_output_names_oom(self):
+ def test_sigkill_with_no_output_names_oom(self, monkeypatch):
+ # Pin the platform: macOS SIGKILLs an invalid code signature the same
+ # way, so the message there names both readings (see
+ # TestMacOSLoaderFailures) and this wording is the non-Darwin one.
+ monkeypatch.setattr(sys, "platform", "linux")
msg = _classify("", "/models/big-bf16.gguf", "local/big", -9)
assert "signal 9" in msg
assert "out of memory" in msg.lower()
assert ".wslconfig" in msg
+ assert "code signature" not in msg.lower()
assert "GGUF file is valid" not in msg
def test_sigterm_is_neutral_not_oom(self):
@@ -494,3 +500,987 @@ class TestMissingSharedLibrary:
msg = _classify(_QWEN_IMAGE_OUT, "/models/qwen-image.gguf", "local/qwen-image", 127)
assert "Images page" in msg
assert "system library" not in msg
+
+
+# Real dyld output. macOS says none of the things glibc says, so before #8566
+# every one of these fell through to "invalid GGUF or not enough memory" on a
+# Mac that had neither problem. Classification is pure text matching, so these
+# run on any host.
+_DYLD_MISSING_OUT = (
+ "dyld[54231]: Library not loaded: @rpath/libllama.dylib\n"
+ " Referenced from: <A1B2C3D4> /Users/me/.unsloth/studio/llama.cpp/build/bin/llama-server\n"
+ " Reason: tried: '/Users/me/.unsloth/studio/llama.cpp/build/bin/libllama.dylib' "
+ "(no such file), '/usr/local/lib/libllama.dylib' (no such file)"
+)
+_DYLD_OLD_MACOS_OUT = (
+ "dyld: Library not loaded: @rpath/libggml-metal.dylib\n"
+ " Referenced from: /Users/me/.unsloth/studio/llama.cpp/build/bin/llama-server\n"
+ " Reason: image not found"
+)
+_DYLD_SIGNATURE_OUT = (
+ "dyld[54231]: Library not loaded: @rpath/libggml-base.dylib\n"
+ " Reason: tried: '/Users/me/.unsloth/studio/llama.cpp/build/bin/libggml-base.dylib' "
+ "(code signature in <A1B2> '.../libggml-base.dylib' not valid for use in process: "
+ "mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed.)"
+)
+_DYLD_ARCH_OUT = (
+ "dyld[54231]: Library not loaded: @rpath/libmtmd.dylib\n"
+ " Reason: tried: '/Users/me/.unsloth/studio/llama.cpp/build/bin/libmtmd.dylib' "
+ "(mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64'))"
+)
+_DYLD_TOO_NEW_OUT = (
+ "dyld[54231]: Library not loaded: @rpath/libggml-metal.dylib\n"
+ " Reason: tried: '.../libggml-metal.dylib' (built for macOS 26.0 which is "
+ "newer than running OS)"
+)
+_DYLD_SYMBOL_OUT = (
+ "dyld[54231]: Symbol not found: __ZN4ggml7backend6deviceEv\n"
+ " Referenced from: <A1B2> /Users/me/.unsloth/studio/llama.cpp/build/bin/libmtmd.dylib\n"
+ " Expected in: <C3D4> /Users/me/.unsloth/studio/llama.cpp/build/bin/libllama.dylib"
+)
+
+
+def _blames_the_gguf_or_memory(msg: str) -> bool:
+ lowered = msg.lower()
+ return "gguf file is valid" in lowered or "enough memory" in lowered
+
+
+class TestMacOSLoaderFailures:
+ def test_missing_dylib_names_the_library_and_the_installer(self):
+ msg = _classify(_DYLD_MISSING_OUT, "/models/x.gguf", "local/x", 1)
+ assert "libllama.dylib" in msg
+ assert "unsloth studio update" in msg
+ assert not _blames_the_gguf_or_memory(msg)
+
+ def test_old_macos_image_not_found_is_recognised(self):
+ msg = _classify(_DYLD_OLD_MACOS_OUT, "/models/x.gguf", "local/x", 1)
+ assert "libggml-metal.dylib" in msg
+ assert not _blames_the_gguf_or_memory(msg)
+
+ def test_invalid_code_signature_is_not_reported_as_a_bad_file(self):
+ msg = _classify(_DYLD_SIGNATURE_OUT, "/models/x.gguf", "local/x", 1)
+ assert "code signature" in msg.lower()
+ assert not _blames_the_gguf_or_memory(msg)
+
+ def test_wrong_architecture_is_named(self):
+ msg = _classify(_DYLD_ARCH_OUT, "/models/x.gguf", "local/x", 1)
+ assert "architecture" in msg.lower()
+ assert not _blames_the_gguf_or_memory(msg)
+
+ def test_runtime_built_for_a_newer_macos(self):
+ msg = _classify(_DYLD_TOO_NEW_OUT, "/models/x.gguf", "local/x", 1)
+ assert "newer version of macOS" in msg
+ assert not _blames_the_gguf_or_memory(msg)
+
+ def test_mtlresidency_symbol_is_read_as_a_too_new_macos_build(self):
+ # What a Tahoe-built libggml-metal actually reports on macOS 15; the
+ # installer's looks_like_macos_incompatibility keys on the same symbol.
+ out = (
+ "dyld[1]: Symbol not found: _MTLResidencySetDescriptor\n"
+ " Referenced from: .../libggml-metal.dylib"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "newer version of macOS" in msg
+
+ def test_symbol_mismatch_reports_a_mixed_install(self):
+ msg = _classify(_DYLD_SYMBOL_OUT, "/models/x.gguf", "local/x", 1)
+ assert "different build" in msg
+ assert not _blames_the_gguf_or_memory(msg)
+
+ def test_dyld_output_outranks_signal_9(self):
+ # -9 alone reads as the OOM killer; a dyld diagnostic is a fact and
+ # must win, or the user is sent to free memory they already have.
+ msg = _classify(_DYLD_MISSING_OUT, "/models/x.gguf", "local/x", -9)
+ assert "libllama.dylib" in msg
+ assert "out of memory" not in msg.lower()
+
+ def test_custom_binary_is_not_sent_to_the_unsloth_updater(self, monkeypatch):
+ monkeypatch.setenv("LLAMA_SERVER_PATH", "/opt/mybuild/bin/llama-server")
+ msg = _classify(
+ _DYLD_ARCH_OUT, "/models/x.gguf", "local/x", 1, "/opt/mybuild/bin/llama-server"
+ )
+ assert "unsloth studio update" not in msg
+ assert "custom llama.cpp" in msg
+
+ def test_linux_loader_wording_is_untouched(self):
+ # The glibc branch must keep winning; the macOS branch runs after it.
+ out = (
+ "llama-server: error while loading shared libraries: libgomp.so.1: "
+ "cannot open shared object file: No such file or directory"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 127)
+ assert "libgomp.so.1" in msg
+ assert "macOS" not in msg
+
+ def test_silent_signal_9_on_macos_also_names_the_code_signature(self, monkeypatch):
+ # macOS kills an unsigned or altered Mach-O with SIGKILL before it can
+ # print anything, which is indistinguishable from the OOM killer by
+ # returncode alone. Offer both readings there instead of only memory.
+ monkeypatch.setattr(sys, "platform", "darwin")
+ msg = _classify("", "/models/x.gguf", "local/x", -9)
+ assert "code signature" in msg.lower()
+ assert "out of memory" in msg.lower()
+
+ def test_ordinary_output_mentioning_reason_is_not_a_loader_failure(self):
+ out = "llama_model_load: error loading model: Reason: something went wrong"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "llama-server failed to start." in msg
+
+
+class TestStartupDiagnostics:
+ _UNKNOWN_OUT = (
+ "build: 9415 (06d26dfd) with Apple clang version 17.0.0 for arm64-apple-darwin24.6.0\n"
+ "ggml_metal_init: error: failed to allocate buffer\n"
+ "GGML_ASSERT(ctx->device != nil) failed"
+ )
+
+ def test_unknown_failure_carries_the_output_tail(self):
+ msg = _classify(self._UNKNOWN_OUT, "/models/x.gguf", "local/x", 1)
+ assert msg.startswith("llama-server failed to start.")
+ assert "GGML_ASSERT" in msg
+ assert "llama-server output:" in msg
+
+ def test_unknown_failure_carries_the_log_path(self, tmp_path):
+ log = tmp_path / "llama-1-port-8080.log"
+ msg = _classify(self._UNKNOWN_OUT, "/models/x.gguf", "local/x", 1, None, log)
+ assert f"Full log: {log}" in msg
+
+ def test_the_tail_is_bounded(self):
+ out = "x" * 50_000 + "\nfinal line"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "final line" in msg
+ assert len(msg) < 4000
+
+ def test_control_characters_are_stripped(self):
+ out = "loading \x1b[32mmodel\x1b[0m \x00done"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "\x00" not in msg
+ assert "\x1b" not in msg
+ assert "done" in msg
+
+ def test_no_output_and_no_log_keeps_the_old_message_exactly(self):
+ assert _classify("", "/models/x.gguf", "local/x", 1) == (
+ "llama-server failed to start. "
+ "Check that the GGUF file is valid and you have enough memory."
+ )
+
+ def test_a_classified_message_gains_no_diagnostics(self, tmp_path):
+ # Only the unknown fallback carries evidence; the specific messages are
+ # already actionable and must keep their exact text.
+ log = tmp_path / "llama-1-port-8080.log"
+ msg = _classify(_QWEN_IMAGE_OUT, "/models/q.gguf", "local/q", 1, None, log)
+ assert "Images page" in msg
+ assert "Full log" not in msg
+ assert "llama-server output:" not in msg
+
+
+class TestMacOSLoaderEdgeCases:
+ """dyld's real output shape: a mixed "tried:" list, unrelated text above it,
+ and a reason that can run for kilobytes."""
+
+ def test_a_mixed_tried_list_judges_our_own_copy(self, monkeypatch, tmp_path):
+ # An Apple Silicon Mac with a leftover Intel Homebrew tree lists our
+ # missing dylib AND an x86_64 one under /usr/local. Scanning the whole
+ # list would report "wrong CPU architecture" for a file that is simply
+ # absent from our install.
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ binary = tmp_path / "llama.cpp" / "build" / "bin" / "llama-server"
+ binary.parent.mkdir(parents = True)
+ binary.write_text("")
+ out = (
+ "dyld[4210]: Library not loaded: @rpath/libmtmd.dylib\n"
+ f" Reason: tried: '{binary.parent}/libmtmd.dylib' (no such file), "
+ "'/usr/local/lib/libmtmd.dylib' (mach-o file, but is an incompatible "
+ "architecture (have 'x86_64', need 'arm64')), "
+ "'/usr/lib/libmtmd.dylib' (no such file, not in dyld cache)"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1, str(binary))
+ assert "libmtmd.dylib" in msg
+ assert "architecture" not in msg.lower()
+ assert "missing" in msg.lower()
+
+ def test_a_policy_blocked_sibling_does_not_accuse_the_user_of_tampering(
+ self, monkeypatch, tmp_path
+ ):
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ binary = tmp_path / "llama.cpp" / "build" / "bin" / "llama-server"
+ binary.parent.mkdir(parents = True)
+ binary.write_text("")
+ out = (
+ "dyld[4210]: Library not loaded: @rpath/libllama.dylib\n"
+ f" Reason: tried: '{binary.parent}/libllama.dylib' (no such file), "
+ "'/usr/local/lib/libllama.dylib' (code signature not valid for use in "
+ "process: library load disallowed by system policy)"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1, str(binary))
+ assert "code signature" not in msg.lower()
+ assert "was modified" not in msg
+
+ def test_our_own_copy_really_is_the_signature_failure(self, monkeypatch, tmp_path):
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ binary = tmp_path / "llama.cpp" / "build" / "bin" / "llama-server"
+ binary.parent.mkdir(parents = True)
+ binary.write_text("")
+ out = (
+ "dyld[4210]: Library not loaded: @rpath/libllama.dylib\n"
+ f" Reason: tried: '{binary.parent}/libllama.dylib' (code signature in "
+ "<A1B2> not valid for use in process: mapped file has no cdhash)"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1, str(binary))
+ assert "code signature" in msg.lower()
+
+ def test_an_earlier_unrelated_reason_is_not_read_as_dylds(self):
+ # llama.cpp prints its own "Reason:" lines; only the one after the
+ # "Library not loaded:" explains it.
+ out = (
+ "main: loading model\n"
+ "llama_model_load: error loading model: Reason: unknown\n"
+ "ggml_metal_init: skipping device, incompatible architecture\n"
+ "dyld[9]: Library not loaded: @rpath/libggml-base.dylib\n"
+ " Reason: tried: '/x/libggml-base.dylib' (no such file)"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "libggml-base.dylib" in msg
+ assert "architecture" not in msg.lower()
+
+ def test_a_stray_reason_does_not_disable_symbol_classification(self):
+ # A "reason:" anywhere used to swallow the symbol-mismatch branch.
+ out = (
+ "srv load: Reason: retrying\n"
+ "dyld[1]: Symbol not found: __ZN4ggml7backendE\n"
+ " Referenced from: /x/libmtmd.dylib\n"
+ " Expected in: /x/libllama.dylib"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "different build" in msg
+
+ def test_the_classified_reason_is_bounded(self):
+ out = (
+ "dyld[1]: Library not loaded: @rpath/libllama.dylib\n"
+ " Reason: no suitable image found. Did find: " + "x" * 20_000
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "libllama.dylib" in msg
+ assert len(msg) < 1000
+
+ def test_the_health_timeout_marker_is_not_absorbed_into_a_dyld_reason(self):
+ # Studio appends its own marker to the captured output; it must not be
+ # quoted back to the user as part of dyld's diagnosis.
+ out = (
+ "dyld[1]: Library not loaded: @rpath/libllama.dylib\n"
+ " Reason: tried: '/x/libllama.dylib' (no such file)\n"
+ "llama-server health check timed out after 600.0s"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "health check timed out" not in msg
+
+ def test_signal_9_on_macos_respects_a_custom_binary(self, monkeypatch):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setenv("LLAMA_SERVER_PATH", "/opt/mybuild/bin/llama-server")
+ msg = _classify("", "/models/x.gguf", "local/x", -9, "/opt/mybuild/bin/llama-server")
+ assert "unsloth studio update" not in msg
+ assert "custom llama.cpp" in msg
+
+
+class TestDiagnosticsDoNotLeak:
+ """The output tail is llama-server's own stdout, and llama-server inherits
+ nearly all of Studio's environment."""
+
+ _OUT = "build: 9415\nenv dump: OPENAI_API_KEY=sk-owner-secret-1234567890\nabort"
+
+ def test_a_secret_env_value_is_redacted(self, monkeypatch):
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-owner-secret-1234567890")
+ msg = _classify(self._OUT, "/models/x.gguf", "local/x", 1)
+ assert "sk-owner-secret-1234567890" not in msg
+ assert "***" in msg
+
+ def test_a_non_secret_env_value_is_left_alone(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_MODEL_DIR", "/models/mymodels")
+ msg = _classify("loading from /models/mymodels failed", "/models/x.gguf", "local/x", 1)
+ assert "/models/mymodels" in msg
+
+ def test_a_credential_url_is_redacted_whatever_it_is_named(self, monkeypatch):
+ # DATABASE_URL / REDIS_URL match no name marker, so the value has to
+ # carry the verdict: scheme://user:secret@host is a credential.
+ monkeypatch.setenv("DATABASE_URL", "postgres://admin:hunter2secret@db:5432/prod")
+ out = "dump: DATABASE_URL=postgres://admin:hunter2secret@db:5432/prod"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "hunter2secret" not in msg
+
+ def test_a_token_shape_is_redacted_under_an_unremarkable_name(self, monkeypatch):
+ monkeypatch.setenv("GITHUB_PAT", "github_pat_11ABCDEFG0123456789abcdefghij")
+ out = "dump: GITHUB_PAT=github_pat_11ABCDEFG0123456789abcdefghij"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "github_pat_11ABCDEFG0123456789abcdefghij" not in msg
+
+ def test_a_bare_hf_token_shape_is_redacted(self):
+ out = "curl -H 'Authorization: Bearer hf_" + "a" * 34 + "' failed"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "hf_" + "a" * 34 not in msg
+
+ def test_a_huge_unterminated_line_is_cheap(self):
+ # _drain_stdout keeps an unterminated line whole; the tail must be
+ # sliced before it is filtered character by character.
+ import time
+
+ out = "x" * 10_000_000 + "\nggml_metal_init: error"
+ start = time.perf_counter()
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert time.perf_counter() - start < 0.2
+ assert "ggml_metal_init: error" in msg
+
+
+class TestDyldInstallNames:
+ def test_an_rpath_placeholder_is_not_reported_as_a_location(self, monkeypatch):
+ # "@rpath/libfoo.dylib is missing from that exact location" is
+ # unusable advice: @rpath is a search directive, not a directory.
+ monkeypatch.setenv("LLAMA_SERVER_PATH", "/opt/mybuild/bin/llama-server")
+ out = (
+ "dyld[1]: Library not loaded: @rpath/libomp.dylib\n"
+ " Reason: tried: '/opt/mybuild/bin/libomp.dylib' (no such file)"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1, "/opt/mybuild/bin/llama-server")
+ assert "@rpath" not in msg
+ assert "libomp.dylib" in msg
+ assert "that exact location" not in msg
+
+ def test_a_bundled_dylib_behind_rpath_still_points_at_the_installer(self, monkeypatch):
+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)
+ out = (
+ "dyld[1]: Library not loaded: @rpath/libggml-metal.dylib\n"
+ " Reason: tried: '/x/libggml-metal.dylib' (no such file)"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "unsloth studio update" in msg
+
+
+class TestMacOSSymbolProvenance:
+ """Where dyld expected the symbol decides the remedy: reinstalling the same
+ build cannot make the OS export a symbol it does not have."""
+
+ def test_a_system_framework_symbol_reads_as_a_too_new_build(self):
+ out = (
+ "dyld[1]: Symbol not found: _MTLDeviceNewCommandQueueWithDescriptor\n"
+ " Referenced from: /Users/me/.unsloth/llama.cpp/build/bin/libggml-metal.dylib\n"
+ " Expected in: /System/Library/Frameworks/Metal.framework/Versions/A/Metal"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "newer macOS" in msg
+ assert "different build than the llama-server binary" not in msg
+
+ def test_a_llama_dylib_symbol_still_reads_as_a_mixed_install(self):
+ out = (
+ "dyld[1]: Symbol not found: __ZN4ggml7backendE\n"
+ " Referenced from: /Users/me/.unsloth/llama.cpp/build/bin/libmtmd.dylib\n"
+ " Expected in: /Users/me/.unsloth/llama.cpp/build/bin/libllama.dylib"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "different build" in msg
+ assert "newer macOS" not in msg
+
+ def test_a_usr_lib_symbol_is_read_the_same_way_as_a_framework(self):
+ out = (
+ "dyld[1]: Symbol not found: _os_signpost_emit\n"
+ " Expected in: /usr/lib/libSystem.B.dylib"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "newer macOS" in msg
+
+
+class TestCommandLineSecrets:
+ """--api-key is minted per launch with secrets.token_urlsafe(32), so it is
+ in no environment variable and matches no token shape."""
+
+ _KEY = "Xy9_kQ2mLp7RtVw4NbZc8FgHjKdSaEuI0oPqWxYz1A"
+
+ def test_the_api_key_is_redacted_by_its_flag(self):
+ out = f"exec: llama-server -m x.gguf --api-key {self._KEY} --port 8080\nabort"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert self._KEY not in msg
+ assert "--api-key" in msg # the flag stays; only the value goes
+
+ def test_the_equals_form_is_redacted_too(self):
+ out = f"argv: --api-key={self._KEY}"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert self._KEY not in msg
+
+ def test_a_known_secret_is_redacted_wherever_it_appears(self):
+ # Passed by the caller, so it goes even without the flag next to it.
+ out = f"client sent token {self._KEY} and was refused"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1, None, None, (self._KEY,))
+ assert self._KEY not in msg
+
+ def test_no_known_secret_is_harmless(self):
+ msg = _classify("plain failure", "/models/x.gguf", "local/x", 1, None, None, (None,))
+ assert "plain failure" in msg
+
+
+class TestClassifierScoping:
+ """The classifier is pure text and runs on every platform, so a macOS
+ diagnosis needs macOS evidence, not an English phrase."""
+
+ def test_a_bare_symbol_not_found_is_not_a_macos_diagnosis(self):
+ # A Linux wrapper or a plugin loader saying this is not dyld.
+ out = "plugin loader: Symbol not found in module registry\nexiting"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "llama.cpp libraries are from" not in msg
+ assert "llama-server failed to start." in msg
+ assert "plugin loader" in msg # the tail survives instead
+
+ def test_dyld_framing_still_classifies(self):
+ out = (
+ "dyld[1]: Symbol not found: __ZN4ggml7backendE\n"
+ " Expected in: /Users/me/.unsloth/llama.cpp/build/bin/libllama.dylib"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "different build" in msg
+
+
+class TestNestedDyldPlaceholders:
+ def test_a_nested_placeholder_is_reduced_to_the_library_name(self, monkeypatch):
+ monkeypatch.setenv("LLAMA_SERVER_PATH", "/opt/mybuild/bin/llama-server")
+ out = (
+ "dyld[1]: Library not loaded: @loader_path/../Frameworks/libomp.dylib\n"
+ " Reason: tried: '/opt/mybuild/Frameworks/libomp.dylib' (no such file)"
+ )
+ msg = _classify(out, "/models/x.gguf", "local/x", 1, "/opt/mybuild/bin/llama-server")
+ assert "libomp.dylib" in msg
+ assert "@loader_path" not in msg
+ assert "../Frameworks" not in msg
+ assert "that exact location" not in msg
+
+
+class TestShortSecrets:
+ def test_a_short_password_is_redacted_beside_its_name(self, monkeypatch):
+ monkeypatch.setenv("DATABASE_PASSWORD", "hunter2")
+ out = "env dump: DATABASE_PASSWORD=hunter2 PORT=8080"
+ msg = _classify(out, "/models/x.gguf", "local/x", 1)
+ assert "hunter2" not in msg
+ assert "PORT=8080" in msg # non-secret short values are untouched
+
+ def test_a_short_non_secret_value_is_not_replaced_globally(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_PORT", "8080")
+ msg = _classify("bound 8080 then failed", "/models/x.gguf", "local/x", 1)
+ assert "8080" in msg
+
+
+class TestDiagnosticsAreAFixedPoint:
+ """Decorating an already-decorated message must be a no-op.
+
+ Only one call site exists today, so none of this can fire yet. It is pinned
+ because the failure mode is silent: a second caller would double the tail
+ and the log line, and nothing else would notice.
+ """
+
+ _OUT = "some unrecognised startup noise"
+ _LOG = "/Users/me/.unsloth/studio/logs/llama-server/llama-1-port-8080.log"
+
+ def test_appending_twice_adds_nothing(self):
+ once = LlamaCppBackend._with_startup_diagnostics("base", self._OUT, self._LOG)
+ assert once.count("llama-server output:") == 1
+ assert once.count("Full log: ") == 1
+ assert LlamaCppBackend._with_startup_diagnostics(once, self._OUT, self._LOG) == once
+
+ def test_a_classified_message_fed_back_in_is_not_decorated_twice(self):
+ once = _classify(self._OUT, "/models/x.gguf", "local/x", 1, None, log_path = self._LOG)
+ twice = LlamaCppBackend._with_startup_diagnostics(once, self._OUT, self._LOG)
+ assert twice == once
+
+ def test_a_tail_that_merely_mentions_the_label_is_still_decorated(self):
+ # The guard keys on our own two-newline framing, so a server that
+ # printed the words itself does not suppress the diagnostics.
+ out = "llama-server output: 3 tokens/s\nthen it died"
+ msg = LlamaCppBackend._with_startup_diagnostics("base", out, None)
+ assert msg.startswith("base\n\nllama-server output:\n")
+
+
+class TestTheDyldReasonIsBounded:
+ def test_a_pathological_reason_does_not_stall_the_classifier(self):
+ # 100KB of "'a' (" drove the candidate scan quadratic: 6.3s measured
+ # before the cap, against 0.0s on main, on the thread serving the load.
+ import time
+
+ out = (
+ "dyld[1]: Library not loaded: @rpath/libllama.dylib\n"
+ " Reason: tried: " + "'a' (" * 20000
+ )
+ start = time.perf_counter()
+ msg = _classify(
+ out,
+ "/models/x.gguf",
+ "local/x",
+ 1,
+ "/Users/me/.unsloth/llama.cpp/build/bin/llama-server",
+ )
+ assert time.perf_counter() - start < 1.0
+ assert "libllama.dylib" in msg
+
+ def test_a_real_reason_is_not_truncated(self):
+ out = (
+ "dyld[1]: Library not loaded: @rpath/libggml-base.dylib\n"
+ " Reason: tried: '/Users/me/.unsloth/llama.cpp/build/bin/libggml-base.dylib' "
+ "(mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64'))"
+ )
+ msg = _classify(
+ out,
+ "/models/x.gguf",
+ "local/x",
+ 1,
+ "/Users/me/.unsloth/llama.cpp/build/bin/llama-server",
+ )
+ assert "architecture" in msg
+
+
+class TestOnlyDyldsOwnOutputIsReadAsDyld:
+ """llama.cpp echoes GGUF metadata while loading.
+
+ A model whose general.name contains "Library not loaded:" or "Symbol not
+ found" put those words in llama-server's stderr, and every case below was
+ answered with library advice instead of the classification it had before.
+ Two of them outranked branches that were already correct.
+ """
+
+ _BIN = "/Users/me/.unsloth/llama.cpp/build/bin/llama-server"
+
+ def test_metadata_does_not_beat_the_tensor_parallel_branch(self):
+ out = (
+ "llama_model_loader: - kv 2: general.name str = Symbol not found: MTLResidency\n"
+ "split_mode_tensor not implemented"
+ )
+ assert "Tensor parallelism" in _classify(out, "/m.gguf", "u/x", 1, self._BIN)
+
+ def test_metadata_does_not_beat_the_diffusion_branch(self):
+ out = (
+ "llama_model_loader: - kv 2: general.name str = Library not loaded: libfake.so\n"
+ "llama_model_load: error loading model architecture: "
+ "unknown model architecture: 'qwen_image'"
+ )
+ assert "diffusion" in _classify(out, "/m.gguf", "u/x", 1, self._BIN)
+
+ def test_metadata_does_not_beat_status_127(self):
+ msg = _classify(
+ "wrapper says Library not loaded: libx.so", "/m.gguf", "u/x", 127, self._BIN
+ )
+ assert "status 127" in msg
+
+ def test_metadata_does_not_beat_signal_15(self):
+ msg = _classify(
+ "wrapper says Library not loaded: libx.so", "/m.gguf", "u/x", -15, self._BIN
+ )
+ assert "signal 15" in msg
+
+ def test_metadata_does_not_claim_a_too_new_macos(self):
+ out = (
+ "llama_model_loader: - kv 9: general.description str = "
+ "built for macOS 26.0 which is newer than running OS"
+ )
+ msg = _classify(out, "/m.gguf", "u/x", 1, self._BIN)
+ assert "newer version of macOS" not in msg
+
+ def test_real_dyld_framing_still_classifies(self):
+ out = (
+ "dyld[4321]: Library not loaded: @rpath/libllama.dylib\n"
+ " Referenced from: <A> /Users/me/.unsloth/llama.cpp/build/bin/llama-server\n"
+ " Reason: tried: '/Users/me/.unsloth/llama.cpp/build/bin/libllama.dylib' (no such file)\n"
+ )
+ assert "libllama.dylib" in _classify(out, "/m.gguf", "u/x", 1, self._BIN)
+
+ def test_the_older_bare_dyld_prefix_is_framing_too(self):
+ out = "dyld: Library not loaded: @rpath/libllama.dylib\n Reason: image not found\n"
+ assert "libllama.dylib" in _classify(out, "/m.gguf", "u/x", 1, self._BIN)
+
+
+class TestArchitectureAndQuotedPaths:
+ _BIN = "/Users/me/.unsloth/llama.cpp/build/bin/llama-server"
+
+ def test_a_quoted_system_framework_reads_as_a_too_new_build(self):
+ out = (
+ "dyld[5]: Symbol not found: _MTLFoo\n"
+ " Referenced from: <A> /Users/me/.unsloth/llama.cpp/build/bin/llama-server\n"
+ " Expected in: '/System/Library/Frameworks/Metal.framework/Versions/A/Metal'\n"
+ )
+ msg = _classify(out, "/m.gguf", "u/x", 1, self._BIN)
+ assert "newer macOS" in msg
+ assert "different build" not in msg
+
+ def test_the_older_wrong_architecture_wording_is_recognised(self):
+ out = (
+ "dyld[5]: Library not loaded: @rpath/libggml.dylib\n"
+ " Reason: tried: '/Users/me/.unsloth/llama.cpp/build/bin/libggml.dylib' "
+ "(mach-o, but wrong architecture)\n"
+ )
+ assert "different CPU architecture" in _classify(out, "/m.gguf", "u/x", 1, self._BIN)
+
+ def test_bad_cpu_type_never_reaches_dyld_and_is_still_named(self):
+ out = "/bin/sh: /Users/me/.unsloth/llama.cpp/build/bin/llama-server: Bad CPU type in executable"
+ msg = _classify(out, "/m.gguf", "u/x", 126, self._BIN)
+ assert "different CPU architecture" in msg
+ assert "GGUF file is valid" not in msg
+
+ def test_a_linux_exec_failure_is_not_read_as_a_mac_one(self):
+ out = "bash: /opt/x/llama-server: cannot execute binary file: Exec format error"
+ msg = _classify(out, "/m.gguf", "u/x", 126, "/opt/x/llama-server")
+ assert "this Mac" not in msg
+
+
+class TestHttpCredentialsInTheTail:
+ def test_a_basic_credential_is_redacted(self):
+ msg = _classify("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "/m.gguf", "u/x", 1)
+ assert "QWxhZGRpbg" not in msg
+
+ def test_a_bearer_token_is_redacted_including_its_base64_tail(self):
+ msg = _classify("Authorization: Bearer QUFB+U0VDUkVUL1RBSUw=", "/m.gguf", "u/x", 1)
+ assert "U0VDUkVU" not in msg
+
+
+class TestOutputIsNeverTrustedForBeingOurOwnFraming:
+ """Child stdout gets the full treatment however it is worded.
+
+ An earlier revision short-circuited when the OUTPUT carried our framing, to
+ keep re-classification a fixed point. That handed a wrapper the whole error
+ message: printing "llama-server output:" as its first line returned its
+ stdout verbatim, past the redaction and past the 2000-character cap. The
+ fixed point was for a caller that does not exist; the bypass was reachable
+ by anything Studio launches.
+ """
+
+ _LOG = "/Users/me/.unsloth/studio/logs/llama-server/llama-1-port-8080.log"
+
+ @pytest.mark.parametrize(
+ "prefix",
+ [
+ "llama-server output:\n",
+ "Full log: /wherever\n",
+ "starting\n\nllama-server output:\n",
+ "starting\n\nFull log: /wherever\n",
+ ],
+ )
+ def test_output_wearing_our_heading_is_still_capped_and_scrubbed(self, prefix, monkeypatch):
+ monkeypatch.setenv("MY_API_TOKEN", "sk-super-secret-value-1234567890")
+ out = prefix + "MY_API_TOKEN=sk-super-secret-value-1234567890\n" + "X" * 50000
+ msg = _classify(out, "/m.gguf", "u/x", 1, None, log_path = self._LOG)
+ assert "sk-super-secret-value-1234567890" not in msg
+ assert len(msg) < 3000, len(msg)
+ assert msg != out
+ # The log path is the whole point of the fallback, and the bypass
+ # dropped it along with everything else.
+ assert self._LOG in msg
+
+ def test_repeated_passes_stay_bounded_by_the_tail_cap(self):
+ # Re-classifying a result is not a fixed point: each pass wraps the
+ # previous message in a fresh tail, growing ~136 characters at a time.
+ # Bounded is the property that matters, and the cap supplies it.
+ cur = "some unrecognised startup noise"
+ seen = []
+ for _ in range(60):
+ cur = _classify(cur, "/m.gguf", "u/x", 1, None, log_path = self._LOG)
+ seen.append(len(cur))
+ assert max(seen) < 3000, max(seen)
+ assert seen[-1] == seen[-2], seen[-4:]
+
+ def test_real_output_that_merely_says_the_words_is_still_classified(self):
+ out = "llama-server output: 3 t/s\nerror while loading shared libraries: libgomp.so.1: cannot open shared object file"
+ msg = _classify(out, "/m.gguf", "u/x", 1)
+ assert "libgomp.so.1" in msg
+
+ def test_a_dyld_diagnosis_survives_the_heading(self):
+ out = (
+ "llama-server output:\n"
+ "dyld[1]: Library not loaded: @rpath/libllama.dylib\n"
+ " Reason: tried: '/a/libllama.dylib' (no such file)\n"
+ )
+ binary = "/Users/me/.unsloth/llama.cpp/build/bin/llama-server"
+ assert "libllama.dylib" in _classify(out, "/m.gguf", "u/x", 1, binary)
+
+
+class TestAnEncodedSecretIsStillRedacted:
+ """Redacting on the value alone only works if the child prints it verbatim.
+
+ A wrapper that dumps its environment as JSON prints pa"ss\\word as
+ pa\\"ss\\\\word. That is a different string, so the literal replacement
+ missed it and the credential reached the API error fully reconstructible.
+ Redacting whatever sits beside a secret-looking NAME does not care how the
+ value was encoded.
+ """
+
+ SECRET = 'pa"ss\\word-12345'
+
+ @pytest.fixture(autouse = True)
+ def _env(self, monkeypatch):
+ monkeypatch.setenv("DB_PASSWORD", self.SECRET)
+ monkeypatch.setenv("MY_API_TOKEN", "sk-abcdefghijklmnopqrstuvwxyz")
+
+ @pytest.mark.parametrize(
+ "dump",
+ [
+ '{"DB_PASSWORD": "pa\\"ss\\\\word-12345"}', # JSON escaped
+ 'DB_PASSWORD=pa"ss\\word-12345', # bare
+ "DB_PASSWORD='pa\"ss\\word-12345'", # shell quoted
+ 'DB_PASSWORD: pa"ss\\word-12345', # yaml-ish
+ "DB_PASSWORD=pa%22ss%5Cword-12345", # url encoded
+ "DB_PASSWORD=secret123456,PORT=8080", # one of several pairs
+ ],
+ )
+ def test_no_recognisable_fragment_survives(self, dump):
+ msg = _classify(dump, "/m.gguf", "u/x", 1, None, log_path = "/tmp/l.log")
+ for fragment in ("ss\\word", "pa%22", "secret123456", 'pa\\"ss'):
+ assert fragment not in msg, msg
+ assert "***" in msg
+
+ def test_a_value_we_never_set_is_redacted_by_its_name(self):
+ """The point of the name pass: we cannot match a value we never saw."""
+ msg = _classify('{"DB_PASSWORD": "never-set-98765"}', "/m.gguf", "u/x", 1)
+ assert "never-set-98765" not in msg
+
+ @pytest.mark.parametrize(
+ "line",
+ [
+ "PATH=/usr/bin:/bin",
+ '{"port": 8080}',
+ "model_path=/models/x.gguf",
+ "n_ctx: 4096",
+ "load time = 1234.5 ms",
+ "llama_model_loader: n_layers = 32",
+ ],
+ )
+ def test_ordinary_llama_cpp_output_is_not_redacted(self, line):
+ """Over-redaction would destroy the diagnostics this PR exists to add."""
+ assert "***" not in _classify(line, "/m.gguf", "u/x", 1)
+
+ @pytest.mark.parametrize(
+ "blob",
+ [
+ '"A' + '\\"' * 20000 + 'B"',
+ "K=" + "x" * 100000,
+ "A=1," * 25000,
+ 'TOKEN="' + "y" * 100000,
+ ],
+ )
+ def test_the_name_pass_stays_linear(self, blob):
+ """No nested quantifier: a crafted line must not be able to stall it."""
+ import time
+
+ start = time.monotonic()
+ _classify(blob, "/m.gguf", "u/x", 1)
+ assert time.monotonic() - start < 2.0
+
+
+class TestQuotedShortSecrets:
+ """A short secret survived quoting.
+
+ The name-adjacent rule for values under eight characters matched only the
+ bare NAME=value form, so a wrapper dumping its environment as shell-ish or
+ JSON put the credential straight into the startup-output tail.
+ """
+
+ @pytest.mark.parametrize(
+ "dump",
+ [
+ "env dump: DB_PASSWORD=hunter2 PORT=8080",
+ "env dump: DB_PASSWORD='hunter2'",
+ 'env dump: DB_PASSWORD="hunter2"',
+ '{"DB_PASSWORD": "hunter2", "port": 8080}',
+ "DB_PASSWORD: hunter2",
+ " 'DB_PASSWORD' => 'hunter2'".replace(" => ", ": "),
+ ],
+ )
+ def test_the_value_never_reaches_the_message(self, monkeypatch, dump):
+ monkeypatch.setenv("DB_PASSWORD", "hunter2")
+ assert "hunter2" not in _classify(dump, "/m.gguf", "u/x", 1)
+
+ def test_a_non_secret_short_value_is_still_untouched(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_PORT", "8080")
+ assert "8080" in _classify('{"UNSLOTH_PORT": "8080"}', "/m.gguf", "u/x", 1)
+
+
+class TestASecretLongerThanTheTailWindow:
+ """The pre-slice window cut long credentials in half.
+
+ _scrub_secret_values matches a whole value, so a secret longer than the
+ 8000-character prefilter lost its head to the slice and the surviving
+ suffix matched neither the literal nor any token shape. A secret SHORTER
+ than the window cannot straddle it: if its end is inside a window wider
+ than the secret, so is its start.
+ """
+
+ def test_a_long_key_does_not_reach_the_message(self, monkeypatch):
+ secret = "A" * 12000 + "TAILMARKER"
+ monkeypatch.setenv("MY_PRIVATE_KEY", secret)
+ out = "noise " * 100 + "dump: MY_PRIVATE_KEY=" + secret + "\nfatal: boom"
+ msg = _classify(out, "/m.gguf", "u/x", 1)
+ assert "TAILMARKER" not in msg
+ assert "AAAA" not in msg
+
+ def test_a_long_minted_api_key_does_not_reach_the_message(self, monkeypatch):
+ key = "k" * 9000 + "MINTEDMARK"
+ out = "x" * 5000 + " --api-key " + key + "\nfatal: boom"
+ msg = _classify(out, "/m.gguf", "u/x", 1, None, secrets = (key,))
+ assert "MINTEDMARK" not in msg
+
+ def test_the_tail_is_still_bounded(self, monkeypatch):
+ monkeypatch.setenv("MY_PRIVATE_KEY", "A" * 12000)
+ msg = _classify("z" * 400000 + "\nfatal: boom", "/m.gguf", "u/x", 1)
+ assert len(msg) < 4000
+
+ def test_no_secret_means_the_window_is_unchanged(self, monkeypatch):
+ for name in list(os.environ):
+ if "SECRET" in name or "PRIVATE" in name or "PASSWORD" in name:
+ monkeypatch.delenv(name, raising = False)
+ assert LlamaCppBackend._max_secret_len(()) >= 0
+
+
+class TestTheLibraryNameIsBounded:
+ """The install name is quoted from untrusted output into an HTTP error.
+
+ A real dyld install name is a path, and macOS PATH_MAX is 1024, but nothing
+ stopped a wrapper from printing a longer one: a 200000-character input
+ produced a 100000-character API response.
+ """
+
+ def test_an_absurd_install_name_is_truncated(self):
+ huge = "lib" + "A" * 100000 + ".dylib"
+ out = (
+ f"dyld[9]: Library not loaded: @rpath/{huge}\n"
+ f" Reason: tried: '/a/{huge}' (no such file)\n"
+ )
+ msg = _classify(out, "/m.gguf", "u/x", 1, "/i/bin/llama-server")
+ assert len(msg) < 4000, len(msg)
+ assert "..." in msg
+
+ def test_a_real_install_name_is_untouched(self):
+ out = (
+ "dyld[9]: Library not loaded: @rpath/libllama.dylib\n"
+ " Reason: tried: '/a/libllama.dylib' (no such file)\n"
+ )
+ msg = _classify(out, "/m.gguf", "u/x", 1, "/i/bin/llama-server")
+ assert "libllama.dylib" in msg
+ assert "..." not in msg
+
+
+class TestEveryClassifiedBranchIsRedacted:
+ """Redaction covered the tail only, so the other branches leaked.
+
+ A dyld message names the library it could not load, and that name comes
+ from the child. A credential appearing there went out in the API error
+ while the same credential in the startup-output tail was starred out.
+ """
+
+ def test_a_secret_in_a_dyld_library_name_is_redacted(self, monkeypatch):
+ token = "sk-supersecret-abcdefghijk"
+ monkeypatch.setenv("MY_API_TOKEN", token)
+ out = (
+ f"dyld[1]: Library not loaded: @rpath/{token}.dylib\n"
+ f" Reason: tried: '/a/{token}.dylib' (no such file)\n"
+ )
+ msg = _classify(
+ out, "/m.gguf", "u/x", 1, "/i/bin/llama-server", log_path = "/l.log", secrets = (token,)
+ )
+ assert token not in msg
+ assert "***" in msg
+
+ def test_a_per_launch_secret_is_redacted_in_a_classified_branch(self):
+ minted = "unsloth-launch-key-abcdefghij"
+ out = f"dyld[1]: Library not loaded: @rpath/{minted}.dylib\n"
+ msg = _classify(out, "/m.gguf", "u/x", 1, "/i/bin/llama-server", secrets = (minted,))
+ assert minted not in msg
+
+ def test_an_ordinary_diagnosis_is_unchanged_by_the_extra_pass(self):
+ out = (
+ "dyld[1]: Library not loaded: @rpath/libllama.dylib\n"
+ " Reason: tried: '/a/libllama.dylib' (no such file)\n"
+ )
+ msg = _classify(out, "/m.gguf", "u/x", 1, "/i/bin/llama-server")
+ assert "libllama.dylib" in msg
+ assert "***" not in msg
+
+
+class TestAQuotedValueEndsOnItsOwnDelimiter:
+ """A JSON value may contain an apostrophe, and a shell one a quote.
+
+ Rejecting both quote characters inside the value made the quoted arm fail,
+ so the bare arm took over and stopped at the first whitespace, leaving the
+ rest of the credential standing in the API error.
+ """
+
+ @pytest.mark.parametrize(
+ "dump,leak",
+ [
+ ('{"DB_PASSWORD": "prefix\' supersecret"}', "supersecret"),
+ ("{'DB_PASSWORD': 'has \" quote inside'}", "quote inside"),
+ ('{"DB_PASSWORD": "trailing \'"}', "trailing"),
+ ],
+ )
+ def test_the_whole_quoted_value_is_replaced(self, dump, leak):
+ cleaned = LlamaCppBackend._scrub_secret_values(dump, ())
+ assert leak not in cleaned, cleaned
+ assert "***" in cleaned
+
+
+class TestTheRedactionHolesCodexFound:
+ """Three ways a credential got past the name pass.
+
+ Each was reachable by a wrapper or crash handler printing its own
+ configuration rather than the environment we could match on.
+ """
+
+ @pytest.mark.parametrize(
+ "dump",
+ [
+ 'DB_PASSWORD="prefix supersecret', # truncated output
+ "DB_PASSWORD='prefix supersecret",
+ 'DB_PASSWORD="prefix supersecret\nnext=1', # runs to end of line only
+ ],
+ )
+ def test_an_unterminated_quoted_value_is_redacted_to_the_line_end(self, dump):
+ cleaned = LlamaCppBackend._scrub_secret_values(dump, ())
+ assert "supersecret" not in cleaned, cleaned
+ if "\n" in dump:
+ assert "next=1" in cleaned, "only the value's line should be consumed"
+
+ @pytest.mark.parametrize(
+ "dump,secret",
+ [
+ ('{"api-key": "abc123def456"}', "abc123def456"),
+ ('{"db-password": "correct horse"}', "correct horse"),
+ ("client.secret: hunter2value", "hunter2value"),
+ ('{"private-key": "MIIEvQIBADAN"}', "MIIEvQIBADAN"),
+ ("auth.token = deadbeefcafe", "deadbeefcafe"),
+ ],
+ )
+ def test_a_config_style_key_is_recognised(self, dump, secret):
+ """Hyphens and dots spell the same names the predicate underscores."""
+ assert secret not in LlamaCppBackend._scrub_secret_values(dump, ())
+
+ @pytest.mark.parametrize(
+ "line",
+ [
+ "model-path=/models/x.gguf",
+ "ggml.backend: metal",
+ "n-gpu-layers=99",
+ "cache.type-k: q8_0",
+ "llama_model_loader: n_layers = 32",
+ "load time = 1234.5 ms",
+ ],
+ )
+ def test_a_widened_name_does_not_redact_ordinary_output(self, line):
+ assert "***" not in LlamaCppBackend._scrub_secret_values(line, ())
+
+ @pytest.mark.parametrize(
+ "order", [("abcdefgh", "abcdefgh VERYSECRET"), ("abcdefgh VERYSECRET", "abcdefgh")]
+ )
+ def test_overlapping_secrets_are_replaced_longest_first(self, order):
+ """The short one first rewrote the long one so it no longer matched."""
+ text = "child printed abcdefgh VERYSECRET plainly"
+ cleaned = LlamaCppBackend._scrub_secret_values(text, order)
+ assert "VERYSECRET" not in cleaned, cleaned
+
+ @pytest.mark.parametrize(
+ "blob",
+ ['TOKEN="' + "y" * 100000, "a.b.c.d=" * 12000, "A=1," * 25000],
+ )
+ def test_the_widened_pattern_stays_linear(self, blob):
+ import time
+
+ start = time.monotonic()
+ LlamaCppBackend._scrub_secret_values(blob, ())
+ assert time.monotonic() - start < 2.0
diff --git a/studio/backend/tests/test_rag_embed_llama_server.py b/studio/backend/tests/test_rag_embed_llama_server.py
index 0e8fe1f368f..cf9fd4a07f4 100644
--- a/studio/backend/tests/test_rag_embed_llama_server.py
+++ b/studio/backend/tests/test_rag_embed_llama_server.py
@@ -6,6 +6,7 @@
import subprocess
import sys
import textwrap
+import types
from pathlib import Path
import numpy as np
@@ -153,6 +154,68 @@ def test_build_env_gpu_inherits_devices(monkeypatch):
assert env.get("CUDA_VISIBLE_DEVICES") == "0,1" # inherit Unsloth's selection
+def test_build_env_gpu_on_macos_uses_the_dyld_search_path(monkeypatch, tmp_path):
+ # dyld ignores LD_LIBRARY_PATH, and Apple Silicon is routed through the
+ # use_gpu branch, so the embedding server needs the same treatment the chat
+ # server got in #8566.
+ import os
+ import sys as _sys
+
+ monkeypatch.setattr(_sys, "platform", "darwin")
+ monkeypatch.setenv("DYLD_LIBRARY_PATH", "/opt/inherited")
+ # Pin an inherited value rather than asserting the key is absent: the child
+ # env is a copy of os.environ, so an ambient LD_LIBRARY_PATH would be there
+ # whatever this branch does. What matters is that it is left alone.
+ monkeypatch.setenv("LD_LIBRARY_PATH", "/opt/sentinel")
+ # A host-native directory, not a POSIX literal: _llama_lib_dir resolves the
+ # path, and this test simulates darwin on whatever host runs it, so on a
+ # Windows runner "/opt/llama/bin" comes back drive-anchored as "D:\opt\...".
+ bin_dir = tmp_path / "llama" / "bin"
+ bin_dir.mkdir(parents = True)
+ (bin_dir / "llama-server").write_bytes(b"\xcf\xfa\xed\xfe")
+ b = LlamaServerBackend()
+ env = b._build_env(str(bin_dir / "llama-server"), use_gpu = True)
+ entries = env["DYLD_LIBRARY_PATH"].split(os.pathsep)
+ assert entries == [str(bin_dir), "/opt/inherited"]
+ assert env["LD_LIBRARY_PATH"] == "/opt/sentinel"
+
+
+def test_build_env_cpu_on_macos_still_gets_the_dyld_search_path(monkeypatch, tmp_path):
+ # EMBED_DEVICE=cpu, and the CPU retry after a failed GPU start, load the
+ # same sibling dylibs; the loader path cannot be gated on use_gpu.
+ import os
+ import sys as _sys
+
+ monkeypatch.setattr(_sys, "platform", "darwin")
+ monkeypatch.delenv("DYLD_LIBRARY_PATH", raising = False)
+ # Host-native, for the same reason as the GPU case above.
+ bin_dir = tmp_path / "llama" / "bin"
+ bin_dir.mkdir(parents = True)
+ (bin_dir / "llama-server").write_bytes(b"\xcf\xfa\xed\xfe")
+ b = LlamaServerBackend()
+ env = b._build_env(str(bin_dir / "llama-server"), use_gpu = False)
+ assert env["DYLD_LIBRARY_PATH"].split(os.pathsep)[0] == str(bin_dir)
+ assert env["CUDA_VISIBLE_DEVICES"] == ""
+
+
+def test_build_env_resolves_a_wrapper_entrypoint(monkeypatch, tmp_path):
+ # The managed install puts an entrypoint in front of the real server; the
+ # dylibs sit next to the target, not next to the wrapper.
+ import os
+ import sys as _sys
+
+ real_dir = tmp_path / "llama.cpp" / "build" / "bin"
+ real_dir.mkdir(parents = True)
+ (real_dir / "llama-server").write_text("")
+ wrapper = tmp_path / "llama.cpp" / "llama-server"
+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n')
+ monkeypatch.setattr(_sys, "platform", "darwin")
+ monkeypatch.delenv("DYLD_LIBRARY_PATH", raising = False)
+ b = LlamaServerBackend()
+ env = b._build_env(str(wrapper), use_gpu = True)
+ assert env["DYLD_LIBRARY_PATH"].split(os.pathsep)[0] == str(real_dir)
+
+
def test_use_gpu_explicit_modes(monkeypatch):
b = LlamaServerBackend()
monkeypatch.setattr(config, "EMBED_DEVICE", "gpu")
@@ -453,3 +516,58 @@ def test_post_restarts_once_on_read_timeout(monkeypatch):
out = b._post("/v1/embeddings", {"input": ["x"]})
assert out["data"][0]["embedding"] == [1.0, 0.0]
assert restarts["n"] == 1 # timeout self-heals like a transport error
+
+
+class TestTheEmbeddingLoaderChangesAreMacOsOnly:
+ """The RAG server's Linux and Windows launches must be as they were.
+
+ The probe environment and the resolved library directory both started out
+ unconditional, which moved the first LD_LIBRARY_PATH entry for every Linux
+ GPU install whose llama-server is a symlink, and gave the capability probe
+ an environment it never had.
+ """
+
+ def test_the_help_probe_still_inherits_the_environment_off_mac(self, monkeypatch):
+ seen = {}
+
+ def fake_run(cmd, **kwargs):
+ seen.update(kwargs)
+ return types.SimpleNamespace(stdout = "--embedding", stderr = "")
+
+ monkeypatch.setattr(mod.sys, "platform", "linux")
+ monkeypatch.setattr(mod.subprocess, "run", fake_run)
+ mod.LlamaServerBackend._help_text.cache_clear()
+ mod.LlamaServerBackend._help_text("/opt/mine/llama-server")
+ assert seen.get("env") is None
+
+ def test_the_help_probe_gets_the_loader_environment_on_mac(self, monkeypatch, tmp_path):
+ binary = tmp_path / "llama-server"
+ binary.write_bytes(b"\xcf\xfa\xed\xfe")
+ seen = {}
+
+ def fake_run(cmd, **kwargs):
+ seen.update(kwargs)
+ return types.SimpleNamespace(stdout = "--embedding", stderr = "")
+
+ monkeypatch.setattr(mod.sys, "platform", "darwin")
+ monkeypatch.setattr(mod.subprocess, "run", fake_run)
+ mod.LlamaServerBackend._help_text.cache_clear()
+ mod.LlamaServerBackend._help_text(str(binary))
+ assert seen.get("env") is not None
+
+ def test_linux_gpu_libs_still_hang_off_the_given_path(self, monkeypatch, tmp_path):
+ real = tmp_path / "build" / "bin" / "llama-server"
+ real.parent.mkdir(parents = True)
+ real.write_bytes(b"\xcf\xfa\xed\xfe")
+ wrapper = tmp_path / "llama-server"
+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n')
+ wrapper.chmod(0o755)
+ seen = {}
+ monkeypatch.setattr(mod.sys, "platform", "linux")
+ monkeypatch.setattr(
+ mod.LlamaServerBackend,
+ "_add_linux_cuda_libs",
+ staticmethod(lambda env, d: seen.setdefault("dir", d)),
+ )
+ mod.LlamaServerBackend()._build_env(str(wrapper), use_gpu = True)
+ assert seen["dir"] == str(wrapper.parent)
diff --git a/studio/backend/tests/test_unsupported_hint_reads_only_our_diagnosis.py b/studio/backend/tests/test_unsupported_hint_reads_only_our_diagnosis.py
new file mode 100644
index 00000000000..907a6d813b8
--- /dev/null
+++ b/studio/backend/tests/test_unsupported_hint_reads_only_our_diagnosis.py
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The "not supported yet" rewrite must not read the child's own output.
+
+A llama-server failure now carries a tail of the child's stdout. The route
+scans the whole error string for phrases like "does not support", so once that
+tail was attached, any llama.cpp line containing one of them rewrote the
+diagnosis to "This model is not supported yet. Try a different model." -- for a
+failure that had nothing to do with the checkpoint. llama.cpp really does print
+such lines, for instance when a Vulkan device lacks 16-bit storage, so this was
+reachable on Linux and Windows as much as on macOS.
+
+The evidence still reaches the user; it just no longer votes on the diagnosis.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from core.inference.llama_cpp import LlamaCppBackend
+from routes.inference import (
+ _diagnosis_text,
+ _is_unsupported_nvfp4_inference_error,
+ _maybe_unsupported_message,
+)
+
+REWRITE = "This model is not supported yet"
+
+
+def _failure_carrying(child_output: str) -> str:
+ """The API error for a llama-server death whose output is ``child_output``."""
+ return LlamaCppBackend._classify_llama_start_failure(
+ child_output,
+ "/m.gguf",
+ "u/x",
+ 1,
+ None,
+ "/tmp/llama-1-port-8080.log",
+ (),
+ )
+
+
+ "child_line",
+ [
+ "ggml_vulkan: device Intel(R) UHD does not support 16-bit storage",
+ "vulkan: this device is not supported by the build",
+ "loader: No config file found in the model directory",
+ "warning: flash attention is not yet supported on this backend",
+ ],
+)
+def test_a_phrase_in_the_childs_output_does_not_rewrite_the_diagnosis(child_line):
+ msg = _failure_carrying(child_line + "\nabort\n")
+ assert child_line in msg, "the tail should still be shown to the user"
+ assert not _maybe_unsupported_message(msg).startswith(REWRITE)
+
+
+def test_the_same_phrase_in_our_own_text_still_rewrites():
+ ours = "Model architecture 'foo' is not supported by this llama.cpp build."
+ assert _maybe_unsupported_message(ours).startswith(REWRITE)
+
+
+def test_our_text_still_rewrites_even_when_a_tail_is_attached():
+ ours = "Model architecture 'foo' is not supported by this llama.cpp build."
+ withtail = ours + "\n\nllama-server output:\nnoise\n\nFull log: /tmp/l.log"
+ out = _maybe_unsupported_message(withtail)
+ assert out.startswith(REWRITE)
+ # The rewrite quotes the whole original, evidence included.
+ assert "llama-server output:" in out and "Full log:" in out
+
+
+def test_the_nvfp4_matcher_also_ignores_the_tail():
+ ours = "NVFP4 checkpoint with per-module MLX quantization metadata"
+ assert _is_unsupported_nvfp4_inference_error(ours)
+ tail = (
+ "llama-server failed to start.\n\nllama-server output:\n"
+ "nvfp4 per-module mlx quantization metadata\n"
+ )
+ assert not _is_unsupported_nvfp4_inference_error(tail)
+
+
+ "msg",
+ [
+ "",
+ "some unrelated backend error",
+ "a message mentioning llama-server output: inline, not as a block",
+ "trailing marker only\n\nFull log: /tmp/l.log",
+ ],
+)
+def test_messages_without_a_diagnostics_block_are_untouched(msg):
+ """Every other error source must behave exactly as it did before."""
+ expected = msg.split("\n\nFull log: ")[0]
+ assert _diagnosis_text(msg) == expected