Repository navigation
Studio: show what the caches cost and let them be cleared - #10528
Conversation
Unsloth's caches are what make an update or a second run fast, so they are worth keeping and worth being able to see. On a working box they are also the largest thing on disk that is safe to delete: uv's wheel cache alone reaches tens of gigabytes, and nothing in Studio said so or offered to reclaim it. Settings > Resources > Storage now lists every cache with its size and a total, and can empty them. Sizes are memoised for 60 seconds with a Recheck button, because a cold walk over a large uv cache and a triton cache of tens of thousands of files takes tens of seconds. Only caches are ever removed. The API takes a cache KEY, never a path, so a caller cannot name a directory to delete; the roots are computed in the backend from the same resolvers the rest of Studio uses. Each root is then checked before anything is unlinked: absolute, not a symlink, at least two components below the filesystem anchor, and neither inside nor containing a protected path (the Studio home, studio.db, auth, projects, models, datasets, outputs, exports, the Hugging Face cache home that holds the token, or a managed asset home such as DATA_DESIGNER_HOME). The root is emptied rather than removed, a symlink inside it is unlinked instead of followed, and a directory whose real path leaves the root is skipped. Three caches are opt-in and are never swept up by the bulk clear. The Hugging Face hub and dataset caches cost a re-download of something the user asked for. The unsloth compiled cache is excluded for a different reason: a training or inference worker imports generated modules from it lazily, long after the job started, and the existing lock only serialises against a sibling backend, not against a spawned worker. Clearing it under a running job would forfeit hours of compute, which is not a trade to make from a button labelled free up space. When free disk crosses 20 GB, or 5 GB for the stronger warning, a toast offers the caches as the thing to trim and links to that section. It is mounted at the app level rather than inside Settings, since a warning shown only to someone already looking at the disk figure reaches the people who least need it, and it adds no polling: it subscribes to the system poll the app already runs. The level is held for the browser session so a threshold is announced when it is crossed, not once per poll while the disk sits below it.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (1)ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f55c9184ef
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const OPT_IN_COST_KEYS: Partial<Record<CacheKey, TranslationKey>> = { | ||
| // biome-ignore lint/style/useNamingConvention: API schema | ||
| hf_hub: "settings.resources.storage.caches.hubCost", | ||
| // biome-ignore lint/style/useNamingConvention: API schema | ||
| hf_datasets: "settings.resources.storage.caches.datasetsCost", | ||
| }; |
There was a problem hiding this comment.
Warn before clearing the compiled cache during active work
unsloth_compiled is deliberately opt-in because deleting it can break a running training or inference worker, but it has no entry in OPT_IN_COST_KEYS. Its confirmation therefore shows only the generic reassurance that the cache will be rebuilt next time, without disclosing that the current job may fail and lose hours of compute. Add a dedicated warning for this key, or prevent the clear while affected work is active.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The premise is right that the compiled cache has no cost line, but every sentence the dialog does show is true for it, the backend already refuses when a sibling backend holds the lock, and the cache is opt-in so a bulk clear never reaches it. Copy enrichment rather than a false statement.
| return subscribeSystemInfo((info) => { | ||
| if (!info.disk) return; | ||
| const level = observeDiskPressure(info.disk); |
There was a problem hiding this comment.
Measure disk pressure on the cache volume
When Studio or the Hugging Face cache is configured on a different filesystem, info.disk is not the volume these actions reclaim: /api/system obtains it from psutil.disk_usage(os.path.abspath(os.sep)), i.e. the root filesystem. The toast therefore misses a nearly full model/cache volume when / has space, or recommends clearing caches on another volume when / is low and clearing them cannot help. Base the warning on the filesystem containing the relevant cache or Studio storage root.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The premise is right that /api/system measures the root filesystem while the caches can sit on another volume, but the toast says free of total and that clearing caches can free space, which is true of the volume it reports, and most caches (uv, pip, npm, triton, inductor) live under HOME or XDG regardless of where the HF cache points. Making it volume-aware needs a per-cache free-space source on the poll, which is a bigger change than the warning warrants.
| elif entry.is_dir(follow_symlinks = False): | ||
| real = _safe_resolve(path) | ||
| if real is None or not _is_within(real, root): | ||
| outcome.errors.append(f"Skipped {path}: it resolves outside the cache root") | ||
| return | ||
| size, _ = _measure_tree(path, seen) | ||
| # rmtree refuses a symlinked directory and does not follow links it | ||
| # finds inside, so the walk cannot leave *root*. | ||
| shutil.rmtree(path) |
There was a problem hiding this comment.
Skip mounted directories inside cache roots
If a cache contains a bind mount or another mounted directory, realpath still returns the lexical path beneath the cache root, so this containment check passes and shutil.rmtree() traverses into the mounted filesystem. In container and workstation setups that mount a project, dataset, or persistent volume below a cache directory, clearing the cache can therefore delete the mounted data itself. Detect and skip mount points before measuring or recursively removing directory entries.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The mechanism is real, but the remedy cannot detect the case: os.path.ismount is documented as unable to reliably detect bind mounts on the same filesystem, and CPython's implementation is an st_dev/st_ino comparison that returns False for exactly the mount --bind described here (bpo-29707 was closed as a docs change). GNU rm --one-file-system has the same blind spot. The reliable detector is /proc/self/mountinfo, which is Linux-only. Against that, the triggering setup is non-cache data bind-mounted under a directory whose declared purpose is disposable, where rm -rf on the cache destroys it identically, and skipping mounts would silently under-clear legitimate multi-mount caches.
|
Before/after from two isolated installs: BEFORE is this PR's merge base The two existing rows are the control: "System disk" and "Models folder" are identical on both sides, down to the path and the "Managed by the HF_HUB_CACHE environment variable" line. The cache inventory is the only thing that moved. Numbers read from the same server that was photographed, not from the picture:
The 1.70 GB between the total and the clearable figure is exactly the three opt-in caches ( Two things about the picture that are the host's, not the feature's. The paths are this build box's, and one row resolves inside the screenshot harness's own temporary home rather than a normal install. The 678 GB uv cache is a shared CI machine that has been building for a long time; it is not a typical figure, though it is a fair illustration of why the feature exists. The scene never presses "Clear caches" or a per-row "Clear". The sizes are this box's real caches, read only, and nothing was deleted to make the image. |
The low-disk notice never worked. Its own comment claimed it subscribed to the system poll the app already runs; there is no such poll. subscribeSystemInfo only adds a callback to a Set, and the only two callers of the fetching hook are the floating monitor and the resources tab, both lazily mounted and both gated on being open. So the warning reached nobody who had not already opened the one screen that shows the disk figure, which is the audience it exists to reach. It now owns a 60 second poll and says so. The test that was supposed to cover this asserted the opposite, requiring the subscribe form and BANNING the fetching one, so it passed for as long as the feature was broken; it now asserts the fetch. It was also mounted in StudioPage, which is the /studio training route rather than an app shell, so anyone in Chat, Images or Audio never subscribed at all. It moves to RootLayout beside the other null-returning mounts. An opt-in cache nested inside another cache root was deleted by a bulk clear of the parent, because opt-in roots were in neither the protected paths nor the protected trees. That defeats the whole point of marking the model, dataset and compiled caches opt-in, so a root that contains one is now refused with that reason, except when it is the cache being asked for by name. On Windows a directory junction is not reported by Path.is_symlink but is followed by realpath, so a junction cache root had its target emptied. Junctions are now refused like symlinks, and skipped when measuring so a row cannot advertise bytes it will not delete. An explicit HF_HUB_CACHE whose basename is not hub made the displayed cache home and the hub directory the same path, so the model cache was permanently unclearable and the UI called it a protected location when it held no credential. The token lives under HF_HOME, which stays protected. The cache rows measured once per mount, so changing the models folder left them showing the previous folder's path and size beside a field showing the new one, with a Clear that acted on the new one. They now follow the inventory version. The hub confirmation dialog concatenated its cost line with the generic assurance that downloaded models are not touched, which denied the deletion it was asking permission for.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ac8bc88ea5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not resolved.is_dir(): | ||
| raise CachePurgeRefused(f"Cache root is not a directory: {resolved}") | ||
| for reserved in protected: | ||
| if resolved == reserved: |
There was a problem hiding this comment.
Refuse cache roots in credential and system directories
When an inherited cache variable points into a sensitive directory, such as UV_CACHE_DIR=~/.ssh or PIP_CACHE_DIR=/etc/ssl, this gate accepts the directory because it is deep enough and is not one of the Studio-specific protected paths, so clearing that cache recursively deletes credentials or system data. This repository already exposes contains_sensitive_path_component() and is_denied_system_path() for rejecting exactly these locations; apply those checks to the resolved purge root before allowing deletion.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. UV_CACHE_DIR=~/.ssh does pass the gate, but neither helper can be applied to a resolved cache root without refusing real caches.
contains_sensitive_path_component (utils/paths/sensitive.py) matches any component against a set that includes .config, .local and .huggingface. That refuses MPLCONFIGDIR=~/.config/matplotlib, which is matplotlib's own default config dir on Linux, any cache under ~/.local, and the hub cache of a legacy HF_HOME=~/.huggingface, which is a model cache made permanently unclearable.
is_denied_system_path denies /private/var on macOS and documents that it wants an already-realpath'd argument. tempfile.gettempdir() on macOS is /var/folders/.../T, which realpath resolves to /private/var/folders/.../T, so every Mac's torch inductor cache, the largest compile cache in this list, would be refused.
Both are the registration policy for user-chosen scan folders, which is a different question from whether a root this backend resolved is safe to empty. The gate already refuses shallow roots, symlinks, junctions, and every Studio-managed data root.
| try: | ||
| child.relative_to(parent) | ||
| return True | ||
| except ValueError: | ||
| return False |
There was a problem hiding this comment.
Compare protected paths using filesystem identity on macOS
On a case-insensitive macOS volume, these lexical Path comparisons treat differently cased spellings as unrelated even though the filesystem treats them as the same location. For example, if studio_root() resolves as /Users/me/.unsloth/studio but UV_CACHE_DIR is inherited as /users/me/.unsloth/studio, the equality and containment guards miss every protected path and the purge can empty the Studio home itself. Canonicalize paths according to the actual filesystem or compare ancestor identities rather than relying on case-sensitive relative_to().
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The mechanism is real, realpath does not canonicalize case on APFS, but three things stand against the fix.
The trigger is an environment variable that deliberately mis-cases a Studio-managed path. Nothing in the product produces a lower-cased HOME, and a user who types /users/me/... into UV_CACHE_DIR is not input this receives.
Windows, the other case-insensitive platform, is already covered. os.path.realpath there is documented to return "the case reported by the operating system, which can differ from the case of path", so _safe_resolve normalizes it.
And filesystem identity cannot replace these checks. protected_paths() deliberately holds paths that need not exist: studio_db_path(), auth_db_path(), <hf home>/token, and the configured env homes. _is_within answers a containment question that has no inode to compare. Identity would fall back to the lexical compare for exactly the entries that matter.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d553c54c11
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| def _triton_dirs() -> list[Path]: | ||
| return _first(_env_dir("TRITON_CACHE_DIR"), _home() / ".triton" / "cache") |
There was a problem hiding this comment.
Resolve Triton's cache derived from TorchInductor
When TORCHINDUCTOR_CACHE_DIR is set but TRITON_CACHE_DIR is not, the targeted Torch versions place Triton's cache under the configured Inductor root (the repository's compile-cache isolation helper documents and compensates for this behavior). This resolver instead always checks ~/.triton/cache, so the Triton row is absent or measures an unrelated legacy directory and its per-cache Clear action cannot clear the active Triton cache. Derive the default from TORCHINDUCTOR_CACHE_DIR before falling back to the home location.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. triton_cache_dir(device) in torch/_inductor/runtime/cache_dir_utils.py is TRITON_CACHE_DIR, else {cache_dir()}/triton/{device}. So whenever TRITON_CACHE_DIR is unset the torch-driven Triton cache is inside the inductor root, whether TORCHINDUCTOR_CACHE_DIR is set or not. tests/_shared/compile_cache_isolation.py in this repo says the same thing and is why it sets both explicitly.
_torch_inductor_dirs() already returns that root, and both the size walk and empty_cache_root are recursive, so those bytes are already measured and already freed, under Torch Inductor. Deriving the same path into _triton_dirs() would report them in two rows and count them twice in the total.
~/.triton/cache is not an unrelated legacy directory either. It is Triton's own default, knobs.py resolves cache.dir to cache.get_triton_dir("cache") when TRITON_CACHE_DIR is unset, which is what a standalone Triton run uses.
|
@codex security review |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: be90a5e965
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| def _hf_hub_dirs() -> list[Path]: | ||
| return [_hf_paths().hub_cache] |
There was a problem hiding this comment.
Bind purges to the cache roots the UI confirmed
The follow-up limits deletion to the active root, but that root remains mutable through the API-key-accessible PUT /hugging-face-cache (routes/settings.py:1113-1123). Because the purge request contains only a key and this resolver reads the active root at execution time, an API-key caller can switch the home after a UI session displayed or confirmed the old path—for example to a writable parent containing a valuable hub directory—and the subsequent UI-only purge empties the new directory. Fresh evidence in this revision is that historical roots were removed while the active root is still dynamically resolved; bind confirmation to the validated root or prevent API-key callers from changing it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The chain does not gain the caller anything they do not already have: DELETE /api/hub/delete-cached (hub/routes/inventory.py:241-256) takes repo_id, variant and a cache_path, depends on get_current_subject only, and its router carries no dependencies, so an API key deletes cached model data today, directly, without planting a root and waiting for a victim to click Clear. require_ui_session on /caches/purge is a guard on the bulk whole-directory clear this PR adds, not a claim that a key cannot delete anything.
Both proposed remedies also reach past this PR. Gating PUT /hugging-face-cache on a UI session changes the auth of a pre-existing route and breaks anyone driving it with a key. A server-issued root digest adds a token to a request protocol whose whole design is that it carries a key and never a path, and it would have to be re-validated at execution time anyway, since the root can move between the digest and the purge just as it can between the render and the click.
If API keys should not be able to delete model data, that is a decision about the hub delete routes, and it is not one an inventory can carry.
| total = sum(entry["size_bytes"] for entry in entries if entry["present"]) | ||
| reclaimable = sum( | ||
| entry["size_bytes"] | ||
| for entry in entries | ||
| if entry["present"] and entry["purgeable"] and not entry["opt_in"] |
There was a problem hiding this comment.
Deduplicate overlapping roots in inventory totals
When two supported cache settings overlap—for example UV_CACHE_DIR=/cache/packages and PIP_CACHE_DIR=/cache/packages/pip—the uv measurement already includes every byte in the pip root, but these sums add the pip measurement again. The displayed total and reclaimable amount, including the bulk-clear confirmation, can therefore substantially overstate the disk space occupied and reclaimable even though the actual purge frees each byte only once. Compute totals over canonical roots without double-counting descendants.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The double count is real when one cache root is nested inside another, but the trigger is a variable deliberately pointing one tool's cache inside another tool's, and no deletion is affected: neither uv nor pip is opt-in or pattern-limited, so a bulk clear empties the outer root and the bytes go once, which is what freed_bytes reports.
The remedy costs more than the defect. Summing over canonical roots makes the rows stop adding up to the total, so the panel would show uv at 5 GB, pip at 2 GB and a total of 5 GB, which is a worse contract for a reader than a total that is high in a configuration nobody arrives at by accident.
| def _hf_datasets_dirs() -> list[Path]: | ||
| return _hf_child_dirs("datasets", "HF_DATASETS_CACHE") |
There was a problem hiding this comment.
Include Studio's processed dataset cache
Studio writes processed Arrow datasets under cache_root()/hf-datasets: prepare_app_processed_dataset_cache() uses its snapshot-loads child for ordinary cached Hub datasets, and load_dataset_cache_safe() also uses the same root after cache permission failures. Because the temporary HF_DATASETS_CACHE override is restored after a fallback load, this resolver later returns only the environment or HF-home directory and never reports or clears the Studio-owned cache, which can retain another dataset-sized copy indefinitely. Include cache_root()/hf-datasets among the hf_datasets roots.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, and the premise is right: hub/utils/dataset_processed_cache.py:35 puts it at cache_root() / "hf-datasets" / ... and utils/datasets/cache_safe.py:77 uses the same root, so it is real, Studio-owned and dataset-sized.
It does not belong in this change. Every root here is a cache a third-party tool writes, plus the Unsloth compiled cache, and cache_root() is deliberately protected whole because it is the parent those sit under plus llama.cpp slot state. Carving a purgeable child out of it is a policy decision, not a resolver. More to the point, the answer it needs is the one unsloth_compiled already carries: a training job memory-maps Arrow files out of that directory long after it started, so clearing it under a running job breaks the job, which makes it opt-in at best and needs its own reasoning about what holds it open. Worth doing, on its own.
| CacheDefinition("pip", GROUP_PACKAGES, False, _pip_dirs), | ||
| CacheDefinition("npm", GROUP_PACKAGES, False, _npm_dirs), | ||
| CacheDefinition("bun", GROUP_PACKAGES, False, _bun_dirs), | ||
| CacheDefinition("torch_inductor", GROUP_COMPILE, False, _torch_inductor_dirs), |
There was a problem hiding this comment.
Include the diffusion compile cache
Image and video inference enable the separate diffusion Mega-cache by default and write bundles plus a per-key Inductor cache under ~/.cache/unsloth/diffusion_compile_cache (or UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR); restore() then removes the temporary TORCHINDUCTOR_CACHE_DIR override. Consequently this torch_inductor definition resolves the ordinary temp cache after unload and misses the persistent diffusion artifacts entirely, so repeated generations can accumulate compile caches that the new inventory neither measures nor clears. Add the diffusion cache root to the compile-cache inventory.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, and the premise is right: core/inference/diffusion_compile_cache.py:53 defaults to ~/.cache/unsloth/diffusion_compile_cache, cache_mode() is auto by default, and restore() puts TORCHINDUCTOR_CACHE_DIR back on unload.
Two reasons to keep it out. It is a new cache key rather than a defect in a listed one, with a name in thirteen locales behind it, and it needs the same decision the compiled cache carries: while a diffusion model is loaded, TORCHINDUCTOR_CACHE_DIR points into <key>/inductor inside that root, so a clear lands under a model that is using it. Note that in that state the Torch Inductor row already resolves there and covers those bytes, so the gap is the bundles and the caches of models that are not loaded.
Worth adding as its own change, with the opt-in question answered rather than assumed.
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
Here are some automated security review suggestions for this pull request.
Reviewed commit: be90a5e965
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| def _hf_child_dirs(name: str, env_key: str) -> list[Path]: | ||
| # HF reads the variable INSTEAD of <home>/<name>, so these are alternatives. | ||
| return _first(_env_dir(env_key), _hf_paths().cache_home / name) |
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
Security: Bind purges to the cache home the UI confirmed
When a lower-trust API-key caller can reach Studio, it can still PUT an ordinary writable project as the active Models Folder after the UI measured its rows. Fresh evidence after the history-only fix is that this resolver rereads the mutable active home at purge time, while /caches/purge sends only a key. A victim clicking Clear on the old row can therefore recursively delete, for example, the new <project>/assets; the API-key purge guard does not help because the victim supplies the UI session. Restrict cache-home changes to UI sessions or bind purges to a server-issued inventory generation/root digest.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same finding as the code-review copy, same answer: DELETE /api/hub/delete-cached already accepts an API key and a cache_path, so this is not an escalation over what the key can do directly. Full reasoning on the other thread.
Polling, and the cost of a readingThe original version hung the low-disk notice off the app-wide It is now event driven. Nothing polls on a timer at all:
A 30 second floor coalesces bursts (queueing eight files asks once), and concurrent callers share one in-flight request. The reading itself is a new That is deliberately not what WinDirStat does. WinDirStat answers "what is using my space", which needs a full tree walk and takes seconds on a large volume. The question here is "is there room for this download", which is a single free-space syscall. Adopting the WinDirStat approach would make a routine download start hang. Measured on GitHub-hosted runners, 1000 calls each: Windows is the slowest and is still about 300x under the 5 ms budget the test enforces. A test asserts that budget, and a second one parses the route's AST and fails the build if Two behaviours worth naming: if the cache directory does not exist yet the route walks up its parents to the nearest existing one rather than failing, and a failed reading returns |
hf_default_cache_dir() is documented to ignore HF_HUB_CACHE and the Models Folder setting, so on a machine that moved its downloads to another disk /api/system/disk reported the free space of a volume the next download will not touch. Its home ancestor always exists, so the fallback never reached studio_root() either. The active hub cache is asked first now, at the cost of one SQLite setting read. The inventory memo is keyed by cache rather than by path, so changing the Models Folder left hf_hub, hf_xet and hf_datasets describing the old root for the rest of the TTL. A browser hides that by forcing a refresh off the inventory-version event, but an API-key caller may change the folder and read the inventory while being forbidden refresh=true, so it had no way to ask again. set_hf_cache_home now invalidates those three alongside the scans it already invalidated.
|
Intel macOS closes the last gap in the matrix above. Six runners now: |
Emptying the whole hub cache skipped the inference load-state guards that deleting ONE repo already runs, which made the wider action the one with the weaker check. sd.cpp re-reads its companion VAE and text-encoder files for every generation, so this broke a model loaded long before the clear, not only one mid-load. A repo-agnostic guard sits beside the per-repo ones and is asked for the model-cache keys, failing closed when it cannot answer, as the per-repo path does with its 503. The uv cache is refused when the installed environment is linked into it rather than copied from it. uv's own help says clearing under UV_LINK_MODE=symlink will break all installed packages, which turns a bulk clear from a re-download into a broken install. Two cheap answers, no walk: the declared link mode, and a top-level symlink in this interpreter's site-packages resolving into a uv root. Reclaimable bytes are now counted per inode rather than per name. uv's default link mode on Windows is hardlink, so an installed environment's files ARE links into the cache and unlinking the cache copy frees nothing; counting them anyway overstated both the row and the freed_bytes toast by the size of the installed packages. A multi-link inode counts only once the number of links seen inside the roots being measured reaches st_nlink, so anything linked from outside is left out. Understating beats promising space that unlinking will not return. And the download that used the space now reports it. requestStart reads the disk before a download, which is the right moment to refuse one, but a download that starts with room and then eats it crossed the threshold with nobody looking: there is no interval, so the warning waited for the next download attempt.
…e, an unguarded import The completion reading is forced. Unforced it was swallowed by the 30 second interval for any download shorter than that, and when the pre-start request was still in flight it was handed that request's answer, which is the figure measured before the download wrote anything and precisely the one it exists to correct. A forced caller now chains behind an in-flight request rather than sharing it, with at most one waiting, so a queue of files finishing together costs two readings. A partial purge reports only what it actually removed. rmtree can delete some children and then hit a permission error or a file that moved under it, and the whole subtree was already in the ledger, so freed_bytes claimed bytes still on disk. What survives is walked into a second ledger and subtracted. The curated dataset import holds the datasets registry across its fetch. Both loaders call load_dataset and snapshot_download directly, so it was neither a managed download nor a training run and claimed nothing: a Clear of hf_hub, hf_xet or hf_datasets passed every guard and could take the snapshot out from under the copy. claim_repository_owner is the same reservation a managed download takes and excludes a purge in both directions; it is released in a finally, and a clear already running answers 409 rather than racing it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 211d1ed3a0
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not granted: | ||
| if reason == "deleting": | ||
| raise HTTPException( | ||
| status_code = 409, | ||
| detail = "A cache clear is running. Try the import again in a moment.", | ||
| ) | ||
| _import_registry = None # already busy with this repo; do not release it |
There was a problem hiding this comment.
Refuse imports that fail to acquire the cache reservation
When a second import of the same curated repository runs under a different destination name, or a managed download already owns that repository, claim_repository_owner() returns repository_owned or an active job state and this branch continues with _import_registry = None. The competing owner may finish and release its reservation while this import is still materializing files, allowing a simultaneous hf_hub, hf_xet, or hf_datasets purge to delete the cache beneath the unreserved import. Fresh evidence in this revision is the non-deleting failure branch that explicitly proceeds without its own claim; wait for the claim or return a conflict instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The mechanism is real but the window is much smaller than the item describes, and the remedy costs more than it buys.
While the competing owner is held, a purge cannot begin at all: begin_cache_purge refuses whenever _repository_owners is non-empty. Checked against the code at head:
second import's claim -> (False, 'repository_owned')
can a purge begin? -> False
after that owner releases, purge -> True
So the exposure is not 'the import runs unreserved and a purge can delete its inputs', it is the gap after the other owner releases and before this import finishes. Refusing or retrying instead would turn every concurrent import of the same repository into a user-visible failure for a race that is already excluded for the whole life of the competing claim, which is the common case and the one a user actually hits. The 'deleting' reason is still refused, because that one names a clear that has already started.
| if not granted: | ||
| if reason == "deleting": | ||
| raise HTTPException( | ||
| status_code = 409, | ||
| detail = "A cache clear is running. Try the import again in a moment.", | ||
| ) | ||
| _import_registry = None # already busy with this repo; do not release it |
There was a problem hiding this comment.
Refuse imports that fail to acquire the cache reservation
When two concurrent curated imports target the same repository under different destination names, the folder-specific import lock allows both, but the second receives repository_owned here and continues without its own reservation. Once the first import finishes and releases its owner, begin_cache_purge() can succeed while the second is still running load_dataset() or copying from the snapshot, allowing a clear to delete its inputs. Fresh evidence after the earlier import-interlock fix is that every failed claim other than deleting is explicitly treated as safe to proceed; instead, refuse or retry the import unless it actually acquires the reservation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The mechanism is real but the window is much smaller than the item describes, and the remedy costs more than it buys.
While the competing owner is held, a purge cannot begin at all: begin_cache_purge refuses whenever _repository_owners is non-empty. Checked against the code at head:
second import's claim -> (False, 'repository_owned')
can a purge begin? -> False
after that owner releases, purge -> True
So the exposure is not 'the import runs unreserved and a purge can delete its inputs', it is the gap after the other owner releases and before this import finishes. Refusing or retrying instead would turn every concurrent import of the same repository into a user-visible failure for a race that is already excluded for the whole life of the competing claim, which is the common case and the one a user actually hits. The 'deleting' reason is still refused, because that one names a clear that has already started.
The last two commits left cache_inventory.py and test_cache_inventory.py in a shape ruff-format-with-kwargs rewrites, which fails pre-commit.ci and tests/test_formatter_fixed_point.py inside Repo tests (CPU). Both red checks on this branch are that one cause. Output of scripts/run_ruff_format.py with the pinned ruff 0.6.9; three collapsed line wraps, no behaviour change.
any_model_load_blocks_cache_clear consults llama.cpp, the inference orchestrator, Images and Video, but not the dictation sidecars, and those are the fifth backend reading out of the cache this clear empties: stt_sidecar._find_complete_cached_snapshot resolves through _repo_cache_dir into hub_cache, so a resident Whisper or Parakeet worker re-reading its snapshot is exactly the case the docstring says is enough on its own. stt_registry.resident() already reports both loaded and loading, so this is the same question the other four are asked, asked once more. Fail open on acquire like the rest: a sidecar that cannot be reached is not holding anything this process can see, and cache_inventory still fails closed on a guard that raises. Four tests. The two positive ones fail with this hunk reverted; the idle and unreachable controls are there so they cannot pass against a guard that has simply started refusing everything.
Three conflicts, all from main moving underneath this branch. settings-section.tsx and settings-dialog-store.ts are orthogonal: main added hideHeading and a chat-composer scroll target, this branch added the optional ref and resources-caches. Both sides kept. settings.py is the one worth stating. Main split the settings routes into account / shared / owner routers, and put both /hugging-face-cache routes behind _owner_settings_router. The cache inventory and purge are the same class of install-wide storage operation and the purge is the most destructive one there, so they move onto the owner router too rather than staying on the open router they were written against. A single-user install is unaffected, since require_owner only refuses an account that is not the owner; a managed account can no longer empty the install's caches, which is the intent of main's policy. The API-key axis is unchanged and still separate: a key may read the inventory, and refresh=true and the purge remain UI-session only. studio/backend tests/test_cache_inventory.py, test_api_cache_routes.py, test_system_disk_route.py and hub/tests: 802 passed on the merged tree.
This PR was doing two separable things. Measuring and clearing caches is one feature; warning that the disk is filling up is another, and the second does not import a line of the first. The only thing joining them was the deep-link string "resources-caches", which is navigation, not a dependency. So the notice goes to a follow-up, and with it everything that existed only to serve it: low-disk.ts, low-disk-check.ts, use-low-disk-notice.ts, the RootLayout mount, the two download-manager call sites, GET /api/system/disk and its AST/budget tests, the toast's frontend tests, and the lowDisk strings in all twelve locales. The deep-link machinery goes with it rather than staying here unused: the SettingsSection ref, the resources-caches scroll target, and the scroll effect in ResourcesTab. What is left is one coherent thing: show what the caches cost, and let them be cleared. 6214 insertions over 37 files becomes 5214 over 26. The follow-up is stacked on this branch, so the Storage section it links into already exists when it lands. studio/backend tests/test_cache_inventory.py, tests/test_api_cache_routes.py and hub/tests: 796 passed. i18n:check:strict: all twelve locale overlays pass parity. The frontend unit tests could not run in this workspace (no node_modules, so tests/helpers/module-stubs.ts cannot import typescript); they run on the staging legs.
|
Slimmed this down. It was doing two separable things, so the low-disk notice is now #11439, stacked on this branch. The split is lossless: checking out this branch and then #11439 on top reproduces the previous head
What moved, and why it could move: neither side imports a line of the other. The only thing joining them was the deep-link string
What is left here is one thing: show what the caches cost, and let them be cleared. On the length that prompted this, for anyone reading the diff: the remaining 5214 lines are 47% tests and 11% mechanical i18n across twelve locales. Also on this branch since the last review:
|
Two more backends that hold the hub cache without any of the guards seeing it, both the same shape as the dictation gap and both found by review. A chat load that has not spawned yet. is_active only covers a live llama-server process, and an HF-backed load does not have one until its GGUF finished downloading, which chat_load_active's own docstring calls minutes. Those files come down through hf_hub_download_with_xet_fallback rather than the download registry, so the reservation the purge takes later does not cover them either. chat_load_active() is exactly the marker for that window. A cancelled image load that is still unwinding. DiffusionBackend drops a cancelled load from loading_repo_ids() at once so the cancel is prompt, but its worker thread reads on inside _prefetch_files holding no lock, and those repos stay in draining_repo_ids(). _diffusion_blocks_delete already refuses on that; emptying the whole cache is every repository at once, so it cannot ask less than the per-repository path does. Asked through getattr, like the two checks beside it, so a backend without the method is simply not draining. Both fail open on acquire, like every other probe here. Two tests, both failing with their hunk reverted. studio/backend test_cache_inventory.py, test_api_cache_routes.py and hub/tests: 798 passed.
A managed-account install does not have one dataset registry, it has one per account: _account_registry() mints a fresh DownloadRegistry the first time each account downloads. The purge reserved only the singleton that get_datasets_registry() returns, which is the owner's, so an owner clearing hf_hub, hf_xet or hf_datasets could not see another account's live dataset download and would remove files under its worker. Reserving the registries that happen to exist at that moment is not enough either, because _account_registry() mints new ones on demand and one created after the purge started would be free to claim work immediately. So the reservation moves into the dataset service, in the same all-or-nothing shape begin_delete already uses there, and the count rides into a newly created registry exactly the way _deleting already does two lines above. cache_inventory now reserves through that service rather than the singleton; both answer begin_cache_purge and end_cache_purge, which is all _release_downloads asks. The two existing reservation tests move to the seam the code now uses. Their assertions are unchanged, since what they check, that a job in either registry holds the purge off, is still exactly the property. Two new tests cover what the old seam could not express, and both fail with the fix reverted: a purge is refused while another account's registry holds a download, and a registry created during a purge is born reserved. studio/backend test_cache_inventory.py, test_api_cache_routes.py and hub/tests: 800 passed.
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Post-convergence pass. The five longest blocks collapse to two lines each, keeping every fact and dropping the retelling around it. It stays at about 24 percent comment lines, and that is deliberate rather than a pass that gave up. This file is a gate in front of rmtree: most of what is left names either a platform convention that is not guessable from the code (matplotlib's directory off Linux, CUDA's roaming AppData, torch deriving its inductor path from getpass.getuser) or the reason a refusal exists at all. The keep test asks what mistake the next reader makes if a comment goes, and for these it is deleting the wrong directory, so they stay and cost a line each. comment_tools.py check: code unchanged. studio/backend test_cache_inventory.py, test_api_cache_routes.py and hub/tests: 800 passed.

Unsloth's caches are what make an update or a second run fast, so they are worth keeping and worth being able to see. On a working box they are also the largest thing on disk that is safe to delete: uv's wheel cache alone reaches tens of gigabytes. Nothing in Studio said so, or offered to reclaim it.
What this adds
Settings > Resources > Storage now lists every cache with its size and a total, and can empty them.
_cacacheand the_npxtrees Studio fills launching MCP servers), bunEach root is the one the tool itself uses rather than the platform convention, which the two disagree about more often than they agree: matplotlib is
~/.matplotliboff Linux and that directory isget_configdir()too, CUDA is roaming%APPDATA%on Windows, vLLM is~/.cache/vllmeverywhere, torch derives its inductor directory fromgetpass.getuser()and repeats the app name in its extensions path on Windows, numba has a user-wide fallback when__pycache__is not writable, and pip and npm both take theirs from a config file no environment variable carries, so those two are asked directly and the answer is kept for the process. uv gets two rows' worth of roots when the installer recorded a different cache from the one this backend runs with.Sizes are memoised for 60 seconds with a Recheck button, and one walk runs per cache at a time. A cold walk over a large uv cache and a triton cache holding tens of thousands of files takes tens of seconds, so it is not something to do on every render, or twice because two tabs are open.
The low-disk toast that offers these caches when the disk fills up was split out into #11439, so this change is one thing: show what the caches cost, and let them be cleared.
Only caches are ever deleted
This is the part worth reviewing closely.
The API takes a cache key, never a path, so a caller cannot name a directory to delete. Every root is computed in the backend from the same resolvers the rest of Studio uses. Each root then has to pass a gate before anything is unlinked:
studio.db, auth, projects, models, datasets, outputs, exports, rag, runs, the Studiobindirectory, the temp workspace, Documents, the Hugging Face cache home that holds the token, a configuredHF_TOKEN_PATH, or a managed asset home such asDATA_DESIGNER_HOMEMPLCONFIGDIR, since that keepsmatplotlibrcbeside the font listThe root is emptied, never removed. A symlink inside it is unlinked rather than followed, a directory whose real path leaves the root is skipped, and a Windows junction is neither descended into nor sized. A root the gate refuses is not walked either: measuring it would be an unbounded walk for bytes nothing can reclaim.
Three caches are opt-in and are never swept up by the bulk clear. The Hugging Face hub and dataset caches cost a re-download of something the user asked for. The unsloth compiled cache is excluded for a different reason: a training or inference worker imports generated modules from it lazily, long after the job started, and the existing
compiled_cache_lockonly serialises against a sibling backend, not against a spawned worker. Clearing it under a running job would forfeit hours of compute, which is not a trade to make from a button labelled "free up space".Three more things a clear will not do. It holds the download registries that write into the cache it is about, the way the per-repository deletes call
begin_delete, so a worker cannot claim a repository between the check and thermtree; the hub and xet roots hold both registries, since a dataset download writesdatasets--entries into the same hub tree and every claim of either kind carries the xet cache it fetches chunks to, and a whole-cache purge and a per-repository delete now exclude each other in both directions. It refuses the Hugging Face caches outright while either trainer is running, for the reason the compiled cache is opt-in: a spawned trainer callssnapshot_downloadandfrom_pretraineditself, outside every registry here, and a run is hours nobody gets back. And a purge root is only ever resolved from a stable location: never the cache-home history, which an API key can append to through an endpoint the purge route itself refuses, and never a scoped override that another operation is holding, such as theHF_DATASETS_CACHEa fallback dataset load points at itself for the length of that load, or theTORCHINDUCTOR_CACHE_DIRthe diffusion cache repoints while a model is resident.GET /api/settings/cachesis readable with an API key;?refresh=trueand the purge are UI sessions only.Testing
test_cache_inventory.pyandtest_api_cache_routes.py. Run with the Hugging Face cache, storage-root and sandbox suites: 655 passed, 0 failed.studio/backend/hub/testspasses too, 683, since the purge reservation is in the download registry. The whole ofstudio/backend/testswas run against this branch as well, with the same failures and errors it has on the merge base and none of them in a file this touches.settings-cache-purge.test.tsandcache-rows-model-folder.test.ts.typecheckclean,i18n:check:strictparity clean across all twelve locales.bindirectory and the temp workspace,HF_TOKEN_PATH, the symlinked and junctioned root refusals, the nested-junction walk, the shallow-root depth rule, the unlink-never-follow rule, unknown-key rejection, the opt-in and pattern-limited exclusions from a bulk clear, gating the walk behind the refusal for the ordinary caches and for the compiled one, the download-registry reservation in both registries and against a per-repository delete, the refusal under either trainer, the resolver for every cache whose default is not the platform one, the scoped-override refusals for datasets and diffusion, the measurement generation guards on both sides including a forced recheck refusing a walk that began before it.Hostile inputs checked by hand as well:
/,~,../../etc,/home,.., the empty string anduv/../../..are all refused as unknown keys before any path is resolved, and a cache containing a symlink tostudio.dbpurges the link while leaving the database intact.Before and after
Two isolated installs, one Playwright scene driven identically against both. BEFORE is this PR's merge base
0054a64be, AFTER is4a8ec9d75, same host, adjacent ports.System disk and Models folder are the control: identical on both halves, down to the path and the "Managed by the HF_HUB_CACHE environment variable" line. The Cache files row is the only thing that moved.
Numbers read from the same server that was photographed, not off the picture:
GET /api/settings/cachesThe 81.6 GB between the total and the reclaimable figure is the three opt-in caches (
hf_hub,hf_datasets,unsloth_compiled), which a bulk clear never touches. That arithmetic is the check worth doing on this screenshot.The scene never presses "Clear caches" or a per-row "Clear". The sizes are this build box's real caches, read only, and nothing was deleted to make the image. The 470 GB is a long-lived shared CI machine, not a typical install.
A first run of this scene produced a pair whose BEFORE half read "0.00 GB used / 0.00 GB" with the Models folder still on "Loading...", because the section was photographed before it finished rendering. The cache row was correct in that image and it still proved nothing, since the two control rows did not match. The scene now refuses to shoot until both have resolved on both sides.