Skip to content

Studio: install the pinned Diffusers build before the backend imports what it replaces - #11635

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
oobabooga:worktree-diffusers-repair-before-imports
Sep 23, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
oobabooga:worktree-diffusers-repair-before-imports

Conversation

@oobabooga

@oobabooga oobabooga commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

After an update using an older installer, the first Qwen-Image-2.1 load can fail inside huggingface_hub. Reported on Reddit on v0.1.814-beta:

cannot import name 'httpx' from 'huggingface_hub.utils'

Restarting Studio clears it.

Cause

#11579 repairs the pinned Diffusers build in a background thread after the app imports huggingface_hub. The build requires huggingface-hub>=1.31.0, so repairing an older installation can replace hub files while its old modules remain in sys.modules. Later imports mix versions and fail on names such as httpx or flag_as_download_call.

Fix

  • Run the repair synchronously before from main import app in run_server(), the shared entry point for direct, CLI, desktop and Colab starts.

  • Healthy starts skip installation after checking metadata. Repairs print progress:

      - installing the pinned Diffusers build (first start after an update)...
      - installed the pinned Diffusers build
    
  • Split the repair in two, within 120 s overall (the desktop's startup deadline is 300 s):

    • --prefetch-diffusers-main downloads and builds the pinned build into uv's cache with --target <scratch dir> --no-deps, so it never writes site-packages. On timeout its process tree is stopped. If a peer holds the install lock, startup exits with code 1 and asks the user to retry. Otherwise diffusers_main_repair: failed is recorded and startup continues; an explicit unsloth studio update clears the key and retries.
    • --repair-diffusers-main then installs from the cache (at least 30 s budget). If that install is stopped, the environment may be half replaced, so startup exits with code 1 instead of importing (same for a peer holding the lock), and nothing is recorded so the next start finishes it.
  • Skip the repair when huggingface_hub or diffusers is already imported in the process (for example a notebook kernel calling run_server()), with a message to run unsloth studio update and restart.

  • Remove the background thread and its load guards, prewarm skip and restart message.

  • Keep install_python_stack.py --repair-diffusers-main unchanged, including its lock that serializes concurrent repairs.

  • On macOS, match a tracked child by start time alone in process_lifetime._same_identity, as Linux already does. A framework Python re-execs into Python.app right after spawn, so the recorded comm stopped matching and terminate_pid signalled nothing, leaving the installer's uv running after a timeout.

Before and after

Tested via run.py in a copied Studio venv on CUDA/Linux, starting with PyPI Diffusers 0.40.0 and huggingface_hub 1.30.0, then loading unsloth/Qwen-Image-2.1-GGUF Q4_K_M.

main this PR
Installed during startup in the background after app import before app import
POST /images/load 200, then load fails on flag_as_download_call import 200, loaded on CUDA
cannot import name errors in the log 10 0
Restart needed yes no

The next start skipped installation and loaded the same model. Installation took 0.17 s with uv's cache and 8 s with an empty cache on this connection.

With a second process holding the real install lock for 200 s, the backend exited with code 1 and the retry message after 120 s.

Tests

  • test_diffusers_repair.py: 20 passed, covering import ordering, clean imports in a fresh interpreter, timeout cleanup, peer contention, failure recording and console messages.
  • test_studio_pid_files.py: added coverage that the real run_server() removes its startup marker on failure.
  • Pid-file, repair, disk-logging and startup suites on the final code: 243 passed, 1 skipped. Earlier checks including prewarm, orchestrator and diffusion suites: 1462 passed, 1 skipped.
  • tests/studio/install/test_diffusers_pin.py: 37 passed.
  • Ruff and git diff --check passed.

Scope

  • The first start after an affected update waits for installation; duration depends on the network and uv's cache.
  • Embedders importing main directly get no startup repair.
  • Repair does not protect another backend already running from the same venv against files changing underneath it.
  • Installer failure and timeout without a peer were unit-tested only. Desktop, the in-process CLI path and Windows were not exercised; the copied venv's CLI loads the installed backend rather than this branch.

Timeout safety (added during review)

Cold uv cache, release Diffusers 0.36.0 and hub 1.30.0 in a scratch venv on Linux:

step time site-packages
--prefetch-diffusers-main 9.77 s unchanged (diffusers 0.36.0 hub 1.30.0, directory mtime unchanged)
--repair-diffusers-main after it 0.73 s diffusers 0.41.0.dev0 hub 1.32.0
backend repair with a 3 s budget 3.8 s unchanged, prefetch stopped, no uv or git process left

macos-15 runners, the four repair timeout tests looped 15 times: 15 of 15 loops had failures before the _same_identity change (the installer's child outlived the kill), 0 of 15 after.

Staging CI (ubuntu-latest, macos-15, windows-latest) on the PR's own test files: Linux green. The remaining macOS and Windows failures are pre-existing on main and unchanged or reduced by this PR (base vs head, 3 runs each):

OS main this PR
windows-latest test_a_real_unreaped_child_is_not_a_live_sibling 5/5; 3 POSIX-only tests in test_orphaned_children.py 3/3 same
macos-15 2 validation-group tests 3/3, test_macos_style_orphans_are_recorded_and_reaped 2/3, test_a_survivor_keeps_its_record_through_a_clean_shutdown 1/3 2 validation-group tests 3/3 only

Upstream CI runs these suites on Linux only.

@danielhanchen danielhanchen self-assigned this Sep 23, 2026
…repair

The startup repair killed the installer at 120s and then imported whatever
was on disk, which could be a uv install stopped part way through replacing
diffusers or huggingface_hub.

Split the repair in two. --prefetch-diffusers-main fetches and builds the
pinned build into uv's cache with --target pointing at a scratch directory,
so stopping it at the deadline leaves site-packages untouched and startup
continues as before. The install that follows runs from the cache (about a
second measured on a cold cache, against about 10s for the fetch). If that
install itself is ever stopped while this process holds the lock, startup
now exits with a message instead of importing, and nothing is recorded so
the next start finishes it.

Also skip the in-process repair when huggingface_hub or diffusers is already
imported (a notebook kernel calling run_server), since replacing files under
loaded modules is the failure this repair exists to avoid.

The timeout tests now let the fake installer spawn its child before the
tree kill runs: the kill names descendants before signalling, so a child
forked in between is missed, which made the peer test flaky on macOS.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 23, 2026
The Popen patch is global, and on macOS the tree kill lists descendants with
ps through it, so the recorded launches picked up those calls too.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 23, 2026
The prefetch takes no lock, so an update or a sibling's repair can begin
replacing packages while it runs. Its timeout now checks the pass lock like
the install's does, instead of recording a failure and importing.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 23, 2026
On macOS a pid's identity was "lstart comm". A framework python (python.org,
the GitHub runners, Homebrew) re-execs into Python.app right after spawn, so
the comm adopt_pid read no longer matches later: terminate_pid took the
installer for a recycled pid, forgot it and signalled nothing, and only the
Popen kill of the installer remained, orphaning uv. Compare lstart alone, as
Linux already compares its start time alone for the same reason.

Measured on macos-15 runners: the four repair timeout tests failed in 15 of
15 loops before and 0 of 15 after.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 23, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #11635, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#65.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 4e834acc2 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 4e834acc2c

No triage reaction was recorded on the mirror

Round 2: reviewed mirror 298552ac5 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/utils/diffusers_repair.py (on the mirror)

@@ -133,93 +130,168 @@ def _peer_holds_pass() -> bool:
         return not uncontended
 
 
-def _wait_for_peer_pass() -> None:
-    """Hold the gate until no process holds the dependency pass. Killing our installer released it,
-    but the pass it was waiting behind may still be writing."""
-    while _peer_holds_pass():
-        time.sleep(_PEER_POLL_S)
+class PeerInstallInProgress(RuntimeError):
+    """A peer still holds the install lock at timeout, so importing packages is unsafe."""
+
+
+class InstallInterrupted(RuntimeError):
+    """Our own install was stopped at its deadline, so the environment may be half replaced."""
+
+
+PEER_INSTALL_MESSAGE = (
+    "Another Unsloth install or update is still changing this environment after "
+    f"{_REPAIR_TIMEOUT_S}s. Start Unsloth Studio again once it has finished."
+)
+INTERRUPTED_MESSAGE = (
+    "Installing the pinned Diffusers build was stopped part way, so this environment may be "
+    "half updated. Start Unsloth Studio again to finish it, or run `unsloth studio update`."
+)
+
+
+def _record_failure() -> None:
+    """Suppress startup retries until an explicit update clears the failure key."""
+    try:
+        from studio.install_manifest import update_manifest
+        update_manifest(diffusers_main_repair = "failed")
+    except Exception as exc:  # noqa: BLE001 - unrecorded means the next start tries again
+        logger.warning("diffusers self-heal could not record its failure: %s", exc)
+
+
+def _installer_would_skip() -> bool:
+    """The installer's no-op gates: a start it would skip must not block or claim to install."""
+    if sys.version_info[:2] < _MAIN_MIN_PYTHON:
+        return True
+    try:
+        from studio.install_manifest import read_manifest
+        manifest = read_manifest() or {}
+    except Exception:  # noqa: BLE001 - an unreadable manifest is no record of a failed try
+        return False
+    step_results = manifest.get("step_results")
+    update_failed = (
+        isinstance(step_results, dict) and step_results.get("diffusers-main.txt") == "failed"
+    )
+    return manifest.get("diffusers_main_repair") == "failed" or update_failed
+
 
+def _run_installer(flag: str, timeout: float) -> "tuple[int | None, str]":
+    """Run one installer mode; None as the code when it was stopped at ``timeout``.
 
-def _run_repair() -> None:
-    global _installed
+    Raises OSError when the installer cannot start.
+    """
     from utils.child_stdio import utf8_child_env
     from utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pid, terminate_pid
 
     kwargs = child_popen_kwargs()
     if os.name == "nt":
         kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
-    try:
-        proc = subprocess.Popen(
-            [sys.executable, str(_INSTALLER), "--repair-diffusers-main"],
-            env = utf8_child_env(_repair_env()),
-            stdout = subprocess.PIPE,
-            stderr = subprocess.STDOUT,
-            text = True,
-            encoding = "utf-8",
-            errors = "replace",
-            **kwargs,
-        )
-    except OSError as exc:
-        logger.warning("diffusers self-heal could not start the installer: %s", exc)
-        return
+    proc = subprocess.Popen(
+        [sys.executable, str(_INSTALLER), flag],
+        env = utf8_child_env(_repair_env()),
+        stdout = subprocess.PIPE,
+        stderr = subprocess.STDOUT,
+        text = True,
+        encoding = "utf-8",
+        errors = "replace",
+        **kwargs,
+    )
     # Tracked, so a backend that exits mid-install takes the installer and its uv/git children down.
     adopt_pid(proc.pid)
     try:
-        output, _ = proc.communicate(timeout = _REPAIR_TIMEOUT_S)
+        output, _ = proc.communicate(timeout = timeout)
     except subprocess.TimeoutExpired:
-        # The whole tree, before the gate reopens: uv keeps rewriting diffusers after its parent dies.
         terminate_pid(proc.pid, owner_verified = True)
         proc.kill()
         proc.wait()
-        logger.warning("diffusers self-heal timed out after %ss", _REPAIR_TIMEOUT_S)
-        _wait_for_peer_pass()
-        return
+        return None, ""
     finally:
         if proc.poll() is not None:
             forget_pid(proc.pid)
-    if proc.returncode == _INSTALLED:
-        _installed = True
+    return proc.returncode, output or ""
+
+
+def _run_repair(echo: Callable[[str], None], prefetch: bool = True) -> bool:
+    started = time.monotonic()
+    if prefetch:
+        # The slow part (clone or download, then build) goes into uv's cache only, so stopping it
+        # at the deadline leaves site-packages untouched and the app can import as it is.
+        try:
+            code, output = _run_installer("--prefetch-diffusers-main", _REPAIR_TIMEOUT_S)
+        except OSError as exc:
+            logger.warning("diffusers self-heal could not start the installer: %s", exc)
+            return False
+        if code is None:
+            _record_failure()
+            echo(
+                f"  - the pinned Diffusers build took over {_REPAIR_TIMEOUT_S}s to download and "
+                "was stopped; run `unsloth studio update` to install it"
+            )
+            logger.warning("diffusers self-heal timed out after %ss", _REPAIR_TIMEOUT_S)
+            return False

P1 Badge Recheck the install lock after a prefetch timeout

When a dependency pass begins while the cache-only prefetch is running—for example, during concurrent direct run.py launches or an installer invoked outside the CLI launch gate—this timeout path records a failure and returns without checking _peer_holds_pass(). run_server() then immediately imports the application even though the peer may still be replacing diffusers and huggingface_hub, recreating the mixed-version import failure this change is intended to prevent. Recheck the pass lock here and abort or wait when it is held rather than continuing startup.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in bd5186c: a prefetch timeout now checks the pass lock first and raises PeerInstallInProgress (nothing recorded) when a peer holds it, as the install path does. Regression test added.

Round 3: reviewed mirror c08b9be9d (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/utils/diffusers_repair.py (on the mirror)

@@ -133,93 +130,172 @@ def _peer_holds_pass() -> bool:
         return not uncontended
 
 
-def _wait_for_peer_pass() -> None:
-    """Hold the gate until no process holds the dependency pass. Killing our installer released it,
-    but the pass it was waiting behind may still be writing."""
-    while _peer_holds_pass():
-        time.sleep(_PEER_POLL_S)
+class PeerInstallInProgress(RuntimeError):
+    """A peer still holds the install lock at timeout, so importing packages is unsafe."""
+
+
+class InstallInterrupted(RuntimeError):
+    """Our own install was stopped at its deadline, so the environment may be half replaced."""
+
+
+PEER_INSTALL_MESSAGE = (
+    "Another Unsloth install or update is still changing this environment after "
+    f"{_REPAIR_TIMEOUT_S}s. Start Unsloth Studio again once it has finished."
+)
+INTERRUPTED_MESSAGE = (
+    "Installing the pinned Diffusers build was stopped part way, so this environment may be "
+    "half updated. Start Unsloth Studio again to finish it, or run `unsloth studio update`."
+)
+
+
+def _record_failure() -> None:
+    """Suppress startup retries until an explicit update clears the failure key."""
+    try:
+        from studio.install_manifest import update_manifest
+        update_manifest(diffusers_main_repair = "failed")
+    except Exception as exc:  # noqa: BLE001 - unrecorded means the next start tries again
+        logger.warning("diffusers self-heal could not record its failure: %s", exc)
+
+
+def _installer_would_skip() -> bool:
+    """The installer's no-op gates: a start it would skip must not block or claim to install."""
+    if sys.version_info[:2] < _MAIN_MIN_PYTHON:
+        return True
+    try:
+        from studio.install_manifest import read_manifest
+        manifest = read_manifest() or {}
+    except Exception:  # noqa: BLE001 - an unreadable manifest is no record of a failed try
+        return False
+    step_results = manifest.get("step_results")
+    update_failed = (
+        isinstance(step_results, dict) and step_results.get("diffusers-main.txt") == "failed"
+    )
+    return manifest.get("diffusers_main_repair") == "failed" or update_failed
+
 
+def _run_installer(flag: str, timeout: float) -> "tuple[int | None, str]":
+    """Run one installer mode; None as the code when it was stopped at ``timeout``.
 
-def _run_repair() -> None:
-    global _installed
+    Raises OSError when the installer cannot start.
+    """
     from utils.child_stdio import utf8_child_env
     from utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pid, terminate_pid
 
     kwargs = child_popen_kwargs()
     if os.name == "nt":
         kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
-    try:
-        proc = subprocess.Popen(
-            [sys.executable, str(_INSTALLER), "--repair-diffusers-main"],
-            env = utf8_child_env(_repair_env()),
-            stdout = subprocess.PIPE,
-            stderr = subprocess.STDOUT,
-            text = True,
-            encoding = "utf-8",
-            errors = "replace",
-            **kwargs,
-        )
-    except OSError as exc:
-        logger.warning("diffusers self-heal could not start the installer: %s", exc)
-        return
+    proc = subprocess.Popen(
+        [sys.executable, str(_INSTALLER), flag],
+        env = utf8_child_env(_repair_env()),
+        stdout = subprocess.PIPE,
+        stderr = subprocess.STDOUT,
+        text = True,
+        encoding = "utf-8",
+        errors = "replace",
+        **kwargs,
+    )
     # Tracked, so a backend that exits mid-install takes the installer and its uv/git children down.
     adopt_pid(proc.pid)
     try:
-        output, _ = proc.communicate(timeout = _REPAIR_TIMEOUT_S)
+        output, _ = proc.communicate(timeout = timeout)
     except subprocess.TimeoutExpired:
-        # The whole tree, before the gate reopens: uv keeps rewriting diffusers after its parent dies.
         terminate_pid(proc.pid, owner_verified = True)
         proc.kill()
         proc.wait()
-        logger.warning("diffusers self-heal timed out after %ss", _REPAIR_TIMEOUT_S)
-        _wait_for_peer_pass()
-        return
+        return None, ""
     finally:
         if proc.poll() is not None:
             forget_pid(proc.pid)
-    if proc.returncode == _INSTALLED:
-        _installed = True
+    return proc.returncode, output or ""
+
+
+def _run_repair(echo: Callable[[str], None], prefetch: bool = True) -> bool:
+    started = time.monotonic()
+    if prefetch:
+        # The slow part (clone or download, then build) goes into uv's cache only, so stopping it
+        # at the deadline leaves site-packages untouched and the app can import as it is.
+        try:
+            code, output = _run_installer("--prefetch-diffusers-main", _REPAIR_TIMEOUT_S)
+        except OSError as exc:
+            logger.warning("diffusers self-heal could not start the installer: %s", exc)
+            return False
+        if code is None:
+            # The prefetch takes no lock, so a peer may have started replacing packages meanwhile.
+            if _peer_holds_pass():
+                logger.warning("diffusers self-heal timed out while a peer's dependency pass ran")
+                raise PeerInstallInProgress(PEER_INSTALL_MESSAGE)
+            _record_failure()
+            echo(
+                f"  - the pinned Diffusers build took over {_REPAIR_TIMEOUT_S}s to download and "
+                "was stopped; run `unsloth studio update` to install it"
+            )
+            logger.warning("diffusers self-heal timed out after %ss", _REPAIR_TIMEOUT_S)
+            return False
+        if code not in (0, _NOTHING_TO_DO):
+            # The install below is authoritative: it fetches for itself and records its own failure.
+            logger.warning("diffusers prefetch failed. Installer output:\n%s", output[-4000:])
+    budget = max(_INSTALL_MIN_TIMEOUT_S, _REPAIR_TIMEOUT_S - (time.monotonic() - started))
+    try:
+        code, output = _run_installer("--repair-diffusers-main", budget)
+    except OSError as exc:
+        logger.warning("diffusers self-heal could not start the installer: %s", exc)
+        return False
+    if code is None:
+        # A remaining lock belongs to a peer. Abort without changing its manifest.
+        if _peer_holds_pass():
+            logger.warning("diffusers self-heal timed out behind a peer's dependency pass")
+            raise PeerInstallInProgress(PEER_INSTALL_MESSAGE)
+        # Ours, and possibly stopped part way through replacing packages: importing them is unsafe.
+        # Not recorded as failed, so the next start retries from uv's cache.
+        logger.warning("diffusers self-heal install stopped after %.0fs", budget)
+        raise InstallInterrupted(INTERRUPTED_MESSAGE)
+    if code == _INSTALLED:
+        echo("  - installed the pinned Diffusers build")
         logger.info("diffusers self-heal installed the pinned Diffusers main build")
-    elif proc.returncode != _NOTHING_TO_DO:
+        return True
+    if code != _NOTHING_TO_DO:
+        echo(
+            "  - could not install the pinned Diffusers build; run `unsloth studio update` to retry"
+        )
         logger.warning(
             "diffusers self-heal could not install the pinned build; run `unsloth studio "
             "update` to retry. Installer output:\n%s",
-            (output or "")[-4000:],
+            output[-4000:],
         )
+    return False
 
 
-def start_diffusers_autorepair_if_needed() -> bool:
-    """Start the background install when diffusers is an index release and the pin wants main.
-    True iff a repair thread was started; at most once per process."""
-    global _thread
-    if _opted_out() or not _MAIN_PIN.is_file() or not _INSTALLER.is_file():
-        return False
-    # A peer mid-install can have removed the metadata, so its pass also starts the installer, which
-    # waits the pass out and keeps loads refused meanwhile.
-    if not _diffusers_is_an_index_install() and not _peer_holds_pass():
-        return False
-    with _lock:
-        if _thread is not None:
-            return False
-        _thread = threading.Thread(target = _run_repair, daemon = True, name = "diffusers-autorepair")
-        _thread.start()
-    logger.info(
-        "checking for the pinned Diffusers main build in the background. Set %s=1 to disable.",
-        DISABLE_ENV_VAR,
-    )
-    return True
-
-
-IN_FLIGHT_MESSAGE = (
-    "Unsloth is installing the pinned diffusers build in the background, which takes a few "
-    "minutes on the first start after an update. Try again shortly."
-)
-
+def _loaded_replaceable_modules() -> "list[str]":
+    """Packages the repair replaces that this process has already imported."""
+    return [name for name in ("huggingface_hub", "diffusers") if name in sys.modules]
 
-def diffusers_repair_in_flight() -> bool:
-    thread = _thread
-    return thread is not None and thread.is_alive()
 
+def repair_diffusers_before_imports(echo: Callable[[str], None] = lambda _line: None) -> bool:
+    """Repair an index install before app imports. Return True if the build was installed.
 
-def diffusers_repair_installed() -> bool:
-    return _installed
+    Raise PeerInstallInProgress if a peer holds the install lock at timeout, and
+    InstallInterrupted if our own install had to be stopped.
+    """
+    if _opted_out() or not _MAIN_PIN.is_file() or not _INSTALLER.is_file():
+        return False

P1 Badge Honor the install lock when autorepair is disabled

When UNSLOTH_DISABLE_DIFFUSERS_AUTOREPAIR=1 or UNSLOTH_DIFFUSERS_MAIN=0 is set while another install_python_stack.py dependency pass is active, this early return bypasses _peer_holds_pass() entirely. run_server() consequently proceeds to from main import app while that pass may be replacing diffusers and huggingface_hub, recreating the mixed-version import failure this change is intended to prevent. The opt-out should suppress installing the main pin, but startup must still wait for or abort on an active dependency pass.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing this. The opt-out turns this self-heal off entirely, and main never waited on the pass lock at startup, so an opted-out start during a concurrent update behaves exactly as it does on main for every package, not just diffusers. Keeping Studio from starting mid-update is the launch gate's job, not this repair's.

Round 4: reviewed mirror 9ebbc7e5d9 (this PR's 3d8452111)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 9ebbc7e5d9

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 9ebbc7e5d9 (this PR's 3d8452111).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen

Copy link
Copy Markdown
Member

Review record, round 1 (supplement). These two findings were raised on the mirror (danielhanchen/unsloth-staging-review#65) against the original head and were removed from it when settled threads were pruned, so they are missing from the record above. Quoted as posted by chatgpt-codex-connector[bot].

P1, studio/backend/utils/diffusers_repair.py: Abort startup after timing out an active install

If this repair itself holds the pass lock and exceeds 120 seconds while pip or uv is replacing diffusers or huggingface_hub, killing the process tree does not roll back the partially modified site-packages. Because _peer_holds_pass() is checked only after this process has been killed and released its own lock, the check returns false, and this return False lets run_server() immediately import the potentially half-installed environment. A timeout of the active repair should stop startup rather than being treated as a safe failure.

Accepted on the mirror. Fixed in 1e9f46e: the slow fetch and build moved to --prefetch-diffusers-main (uv cache only, safe to stop), and a stopped install now exits startup with InstallInterrupted instead of importing.

P1, studio/backend/run.py: Avoid repairing after dependencies are already cached

When run_server() is called from a long-lived process that has already imported huggingface_hub or diffusers (notably a Colab kernel after importing Unsloth), this call still replaces those packages while their old modules remain in sys.modules. The later from main import app can therefore combine cached 1.30-era modules with newly installed files and reproduce the httpx/flag_as_download_call import failures this change is intended to prevent; detect this state and require a fresh interpreter or otherwise avoid performing the in-process repair.

Accepted on the mirror. Fixed in 1e9f46e: the in-process repair is skipped with a message when either package is already in sys.modules.

@danielhanchen
danielhanchen merged commit 94ca6f4 into unslothai:main Sep 23, 2026
78 of 85 checks passed
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 23, 2026
…ai#11635's prefetch

The ARM64 wheelhouse test counted _effective_requirements(req) and expected
four. unslothai#11635's Diffusers prefetch is a fifth, and it has to filter the same
way, since it builds the cache entry the install then reads. Name each caller
and the file it passes instead, so a new caller fails with its own name.
pull Bot pushed a commit to eoinmcgee1993/unsloth that referenced this pull request Sep 23, 2026
…ponsive classes in the tests (unslothai#11680)

* Let a scratch --target prefetch through the torch-probe installer check

unslothai#11635's _prefetch_diffusers_main builds the pinned Diffusers into a scratch
--target directory to warm uv's cache, so it installs nothing into the
environment and cannot change which torch is there. The entry-point check
counted any caller of _build_uv_cmd as an installer and failed main.

A function whose every build command carries --target is now read as a
scratch prefetch. Anything else that builds a command still has to drop the
memoized torch classification.

* Follow unslothai#11660's phone gutters and lg chat split in the desktop contract

unslothai#11660 gave the Images, Audio and image-train rails a 20px gutter on phones
(max-sm:px-5, max-sm:pl-5) and moved the chat split from md to lg, so
tablets stack. Four contracts still pinned the old class strings.

* Exempt only a --target into a directory the function just made with mkdtemp

* Only a name bound once can prove its --target is the mkdtemp scratch

* Hold the prefetch to a scratch target by running it, not by reading its source

The AST classifier kept meeting spellings it could not see through: a
rebound name, a second --target. Exempt _prefetch_diffusers_main by name
instead, and prove the exemption by running it with the subprocess stubbed,
through both the git and the archive source: exactly one --target, naming a
directory it made under the temp root, gone afterwards.

* Name the callers of the shared requirements filter, including unslothai#11635's prefetch

The ARM64 wheelhouse test counted _effective_requirements(req) and expected
four. unslothai#11635's Diffusers prefetch is a fifth, and it has to filter the same
way, since it builds the cache entry the install then reads. Name each caller
and the file it passes instead, so a new caller fails with its own name.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
… what it replaces (unslothai#11635)

* Studio: install the pinned Diffusers build before the backend imports what it replaces

* Skip the startup repair when the installer would do nothing

* Never import a half-replaced environment after a timed-out Diffusers repair

The startup repair killed the installer at 120s and then imported whatever
was on disk, which could be a uv install stopped part way through replacing
diffusers or huggingface_hub.

Split the repair in two. --prefetch-diffusers-main fetches and builds the
pinned build into uv's cache with --target pointing at a scratch directory,
so stopping it at the deadline leaves site-packages untouched and startup
continues as before. The install that follows runs from the cache (about a
second measured on a cold cache, against about 10s for the fetch). If that
install itself is ever stopped while this process holds the lock, startup
now exits with a message instead of importing, and nothing is recorded so
the next start finishes it.

Also skip the in-process repair when huggingface_hub or diffusers is already
imported (a notebook kernel calling run_server), since replacing files under
loaded modules is the failure this repair exists to avoid.

The timeout tests now let the fake installer spawn its child before the
tree kill runs: the kill names descendants before signalling, so a child
forked in between is missed, which made the peer test flaky on macOS.

* Count only installer launches in the repair timeout tests

The Popen patch is global, and on macOS the tree kill lists descendants with
ps through it, so the recorded launches picked up those calls too.

* Stop startup when a peer's pass is running at a prefetch timeout

The prefetch takes no lock, so an update or a sibling's repair can begin
replacing packages while it runs. Its timeout now checks the pass lock like
the install's does, instead of recording a failure and importing.

* Match a macOS child by start time alone, so a timed-out repair is killed

On macOS a pid's identity was "lstart comm". A framework python (python.org,
the GitHub runners, Homebrew) re-execs into Python.app right after spawn, so
the comm adopt_pid read no longer matches later: terminate_pid took the
installer for a recycled pid, forgot it and signalled nothing, and only the
Popen kill of the installer remained, orphaning uv. Compare lstart alone, as
Linux already compares its start time alone for the same reason.

Measured on macos-15 runners: the four repair timeout tests failed in 15 of
15 loops before and 0 of 15 after.

---------

Co-authored-by: Daniel Han <[email protected]>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…ponsive classes in the tests (unslothai#11680)

* Let a scratch --target prefetch through the torch-probe installer check

unslothai#11635's _prefetch_diffusers_main builds the pinned Diffusers into a scratch
--target directory to warm uv's cache, so it installs nothing into the
environment and cannot change which torch is there. The entry-point check
counted any caller of _build_uv_cmd as an installer and failed main.

A function whose every build command carries --target is now read as a
scratch prefetch. Anything else that builds a command still has to drop the
memoized torch classification.

* Follow unslothai#11660's phone gutters and lg chat split in the desktop contract

unslothai#11660 gave the Images, Audio and image-train rails a 20px gutter on phones
(max-sm:px-5, max-sm:pl-5) and moved the chat split from md to lg, so
tablets stack. Four contracts still pinned the old class strings.

* Exempt only a --target into a directory the function just made with mkdtemp

* Only a name bound once can prove its --target is the mkdtemp scratch

* Hold the prefetch to a scratch target by running it, not by reading its source

The AST classifier kept meeting spellings it could not see through: a
rebound name, a second --target. Exempt _prefetch_diffusers_main by name
instead, and prove the exemption by running it with the subprocess stubbed,
through both the git and the archive source: exactly one --target, naming a
directory it made under the temp root, gone afterwards.

* Name the callers of the shared requirements filter, including unslothai#11635's prefetch

The ARM64 wheelhouse test counted _effective_requirements(req) and expected
four. unslothai#11635's Diffusers prefetch is a fifth, and it has to filter the same
way, since it builds the cache entry the install then reads. Name each caller
and the file it passes instead, so a new caller fails with its own name.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants