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: keep the compiled cache when a sibling backend is live (#8457)

Daniel Han1ef30b95fd3a
diff --git a/studio/backend/main.py b/studio/backend/main.py
index ab05c8836b1..b59aed659af 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -341,7 +341,9 @@ from utils.torch_warmup import (
start_background_warm,
warm_status,
)
-from utils.cache_cleanup import clear_unsloth_compiled_cache
+from utils.cache_cleanup import (
+ clear_compiled_cache_unless_shared as _clear_compiled_cache_unless_shared,
+)
from utils.lifespan_shutdown import run_lifespan_shutdown
from utils.native_path_leases import native_path_leases_supported
from utils.update_status import (
@@ -629,6 +631,16 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:
_warm_rag_embedder()
+def clear_compiled_cache_unless_shared(app: FastAPI) -> None:
+ """Clear the compiled cache unless a sibling backend of this install is live.
+
+ The decision lives in cache_cleanup, next to the paths it clears and the lock
+ that serializes it against a sibling's startup; run_server puts the probe on
+ app.state because main.py must not import run.py back.
+ """
+ _clear_compiled_cache_unless_shared(getattr(app.state, "live_sibling_backend", None))
+
+
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Startup: detect hardware, seed default admin if needed. Shutdown: clean up compiled cache."""
@@ -639,7 +651,7 @@ async def lifespan(app: FastAPI):
import structlog as _structlog
_lifespan_log = _structlog.get_logger(__name__)
- clear_unsloth_compiled_cache()
+ clear_compiled_cache_unless_shared(app)
# Move the legacy sandbox up here rather than from the first request: the
# copy can be minutes when the studio home is on another filesystem.
@@ -783,7 +795,7 @@ async def lifespan(app: FastAPI):
await run_lifespan_shutdown(
terminate_hub_downloads,
- clear_unsloth_compiled_cache,
+ lambda: clear_compiled_cache_unless_shared(app),
_hw_module,
)
# Shutdown cleared the state this warm produced, so release the one-per-process latch.
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 5cf0db371c4..1c108a60f74 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -827,6 +827,12 @@ from utils.paths.storage_roots import studio_root as _studio_root
# Legacy single-instance file; still read so `stop` finds an older build's server.
_PID_FILE = _studio_root() / "studio.pid"
PID_FILE_GLOB = "studio-*.pid"
+# Deliberately not a .pid: everything that globs PID_FILE_GLOB expects a bound
+# server with a port in the name, and a process that has not bound yet is not
+# one. Only the sibling probe reads these.
+STARTUP_MARKER_GLOB = "studio-starting-*.marker"
+_OWN_STARTUP_MARKERS: "list[Path]" = []
+_STARTUP_MARKER_HOOK_REGISTERED = False
def _pid_file_for_port(port: int) -> Path:
@@ -976,6 +982,253 @@ def _legacy_studio_on_port(port: int) -> "int | None":
return pid
+def write_startup_marker() -> None:
+ """Record that this process is coming up, before uvicorn starts.
+
+ The per-port record cannot be written until uvicorn reports the bound port,
+ and lifespan startup runs well before that. Two overlapping launches would
+ otherwise each find no sibling and each clear the shared compiled cache, the
+ exact race this is meant to prevent, so a sibling has to be discoverable
+ from the moment it could do any clearing.
+
+ Published under the same lock the clear takes, so the marker cannot appear in
+ the gap between a sibling's probe and its rmtree; that ordering is the whole
+ point of the marker.
+
+ Best effort, like the records themselves: a studio home we cannot write to
+ is not a reason to refuse to start.
+ """
+ me = os.getpid()
+ created = _process_create_time(me)
+ body = f"{me}\n{created if created is not None else ''}\n"
+ try:
+ from utils.cache_cleanup import compiled_cache_lock, LOCK_BUSY
+ except Exception:
+ import contextlib
+
+ # No lock available means an unserialized publish, which is what this
+ # did before the lock existed. Startup still has to happen.
+ compiled_cache_lock = contextlib.nullcontext
+ LOCK_BUSY = None
+ # A longer budget than a clear takes: publishing behind a holder that is
+ # mid-rmtree is the case worth waiting out. Publishing anyway if the wait
+ # runs out is still right, because a marker that never appears makes this
+ # backend invisible, which is the failure the marker exists to prevent.
+ with compiled_cache_lock(timeout = 30.0) as lock_state:
+ published_unlocked = lock_state == LOCK_BUSY
+ if published_unlocked:
+ logger.warning(
+ "Publishing the startup marker without the cache lock: another backend "
+ "has held it for 30s"
+ )
+ directory = _studio_root()
+ path = directory / f"studio-starting-{me}.marker"
+ try:
+ directory.mkdir(parents = True, exist_ok = True)
+ # Same layout as a per-port record, so _read_pid_record parses both.
+ # An unknown start time is a blank line, read back as None.
+ path.write_text(body, encoding = "utf-8")
+ # Not appended twice. The path is the same file every time (this
+ # PID names it), so a second publish rewrites identical bytes, but
+ # a duplicate entry would be popped and retried twice on the way
+ # out for no reason.
+ if path not in _OWN_STARTUP_MARKERS:
+ _OWN_STARTUP_MARKERS.append(path)
+ except OSError:
+ pass
+ if not _OWN_STARTUP_MARKERS:
+ return
+ import atexit
+
+ # Registered here rather than beside the pid-file hook: startup can fail
+ # between these two points, and the marker has to go either way. Before the
+ # wait below, so an interrupt during it still takes the marker back. Once
+ # per process: the hook drains the whole list, so a second registration
+ # only runs it again on an empty one.
+ global _STARTUP_MARKER_HOOK_REGISTERED
+ if not _STARTUP_MARKER_HOOK_REGISTERED:
+ atexit.register(_remove_startup_marker)
+ _STARTUP_MARKER_HOOK_REGISTERED = True
+ if published_unlocked:
+ _wait_out_a_running_cache_clear(compiled_cache_lock, LOCK_BUSY)
+
+
+# A clear is an rmtree of one directory. Five minutes is not how long that takes
+# even on network storage; it is how long to keep waiting before deciding that
+# refusing to start is worse for the user than starting on a cache that may lose
+# files underneath it.
+_CACHE_CLEAR_WAIT_SECONDS = 300.0
+
+
+def _wait_out_a_running_cache_clear(compiled_cache_lock, lock_busy) -> None:
+ """Block until whoever is clearing the compiled cache has finished.
+
+ The marker is already published, so this backend is visible to every sibling
+ probe from here on, which is what publishing unlocked bought. What it must
+ not do is return to a caller that immediately imports and compiles into a
+ cache another backend is still deleting: that is the cross-backend race the
+ lock exists to close. Taking the lock and dropping it again is the wait.
+
+ The lock is an OS file lock, released when its holder exits, so a crashed
+ backend cannot hold this here.
+ """
+ with compiled_cache_lock(timeout = _CACHE_CLEAR_WAIT_SECONDS) as state:
+ if state == lock_busy:
+ logger.warning(
+ "Starting while another backend is still clearing the compiled cache: "
+ "it has held the lock for %ss. Compiled modules may be removed underneath "
+ "this one and recompiled.",
+ int(30.0 + _CACHE_CLEAR_WAIT_SECONDS),
+ )
+
+
+# Enough attempts to outlast the usual Windows holder (an indexer or a scanner
+# with the file open), short enough that shutdown is not visibly delayed.
+_MARKER_REMOVAL_ATTEMPTS = 5
+_MARKER_REMOVAL_BACKOFF_SECONDS = 0.2
+
+
+def _remove_startup_marker() -> None:
+ """Delete this process's startup markers, retrying a failure a few times.
+
+ A path is dropped from the list only once it is actually gone. A transient
+ unlink failure would otherwise lose the only reference to it, leaving a
+ marker on disk that no later cleanup can retry: its recorded start time
+ still matches this process, so an embedded host that keeps running would go
+ on answering as a live backend and pin the compiled cache.
+
+ Retrying here rather than only keeping the path is what makes that recovery
+ real. The one guaranteed later call is the atexit hook, which an embedded
+ host that outlives its backend does not reach for a long time, if ever.
+ """
+ import time
+
+ remaining = []
+ while _OWN_STARTUP_MARKERS:
+ path = _OWN_STARTUP_MARKERS.pop()
+ for attempt in range(_MARKER_REMOVAL_ATTEMPTS):
+ try:
+ path.unlink(missing_ok = True)
+ break
+ except OSError:
+ if attempt + 1 == _MARKER_REMOVAL_ATTEMPTS:
+ # Still tracked, so the atexit hook and any later call try
+ # again; this is the floor, not the only chance.
+ remaining.append(path)
+ break
+ time.sleep(_MARKER_REMOVAL_BACKOFF_SECONDS)
+ _OWN_STARTUP_MARKERS.extend(remaining)
+
+
+def _record_written_at(path: Path) -> float:
+ """When *path* was last written, or 0.0 when the filesystem will not say.
+
+ 0.0 makes an unreadable time the oldest possible, so it never wins the
+ "which statement about this PID came last" comparison below.
+ """
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+
+def _timed_records() -> "list[tuple[tuple[int, float | None, str | None], float]]":
+ """Every startup marker and per-port record, each with its write time."""
+ paths: "list[Path]" = []
+ for pattern in (STARTUP_MARKER_GLOB, PID_FILE_GLOB):
+ try:
+ paths.extend(_studio_root().glob(pattern))
+ except OSError:
+ continue
+ found = []
+ for path in paths:
+ record = _read_pid_record(path)
+ if record is not None:
+ found.append((record, _record_written_at(path)))
+ return found
+
+
+def _legacy_record() -> "tuple[tuple[int, float | None, str | None], float] | None":
+ try:
+ if not _PID_FILE.is_file():
+ return None
+ except OSError:
+ return None
+ record = _read_pid_record(_PID_FILE)
+ return None if record is None else (record, _record_written_at(_PID_FILE))
+
+
+def _sibling_is_running(pid: int) -> bool:
+ """Alive, and not an exited process nobody waited on.
+
+ A zombie answers kill(0) and keeps its start time, so on its own liveness
+ reads it as a serving backend. Under a non-reaping parent (PID 1 in some
+ containers) it can stay that way indefinitely, and a record pointing at one
+ would pin the compiled cache on every later startup.
+ """
+ if not _pid_alive(pid):
+ return False
+ try:
+ from utils.process_lifetime import _pid_is_zombie
+ except Exception: # noqa: BLE001
+ # The check is an exclusion, so without it this behaves as it did
+ # before: alive is alive.
+ return True
+ return not _pid_is_zombie(pid)
+
+
+def _live_sibling(records: "list", me: int, timed: "list") -> "int | None":
+ for entry in records:
+ if entry is None:
+ continue
+ record, written_at = entry
+ pid, created, _address = record
+ if pid == me or not _sibling_is_running(pid):
+ continue
+ # Corroborate against other records for this PID, the way
+ # _legacy_studio_on_port does. studio.pid holds a bare PID with no start
+ # time, and an untimed record is trusted unconditionally, so on its own
+ # it would resurrect a server that died and had its PID reused -- and
+ # keep the compiled cache forever on the strength of it. A timestamped
+ # record for the same PID that fails the check is evidence it is gone.
+ #
+ # Only a record written no earlier than this one counts as that
+ # evidence. A pre-upgrade backend writes a bare studio.pid and nothing
+ # else, so if it starts on a PID a crashed current-version backend left
+ # a timestamped record for, the older timestamp is a statement about a
+ # process that is gone, not about this one. Letting it veto would clear
+ # the compiled cache under a serving legacy backend.
+ corroborating = [
+ other[1]
+ for other, other_written in timed
+ if other[0] == pid and other_written >= written_at
+ ]
+ if _pid_is_studio_backend(pid, [created] + corroborating):
+ return pid
+ return None
+
+
+def live_sibling_backend() -> "int | None":
+ """PID of another live Studio backend of this install, or None.
+
+ Two of ours at once is a supported configuration: `_resolve_port` refuses
+ only the port one of ours already holds, and `_abort_already_running` tells
+ the user to pick another. They share an install-tree compiled cache, so the
+ second one must not wipe it out from under the first.
+
+ All three records are read, because a sibling can be in a state where only
+ one of them exists: a startup marker while it is still binding, a per-port
+ record once it has bound, and `studio.pid` alone for a pre-upgrade server or
+ one whose best-effort per-port write failed.
+
+ Called before `_write_pid_file`, so our own record is not there yet; the
+ explicit pid check keeps it correct for the marker, which is.
+ """
+ me = os.getpid()
+ timed = _timed_records()
+ return _live_sibling(timed + [_legacy_record()], me, timed)
+
+
def _per_port_records() -> "list[tuple[int, float | None, str | None] | None]":
try:
return [_read_pid_record(p) for p in _studio_root().glob(PID_FILE_GLOB)]
@@ -1106,10 +1359,17 @@ def _legacy_heir() -> "int | None":
def _remove_pid_file():
- """Remove the PID files that belong to this process.
+ """Remove the records that belong to this process.
_PID_FILE is checked even when the per-port record was never written, since
_write_pid_file writes the two independently.
+
+ The startup marker is deliberately NOT dropped here. _graceful_shutdown
+ calls this before the server thread is joined, and a backend that is still
+ finishing an in-flight request or a background warm is still importing from
+ the cache; going invisible there would let a replacement clear it underneath.
+ The marker goes when the server thread actually ends, and from the atexit
+ hook if the process exits first.
"""
# Nothing here may raise: _graceful_shutdown calls this at the end, and an
# unreadable or undeletable record must not abandon the rest of the exit
@@ -1876,6 +2136,41 @@ _PARALLEL_MAX = 64
_PARALLEL_DEFAULT_PLAIN = 4
+def _drops_its_marker_on_failure(start):
+ """Take the startup marker back if the server never starts.
+
+ An embedded caller keeps its process alive across a failure -- colab.py
+ catches SystemExit and Exception around run_server -- and no exit hook runs
+ then. A marker left behind would answer every later sibling probe as a live
+ backend, so no backend of this install would clear the compiled cache again.
+
+ A decorator rather than a renamed inner function: run_server's signature is
+ a contract here, read both by inspect.signature and by tests that parse the
+ def out of this file, and functools.wraps keeps both intact.
+ """
+ import functools
+
+ @functools.wraps(start)
+ def started(*args, **kwargs):
+ try:
+ return start(*args, **kwargs)
+ except BaseException:
+ # Only when no server thread is left running. A KeyboardInterrupt
+ # during the readiness wait asks uvicorn to stop and re-raises
+ # without joining, so the thread may still be finishing lifespan
+ # startup or shutdown. Taking the marker back there makes a backend
+ # that is still up invisible to a sibling, which would then clear
+ # the compiled cache under it. That thread's own finally removes
+ # the marker at the point it has genuinely stopped serving.
+ thread = _server_thread
+ if thread is None or not thread.is_alive():
+ _remove_startup_marker()
+ raise
+
+ return started
+
+
+@_drops_its_marker_on_failure
def run_server(
host: str = "127.0.0.1",
port: int = 8888,
@@ -2007,8 +2302,29 @@ def run_server(
import_started = time.perf_counter()
+ # Before the import, not just before uvicorn: this is what makes us visible
+ # to a sibling's own probe, and the earlier it lands the smaller the window
+ # in which two launches can each believe they are alone.
+ #
+ # The cache env has to be seeded first. main.py pins UNSLOTH_COMPILE_LOCATION
+ # at import time, which is after this point, and that variable is part of the
+ # coordination key: publishing before it is set would key the marker and the
+ # lock differently from the clear that follows, and serialize nothing.
+ try:
+ from utils.paths.storage_roots import setup_cache_env
+ setup_cache_env()
+ except Exception: # noqa: BLE001
+ # main.py seeds it too, and does not depend on this having worked.
+ pass
+ write_startup_marker()
+
from main import app, setup_frontend, _desktop_owner, _IS_COLAB
+ # Handed to lifespan as a callable, not a value: it is asked again at
+ # shutdown, when a sibling may have started since. On app.state rather than
+ # imported, because main.py must not import this module back.
+ app.state.live_sibling_backend = live_sibling_backend
+
logger.info(
"Imported FastAPI app in %.1fms",
(time.perf_counter() - import_started) * 1000,
@@ -2250,6 +2566,14 @@ def run_server(
loop.close()
if not ready_event.is_set():
startup_failed.set()
+ # An embedded host stays alive after the server thread ends, and a
+ # post-readiness failure in here never reaches run_server's caller,
+ # so nothing else takes these back. They would keep validating
+ # against the still-live host PID with no backend serving. This is
+ # also the point at which the backend has genuinely stopped serving,
+ # which is why the marker goes here rather than in _remove_pid_file.
+ _remove_startup_marker()
+ _remove_pid_file()
thread = Thread(target = _run, daemon = True)
_server_thread = thread
diff --git a/studio/backend/tests/test_studio_pid_files.py b/studio/backend/tests/test_studio_pid_files.py
index df2c8e87f87..827d270fd08 100644
--- a/studio/backend/tests/test_studio_pid_files.py
+++ b/studio/backend/tests/test_studio_pid_files.py
@@ -8,7 +8,11 @@ Imports run.py directly, so run under the Unsloth venv.
from __future__ import annotations
+import contextlib
+import errno
import os
+import threading
+import time
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -20,6 +24,7 @@ if str(_BACKEND) not in sys.path:
sys.path.insert(0, str(_BACKEND))
import run # noqa: E402
+from utils import cache_cleanup # noqa: E402
# Captured before the autouse fixture stubs them, for the tests that exercise them.
_REAL_IS_STUDIO_BACKEND = run._pid_is_studio_backend
@@ -33,6 +38,11 @@ def isolated_root(tmp_path, monkeypatch):
monkeypatch.setattr(run, "_OWN_PID_FILE", None)
monkeypatch.setattr(run, "_pid_alive", lambda pid: True)
monkeypatch.setattr(run, "_pid_is_studio_backend", lambda pid, created_times = (): True)
+ # The lock lives in the studio home. A session-scoped conftest fixture
+ # already keeps that out of the developer's real one, but this file
+ # redirects everything else it touches to tmp_path, so redirect this too.
+ monkeypatch.setattr(cache_cleanup, "cache_coordination_dir", lambda: tmp_path)
+ monkeypatch.setattr(run, "_OWN_STARTUP_MARKERS", [])
yield
@@ -566,3 +576,604 @@ def test_the_legacy_file_is_taken_over_from_a_dead_server(tmp_path, monkeypatch)
run._write_pid_file(8902, "127.0.0.1")
assert (tmp_path / "studio.pid").read_text(encoding = "utf-8") == str(os.getpid())
+
+
+def test_a_live_sibling_is_found_so_the_shared_cache_survives(tmp_path):
+ # The compiled cache is install-tree relative, so a second backend of this
+ # install must not wipe it out from under the first.
+ (tmp_path / "studio-8888-8550.pid").write_text("8550\n\n127.0.0.1", encoding = "utf-8")
+
+ assert run.live_sibling_backend() == 8550
+
+
+def test_our_own_record_is_not_a_sibling(tmp_path):
+ # _write_pid_file has already run by shutdown, so our own record is there.
+ me = os.getpid()
+ (tmp_path / f"studio-8888-{me}.pid").write_text(f"{me}\n\n127.0.0.1", encoding = "utf-8")
+
+ assert run.live_sibling_backend() is None
+
+
+def test_a_dead_record_is_not_a_sibling(tmp_path, monkeypatch):
+ # A crashed server leaves its record behind; clearing the cache is right then.
+ monkeypatch.setattr(run, "_pid_alive", lambda pid: False)
+ (tmp_path / "studio-8888-8550.pid").write_text("8550\n\n127.0.0.1", encoding = "utf-8")
+
+ assert run.live_sibling_backend() is None
+
+
+def test_a_reused_pid_is_not_a_sibling(tmp_path, monkeypatch):
+ # Alive, but not our server: the create_time no longer matches the record.
+ monkeypatch.setattr(run, "_pid_is_studio_backend", lambda pid, created_times = (): False)
+ (tmp_path / "studio-8888-8550.pid").write_text("8550\n1.0\n127.0.0.1", encoding = "utf-8")
+
+ assert run.live_sibling_backend() is None
+
+
+def test_a_sibling_that_is_still_binding_is_found(tmp_path):
+ # The window Codex flagged: lifespan startup runs, and would clear the
+ # cache, long before uvicorn reports a port for _write_pid_file to record.
+ (tmp_path / "studio-starting-8550.marker").write_text("8550\n", encoding = "utf-8")
+
+ assert run.live_sibling_backend() == 8550
+
+
+def test_a_legacy_only_sibling_is_found(tmp_path):
+ # A pre-upgrade server is recorded here and nowhere else, and so is one
+ # whose best-effort per-port write failed.
+ (tmp_path / "studio.pid").write_text("8550", encoding = "utf-8")
+
+ assert run.live_sibling_backend() == 8550
+
+
+def test_a_dead_legacy_record_is_not_a_sibling(tmp_path, monkeypatch):
+ monkeypatch.setattr(run, "_pid_alive", lambda pid: False)
+ (tmp_path / "studio.pid").write_text("8550", encoding = "utf-8")
+
+ assert run.live_sibling_backend() is None
+
+
+def test_the_startup_marker_is_written_and_removed(tmp_path):
+ run.write_startup_marker()
+ marker = tmp_path / f"studio-starting-{os.getpid()}.marker"
+
+ assert marker.is_file()
+ # Parsed by the same reader as a per-port record, with a real start time.
+ record = run._read_pid_record(marker)
+ assert record is not None and record[0] == os.getpid()
+
+ run._remove_startup_marker()
+
+ assert not marker.exists()
+ assert run._OWN_STARTUP_MARKERS == []
+
+
+def test_our_own_startup_marker_is_not_a_sibling(tmp_path):
+ run.write_startup_marker()
+
+ assert run.live_sibling_backend() is None
+
+ run._remove_startup_marker()
+
+
+def test_a_startup_marker_is_invisible_to_the_pid_file_glob(tmp_path):
+ # Everything reading PID_FILE_GLOB expects a port in the name; a process
+ # that has not bound yet has none, so `stop` and _legacy_heir must skip it.
+ (tmp_path / "studio-starting-8550.marker").write_text("8550\n", encoding = "utf-8")
+
+ assert list(tmp_path.glob(run.PID_FILE_GLOB)) == []
+
+
+def test_the_marker_outlives_the_early_record_drop(tmp_path):
+ # _graceful_shutdown drops the records before the server thread is joined,
+ # while an in-flight request or a background warm may still be importing
+ # from the cache. Going invisible there would let a replacement clear it
+ # underneath, so the marker waits for the thread to actually end.
+ run.write_startup_marker()
+ marker = tmp_path / f"studio-starting-{os.getpid()}.marker"
+ run._write_pid_file(8906, "127.0.0.1")
+
+ run._remove_pid_file()
+
+ assert marker.is_file(), "the backend is still serving until the thread ends"
+ assert _files(tmp_path) == []
+
+ run._remove_startup_marker()
+
+ assert not marker.exists()
+
+
+def test_a_bare_legacy_record_cannot_resurrect_a_reused_pid(tmp_path, monkeypatch):
+ # studio.pid holds a PID and no start time, and an untimed record is trusted
+ # unconditionally. A timestamped record for that same PID, written after it,
+ # is proof the server is gone, so the bare one must not override it.
+ monkeypatch.setattr(run, "_pid_is_studio_backend", _REAL_IS_STUDIO_BACKEND)
+ monkeypatch.setattr(run, "_process_create_time", lambda pid: 999.0)
+ legacy = tmp_path / "studio.pid"
+ timed = tmp_path / "studio-8888-8550.pid"
+ legacy.write_text("8550", encoding = "utf-8")
+ timed.write_text("8550\n111.5\n127.0.0.1", encoding = "utf-8")
+ os.utime(legacy, (100.0, 100.0))
+ os.utime(timed, (200.0, 200.0))
+
+ assert run.live_sibling_backend() is None
+
+
+def test_an_older_timed_record_does_not_veto_a_newer_legacy_one(tmp_path, monkeypatch):
+ # The other order is a pre-upgrade backend starting on a PID a crashed
+ # current-version backend left a record for: it writes studio.pid and
+ # nothing else. The older timestamp describes the process that is gone, so
+ # letting it veto would clear the compiled cache under a serving backend.
+ monkeypatch.setattr(run, "_pid_is_studio_backend", _REAL_IS_STUDIO_BACKEND)
+ monkeypatch.setattr(run, "_process_create_time", lambda pid: 999.0)
+ legacy = tmp_path / "studio.pid"
+ timed = tmp_path / "studio-8888-8550.pid"
+ timed.write_text("8550\n111.5\n127.0.0.1", encoding = "utf-8")
+ legacy.write_text("8550", encoding = "utf-8")
+ os.utime(timed, (100.0, 100.0))
+ os.utime(legacy, (200.0, 200.0))
+
+ assert run.live_sibling_backend() == 8550
+
+
+def test_a_timed_record_for_another_pid_leaves_the_legacy_one_alone(tmp_path, monkeypatch):
+ # Corroboration is per PID: a dead record for a different server says nothing
+ # about the pre-upgrade one, which is recorded in studio.pid and nowhere else.
+ monkeypatch.setattr(run, "_pid_is_studio_backend", _REAL_IS_STUDIO_BACKEND)
+ monkeypatch.setattr(run, "_process_create_time", lambda pid: 999.0)
+ (tmp_path / "studio-8888-8551.pid").write_text("8551\n111.5\n127.0.0.1", encoding = "utf-8")
+ (tmp_path / "studio.pid").write_text("8550", encoding = "utf-8")
+
+ assert run.live_sibling_backend() == 8550
+
+
+def test_the_cache_lock_is_exclusive(tmp_path):
+ # Two backends racing is the whole point, so the second one must be told the
+ # section is taken rather than be let into it.
+ with cache_cleanup.compiled_cache_lock() as first:
+ assert first == cache_cleanup.LOCK_HELD
+ with cache_cleanup.compiled_cache_lock(timeout = 0.05) as second:
+ assert second == cache_cleanup.LOCK_BUSY
+
+ with cache_cleanup.compiled_cache_lock() as again:
+ assert again == cache_cleanup.LOCK_HELD
+
+
+def test_the_probe_and_the_clear_happen_inside_one_lock(tmp_path, monkeypatch):
+ # The race Codex flagged: our probe finds nobody, a sibling publishes and
+ # starts compiling, and then our rmtree deletes what it just wrote.
+ events = []
+
+ @contextlib.contextmanager
+ def _lock(timeout = None):
+ events.append("lock")
+ try:
+ yield cache_cleanup.LOCK_HELD
+ finally:
+ events.append("unlock")
+
+ monkeypatch.setattr(cache_cleanup, "compiled_cache_lock", _lock)
+ monkeypatch.setattr(
+ cache_cleanup, "clear_unsloth_compiled_cache", lambda *a, **k: events.append("clear")
+ )
+
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: events.append("probe"))
+
+ assert events == ["lock", "probe", "clear", "unlock"]
+
+
+def test_a_busy_cache_lock_keeps_the_cache_without_probing(tmp_path, monkeypatch):
+ # Whoever holds it is a sibling by definition, so the answer is already known.
+ events = []
+
+ @contextlib.contextmanager
+ def _lock(timeout = None):
+ yield cache_cleanup.LOCK_BUSY
+
+ monkeypatch.setattr(cache_cleanup, "compiled_cache_lock", _lock)
+ monkeypatch.setattr(
+ cache_cleanup, "clear_unsloth_compiled_cache", lambda *a, **k: events.append("clear")
+ )
+
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: events.append("probe"))
+
+ assert events == []
+
+
+def test_a_lock_that_cannot_be_taken_at_all_still_clears(tmp_path, monkeypatch):
+ # An unwritable temp dir or a filesystem without flock must not mean the
+ # cache is never cleared again on that machine; fall back to the plain probe.
+ blocked = tmp_path / "not-a-directory"
+ blocked.write_text("", encoding = "utf-8")
+ monkeypatch.setattr(cache_cleanup, "cache_coordination_dir", lambda: blocked / "lock")
+ events = []
+ monkeypatch.setattr(
+ cache_cleanup, "clear_unsloth_compiled_cache", lambda *a, **k: events.append("clear")
+ )
+
+ with cache_cleanup.compiled_cache_lock() as state:
+ assert state == cache_cleanup.LOCK_UNAVAILABLE
+
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: None)
+
+ assert events == ["clear"]
+
+
+def test_a_live_sibling_keeps_the_compiled_cache(tmp_path, monkeypatch):
+ events = []
+ monkeypatch.setattr(
+ cache_cleanup, "clear_unsloth_compiled_cache", lambda *a, **k: events.append("clear")
+ )
+
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: 8550)
+
+ assert events == []
+
+
+def test_no_sibling_probe_clears_unconditionally(tmp_path, monkeypatch):
+ # An embedded app or a test never sets the probe, and the old behaviour stands.
+ events = []
+ monkeypatch.setattr(
+ cache_cleanup, "clear_unsloth_compiled_cache", lambda *a, **k: events.append("clear")
+ )
+
+ cache_cleanup.clear_compiled_cache_unless_shared(None)
+
+ assert events == ["clear"]
+
+
+def test_the_startup_marker_is_published_under_the_cache_lock(tmp_path, monkeypatch):
+ # Publication has to be inside the same section as a sibling's probe and
+ # clear, or the marker lands in the gap between them and is clear-and-lost.
+ marker = tmp_path / f"studio-starting-{os.getpid()}.marker"
+ events = []
+
+ @contextlib.contextmanager
+ def _lock(timeout = None):
+ events.append(("lock", marker.exists()))
+ try:
+ yield cache_cleanup.LOCK_HELD
+ finally:
+ events.append(("unlock", marker.exists()))
+
+ monkeypatch.setattr(cache_cleanup, "compiled_cache_lock", _lock)
+
+ run.write_startup_marker()
+
+ assert events == [("lock", False), ("unlock", True)]
+
+
+def test_a_zombie_backend_is_not_a_live_sibling(tmp_path, monkeypatch):
+ # A backend that exited under a non-reaping parent stays a zombie: it
+ # answers kill(0) and keeps its start time, so liveness alone reads it as
+ # serving and its record would pin the compiled cache forever.
+ (tmp_path / "studio-8888-4242.pid").write_text("4242\n111.5\n127.0.0.1", encoding = "utf-8")
+
+ monkeypatch.setattr(run, "_pid_alive", lambda pid: True)
+ assert run.live_sibling_backend() == 4242, "the check under test must start from live"
+
+ import utils.process_lifetime as process_lifetime
+
+ monkeypatch.setattr(process_lifetime, "_pid_is_zombie", lambda pid: pid == 4242)
+
+ assert run.live_sibling_backend() is None
+
+
+def test_a_real_unreaped_child_is_not_a_live_sibling(tmp_path):
+ # The same thing without a patch: a killed but unwaited child.
+ import subprocess
+ import sys
+
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ child.kill()
+ (tmp_path / f"studio-8889-{child.pid}.pid").write_text(f"{child.pid}\n", encoding = "utf-8")
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ if run.live_sibling_backend() is None:
+ break
+ time.sleep(0.05)
+
+ assert run.live_sibling_backend() is None, "a zombie was taken for a serving backend"
+ finally:
+ child.wait()
+
+
+def test_every_record_call_can_be_repeated(tmp_path):
+ # Startup and shutdown both run more than once in a long-lived embedded
+ # host, and a crash can leave either half done. Each of these has to be
+ # safe to call again on the state the previous call left.
+ run.write_startup_marker()
+ marker = tmp_path / f"studio-starting-{os.getpid()}.marker"
+ published = sorted(p.name for p in tmp_path.iterdir())
+ body = marker.read_text(encoding = "utf-8")
+
+ run.write_startup_marker()
+
+ assert sorted(p.name for p in tmp_path.iterdir()) == published, "a second publish added a file"
+ assert marker.read_text(encoding = "utf-8") == body
+ assert run._OWN_STARTUP_MARKERS == [marker], "tracked twice would be removed twice"
+
+ run._write_pid_file(8888, "127.0.0.1")
+ recorded = sorted(p.name for p in tmp_path.iterdir())
+ run._write_pid_file(8888, "127.0.0.1")
+
+ assert sorted(p.name for p in tmp_path.iterdir()) == recorded
+
+ run._remove_startup_marker()
+ run._remove_startup_marker()
+ run._remove_pid_file()
+ run._remove_pid_file()
+
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) == []
+ assert _files(tmp_path) == []
+ assert run._OWN_STARTUP_MARKERS == []
+
+
+def test_reading_the_siblings_changes_nothing_on_disk(tmp_path):
+ # The probe runs on every startup and is a read. If it pruned or rewrote
+ # anything, one install's startup would edit another's records.
+ (tmp_path / "studio-8888-4242.pid").write_text("4242\n111.5\n127.0.0.1", encoding = "utf-8")
+ (tmp_path / "studio.pid").write_text("4243", encoding = "utf-8")
+ before = {p.name: p.read_text(encoding = "utf-8") for p in tmp_path.iterdir()}
+
+ for _ in range(3):
+ run.live_sibling_backend()
+
+ assert {p.name: p.read_text(encoding = "utf-8") for p in tmp_path.iterdir()} == before
+
+
+def test_a_busy_lock_publishes_then_waits_for_the_clear_to_finish(tmp_path, monkeypatch):
+ # Publishing unlocked keeps this backend visible to sibling probes, but
+ # returning straight away would let the caller import and compile into a
+ # cache the holder is still deleting. The marker goes out first, then the
+ # wait, so both halves hold.
+ marker = tmp_path / f"studio-starting-{os.getpid()}.marker"
+ timeouts = []
+
+ @contextlib.contextmanager
+ def _lock(timeout = None):
+ timeouts.append((timeout, marker.exists()))
+ # Busy the first time (the publish), free the second (the wait).
+ yield cache_cleanup.LOCK_BUSY if len(timeouts) == 1 else cache_cleanup.LOCK_HELD
+
+ monkeypatch.setattr(cache_cleanup, "compiled_cache_lock", _lock)
+
+ run.write_startup_marker()
+
+ assert timeouts == [
+ (30.0, False),
+ (run._CACHE_CLEAR_WAIT_SECONDS, True),
+ ], "the wait must come after the marker is on disk"
+
+
+def test_a_lock_taken_at_once_does_not_wait(tmp_path, monkeypatch):
+ # Nobody is clearing, so there is nothing to wait for.
+ calls = []
+
+ @contextlib.contextmanager
+ def _lock(timeout = None):
+ calls.append(timeout)
+ yield cache_cleanup.LOCK_HELD
+
+ monkeypatch.setattr(cache_cleanup, "compiled_cache_lock", _lock)
+
+ run.write_startup_marker()
+
+ assert calls == [30.0]
+
+
+def test_a_clear_that_never_finishes_still_lets_the_backend_start(tmp_path, monkeypatch):
+ # Refusing to start is worse for the user than starting on a cache that may
+ # lose files, so the wait is bounded and startup continues past it.
+ @contextlib.contextmanager
+ def _lock(timeout = None):
+ yield cache_cleanup.LOCK_BUSY
+
+ monkeypatch.setattr(cache_cleanup, "compiled_cache_lock", _lock)
+ monkeypatch.setattr(run, "_CACHE_CLEAR_WAIT_SECONDS", 0.0)
+
+ run.write_startup_marker()
+
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) != []
+
+
+def test_a_filesystem_that_cannot_lock_is_not_read_as_contention(tmp_path, monkeypatch):
+ # ENOSYS is the lock being unsupported, not a sibling holding it. Retrying it
+ # to a timeout and answering busy would keep the cache forever, since busy is
+ # read as proof of a sibling.
+ def unsupported(fd):
+ raise OSError(errno.ENOSYS, "flock not supported")
+
+ monkeypatch.setattr(cache_cleanup, "_try_lock", unsupported)
+ events = []
+ monkeypatch.setattr(
+ cache_cleanup, "clear_unsloth_compiled_cache", lambda *a, **k: events.append("clear")
+ )
+
+ with cache_cleanup.compiled_cache_lock(timeout = 30.0) as state:
+ assert state == cache_cleanup.LOCK_UNAVAILABLE
+
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: None)
+
+ assert events == ["clear"]
+
+
+def test_contention_is_still_retried_to_the_timeout(tmp_path, monkeypatch):
+ def busy(fd):
+ raise OSError(errno.EWOULDBLOCK, "held")
+
+ monkeypatch.setattr(cache_cleanup, "_try_lock", busy)
+
+ started = time.monotonic()
+ with cache_cleanup.compiled_cache_lock(timeout = 0.2) as state:
+ assert state == cache_cleanup.LOCK_BUSY
+ assert time.monotonic() - started >= 0.2, "contention waits out the budget"
+
+
+def test_a_startup_that_raises_takes_its_marker_back(tmp_path, monkeypatch):
+ # colab.py catches SystemExit and Exception around run_server and keeps the
+ # process alive, so no exit hook runs. A marker left behind would answer
+ # every later probe as a live backend of this install.
+ run.write_startup_marker()
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) != []
+
+ def explode(*args, **kwargs):
+ raise RuntimeError("startup failed")
+
+ monkeypatch.setattr(run, "run_server", run._drops_its_marker_on_failure(explode))
+
+ with pytest.raises(RuntimeError):
+ run.run_server()
+
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) == []
+ assert run._OWN_STARTUP_MARKERS == []
+
+
+def test_a_startup_that_exits_takes_its_marker_back(tmp_path, monkeypatch):
+ # SystemExit is a BaseException, and it is the one colab.py catches.
+ run.write_startup_marker()
+
+ def bail(*args, **kwargs):
+ raise SystemExit(1)
+
+ monkeypatch.setattr(run, "run_server", run._drops_its_marker_on_failure(bail))
+
+ with pytest.raises(SystemExit):
+ run.run_server()
+
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) == []
+
+
+def test_an_interrupt_leaves_the_marker_to_a_live_server_thread(tmp_path, monkeypatch):
+ # The KeyboardInterrupt path asks uvicorn to stop and re-raises without
+ # joining, so the thread may still be finishing lifespan startup or
+ # shutdown. Taking the marker back there makes a backend that is still up
+ # invisible to a sibling, which would clear the compiled cache under it.
+ run.write_startup_marker()
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) != []
+
+ stop = threading.Event()
+ serving = threading.Thread(target = stop.wait, daemon = True)
+ serving.start()
+ monkeypatch.setattr(run, "_server_thread", serving)
+
+ def interrupt(*args, **kwargs):
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(run, "run_server", run._drops_its_marker_on_failure(interrupt))
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ run.run_server()
+
+ assert (
+ list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) != []
+ ), "the sibling can no longer see it"
+ assert run._OWN_STARTUP_MARKERS != []
+ finally:
+ stop.set()
+ serving.join(timeout = 5)
+
+ # Once that thread is gone, the same failure does take the marker back:
+ # nothing else is going to.
+ with pytest.raises(KeyboardInterrupt):
+ run.run_server()
+
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) == []
+
+
+def test_a_server_thread_that_dies_after_readiness_drops_its_records(tmp_path, monkeypatch):
+ # An embedded host stays alive after the uvicorn thread ends, and a failure
+ # in there never reaches run_server's caller. Records left behind would keep
+ # validating against the still-live host PID with no backend serving. Both
+ # calls are what the thread's finally block makes.
+ run.write_startup_marker()
+ run._write_pid_file(8905, "127.0.0.1")
+
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) != []
+ assert _files(tmp_path) != []
+
+ run._remove_startup_marker()
+ run._remove_pid_file()
+
+ assert list(tmp_path.glob(run.STARTUP_MARKER_GLOB)) == []
+ assert _files(tmp_path) == []
+
+
+def test_two_cold_starts_keep_rather_than_delete_each_others_modules(tmp_path, monkeypatch):
+ # The documented limitation of scoping this back: both keep a cache neither
+ # cleaned, which is the safe direction. The failure being replaced is the two
+ # of them deleting each other's modules mid-run.
+ events = []
+ monkeypatch.setattr(
+ cache_cleanup, "clear_unsloth_compiled_cache", lambda *a, **k: events.append("clear")
+ )
+
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: 8550)
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: 8551)
+
+ assert events == []
+
+ # ...and a launch that really is alone still clears.
+ cache_cleanup.clear_compiled_cache_unless_shared(lambda: None)
+
+ assert events == ["clear"]
+
+
+def test_a_transient_unlink_failure_is_retried_on_the_spot(tmp_path, monkeypatch):
+ # A holder that lets go a moment later (an indexer on Windows) must not cost
+ # the marker its removal: waiting for the atexit hook leaves it on disk, and
+ # an embedded host that outlives the backend may not reach that for hours.
+ run.write_startup_marker()
+ marker = tmp_path / f"studio-starting-{os.getpid()}.marker"
+ assert run._OWN_STARTUP_MARKERS == [marker]
+
+ real_unlink = Path.unlink
+ refused = []
+
+ def refuse_once(self, missing_ok = False):
+ if not refused:
+ refused.append(self)
+ raise OSError("busy")
+ return real_unlink(self, missing_ok = missing_ok)
+
+ monkeypatch.setattr(Path, "unlink", refuse_once)
+ monkeypatch.setattr(run, "_MARKER_REMOVAL_BACKOFF_SECONDS", 0.0)
+ run._remove_startup_marker()
+
+ assert refused, "the first attempt did not run"
+ assert run._OWN_STARTUP_MARKERS == []
+ assert not marker.exists()
+
+
+def test_a_marker_that_will_not_delete_stays_retryable(tmp_path, monkeypatch):
+ # Once the retries run out, dropping the path loses the only reference to
+ # it. The marker would stay on disk, keep matching this live process, and
+ # pin the compiled cache with no later cleanup able to retry.
+ run.write_startup_marker()
+ marker = tmp_path / f"studio-starting-{os.getpid()}.marker"
+ assert run._OWN_STARTUP_MARKERS == [marker]
+
+ real_unlink = Path.unlink
+ attempts = []
+
+ def refuse_while_locked(self, missing_ok = False):
+ attempts.append(self)
+ if locked:
+ raise OSError("busy")
+ return real_unlink(self, missing_ok = missing_ok)
+
+ locked = True
+ monkeypatch.setattr(Path, "unlink", refuse_while_locked)
+ monkeypatch.setattr(run, "_MARKER_REMOVAL_BACKOFF_SECONDS", 0.0)
+ run._remove_startup_marker()
+
+ assert len(attempts) == run._MARKER_REMOVAL_ATTEMPTS, "the retries did not run"
+ assert run._OWN_STARTUP_MARKERS == [marker], "still tracked for a retry"
+ assert marker.exists()
+
+ locked = False
+ run._remove_startup_marker()
+
+ assert run._OWN_STARTUP_MARKERS == []
+ assert not marker.exists()
diff --git a/studio/backend/utils/cache_cleanup.py b/studio/backend/utils/cache_cleanup.py
index 41f1ede863a..18bfbe77d39 100644
--- a/studio/backend/utils/cache_cleanup.py
+++ b/studio/backend/utils/cache_cleanup.py
@@ -9,6 +9,8 @@ selectively between model loads, preserving model-agnostic components (Trainers)
that spawned subprocesses need.
"""
+import contextlib
+import errno
import os
import shutil
import structlog
@@ -201,6 +203,167 @@ def register_compiled_cache_on_path() -> None:
os.environ["PYTHONPATH"] = os.pathsep.join(pypath_entries)
+def cache_coordination_dir() -> Path:
+ """Where backends of this install find each other.
+
+ The studio home, the same scope the startup markers use. Two backends of one
+ install share an install-tree compiled cache and that is the case this
+ coordinates; two SEPARATE installs pointed at one UNSLOTH_COMPILE_LOCATION
+ are not coordinated, and clearing is best effort there, as it was before.
+ """
+ from utils.paths.storage_roots import studio_root
+ return studio_root()
+
+
+# Held: we may probe and clear. Busy: someone else is in that critical section.
+# Unavailable: no lock could be taken at all (unwritable studio home, a
+# filesystem without flock), which must not mean "never clear the cache again",
+# so the caller falls back to the unserialized probe it did before this lock.
+LOCK_HELD = "held"
+LOCK_BUSY = "busy"
+LOCK_UNAVAILABLE = "unavailable"
+
+# Long enough to outlast a real clear (an rmtree of a few dozen files), short
+# enough that a wedged holder cannot stall lifespan startup behind it.
+_LOCK_TIMEOUT = 10.0
+
+
+# flock/msvcrt report contention through these; anything else (ENOSYS,
+# EOPNOTSUPP on a network mount) is the lock being unsupported, and retrying it
+# for ten seconds only to answer "busy" would pin the cache forever, since busy
+# is read as proof of a sibling.
+_CONTENTION_ERRNOS = frozenset(
+ code
+ for code in (
+ getattr(errno, "EACCES", None),
+ getattr(errno, "EAGAIN", None),
+ getattr(errno, "EWOULDBLOCK", None),
+ getattr(errno, "EDEADLOCK", None),
+ getattr(errno, "EDEADLK", None),
+ )
+ if code is not None
+)
+
+
+def _try_lock(fd: int) -> None:
+ if os.name == "nt":
+ import msvcrt
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+
+
+def _unlock(fd: int) -> None:
+ with contextlib.suppress(Exception):
+ if os.name == "nt":
+ import msvcrt
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ with contextlib.suppress(OSError):
+ os.close(fd)
+
+
+def compiled_cache_lock(timeout: float = _LOCK_TIMEOUT):
+ """Serialize a sibling probe plus cache clear against a sibling's publication.
+
+ Without it the probe is a check-then-act race with a real window: A probes and
+ finds nobody, B publishes its startup marker and begins compiling, A then
+ clears and deletes the modules B just wrote. Holding this across both halves
+ (the probe plus clear here, the marker write in run.py) closes it.
+
+ Never raises at the caller and never waits indefinitely: startup runs through
+ here, so a lock that cannot be taken has to degrade rather than block.
+ """
+ import time
+
+ try:
+ lock_dir = cache_coordination_dir()
+ lock_dir.mkdir(parents = True, exist_ok = True)
+ fd = os.open(str(lock_dir / "compiled-cache.lock"), os.O_CREAT | os.O_RDWR, 0o600)
+ except Exception as exc: # noqa: BLE001
+ # Resolving or opening it is part of taking it, so it degrades the same
+ # way rather than aborting a startup that only wanted to know about
+ # siblings.
+ logger.debug(f"Could not open the compiled-cache lock ({exc})")
+ yield LOCK_UNAVAILABLE
+ return
+
+ fds: "List[int]" = []
+ state = LOCK_HELD
+ deadline = time.monotonic() + timeout
+ try:
+ while True:
+ try:
+ _try_lock(fd)
+ fds.append(fd)
+ break
+ except OSError as exc:
+ if exc.errno not in _CONTENTION_ERRNOS:
+ # Not contention: the filesystem cannot lock at all.
+ logger.debug(f"Compiled-cache locking unavailable ({exc})")
+ with contextlib.suppress(OSError):
+ os.close(fd)
+ state = LOCK_UNAVAILABLE
+ break
+ if time.monotonic() >= deadline:
+ with contextlib.suppress(OSError):
+ os.close(fd)
+ state = LOCK_BUSY
+ break
+ time.sleep(0.05)
+ except Exception as exc: # noqa: BLE001
+ logger.debug(f"Compiled-cache locking unavailable ({exc})")
+ with contextlib.suppress(OSError):
+ os.close(fd)
+ state = LOCK_UNAVAILABLE
+ break
+ yield state
+ finally:
+ for fd in fds:
+ _unlock(fd)
+
+
+def clear_compiled_cache_unless_shared(sibling_probe = None) -> None:
+ """Clear the compiled cache, unless another backend of this install is live.
+
+ The cache sits in the install tree, not the studio home, so two of our own
+ backends share it and the wipe would delete modules the other one is still
+ importing -- including the Unsloth*Trainer.py that the in-process clears
+ preserve for spawn workers. run_server supplies the probe; without it (tests,
+ an embedded app) the old unconditional clear stands.
+
+ The probe and the clear run under `compiled_cache_lock` so a sibling cannot
+ publish itself in between and lose the modules it has already compiled.
+
+ Two launches that overlap from cold both keep a cache neither has cleaned,
+ so stale modules can survive until the next start that finds itself alone.
+ That is the deliberate direction: the failure this replaces was the two of
+ them deleting each other's modules mid-run.
+ """
+ if not callable(sibling_probe):
+ clear_unsloth_compiled_cache()
+ return
+ with compiled_cache_lock() as lock_state:
+ if lock_state == LOCK_BUSY:
+ # Somebody is inside the critical section, so there is a sibling by
+ # definition; that is already the answer, no probe needed.
+ logger.info(
+ "Keeping the compiled cache: another backend of this install holds the cache lock"
+ )
+ return
+ sibling = sibling_probe()
+ if sibling is None:
+ clear_unsloth_compiled_cache()
+ return
+ logger.info(
+ f"Keeping the compiled cache: another backend of this install is live (PID {sibling})"
+ )
+
+
def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None) -> None:
"""
Remove compiled files from the cache directory (idempotent).