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.

Repair .venv_t5_* sidecars whose files are damaged (#7725)

Daniel Han8f7374ec301f
diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.py
index 839380b6df5..33f9273b2d8 100644
--- a/studio/backend/tests/test_transformers_version.py
+++ b/studio/backend/tests/test_transformers_version.py
@@ -59,6 +59,7 @@ from utils.transformers_version import (
get_transformers_tier,
activate_transformers_for_subprocess,
_venv_dir_is_valid,
+ _venv_dir_is_valid_and_undamaged,
_ensure_venv_dir,
hf_endpoint_unreachable,
)
@@ -1800,6 +1801,222 @@ class TestVenvDirIsValidLogging:
], "no warning expected when the installed version matches"
+# ---------------------------------------------------------------------------
+# _venv_dir_is_valid_and_undamaged — issue #7715
+# A sidecar whose METADATA survived a disk-full or an interrupted pip passes
+# every package-level check, so the wipe-and-reinstall in _ensure_venv_dir
+# never fires and the worker dies importing transformers instead.
+# ---------------------------------------------------------------------------
+
+
+class TestVenvDirFileIntegrity:
+ def _make_venv(
+ self,
+ venv_dir: Path,
+ pkg: str = "transformers",
+ version: str = "5.3.0",
+ files: dict | None = None,
+ record_extra: list | None = None,
+ ) -> Path:
+ """Fake target-dir install of *pkg* with a RECORD matching what it wrote."""
+ di = venv_dir / f"{pkg}-{version}.dist-info"
+ di.mkdir(parents = True)
+ (di / "METADATA").write_text(f"Name: {pkg}\nVersion: {version}\n")
+ files = files if files is not None else {f"{pkg}/__init__.py": "x" * 40}
+ rows = []
+ for rel, body in files.items():
+ path = venv_dir / rel
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text(body)
+ rows.append(f"{rel},sha256=deadbeef,{len(body)}")
+ rows.extend(record_extra or [])
+ # pip records its own metadata with a blank size, as real wheels do.
+ rows.append(f"{pkg}-{version}.dist-info/METADATA,sha256=cafe,")
+ rows.append(f"{pkg}-{version}.dist-info/RECORD,,")
+ (di / "RECORD").write_text("\n".join(rows) + "\n")
+ return venv_dir
+
+ def test_intact_sidecar_is_valid(self, tmp_path: Path):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_truncated_file_is_detected(self, tmp_path: Path, caplog):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers" / "__init__.py").write_text("x") # disk-full shape
+
+ caplog.set_level(logging.INFO)
+ result = _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ assert result is False, "a truncated file must force the wipe-and-reinstall"
+ joined = " ".join(r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING)
+ assert "transformers/__init__.py" in joined, f"damage not named in the log: {joined!r}"
+
+ def test_deleted_file_is_detected(self, tmp_path: Path):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers" / "__init__.py").unlink()
+ assert not _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_damage_in_an_unpinned_dependency_is_detected(self, tmp_path: Path):
+ """The whole dir is prepended to sys.path, so a shadowing dep breaks the
+ import just as surely as transformers itself."""
+ venv_dir = self._make_venv(tmp_path / "venv")
+ self._make_venv(venv_dir, pkg = "regex", version = "2026.7.19")
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+ (venv_dir / "regex" / "__init__.py").write_text("")
+ assert not _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_console_script_rows_are_ignored(self, tmp_path: Path):
+ """pip --target records scripts at a path that cannot resolve.
+
+ pip installs through a temporary normal-scheme prefix and writes RECORD
+ before flattening, so a healthy sidecar records ../../bin/hf while the
+ file lands in <target>/bin. Believing those rows fails CLOSED on a
+ healthy install, and since the repair reinstalls with the same pip it
+ would wipe and re-download several hundred MB on every activation,
+ forever.
+ """
+ venv_dir = self._make_venv(
+ tmp_path / "venv",
+ record_extra = [
+ "../../bin/hf,sha256=deadbeef,343",
+ "../../Scripts/hf.exe,sha256=deadbeef,343",
+ ],
+ )
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_in_target_script_rows_are_ignored(self, tmp_path: Path):
+ """uv records bin/hf, which does resolve -- but pip --upgrade rmtree's a
+ colliding directory in the target, so a later install into the same
+ sidecar deletes an earlier package's scripts. Nothing imports from
+ there, so the row carries no signal either way."""
+ venv_dir = self._make_venv(
+ tmp_path / "venv",
+ record_extra = [
+ "bin/hf,sha256=deadbeef,343",
+ "Scripts/hf.exe,sha256=deadbeef,343",
+ ],
+ )
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_skipping_scripts_does_not_mask_real_damage(self, tmp_path: Path):
+ """The skip must be scoped to script rows, not a blanket exemption."""
+ venv_dir = self._make_venv(
+ tmp_path / "venv", record_extra = ["../../bin/hf,sha256=deadbeef,343"]
+ )
+ (venv_dir / "transformers" / "__init__.py").unlink()
+ assert not _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_larger_than_recorded_is_not_damage(self, tmp_path: Path):
+ """A packaging collision leaves a bigger file, not a broken one."""
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers" / "__init__.py").write_text("y" * 400)
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_multiply_owned_path_skips_the_size_check_but_not_existence(self, tmp_path: Path):
+ venv_dir = self._make_venv(
+ tmp_path / "venv",
+ files = {"transformers/__init__.py": "x" * 40, "shared/mod.py": "z" * 90},
+ )
+ self._make_venv(
+ venv_dir,
+ pkg = "other",
+ version = "1.0.0",
+ files = {"other/__init__.py": "o" * 10},
+ record_extra = ["shared/mod.py,sha256=beef,999999"],
+ )
+ # Two RECORDs disagree on the size; whichever copy landed says nothing
+ # about either, so this is not damage.
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+ # Ambiguous sizes cannot explain the file being gone.
+ (venv_dir / "shared" / "mod.py").unlink()
+ assert not _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_directory_standing_in_for_a_recorded_file_is_damage(self, tmp_path: Path):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ target = venv_dir / "transformers" / "__init__.py"
+ target.unlink()
+ target.mkdir() # st_size 4096 on POSIX would sail past a shrinkage test
+ assert not _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_blank_size_row_still_reports_a_deletion(self, tmp_path: Path):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers" / "data.bin").write_text("q")
+ record = venv_dir / "transformers-5.3.0.dist-info" / "RECORD"
+ record.write_text(record.read_text() + "transformers/data.bin,,\n")
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+ (venv_dir / "transformers" / "data.bin").unlink()
+ assert not _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_missing_record_is_not_damage(self, tmp_path: Path):
+ """Fails open: the answer to a finding is to delete hundreds of MB."""
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers-5.3.0.dist-info" / "RECORD").unlink()
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_pyc_and_dist_info_rows_are_ignored(self, tmp_path: Path):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ record = venv_dir / "transformers-5.3.0.dist-info" / "RECORD"
+ record.write_text(
+ record.read_text()
+ + "transformers/__pycache__/__init__.cpython-311.pyc,sha256=aa,500\n"
+ + "transformers-5.3.0.dist-info/direct_url.json,sha256=bb,500\n"
+ )
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_directory_rows_are_ignored(self, tmp_path: Path):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ record = venv_dir / "transformers-5.3.0.dist-info" / "RECORD"
+ record.write_text(record.read_text() + "transformers/subdir/,,\n")
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_default_is_package_level_only(self, tmp_path: Path):
+ """The routing predicate keeps the cheap semantics: it runs several times
+ per /validate request with no cache in front of it."""
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers" / "__init__.py").write_text("x")
+ assert _venv_dir_is_valid(str(venv_dir), ("transformers==5.3.0",)) is True
+
+ def test_env_kill_switch_disables_the_scan(self, tmp_path: Path, monkeypatch):
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers" / "__init__.py").write_text("x")
+ monkeypatch.setenv("UNSLOTH_SKIP_SIDECAR_FILE_CHECK", "1")
+ assert _venv_dir_is_valid_and_undamaged(str(venv_dir), ("transformers==5.3.0",))
+
+ def test_ensure_venv_dir_wipes_and_reinstalls_a_damaged_sidecar(
+ self, tmp_path: Path, monkeypatch
+ ):
+ """End to end: the damage reaches the repair that already exists."""
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / "transformers" / "__init__.py").write_text("x")
+
+ installed = []
+
+ def _fake_install(pkg, target):
+ installed.append(pkg)
+ return True
+
+ monkeypatch.setattr("utils.transformers_version._install_to_dir", _fake_install)
+ ok = _ensure_venv_dir(str(venv_dir), ("transformers==5.3.0",), "transformers 5.3.0")
+
+ assert ok is True
+ assert installed == ["transformers==5.3.0"], "damaged sidecar was not reinstalled"
+ assert not (venv_dir / "transformers").exists(), "damaged tree was not wiped first"
+
+ def test_ensure_venv_dir_restores_the_studio_owned_marker(self, tmp_path: Path, monkeypatch):
+ """The wipe takes setup.sh's ownership marker with the old directory. Without a
+ new one, the next `unsloth studio update` under a custom UNSLOTH_STUDIO_HOME
+ aborts on a sidecar we just repaired, and adoption cannot rescue it because that
+ needs a prebuilt-info file a venv never has."""
+ venv_dir = self._make_venv(tmp_path / "venv")
+ (venv_dir / ".unsloth-studio-owned").touch()
+ (venv_dir / "transformers" / "__init__.py").write_text("x")
+
+ monkeypatch.setattr("utils.transformers_version._install_to_dir", lambda pkg, target: True)
+ assert _ensure_venv_dir(str(venv_dir), ("transformers==5.3.0",), "transformers 5.3.0")
+
+ assert (venv_dir / ".unsloth-studio-owned").is_file()
+
+
# ---------------------------------------------------------------------------
# _ensure_venv_dir — issue #6103
# A slow runtime install must log each package as it starts, otherwise it
@@ -3271,6 +3488,10 @@ class TestKillSwitchBeatsMappingCache:
key = tv._probe_cache_key("some/model")
monkeypatch.setitem(tv._probe_tier_cache, key, "latest")
+ # A cached 'latest' only ever arises while the tier is pinned, since an unpinned
+ # one is not in the probe order at all, and an unpinned cache entry is now
+ # re-probed in its own right. Hold the pin so this stays a test of the switch.
+ monkeypatch.setattr(tv, "latest_venv_pinned_version", lambda: "5.99.0")
monkeypatch.setenv("UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS", "1")
# With the switch set, the cached latest entry must not short-circuit;
# the probe re-resolves against the non-latest order (stub it to 530).
@@ -3363,3 +3584,375 @@ class TestRaiseTierForNested:
monkeypatch.setattr(tv, "_config_needs_510", lambda cfg: False)
monkeypatch.setattr(tv, "_config_needs_550", lambda cfg: True)
assert tv.get_transformers_tier(str(ckpt), probe = False) == "latest"
+
+
+class TestDamagedLatestSidecarRepairHandoff:
+ """A worker child refuses to repair the sidecar, so damage it finds must reach the
+ parent's routing self-heal. The routing predicate is package-level and cannot see a
+ truncated file, so without a handoff every worker retry fails forever waiting for a
+ repair nothing ever triggers."""
+
+ def _sidecar(
+ self,
+ root: Path,
+ model_types = ("brandnew",),
+ ) -> Path:
+ """A pinned latest sidecar whose RECORD matches what it wrote."""
+ import utils.transformers_version as tv
+
+ di = root / "transformers-5.99.0.dist-info"
+ di.mkdir(parents = True, exist_ok = True)
+ (di / "METADATA").write_text("Name: transformers\nVersion: 5.99.0\n")
+ mapping = ", ".join(f'"{t}": "C"' for t in model_types)
+ files = {
+ "transformers/__init__.py": "x" * 40,
+ "transformers/models/auto/configuration_auto.py": "CONFIG_MAPPING_NAMES = {%s}\n"
+ % mapping,
+ }
+ rows = []
+ for rel, body in files.items():
+ path = root / rel
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text(body)
+ rows.append(f"{rel},sha256=deadbeef,{len(body)}")
+ rows.append("transformers-5.99.0.dist-info/RECORD,,")
+ (di / "RECORD").write_text("\n".join(rows) + "\n")
+ (root / tv._LATEST_PIN_MARKER).write_text(
+ json.dumps({"version": "5.99.0", "packages": ["transformers==5.99.0"]})
+ )
+ return root
+
+ def _patch(
+ self,
+ monkeypatch,
+ live: Path,
+ is_child: bool = False,
+ ):
+ """Point the module at *live* and make a repair succeed without pip."""
+ import multiprocessing
+ import utils.transformers_version as tv
+
+ monkeypatch.setattr(tv, "_VENV_T5_LATEST_DIR", str(live))
+ monkeypatch.setattr(tv, "_latest_tier_disabled", lambda: False)
+ monkeypatch.setattr(tv, "_env_offline", lambda: False)
+ monkeypatch.setattr(tv, "_workers_active_for_repair", lambda: False)
+ monkeypatch.setattr(tv, "_config_mapping_cache", {})
+ monkeypatch.setattr(tv, "_latest_repair_failed_at", 0.0)
+ monkeypatch.setattr(
+ multiprocessing, "parent_process", lambda: object() if is_child else None
+ )
+ installs = []
+
+ def _fake_install(pkg, target):
+ installs.append(pkg)
+ self._sidecar(Path(target))
+ return True
+
+ monkeypatch.setattr(tv, "_install_to_dir", _fake_install)
+ return tv, installs
+
+ def _damage(self, live: Path):
+ """Disk-full shape: the file is still there, just short."""
+ (live / "transformers" / "__init__.py").write_text("x")
+
+ def _is_damaged(self, tv, live: Path) -> bool:
+ return bool(tv._sidecar_damaged_files(str(live)))
+
+ def test_damage_predating_the_process_heals_before_any_worker_starts(
+ self, monkeypatch, tmp_path
+ ):
+ """The parent resolves the mapping through _overlay_transformers_dir on a cache
+ miss, which is the one place that can afford the RECORD scan."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, installs = self._patch(monkeypatch, live)
+ self._damage(live)
+ assert tv._venv_dir_is_valid(
+ str(live), ("transformers==5.99.0",)
+ ), "precondition: the package-level predicate cannot see this damage"
+
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) == "latest"
+
+ assert installs == ["transformers==5.99.0"], "the parent did not self-heal"
+ assert not self._is_damaged(tv, live)
+
+ def test_worker_child_flags_damage_instead_of_only_refusing(self, monkeypatch, tmp_path):
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, installs = self._patch(monkeypatch, live, is_child = True)
+ self._damage(live)
+
+ assert tv._ensure_venv_t5_latest_exists() is False, "a child must not repair"
+ assert installs == []
+ assert tv._latest_repair_requested(), "the child left no signal for the parent"
+
+ def test_flagged_damage_breaks_the_worker_retry_deadlock(self, monkeypatch, tmp_path):
+ """The reported deadlock, end to end.
+
+ Damage that appears AFTER this process cached the latest mapping is invisible to
+ every parent-side predicate cheap enough to run per request, so the parent keeps
+ routing to 'latest' and the child keeps refusing. Pinned here is that the loop
+ terminates: the child's flag makes the next parent routing call repair, and the
+ retry after that activates.
+ """
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, installs = self._patch(monkeypatch, live)
+
+ # Warm the mapping cache from the healthy sidecar, as any earlier request does.
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) == "latest"
+ assert "latest" in tv._config_mapping_cache
+ installs.clear()
+
+ self._damage(live)
+
+ # Parent keeps routing to 'latest' off the cached mapping and never scans.
+ for _ in range(3):
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) == "latest"
+ assert installs == [], "the cached hot path must not pay for a scan"
+ assert self._is_damaged(tv, live)
+
+ # The worker child sees the damage, refuses, and flags it.
+ monkeypatch.setattr("multiprocessing.parent_process", lambda: object())
+ assert tv._ensure_venv_t5_latest_exists() is False
+ assert installs == []
+
+ # The next parent routing call repairs. Before the fix it never did, and the
+ # worker below failed forever.
+ monkeypatch.setattr("multiprocessing.parent_process", lambda: None)
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) == "latest"
+ assert installs == ["transformers==5.99.0"], "the parent never repaired"
+ assert not self._is_damaged(tv, live)
+
+ # The worker retry now succeeds, which is the property that was deadlocked.
+ monkeypatch.setattr("multiprocessing.parent_process", lambda: object())
+ assert tv._ensure_venv_t5_latest_exists() is True
+ assert not tv._latest_repair_requested(), "a satisfied request must not persist"
+
+ def test_stale_flag_on_a_healthy_sidecar_is_cleared_not_acted_on(self, monkeypatch, tmp_path):
+ """A false positive here costs a several-hundred-MB re-download, so a flag a
+ clean scan contradicts must be dropped, and must not re-arm the branch."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, installs = self._patch(monkeypatch, live)
+ sentinel = live / "transformers" / "__init__.py"
+ tv._request_latest_repair()
+
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) == "latest"
+
+ assert installs == [], "a healthy sidecar must never be wiped on a stale flag"
+ assert sentinel.read_text() == "x" * 40
+ assert not tv._latest_repair_requested(), "the stale flag must not survive"
+
+ def test_cached_mapping_hit_never_scans_the_sidecar(self, monkeypatch, tmp_path):
+ """The revalidation on a _config_mapping_cache HIT runs several times per
+ /validate request, so it must stay package level."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ assert tv._config_model_types("latest") == frozenset({"brandnew"})
+
+ monkeypatch.setattr(
+ tv,
+ "_sidecar_damaged_files",
+ lambda d, limit = 3: pytest.fail("the cached hot path must not scan RECORDs"),
+ )
+ for _ in range(5):
+ assert tv._config_model_types("latest") == frozenset({"brandnew"})
+
+ def test_repair_backoff_window_never_repeats_the_scan(self, monkeypatch, tmp_path):
+ """A sidecar that cannot be repaired (offline, pip down) must not put a ~25 ms
+ scan on every routing call for the whole backoff window."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ self._damage(live)
+
+ assert tv._overlay_transformers_dir("latest") is None # scans, tries, fails
+
+ monkeypatch.setattr(
+ tv,
+ "_sidecar_damaged_files",
+ lambda d, limit = 3: pytest.fail("the backoff window must not re-scan"),
+ )
+ for _ in range(5):
+ tv._overlay_transformers_dir("latest")
+
+ def test_backoff_window_keeps_the_damaged_sidecar_withheld(self, monkeypatch, tmp_path):
+ """Backing off from pip must not double as declaring the sidecar usable: the
+ cheap predicate cannot see a truncated file, so without the marker every
+ routing call in the window routes latest-only models straight back into a
+ sidecar whose worker activation is known to fail."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ self._damage(live)
+
+ assert tv._overlay_transformers_dir("latest") is None # scans, tries, fails
+ assert tv._venv_dir_is_valid(
+ str(live), ("transformers==5.99.0",)
+ ), "precondition: only the scan can see this damage, not the cheap predicate"
+
+ monkeypatch.setattr(
+ tv,
+ "_sidecar_damaged_files",
+ lambda d, limit = 3: pytest.fail("the backoff window must not re-scan"),
+ )
+ for _ in range(5):
+ assert tv._overlay_transformers_dir("latest") is None
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) != "latest"
+
+ def test_every_unrepaired_exit_flags_the_damage(self, monkeypatch, tmp_path):
+ """Offline, a child, and a swap already running each return before any repair.
+ Whichever one is taken, the damage has to be recorded, or the cheap predicate
+ keeps reporting the sidecar healthy and nothing ever revisits it."""
+ import multiprocessing
+
+ bailouts = {
+ "offline": lambda tv: monkeypatch.setattr(tv, "_env_offline", lambda: True),
+ "child": lambda tv: monkeypatch.setattr(
+ multiprocessing, "parent_process", lambda: object()
+ ),
+ "swap_running": lambda tv: monkeypatch.setattr(
+ tv, "try_begin_sidecar_swap", lambda kind = None: False
+ ),
+ }
+ for name, arrange in bailouts.items():
+ live = self._sidecar(tmp_path / f"venv_t5_latest_{name}")
+ tv, _ = self._patch(monkeypatch, live)
+ arrange(tv)
+ self._damage(live)
+
+ assert tv._ensure_venv_t5_latest_exists() is False, name
+ assert tv._latest_repair_requested(), f"{name} exited without recording the damage"
+ assert not tv._latest_sidecar_intact(), name
+
+ def test_cached_probe_result_does_not_survive_a_flagged_sidecar(self, monkeypatch, tmp_path):
+ """_probe_tier caches per process. A result cached while the sidecar was healthy
+ must not keep sending workers into it once damage is known, the way the
+ config-mapping cache already refuses to."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ key = f"{tv._probe_cache_key('some/model')}\0floor=default:def=1"
+ monkeypatch.setitem(tv._probe_tier_cache, key, "latest")
+
+ self._damage(live)
+ tv._request_latest_repair()
+
+ assert (
+ tv._probe_tier("some/model", None, "test", include_default = True, floor = "default")
+ != "latest"
+ )
+
+ def test_file_check_kill_switch_suppresses_the_whole_handoff(self, monkeypatch, tmp_path):
+ """UNSLOTH_SKIP_SIDECAR_FILE_CHECK is the escape hatch for a false positive; it
+ must leave no path that still wipes the sidecar."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, installs = self._patch(monkeypatch, live)
+ monkeypatch.setenv("UNSLOTH_SKIP_SIDECAR_FILE_CHECK", "1")
+ self._damage(live)
+
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) == "latest"
+ assert installs == []
+ monkeypatch.setattr("multiprocessing.parent_process", lambda: object())
+ assert tv._ensure_venv_t5_latest_exists() is True
+ assert not tv._latest_repair_requested()
+
+ def test_kill_switch_frees_the_sidecar_mid_backoff(self, monkeypatch, tmp_path):
+ """The hatch exists for a false positive, so it has to work at the moment one is
+ being hit: with a marker already written and a repair already failed, it must
+ restore routing now rather than one backoff window later."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ self._damage(live)
+
+ assert tv._overlay_transformers_dir("latest") is None # arms marker + backoff
+ assert tv._latest_repair_requested(), "precondition: the marker is armed"
+
+ monkeypatch.setenv("UNSLOTH_SKIP_SIDECAR_FILE_CHECK", "1")
+
+ assert tv._overlay_transformers_dir("latest") is not None
+ assert tv._tier_from_config_mapping({"model_type": "brandnew"}) == "latest"
+
+ def test_an_unreadable_file_is_not_reported_as_damage(self, monkeypatch, tmp_path):
+ """A wipe costs a several-hundred-MB re-download, so the scan may only condemn
+ what it can prove: EIO or ESTALE on a flaky mount says the file could not be
+ read, never that it is gone."""
+ import errno
+
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ real_stat = Path.stat
+
+ def _flaky(self, *a, **k):
+ if self.name == "__init__.py":
+ raise OSError(errno.EIO, "Input/output error")
+ return real_stat(self, *a, **k)
+
+ monkeypatch.setattr(Path, "stat", _flaky)
+
+ assert tv._sidecar_damaged_files(str(live)) == []
+ assert tv._latest_sidecar_undamaged() is True
+ assert tv._overlay_transformers_dir("latest") is not None
+
+ def test_a_deleted_file_is_still_reported_as_damage(self, monkeypatch, tmp_path):
+ """The counterpart: narrowing the caught errors must not blind the scan to a
+ genuinely missing file."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ (live / "transformers" / "__init__.py").unlink()
+
+ assert tv._sidecar_damaged_files(str(live)) == [
+ "transformers: transformers/__init__.py is missing"
+ ]
+
+ def test_an_inconclusive_scan_does_not_retire_proven_damage(self, monkeypatch, tmp_path):
+ """Skipping unreadable rows means an empty result can mean 'nothing proven', not
+ 'proven healthy'. A worker already proved this sidecar damaged, and a scan that
+ could not read the file must not erase that and hand it back to routing."""
+ import errno
+
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ # A repair that cannot complete, so what is observed is the decision itself and
+ # not a rebuild papering over it.
+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: False)
+ self._damage(live)
+ tv._request_latest_repair()
+ real_stat = Path.stat
+
+ def _flaky(self, *a, **k):
+ if self.name == "__init__.py":
+ raise OSError(errno.EIO, "Input/output error")
+ return real_stat(self, *a, **k)
+
+ monkeypatch.setattr(Path, "stat", _flaky)
+ assert tv._sidecar_damaged_files(str(live)) == [] # the scan sees nothing
+ assert tv._sidecar_scan(str(live)) == ([], True) # but knows it is blind
+
+ assert tv._ensure_venv_t5_latest_exists() is False
+ assert tv._latest_repair_requested(), "an unreadable scan cannot disprove damage"
+
+ def test_a_clean_scan_still_retires_a_stale_marker(self, monkeypatch, tmp_path):
+ """The counterpart: a scan that really did read every row must still clear the
+ marker, or a request left by a lost race loops forever."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ tv._request_latest_repair()
+
+ assert tv._ensure_venv_t5_latest_exists() is True
+ assert not tv._latest_repair_requested()
+
+ def test_a_cached_probe_does_not_survive_the_pin_being_deleted(self, monkeypatch, tmp_path):
+ """Deleting the pin takes the repair marker with it, so the marker cannot carry
+ this case. Activation short-circuits on a missing pin before it can signal
+ anything, so a cached latest would fail every retry until the process restarts."""
+ live = self._sidecar(tmp_path / "venv_t5_latest")
+ tv, _ = self._patch(monkeypatch, live)
+ import shutil
+
+ key = f"{tv._probe_cache_key('some/model')}\0floor=default:def=1"
+ monkeypatch.setitem(tv._probe_tier_cache, key, "latest")
+ shutil.rmtree(live)
+
+ assert (
+ tv._probe_tier("some/model", None, "test", include_default = True, floor = "default")
+ != "latest"
+ )
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 59de2ccad07..fbbb2931c62 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -37,6 +37,7 @@ from loggers import get_logger
import os
import re
import shutil
+import stat
import subprocess
import sys
import threading
@@ -1135,6 +1136,57 @@ _latest_repair_failed_at: float = 0.0
_LATEST_REPAIR_BACKOFF_SECS = 5 * 60
+# Remembers that a RECORD scan found the sidecar damaged, so the cheap predicate
+# can act on damage it cannot itself see. Written by a worker child, which cannot
+# repair (repairs are a parent action) and needs the parent's routing self-heal to
+# pick the damage up, and by the parent when a repair attempt fails, so the backoff
+# window suppresses pip retries without handing the damaged sidecar back. Lives
+# inside the sidecar dir, so the stage-and-swap that repairs it clears the marker by
+# construction.
+_LATEST_REPAIR_MARKER = ".unsloth_sidecar_repair_needed"
+
+
+def _latest_repair_marker_path() -> Path:
+ return Path(_VENV_T5_LATEST_DIR) / _LATEST_REPAIR_MARKER
+
+
+def _latest_repair_requested() -> bool:
+ """True while a scan has found the sidecar damaged and no repair has succeeded.
+
+ One os.path.isfile, so the routing predicate below can carry it; the RECORD
+ scan that produced the request costs ~25 ms and cannot.
+ """
+ if _sidecar_file_check_disabled():
+ # The marker only ever records a file-level finding, which is precisely what
+ # the switch turns off. Ignoring it here is what makes the hatch immediate:
+ # otherwise a marker left by a false positive keeps the sidecar withheld for
+ # the rest of the backoff, since the disabled scan is never reached to clear it.
+ return False
+ try:
+ return _latest_repair_marker_path().is_file()
+ except OSError:
+ return False
+
+
+def _request_latest_repair() -> None:
+ """Record that the sidecar needs a repair the caller could not perform."""
+ try:
+ _latest_repair_marker_path().write_text(
+ json.dumps({"pid": os.getpid(), "at": time.time()}), encoding = "utf-8"
+ )
+ except OSError:
+ pass
+
+
+def _clear_latest_repair_request() -> None:
+ """Drop the flag once a scan finds the sidecar healthy, so a request left by a
+ lost race costs one extra scan instead of looping forever."""
+ try:
+ _latest_repair_marker_path().unlink()
+ except OSError:
+ pass
+
+
def _latest_sidecar_intact() -> bool:
"""The pinned latest sidecar exists with its transformers dir and every pinned
package. False when the pin itself is gone: a cached 'latest' mapping must then be
@@ -1144,13 +1196,36 @@ def _latest_sidecar_intact() -> bool:
(_overlay_transformers_dir only calls this after gating on a present pin, so the
pin-missing case here is the cache-revalidation caller whose pin was deleted after
- the mapping was first cached.)"""
+ the mapping was first cached.)
+
+ Package level only, deliberately not _venv_dir_is_valid_and_undamaged: this
+ runs several times per /validate request, on _config_mapping_cache HITS as
+ well as misses, with no cache in front of it, and a False here only
+ re-routes a model. Sub-file damage is caught one step later instead, by
+ _ensure_venv_t5_latest_exists at worker activation, which repairs in a
+ parent and refuses with a named reason in a child, after flagging the sidecar
+ for repair here."""
pin = _latest_pin_data()
if pin is None:
return False
+ if _latest_repair_requested():
+ return False
return _venv_dir_is_valid(_VENV_T5_LATEST_DIR, tuple(pin["packages"]))
+def _latest_sidecar_undamaged() -> bool:
+ """_latest_sidecar_intact plus the RECORD-vs-filesystem scan.
+
+ Only for the self-heal decision in _overlay_transformers_dir, which runs on a
+ _config_mapping_cache MISS -- measured once per process while the sidecar is
+ healthy, and never on the cached hot path _latest_sidecar_intact serves.
+ """
+ pin = _latest_pin_data()
+ if pin is None:
+ return False
+ return _venv_dir_is_valid_and_undamaged(_VENV_T5_LATEST_DIR, tuple(pin["packages"]))
+
+
def _overlay_transformers_dir(tier: str) -> str | None:
"""transformers source dir for a tier, located without importing it."""
global _latest_repair_failed_at
@@ -1165,21 +1240,32 @@ def _overlay_transformers_dir(tier: str) -> str | None:
"latest": _VENV_T5_LATEST_DIR,
}.get(tier)
src = os.path.join(root, "transformers") if root else None
- if src and tier == "latest" and not _latest_sidecar_intact():
- # A valid pin whose sidecar vanished or lost a pinned package (partial
- # deletion, disk issue, interrupted external edits) must self-heal, or
- # latest-only models either silently route to older tiers or reach a
- # worker that cannot repair, failing every load until a manual
- # reinstall. Repair under the swap reservation; back off after a
- # failure so routing calls don't hammer pip.
+ if src and tier == "latest":
+ # A valid pin whose sidecar vanished, lost a pinned package or had a
+ # recorded file truncated/deleted (partial deletion, disk issue,
+ # interrupted external edits) must self-heal, or latest-only models
+ # either silently route to older tiers or reach a worker that cannot
+ # repair, failing every load until a manual reinstall. Repair under the
+ # swap reservation; back off after a failure so routing calls don't
+ # hammer pip.
+ heal_due = time.time() - _latest_repair_failed_at >= _LATEST_REPAIR_BACKOFF_SECS
+ # The ~25 ms RECORD scan runs only when a repair could actually follow it,
+ # and only on a _config_mapping_cache miss (once per process while the
+ # sidecar is healthy) -- never during the backoff window, where every
+ # routing call would otherwise re-pay it for an answer it cannot act on.
+ broken = not _latest_sidecar_intact() or (heal_due and not _latest_sidecar_undamaged())
repaired = False
- if time.time() - _latest_repair_failed_at >= _LATEST_REPAIR_BACKOFF_SECS:
+ if broken and heal_due:
if _ensure_venv_t5_latest_exists():
_latest_repair_failed_at = 0.0
repaired = True
else:
+ # The failed attempt left the marker, so the backoff suppresses pip
+ # retries without also declaring the sidecar usable: without it the
+ # cheap predicate would find nothing broken on the next routing call
+ # and hand the damaged sidecar back for the whole window.
_latest_repair_failed_at = time.time()
- if not repaired:
+ if broken and not repaired:
# Still broken: treat the overlay as unavailable rather than route
# models to a tier whose worker activation is known to fail. Models
# an older tier supports keep loading there until a repair succeeds,
@@ -1516,7 +1602,18 @@ def _probe_tier(
if key in _probe_tier_cache:
cached = _probe_tier_cache[key]
# Kill switch beats the cache (like _config_model_types): a stale 'latest' probe must not keep activating it.
- if cached != "latest" or not _latest_tier_disabled():
+ # A sidecar since found damaged beats it too, or a probe cached while it was
+ # healthy keeps spawning workers into a tier whose activation is known to fail,
+ # and a model that reaches latest this way never touches the config-mapping path
+ # that would repair it. So does an unpinned tier: deleting the pin takes the
+ # repair marker with it, and activation then short-circuits on a missing pin
+ # before anything can signal, so the cached answer would fail every retry.
+ # Falling through re-probes, which runs the ensure and repair path instead.
+ if cached != "latest" or not (
+ _latest_tier_disabled()
+ or _latest_repair_requested()
+ or latest_venv_pinned_version() is None
+ ):
return cached
def _cache(tier: str, *, skipped: bool) -> str:
@@ -1920,8 +2017,184 @@ _VENV_T5_550_PACKAGES = (
_VENV_T5_PACKAGES = _VENV_T5_550_PACKAGES
+_SIDECAR_FILE_CHECK_ENV = "UNSLOTH_SKIP_SIDECAR_FILE_CHECK"
+
+
+def _sidecar_file_check_disabled() -> bool:
+ """Escape hatch: a false positive costs a several-hundred-MB reinstall, so a user
+ hitting one must be able to turn the scan off without waiting for a release. It has
+ to reach everything the scan produced, the repair marker included, or the hatch only
+ takes effect a backoff window later."""
+ return os.environ.get(_SIDECAR_FILE_CHECK_ENV, "").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+ "on",
+ )
+
+
+def _sidecar_scan(venv_dir: str, limit: int = 3) -> tuple[list[str], bool]:
+ """``(findings, inconclusive)``. See _sidecar_damaged_files.
+
+ *inconclusive* is True when some row could not be read at all, so an empty
+ findings list means "nothing proven" rather than "proven healthy". Callers that
+ retire a record of damage need that difference; callers that only decide whether
+ to repair do not.
+ """
+ return _sidecar_scan_impl(venv_dir, limit)
+
+
+def _sidecar_damaged_files(venv_dir: str, limit: int = 3) -> list[str]:
+ """RECORD entries under *venv_dir* that are gone, or shorter than pip recorded.
+
+ Findings only. Use _sidecar_scan when an empty result has to be told apart from a
+ scan that could not read the disk.
+ """
+ return _sidecar_scan_impl(venv_dir, limit)[0]
+
+
+def _sidecar_scan_impl(venv_dir: str, limit: int = 3) -> tuple[list[str], bool]:
+ """Body of the two above.
+
+ A sidecar whose METADATA survived a disk-full or an interrupted pip still
+ passes every version check above, so the wipe-and-reinstall in
+ _ensure_venv_dir never fires and the worker dies importing transformers
+ instead. Comparing each RECORD row against the filesystem sees that;
+ a package-level check cannot, because the damaged module is still there.
+
+ Deliberately mirrored from ``unsloth_cli/_studio_deps.py``'s
+ ``damaged_installed_files`` rather than imported from it. The backend runs
+ with ``studio/backend`` on sys.path and never imports the CLI package (which
+ may be an entirely different install), and the subject differs: that one
+ describes its own interpreter through importlib.metadata, this one a flat
+ ``pip --target`` directory no interpreter owns. Same deliberate mirror as
+ ``auth/terminal_prompt.py``; keep the two predicates in sync.
+
+ Every distribution in the sidecar is checked, not only the pinned ones. The
+ whole directory is prepended to sys.path, so a truncated ``regex/`` or
+ ``urllib3/`` shadows the base install and breaks ``import transformers``
+ exactly as a truncated ``transformers/`` does. Measured on three live
+ sidecars that is 7729 files instead of 7432, i.e. 4% more work.
+
+ Only shrinkage and disappearance count, and only for paths a single
+ distribution claims: when two claim one path, whichever copy landed says
+ nothing about either RECORD, in either direction. A file LARGER than
+ recorded is a packaging collision, not damage. Sizes are therefore compared
+ after the whole scan, once multiply-owned paths are known.
+
+ Fails open everywhere. The caller's answer to a finding is to delete several
+ hundred MB and reinstall, so an unreadable or absent RECORD -- and any other
+ surprise -- reports nothing rather than guessing.
+ """
+ import csv
+ import io
+
+ inconclusive = False
+ if _sidecar_file_check_disabled():
+ return [], False
+ root = Path(venv_dir)
+ entries: list[tuple] = []
+ owners: dict[str, int] = {}
+ try:
+ dist_infos = sorted(root.glob("*.dist-info"))
+ except OSError:
+ return [], True
+ for di in dist_infos:
+ name = di.name.split("-")[0]
+ try:
+ record = (di / "RECORD").read_text(encoding = "utf-8", errors = "replace")
+ except FileNotFoundError:
+ # No RECORD says nothing about damage; some installs legitimately
+ # have none, so this is not a gap in what the scan could see.
+ continue
+ except OSError:
+ # Present but unreadable: a real gap, so the result cannot be called clean.
+ inconclusive = True
+ continue
+ try:
+ rows = list(csv.reader(io.StringIO(record)))
+ except csv.Error:
+ inconclusive = True
+ continue
+ for row in rows:
+ rel = row[0] if row else ""
+ # A trailing slash is a directory entry, which has nothing to check.
+ if not rel or rel.endswith("/"):
+ continue
+ # Installer-owned metadata is rewritten in place and drifts from the
+ # size recorded inside itself; .pyc is regenerated from source.
+ if ".dist-info/" in rel or ".egg-info/" in rel or rel.endswith(".pyc"):
+ continue
+ # Console scripts are not checkable in a flat --target tree, and
+ # believing them fails CLOSED on a healthy sidecar, which is the
+ # worst outcome here. pip installs through a temporary normal-scheme
+ # prefix and writes RECORD before flattening, so it records
+ # ../../bin/hf (../../Scripts/hf.exe on Windows) while the file
+ # lands in <target>/bin. uv records bin/hf, which does resolve, but
+ # pip's --upgrade rmtree's a colliding directory in the target, so a
+ # later install into the same sidecar deletes an earlier package's
+ # scripts. Either way the sidecar is only ever prepended to
+ # sys.path, never put on PATH, so nothing here is imported and
+ # nothing is lost by skipping it.
+ parts = tuple(p for p in rel.replace("\\", "/").split("/") if p)
+ if (
+ rel.startswith("/")
+ or (len(rel) > 1 and rel[1] == ":")
+ or ".." in parts
+ or (parts and parts[0] in ("bin", "Scripts"))
+ ):
+ continue
+ # The size field is optional and real wheels do leave it blank. Keep
+ # the row anyway with an unknown size: existence is still checkable,
+ # and dropping the row means a deletion goes unreported.
+ recorded: int | None = None
+ if len(row) >= 3 and row[2]:
+ try:
+ recorded = int(row[2])
+ except ValueError:
+ recorded = None
+ target = root / rel
+ key = os.path.normcase(str(target))
+ owners[key] = owners.get(key, 0) + 1
+ entries.append((name, rel, recorded, target, key))
+
+ found: list[str] = []
+ for name, rel, recorded, target, key in entries:
+ try:
+ info = target.stat()
+ except (FileNotFoundError, NotADirectoryError):
+ # Multiple ownership makes the recorded SIZES ambiguous; it cannot
+ # explain the file being gone, so this branch runs for shared paths
+ # too. NotADirectoryError means a parent component is a file, which
+ # is the same tree damage seen one level up.
+ found.append(f"{name}: {rel} is missing")
+ except OSError:
+ # Inconclusive, not damage. EIO, ESTALE on an NFS mount, or EACCES
+ # says the file could not be read, never that it is gone, and the
+ # answer here costs a several-hundred-MB wipe and re-download. Skip
+ # the row, but remember the gap: a scan that cannot see the disk must
+ # neither condemn it nor certify it.
+ inconclusive = True
+ continue
+ else:
+ if not stat.S_ISREG(info.st_mode):
+ # A directory standing in for a recorded module still imports as
+ # something else, and on POSIX its st_size (commonly 4096) can
+ # sail past the shrinkage test.
+ found.append(f"{name}: {rel} is not a regular file")
+ elif owners[key] == 1 and recorded is not None and info.st_size < recorded:
+ found.append(f"{name}: {rel} is {info.st_size} bytes, expected {recorded}")
+ if len(found) >= limit:
+ return found, inconclusive
+ return found, inconclusive
+
+
def _venv_dir_is_valid(venv_dir: str, packages: tuple[str, ...]) -> bool:
- """Return True if *venv_dir* has all *packages* at the correct versions."""
+ """Return True if *venv_dir* has all *packages* at the correct versions.
+
+ Package level only. Callers that can REPAIR the sidecar want
+ _venv_dir_is_valid_and_undamaged below instead.
+ """
if not os.path.isdir(venv_dir) or not os.listdir(venv_dir):
return False
for pkg_spec in packages:
@@ -1964,6 +2237,42 @@ def _venv_dir_is_valid(venv_dir: str, packages: tuple[str, ...]) -> bool:
return True
+def _venv_dir_is_valid_and_undamaged(venv_dir: str, packages: tuple[str, ...]) -> bool:
+ """_venv_dir_is_valid, plus a RECORD-against-filesystem scan of the whole dir.
+
+ Only for the callers that can act on a False: _ensure_venv_dir and the two
+ latest-sidecar installers, which wipe and reinstall. The routing predicate
+ _latest_sidecar_intact keeps the cheap check, because it runs several times
+ per /validate request with no cache in front of it and a False there only
+ re-routes a model. Measured on a live install the scan is ~28 ms per
+ sidecar: real money on an HTTP path, nothing next to the 1.7 s
+ ``import transformers`` that follows a repair-site call.
+
+ The package checks run first, so a wrong version is rejected without paying
+ for the scan.
+ """
+ return _venv_dir_health(venv_dir, packages)[0]
+
+
+def _venv_dir_health(venv_dir: str, packages: tuple[str, ...]) -> tuple[bool, bool]:
+ """``(undamaged, conclusive)`` for _venv_dir_is_valid_and_undamaged.
+
+ *conclusive* is False when the scan hit a row it could not read, so *undamaged*
+ means "nothing proven against it" rather than "proven healthy".
+ """
+ if not _venv_dir_is_valid(venv_dir, packages):
+ return False, True
+ damaged, inconclusive = _sidecar_scan(venv_dir)
+ if damaged:
+ logger.warning(
+ "%s has damaged files -- venv will be wiped and reinstalled: %s",
+ venv_dir,
+ "; ".join(damaged),
+ )
+ return False, True
+ return True, not inconclusive
+
+
def _venv_t5_is_valid() -> bool:
"""Backwards-compat: check the Gemma 4 sidecar venv."""
return _venv_dir_is_valid(_VENV_T5_550_DIR, _VENV_T5_550_PACKAGES)
@@ -2027,14 +2336,33 @@ def _install_to_dir(pkg: str, target_dir: str) -> bool:
return True
+# setup.sh and setup.ps1 write this beside a sidecar venv they created, and refuse to
+# touch an unmarked directory under a custom UNSLOTH_STUDIO_HOME rather than risk
+# deleting something of the user's. A runtime rebuild takes the marker with the old
+# directory, so it has to put one back: the rebuilt tree is ours by construction, and
+# without it the next `unsloth studio update` aborts on a sidecar we just repaired.
+# Adoption cannot cover it either, since that needs a prebuilt-info file a venv never has.
+_STUDIO_OWNED_MARKER = ".unsloth-studio-owned"
+
+
+def _mark_studio_owned(venv_dir: str) -> None:
+ try:
+ Path(venv_dir, _STUDIO_OWNED_MARKER).touch()
+ except OSError:
+ # Best effort, exactly as the shell does: a missing marker costs a clear error
+ # on a later update, never a wrong deletion.
+ pass
+
+
def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bool:
"""Ensure *venv_dir* exists with all *packages*. Install if missing."""
- if _venv_dir_is_valid(venv_dir, packages):
+ if _venv_dir_is_valid_and_undamaged(venv_dir, packages):
return True
logger.warning("%s not found or incomplete at %s -- installing at runtime", label, venv_dir)
shutil.rmtree(venv_dir, ignore_errors = True)
os.makedirs(venv_dir, exist_ok = True)
+ _mark_studio_owned(venv_dir)
total = len(packages)
for idx, pkg in enumerate(packages, start = 1):
logger.info("Installing %s (%d/%d) into %s ...", pkg, idx, total, venv_dir)
@@ -2457,8 +2785,23 @@ def _ensure_venv_t5_latest_exists() -> bool:
return False
version = pin["version"]
packages = tuple(pin["packages"])
- if _venv_dir_is_valid(_VENV_T5_LATEST_DIR, packages):
+ undamaged, conclusive = _venv_dir_health(_VENV_T5_LATEST_DIR, packages)
+ if undamaged and (conclusive or not _latest_repair_requested()):
+ # A repair request that a clean scan contradicts (another process already
+ # repaired it, or a child lost the race with a swap and flagged the fresh
+ # dir) must not survive, or every routing call re-enters the self-heal
+ # branch forever. Only a scan that actually read the files may retire it:
+ # a worker proved the damage, and a scan that hit EIO has not disproved it.
+ if conclusive:
+ _clear_latest_repair_request()
return True
+ # Broken, and every path below can still fail to fix it (offline, a child, a swap
+ # already running, pip). Flag it here rather than per bailout, so the routing
+ # predicate withholds the sidecar no matter which one we take: it cannot see
+ # sub-file damage itself, and a mapping cached before the damage keeps it off the
+ # scanning path entirely. A repair that does succeed swaps the dir and takes the
+ # marker with it.
+ _request_latest_repair()
if _env_offline():
logger.warning(
".venv_t5_latest (transformers %s) is incomplete and offline mode is set; "
@@ -2531,7 +2874,7 @@ def ensure_latest_transformers_venv(
pin is not None
and pin["version"] == version
and tuple(pin["packages"]) == packages
- and _venv_dir_is_valid(_VENV_T5_LATEST_DIR, packages)
+ and _venv_dir_is_valid_and_undamaged(_VENV_T5_LATEST_DIR, packages)
):
return True
return _stage_and_swap_latest_venv(version, packages, before_swap = before_swap)