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: stop rewriting the compile-cache bundle on every warm start, and bound its disk use (#11874)
Daniel Han06ed93714976
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex bf4321e8d0c..e26d1dcbbd0 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -128,7 +128,7 @@ from .diffusion_speed import (compile_dynamic,compile_eligible,compiled_shapes_are_static,- dynamo_graph_count,+ fresh_compile_count,normalize_speed_mode,resolve_speed_mode,restore_backend_flags,@@ -7460,7 +7460,8 @@ class DiffusionBackend:images: list[Any] = []per_image_seeds: list[int] = []chunk_shapes: list[int] = []- graphs_before = dynamo_graph_count()+ graphs_before = fresh_compile_count()+ compile_cache.note_use(state.compile_cache_ctx)try:pending = list(chunks)while pending:@@ -7541,7 +7542,10 @@ class DiffusionBackend:# A cancelled or failed render may already have generalised a graph that the next render reuses# without compiling, so the success path below would never see the count grow: dirty it now.try:- if auto_dynamic_active(state.pipe) and dynamo_graph_count() > graphs_before:+ if (+ auto_dynamic_active(state.pipe)+ and fresh_compile_count() > graphs_before+ ):compile_cache.mark_recompiled(state.compile_cache_ctx)except Exception: # noqa: BLE001 - bookkeeping must not mask the render's own errorpass@@ -7566,7 +7570,7 @@ class DiffusionBackend:(reg_width, reg_height, int(chunk_batch)),static = static_shapes,)- if auto_dynamic_active(state.pipe) and dynamo_graph_count() > graphs_before:+ if auto_dynamic_active(state.pipe) and fresh_compile_count() > graphs_before:# Automatic dynamic recompiles on the first new text length at an already-registered# (width, height, batch): persist those graphs too, or every fresh process pays them again.compile_cache.mark_recompiled(state.compile_cache_ctx)diff --git a/studio/backend/core/inference/diffusion_compile_cache.py b/studio/backend/core/inference/diffusion_compile_cache.pyindex 9ad178db357..c77c23678e5 100644--- a/studio/backend/core/inference/diffusion_compile_cache.py+++ b/studio/backend/core/inference/diffusion_compile_cache.py@@ -30,6 +30,8 @@ first compiled forward); ``save`` writes the bundle + manifest after the warmup(on by default, a hit skips the rewrite); ``restore`` resets the inductor dir on unload.All env-gated and best-effort; torch imported lazily.+DISK: LRU keys are evicted past ``UNSLOTH_DIFFUSION_COMPILE_CACHE_MAX_GB``, never one open here or used in the last hour.+The generate path calls ``save_async``, not ``save``: the write is pure bookkeeping forthe NEXT process, so making a user wait on it buys them nothing. Measured on a B200(Z-Image-Turbo, speed=max, torch 2.11): a 42.7 MB bundle costs 0.088 s to serialise plus@@ -56,11 +58,13 @@ from __future__ import annotationsimport dataclassesimport hashlibimport json+import mathimport osimport shutilimport tempfileimport threadingimport time+import uuidfrom pathlib import Pathfrom typing import Any, Optional@@ -71,10 +75,13 @@ from typing import Any, Optional# UNSLOTH_DIFFUSION_COMPILE_CACHE_SAVE: 0 disables the auto save (load-only); 1 keeps it.# UNSLOTH_DIFFUSION_COMPILE_CACHE_SYNC: 1 makes save_async write inline on the calling thread, as it did before the# background worker existed. For tests and for debugging a save that looks like it never ran.+# UNSLOTH_DIFFUSION_COMPILE_CACHE_MAX_GB: cache root budget in GB (default 20); 0 disables eviction._ENV_MODE = "UNSLOTH_DIFFUSION_COMPILE_CACHE"_ENV_DIR = "UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR"_ENV_SAVE = "UNSLOTH_DIFFUSION_COMPILE_CACHE_SAVE"_ENV_SYNC = "UNSLOTH_DIFFUSION_COMPILE_CACHE_SYNC"+_ENV_MAX_GB = "UNSLOTH_DIFFUSION_COMPILE_CACHE_MAX_GB"+_DEFAULT_MAX_GB = 20.0_LEGACY_ROOT = Path.home() / ".cache" / "unsloth" / "diffusion_compile_cache"@@ -88,6 +95,12 @@ _BUNDLE_SUFFIX = ".bin"_TEMP_SUFFIX = ".tmp"_FORMAT_VERSION = 1+_LAST_USED_NAME = "last_used"+_TOUCH_INTERVAL_SECONDS = 600.0+# Must exceed _TOUCH_INTERVAL_SECONDS: another process may be compiling into a key touched this recently.+_EVICT_GRACE_SECONDS = 3600.0+_TOMBSTONE_SUFFIX = ".evicting"+# A bundle file this new is NOT collectable even when the manifest does not name it: another process may have just# published it and not yet committed its manifest, and the whole point of the split is that the loser of that race# keeps a loadable pair. Only ever delays a delete.@@ -332,6 +345,7 @@ class CacheContext:# digest, so the shortcut would leave the corrupt bytes in place under a manifest that names# them, and every future start would reject the cache again with no way back.rejected_bundle: Optional[str] = None+ last_touch: float = 0.0def begin(@@ -431,6 +445,9 @@ def begin(if published is not None:ctx.bundle = _manifest_bundle(cdir, published)+ _register_live(cdir)+ _touch_last_used(ctx)+# Collect here as well as after a save, because the grace window can otherwise leak a bundle for# good: two saves for one key inside 60 s leave the first one too young to collect, and the# second save is the last thing that ever looks. By the time this key is opened again that@@ -458,6 +475,9 @@ def begin(# Loaded artifacts == on-disk artifacts, so nothing to save. A new static-compile shape# re-dirties via register_shape; mode "on" keeps saving.ctx.saved = True+ # A hit never saves, so an over-budget cache would otherwise never shrink.+ if _save_enabled(mode):+ _evict_soon(logger)return ctx@@ -744,6 +764,7 @@ def _write_bundle(ctx: CacheContext, logger: Any) -> bool:)ctx.bundle = bundle_collect_superseded(ctx.dir, logger)+ evict(logger = logger)with _dirty_lock:# A shape registered while this ran is NOT in the bundle just written, so leave the context dirty for# the save its own register_shape queued.@@ -821,7 +842,10 @@ def save_async(ctx: Optional[CacheContext], *, logger: Any = None) -> bool:registered up to that point. A context whose save is IN FLIGHT does get queued again,since the running save cannot contain what was registered after it started."""- if ctx is None or not _save_enabled(ctx.mode) or ctx.saved:+ if ctx is None:+ return False+ note_use(ctx)+ if not _save_enabled(ctx.mode) or ctx.saved:return Falseif sync_saves():return _write_bundle(ctx, logger)@@ -852,7 +876,10 @@ def wait_for_saves(timeout: float = _SAVE_JOIN_TIMEOUT) -> bool:def restore(ctx: Optional[CacheContext], *, logger: Any = None) -> None:"""Restore ``TORCHINDUCTOR_CACHE_DIR`` to its pre-load value. Call on unload."""- if ctx is None or not ctx.prev_inductor_dir_set:+ if ctx is None:+ return+ _unregister_live(ctx.dir)+ if not ctx.prev_inductor_dir_set:return# Before the env var moves: save_cache_artifacts() reads the inductor cache this load pointed at, so a save# still running when the dir is handed back would be collecting against a directory that is about to mean@@ -871,6 +898,165 @@ def restore(ctx: Optional[CacheContext], *, logger: Any = None) -> None:pass+# Refcounted: a reload of the same model overlaps its predecessor's teardown.+_live_lock = threading.Lock()+_live_dirs: dict[str, int] = {}+++def _register_live(cdir: Path) -> None:+ with _live_lock:+ _live_dirs[str(cdir)] = _live_dirs.get(str(cdir), 0) + 1+++def _unregister_live(cdir: Path) -> None:+ with _live_lock:+ count = _live_dirs.get(str(cdir), 0) - 1+ if count > 0:+ _live_dirs[str(cdir)] = count+ else:+ _live_dirs.pop(str(cdir), None)+++def note_use(ctx: Optional[CacheContext]) -> None:+ """Throttled touch keeping ``ctx``'s key out of other processes' eviction; call before a render too."""+ if ctx is not None and time.time() - ctx.last_touch > _TOUCH_INTERVAL_SECONDS:+ _touch_last_used(ctx)+++def _touch_last_used(ctx: CacheContext) -> None:+ ctx.last_touch = time.time()+ try:+ path = ctx.dir / _LAST_USED_NAME+ path.touch(exist_ok = True)+ os.utime(path, None)+ except OSError:+ pass+++def max_cache_bytes() -> Optional[int]:+ raw = (os.environ.get(_ENV_MAX_GB) or "").strip()+ try:+ gb = float(raw) if raw else _DEFAULT_MAX_GB+ except ValueError:+ gb = _DEFAULT_MAX_GB+ if not math.isfinite(gb * (1 << 30)):+ gb = _DEFAULT_MAX_GB+ if not gb > 0:+ return None+ return int(gb * (1 << 30))+++def _is_key_dir(path: Path) -> bool:+ name = path.name+ return len(name) == 32 and all(c in "0123456789abcdef" for c in name)+++def _dir_bytes(path: Path) -> int:+ total = 0+ for dirpath, _dirnames, filenames in os.walk(path, followlinks = False):+ for name in filenames:+ try:+ total += os.lstat(os.path.join(dirpath, name)).st_size+ except OSError:+ continue+ return total+++def _last_used(path: Path) -> float:+ for name in (_LAST_USED_NAME, _MANIFEST_NAME):+ try:+ return (path / name).stat().st_mtime+ except OSError:+ continue+ try:+ return path.stat().st_mtime+ except OSError:+ return 0.0+++def _is_tombstone(path: Path) -> bool:+ name = path.name+ return name.endswith(_TOMBSTONE_SUFFIX) and name[32:33] == "." and _is_key_dir(Path(name[:32]))+++def _remove_key_dir(path: Path) -> Optional[int]:+ """Atomic rename then delete, so a concurrent open sees a clean miss. Returns bytes left, None if not taken."""+ tomb = path.with_name(f"{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}{_TOMBSTONE_SUFFIX}")+ try:+ os.rename(path, tomb)+ except OSError:+ return None+ shutil.rmtree(tomb, ignore_errors = True)+ return _dir_bytes(tomb) if tomb.exists() else 0+++def _evict_soon(logger: Any) -> None:+ if sync_saves():+ evict(logger = logger)+ return+ try:+ threading.Thread(+ target = evict,+ kwargs = {"logger": logger},+ name = "unsloth-compile-cache-evict",+ daemon = True,+ ).start()+ except Exception: # noqa: BLE001+ pass+++def evict(+ *,+ root: Optional[Path] = None,+ max_bytes: Optional[int] = None,+ logger: Any = None,+) -> list[str]:+ """Delete LRU keys until the root fits its budget (a target: live and recent keys are spared). Never raises."""+ removed: list[str] = []+ try:+ root = root if root is not None else cache_root()+ budget = max_bytes if max_bytes is not None else max_cache_bytes()+ if budget is None or not root.is_dir():+ return removed+ entries = []+ leftover = 0+ for child in root.iterdir():+ if child.is_symlink() or not child.is_dir():+ continue+ if _is_tombstone(child):+ shutil.rmtree(child, ignore_errors = True)+ leftover += _dir_bytes(child) if child.exists() else 0+ elif _is_key_dir(child):+ entries.append((_last_used(child), child, _dir_bytes(child)))+ total = leftover + sum(size for _, _, size in entries)+ if total <= budget:+ return removed+ with _live_lock:+ live = set(_live_dirs)+ cutoff = time.time() - _EVICT_GRACE_SECONDS+ for used, path, size in sorted(entries, key = lambda e: e[0]):+ if total <= budget:+ break+ if str(path) in live or used > cutoff or _last_used(path) > cutoff:+ continue+ left = _remove_key_dir(path)+ if left is None:+ if not path.exists():+ total -= size+ continue+ total -= size - left+ removed.append(path.name)+ if removed:+ _info(+ logger,+ f"compile-cache: evicted {len(removed)} least recently used key(s); "+ f"{total / (1 << 30):.2f} GB of {budget / (1 << 30):.2f} GB now in use",+ )+ except Exception as exc: # noqa: BLE001 - housekeeping must never fail a save+ _warn(logger, f"compile-cache: eviction failed: {exc}")+ return removed++def _warn(logger: Any, msg: str) -> None:if logger is not None:logger.warning("diffusion.compile_cache: %s", msg)diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex 28fb7561eb8..d7663df566b 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -700,6 +700,15 @@ def dynamo_graph_count() -> int:return 0+def fresh_compile_count() -> int:+ """FX graph cache misses. Not ``dynamo_graph_count``: it also grows on cache-served retraces, rewriting bundles."""+ try:+ from torch._dynamo.utils import counters+ return int(counters["inductor"]["fxgraph_cache_miss"])+ except Exception: # noqa: BLE001+ return 0++def compile_fallback_error(pipe: Any) -> Optional[str]:"""The compile failure a guarded DiT fell back from, or None while every compiled DiT still runs compiled."""for transformer in _guarded_dits(pipe):diff --git a/studio/backend/tests/test_diffusion_compile_cache.py b/studio/backend/tests/test_diffusion_compile_cache.pyindex c74d4d7dfc5..3f5c857f2b8 100644--- a/studio/backend/tests/test_diffusion_compile_cache.py+++ b/studio/backend/tests/test_diffusion_compile_cache.py@@ -1164,7 +1164,273 @@ def test_a_failed_or_cancelled_render_still_dirties_the_bundle_after_a_recompilefrom core.inference import diffusionsrc = inspect.getsource(diffusion.DiffusionBackend)- before = src.index("graphs_before = dynamo_graph_count()")+ before = src.index("graphs_before = fresh_compile_count()")handler = src.index("except BaseException:", before)reraise = src.index("raise\n", handler)assert "compile_cache.mark_recompiled(state.compile_cache_ctx)" in src[handler:reraise]+++# ---------------------------------------------------------------------------- eviction+def _key_dir(root: Path, name: str, size: int, age_s: float) -> Path:+ import os+ import time++ d = root / name+ (d / "inductor").mkdir(parents = True)+ (d / "inductor" / "blob").write_bytes(b"x" * size)+ (d / cc._MANIFEST_NAME).write_text("{}")+ used = d / cc._LAST_USED_NAME+ used.write_text("")+ t = time.time() - age_s+ os.utime(used, (t, t))+ return d+++def test_max_cache_bytes_env(monkeypatch):+ monkeypatch.delenv(cc._ENV_MAX_GB, raising = False)+ assert cc.max_cache_bytes() == int(cc._DEFAULT_MAX_GB * (1 << 30))+ monkeypatch.setenv(cc._ENV_MAX_GB, "0.5")+ assert cc.max_cache_bytes() == 1 << 29+ monkeypatch.setenv(cc._ENV_MAX_GB, "0")+ assert cc.max_cache_bytes() is None+ monkeypatch.setenv(cc._ENV_MAX_GB, "not-a-number")+ assert cc.max_cache_bytes() == int(cc._DEFAULT_MAX_GB * (1 << 30))+ for raw in ("nan", "inf", "-inf"):+ monkeypatch.setenv(cc._ENV_MAX_GB, raw)+ assert cc.max_cache_bytes() == int(cc._DEFAULT_MAX_GB * (1 << 30))+++def test_evict_removes_least_recently_used_keys_until_under_budget(tmp_path):+ old = _key_dir(tmp_path, "a" * 32, 1000, age_s = 3 * 86400)+ mid = _key_dir(tmp_path, "b" * 32, 1000, age_s = 2 * 86400)+ new = _key_dir(tmp_path, "c" * 32, 1000, age_s = 1 * 86400)+ removed = cc.evict(root = tmp_path, max_bytes = 2500)+ assert removed == ["a" * 32]+ assert not old.exists() and mid.exists() and new.exists()+++def test_evict_is_a_noop_under_budget_or_disabled(monkeypatch, tmp_path):+ d = _key_dir(tmp_path, "a" * 32, 1000, age_s = 86400)+ assert cc.evict(root = tmp_path, max_bytes = 10_000) == []+ monkeypatch.setenv(cc._ENV_MAX_GB, "0")+ assert cc.evict(root = tmp_path) == []+ assert d.exists()+++def test_evict_spares_live_recent_and_foreign_dirs(tmp_path):+ live = _key_dir(tmp_path, "a" * 32, 1000, age_s = 5 * 86400)+ recent = _key_dir(tmp_path, "b" * 32, 1000, age_s = 60)+ foreign = tmp_path / "not-a-key"+ foreign.mkdir()+ (foreign / "big").write_bytes(b"x" * 5000)+ cc._register_live(live)+ try:+ assert cc.evict(root = tmp_path, max_bytes = 1) == []+ finally:+ cc._unregister_live(live)+ assert live.exists() and recent.exists() and foreign.exists()+ assert cc.evict(root = tmp_path, max_bytes = 1) == ["a" * 32]+ assert foreign.exists()+++def test_save_evicts_other_keys_but_never_its_own(monkeypatch, tmp_path, fake_megacache):+ monkeypatch.setenv(cc._ENV_MODE, "auto")+ monkeypatch.delenv(cc._ENV_SAVE, raising = False)+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))+ stale = _key_dir(tmp_path, "d" * 32, 4096, age_s = 30 * 86400)+ monkeypatch.setenv(cc._ENV_MAX_GB, str(1024 / (1 << 30)))+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)+ try:+ assert cc.save(ctx) is True+ assert not stale.exists()+ assert ctx.dir.exists() and ctx.manifest_path.exists() and ctx.bundle.exists()+ finally:+ cc.restore(ctx)+++def test_begin_touches_last_used_and_restore_releases_the_key(+ monkeypatch, tmp_path, fake_megacache+):+ monkeypatch.setenv(cc._ENV_MODE, "auto")+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)+ assert (ctx.dir / cc._LAST_USED_NAME).exists()+ assert str(ctx.dir) in cc._live_dirs+ cc.restore(ctx)+ assert str(ctx.dir) not in cc._live_dirs+++def test_removed_key_reads_as_a_miss_not_a_broken_pair(monkeypatch, tmp_path, fake_megacache):+ monkeypatch.setenv(cc._ENV_MODE, "auto")+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)+ assert cc.save(ctx) is True+ cc.restore(ctx)+ cc._remove_key_dir(ctx.dir)+ ctx2 = cc.begin(transformer = _transformer(), **_BEGIN_KW)+ try:+ assert ctx2.hit is False+ finally:+ cc.restore(ctx2)+++def test_fresh_compile_count_ignores_a_retrace_the_cache_serves():+ pytest.importorskip("torch")+ from torch._dynamo.utils import counters++ from core.inference import diffusion_speed as ds_mod++ graphs, misses = ds_mod.dynamo_graph_count(), ds_mod.fresh_compile_count()+ counters["stats"]["unique_graphs"] += 3+ counters["inductor"]["fxgraph_cache_hit"] += 3+ try:+ assert ds_mod.dynamo_graph_count() == graphs + 3+ assert ds_mod.fresh_compile_count() == misses+ counters["inductor"]["fxgraph_cache_miss"] += 1+ assert ds_mod.fresh_compile_count() == misses + 1+ finally:+ counters["stats"]["unique_graphs"] -= 3+ counters["inductor"]["fxgraph_cache_hit"] -= 3+ counters["inductor"]["fxgraph_cache_miss"] -= 1+++def test_a_render_marks_its_key_used_before_it_compiles(monkeypatch, tmp_path):+ import os+ import time++ ctx = cc.CacheContext(+ key = "e" * 32,+ dir = tmp_path / ("e" * 32),+ bundle = tmp_path / "b",+ manifest_path = tmp_path / "m",+ env_fp = {},+ model_fp = {},+ mode = "auto",+ )+ d = _key_dir(tmp_path, "e" * 32, 1000, age_s = 5 * 86400)+ ctx.last_touch = time.time() - 2 * cc._TOUCH_INTERVAL_SECONDS+ cc.note_use(ctx)+ assert time.time() - os.stat(d / cc._LAST_USED_NAME).st_mtime < 60+ assert cc.evict(root = tmp_path, max_bytes = 1) == []+ stamp = os.stat(d / cc._LAST_USED_NAME).st_mtime+ cc.note_use(ctx)+ assert os.stat(d / cc._LAST_USED_NAME).st_mtime == stamp+ cc.note_use(None)+++def test_generate_marks_the_key_used_before_the_render():+ import inspect++ from core.inference import diffusion++ src = inspect.getsource(diffusion.DiffusionBackend)+ before = src.index("graphs_before = fresh_compile_count()")+ render = src.index("pending = list(chunks)", before)+ assert "compile_cache.note_use(state.compile_cache_ctx)" in src[before:render]+++def test_evict_rereads_last_used_before_deleting(monkeypatch, tmp_path):+ import os+ import time++ old = _key_dir(tmp_path, "a" * 32, 1000, age_s = 5 * 86400)+ other = _key_dir(tmp_path, "b" * 32, 1000, age_s = 4 * 86400)+ real_dir_bytes = cc._dir_bytes++ def dir_bytes_then_claim(path):+ size = real_dir_bytes(path)+ if path == old:+ now = time.time()+ os.utime(old / cc._LAST_USED_NAME, (now, now))+ return size++ monkeypatch.setattr(cc, "_dir_bytes", dir_bytes_then_claim)+ assert cc.evict(root = tmp_path, max_bytes = 1500) == ["b" * 32]+ assert old.exists() and not other.exists()+++def test_evict_counts_only_what_it_actually_removed(monkeypatch, tmp_path):+ import shutil++ stuck = _key_dir(tmp_path, "a" * 32, 1000, age_s = 5 * 86400)+ nxt = _key_dir(tmp_path, "b" * 32, 1000, age_s = 4 * 86400)+ keep = _key_dir(tmp_path, "c" * 32, 1000, age_s = 3 * 86400)+ real_rmtree = shutil.rmtree++ def rmtree_keeps_the_oldest(path, *args, **kwargs):+ if str(path).startswith(str(stuck)) or "a" * 32 in str(path):+ return+ return real_rmtree(path, *args, **kwargs)++ monkeypatch.setattr(shutil, "rmtree", rmtree_keeps_the_oldest)+ cc.evict(root = tmp_path, max_bytes = 2500)+ assert not nxt.exists() and keep.exists()+ assert cc._dir_bytes(tmp_path) <= 2500+ monkeypatch.setattr(shutil, "rmtree", real_rmtree)+ cc.evict(root = tmp_path, max_bytes = 2500)+ assert sorted(p.name for p in tmp_path.iterdir()) == ["c" * 32]+++def test_evict_skips_a_key_it_cannot_take_and_moves_on(monkeypatch, tmp_path):+ import os++ held = _key_dir(tmp_path, "a" * 32, 1000, age_s = 5 * 86400)+ nxt = _key_dir(tmp_path, "b" * 32, 1000, age_s = 4 * 86400)+ real_rename = os.rename++ def rename_refuses_held(src, dst):+ if str(src) == str(held):+ raise PermissionError("in use by another process")+ return real_rename(src, dst)++ monkeypatch.setattr(os, "rename", rename_refuses_held)+ assert cc.evict(root = tmp_path, max_bytes = 1500) == ["b" * 32]+ assert held.exists() and (held / cc._MANIFEST_NAME).exists() and not nxt.exists()+++def test_a_warm_hit_enforces_the_budget_without_a_save(monkeypatch, tmp_path, fake_megacache):+ monkeypatch.setenv(cc._ENV_MODE, "auto")+ monkeypatch.delenv(cc._ENV_SAVE, raising = False)+ monkeypatch.setenv(cc._ENV_SYNC, "1")+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)+ assert cc.save(ctx) is True+ cc.restore(ctx)+ stale = _key_dir(tmp_path, "d" * 32, 4096, age_s = 30 * 86400)+ monkeypatch.setenv(cc._ENV_MAX_GB, str(1024 / (1 << 30)))+ monkeypatch.setenv(cc._ENV_SAVE, "0")+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)+ cc.restore(ctx)+ assert stale.exists()+ monkeypatch.delenv(cc._ENV_SAVE)+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)+ try:+ assert ctx.hit is True and ctx.saved is True+ assert cc.save_async(ctx) is False+ assert not stale.exists()+ assert ctx.manifest_path.exists() and ctx.bundle.exists()+ finally:+ cc.restore(ctx)+++def test_max_cache_bytes_overflowing_value_keeps_the_default(monkeypatch):+ monkeypatch.setenv(cc._ENV_MAX_GB, "1e300")+ assert cc.max_cache_bytes() == int(cc._DEFAULT_MAX_GB * (1 << 30))+++def test_evict_counts_a_key_another_evictor_took(monkeypatch, tmp_path):+ import os+ import shutil++ taken = _key_dir(tmp_path, "a" * 32, 1000, age_s = 5 * 86400)+ nxt = _key_dir(tmp_path, "b" * 32, 1000, age_s = 4 * 86400)+ real_rename = os.rename++ def another_process_got_there_first(src, dst):+ if str(src) == str(taken):+ shutil.rmtree(taken)+ return real_rename(src, dst)++ monkeypatch.setattr(os, "rename", another_process_got_there_first)+ assert cc.evict(root = tmp_path, max_bytes = 1500) == []+ assert not taken.exists() and nxt.exists()