Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: size Xet download buffers from free RAM, not total (#9052)
Michael Hanb8c931f9a4fd
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.pyindex 4b61ceb49d7..59f49efce37 100644--- a/studio/backend/hub/services/download_lifecycle.py+++ b/studio/backend/hub/services/download_lifecycle.py@@ -75,11 +75,51 @@ def resolve_auto_use_xet() -> tuple[bool, str]:health = xet_health()except Exception as exc: # noqa: BLE001 - never let a health probe block a downloadlogger.debug("Xet health probe failed, defaulting to Xet: %s", exc)- return (True, "Xet (health check unavailable)")- if health is None:+ health, reason = None, "Xet (health check unavailable)"+ else:# Older unsloth_zoo without the health module: no opinion, keep the existing default.- return (True, "Xet")- return (bool(health.use_xet), str(health.reason))+ reason = "Xet" if health is None else str(health.reason)+ if health is not None and not health.use_xet:+ return (False, reason)+ if _health_is_forced(health):+ # ``UNSLOTH_FORCE_XET=1``. The zoo's off switches (``UNSLOTH_DISABLE_XET``,+ # ``UNSLOTH_STABLE_DOWNLOADS``, ``HF_HUB_DISABLE_XET``) already win above, so the on switch+ # has to win here or the pair is asymmetric and the only escape from the RAM rule is+ # editing the request. Buffers are still clamped to free RAM; only the transport choice is+ # left to the operator, the same stand-down the zoo makes for a user-set+ # HF_XET_HIGH_PERFORMANCE.+ return (True, reason)+ # Health said Xet, or had no opinion at all. Free RAM is separate evidence, read from a+ # different zoo module, so it still gets a say: a missing health module says nothing about+ # whether this machine can afford Xet right now.+ pressure = _memory_pressure_reason()+ if pressure is not None:+ return (False, pressure)+ return (True, reason)+++def _health_is_forced(health) -> bool:+ """``UNSLOTH_FORCE_XET``-style verdict? Delegates so this and the capabilities probe stand down+ on exactly the same evidence; a degraded shim answers False, which keeps the RAM gate on."""+ try:+ from utils.hf_xet_fallback import xet_health_is_forced+ return xet_health_is_forced(health)+ except Exception as exc: # noqa: BLE001 - an unreadable verdict is not an override+ logger.debug("Could not read the Xet health source: %s", exc)+ return False+++def _memory_pressure_reason() -> Optional[str]:+ """Free-RAM verdict for an API caller that sends "auto".++ The Studio UI never reaches here: it resolves Auto through the capabilities probe and submits+ the concrete xet/http, so that probe applies the same rule. Shared helper, so the two agree."""+ try:+ from utils.hf_xet_fallback import free_ram_pressure_reason+ return free_ram_pressure_reason()+ except Exception as exc: # noqa: BLE001 - a probe must not decide the transport by crashing+ logger.debug("Free-RAM probe failed, leaving the Xet verdict alone: %s", exc)+ return Nonedef _allow_high_performance() -> bool:@@ -186,23 +226,33 @@ def spawn_worker(env["HF_TOKEN"] = hf_tokenexisting_path = env.get("PYTHONPATH", "")env["PYTHONPATH"] = f"{cwd}{os.pathsep}{existing_path}" if existing_path else str(cwd)- return subprocess.Popen(- [- sys.executable,- "-m",- "hub.workers.hf_download",- *args,- "--parent-pid",- str(os.getpid()),- "--transport",- mode,- ],- env = env,- cwd = str(cwd),- stdout = subprocess.DEVNULL,- stderr = subprocess.PIPE,- start_new_session = sys.platform != "win32",- )+ proc = None+ try:+ proc = subprocess.Popen(+ [+ sys.executable,+ "-m",+ "hub.workers.hf_download",+ *args,+ "--parent-pid",+ str(os.getpid()),+ "--transport",+ mode,+ ],+ env = env,+ cwd = str(cwd),+ stdout = subprocess.DEVNULL,+ stderr = subprocess.PIPE,+ start_new_session = sys.platform != "win32",+ )+ return proc+ finally:+ if use_xet:+ # Tie the sizing's RAM reservation to the worker, so it frees when the worker exits and+ # a sibling starting in this window sizes against the remainder. A spawn that raised+ # passes None, which drops the reservation instead of leaking it.+ from utils import hf_xet_fallback+ hf_xet_fallback.bind_worker_budget(proc.pid if proc is not None else None)def drain_stderr_excerpt(stream, edge_bytes: int = 500) -> bytes:diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.pyindex 8b9c0053db0..147226c4e9f 100644--- a/studio/backend/hub/utils/download_registry.py+++ b/studio/backend/hub/utils/download_registry.py@@ -107,6 +107,7 @@ def get_download_transport_capabilities(*, probe: bool = False) -> DownloadTransxet_available = importlib.util.find_spec("hf_xet") is not Noneauto_transport = TRANSPORT_XET if xet_available else TRANSPORT_HTTPauto_reason: Optional[str] = None+ auto_forced = Falseif xet_available:try:from utils.hf_xet_fallback import cached_xet_health, xet_health@@ -119,9 +120,32 @@ def get_download_transport_capabilities(*, probe: bool = False) -> DownloadTransif health is not None:auto_transport = TRANSPORT_XET if health.use_xet else TRANSPORT_HTTPauto_reason = str(health.reason)+ # UNSLOTH_FORCE_XET=1: an operator override, not a measurement, so the free-RAM+ # gate below stands down exactly as `resolve_auto_use_xet` does. Same helper, so+ # the probe and the API "auto" path cannot disagree about what "forced" means.+ # Imported separately and guarded: an older or stubbed shim that lacks it must not+ # cost us the health verdict just recorded above.+ try:+ from utils.hf_xet_fallback import xet_health_is_forced+ auto_forced = bool(xet_health_is_forced(health))+ except Exception:+ auto_forced = Falseexcept Exception:# No opinion: keep the optimistic default; the download-time ladder still recovers.pass+ if xet_available and probe and auto_transport == TRANSPORT_XET and not auto_forced:+ # Free RAM belongs in the same verdict: this IS the Auto decision, since the UI submits the+ # answer as an explicit xet/http. Read outside the health try, because a health module that+ # is missing or raising says nothing about RAM. Probe-only, so an ordinary poll stays+ # read-only and still does not load Zoo.+ try:+ from utils.hf_xet_fallback import free_ram_pressure_reason+ pressure = free_ram_pressure_reason()+ except Exception:+ pressure = None+ if pressure is not None:+ auto_transport = TRANSPORT_HTTP+ auto_reason = pressurereturn DownloadTransportCapabilities(http = DownloadTransportCapability(available = True),xet = DownloadTransportCapability(diff --git a/studio/backend/tests/test_hf_xet_fallback.py b/studio/backend/tests/test_hf_xet_fallback.pyindex 8ad7b15cb93..d3f1ebec881 100644--- a/studio/backend/tests/test_hf_xet_fallback.py+++ b/studio/backend/tests/test_hf_xet_fallback.py@@ -780,3 +780,579 @@ def test_a_zoo_that_can_resize_is_asked_for_the_workers_own_cache(monkeypatch):)assert shim.apply_xet_env({}, "/new/volume/hub") == {}assert seen["applied"] is True+++# --- free-RAM clamp (issue #9032) ---------------------------------------------------------------+# The zoo sizes Xet's buffers from TOTAL RAM, which cannot see a loaded model. Studio clamps the+# result to what is free. The bar: shrink under pressure, change nothing otherwise.++_GB = 1_000_000_000+_LIMIT = "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"+++def _fake_profile_cls():+ import dataclasses++ @dataclasses.dataclass(frozen = True)+ class _Profile:+ total_ram_bytes: int+ available_ram_bytes: int+ cpu_count: int = 16+ ram_source: str = "psutil"+ cpu_source: str = "affinity"+ free_disk_bytes: int = 500 * _GB+ disk_source: str = "statvfs"++ return _Profile+++def _fake_tuning(+ total,+ available,+ *,+ calls = None,+):+ """Stand-in zoo sized like the real one (an eighth of total RAM), recording the profile it was+ asked about so a test can prove the clamp re-asks rather than editing numbers itself."""+ import types++ profile_cls = _fake_profile_cls()++ def _overrides(profile, **kwargs):+ if calls is not None:+ calls.append(profile)+ limit = max(1 * _GB, profile.total_ram_bytes // 8)+ return {+ _LIMIT: str(limit),+ "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE": str(limit // 2),+ "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_PERFILE_SIZE": str(limit // 32),+ "HF_XET_DATA_MAX_CONCURRENT_FILE_DOWNLOADS": "8",+ "HF_XET_CLIENT_AC_MAX_DOWNLOAD_CONCURRENCY": "32",+ "HF_XET_CLIENT_READ_TIMEOUT": "60s",+ }++ return types.SimpleNamespace(+ xet_env_overrides = _overrides,+ system_profile = lambda cache_dir = None: profile_cls(total, available),+ _MIN_BUFFER_LIMIT = 1 * _GB,+ _RAM_FRACTION = 8,+ )+++def test_clamp_is_a_no_op_when_the_machine_has_room(monkeypatch):+ """The design rests on this: an eighth of TOTAL cannot exceed a quarter of AVAILABLE unless RAM+ is already held, so an idle machine keeps the zoo's numbers and no download gets slower."""+ import utils.hf_xet_fallback as shim++ calls = []+ module = _fake_tuning(32 * _GB, 30 * _GB, calls = calls)+ sized = module.xet_env_overrides(module.system_profile())+ calls.clear()++ env = dict(sized)+ written = shim.clamp_to_available_ram(env, dict(sized), module = module)++ assert written == sized, "an affordable budget must come back untouched"+ assert env == sized+ assert calls == [], "re-sizing a machine that fits would burn the zero-cost guarantee"+++def test_clamp_shrinks_a_budget_free_ram_cannot_afford(monkeypatch):+ """Issue #9032: 32GB box, 27B GGUF resident, 8GB free. The zoo still hands out a 4GB buffer+ because total RAM has not changed, and that on top of the loaded weights is the swap."""+ import utils.hf_xet_fallback as shim++ calls = []+ module = _fake_tuning(32 * _GB, 8 * _GB, calls = calls)+ unclamped = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))+ calls.clear()++ env = dict(unclamped)+ written = shim.clamp_to_available_ram(env, dict(unclamped), module = module)++ budget = 8 * _GB // 4+ assert int(unclamped[_LIMIT]) > budget, "precondition: the unclamped budget overshoots"+ assert int(written[_LIMIT]) <= budget, "the clamp has to bring it inside what is free"+ assert env[_LIMIT] == written[_LIMIT], "the worker's env is what actually ships"+ assert calls, "the zoo must be the one re-sizing, so its formulas stay the single source"+ assert calls[0].total_ram_bytes < 32 * _GB, "it should be asked about a smaller machine"+ # Every derived number moves together; a limit shrunk on its own would leave the per-file and+ # concurrency values describing a budget that no longer exists.+ assert int(written["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE"]) < int(+ unclamped["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE"]+ )+++def test_clamp_bottoms_out_at_the_zoos_own_floor(monkeypatch):+ """Below the floor the answer is a different transport, not a tinier buffer: Xet has a minimum+ it can work in, and ``_memory_pressure_reason`` routes a machine this tight to HTTP."""+ import utils.hf_xet_fallback as shim++ module = _fake_tuning(32 * _GB, 1 * _GB)+ unclamped = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 1 * _GB))++ written = shim.clamp_to_available_ram({}, dict(unclamped), module = module)+ assert int(written[_LIMIT]) == module._MIN_BUFFER_LIMIT+ assert int(written[_LIMIT]) < int(unclamped[_LIMIT])+++def test_clamp_never_writes_a_key_the_user_set(monkeypatch):+ """The zoo's apply is setdefault, so a user-set variable never reaches ``sized`` and must not be+ reintroduced here. Same mechanism covers HF_XET_HIGH_PERFORMANCE: the zoo drops its caps, no+ budget key arrives, and the clamp stands down with it."""+ import utils.hf_xet_fallback as shim++ calls = []+ module = _fake_tuning(32 * _GB, 1 * _GB, calls = calls)++ # High-performance stand-down: no budget key in what the zoo wrote.+ env = {"HF_XET_HIGH_PERFORMANCE": "1"}+ assert shim.clamp_to_available_ram(env, {}, module = module) == {}+ assert env == {"HF_XET_HIGH_PERFORMANCE": "1"}+ assert calls == [], "with no caps to clamp there is nothing to re-size"++ # A user-pinned per-file size is absent from `sized` for the same reason; clamping the rest must+ # not write it back at our number.+ sized = {_LIMIT: str(8 * _GB)}+ env = {_LIMIT: str(8 * _GB), "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_PERFILE_SIZE": "999"}+ written = shim.clamp_to_available_ram(env, sized, module = module)+ assert set(written) == {_LIMIT}, "only keys the zoo wrote are ours to rewrite"+ assert env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_PERFILE_SIZE"] == "999"+++def test_clamp_stands_down_when_ram_cannot_be_measured(monkeypatch):+ """No psutil, no cgroup, or a zoo too old to expose a profile: absence of evidence is not+ evidence of pressure, so the download runs as before."""+ import types++ import utils.hf_xet_fallback as shim++ sized = {_LIMIT: str(8 * _GB)}++ unmeasurable = _fake_tuning(0, 0)+ assert shim.clamp_to_available_ram({}, dict(sized), module = unmeasurable) == sized++ old_zoo = types.SimpleNamespace(apply_xet_env = lambda *a, **k: {})+ assert shim.clamp_to_available_ram({}, dict(sized), module = old_zoo) == sized++ def _boom(*args, **kwargs):+ raise RuntimeError("no")++ raising = types.SimpleNamespace(xet_env_overrides = _boom, system_profile = _boom)+ assert (+ shim.clamp_to_available_ram({}, dict(sized), module = raising) == sized+ ), "a clamp must never be the thing that breaks a download"+++def test_clamp_holds_against_the_real_zoo_formulas():+ """The fakes above pin the seam; this pins the arithmetic, so a zoo that changes how it sizes+ cannot quietly reintroduce a budget bigger than free RAM."""+ tuning = pytest.importorskip("unsloth_zoo.hf_xet_tuning")++ idle = tuning.SystemProfile(+ total_ram_bytes = 32 * 1024**3,+ available_ram_bytes = 30 * _GB,+ cpu_count = 24,+ ram_source = "psutil",+ cpu_source = "affinity",+ free_disk_bytes = 500 * _GB,+ disk_source = "statvfs",+ )+ import dataclasses++ loaded = dataclasses.replace(idle, available_ram_bytes = 8 * _GB)++ import types++ import utils.hf_xet_fallback as shim++ sized = dict(tuning.xet_env_overrides(idle, fail_fast = True))++ def _module_for(profile):+ return types.SimpleNamespace(+ xet_env_overrides = tuning.xet_env_overrides,+ system_profile = lambda cache_dir = None: profile,+ _MIN_BUFFER_LIMIT = tuning._MIN_BUFFER_LIMIT,+ _RAM_FRACTION = tuning._RAM_FRACTION,+ )++ assert (+ shim.clamp_to_available_ram({}, dict(sized), module = _module_for(idle)) == sized+ ), "30GB free must still buy the zoo's own 32GB-machine budget"++ clamped = shim.clamp_to_available_ram({}, dict(sized), module = _module_for(loaded))+ assert int(clamped[_LIMIT]) <= 8 * _GB // 4, "a 27B model resident must shrink the budget"+ assert int(clamped[_LIMIT]) < int(sized[_LIMIT])+++def test_clamp_never_raises_a_value_the_zoo_had_lowered():+ """The recompute runs without the throttled flag that a 429 backoff sets, so the clamp must take+ the smaller of the two per key. Otherwise shrinking buffers would restore the stream ceiling."""+ import utils.hf_xet_fallback as shim++ module = _fake_tuning(32 * _GB, 8 * _GB)+ unclamped = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))+ # As if a 429 had halved the ceiling on the way in.+ throttled = dict(unclamped, HF_XET_CLIENT_AC_MAX_DOWNLOAD_CONCURRENCY = "4")++ written = shim.clamp_to_available_ram({}, dict(throttled), module = module)+ assert int(written[_LIMIT]) < int(throttled[_LIMIT]), "the budget still has to shrink"+ assert (+ written["HF_XET_CLIENT_AC_MAX_DOWNLOAD_CONCURRENCY"] == "4"+ ), "a clamp that raises anything is not a clamp"+++def test_free_ram_pressure_reason_applies_the_zoos_own_floor(monkeypatch):+ """The threshold logic itself, now that both transport callers share this one helper."""+ import utils.hf_xet_fallback as shim++ monkeypatch.setattr(shim, "available_ram_bytes", lambda: (2 * _GB, 4 * _GB))+ reason = shim.free_ram_pressure_reason()+ assert reason is not None and "2.0GB RAM free" in reason++ monkeypatch.setattr(shim, "available_ram_bytes", lambda: (4 * _GB, 4 * _GB))+ assert shim.free_ram_pressure_reason() is None, "at the floor is not below it"++ monkeypatch.setattr(shim, "available_ram_bytes", lambda: (30 * _GB, 4 * _GB))+ assert shim.free_ram_pressure_reason() is None++ monkeypatch.setattr(shim, "available_ram_bytes", lambda: (None, 4 * _GB))+ assert shim.free_ram_pressure_reason() is None, "unmeasurable is not pressure"++ def _boom():+ raise RuntimeError("no")++ monkeypatch.setattr(shim, "available_ram_bytes", _boom)+ assert shim.free_ram_pressure_reason() is None+++# --- concurrent-worker reservations --------------------------------------------------------------+# A worker allocates in the child, after Popen returns, so free RAM does not move until well after+# sizing. Without reservations, downloads starting together each read the same untouched number.++[email protected](autouse = True)+def clean_ledger():+ """Autouse: sizing reserves RAM, so any clamp test leaves a reservation that would otherwise+ follow the process into the next test and shrink its budget."""+ import utils.hf_xet_fallback as shim++ shim._budget_reservations.clear()+ shim._pending_reservation.token = None+ yield shim+ shim._budget_reservations.clear()+ shim._pending_reservation.token = None+++def test_workers_starting_together_do_not_promise_the_same_ram_twice(clean_ledger):+ """Four downloads queued at once each used to take a quarter of the same snapshot, promising the+ whole machine before any of them had allocated a byte."""+ import os++ shim = clean_ledger+ module = _fake_tuning(32 * _GB, 8 * _GB)+ sized = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))++ promised, budgets = 0, []+ for _ in range(4):+ written = shim.clamp_to_available_ram({}, dict(sized), module = module)+ shim.bind_worker_budget(os.getpid()) # this process stands in for a live worker+ budgets.append(int(written[_LIMIT]))+ promised += budgets[-1]++ # Strictly under, not merely equal: without the ledger these four land on exactly 8GB, a+ # quarter each of the same snapshot, which is the whole bug.+ assert promised < 8 * _GB, f"four workers promised {promised / _GB:.2f}GB of 8GB free"+ assert budgets[1] < budgets[0], "the second worker ignored what the first was already promised"+++def test_a_reservation_frees_when_its_worker_exits(clean_ledger):+ """Held forever, one finished download would shrink every later one on the machine."""+ import subprocess+ import sys++ shim = clean_ledger+ module = _fake_tuning(32 * _GB, 8 * _GB)+ sized = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))++ dead = subprocess.Popen([sys.executable, "-c", ""])+ dead.wait()+ shim.clamp_to_available_ram({}, dict(sized), module = module)+ shim.bind_worker_budget(dead.pid)++ with shim._budget_lock:+ assert shim._live_reserved_locked() == 0, "a finished worker still held RAM"+++def test_a_spawn_that_never_happened_does_not_leak(clean_ledger):+ """Popen raising must not strand the reservation its sizing took."""+ shim = clean_ledger+ module = _fake_tuning(32 * _GB, 8 * _GB)+ sized = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))++ shim.clamp_to_available_ram({}, dict(sized), module = module)+ shim.bind_worker_budget(None)+ with shim._budget_lock:+ assert shim._live_reserved_locked() == 0++ # And one never bound at all ages out rather than pinning RAM for the process's life.+ shim.clamp_to_available_ram({}, dict(sized), module = module)+ for entry in shim._budget_reservations.values():+ entry[2] -= shim._UNBOUND_RESERVATION_TTL + 1+ with shim._budget_lock:+ assert shim._live_reserved_locked() == 0+++def test_one_download_on_an_idle_machine_is_still_untouched(clean_ledger):+ """The ledger must not cost the common case: nothing is reserved yet, so sizing is the zoo's."""+ shim = clean_ledger+ module = _fake_tuning(32 * _GB, 30 * _GB)+ sized = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 30 * _GB))++ assert shim.clamp_to_available_ram({}, dict(sized), module = module) == sized+++def test_the_transport_gate_counts_ram_promised_to_running_downloads(clean_ledger, monkeypatch):+ """The clamp bottoms out at Xet's floor, so enough simultaneous workers would still add up past+ free RAM. Subtracting reservations sends the next one to HTTP instead.++ Both halves of that guard are asserted, because the promise and the RAM reading cover different+ moments: three just-admitted workers have taken nothing yet, so only the ledger can stop the+ fourth; three that have finished allocating are already missing from `available`, which stops it+ without the ledger. `os.getpid()` stands in for all three, so its own RSS is stubbed out rather+ than credited three times against promises it has nothing to do with."""+ import os++ shim = clean_ledger+ monkeypatch.setattr(shim, "available_ram_bytes", lambda: (8 * _GB, 4 * _GB))+ assert shim.free_ram_pressure_reason() is None, "8GB free is not pressure on its own"++ module = _fake_tuning(32 * _GB, 8 * _GB)+ sized = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))+ monkeypatch.setattr(shim, "_worker_rss", lambda pid: 0) # spawned, nothing allocated yet+ promised = 0+ for _ in range(3):+ written = shim.clamp_to_available_ram({}, dict(sized), module = module)+ shim.bind_worker_budget(os.getpid())+ promised += int(written[_LIMIT])++ reason = shim.free_ram_pressure_reason()+ assert reason is not None, "three running downloads left too little RAM for a fourth on Xet"+ assert "RAM free" in reason++ # Same three workers once their buffers are resident: the promises are spent, and the RAM+ # reading they have already moved is what refuses the fourth.+ monkeypatch.setattr(shim, "_worker_rss", lambda pid: promised)+ monkeypatch.setattr(shim, "available_ram_bytes", lambda: (8 * _GB - promised, 4 * _GB))+ assert (+ shim.free_ram_pressure_reason() is not None+ ), "three allocated downloads left too little RAM for a fourth on Xet"+++def test_a_resident_promise_is_not_charged_against_free_ram_twice(clean_ledger, monkeypatch):+ """Once a worker's buffers are resident, `available` has already dropped by them.++ The reservation exists to cover the gap between sizing and allocation, so charging the whole+ promise on top of a reading that already reflects it counts the same bytes twice for the+ worker's entire lifetime. On an 8GB-free host that is the difference between the next Auto+ download getting Xet and being told "only 2.0GB RAM free" while 4GB genuinely is."""+ import os++ shim = clean_ledger+ module = _fake_tuning(32 * _GB, 8 * _GB)+ sized = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))++ written = shim.clamp_to_available_ram({}, dict(sized), module = module)+ promise = int(written[_LIMIT])+ shim.bind_worker_budget(os.getpid())++ # Not yet allocated: the promise is the only thing standing between the sibling and this RAM.+ monkeypatch.setattr(shim, "_worker_rss", lambda pid: 0)+ with shim._budget_lock:+ assert shim._live_reserved_locked() == promise++ # Allocated: `available` fell by `promise`, so the ledger must stop asking for it again.+ monkeypatch.setattr(shim, "_worker_rss", lambda pid: promise)+ with shim._budget_lock:+ assert shim._live_reserved_locked() == 0, "a resident promise was subtracted a second time"++ # Half in flight leaves exactly the unmaterialized half reserved.+ monkeypatch.setattr(shim, "_worker_rss", lambda pid: promise // 2)+ with shim._budget_lock:+ assert shim._live_reserved_locked() == promise - promise // 2++ # And the gate follows: 8GB free with one fully resident 2GB worker is 6GB, not 4GB, so Auto+ # for the next download stays on Xet.+ monkeypatch.setattr(shim, "available_ram_bytes", lambda: (8 * _GB - promise, 4 * _GB))+ monkeypatch.setattr(shim, "_worker_rss", lambda pid: promise)+ assert (+ shim.free_ram_pressure_reason() is None+ ), "the next Auto download was demoted to HTTP over RAM its sibling never took"+++def test_the_ledger_reads_a_real_workers_rss(clean_ledger):+ """The credit above is only correct if the psutil read actually works on a live child."""+ import subprocess+ import sys++ shim = clean_ledger+ child = subprocess.Popen(+ [sys.executable, "-c", "import sys; sys.stdin.read()"],+ stdin = subprocess.PIPE,+ )+ try:+ rss = shim._worker_rss(child.pid)+ assert rss > 0, "a running interpreter reported no resident memory"+ finally:+ child.stdin.close()+ child.wait(timeout = 30)++ # An exited worker cannot be read, and an unreadable one keeps its whole promise reserved.+ assert shim._worker_rss(child.pid) == 0 or not shim._pid_alive(child.pid)+++def test_concurrent_sizings_cannot_all_claim_the_same_free_ram(clean_ledger):+ """The reservation tests above start workers one after another, which never exercises the race:+ read the ledger, then reserve, with a gap in between. These threads sit in that gap together.++ The barrier is in system_profile, which the clamp reads OUTSIDE the lock, so all four arrive at+ the decision at once; the sleep in xet_env_overrides widens the read-to-reserve window that a+ split critical section would leave open."""+ import os+ import threading+ import time++ shim = clean_ledger+ workers = 4+ barrier = threading.Barrier(workers)+ profile_cls = _fake_profile_cls()+ profile = profile_cls(32 * _GB, 8 * _GB)++ def _overrides(prof, **kwargs):+ time.sleep(0.02)+ limit = max(1 * _GB, prof.total_ram_bytes // 8)+ return {+ _LIMIT: str(limit),+ "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_SIZE": str(limit // 2),+ "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_PERFILE_SIZE": str(limit // 32),+ "HF_XET_DATA_MAX_CONCURRENT_FILE_DOWNLOADS": "8",+ }++ def _profile_of(cache_dir = None):+ barrier.wait(timeout = 10)+ return profile++ module = _types.SimpleNamespace(+ xet_env_overrides = _overrides,+ system_profile = _profile_of,+ _MIN_BUFFER_LIMIT = 1 * _GB,+ _RAM_FRACTION = 8,+ )+ sized = _overrides(profile)++ granted: list[int] = []+ lock = threading.Lock()++ def _size():+ written = shim.clamp_to_available_ram({}, dict(sized), module = module)+ shim.bind_worker_budget(os.getpid())+ with lock:+ granted.append(int(written[_LIMIT]))++ threads = [threading.Thread(target = _size) for _ in range(workers)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout = 30)++ assert len(granted) == workers, "a sizing thread never finished"+ total = sum(granted)+ assert total < 8 * _GB, (+ f"{workers} concurrent sizings promised {total / _GB:.2f}GB of 8GB free; "+ "the ledger read and the reservation are not one decision"+ )+ assert len(set(granted)) > 1, "identical budgets means they all read the same snapshot"+++def test_the_ledgers_liveness_probe_never_signals_on_windows(clean_ledger, monkeypatch):+ """`os.kill(pid, 0)` is not a probe on Windows.++ CPython's `os_kill_impl` routes every signal other than CTRL_C_EVENT/CTRL_BREAK_EVENT into+ `OpenProcess(PROCESS_ALL_ACCESS)` + `TerminateProcess(handle, sig)`, so signal 0 KILLS the+ target. The ledger prunes dead reservations on every sizing and on every capability probe, so+ the old probe would terminate a running download merely because a second one was considered."""+ import os as _os++ import utils.process_lifetime as pl++ shim = clean_ledger+ monkeypatch.setattr(pl, "_is_windows", lambda: True)++ signalled: list[tuple] = []++ def _forbidden(pid, sig):+ signalled.append((pid, sig))+ raise AssertionError("os.kill must never be reached on Windows")++ monkeypatch.setattr(_os, "kill", _forbidden)++ shim._pid_alive(_os.getpid())+ assert signalled == [], "the liveness probe signalled the worker it was asking about"+++def test_a_running_worker_keeps_its_reservation_on_windows(clean_ledger, monkeypatch):+ """The Windows probe must also answer correctly, or every reservation is pruned on sight and+ concurrent workers go back to promising the same free RAM."""+ import ctypes+ import os as _os++ import utils.process_lifetime as pl++ shim = clean_ledger+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(_os, "kill", _fail_on_kill)++ WAIT_TIMEOUT = 0x102++ class _FakeKernel32:+ def __init__(self, *_args, **_kwargs):+ self.OpenProcess = _FakeFn(0xBEEF)+ self.WaitForSingleObject = _FakeFn(WAIT_TIMEOUT) # still running+ self.CloseHandle = _FakeFn(1)++ monkeypatch.setattr(ctypes, "WinDLL", _FakeKernel32, raising = False)++ assert shim._pid_alive(4321) is True++ module = _fake_tuning(32 * _GB, 8 * _GB)+ sized = module.xet_env_overrides(_fake_profile_cls()(32 * _GB, 8 * _GB))+ shim.clamp_to_available_ram({}, dict(sized), module = module)+ shim.bind_worker_budget(4321)+ with shim._budget_lock:+ assert shim._live_reserved_locked() > 0, "a live Windows worker's reservation was pruned"++ # And an exited worker (handle signalled) frees its reservation.+ class _FakeKernel32Dead(_FakeKernel32):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.WaitForSingleObject = _FakeFn(0) # WAIT_OBJECT_0: exited++ monkeypatch.setattr(ctypes, "WinDLL", _FakeKernel32Dead, raising = False)+ with shim._budget_lock:+ assert shim._live_reserved_locked() == 0, "an exited Windows worker still held RAM"+++class _FakeFn:+ """A stand-in for a ctypes function pointer: assignable argtypes/restype, fixed return."""++ def __init__(self, result):+ self._result = result+ self.argtypes = None+ self.restype = None++ def __call__(self, *_args, **_kwargs):+ return self._result+++def _fail_on_kill(pid, sig):+ raise AssertionError("os.kill must never be reached on Windows")diff --git a/studio/backend/tests/test_hub_download_transport_auto.py b/studio/backend/tests/test_hub_download_transport_auto.pyindex 0df90595edc..4dd04caf0d6 100644--- a/studio/backend/tests/test_hub_download_transport_auto.py+++ b/studio/backend/tests/test_hub_download_transport_auto.py@@ -555,3 +555,284 @@ def test_the_worker_never_gets_the_flag_and_our_caps_together(monkeypatch):flag_on = env.get("HF_XET_HIGH_PERFORMANCE", "0").strip().lower() in ("1", "true", "yes", "on")sized = "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_PERFILE_SIZE" in envassert not (flag_on and sized), f"worst of both: flag on with our sizing still applied ({env})"+++# --- free-RAM transport gate (issue #9032) -------------------------------------------------------+++def test_auto_picks_http_when_free_ram_is_below_the_xet_floor(monkeypatch):+ """The zoo already refuses Xet under MIN_XET_RAM_BYTES, but asks TOTAL RAM, which cannot see a+ loaded 27B GGUF. Same rule, asked of free RAM."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: _types.SimpleNamespace(use_xet = True, reason = "Xet")+ fake.free_ram_pressure_reason = lambda: "HTTP: only 2.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ use_xet, reason = dl.resolve_auto_use_xet()+ assert use_xet is False+ assert "2.0GB RAM free" in reason, "the user needs to read why their download changed transport"+++def test_free_ram_gate_leaves_a_machine_with_room_alone(monkeypatch):+ """The gate is for the pressured case only: with headroom the health verdict still decides, so+ no download drops to the slower sequential writer for nothing."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: _types.SimpleNamespace(use_xet = True, reason = "Xet")+ fake.free_ram_pressure_reason = lambda: None+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ assert dl.resolve_auto_use_xet() == (True, "Xet")+++def test_free_ram_gate_never_decides_the_transport_by_failing(monkeypatch):+ """An unmeasurable machine, or a shim too old to expose the probe, is not evidence of pressure."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)++ for probe in (+ None, # older shim: attribute missing entirely+ lambda: None, # psutil absent: RAM unmeasurable+ lambda: (_ for _ in ()).throw(RuntimeError()), # probe itself raises+ ):+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: _types.SimpleNamespace(use_xet = True, reason = "Xet")+ if probe is not None:+ fake.free_ram_pressure_reason = probe+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ assert dl.resolve_auto_use_xet() == (True, "Xet")+++def test_a_demoted_health_verdict_is_not_second_guessed(monkeypatch):+ """The gate only demotes. A machine already on HTTP keeps the zoo's reason, so the user reads+ the real cause instead of a free-RAM number that was never the problem."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: _types.SimpleNamespace(use_xet = False, reason = "Xet stalled twice")+ fake.free_ram_pressure_reason = lambda: "HTTP: only 1.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ assert dl.resolve_auto_use_xet() == (False, "Xet stalled twice")+++def test_the_auto_probe_carries_the_free_ram_verdict(monkeypatch):+ """The UI never sends "auto": effectiveTransportMode() resolves it through this probe and submits+ the answer as an explicit xet/http, which resolve_requested_use_xet honours without consulting+ resolve_auto_use_xet. So the gate has to live here or the primary flow never sees it."""+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.cached_xet_health = lambda **kw: _types.SimpleNamespace(use_xet = True, reason = "Xet")+ fake.xet_health = fake.cached_xet_health+ fake.free_ram_pressure_reason = lambda: "HTTP: only 2.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())++ caps = download_registry.get_download_transport_capabilities(probe = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTP+ assert "2.0GB RAM free" in caps.auto_reason+++def test_a_browse_poll_never_reads_free_ram(monkeypatch):+ """probe=False is the read-only poll behind opening Hub. It must stay off the zoo, so the free-RAM+ reading is probe-only like the health verdict it rides along with."""+ called: list[str] = []+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.cached_xet_health = lambda **kw: _types.SimpleNamespace(use_xet = True, reason = "Xet")+ fake.xet_health = fake.cached_xet_health+ fake.free_ram_pressure_reason = lambda: called.append("read") or "HTTP: pressured"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())++ caps = download_registry.get_download_transport_capabilities()+ assert called == [], "a browse poll measured RAM"+ assert caps.auto_resolves_to == download_registry.TRANSPORT_XET+++def test_the_probe_does_not_override_a_health_demotion(monkeypatch):+ """Health already said HTTP; the free-RAM read is skipped and its reason does not replace one the+ user is better served by."""+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.cached_xet_health = lambda **kw: _types.SimpleNamespace(+ use_xet = False, reason = "Xet failed 2 times in a row on this machine"+ )+ fake.xet_health = fake.cached_xet_health+ fake.free_ram_pressure_reason = lambda: "HTTP: only 2.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())++ caps = download_registry.get_download_transport_capabilities(probe = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTP+ assert "2 times" in caps.auto_reason+++def test_the_probe_survives_a_shim_without_the_free_ram_helper(monkeypatch):+ """An older shim has no free_ram_pressure_reason; the probe keeps the health verdict."""+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.cached_xet_health = lambda **kw: _types.SimpleNamespace(use_xet = True, reason = "Xet")+ fake.xet_health = fake.cached_xet_health+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())++ caps = download_registry.get_download_transport_capabilities(probe = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_XET+ assert caps.auto_reason == "Xet"+++def test_the_gate_runs_when_health_has_no_verdict(monkeypatch):+ """Health lives in unsloth_zoo.hf_xet_health, free RAM in unsloth_zoo.hf_xet_tuning. A zoo too+ old for the first says nothing about the second, so "no opinion" must not skip the RAM read."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: None+ fake.free_ram_pressure_reason = lambda: "HTTP: only 2.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ assert dl.resolve_auto_use_xet() == (False, "HTTP: only 2.0GB RAM free")+++def test_the_gate_runs_when_the_health_probe_raises(monkeypatch):+ """Same for a health module that blows up: the failure is evidence about health, not about RAM."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)++ def _boom(**kw):+ raise RuntimeError("no")++ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = _boom+ fake.free_ram_pressure_reason = lambda: "HTTP: only 2.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ assert dl.resolve_auto_use_xet() == (False, "HTTP: only 2.0GB RAM free")+++def test_no_health_and_no_pressure_still_reads_as_xet(monkeypatch):+ """The optimistic default survives when neither probe objects, including its wording."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)++ def _boom(**kw):+ raise RuntimeError("no")++ for health_fn, expected in (+ (lambda **kw: None, "Xet"),+ (_boom, "Xet (health check unavailable)"),+ ):+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = health_fn+ fake.free_ram_pressure_reason = lambda: None+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ assert dl.resolve_auto_use_xet() == (True, expected)+++def test_the_probe_reads_free_ram_even_when_health_raises(monkeypatch):+ """Registry mirror of the above: the RAM read sits outside the health try, so a raising health+ module cannot take the free-RAM verdict down with it."""++ def _boom(**kw):+ raise RuntimeError("no")++ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.cached_xet_health = _boom+ fake.xet_health = _boom+ fake.free_ram_pressure_reason = lambda: "HTTP: only 2.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())++ caps = download_registry.get_download_transport_capabilities(probe = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTP+ assert "2.0GB RAM free" in caps.auto_reason+++def test_spawn_binds_the_ram_reservation_to_the_worker(monkeypatch):+ """The sizing reserves RAM for a spawn that has not happened yet. spawn_worker has to hand that+ reservation the worker's pid, or it ages out and siblings oversubscribe the machine."""+ import utils.hf_xet_fallback as shim++ bound = []+ monkeypatch.setattr(shim, "bind_worker_budget", lambda pid: bound.append(pid))+ _spawn_env(monkeypatch, use_xet = True)+ assert bound == [4242], "the worker's pid never reached the reservation"++ bound.clear()+ _spawn_env(monkeypatch, use_xet = False)+ assert bound == [], "an HTTP worker allocates no Xet buffers, so it reserves nothing"+++def test_a_failed_spawn_releases_its_reservation(monkeypatch):+ """Popen raising must drop the reservation rather than pin RAM until it ages out."""+ import utils.hf_xet_fallback as shim++ bound = []+ monkeypatch.setattr(shim, "bind_worker_budget", lambda pid: bound.append(pid))++ def _boom(*a, **k):+ raise OSError("no fork for you")++ paths = _types.SimpleNamespace(child_env = lambda *a, **k: {})+ fake_settings = _types.ModuleType("utils.hf_cache_settings")+ fake_settings.get_hf_cache_paths = lambda: paths+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", fake_settings)+ monkeypatch.setattr(dl.subprocess, "Popen", _boom)++ with pytest.raises(OSError):+ dl.spawn_worker(["--repo-id", "a/b"], None, use_xet = True)+ assert bound == [None], "a spawn that never produced a process must release, not leak"+++def test_the_force_xet_escape_hatch_still_wins_over_the_free_ram_gate(monkeypatch):+ """`UNSLOTH_FORCE_XET=1` is an operator override, not a measurement.++ `unsloth_zoo.hf_xet_health` stamps `source = "forced"` on both env verdicts, and the OFF+ switches already win (the `not health.use_xet` return above). Without the same stand-down for+ the ON switch the pair is asymmetric: the zoo's own log tells the operator to "set+ UNSLOTH_FORCE_XET=1 to override", and the new RAM gate would ignore it. Buffers are still+ clamped to free RAM, so forcing costs the transport choice, not the memory bound."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)++ forced = _types.SimpleNamespace(+ use_xet = True, reason = "Xet forced by environment", source = "forced"+ )+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: forced+ fake.xet_health_is_forced = lambda h: getattr(h, "source", "") == "forced"+ fake.free_ram_pressure_reason = lambda: "HTTP: only 1.0GB RAM free (Xet wants 4GB)"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ assert dl.resolve_auto_use_xet() == (True, "Xet forced by environment")++ # The OFF switch keeps winning, and keeps its own reason.+ off = _types.SimpleNamespace(+ use_xet = False, reason = "Xet disabled by environment", source = "forced"+ )+ fake.xet_health = lambda **kw: off+ assert dl.resolve_auto_use_xet() == (False, "Xet disabled by environment")++ # An ordinary measured verdict is still gated by free RAM.+ measured = _types.SimpleNamespace(use_xet = True, reason = "Xet", source = "probe")+ fake.xet_health = lambda **kw: measured+ used, reason = dl.resolve_auto_use_xet()+ assert used is False and "RAM free" in reason+++def test_the_capabilities_probe_agrees_about_a_forced_verdict(monkeypatch):+ """The probe is where the UI's Auto is actually resolved, so it must stand down identically or+ the picker and the API caller disagree about what UNSLOTH_FORCE_XET means."""+ forced = _types.SimpleNamespace(+ use_xet = True, reason = "Xet forced by environment", source = "forced"+ )+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.cached_xet_health = lambda **kw: forced+ fake.xet_health = lambda **kw: forced+ fake.xet_health_is_forced = lambda h: getattr(h, "source", "") == "forced"+ fake.free_ram_pressure_reason = lambda: "HTTP: only 1.0GB RAM free (Xet wants 4GB)"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda name: object())++ caps = download_registry.get_download_transport_capabilities(probe = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_XET+ assert caps.auto_reason == "Xet forced by environment"++ # A shim too old to answer "is this forced" must not cost the health verdict, and must leave+ # the RAM gate in force rather than silently forcing Xet.+ del fake.xet_health_is_forced+ caps = download_registry.get_download_transport_capabilities(probe = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTP+ assert "RAM free" in (caps.auto_reason or "")diff --git a/studio/backend/utils/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.pyindex d83a0329073..8c307ce8834 100644--- a/studio/backend/utils/hf_xet_fallback.py+++ b/studio/backend/utils/hf_xet_fallback.py@@ -22,6 +22,7 @@ from __future__ import annotationsimport osimport threading+import timefrom functools import partialfrom pathlib import Pathfrom typing import Any, Callable, Optional@@ -249,6 +250,20 @@ def xet_health(**kwargs: Any) -> Any:return _xet_health_from(module, **kwargs)+def xet_health_is_forced(health: Any) -> bool:+ """Is *health* an operator override rather than a measurement of this machine?++ ``unsloth_zoo.hf_xet_health`` stamps ``source = "forced"`` on exactly the two env-var verdicts:+ ``UNSLOTH_DISABLE_XET`` / ``UNSLOTH_STABLE_DOWNLOADS`` / ``HF_HUB_DISABLE_XET`` turning Xet OFF,+ and ``UNSLOTH_FORCE_XET`` turning it ON. Callers already honour the off switches by returning+ early, so this exists for the on switch: the free-RAM gate must stand down for it, or Unsloth+ ships an escape hatch that only works in one direction.++ Anything unreadable (an older zoo whose verdict has no ``source``, a test double) answers False,+ which leaves the RAM gate in force -- the safe default."""+ return health is not None and str(getattr(health, "source", "")) == "forced"++def record_xet_outcome(ok: bool, reason: str = "") -> None:"""Record a finished Xet attempt so a repeatedly-failing machine stops starting on Xet."""module = _load_optional("unsloth_zoo.hf_xet_health")@@ -284,19 +299,331 @@ def apply_xet_env(env: dict, cache_dir: "Optional[str]" = None) -> "Optional[dic*env* is a copy of this process's environment, which already carries the zoo's import-timesizing, and applying is setdefault: on a zoo that can resize we recompute for *cache_dir*instead, so a backend whose cache has since moved does not hand the worker the old volume's- numbers. Older zoos keep the previous behaviour."""+ numbers. Older zoos keep the previous behaviour.++ The zoo sizes from TOTAL RAM, which cannot see a model already loaded, so the result passes+ through :func:`clamp_to_available_ram` before it reaches the worker."""module = _load_optional("unsloth_zoo.hf_xet_tuning")if module is None or not hasattr(module, "apply_xet_env"):return Nonetry:resize = getattr(module, "resize_for_cache_dir", None)if resize is not None:- return dict(resize(env, cache_dir))- return dict(module.apply_xet_env(env, fail_fast = True))+ sized = dict(resize(env, cache_dir))+ else:+ sized = dict(module.apply_xet_env(env, fail_fast = True))except Exception as exc: # noqa: BLE001import logging as _logging_logging.getLogger(__name__).debug("apply_xet_env failed: %s", exc)return None+ return clamp_to_available_ram(env, sized, cache_dir = cache_dir, module = module)+++# Share of free RAM a download may turn into buffers. A quarter of AVAILABLE always exceeds the+# zoo's eighth of TOTAL on an idle machine, so the clamp is unreachable unless RAM is actually held.+_AVAILABLE_RAM_SHARE = 4+# Integer arithmetic converges in one or two passes; the bound only guards a future non-monotonic zoo.+_CLAMP_MAX_PASSES = 3+_BUFFER_LIMIT_KEY = "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"+++def _as_int(value: str) -> "Optional[int]":+ """``value`` as a plain int, or None for the unit-suffixed ones ("60s") that never scale."""+ try:+ return int(str(value).strip())+ except (TypeError, ValueError):+ return None+++# --- concurrent-worker budget ledger -------------------------------------------------------------+# A worker allocates inside the child, after Popen returns, so free RAM does not drop until well+# after we sized it. Four downloads starting together would each read the same untouched `available`+# and each take a quarter of it, promising the whole machine. Reservations bridge that window:+# sizing subtracts what live siblings were already promised but have not yet taken. Only the+# unmaterialized remainder, because once a worker's buffers are resident `available` has ALREADY+# dropped by them: charging the whole promise on top of that reading counts the same bytes twice,+# for the worker's entire lifetime, and talks the next download out of RAM that is genuinely free.+# RLock: the clamp holds this across its whole decide-and-reserve region, and the reserve retakes it.+_budget_lock = threading.RLock()+# token -> [bytes, pid or None, monotonic stamp]+_budget_reservations: "dict[int, list]" = {}+_budget_token_seq = 0+# A reservation never bound to a pid means the spawn died between sizing and Popen.+_UNBOUND_RESERVATION_TTL = 60.0+# Backstop against pid reuse keeping a dead reservation alive; no download worker outlives this.+_BOUND_RESERVATION_TTL = 12 * 60 * 60.0+# Set by the sizing call, consumed by the spawn that follows it on the SAME thread.+_pending_reservation = threading.local()+++def _pid_alive(pid: int) -> bool:+ """Is *pid* still running? Platform-aware, because this probe must not have side effects.++ NOT ``os.kill(pid, 0)``: on Windows CPython maps every signal other than ``CTRL_C_EVENT`` /+ ``CTRL_BREAK_EVENT`` onto ``TerminateProcess(handle, sig)``, so signal 0 would KILL the download+ worker this ledger is merely asking about. ``utils.process_lifetime`` already carries the+ handle-based probe (``OpenProcess`` + ``WaitForSingleObject``); reuse it rather than growing a+ second copy that can drift."""+ try:+ from utils.process_lifetime import _pid_alive as _platform_pid_alive+ return bool(_platform_pid_alive(pid))+ except Exception: # noqa: BLE001 - fall through to the POSIX probe below+ pass+ if os.name == "nt":+ # No platform probe available: assume alive rather than reach for os.kill, so a reservation+ # is at worst held too long instead of a running download being terminated.+ return True+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ except OSError:+ return True+ return True+++def _worker_rss(pid: int) -> int:+ """Physical RAM *pid* already holds, or ``0`` when it cannot be read.++ ``rss`` is psutil's portable field: RES on Linux, resident size on macOS, ``WorkingSetSize`` on+ Windows. All three are physical pages, which is the same quantity ``virtual_memory().available``+ has already been reduced by, so it is the right thing to credit against a promise.++ Zero on any failure (no psutil, the worker exited between the liveness probe and here, Windows+ ``AccessDenied``), which reserves the whole promise -- the conservative pre-credit behaviour."""+ try:+ import psutil # noqa: PLC0415 - optional, and only on the ledger path+ return max(0, int(psutil.Process(pid).memory_info().rss))+ except Exception: # noqa: BLE001 - an unreadable worker is not evidence it allocated nothing+ return 0+++def _live_reserved_locked() -> int:+ """Bytes promised to live workers that are NOT YET RESIDENT, pruning anything finished or never+ spawned.++ A promise covers the gap between sizing and allocation. The hf_xet buffer is an adjustable+ semaphore, so the worker draws on it as terms arrive rather than allocating it up front; every+ byte it has drawn is already missing from ``available``. Subtracting the whole promise from that+ reading charges the resident part a second time, which is why the credit is capped at the+ promise: a fully materialized worker contributes nothing further, a freshly spawned one still+ contributes all of it."""+ now = time.monotonic()+ total = 0+ for token, entry in list(_budget_reservations.items()):+ nbytes, pid, stamp = entry+ if pid is None:+ if now - stamp > _UNBOUND_RESERVATION_TTL:+ _budget_reservations.pop(token, None)+ else:+ total += nbytes # nothing spawned yet, so nothing of it is resident+ continue+ if now - stamp > _BOUND_RESERVATION_TTL or not _pid_alive(pid):+ _budget_reservations.pop(token, None)+ continue+ total += max(0, nbytes - _worker_rss(pid))+ return total+++def _reserve_worker_budget(nbytes: int) -> None:+ """Hold *nbytes* against this thread's imminent spawn, replacing any reservation it still owns+ (a retried sizing must not stack)."""+ global _budget_token_seq+ with _budget_lock:+ stale = getattr(_pending_reservation, "token", None)+ if stale is not None:+ _budget_reservations.pop(stale, None)+ _budget_token_seq += 1+ token = _budget_token_seq+ _budget_reservations[token] = [max(0, int(nbytes)), None, time.monotonic()]+ _pending_reservation.token = token+++def bind_worker_budget(pid: "Optional[int]") -> None:+ """Attach the reservation this thread just made to *pid*, so it frees when the worker exits.++ ``None`` drops it, for a spawn that never produced a process."""+ token = getattr(_pending_reservation, "token", None)+ _pending_reservation.token = None+ if token is None:+ return+ with _budget_lock:+ entry = _budget_reservations.get(token)+ if entry is None:+ return+ if pid is None:+ _budget_reservations.pop(token, None)+ else:+ entry[1], entry[2] = int(pid), time.monotonic()+++def clamp_to_available_ram(+ env: dict,+ sized: "dict[str, str]",+ *,+ cache_dir: "Optional[str]" = None,+ module: Any = None,+) -> "dict[str, str]":+ """Shrink a zoo-sized ``HF_XET_*`` budget that free RAM cannot afford. Returns what *env* holds.++ hf_xet's reconstruction buffers are the worker's RSS, not reclaimable page cache. Sized from+ total RAM, a download started while a 27B GGUF is resident asks for the same multi-GB budget it+ would on an idle box, and the two together are the swap (issue #9032).++ A clamp, not a second sizing formula: the zoo keeps deciding, this only hands it a smaller+ machine, so the two cannot drift. Three properties:++ - Free when there is headroom: a budget that fits returns untouched.+ - Only keys the zoo wrote are rewritten, so an explicit user setting survives. A user-set+ ``HF_XET_HIGH_PERFORMANCE`` makes the zoo drop its caps, leaving no budget key to clamp.+ - Unmeasurable RAM, or a zoo too old to report it, leaves the download alone.++ Whatever budget ends up in force is reserved for this thread's imminent spawn, so siblings+ starting in the same window size against the remainder instead of against the same snapshot.+ ``bind_worker_budget`` ties that reservation to the worker's pid.+ """+ if module is None:+ module = _load_optional("unsloth_zoo.hf_xet_tuning")+ overrides = getattr(module, "xet_env_overrides", None)+ profile_of = getattr(module, "system_profile", None)+ if overrides is None or profile_of is None or _BUFFER_LIMIT_KEY not in sized:+ return sized+ try:+ import dataclasses++ profile = profile_of(cache_dir)+ available = int(getattr(profile, "available_ram_bytes", 0) or 0)+ total = int(getattr(profile, "total_ram_bytes", 0) or 0)+ if available <= 0 or total <= 0:+ return sized+ floor = int(getattr(module, "_MIN_BUFFER_LIMIT", 1_000_000_000))+ limit = int(sized[_BUFFER_LIMIT_KEY])+ # Reading the ledger and reserving against it is ONE decision. Split across two critical+ # sections, concurrent workers all read the same total before any of them wrote, which is+ # the very overcommit the ledger exists to stop. The recompute inside is pure arithmetic on+ # a frozen profile, so holding the lock across it costs microseconds; the RAM/disk reading+ # above stays outside. `_budget_lock` is an RLock because `_reserve_worker_budget` retakes+ # it here.+ with _budget_lock:+ unclaimed = max(0, available - _live_reserved_locked())+ budget = max(floor, unclaimed // _AVAILABLE_RAM_SHARE)+ if limit <= budget:+ # Still reserved: four unclamped workers would otherwise promise four full budgets.+ _reserve_worker_budget(limit)+ return sized++ # Re-ask the zoo about a machine the download can afford, so buffer, per-file and file+ # count all scale together instead of the limit moving on its own.+ fraction = int(getattr(module, "_RAM_FRACTION", 8)) or 8+ synthetic = max(floor, budget * fraction)+ clamped = sized+ for _ in range(_CLAMP_MAX_PASSES):+ candidate = dict(+ overrides(+ dataclasses.replace(+ profile,+ total_ram_bytes = min(total, synthetic),+ available_ram_bytes = available,+ ),+ fail_fast = True,+ )+ )+ clamped = candidate+ new_limit = int(candidate[_BUFFER_LIMIT_KEY])+ if new_limit <= budget:+ break+ # Monotonic in total RAM, so scaling by the overshoot converges.+ synthetic = max(floor, synthetic * budget // new_limit)++ # Reduce-only: keep a value the recompute would RAISE. `xet_env_overrides` is called raw+ # here, without the throttled flag `apply_xet_env` threads through after a 429, so an+ # un-throttled recompute could otherwise hand back the stream ceiling that backoff+ # lowered. Every derived number is monotonic in total RAM, so taking the smaller of the+ # two is always a coherent config.+ written = {}+ for key, value in clamped.items():+ if key not in sized:+ continue+ before, after = _as_int(sized[key]), _as_int(value)+ written[key] = (+ sized[key]+ if before is not None and after is not None and after > before+ else value+ )+ env.update(written)+ effective = _as_int(written.get(_BUFFER_LIMIT_KEY, "")) or budget+ _reserve_worker_budget(effective)+ import logging as _logging++ _logging.getLogger(__name__).info(+ "Xet download buffers clamped to free RAM: %.2fGB -> %.2fGB "+ "(%.1fGB free of %.1fGB total, %.2fGB promised to running downloads and not yet taken)",+ limit / 1e9,+ effective / 1e9,+ available / 1e9,+ total / 1e9,+ (available - unclaimed) / 1e9,+ )+ return written+ except Exception as exc: # noqa: BLE001 - a clamp must never be what breaks a download+ import logging as _logging+ _logging.getLogger(__name__).debug("clamp_to_available_ram failed: %s", exc)+ return sized+++def available_ram_bytes() -> "tuple[Optional[int], int]":+ """``(free RAM right now, the floor Xet wants)``; ``(None, floor)`` when RAM is unmeasurable.++ Both numbers are the zoo's. It just compares its floor against TOTAL RAM, which cannot see a+ loaded model; exposing them here lets the transport choice apply the same rule to free RAM."""+ module = _load_optional("unsloth_zoo.hf_xet_tuning")+ floor = int(getattr(module, "MIN_XET_RAM_BYTES", 4_000_000_000) or 4_000_000_000)+ profile_of = getattr(module, "system_profile", None)+ if profile_of is None:+ return (None, floor)+ try:+ available = int(getattr(profile_of(), "available_ram_bytes", 0) or 0)+ except Exception as exc: # noqa: BLE001+ import logging as _logging+ _logging.getLogger(__name__).debug("available_ram_bytes failed: %s", exc)+ return (None, floor)+ return (available if available > 0 else None, floor)+++def free_ram_pressure_reason() -> "Optional[str]":+ """Why a download should take HTTP right now, or ``None`` to leave Xet alone.++ The zoo refuses Xet below ``MIN_XET_RAM_BYTES`` but measures TOTAL RAM, so the check passes on a+ 32 GB box down to 2 GB free because a 27B GGUF is loaded (issue #9032). Same rule and threshold,+ asked of free RAM. Buffers are clamped separately; this catches the host where even the clamped+ floor will not fit.++ One rule with two callers, which must agree: the capabilities probe resolves what the UI submits+ as an explicit transport, and ``resolve_auto_use_xet`` covers an API caller that sends "auto".+ Unmeasurable RAM is not evidence of pressure, so anything unreadable keeps Xet.++ RAM promised to running downloads but not yet resident is subtracted, so the Nth concurrent+ download is sent to HTTP rather than handed Xet's floor. The clamp alone cannot bound that: its+ budget bottoms out at the floor, so enough simultaneous workers would still add up past free+ RAM. Only the unclaimed remainder, since whatever a worker has already taken is missing from+ this reading already (see ``_live_reserved_locked``)."""+ try:+ available, floor = available_ram_bytes()+ if available is not None:+ with _budget_lock:+ available = max(0, available - _live_reserved_locked())+ except Exception as exc: # noqa: BLE001 - a probe must not decide the transport by crashing+ import logging as _logging+ _logging.getLogger(__name__).debug("free_ram_pressure_reason failed: %s", exc)+ return None+ if available is None or available >= floor:+ return None+ return (+ f"HTTP: only {available / 1e9:.1f}GB RAM free (Xet wants {floor / 1e9:.0f}GB); "+ "close a loaded model or wait for running downloads to use Xet"+ )def child_should_disable_xet(config: dict) -> bool:@@ -567,7 +894,12 @@ __all__ = ["start_watchdog","xet_env_overrides","apply_xet_env",+ "clamp_to_available_ram",+ "available_ram_bytes",+ "free_ram_pressure_reason",+ "bind_worker_budget","xet_health",+ "xet_health_is_forced","hf_hub_download_with_xet_fallback","snapshot_download_with_xet_fallback",]diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.tsindex ea931ca413e..e023ca9dea8 100644--- a/studio/frontend/src/features/hub/download-manager/api.ts+++ b/studio/frontend/src/features/hub/download-manager/api.ts@@ -167,7 +167,6 @@ import type { DownloadTransportCapabilities } from "./transport-capabilities";const DOWNLOAD_TRANSPORT_CAPABILITIES_TTL_MS = 30_000;let downloadTransportCapabilitiesCache: {expiresAt: number;- probed: boolean;capabilities: DownloadTransportCapabilities;} | null = null;let downloadTransportCapabilitiesInFlight: Promise<DownloadTransportCapabilities> | null =@@ -180,11 +179,15 @@ export async function getDownloadTransportCapabilities(options: {probe?: boolean;} = {}): Promise<DownloadTransportCapabilities> {const cached = downloadTransportCapabilitiesCache;- // A cheap cached answer cannot satisfy a probe request, but a probed one satisfies everybody.+ // No cached answer satisfies a probe, not even an earlier probe's. This request IS the Auto+ // admission decision for one download, and the backend's verdict subtracts the RAM already+ // promised to Xet workers that started since (free_ram_pressure_reason -> the reservation+ // ledger). Replaying the previous answer admits every download started inside the TTL on the+ // same pre-reservation verdict, and each one is then submitted as an explicit+ // transport_mode="xet" that the start path honours without re-reading free RAM. A probed answer+ // still satisfies the render polls below; only the probe itself has to be live.const cacheUsable =- cached !== null &&- cached.expiresAt > Date.now() &&- (!options.probe || cached.probed);+ cached !== null && cached.expiresAt > Date.now() && !options.probe;if (!options.force && cacheUsable) {return cached.capabilities;}@@ -199,7 +202,6 @@ export async function getDownloadTransportCapabilities(options: {.then((capabilities) => {downloadTransportCapabilitiesCache = {expiresAt: Date.now() + DOWNLOAD_TRANSPORT_CAPABILITIES_TTL_MS,- probed: options.probe === true,capabilities,};return capabilities;diff --git a/studio/frontend/tests/download-transport-probe-freshness.test.ts b/studio/frontend/tests/download-transport-probe-freshness.test.tsnew file mode 100644index 00000000000..c906b32b17c--- /dev/null+++ b/studio/frontend/tests/download-transport-probe-freshness.test.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { registerStoreStubResolver } from "./helpers/kit.ts";++registerStoreStubResolver();++const { setAuthFetchHandler } = await import("./helpers/store-stubs/auth.ts");+const { getDownloadTransportCapabilities } = await import(+ "../src/features/hub/download-manager/api.ts"+);++const CAPS_URL = "/api/studio/download-transport-capabilities";++function serve(verdicts: string[]): { probes: string[]; polls: string[] } {+ const probes: string[] = [];+ const polls: string[] = [];+ setAuthFetchHandler((input) => {+ const url = String(input);+ assert.ok(url.startsWith(CAPS_URL), `unexpected request: ${url}`);+ const probed = url.includes("probe=1");+ (probed ? probes : polls).push(url);+ const auto = verdicts[Math.min(probes.length - 1, verdicts.length - 1)];+ return new Response(+ JSON.stringify({+ http: { available: true, reason: null },+ xet: { available: true, reason: null },+ auto_resolves_to: probed ? auto : "xet",+ auto_reason: null,+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ });+ return { probes, polls };+}++test("every Auto download start re-asks the backend, so admission sees live reservations", async () => {+ // The free-RAM gate lives in the probe (get_download_transport_capabilities(probe=True)), and+ // its verdict subtracts RAM already promised to running Xet workers. Serving the previous+ // probe's answer from cache admits every download started inside the TTL on the SAME+ // pre-reservation verdict: they all submit transport_mode="xet", and the start path honours an+ // explicit "xet" without re-reading free RAM.+ const { probes } = serve(["xet", "http", "http"]);++ const first = await getDownloadTransportCapabilities({ probe: true });+ const second = await getDownloadTransportCapabilities({ probe: true });+ const third = await getDownloadTransportCapabilities({ probe: true });++ assert.equal(probes.length, 3, "a start reused a stale Auto verdict");+ assert.equal(first.auto_resolves_to, "xet");+ assert.equal(second.auto_resolves_to, "http", "start 2 skipped the gate");+ assert.equal(third.auto_resolves_to, "http", "start 3 skipped the gate");+});++test("an ordinary render poll still answers from cache", async () => {+ // The probe is per download start; the picker polls on render and must not connect per poll.+ const { probes, polls } = serve(["xet"]);++ await getDownloadTransportCapabilities({ probe: true });+ await getDownloadTransportCapabilities();+ await getDownloadTransportCapabilities();++ assert.equal(probes.length, 1);+ assert.equal(polls.length, 0, "a render poll re-fetched needlessly");+});++test("a probe failure is not cached as a verdict", async () => {+ setAuthFetchHandler(() => new Response("nope", { status: 500 }));+ const caps = await getDownloadTransportCapabilities({ probe: true });+ assert.equal(caps.auto_resolves_to, "xet", "optimistic fallback stands");++ const { probes } = serve(["http"]);+ const next = await getDownloadTransportCapabilities({ probe: true });+ assert.equal(probes.length, 1);+ assert.equal(next.auto_resolves_to, "http");+ setAuthFetchHandler(null);+});