Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: download prebuilt kernel wheels once (#14051)
oobabooga6ba60c0a19c4
diff --git a/studio/backend/tests/test_kernel_install.py b/studio/backend/tests/test_kernel_install.pyindex 23b19639c0e..4430ffe334d 100644--- a/studio/backend/tests/test_kernel_install.py+++ b/studio/backend/tests/test_kernel_install.py@@ -18,7 +18,7 @@ _BACKEND = Path(__file__).resolve().parent.parentif str(_BACKEND) not in sys.path:sys.path.insert(0, str(_BACKEND))-from utils import kernel_install # noqa: E402+from utils import kernel_install, wheel_utils # noqa: E402_REAL_LOCK_PATH = kernel_install._kernel_lock_path@@ -51,6 +51,7 @@ def _no_mirror(monkeypatch):monkeypatch.delenv("UNSLOTH_PYTORCH_MIRROR", raising = False)# Forces the mamba_ssm decision below sm80; an inherited value would override the mocked Triton.monkeypatch.delenv("UNSLOTH_MAMBA_PRE_AMPERE_FAST", raising = False)+ monkeypatch.setattr(wheel_utils, "_uv_static_metadata_config", lambda *args: False)@pytest.mark.parametrize(diff --git a/studio/backend/tests/test_wheel_download.py b/studio/backend/tests/test_wheel_download.pynew file mode 100644index 00000000000..963f58643c3--- /dev/null+++ b/studio/backend/tests/test_wheel_download.py@@ -0,0 +1,296 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""install_wheel gives uv a URL wheel's metadata, so uv fetches it once (astral-sh/uv#18998)."""++import http.server+import io+import os+import shutil+import subprocess+import sys+import threading+import zipfile+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++from utils import wheel_utils # noqa: E402++FLASH_ATTN = (+ "https://github.com/unslothai/unsloth/releases/download/prebuilt-wheels-cu13/"+ "flash_attn-2.8.4+cu13torch2.13cxx11abiTRUE-cp313-cp313-win_amd64.whl"+)+FLASH_ATTN_TOML = (+ "[[dependency-metadata]]\n"+ 'name = "flash-attn"\n'+ 'version = "2.8.4+cu13torch2.13cxx11abitrue"\n'+ "requires-dist = []\n"+)+++def no_project_config(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(wheel_utils, "_uv_project_config_found", lambda: False)+ monkeypatch.delenv("UV_CONFIG_FILE", raising = False)+ monkeypatch.delenv("UV_NO_CONFIG", raising = False)+ for name in wheel_utils._UV_PROJECT_DIR_ENV:+ monkeypatch.delenv(name, raising = False)+ return tmp_path+++def test_static_metadata_names_the_wheel(no_project_config, tmp_path):+ out = tmp_path / "cfg"+ out.mkdir()+ assert wheel_utils._uv_static_metadata_config(FLASH_ATTN, str(out)) is True+ assert (out / "uv.toml").read_text(encoding = "utf-8") == FLASH_ATTN_TOML+++def test_static_metadata_reads_an_escaped_filename_behind_a_query(no_project_config, tmp_path):+ url = (+ "https://mirror.example/whl/causal_conv1d-1.7.0%2Bcu13torch2.13cxx11abiTRUE"+ "-cp313-cp313-linux_x86_64.whl?token=abc"+ )+ assert wheel_utils._uv_static_metadata_config(url, str(tmp_path)) is True+ text = (tmp_path / "uv.toml").read_text(encoding = "utf-8")+ assert 'name = "causal-conv1d"' in text+ assert 'version = "1.7.0+cu13torch2.13cxx11abitrue"' in text+++ "url",+ [+ "https://example.test/whl/simple/",+ "https://example.test/notawheel-1.0.tar.gz",+ 'https://example.test/evil"name-1.0-py3-none-any.whl',+ "https://example.test/too-few-fields.whl",+ ],+)+def test_no_static_metadata_for_what_is_not_a_plain_wheel(url, no_project_config, tmp_path):+ assert wheel_utils._uv_static_metadata_config(url, str(tmp_path)) is False+ assert not (tmp_path / "uv.toml").exists()++[email protected]("value", ["0", "false", "FALSE", "no", "off", "f", "n", ""])+def test_a_false_uv_no_config_keeps_static_metadata(+ value, no_project_config, tmp_path, monkeypatch+):+ # uv reads these as false and still discovers config, so the metadata file is honoured.+ monkeypatch.setenv("UV_NO_CONFIG", value)+ assert wheel_utils._uv_static_metadata_config(FLASH_ATTN, str(tmp_path)) is True++[email protected]("value", ["1", "true", "yes", "on", "anything"])+def test_a_true_uv_no_config_skips_static_metadata(value, no_project_config, tmp_path, monkeypatch):+ monkeypatch.setenv("UV_NO_CONFIG", value)+ assert wheel_utils._uv_static_metadata_config(FLASH_ATTN, str(tmp_path)) is False+++ "variable",+ ["UV_CONFIG_FILE", "UV_NO_CONFIG", "UV_PROJECT", "UV_WORKING_DIR", "UV_WORKING_DIRECTORY"],+)+def test_no_static_metadata_where_uv_would_not_read_it(+ variable, no_project_config, tmp_path, monkeypatch+):+ monkeypatch.setenv(variable, "1")+ assert wheel_utils._uv_static_metadata_config(FLASH_ATTN, str(tmp_path)) is False+++ "name, text, found",+ [+ ("uv.toml", "", True),+ ("pyproject.toml", "[project]\nname = 'x'\n\n[tool.uv]\nnative-tls = true\n", True),+ ("pyproject.toml", "[tool.uv.pip]\nnative-tls = true\n", True),+ ("pyproject.toml", "[project]\nname = 'x'\n", False),+ ("pyproject.toml", "[tool]\nuv = { native-tls = true }\n", True),+ ("pyproject.toml", '[tool."uv"]\nnative-tls = true\n', True),+ ("pyproject.toml", "[ tool.uv ]\nnative-tls = true\n", True),+ ("pyproject.toml", "tool.uv.native-tls = true\n", True),+ ("pyproject.toml", "[project]\ndescription = '[tool.uv] docs'\n", False),+ ("pyproject.toml", "[tool.uv\n", True),+ ],+)+def test_project_config_is_found_from_a_parent(name, text, found, tmp_path, monkeypatch):+ (tmp_path / name).write_text(text, encoding = "utf-8")+ child = tmp_path / "a" / "b"+ child.mkdir(parents = True)+ monkeypatch.chdir(child)+ assert wheel_utils._uv_project_config_found() is found+++class _Recorder:+ def __init__(self, codes):+ self.codes = list(codes)+ self.calls: list[tuple[list[str], str | None, str | None]] = []++ def __call__(self, cmd, **kwargs):+ assert "cwd" not in kwargs, "uv must run from the caller's directory"+ project = cmd[cmd.index("--project") + 1] if "--project" in cmd else None+ toml = Path(project, "uv.toml").read_text(encoding = "utf-8") if project else None+ self.calls.append((list(cmd), project, toml))+ return subprocess.CompletedProcess(cmd, self.codes.pop(0), stdout = "")+++def test_uv_reads_the_metadata_and_pip_runs_as_before(no_project_config, monkeypatch):+ monkeypatch.setattr(wheel_utils.shutil, "which", lambda name: "/usr/bin/uv")+ run = _Recorder([1, 0])+ attempts = wheel_utils.install_wheel(FLASH_ATTN, python_executable = "PY", use_uv = True, run = run)+ assert [installer for installer, _ in attempts] == ["uv", "pip"]+ (uv_cmd, project, uv_toml), (pip_cmd, _, _) = run.calls+ assert uv_cmd == [+ "uv",+ "--project",+ project,+ "pip",+ "install",+ "--python",+ "PY",+ "--no-deps",+ FLASH_ATTN,+ ]+ assert uv_toml == FLASH_ATTN_TOML+ assert not os.path.exists(project), "the config directory outlived the install"+ assert pip_cmd == ["PY", "-m", "pip", "install", "--no-deps", FLASH_ATTN]++[email protected]("broken", ["mkdtemp", "write"])+def test_an_unwritable_temp_dir_still_installs_with_plain_uv(+ broken, no_project_config, monkeypatch+):+ monkeypatch.setattr(wheel_utils.shutil, "which", lambda name: "/usr/bin/uv")++ def fail(*args, **kwargs):+ raise PermissionError("denied")++ if broken == "mkdtemp":+ monkeypatch.setattr(wheel_utils.tempfile, "mkdtemp", fail)+ else:+ monkeypatch.setattr("builtins.open", fail)+ run = _Recorder([0])+ attempts = wheel_utils.install_wheel(FLASH_ATTN, python_executable = "PY", use_uv = True, run = run)+ assert [(i, r.returncode) for i, r in attempts] == [("uv", 0)]+ assert run.calls[0][0] == ["uv", "pip", "install", "--python", "PY", "--no-deps", FLASH_ATTN]+++def test_uv_runs_as_before_when_a_project_config_applies(monkeypatch):+ monkeypatch.setattr(wheel_utils.shutil, "which", lambda name: "/usr/bin/uv")+ monkeypatch.setattr(wheel_utils, "_uv_project_config_found", lambda: True)+ run = _Recorder([0])+ wheel_utils.install_wheel(FLASH_ATTN, python_executable = "PY", use_uv = True, run = run)+ assert run.calls[0][0] == ["uv", "pip", "install", "--python", "PY", "--no-deps", FLASH_ATTN]+++def _wheel_bytes(name: str, version: str) -> bytes:+ dist = f"{name}-{version}.dist-info"+ files = {+ f"{name}/__init__.py": "VALUE = 1\n",+ f"{dist}/METADATA": f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n",+ f"{dist}/WHEEL": "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n",+ }+ record = "".join(f"{path},,\n" for path in files) + f"{dist}/RECORD,,\n"+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as archive:+ for path, text in files.items():+ archive.writestr(path, text)+ archive.writestr(f"{dist}/RECORD", record)+ return buffer.getvalue()+++def no_range_server():+ """Serves a wheel like a GitHub asset: no Range, ETag honoured; ``gets`` counts bodies sent."""+ body = _wheel_bytes("rangeless_kernel", "1.0.0")+ etag = '"0x1"'+ gets: list[str] = []++ class Handler(http.server.BaseHTTPRequestHandler):+ def _head(self, status = 200):+ self.send_response(status)+ self.send_header("ETag", etag)+ if status == 200:+ self.send_header("Content-Type", "application/octet-stream")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()++ def do_HEAD(self): # noqa: N802+ self._head()++ def do_GET(self): # noqa: N802+ if self.headers.get("If-None-Match") == etag:+ self._head(304)+ return+ gets.append(self.headers.get("Range") or "")+ self._head()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target = httpd.serve_forever, daemon = True).start()+ url = f"http://127.0.0.1:{httpd.server_address[1]}/rangeless_kernel-1.0.0-py3-none-any.whl"+ try:+ yield url, gets+ finally:+ httpd.shutdown()+ httpd.server_close()++[email protected](shutil.which("uv") is None, reason = "needs uv on PATH")[email protected]("static_metadata, expected_gets", [(False, 2), (True, 1)])+def test_real_uv_fetches_the_wheel_once(+ static_metadata, expected_gets, no_range_server, no_project_config, tmp_path, monkeypatch+):+ url, gets = no_range_server+ venv = tmp_path / "venv"+ subprocess.run(["uv", "venv", "-q", "--python", sys.executable, str(venv)], check = True)+ python = venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+ # Relative on purpose: it must resolve against the cwd, not the deleted config dir.+ monkeypatch.setenv("UV_CACHE_DIR", "relative-uv-cache")+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")+ if not static_metadata:+ monkeypatch.setattr(wheel_utils, "_uv_static_metadata_config", lambda *args: False)+ attempts = wheel_utils.install_wheel(url, python_executable = str(python), use_uv = True)+ assert [(i, r.returncode) for i, r in attempts] == [("uv", 0)], attempts[-1][1].stdout+ assert len(gets) == expected_gets, gets+ assert (no_project_config / "relative-uv-cache").is_dir()+ wheel_utils.install_wheel(url, python_executable = str(python), use_uv = True, reinstall = True)+ assert len(gets) == expected_gets, gets++[email protected](shutil.which("uv") is None, reason = "needs uv on PATH")[email protected]("variable", ["UV_PROJECT", "UV_WORKING_DIR", "UV_WORKING_DIRECTORY"])+def test_real_uv_still_honours_the_users_project_dir(+ variable, no_range_server, no_project_config, tmp_path, monkeypatch+):+ url, _ = no_range_server+ venv = tmp_path / "venv"+ subprocess.run(["uv", "venv", "-q", "--python", sys.executable, str(venv)], check = True)+ python = venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+ chosen = tmp_path / "chosen-project"+ chosen.mkdir()+ # Unsatisfiable, so honouring this config shows as a refusal.+ (chosen / "uv.toml").write_text('required-version = "==0.0.1"\n', encoding = "utf-8")+ monkeypatch.setenv(variable, str(chosen))+ monkeypatch.setenv("UV_CACHE_DIR", str(tmp_path / "uv-cache"))+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")+ installer, result = wheel_utils.install_wheel(url, python_executable = str(python), use_uv = True)[+ 0+ ]+ assert installer == "uv" and "--project" not in result.args, result.args+ # Older uv ignores UV_WORKING_DIR*; plain uv is the reference for what the user's config does.+ plain = subprocess.run(+ ["uv", "pip", "install", "--python", str(python), "--no-deps", url],+ capture_output = True,+ text = True,+ )+ assert (result.returncode == 0) == (plain.returncode == 0), (result.stdout, plain.stderr)+ if variable == "UV_PROJECT":+ assert result.returncode != 0 and "0.0.1" in result.stdout, result.stdoutdiff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.pyindex 3c09dee3287..5aacab241a6 100644--- a/studio/backend/utils/wheel_utils.py+++ b/studio/backend/utils/wheel_utils.py@@ -12,7 +12,9 @@ import reimport shutilimport subprocessimport sys+import tempfileimport urllib.error+import urllib.parseimport urllib.requestfrom typing import Callable@@ -530,6 +532,77 @@ def flash_attn_wheel_url(env: dict[str, str] | None) -> str | None:)+_WHEEL_FILENAME_FIELD_RE = re.compile(r"[A-Za-z0-9._+!]+")+# Each picks the directory uv discovers its project config from; --project would override it.+_UV_PROJECT_DIR_ENV = ("UV_PROJECT", "UV_WORKING_DIR", "UV_WORKING_DIRECTORY")+++def _pyproject_has_uv_table(path: str) -> bool:+ """Whether a pyproject.toml has a [tool.uv] table; True when unreadable, so its config is kept."""+ try:+ # novermin -- 3.11; the ImportError fallback below is the guard, which vermin cannot see.+ import tomllib # novermin+ except ImportError: # Python < 3.11: no parser, stay out of the way+ return True+ try:+ with open(path, "rb") as fh:+ data = tomllib.load(fh)+ except (OSError, ValueError):+ return True+ tool = data.get("tool")+ return isinstance(tool, dict) and "uv" in tool+++def _uv_project_config_found() -> bool:+ """Whether uv would find a project config from the cwd, which --project elsewhere drops."""+ try:+ directory = os.getcwd()+ except OSError:+ return True+ while True:+ if os.path.isfile(os.path.join(directory, "uv.toml")):+ return True+ pyproject = os.path.join(directory, "pyproject.toml")+ if os.path.isfile(pyproject) and _pyproject_has_uv_table(pyproject):+ return True+ parent = os.path.dirname(directory)+ if parent == directory:+ return False+ directory = parent+++# uv's boolean environment values; anything else counts as set, which only skips the shortcut.+_UV_ENV_FALSE = frozenset({"", "0", "false", "f", "no", "n", "off"})+++def _uv_env_flag_set(name: str) -> bool:+ return os.environ.get(name, "").strip().lower() not in _UV_ENV_FALSE+++def _uv_static_metadata_config(wheel_url: str, config_dir: str) -> bool:+ """Write a uv.toml giving uv the wheel's metadata, so a rangeless GitHub asset downloads once+ (astral-sh/uv#18998); --no-deps makes the empty requires-dist exact. True if written."""+ if os.environ.get("UV_CONFIG_FILE") or _uv_env_flag_set("UV_NO_CONFIG"):+ return False+ if any(os.environ.get(name) for name in _UV_PROJECT_DIR_ENV) or _uv_project_config_found():+ return False+ filename = urllib.parse.unquote(urllib.parse.urlsplit(wheel_url).path.rsplit("/", 1)[-1])+ fields = filename[: -len(".whl")].split("-") if filename.endswith(".whl") else []+ if len(fields) not in (5, 6) or not all(+ _WHEEL_FILENAME_FIELD_RE.fullmatch(f) for f in fields[:2]+ ):+ return False+ name, version = fields[0].replace("_", "-").lower(), fields[1].lower()+ with open(os.path.join(config_dir, "uv.toml"), "w", encoding = "utf-8") as fh:+ fh.write(+ "[[dependency-metadata]]\n"+ f'name = "{name}"\n'+ f'version = "{version}"\n'+ "requires-dist = []\n"+ )+ return True++_UV_OFFLINE_TRUE_VALUES = frozenset({"1", "true", "t", "yes", "y", "on"})_HF_OFFLINE_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})@@ -584,15 +657,27 @@ def install_wheel(if reinstall:uv_cmd.append("--reinstall")uv_cmd.append(wheel_url)- result = run(- uv_cmd,- stdout = subprocess.PIPE,- stderr = subprocess.STDOUT,- text = True,- encoding = "utf-8",- errors = "replace",- env = child_env_without_native_path_secret(),- )+ config_dir = None+ try:+ config_dir = tempfile.mkdtemp(prefix = "unsloth-uv-")+ # --project, not cwd: relative UV_CACHE_DIR etc. still resolve here; uv pip reads only config from it.+ if _uv_static_metadata_config(wheel_url, config_dir):+ uv_cmd[1:1] = ["--project", config_dir]+ except OSError:+ pass # Optional: an unwritable temp dir must not stop the plain uv install.+ try:+ result = run(+ uv_cmd,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ env = child_env_without_native_path_secret(),+ )+ finally:+ if config_dir:+ shutil.rmtree(config_dir, ignore_errors = True)attempts.append(("uv", result))if result.returncode == 0:return attemptsdiff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex c06a21cfff9..9fed5103430 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -12,6 +12,7 @@ activated. Expects `pip` and `python` on PATH to point at the venv.from __future__ import annotationsimport ast+import contextlibimport functoolsimport globimport importlib@@ -27,6 +28,8 @@ import sysimport sysconfigimport tempfileimport textwrap+import threading+import timeimport urllib.requestfrom pathlib import Path@@ -7519,15 +7522,19 @@ def _step(def _progress(label: str) -> None:"""Print an in-place progress bar aligned to the step column layout."""- global _STEP, _PROGRESS_LINE_ACTIVE+ global _STEP_STEP += 1if VERBOSE:return+ _draw_progress(label, end = "\n" if _STEP >= _TOTAL else "")+++def _draw_progress(label: str, end: str = "") -> None:+ global _PROGRESS_LINE_ACTIVEwidth = 20filled = int(width * _STEP / _TOTAL)bar = "=" * filled + "-" * (width - filled)pad = " " * (_COL - len(_LABEL))- end = "\n" if _STEP >= _TOTAL else ""try:sys.stdout.write(f"\r {_dim(_LABEL)}{pad}[{bar}] {_STEP:2}/{_TOTAL} {label:<20}{end}")sys.stdout.flush()@@ -7536,6 +7543,48 @@ def _progress(label: str) -> None:pass+def _stdout_is_tty() -> bool:+ try:+ return sys.stdout.isatty()+ except (AttributeError, OSError, ValueError):+ return False+++_HEARTBEAT_NOTE_SECONDS = 60+_HEARTBEAT_TICK_SECONDS = 1+# Fits "flash-attn 120:00", so the final padded label overwrites every frame.+_HEARTBEAT_WIDTH = 30+++def _install_heartbeat(label: str):+ """Show a quiet install is alive: elapsed time on a TTY bar, else a flushed note each minute."""+ in_place = not VERBOSE and _PROGRESS_LINE_ACTIVE and _stdout_is_tty()+ done = threading.Event()+ started = time.monotonic()++ def beat() -> None:+ interval = _HEARTBEAT_TICK_SECONDS if in_place else _HEARTBEAT_NOTE_SECONDS+ while not done.wait(interval):+ minutes, seconds = divmod(int(time.monotonic() - started), 60)+ if not in_place:+ _note(f"still installing {label} ({minutes} min)")+ sys.stdout.flush()+ # A message printed meanwhile closed the bar line; do not glue onto it.+ elif _PROGRESS_LINE_ACTIVE:+ _draw_progress(f"{f'{label} {minutes}:{seconds:02d}':<{_HEARTBEAT_WIDTH}}")++ thread = threading.Thread(target = beat, daemon = True, name = f"{label}-heartbeat")+ thread.start()+ try:+ yield+ finally:+ done.set()+ thread.join(timeout = 2)+ if in_place and _PROGRESS_LINE_ACTIVE:+ _draw_progress(f"{label:<{_HEARTBEAT_WIDTH}}")++_ENV_FOR_CMD = object()@@ -8617,18 +8666,19 @@ def _ensure_flash_attn() -> None:if wheel_available:# installing a distribution invalidates caches keyed on the action counter._count_install_action()- outcome = install_prebuilt(- wheel_url,- install = install_wheel,- verify = _flash_attn_importable,- on_failed = lambda installer, wheel_result: _print_optional_install_failure(- f"Installing flash-attn prebuilt wheel with {installer}",- wheel_result,- ),- use_uv = USE_UV,- uv_needs_system = UV_NEEDS_SYSTEM,- reinstall = stale,- )+ with _install_heartbeat("flash-attn"):+ outcome = install_prebuilt(+ wheel_url,+ install = install_wheel,+ verify = _flash_attn_importable,+ on_failed = lambda installer, wheel_result: _print_optional_install_failure(+ f"Installing flash-attn prebuilt wheel with {installer}",+ wheel_result,+ ),+ use_uv = USE_UV,+ uv_needs_system = UV_NEEDS_SYSTEM,+ reinstall = stale,+ )if outcome == "installed":returnif outcome == "rejected":diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.pyindex fdbb7da51e7..92aa2c4d3f1 100644--- a/tests/python/test_install_python_stack.py+++ b/tests/python/test_install_python_stack.py@@ -8,6 +8,7 @@ import importlibimport inspectimport ioimport json+import threadingimport osimport reimport shutil@@ -1106,6 +1107,51 @@ class TestProgressLineNotes:assert msg not in bar_lines[0], f"note glued onto the bar: {bar_lines[0]!r}"assert any(ln.strip() == msg for ln in out.split("\n")), out+ def _heartbeat(self, *, tty: bool, beats: int) -> str:+ seen = threading.Event()+ count = [0]+ real_draw, real_note = ips._draw_progress, ips._note++ def counted(real):+ def wrapper(*args, **kwargs):+ real(*args, **kwargs)+ if threading.current_thread().name == "flash-attn-heartbeat":+ count[0] += 1+ if count[0] >= beats:+ seen.set()++ return wrapper++ def emit():+ ips._progress("flash-attn")+ with ips._install_heartbeat("flash-attn"):+ assert seen.wait(10), "the heartbeat never fired"++ with (+ mock.patch.object(ips, "_stdout_is_tty", return_value = tty),+ mock.patch.object(ips, "_HEARTBEAT_TICK_SECONDS", 0.01),+ mock.patch.object(ips, "_HEARTBEAT_NOTE_SECONDS", 0.01),+ mock.patch.object(ips, "_draw_progress", counted(real_draw)),+ mock.patch.object(ips, "_note", counted(real_note)),+ ):+ return self._render(emit)++ def test_captured_install_gets_a_still_installing_note(self):+ out = self._heartbeat(tty = False, beats = 2)+ notes = [ln.strip() for ln in out.split("\n") if "still installing" in ln]+ assert notes[:2] == ["still installing flash-attn (0 min)"] * 2, out+ bar_lines = [ln for ln in out.split("\n") if "5/14" in ln]+ assert all("still installing" not in ln for ln in bar_lines), bar_lines++ def test_terminal_install_redraws_elapsed_time_on_the_bar_line(self):+ out = self._heartbeat(tty = True, beats = 2)+ assert "\n" not in out, "the heartbeat must stay on the bar line"+ frames = out.split("\r")[1:]+ assert all(" 5/14 flash-attn" in frame for frame in frames), frames+ assert "flash-attn 0:00" in frames[1]+ assert frames[-1].rstrip().endswith("flash-attn")+ assert len(frames[-1]) >= max(len(frame) for frame in frames[1:-1])+def test_note_aligns_under_the_step_value_column(self):out = self._render(lambda: (ips._progress("dependency overrides"), ips._note("hello")))note_line = next(ln for ln in out.split("\n") if ln.strip() == "hello")@@ -1188,7 +1234,7 @@ class TestProgressLineNotes:allowed = [(n.lineno, n.end_lineno)for n in ast.walk(tree)- if isinstance(n, ast.FunctionDef) and n.name in {"_progress", "_end_progress_line"}+ if isinstance(n, ast.FunctionDef) and n.name in {"_draw_progress", "_end_progress_line"}]offenders = [n.lineno@@ -1203,7 +1249,7 @@ class TestProgressLineNotes:]assert not offenders, (f"install_python_stack.py:{offenders} write to sys.stdout directly; "- "only _progress()/_end_progress_line() may, everything else uses _safe_print()"+ "only _draw_progress()/_end_progress_line() may, everything else uses _safe_print()")def test_no_message_starts_with_a_newline(self):