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.

Take the compile-cache bundle write off the image generation request path (#11009)

Daniel Han075a3cb28fd1
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 1db0ea71aca..f183e4f510d 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -5563,7 +5563,7 @@ class DiffusionBackend:
# Pre-commit failure: roll back the process-wide mutations (symmetric with _unload_locked).
if not state_committed:
restore_backend_flags(backend_flags_before)
- compile_cache.restore(compile_ctx)
+ compile_cache.restore(compile_ctx, logger = logger)
gguf_compile.uninstall_all() # idempotent
cuda_graph.uninstall_all(getattr(pipe, "_unsloth_cuda_graphs", ()) or ())
if eager_patched:
@@ -7135,7 +7135,9 @@ class DiffusionBackend:
steps_done[0] += steps
# Keep progress ACTIVE through the post-denoise work: the route persists the image after this returns,
# so a mount probe reading idle would refresh the gallery too early. Persist the warm compile bundle;
- # a STATIC compile makes new artifacts per (w,h,batch), so register this shape.
+ # a STATIC compile makes new artifacts per (w,h,batch), so register this shape. The write itself is
+ # QUEUED, not performed: nothing in this response depends on it (only the NEXT process reads the
+ # bundle), so save_async hands it to the shared worker and the user stops waiting on it.
try:
# Register the dims the forward ACTUALLY compiled with, and every distinct chunk size (a static
# compile makes one artifact per batch size too).
@@ -7149,11 +7151,11 @@ class DiffusionBackend:
(reg_width, reg_height, int(chunk_batch)),
static = static_shapes,
)
- compile_cache.save(state.compile_cache_ctx, logger = logger)
+ compile_cache.save_async(state.compile_cache_ctx, logger = logger)
except Exception: # noqa: BLE001 - cache persistence is best-effort
pass
# Last word on cancellation, AFTER the post-denoise work: the event stays registered through the
- # compile-cache save and the page still shows Stop for as long as progress reads active, so a Stop
+ # compile-cache bookkeeping and the page still shows Stop for as long as progress reads active, so a Stop
# landing there was answered cancelled = true and then contradicted by the image the route persisted.
# Check and deregister under the cancellation lock, which cancel_generate takes, so the two cannot
# interleave. The finally below repeats the clear for every other exit.
@@ -7341,7 +7343,7 @@ class DiffusionBackend:
# Restore the process-wide backend flags this load flipped so the next `off` load is bit-identical. All
# idempotent.
restore_backend_flags(state.backend_flags_before)
- compile_cache.restore(state.compile_cache_ctx)
+ compile_cache.restore(state.compile_cache_ctx, logger = logger)
# Before clear_gpu_cache(), or the graph pool stays reserved for the life of the process.
cuda_graph.uninstall_all(state.cuda_graphs)
gguf_compile.uninstall_all()
diff --git a/studio/backend/core/inference/diffusion_compile_cache.py b/studio/backend/core/inference/diffusion_compile_cache.py
index b93d92f0ac4..a5a416882fc 100644
--- a/studio/backend/core/inference/diffusion_compile_cache.py
+++ b/studio/backend/core/inference/diffusion_compile_cache.py
@@ -29,6 +29,26 @@ Lifecycle (around ``_compile_repeated_blocks``): ``begin`` builds the fingerprin
first compiled forward); ``save`` writes the bundle + manifest after the warmup forward
(on by default, a hit skips the rewrite); ``restore`` resets the inductor dir on unload.
All env-gated and best-effort; torch imported lazily.
+
+The generate path calls ``save_async``, not ``save``: the write is pure bookkeeping for
+the 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
+0.033 s to write, a 71.1 MB one 0.130 s plus 0.057 s, so roughly 2.6 ms per MB, and the
+docstring's batched-GGUF bundles are far larger than either. ``save`` itself is unchanged
+and still synchronous, for tests and for anyone who needs the write to have happened by
+the time the call returns.
+
+ON-DISK LAYOUT, per key dir: ``manifest.json`` plus one or more ``bundle-<sha16>.bin``.
+The bundle is CONTENT-ADDRESSED and the manifest names the one it is paired with, so the
+manifest is the single commit point: a save writes a file no reader is using, then
+publishes the manifest naming it, then collects the bundles no manifest names. Killed
+anywhere in between, what is on disk is still a matching pair, either the old one (the
+new bundle is an orphan) or the new one. That matters because a save runs on a daemon
+thread that interpreter exit can kill mid-write: writing one fixed ``cache.bin`` in place
+would leave the old manifest paired with a new bundle, and the sha256 check on load would
+then throw away a warm start that was perfectly good. Manifests without a ``bundle`` key
+are pre-content-addressing and name ``cache.bin``, so old bundles keep hitting; the format
+version is deliberately NOT bumped, since bumping it is what would invalidate them.
"""
from __future__ import annotations
@@ -37,6 +57,8 @@ import dataclasses
import hashlib
import json
import os
+import tempfile
+import threading
import time
from pathlib import Path
from typing import Any, Optional
@@ -46,16 +68,50 @@ from typing import Any, Optional
# 22.2 s, bit-identical, 7.9 MB bundle. The rest is dynamo tracing + guards, which Mega-cache does not capture.
# UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR: root dir for bundles (default under the workspace).
# 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.
_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"
_DEFAULT_ROOT = Path.home() / ".cache" / "unsloth" / "diffusion_compile_cache"
_MANIFEST_NAME = "manifest.json"
+# The pre-content-addressing bundle name. Still read (a manifest without a "bundle" key names it, which is every
+# bundle written before this scheme) and still collected once a newer pair supersedes it, never written.
_BUNDLE_NAME = "cache.bin"
+_BUNDLE_PREFIX = "bundle-"
+_BUNDLE_SUFFIX = ".bin"
+# What _atomic_write names its in-progress file, as a suffix: ".<final name>.<random>.tmp".
+_TEMP_SUFFIX = ".tmp"
_FORMAT_VERSION = 1
+# 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.
+_GC_GRACE_SECONDS = 60.0
+
+
+def _bundle_name(digest: str) -> str:
+ """Content-addressed file name, so writing a bundle can never damage the live one."""
+ return f"{_BUNDLE_PREFIX}{digest[:16]}{_BUNDLE_SUFFIX}"
+
+
+def _manifest_bundle(cdir: Path, manifest: dict[str, Any]) -> Path:
+ """The bundle file a manifest names. Absent "bundle" means a pre-content-addressing manifest."""
+ name = str(manifest.get("bundle") or _BUNDLE_NAME)
+ # Defence against a manifest naming something outside its own directory.
+ return cdir / Path(name).name
+
+
+def _read_manifest(path: Path) -> Optional[dict[str, Any]]:
+ try:
+ loaded = json.loads(path.read_text(encoding = "utf-8"))
+ except Exception: # noqa: BLE001 - unreadable/absent/half-written reads as "no manifest"
+ return None
+ return loaded if isinstance(loaded, dict) else None
+
def cache_mode() -> str:
"""``off`` | ``auto`` | ``on`` from the environment. ``auto`` is the default."""
@@ -77,6 +133,11 @@ def _save_enabled(mode: str) -> bool:
return (os.environ.get(_ENV_SAVE) or "").strip().lower() not in ("0", "off", "false", "no")
+def sync_saves() -> bool:
+ """Whether ``save_async`` must write inline instead of handing off to the worker."""
+ return (os.environ.get(_ENV_SYNC) or "").strip().lower() in ("1", "on", "true", "yes")
+
+
def cache_root() -> Path:
root = os.environ.get(_ENV_DIR)
return Path(root) if root else _DEFAULT_ROOT
@@ -185,6 +246,15 @@ class CacheContext:
prev_inductor_dir: Optional[str] = None
prev_inductor_dir_set: bool = False
shapes: set = dataclasses.field(default_factory = set)
+ # Bumped by every ``register_shape`` that dirties the context. A background save clears ``saved`` -> True only
+ # when this still reads what it read before it started, so a shape registered WHILE that save ran cannot be
+ # marked persisted by it.
+ dirty_seq: int = 0
+ # A bundle this context LOADED and rejected on its checksum. The save below must overwrite that
+ # file rather than take its exists() shortcut: the recompiled artifacts usually hash to the same
+ # 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
def begin(
@@ -240,6 +310,13 @@ def begin(
mode = mode,
)
+ # Same reason as restore(): the previous load's save reads the inductor dir that is about to be repointed.
+ if not wait_for_saves():
+ _warn(
+ logger,
+ f"compile-cache: background save still running after {_SAVE_JOIN_TIMEOUT:.0f}s; continuing",
+ )
+
try:
cdir.mkdir(parents = True, exist_ok = True)
ctx.prev_inductor_dir = os.environ.get("TORCHINDUCTOR_CACHE_DIR")
@@ -248,8 +325,21 @@ def begin(
except Exception as exc: # noqa: BLE001
_warn(logger, f"could not set TORCHINDUCTOR_CACHE_DIR: {exc}")
+ # The MANIFEST decides which bundle is live: it is published last and only ever names a bundle that was
+ # completely written, so an interrupted save leaves the previous pair addressed and loadable.
+ published = _read_manifest(ctx.manifest_path)
+ if published is not None:
+ ctx.bundle = _manifest_bundle(cdir, published)
+
+ # 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
+ # orphan is minutes or days old, the live bundle is spared by name, and anything a concurrent
+ # process is mid-save on is still inside its grace, so the same two rules decide it.
+ _collect_superseded(cdir, logger)
+
# Try an exact-match load. A miss/mismatch is normal and non-fatal.
- if ctx.bundle.exists() and ctx.manifest_path.exists():
+ if published is not None and ctx.bundle.exists():
ctx.hit = _try_load(ctx, logger)
if ctx.hit and mode != "on":
# Loaded artifacts == on-disk artifacts, so nothing to save. A new static-compile shape re-dirties via
@@ -271,9 +361,13 @@ def register_shape(ctx: Optional[CacheContext], shape: Any, *, static: bool) ->
return
try:
key = tuple(shape)
- if key not in ctx.shapes:
- ctx.shapes.add(key)
- ctx.saved = False
+ # Under the dirty lock so a background save cannot read dirty_seq, lose the race to this block, and then
+ # publish saved = True over the clear below.
+ with _dirty_lock:
+ if key not in ctx.shapes:
+ ctx.shapes.add(key)
+ ctx.saved = False
+ ctx.dirty_seq += 1
except Exception: # noqa: BLE001 - bookkeeping only
pass
@@ -300,6 +394,7 @@ def _try_load(ctx: CacheContext, logger: Any) -> bool:
digest = hashlib.sha256(data).hexdigest()
if manifest.get("sha256") and manifest["sha256"] != digest:
_warn(logger, "compile-cache: bundle checksum mismatch; ignoring")
+ ctx.rejected_bundle = ctx.bundle.name
return False
try:
@@ -320,16 +415,86 @@ def _try_load(ctx: CacheContext, logger: Any) -> bool:
return False
-def save(ctx: Optional[CacheContext], *, logger: Any = None) -> bool:
- """Persist compiled artifacts to the bundle + manifest, AFTER a warmup forward.
+def _atomic_write(path: Path, data: bytes) -> None:
+ """Write ``data`` to ``path`` via a temp file in the SAME directory plus ``os.replace``.
- No-op unless save is enabled and the context is dirty: a bundle HIT starts clean
- (rewriting the just-loaded artifacts costs ~0.5 s for no change); a new static-compile
- shape re-dirties via ``register_shape`` so the bundle grows to cover every shape used.
- Returns True if a bundle was written.
+ A save runs on a daemon thread, so interpreter exit can kill it anywhere. Renaming a
+ fully written temp file into place means a half-written file is never visible under a
+ name anything reads. Paired with the content-addressed bundle names above, that is
+ what makes an interrupted save leave a matching manifest/bundle pair rather than a
+ good bundle the sha256 check has to reject.
"""
- if ctx is None or not _save_enabled(ctx.mode) or ctx.saved:
+ tmp: Optional[str] = None
+ try:
+ fd, tmp = tempfile.mkstemp(
+ dir = str(path.parent), prefix = f".{path.name}.", suffix = _TEMP_SUFFIX
+ )
+ with os.fdopen(fd, "wb") as fh:
+ fh.write(data)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(tmp, path)
+ tmp = None
+ finally:
+ if tmp is not None:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+
+
+def _collect_superseded(cdir: Path, logger: Any) -> list[str]:
+ """Delete bundles no manifest names any more. Returns the names removed. Never raises.
+
+ Two rules keep this from deleting a bundle somebody is about to need:
+
+ 1. The live name is re-read from the manifest ON DISK, not from the context that just wrote it, so a manifest
+ another process committed in between decides what survives rather than our stale idea of it.
+ 2. A file younger than the grace window is spared regardless. Between a racing process publishing its bundle
+ and committing its manifest, that bundle is named by nothing; deleting it there would hand the loser of the
+ race exactly the broken pair this whole scheme exists to prevent.
+ """
+ removed: list[str] = []
+ try:
+ manifest = _read_manifest(cdir / _MANIFEST_NAME)
+ live = _manifest_bundle(cdir, manifest).name if manifest is not None else None
+ cutoff = time.time() - _GC_GRACE_SECONDS
+ for path in cdir.iterdir():
+ name = path.name
+ if name == live or not path.is_file():
+ continue
+ if not (
+ name == _BUNDLE_NAME
+ or (name.startswith(_BUNDLE_PREFIX) and name.endswith(_BUNDLE_SUFFIX))
+ # An _atomic_write that the interpreter killed mid-write leaves its temp file
+ # behind: the finally that removes it does not run when the daemon save thread is
+ # torn down inside fh.write, and the file can be gigabytes. The same grace window
+ # covers it, so a write actually in flight is never the one taken.
+ or (name.startswith(".") and name.endswith(_TEMP_SUFFIX))
+ ):
+ continue
+ try:
+ if path.stat().st_mtime > cutoff:
+ continue
+ path.unlink()
+ removed.append(name)
+ except OSError:
+ # Another process got there first, or it is busy on Windows. Next save tries again.
+ continue
+ except Exception as exc: # noqa: BLE001 - housekeeping must never fail a save
+ _warn(logger, f"compile-cache: could not collect superseded bundles: {exc}")
+ return removed
+
+
+def _write_bundle(ctx: CacheContext, logger: Any) -> bool:
+ """The save itself. Runs on the caller's thread (``save``) or the worker (``save_async``)."""
+ if not _save_enabled(ctx.mode) or ctx.saved:
return False
+ # Read BEFORE the artifacts are collected: anything registered from here on is not in `data`, and iterating the
+ # live set while the request thread adds to it is a "set changed size during iteration" away from failing.
+ with _dirty_lock:
+ seq = ctx.dirty_seq
+ shapes = sorted(list(s) for s in ctx.shapes)
try:
import torch # noqa: PLC0415
result = torch.compiler.save_cache_artifacts()
@@ -343,22 +508,39 @@ def save(ctx: Optional[CacheContext], *, logger: Any = None) -> bool:
data = result[0]
try:
ctx.dir.mkdir(parents = True, exist_ok = True)
- ctx.bundle.write_bytes(data)
+ digest = hashlib.sha256(data).hexdigest()
+ bundle = ctx.dir / _bundle_name(digest)
manifest = {
"format": _FORMAT_VERSION,
"key": ctx.key,
"created": time.time(),
"bytes": len(data),
- "sha256": hashlib.sha256(data).hexdigest(),
+ "sha256": digest,
+ # The bundle THIS manifest is paired with. Content-addressed, so a save writes a file no reader is
+ # using and the previous pair stays whole and addressed until the manifest below commits.
+ "bundle": bundle.name,
"env": ctx.env_fp,
"model": ctx.model_fp,
# Static-compile shape coverage (register_shape); unused by dynamic compiles.
- "shapes": sorted(list(s) for s in ctx.shapes),
+ "shapes": shapes,
}
- ctx.manifest_path.write_text(
- json.dumps(manifest, indent = 2, sort_keys = True, default = str), encoding = "utf-8"
+ # Bundle first, under its own name, THEN the manifest: the manifest is the single commit point, and it only
+ # ever names a bundle already fully on disk. An exit between the two leaves the OLD manifest still naming
+ # the OLD bundle, which is untouched, so the previous warm start survives and the new file is just an
+ # orphan the next successful save collects.
+ if not bundle.exists() or bundle.name == ctx.rejected_bundle:
+ _atomic_write(bundle, data)
+ _atomic_write(
+ ctx.manifest_path,
+ json.dumps(manifest, indent = 2, sort_keys = True, default = str).encode("utf-8"),
)
- ctx.saved = True
+ ctx.bundle = bundle
+ _collect_superseded(ctx.dir, 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.
+ if ctx.dirty_seq == seq:
+ ctx.saved = True
_info(logger, f"compile-cache: saved bundle ({len(data)} bytes) for key {ctx.key}")
return True
except Exception as exc: # noqa: BLE001
@@ -366,10 +548,112 @@ def save(ctx: Optional[CacheContext], *, logger: Any = None) -> bool:
return False
-def restore(ctx: Optional[CacheContext]) -> None:
+def save(ctx: Optional[CacheContext], *, logger: Any = None) -> bool:
+ """Persist compiled artifacts to the bundle + manifest, AFTER a warmup forward.
+
+ No-op unless save is enabled and the context is dirty: a bundle HIT starts clean
+ (rewriting the just-loaded artifacts costs ~0.5 s for no change); a new static-compile
+ shape re-dirties via ``register_shape`` so the bundle grows to cover every shape used.
+ Returns True if a bundle was written. Synchronous: the write has happened when this
+ returns. ``save_async`` is what the generate path uses.
+ """
+ if ctx is None:
+ return False
+ return _write_bundle(ctx, logger)
+
+
+# One daemon worker for the whole process, created on first use. Saves are serialised through it, so no two threads
+# ever touch the same context and two contexts cannot interleave their save_cache_artifacts() calls.
+_dirty_lock = threading.RLock()
+_worker_cv = threading.Condition(threading.Lock())
+_worker_thread: Optional[threading.Thread] = None
+_worker_queue: list[tuple[CacheContext, Any]] = []
+_worker_active: Optional[CacheContext] = None
+
+# How long restore()/begin() will wait for an in-flight save before going ahead anyway. The worst save measured on a
+# B200 was 0.19 s for a 71 MB bundle (~2.6 ms/MB), so this is ~150x the observed cost and still covers a multi-GB
+# bundle; past it, an unload that keeps blocking reads to a user as a wedged app, which is worse than a bundle that
+# lands a moment late (the rename keeps whatever it writes atomic either way).
+_SAVE_JOIN_TIMEOUT = 30.0
+
+
+def _worker_loop() -> None:
+ global _worker_active
+ while True:
+ with _worker_cv:
+ while not _worker_queue:
+ _worker_cv.wait()
+ ctx, logger = _worker_queue.pop(0)
+ _worker_active = ctx
+ try:
+ _write_bundle(ctx, logger)
+ except Exception as exc: # noqa: BLE001 - a cache write must never reach a render
+ _warn(logger, f"compile-cache: background save failed: {exc}")
+ finally:
+ with _worker_cv:
+ _worker_active = None
+ _worker_cv.notify_all()
+
+
+def _start_worker_locked() -> None:
+ global _worker_thread
+ if _worker_thread is not None and _worker_thread.is_alive():
+ return
+ _worker_thread = threading.Thread(
+ target = _worker_loop, name = "unsloth-compile-cache-save", daemon = True
+ )
+ _worker_thread.start()
+
+
+def save_async(ctx: Optional[CacheContext], *, logger: Any = None) -> bool:
+ """Queue ``save`` on the shared worker and return at once. Never raises.
+
+ Returns True when a save was queued (or, under the SYNC env, written). Already queued
+ is False: the pending save reads the context when it runs, so it covers every shape
+ 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:
+ return False
+ if sync_saves():
+ return _write_bundle(ctx, logger)
+ try:
+ with _worker_cv:
+ if any(queued is ctx for queued, _ in _worker_queue):
+ return False
+ _worker_queue.append((ctx, logger))
+ _start_worker_locked()
+ _worker_cv.notify_all()
+ return True
+ except Exception as exc: # noqa: BLE001 - best-effort, exactly like the write itself
+ _warn(logger, f"compile-cache: could not queue background save: {exc}")
+ return False
+
+
+def wait_for_saves(timeout: float = _SAVE_JOIN_TIMEOUT) -> bool:
+ """Block until the worker is idle. True if it drained, False on timeout."""
+ deadline = time.monotonic() + timeout
+ with _worker_cv:
+ while _worker_queue or _worker_active is not None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ _worker_cv.wait(remaining)
+ return True
+
+
+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:
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
+ # something else, and the unload below goes on to tear that directory's owner down.
+ if not wait_for_saves():
+ _warn(
+ logger,
+ f"compile-cache: background save still running after {_SAVE_JOIN_TIMEOUT:.0f}s; continuing",
+ )
try:
if ctx.prev_inductor_dir is None:
os.environ.pop("TORCHINDUCTOR_CACHE_DIR", None)
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index f31906818f8..786826a8a27 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -1087,7 +1087,8 @@ def test_generate_progress_cleared_on_setup_error(fake_runtime, tmp_path, monkey
def test_generate_progress_active_through_compile_cache_save(fake_runtime, tmp_path, monkeypatch):
- # The compile-cache save runs before the route persists the image, so progress must stay active through it.
+ # The compile-cache save is handed to the background worker before the route persists the image, so progress
+ # must stay active through that post-denoise work.
from core.inference import diffusion as dmod
backend = _loaded_backend(tmp_path, hf_token = "hf_secret")
@@ -1099,11 +1100,11 @@ def test_generate_progress_active_through_compile_cache_save(fake_runtime, tmp_p
return True
monkeypatch.setattr(dmod.compile_cache, "register_shape", lambda *a, **k: None)
- monkeypatch.setattr(dmod.compile_cache, "save", fake_save)
+ monkeypatch.setattr(dmod.compile_cache, "save_async", fake_save)
gen = backend.generate(prompt = "a sloth", steps = 4)
assert len(gen["images"]) == 1
- # Still active while the compile-cache save ran.
+ # Still active while the compile-cache save was handed off.
assert seen["progress"]["active"] is True
assert seen["progress"]["total_steps"] == 4
assert backend.generate_progress()["active"] is False
@@ -1873,7 +1874,7 @@ def test_register_shape_uses_actual_forward_dims(fake_runtime, tmp_path, monkeyp
"register_shape",
lambda ctx, shape, *, static: registered.append(tuple(shape)),
)
- monkeypatch.setattr(diff.compile_cache, "save", lambda ctx, *, logger = None: True)
+ monkeypatch.setattr(diff.compile_cache, "save_async", lambda ctx, *, logger = None: True)
(tmp_path / "model.gguf").write_bytes(b"x")
backend = _loaded_backend(tmp_path)
# txt2img registers the requested slider size.
@@ -7348,7 +7349,7 @@ def test_generate_reclaims_model_offload_memory_once_after_success(
monkeypatch.setattr(dmod, "reclaim_offload_host_memory", fake_reclaim, raising = False)
monkeypatch.setattr(dmod.compile_cache, "register_shape", lambda *a, **k: None)
- monkeypatch.setattr(dmod.compile_cache, "save", lambda *a, **k: trace.append("save"))
+ monkeypatch.setattr(dmod.compile_cache, "save_async", lambda *a, **k: trace.append("save"))
object.__setattr__(backend._state, "offload_policy", "model")
object.__setattr__(backend._state, "pipe", _CountingPipe(max_images = 2))
@@ -10710,7 +10711,7 @@ def test_cancel_generate_lands_at_the_next_step_boundary(fake_runtime, tmp_path,
def test_cancel_generate_during_the_post_denoise_save_still_cancels(
fake_runtime, tmp_path, monkeypatch
):
- # The cancel event stays registered through the compile-cache save, and progress still reads
+ # The cancel event stays registered through the compile-cache handoff, and progress still reads
# active, so the page still shows Stop. Before the final recheck, a Stop landing there was
# answered cancelled = true and then contradicted: generate() returned the images and the
# route persisted them. The two answers have to agree, so the run unwinds as cancelled.
@@ -10720,11 +10721,11 @@ def test_cancel_generate_during_the_post_denoise_save_still_cancels(
backend = _loaded_backend(tmp_path)
def _save(ctx, logger = None):
- # Stop pressed while the bundle is being written: the route's cancel reaches the SAME
- # event, and it must still be registered here or the button would have reported False.
+ # Stop pressed during the post-denoise compile-cache work: the route's cancel reaches the
+ # SAME event, and it must still be registered here or the button would have reported False.
assert backend.cancel_generate() is True
- monkeypatch.setattr(compile_cache, "save", _save)
+ monkeypatch.setattr(compile_cache, "save_async", _save)
with pytest.raises(RuntimeError, match = "cancelled"):
backend.generate(prompt = "x", steps = 2)
diff --git a/studio/backend/tests/test_diffusion_compile_cache.py b/studio/backend/tests/test_diffusion_compile_cache.py
index ed62890970e..6665490935d 100644
--- a/studio/backend/tests/test_diffusion_compile_cache.py
+++ b/studio/backend/tests/test_diffusion_compile_cache.py
@@ -11,6 +11,7 @@ fingerprint helpers run against the real torch on this box.
from __future__ import annotations
+import hashlib
import json
import types
@@ -339,3 +340,489 @@ def test_restore_inductor_dir(monkeypatch, tmp_path, fake_megacache):
assert os.environ["TORCHINDUCTOR_CACHE_DIR"] != "/tmp/prior-inductor" # redirected
cc.restore(ctx)
assert os.environ["TORCHINDUCTOR_CACHE_DIR"] == "/tmp/prior-inductor" # restored
+
+
+# ------------------------------------------------------------------ background save worker
+# save_async hands the write to a single module-level daemon worker so a generation stops paying for it. These drive
+# the worker directly, gating the fake save_cache_artifacts on Events so ordering is asserted, never slept on.
+def drained():
+ """Leave the shared worker idle for the next test whatever this one did."""
+ yield
+ cc.wait_for_saves(timeout = 10.0)
+
+
+def _fake_logger():
+ class _L:
+ def __init__(self):
+ self.warnings: list[str] = []
+ self.infos: list[str] = []
+
+ def warning(self, fmt, *args):
+ self.warnings.append(fmt % args if args else fmt)
+
+ def info(self, fmt, *args):
+ self.infos.append(fmt % args if args else fmt)
+
+ return _L()
+
+
+def test_async_save_writes_the_same_bytes_as_sync(monkeypatch, tmp_path, fake_megacache, drained):
+ monkeypatch.setenv(cc._ENV_MODE, "auto")
+ monkeypatch.delenv(cc._ENV_SYNC, raising = False)
+
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path / "sync"))
+ sync_ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ cc.register_shape(sync_ctx, (1024, 1024, 1), static = True)
+ assert cc.save(sync_ctx) is True
+
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path / "async"))
+ async_ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ cc.register_shape(async_ctx, (1024, 1024, 1), static = True)
+ assert cc.save_async(async_ctx) is True
+ assert cc.wait_for_saves(timeout = 10.0) is True
+
+ assert async_ctx.bundle.read_bytes() == sync_ctx.bundle.read_bytes()
+ a = json.loads(async_ctx.manifest_path.read_text())
+ b = json.loads(sync_ctx.manifest_path.read_text())
+ # "created" is a wall clock, everything else must match byte for byte.
+ a.pop("created"), b.pop("created")
+ assert a == b
+ assert async_ctx.saved is True
+
+
+def test_async_save_is_a_noop_on_a_clean_context(monkeypatch, tmp_path, fake_megacache, drained):
+ monkeypatch.setenv(cc._ENV_MODE, "auto")
+ monkeypatch.delenv(cc._ENV_SYNC, raising = False)
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))
+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert cc.save_async(ctx) is True
+ assert cc.wait_for_saves(timeout = 10.0) is True
+ ctx2 = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert ctx2.hit is True and ctx2.saved is True
+ assert cc.save_async(ctx2) is False # a hit has nothing to write
+
+
+def test_worker_serialises_two_queued_saves(monkeypatch, tmp_path, fake_megacache, drained):
+ """One save in flight at a time: the second context waits in the queue, untouched."""
+ import threading
+
+ import torch
+
+ monkeypatch.setenv(cc._ENV_MODE, "auto")
+ monkeypatch.delenv(cc._ENV_SYNC, raising = False)
+ started = threading.Event()
+ release = threading.Event()
+ calls: list[int] = []
+
+ def gated_save():
+ calls.append(1)
+ started.set()
+ release.wait(10)
+ return (b"ARTIFACT-BYTES", None)
+
+ monkeypatch.setattr(torch.compiler, "save_cache_artifacts", gated_save, raising = False)
+
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path / "one"))
+ ctx1 = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path / "two"))
+ ctx2 = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+
+ assert cc.save_async(ctx1) is True
+ assert started.wait(10) is True
+ assert cc.save_async(ctx2) is True
+ # Deterministic, no sleeping: ctx1 holds the worker and ctx2 is still queued behind it.
+ assert cc._worker_active is ctx1
+ assert [c is ctx2 for c, _ in cc._worker_queue] == [True]
+ assert len(calls) == 1
+ assert not ctx2.bundle.exists()
+
+ release.set()
+ assert cc.wait_for_saves(timeout = 10.0) is True
+ assert len(calls) == 2
+ assert ctx1.bundle.exists() and ctx2.bundle.exists()
+
+
+def test_redirtied_context_queues_a_second_save(monkeypatch, tmp_path, fake_megacache, drained):
+ """A shape registered WHILE a save runs is not in that bundle, so it must get its own save."""
+ import threading
+
+ import torch
+
+ monkeypatch.setenv(cc._ENV_MODE, "auto")
+ monkeypatch.delenv(cc._ENV_SYNC, raising = False)
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))
+
+ started = threading.Event()
+ release = threading.Event()
+ saves: list[int] = []
+
+ def gated_save():
+ saves.append(1)
+ if len(saves) == 1:
+ started.set()
+ release.wait(10)
+ return (b"ARTIFACT-BYTES", None)
+
+ monkeypatch.setattr(torch.compiler, "save_cache_artifacts", gated_save, raising = False)
+
+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ cc.register_shape(ctx, (1024, 1024, 1), static = True)
+ assert cc.save_async(ctx) is True
+ assert started.wait(10) is True
+
+ # Second generation, new static shape, while the first save is mid-flight.
+ cc.register_shape(ctx, (768, 768, 1), static = True)
+ assert ctx.saved is False
+ assert cc.save_async(ctx) is True # queued behind the running one, not dropped
+
+ release.set()
+ assert cc.wait_for_saves(timeout = 10.0) is True
+ assert len(saves) == 2
+ # The in-flight save must NOT have claimed the context clean, and the rewritten manifest covers both shapes.
+ assert ctx.saved is True
+ assert json.loads(ctx.manifest_path.read_text())["shapes"] == [[768, 768, 1], [1024, 1024, 1]]
+
+
+def test_sync_env_switch_writes_inline(monkeypatch, tmp_path, fake_megacache, drained):
+ monkeypatch.setenv(cc._ENV_MODE, "auto")
+ monkeypatch.setenv(cc._ENV_SYNC, "1")
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))
+ assert cc.sync_saves() is True
+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ cc.register_shape(ctx, (1024, 1024, 1), static = True)
+ assert cc.save_async(ctx) is True
+ # No worker involved: the bundle is on disk the moment save_async returns, as it was before the worker existed.
+ assert ctx.bundle.exists() and ctx.manifest_path.exists()
+ assert ctx.saved is True
+ assert cc._worker_active is None and not cc._worker_queue
+
+
+def test_worker_failure_is_swallowed_and_logged(monkeypatch, tmp_path, fake_megacache, drained):
+ import torch
+
+ monkeypatch.setenv(cc._ENV_MODE, "auto")
+ monkeypatch.delenv(cc._ENV_SYNC, raising = False)
+ monkeypatch.setenv(cc._ENV_DIR, str(tmp_path))
+
+ def boom():
+ raise RuntimeError("inductor exploded")
+
+ monkeypatch.setattr(torch.compiler, "save_cache_artifacts", boom, raising = False)
+ log = _fake_logger()
+ ctx = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ cc.register_shape(ctx, (1024, 1024, 1), static = True)
+ assert cc.save_async(ctx, logger = log) is True # queuing succeeds; the failure is the worker's
+ assert cc.wait_for_saves(timeout = 10.0) is True
+ assert not ctx.bundle.exists()
+ assert ctx.saved is False
+ assert any("inductor exploded" in w for w in log.warnings)
+
+ # The worker survives its own failure and takes the next save.
+ monkeypatch.setattr(
+ torch.compiler, "save_cache_artifacts", lambda: (b"ARTIFACT-BYTES", None), raising = False
+ )
+ assert cc.save_async(ctx, logger = log) is True
+ assert cc.wait_for_saves(timeout = 10.0) is True
+ assert ctx.bundle.exists()
+
+
+def test_atomic_write_never_publishes_a_partial_file(monkeypatch, tmp_path, fake_megacache):
+ """A save killed mid-write must leave the PREVIOUS bundle, not a truncated new one."""
+ monkeypatch.setenv(cc._ENV_MODE, "on")
+ 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
+ good = ctx.bundle.read_bytes()
+
+ # Fail at the exact moment the finished temp file would be published.
+ def exploding_replace(src, dst):
+ raise OSError("killed mid-write")
+
+ monkeypatch.setattr(cc.os, "replace", exploding_replace)
+ ctx.saved = False
+ assert cc.save(ctx) is False
+ monkeypatch.undo()
+
+ assert ctx.bundle.read_bytes() == good # the old bundle is still whole and still loadable
+ assert [p.name for p in ctx.dir.iterdir() if p.name.endswith(".tmp")] == []
+
+
+def test_atomic_write_replaces_in_place(tmp_path):
+ target = tmp_path / "cache.bin"
+ cc._atomic_write(target, b"first")
+ cc._atomic_write(target, b"second")
+ assert target.read_bytes() == b"second"
+ assert list(tmp_path.iterdir()) == [target] # no temp files left behind
+
+
+# ------------------------------------------------- interrupted saves and bundle collection
+# The manifest is the single commit point and the bundle is content-addressed, so whatever a save is killed in the
+# middle of, what is left on disk is a MATCHING pair. These drive each window of that directly.
+def mutable_megacache(monkeypatch):
+ """Like ``fake_megacache`` but the artifact bytes can change between saves."""
+ import torch
+
+ state = {"bytes": b"ARTIFACT-ONE"}
+ monkeypatch.setattr(
+ torch.compiler, "save_cache_artifacts", lambda: (state["bytes"], None), raising = False
+ )
+ monkeypatch.setattr(
+ torch.compiler,
+ "load_cache_artifacts",
+ lambda data: object() if data else None,
+ raising = False,
+ )
+ return state
+
+
+def _cold_pair(monkeypatch, tmp_path):
+ """A committed manifest/bundle pair, saved synchronously."""
+ monkeypatch.setenv(cc._ENV_MODE, "on")
+ 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
+ return ctx
+
+
+def test_bundles_are_content_addressed_and_named_by_the_manifest(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ digest = hashlib.sha256(b"ARTIFACT-ONE").hexdigest()
+ assert ctx.bundle.name == cc._bundle_name(digest)
+ manifest = json.loads(ctx.manifest_path.read_text())
+ assert manifest["bundle"] == ctx.bundle.name
+ assert manifest["sha256"] == digest
+ # The fixed legacy name is never written any more.
+ assert not (ctx.dir / cc._BUNDLE_NAME).exists()
+
+
+def test_an_interrupted_bundle_write_leaves_the_previous_pair_loadable(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ """Window 1: the manifest is committed and the NEW bundle is only half written."""
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ live, live_bytes = ctx.bundle, ctx.bundle.read_bytes()
+
+ mutable_megacache["bytes"] = b"ARTIFACT-TWO-IS-A-DIFFERENT-LENGTH"
+ doomed = ctx.dir / cc._bundle_name(hashlib.sha256(mutable_megacache["bytes"]).hexdigest())
+ real_replace = cc.os.replace
+
+ def die_publishing_the_bundle(src, dst):
+ raise OSError("killed mid-write")
+
+ monkeypatch.setattr(cc.os, "replace", die_publishing_the_bundle)
+ ctx.saved = False
+ assert cc.save(ctx) is False
+ monkeypatch.setattr(cc.os, "replace", real_replace) # not undo(): the env must survive
+
+ # Nothing half written is visible under a name anything reads, and no temp file is left over.
+ assert not doomed.exists()
+ assert [p.name for p in ctx.dir.iterdir() if p.name.endswith(".tmp")] == []
+ # The previous pair is untouched and still a real warm start.
+ assert live.read_bytes() == live_bytes
+ reopened = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert reopened.hit is True
+ assert reopened.bundle == live
+
+
+def test_a_bundle_published_without_its_manifest_leaves_the_previous_pair_loadable(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ """Window 2: the NEW bundle landed and the manifest never committed.
+
+ This is the case a single fixed ``cache.bin`` got wrong: it left the old manifest describing a file that had
+ already been overwritten, so the sha256 check discarded a warm start that was fine.
+ """
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ live, live_bytes = ctx.bundle, ctx.bundle.read_bytes()
+
+ mutable_megacache["bytes"] = b"ARTIFACT-TWO-IS-A-DIFFERENT-LENGTH"
+ orphan = ctx.dir / cc._bundle_name(hashlib.sha256(mutable_megacache["bytes"]).hexdigest())
+ real_atomic = cc._atomic_write
+
+ def die_before_committing_the_manifest(path, data):
+ if path.name == cc._MANIFEST_NAME:
+ raise OSError("killed before the manifest committed")
+ return real_atomic(path, data)
+
+ monkeypatch.setattr(cc, "_atomic_write", die_before_committing_the_manifest)
+ ctx.saved = False
+ assert cc.save(ctx) is False
+ monkeypatch.setattr(cc, "_atomic_write", real_atomic)
+
+ # The new bundle is on disk but nothing names it; the committed manifest still names the old one, intact.
+ assert orphan.exists() and orphan.read_bytes() == b"ARTIFACT-TWO-IS-A-DIFFERENT-LENGTH"
+ assert live.read_bytes() == live_bytes
+ assert json.loads(ctx.manifest_path.read_text())["bundle"] == live.name
+ reopened = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert reopened.hit is True
+ assert reopened.bundle == live
+
+ # And orphans do not accumulate. A save of the SAME artifacts adopts the orphan rather than rewriting it
+ # (that is what content addressing buys), retiring the old bundle instead...
+ monkeypatch.setattr(cc, "_GC_GRACE_SECONDS", -1.0)
+ reopened.saved = False
+ assert cc.save(reopened) is True
+ assert reopened.bundle == orphan and orphan.exists()
+ assert not live.exists()
+
+ # ...and a save of DIFFERENT artifacts collects it like any other superseded bundle.
+ mutable_megacache["bytes"] = b"ARTIFACT-THREE"
+ reopened.saved = False
+ assert cc.save(reopened) is True
+ assert not orphan.exists()
+ assert [p.name for p in reopened.dir.iterdir() if p.name.startswith(cc._BUNDLE_PREFIX)] == [
+ reopened.bundle.name
+ ]
+
+
+def test_a_superseded_bundle_is_collected_and_the_live_pair_still_loads(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ """Window 3: a committed new pair retires the old bundle, and what is left still loads."""
+ monkeypatch.setattr(cc, "_GC_GRACE_SECONDS", -1.0)
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ first = ctx.bundle
+
+ mutable_megacache["bytes"] = b"ARTIFACT-TWO-IS-A-DIFFERENT-LENGTH"
+ ctx.saved = False
+ assert cc.save(ctx) is True
+ second = ctx.bundle
+
+ assert second != first
+ assert second.exists() and not first.exists()
+ assert [p.name for p in ctx.dir.iterdir() if p.name.startswith(cc._BUNDLE_PREFIX)] == [
+ second.name
+ ]
+ reopened = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert reopened.hit is True
+ assert reopened.bundle == second
+
+
+def test_collection_never_removes_the_live_bundle_or_one_a_racing_process_just_wrote(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ import os as _os
+
+ ctx = _cold_pair(monkeypatch, tmp_path)
+
+ # A bundle another process has written but not yet committed a manifest for is named by nothing. Deleting it
+ # there would hand that process the broken pair this layout exists to prevent, so the grace window spares it.
+ stray = ctx.dir / cc._bundle_name("f" * 64)
+ stray.write_bytes(b"written by another process, manifest still pending")
+ assert cc._collect_superseded(ctx.dir, None) == []
+ assert stray.exists()
+
+ # Once it is old enough to not be anybody's in-flight save, it goes.
+ _os.utime(stray, (0, 0))
+ assert cc._collect_superseded(ctx.dir, None) == [stray.name]
+ assert not stray.exists()
+
+ # The bundle the manifest ON DISK names is never a candidate, however old it is.
+ _os.utime(ctx.bundle, (0, 0))
+ assert cc._collect_superseded(ctx.dir, None) == []
+ assert ctx.bundle.exists()
+ assert cc.begin(transformer = _transformer(), **_BEGIN_KW).hit is True
+
+
+def test_a_manifest_from_before_content_addressing_still_hits(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ """Bundles written by the old layout name no "bundle" key, so they resolve to cache.bin and keep hitting."""
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ legacy = ctx.dir / cc._BUNDLE_NAME
+ ctx.bundle.rename(legacy)
+ manifest = json.loads(ctx.manifest_path.read_text())
+ manifest.pop("bundle")
+ ctx.manifest_path.write_text(json.dumps(manifest))
+
+ reopened = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert reopened.hit is True
+ assert reopened.bundle == legacy
+
+ # And the legacy file is collected only once a new pair supersedes it.
+ monkeypatch.setattr(cc, "_GC_GRACE_SECONDS", -1.0)
+ mutable_megacache["bytes"] = b"ARTIFACT-TWO-IS-A-DIFFERENT-LENGTH"
+ reopened.saved = False
+ assert cc.save(reopened) is True
+ assert not legacy.exists()
+ assert cc.begin(transformer = _transformer(), **_BEGIN_KW).hit is True
+
+
+def test_a_bundle_spared_by_the_grace_window_is_collected_when_the_key_is_opened_again(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ # Two saves for one key inside the grace window: the first bundle is superseded but too young
+ # to collect, and the second save is the last thing that would ever have looked at it. Opening
+ # the key again is what collects it, so the window costs a delay rather than the disk.
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ first = ctx.bundle
+
+ mutable_megacache["bytes"] = b"ARTIFACT-TWO-IS-A-DIFFERENT-LENGTH"
+ ctx.saved = False
+ monkeypatch.setattr(cc, "_GC_GRACE_SECONDS", 3600.0)
+ assert cc.save(ctx) is True
+ second = ctx.bundle
+
+ # Still there: inside an hour-long grace, the save left it alone.
+ assert second != first
+ assert first.exists()
+
+ # Next open of the same key, with that grace expired, takes it.
+ monkeypatch.setattr(cc, "_GC_GRACE_SECONDS", 60.0)
+ import os as _os
+
+ _os.utime(first, (0, 0))
+ reopened = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert not first.exists()
+ assert second.exists()
+ assert reopened.hit is True
+ assert reopened.bundle == second
+
+
+def test_a_bundle_rejected_on_its_checksum_is_rewritten_rather_than_kept(
+ monkeypatch, tmp_path, mutable_megacache
+):
+ # Corruption on disk gives a load that fails the checksum. The recompile that follows produces
+ # the same artifacts and therefore the same content-addressed NAME, so the exists() shortcut
+ # would leave the corrupt bytes in place under a manifest that names them and the cache could
+ # never come back. The rejection is remembered and the file overwritten.
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ good = ctx.bundle.read_bytes()
+ ctx.bundle.write_bytes(b"CORRUPT" + good[7:])
+
+ reopened = cc.begin(transformer = _transformer(), **_BEGIN_KW)
+ assert reopened.hit is False
+ assert reopened.rejected_bundle == ctx.bundle.name
+
+ reopened.saved = False
+ assert cc.save(reopened) is True
+ assert reopened.bundle.read_bytes() == good
+
+ # And the next start hits again, which is the whole point: the cache healed itself.
+ assert cc.begin(transformer = _transformer(), **_BEGIN_KW).hit is True
+
+
+def test_a_temp_file_left_by_a_killed_save_is_collected(monkeypatch, tmp_path, mutable_megacache):
+ # _atomic_write's finally does not run when the interpreter tears the daemon save thread down
+ # inside fh.write, so its temp file survives, and it is as large as the bundle. Collection now
+ # recognises it, under the same grace window that protects a write actually in flight.
+ import os as _os
+
+ ctx = _cold_pair(monkeypatch, tmp_path)
+ stranded = ctx.dir / f".{ctx.bundle.name}.abcd1234{cc._TEMP_SUFFIX}"
+ stranded.write_bytes(b"half of a multi-GB bundle")
+
+ # Fresh, so it could still be somebody's in-flight write.
+ assert cc._collect_superseded(ctx.dir, None) == []
+ assert stranded.exists()
+
+ _os.utime(stranded, (0, 0))
+ assert cc._collect_superseded(ctx.dir, None) == [stranded.name]
+ assert not stranded.exists()
+ assert ctx.bundle.exists()