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.

Fix three CI regressions: code-span anchor, load-dispatch anchor, recordless pip install (#9959)

Daniel Han5bd09e13e0d7
diff --git a/install.ps1 b/install.ps1
index 9d009ad3bd4..64f6d189c40 100644
--- a/install.ps1
+++ b/install.ps1
@@ -1598,6 +1598,9 @@ public static class UnslothStudioFinalPathV2
# Shared default cache, or the custom Unsloth home's llama.cpp tree.
function Get-ManagedLlamaCppDir {
+ if ($StageRoot) {
+ return (Join-Path $StageRoot "llama.cpp")
+ }
if (-not (Test-StudioHomeIsCustom)) {
return (Join-Path $env:USERPROFILE ".unsloth\llama.cpp")
}
diff --git a/studio/backend/tests/test_parallel_slots_per_load.py b/studio/backend/tests/test_parallel_slots_per_load.py
index 11fbd4ea11b..0436e6db5c3 100644
--- a/studio/backend/tests/test_parallel_slots_per_load.py
+++ b/studio/backend/tests/test_parallel_slots_per_load.py
@@ -312,6 +312,22 @@ def _load_impl_source() -> str:
return body[: body.index("\n@router.")]
+def _first_load_dispatch(load_impl: str) -> int:
+ """Where the body first hands a load to a backend.
+
+ The GGUF call now goes through _run_gguf_load_attempt, a health-wait helper
+ defined above _load_model_impl, so no single backend method name marks the
+ load any more. Whichever spelling survives, the load is still what every
+ assertion here has to sit before.
+ """
+ found = [pos for n in _LOAD_DISPATCH if (pos := load_impl.find(n)) != -1]
+ assert found, f"no load dispatch in _load_model_impl; looked for {_LOAD_DISPATCH}"
+ return min(found)
+
+
+_LOAD_DISPATCH = ("_run_gguf_load_attempt(", "llama_backend.load_model", "backend.load_model,")
+
+
def test_route_resolves_slots_once_before_dedupe_guard_and_load():
load_impl = _load_impl_source()
resolve = load_impl.index("_resolve_parallel_slots(request, fastapi_request)")
@@ -320,7 +336,7 @@ def test_route_resolves_slots_once_before_dedupe_guard_and_load():
resolved_intent = load_impl.index("_resolve_gguf_load_intent(")
resolved_dedupe = load_impl.index("_reuse_loaded_gguf(", resolved_intent)
guard = load_impl.index("_guard_chat_load_against_training")
- load_call = load_impl.index("llama_backend.load_model")
+ load_call = _first_load_dispatch(load_impl)
assert resolve < fast_dedupe < active_intent
assert active_intent < resolved_intent < resolved_dedupe
assert resolved_dedupe < guard < load_call
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index c6a5b51ac46..596d87502b1 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -3691,8 +3691,9 @@ def run(
cmd: list[str],
*,
quiet: bool = True,
+ check: bool = True,
) -> subprocess.CompletedProcess[bytes]:
- """Run a command; on failure print output and exit."""
+ """Run a command; on failure print output and exit, unless ``check`` is False."""
if VERBOSE:
_step(_LABEL, f"{label}...", _dim)
result = subprocess.run(
@@ -3703,15 +3704,74 @@ def run(
**_windows_hidden_subprocess_kwargs(),
)
if result.returncode != 0:
- _step("error", f"{label} failed (exit code {result.returncode})", _red)
- if result.stdout:
- # Redact before printing: the failing pip command may carry a pinned --index-url
- # with userinfo/?token= creds, so raw pip error text would leak them.
- _safe_print(_redact_install_output(result.stdout))
- sys.exit(result.returncode)
+ if not check:
+ # The caller inspects the failure itself; it is responsible for
+ # reporting and exiting if it cannot recover.
+ return result
+ _report_failed_command(label, result)
return result
+def _report_failed_command(label: str, result: subprocess.CompletedProcess[bytes]) -> None:
+ """Print a failed command's redacted output and exit with its code."""
+ _step("error", f"{label} failed (exit code {result.returncode})", _red)
+ if result.stdout:
+ # Redact before printing: the failing pip command may carry a pinned --index-url
+ # with userinfo/?token= creds, so raw pip error text would leak them.
+ _safe_print(_redact_install_output(result.stdout))
+ sys.exit(result.returncode)
+
+
+# pip will not replace a distribution whose .dist-info carries no RECORD -- it cannot
+# know which files to remove -- and an interrupted install (or one uv wrote and pip is
+# now asked to take over) leaves exactly that. The venv is REUSED across runs, so the
+# stub is not transient: once written, every later install of that package dies on it
+# with "The package's contents are unknown", and the dependency step never completes
+# again on that machine. Seen on the Windows startup job, where the whole install is a
+# uv pass that falls back to pip.
+_NO_RECORD_MARKER = "no RECORD file was found"
+_CANNOT_UNINSTALL_RE = re.compile(r"Cannot uninstall ([A-Za-z0-9][A-Za-z0-9._-]*)")
+
+
+def _canonical_dist_name(name: str) -> str:
+ return re.sub(r"[-_.]+", "_", name).lower()
+
+
+def _purge_recordless_distributions(output: "bytes | str | None") -> list[str]:
+ """Delete the .dist-info directories pip named, where they carry no RECORD.
+
+ pip's own hint here is ``--ignore-installed``, which would apply to every
+ package in the command and so silently skip real upgrades too. Dropping just
+ the metadata that blocked it keeps the rest of the environment visible to the
+ retry, and removes nothing that pip itself considers a tracked install.
+ """
+ if not output:
+ return []
+ text = output.decode("utf-8", "replace") if isinstance(output, bytes) else output
+ # Both halves are required: the marker alone can appear in unrelated advice, and
+ # a "Cannot uninstall" without it is a different problem that deleting won't fix.
+ if _NO_RECORD_MARKER not in text:
+ return []
+ blocked = {_canonical_dist_name(n) for n in _CANNOT_UNINSTALL_RE.findall(text)}
+ if not blocked:
+ return []
+ site_packages = sysconfig.get_path("purelib")
+ if not site_packages:
+ return []
+ cleared: list[str] = []
+ for dist_info in sorted(Path(site_packages).glob("*.dist-info")):
+ if _canonical_dist_name(dist_info.name.split("-", 1)[0]) not in blocked:
+ continue
+ if (dist_info / "RECORD").is_file():
+ continue # complete install; whatever failed, it was not this
+ try:
+ shutil.rmtree(dist_info)
+ except OSError:
+ continue
+ cleared.append(dist_info.name)
+ return cleared
+
+
# Packages to skip on Windows (require special build steps)
WINDOWS_SKIP_PACKAGES = {"triton_kernels"}
@@ -5073,7 +5133,16 @@ def pip_install(
_safe_print(_redact_install_output(result.stdout))
pip_cmd = _build_pip_cmd(args) + constraint_args_pip + req_args_pip
- run(f"{label} (pip)" if USE_UV else label, pip_cmd)
+ pip_label = f"{label} (pip)" if USE_UV else label
+ result = run(pip_label, pip_cmd, check = False)
+ if result.returncode != 0:
+ # Retry once, and only after clearing something pip named as
+ # unremovable: a blind retry of a failing install just doubles the wait.
+ cleared = _purge_recordless_distributions(result.stdout)
+ if not cleared:
+ _report_failed_command(pip_label, result)
+ _step(_LABEL, f"cleared half-written {', '.join(cleared)}, retrying...", _dim)
+ run(pip_label, pip_cmd)
finally:
for temp_req in temp_reqs:
temp_req.unlink(missing_ok = True)
diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.py
index bf7eb4ff1bb..788ed5beb56 100644
--- a/tests/python/test_install_python_stack.py
+++ b/tests/python/test_install_python_stack.py
@@ -500,6 +500,8 @@ class TestHardenedPipConfigRelaxation:
def _fake_run(label, cmd, *a, **kw):
seen["env"] = ips._install_env_for_cmd(cmd)
seen["cmd"] = cmd
+ # pip_install reads the result to decide whether to attempt recovery.
+ return mock.Mock(returncode = 0, stdout = b"")
with (
mock.patch.object(ips, "USE_UV", True),
@@ -595,6 +597,8 @@ class TestProgressLineNotes:
mock.patch.object(ips, "subprocess") as sp,
mock.patch.object(ips, "run") as fallback,
):
+ # pip_install reads the result to decide whether to attempt recovery.
+ fallback.return_value = mock.Mock(returncode = 0, stdout = b"")
sp.run.return_value = fake
sp.PIPE, sp.STDOUT = -1, -2
out = self._render(
@@ -2243,3 +2247,130 @@ class TestDesktopBackendVersionConstraint:
else package_name
)
assert unsloth_spec == "unsloth"
+
+
+class TestRecordlessDistributionRecovery:
+ """pip cannot replace a .dist-info with no RECORD, and the venv is reused.
+
+ Observed on the Windows startup job: uv wrote pydantic-core, the pip fallback
+ tried to uninstall it, found no RECORD, and the dependency step died. Nothing
+ clears that state, so the same venv failed the same way on every later run.
+ """
+
+ _PIP_OUTPUT = (
+ b"Attempting uninstall: pydantic-core\n"
+ b" Found existing installation: pydantic-core None\n"
+ b"error: uninstall-no-record-file\n"
+ b"x Cannot uninstall pydantic-core None\n"
+ b"|-> The package's contents are unknown: no RECORD file was found for pydantic-core.\n"
+ )
+
+ def _site_packages(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(ips.sysconfig, "get_path", lambda name: str(tmp_path))
+ return tmp_path
+
+ def _write_dist_info(self, root, name, *, record: bool):
+ dist_info = root / name
+ dist_info.mkdir()
+ (dist_info / "METADATA").write_text("Name: x\n", encoding = "utf-8")
+ if record:
+ (dist_info / "RECORD").write_text("", encoding = "utf-8")
+ return dist_info
+
+ def test_the_named_stub_is_cleared(self, tmp_path, monkeypatch):
+ root = self._site_packages(tmp_path, monkeypatch)
+ stub = self._write_dist_info(root, "pydantic_core-2.46.5.dist-info", record = False)
+
+ cleared = ips._purge_recordless_distributions(self._PIP_OUTPUT)
+
+ assert cleared == ["pydantic_core-2.46.5.dist-info"]
+ assert not stub.exists()
+
+ def test_a_complete_install_of_the_same_name_is_left_alone(self, tmp_path, monkeypatch):
+ # A RECORD means pip knows what it owns; whatever failed, it was not this.
+ root = self._site_packages(tmp_path, monkeypatch)
+ intact = self._write_dist_info(root, "pydantic_core-2.46.5.dist-info", record = True)
+
+ assert ips._purge_recordless_distributions(self._PIP_OUTPUT) == []
+ assert intact.exists()
+
+ def test_other_packages_are_never_touched(self, tmp_path, monkeypatch):
+ # The blast radius is the names pip named, not every stub in site-packages.
+ root = self._site_packages(tmp_path, monkeypatch)
+ bystander = self._write_dist_info(root, "fastapi-0.121.0.dist-info", record = False)
+
+ assert ips._purge_recordless_distributions(self._PIP_OUTPUT) == []
+ assert bystander.exists()
+
+ def test_an_unrelated_failure_clears_nothing(self, tmp_path, monkeypatch):
+ # No RECORD marker: a different problem, which deleting metadata cannot fix.
+ root = self._site_packages(tmp_path, monkeypatch)
+ stub = self._write_dist_info(root, "pydantic_core-2.46.5.dist-info", record = False)
+
+ assert ips._purge_recordless_distributions(b"ERROR: could not resolve pydantic-core") == []
+ assert stub.exists()
+
+ @pytest.mark.parametrize("output", [None, b"", ""])
+ def test_no_output_is_not_a_reason_to_delete(self, output, tmp_path, monkeypatch):
+ self._site_packages(tmp_path, monkeypatch)
+ assert ips._purge_recordless_distributions(output) == []
+
+ def test_the_name_matches_across_dash_and_underscore_spellings(self, tmp_path, monkeypatch):
+ # pip reports "pydantic-core"; the directory is written "pydantic_core".
+ root = self._site_packages(tmp_path, monkeypatch)
+ stub = self._write_dist_info(root, "pydantic.core-2.46.5.dist-info", record = False)
+
+ assert ips._purge_recordless_distributions(self._PIP_OUTPUT) == [stub.name]
+ assert not stub.exists()
+
+ def test_the_fallback_retries_once_after_clearing(self, tmp_path, monkeypatch):
+ """The recovery is only worth anything if pip_install actually re-runs."""
+ root = self._site_packages(tmp_path, monkeypatch)
+ self._write_dist_info(root, "pydantic_core-2.46.5.dist-info", record = False)
+ monkeypatch.setattr(ips, "USE_UV", False)
+ monkeypatch.setattr(ips, "CONSTRAINTS", tmp_path / "absent.txt")
+
+ attempts = []
+
+ def fake_run(
+ label,
+ cmd,
+ *,
+ quiet = True,
+ check = True,
+ ):
+ attempts.append(cmd)
+ failed = len(attempts) == 1
+ return types.SimpleNamespace(
+ returncode = 1 if failed else 0,
+ stdout = self._PIP_OUTPUT if failed else b"",
+ )
+
+ monkeypatch.setattr(ips, "run", fake_run)
+ ips.pip_install("studio deps", "pydantic-core")
+
+ assert len(attempts) == 2 and attempts[0] == attempts[1]
+
+ def test_a_failure_it_cannot_recover_from_still_exits(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(ips.sysconfig, "get_path", lambda name: str(tmp_path))
+ monkeypatch.setattr(ips, "USE_UV", False)
+ monkeypatch.setattr(ips, "CONSTRAINTS", tmp_path / "absent.txt")
+
+ attempts = []
+
+ def fake_run(
+ label,
+ cmd,
+ *,
+ quiet = True,
+ check = True,
+ ):
+ attempts.append(cmd)
+ return types.SimpleNamespace(returncode = 1, stdout = b"ERROR: no matching distribution")
+
+ monkeypatch.setattr(ips, "run", fake_run)
+ with pytest.raises(SystemExit) as excinfo:
+ ips.pip_install("studio deps", "pydantic-core")
+
+ assert excinfo.value.code == 1
+ assert len(attempts) == 1, "a failure with nothing to clear must not be retried"
diff --git a/tests/studio/test_update_release_notes.py b/tests/studio/test_update_release_notes.py
index 447575641c0..ce2b2065f33 100644
--- a/tests/studio/test_update_release_notes.py
+++ b/tests/studio/test_update_release_notes.py
@@ -1257,8 +1257,17 @@ def test_link_resolver_leaves_raw_blocks_and_escapes_alone():
def test_code_span_closers_ignore_backslashes():
"""Escapes are not processed inside a code span, so a run after one closes."""
src = CODE_SPANS.read_text(encoding = "utf-8")
- body = src[src.index("export function codeSpans") :]
- assert body.count("escaped(text") == 1, "only an opener can be escaped"
+ # Counted over the whole module rather than from an exported wrapper: the
+ # scanner has already moved above `codeSpans` once, and a slice anchored on
+ # a wrapper reads as "no opener is escaped either" when that happens.
+ calls = [
+ " ".join(line.split())
+ for line in src.splitlines()
+ if "escaped(" in line and not line.lstrip().startswith("function escaped(")
+ ]
+ assert len(calls) == 1, f"only an opener can be escaped, called at {calls}"
+ # And that one call guards the run that opens a span, not the one closing it.
+ assert '!== "`" || escaped(' in calls[0]
# The card's incompressible height, a fixed part plus a part that follows