Skip to content

Studio: make image-model companion assets reusable, visible, and safely removable - #8223

Merged
danielhanchen merged 42 commits into
mainfrom
i8116
Aug 10, 2026
Merged

danielhanchen merged 42 commits into
mainfrom
i8116

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Closes #8116.

What was actually true

I built the reporter's exact case in a scratch cache: unsloth/FLUX.2-klein-4B-GGUF at Q2_K and Q4_K_M, plus the companion base black-forest-labs/FLUX.2-klein-4B. Real bytes, measured on disk:

8,229,026,136  models--black-forest-labs--FLUX.2-klein-4B     (text encoder, VAE, tokenizer, configs)
4,432,118,952  models--unsloth--FLUX.2-klein-4B-GGUF          (Q2_K 1.8 GB + Q4_K_M 2.6 GB)

Four claims, checked one at a time.

Reuse already works. Both quants live in one GGUF repo, and detect_family_for_pick + resolve_base_repo resolve both to the same base id, so the cache holds exactly one companion copy. The mirror indirection does not split it either: _run_load takes one prefer_ungated_mirror decision with the staged file list in hand and threads it through as _fetch_base, so plan and load cannot disagree. The one latent inconsistency is that the fallback at diffusion.py:2071 re-decides without files, and a partially cached upstream makes the two answers differ:

partially cached black-forest-labs/FLUX.1-dev
  prefer_ungated_mirror(base, files=[...])  ->  unsloth/FLUX.1-dev
  prefer_ungated_mirror(base)               ->  black-forest-labs/FLUX.1-dev

That path is only reachable from a direct load_pipeline call, not from the product, so it is not a shipped duplicate. Nothing in this PR changes it, but the guards below treat both identities as one repo so a cache holding both behaves sanely.

Delete never touched companions, and reported nothing. _delete_cached_model_blocking is scoped to one repo id in one cache root. The response is {"status": "deleted", ...}, with no size, and the dialog said only "You can re-download it later". Deleting the last quant left 8.2 GB stranded, 65% of the footprint, with no way back short of hand-editing the Hugging Face cache.

Nothing knew an asset was shared. _snapshot_blob_reference_counts counts symlinks to a blob within one repo. There was no notion of one repo needing another. So this succeeded, with both quants installed:

DELETE OF SHARED BASE -> {'status': 'deleted', 'repo_id': 'black-forest-labs/FLUX.2-klein-4B'}
after: 4,432,118,952  models--unsloth--FLUX.2-klein-4B-GGUF     (both quants now unloadable)

That is the sharp edge in the issue, and it was reachable from the picker in two clicks.

What this changes

Derived, not counted. hub/utils/companion_assets.py answers "what still needs this base" from the cache scan at call time, using the same resolvers the loader uses to pick a base. If family detection fails for a cached repo the loader cannot load it either, so there is no dependant to protect: the derivation and the thing it protects fail together.

The one input a later offline scan cannot reconstruct is a card base_model tag, because a GGUF pick caches only the .gguf, never the card. record_companion_link closes that from inside _resolve_base_repo, where the choice is made. It is a link, not a count: an entry can only ever add a dependant, it is filtered by "is that checkpoint still installed", and losing it degrades to the family default rather than to a wrong answer.

The two directions are guarded by two different sets, deliberately. is_companion_base gates a refusal, so it is wide and admits any base a link names. known_companion_base_ids gates an offer to delete, so it is table-only and a bad link can never reach it.

The dialog says what happens. POST /api/hub/delete-impact returns reclaimed bytes, retained companions with who holds them, and companions this delete orphans. Sizes are real on-disk blob bytes from the cache scan, deduped per blob, not Hub metadata.

This will remove unsloth/FLUX.2-klein-4B-GGUF (Q2_K) from disk. You can re-download it later.
Frees 1.8 GB of disk space.
8.2 GB of shared assets stay on disk: black-forest-labs/FLUX.2-klein-4B is still needed by unsloth/FLUX.2-klein-4B-GGUF.
This will remove unsloth/FLUX.2-klein-4B-GGUF (Q4_K_M) from disk. You can re-download it later.
Frees 2.6 GB of disk space.
This also leaves 8.2 GB of shared assets (black-forest-labs/FLUX.2-klein-4B) that nothing else
needs. Remove them with Free up space on the On Device tab.

A shared base cannot be deleted out from under an installed model. The same delete now returns 400 and the dialog's Delete button is disabled:

These are shared assets that unsloth/FLUX.2-klein-4B-GGUF still needs, so they cannot be
removed yet. Delete those models first.

The check runs inside the destructive stage, fails closed on an unreadable cache, and only for a repo the table already identified as a companion base, so every other delete is untouched.

Free up space. A button on the On Device toolbar lists companion bases no installed model needs, with sizes, every row opt-in, removal through the ordinary guarded delete. Nothing runs automatically: this deletes user data, so it stays a deliberate act. A base that also holds a denoiser is never offered, because a companion fetch skips the denoiser folder and a pipeline pick takes it, which is the derived answer to "did the user ask for this repo, or did a GGUF drag it in".

Scope

Image families only. known_companion_base_ids is built from the image family table, so no video repo is ever offered for cleanup and no video delete changes behaviour. The chat GGUF path has no separate companion repo at all, since mmproj and drafters live in the same repo and _delete_gguf_variant_from_repos already reclaims them with the last variant.

Verification

Driven in a real browser against a Studio serving the built frontend, with an isolated HF_HOME, on the cache above. The byte counts at each step:

start                             12,661,145,088
after deleting Q2_K               10,833,337,280
delete the shared base            refused, Delete disabled
after deleting Q4_K_M              8,229,026,176   (companions stranded)
after Free up space                            40
  • 20 new backend tests, including the adversarial one, which fails on main because the delete succeeds there.
  • Mutation run: 15 mutations against the shipped source, all 15 killed, suite green after restoring. The list covers the guard never firing, the guard failing open, dropped card-tag links, collapsed mirror identities, wrong reclaimed bytes, a surviving sibling read as freeable, unrecognised repos offered for cleanup, a pipeline install read as a leftover, unserialised link writes, pooled multi-cache rows, and the self-reference drop.
  • hub/tests: 304 passed before, 324 after.
  • Full studio/backend/tests: 71 failed + 18 errors on the merge base, and the identical 89 FAILED/ERROR lines after. No changed set.
  • npm run typecheck, npm test (1316 passed), npm run build: clean.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 794848a57b

ℹ️ 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".

Comment on lines +300 to +309
export async function fetchDeleteImpact(
repoId: string,
variant?: string | null,
): Promise<DeleteImpact | null> {
try {
const response = await authFetch("/api/hub/delete-impact", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(
variant ? { repo_id: repoId, variant } : { repo_id: repoId },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope delete previews to the selected cache

When the same repository exists in multiple remembered cache roots, the actual delete is scoped by cache_path, but this preview request sends only the repository and variant. _delete_impact_blocking() consequently sums every cached copy and ignores the repository ID globally when calculating remaining dependents, so deleting one row can be reported as reclaiming all copies and making its companions freeable even though another copy remains installed. Pass the row's cache_path through this API and restrict both size and dependency calculations to the delete target.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting. Nothing unsafe follows from it: the delete itself is already scoped by cache_path, the orphan listing recomputes what is required across every cache root, and the companion delete guard refuses on the same global view, so a surviving copy in another root still protects its companions. What is wrong is the preview's arithmetic for a user who has the same repo in two remembered cache roots, which is an uncommon configuration and a number on a confirmation dialog rather than an action. Scoping it properly means threading cache_path through the endpoint and then deciding what removes_last_checkpoint and required_after even mean per root, which is a larger change than the inaccuracy justifies here.

danielhanchen and others added 4 commits August 9, 2026 12:04
# Conflicts:
#	studio/backend/core/inference/sd_cpp_backend.py
…honest

- The native engine never reads the diffusers base: FLUX.2 takes its VAE and encoders from
  separate repos that _asset_specs names. Recording only the base left every repo the pick
  actually fetches outside the dependency guard, so an unloaded model's encoder could be deleted
  while its GGUF stayed installed. Each asset repo is recorded now.
- The link file was written with sort_keys, so the next read came back alphabetical and the
  512-entry trim evicted the lexicographically smallest link rather than the oldest. Document
  order is the recency record, so it is no longer sorted away, and re-recording a checkpoint
  moves it to the newest end.
- The delete preview offered link-only bases under freeable_companions and told the user to
  remove them with Free up space, which is table-only by design and never lists them. Those
  bases are no longer advertised as freeable; they stay protected, which is the half the guard
  owns.
- Free up space returns one row per cache root, so selection, React keys and checkbox ids are
  keyed on the repo AND its cache path; one checkbox no longer toggles both copies.
- The local card's Delete stays enabled while the preview says the assets are blocked, which
  only bought the user a 400. Same gate the model row menu already applies.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Screenshot evidence for this PR, from two Studio installs: one built at the merge base f0ef75ec91e2021f9937b8ebfa1aead05a702d0c, one at the head aacfb9c0f1005b17241511cb1e51f12520d8878f. Both were pointed at the same isolated cache and driven through the same clicks. No delete was ever confirmed, so the two sides read an identical, unmutated disk.

Cache under test, real blob bytes on disk:

 4,432,118,912  unsloth/FLUX.2-klein-4B-GGUF       Q2_K 1,827,807,808 + Q4_K_M 2,604,311,104
 8,229,021,460  black-forest-labs/FLUX.2-klein-4B  text encoders, VAE, tokenizer, configs
12,661,140,372  total

The base repo was fetched with the same filter a companion fetch uses (no transformer/, no assets/, only model_index.json at top level), so what is on disk is what a GGUF pick would leave behind.

1. Deleting the GGUF checkpoint now says what it reclaims and what it strands

delete the GGUF checkpoint

POST /api/hub/delete-impact {"repo_id": "unsloth/FLUX.2-klein-4B-GGUF"} on the head:

{"reclaimed_bytes": 4432118912,
 "retained_companions": [],
 "freeable_companions": [{"repo_id": "black-forest-labs/FLUX.2-klein-4B",
                          "size_bytes": 8229021460, "needed_by": []}],
 "blocked_by": []}

The delete the old dialog described only as "removes it from disk" gives back 4.4 GB of the 12.7 GB installed and leaves the other 8.2 GB, 65 percent of the footprint, with nothing on screen that knew it was there. The endpoint does not exist on the merge base (405 for delete-impact, 404 for orphan-companions).

2. A shared base can no longer be deleted out from under an installed quant

deleting the shared base is refused

POST /api/hub/delete-impact {"repo_id": "black-forest-labs/FLUX.2-klein-4B"} on the head:

{"reclaimed_bytes": 8229021460,
 "retained_companions": [], "freeable_companions": [],
 "blocked_by": ["unsloth/FLUX.2-klein-4B-GGUF"]}

Delete is disabled and the reason names the holder. On the merge base the wording is identical and the button is live, which is the sharp edge in #8116: the delete succeeds, 4.4 GB of quants stay on disk, and neither of them can load again.

3. On Device toolbar

Free up space on the On Device toolbar

On this cache GET /api/hub/orphan-companions answers {"companions": [], "total_bytes": 0}, which is the right answer while the GGUF repo is installed: the base is still held, so nothing is offered for removal until the last quant goes. The list is what picks up the 8.2 GB that case 1 points at.

Dialog sizes are decimal, so 4,432,118,912 renders as 4.4 GB and 8,229,021,460 as 8.2 GB.

danielhanchen and others added 2 commits August 9, 2026 13:13
…on disk

- begin_load resolves the FLUX.2 header offline, so a remote or renamed klein 9B checkpoint with
  no cached probe recorded the default 4B encoder while the worker fetched the 9B one. The worker
  already recomputes the specs after the network probe and publishes asset_repos there; the links
  are recorded from that same authoritative set now, on the fetch ids as well as the upstream
  ones.
- A repeat resolution returned early and skipped the recency refresh, so a checkpoint reloaded
  daily but first recorded long ago could still be trimmed by the 512-link cap, which for a
  card-tag-only base is the delete guard going quiet on it.
- prefer_cached_legacy_source sends the native fetch back to a community repack an upgraded
  install already holds, so on those machines the bytes protecting an installed GGUF sit under
  the old repo key. The identity expansion covers the repack now, and is_companion_base runs the
  same expansion so the refusal protects whichever copy is on disk.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 77e672eaf2

ℹ️ 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".

key = _normalise(repo_id)
if key in ignored:
continue
bases = _family_bases(repo_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip complete pipelines when deriving dependents

Because _cached_model_repo_ids() returns every cached model repo, this line also infers companion dependencies for complete diffusers pipelines. For example, a cached black-forest-labs/FLUX.1-dev pipeline already contains its own components but matches the flux.1 family, so _family_bases() marks black-forest-labs/FLUX.1-schnell as required by it; that makes the delete guard and Free up space retain/block a stranded schnell base until the unrelated dev pipeline is removed. Restrict family-default derivation to repos that actually omit companions, or rely on recorded links for non-GGUF pipeline variants.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting. The failure direction here is over-protection: a base is retained and refused, never removed underneath something that needs it. That is the side this guard is built to fail on, and the remedy proposed cuts the other way. 'Restrict family-default derivation to repos that omit companions' would decide from what a repo currently HOLDS, and a partially fetched pipeline holds nothing yet while still being a dependent, so the guard would go quiet exactly while a download is in flight. Trading a stranded base nobody can reclaim for a base that can be deleted mid-fetch is a bad trade in a cleanup feature.

# Returns the UPSTREAM id; the swap happens at the fetch sites only.
return resolve_base_repo(fam, base)
resolved = resolve_base_repo(fam, base)
_remember_companion_base(repo_id, resolved)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Record links after the base passes preflight

Writing the link inside _resolve_base_repo() means callers such as preflight_base_access() persist it before _assert_base_repo_accessible() and assert_flux2_pick_compatible() run. If a downloaded GGUF is tried with an incompatible trusted card-tag or explicit base, preflight rejects the load but the link remains; later is_companion_base()/companion_dependents() treat that unrelated cached base as required and block its deletion until the checkpoint or state file is removed. Move recording after the validations that prove this base can actually serve the pick, or roll it back on failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting. Recording at resolution is deliberate: the guard has to hold from the moment a base is CHOSEN, because the very next thing that happens is a multi-gigabyte fetch into that repo, and a load that dies partway still leaves those bytes on disk with nothing else naming them. Moving the write behind the validations opens exactly that window. A link left by a rejected preflight is over-protection, which refuses a delete rather than losing anything, and it only bites while both the checkpoint and that base are cached.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 77e672eaf2

ℹ️ 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".

Comment on lines +135 to +139
if (
"/" not in checkpoint.replace("\\", "/").strip("/")
or Path(checkpoint).expanduser().exists()
):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Protect companions used by local GGUF checkpoints

When checkpoint_repo_id is a local path—an explicitly supported input for both diffusion backends—this return prevents its dependency from being recorded, while required_companion_bases() only discovers checkpoints in Hugging Face cache scans. The local GGUF can still fetch its VAE/encoders into the HF cache, but after it is unloaded those assets have no recorded dependent, so Free up space can offer and delete them even though the local checkpoint remains installed and will no longer load. Track existing local checkpoints as dependents rather than dropping them here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting. The whole guard is derived from the Hugging Face cache inventory, and a local path is outside it by construction, which is why the recorder drops one. Admitting paths means persisting absolute filesystem paths in shared state, and a path that is moved, renamed or on an unplugged drive then blocks a delete forever with no way for the user to see why. That is a worse failure than the one it closes, and closing it properly means giving the inventory a notion of local checkpoints, which is a change of its own rather than a line in the recorder.

Comment on lines +92 to +94
return _is_main_gguf_filename(name) and extract_quant_label(name).lower() == target

return _repo_blob_bytes(repo_info, only = _matches)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include last-variant companion blobs in reclaimed bytes

When deleting the last quant from a GGUF repo containing an mmproj or reclaimable MTP/DSpark drafter, _delete_gguf_variant_from_repos() also unlinks those companion blobs once no main GGUF remains, but this preview counts only files accepted by _is_main_gguf_filename. The new confirmation therefore understates the actual reclaimed space—potentially by gigabytes—for multimodal and speculative-decoding models. Apply the same last-variant companion predicate used by the destructive path when calculating reclaimed_bytes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting. reclaimed_bytes errs LOW, so the delete frees at least what the dialog promised, and a preview that under-promises is the safe direction for a confirmation. It is also the same call I made on the cache-scoping comment earlier in this PR: preview arithmetic that no action depends on is not worth reaching further into the destructive path to mirror, and duplicating that last-variant predicate here is a second copy of a rule that then has to stay in step with the deleter forever.

Comment on lines +135 to +139
if (
"/" not in checkpoint.replace("\\", "/").strip("/")
or Path(checkpoint).expanduser().exists()
):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Protect companions used by local GGUF checkpoints

When checkpoint_repo_id is a local path—an explicitly supported input for both diffusion backends—this return prevents its dependency from being recorded, while required_companion_bases() only discovers checkpoints in Hugging Face cache scans. The local GGUF can still fetch its VAE/encoders into the HF cache, but after it is unloaded those assets have no recorded dependent, so Free up space can offer and delete them even though the local checkpoint remains installed and will no longer load. Track local checkpoint existence/inventory rather than drop.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same item as the other local-path comment; rejecting for the same reason. The dependency view is built from the Hugging Face cache inventory, and persisting absolute filesystem paths in shared state to reach outside it trades a visible gap for a delete that can be blocked forever by a path that has since moved.

Comment on lines +128 to +130
scans = cache_scans if cache_scans is not None else cache_inventory.all_hf_cache_scans()
required = companion_assets.required_companion_bases(scans, ignore_repo_ids = ignore_repo_ids)
return sorted(required.get((base_repo_id or "").strip().lower(), set()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fail closed when any cache-root scan is omitted

all_hf_cache_scans() does not propagate every scan failure: _compute_all_hf_cache_scans() catches exceptions per cache root, logs them, and returns the remaining roots. Consequently this dependency check can receive a seemingly valid but incomplete list, omit a checkpoint in the failed root, and allow a companion base in another root to be listed or deleted despite still being required. Preserve scan-failure metadata and refuse companion cleanup whenever the global cache view is incomplete.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting as written, though the observation about all_hf_cache_scans is right. Refusing companion cleanup whenever any root fails would take the feature away on a machine with a stale remembered root that no longer exists, which is a common state and precisely when a user is trying to free space. A partial view also degrades the same way everywhere else that reads it, including the plain delete path, so fail-closed here alone would be inconsistent rather than safe. If scan-failure metadata is worth surfacing it is worth surfacing to everything that consumes the inventory, which is a change to cache_inventory rather than to this endpoint, and not one this PR should make.

danielhanchen and others added 2 commits August 9, 2026 14:52
…ding

- For an sd.cpp pick the single-file VAE and text encoder ARE the companions, and the largest
  half of the footprint, but their curated table was not in the offerable set, so they were
  dropped from the delete preview and never listed by Free up space. They are curated entries,
  not link-derived, so admitting them keeps the safety rule intact, and the chat models that
  table also holds stay out because the listing skips any repo carrying a GGUF.
- Both loaders detect a family from the cached FILENAME as well as the repo id, so a runnable
  repo whose name says nothing had no dependency at all. On an upgraded install, where no links
  have been recorded yet, that probe is the whole guard.
- The denoiser test pooled every cache copy, so a full pipeline copy in one root suppressed an
  orphaned companion-only copy in another that nothing else can reclaim. A delete is scoped to
  one root, which is why the listing emits one row per root, so the test belongs there too.
- Free up space pre-checked every row, which let one click delete every listed copy without the
  user opting into any of them. Its own contract is per-row opt-in.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 9, 2026 15:15
- The derived fallback named only the diffusers base, but the native engine never reads it: it
  fetches a single-file VAE and text encoder from their own repos, which are now offerable for
  deletion. A pre-existing native GGUF with no recorded link therefore had its encoder listed as
  an unused asset. The fallback derives those component repos from the family too, using the same
  id-plus-filename resolution the delete guard uses to reconstruct a committed load.
- A variant delete normally cannot touch another repo, which is why the companion guard was a
  whole-repo check. The native Qwen-Image encoder is one quant inside a chat GGUF repo, so
  removing the last main GGUF from a companion base takes the encoder just as surely as deleting
  the repo, and the guard now runs there. Fails closed on an unreadable cache.
- The pick probe kept the first cache root's names and skipped later copies of the same repo id,
  so a family only the second copy named lost its base. Names are accumulated and deduplicated
  across roots.
- It also kept only .gguf names, while the loader hands a top-level single-file .safetensors to
  detect_family_for_pick the same way. A cached FLUX.2-dev-fp8.safetensors pick therefore had no
  derivable family and its base was reclaimable.
- The component-only exclusion listed the current unsloth ids only, so a legacy repack an upgraded
  install still holds (Comfy-Org/flux2-dev) was read as an installed checkpoint and kept its
  sibling VAE pinned. Expanded through the same mirror identities the rest of the file uses.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0184232777

ℹ️ 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".

logger.debug("Companion base derivation unavailable for %s: %s", repo_id, exc)
return set()
try:
fam = detect_family_for_pick(repo_id, gguf_filename)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve family overrides when deriving dependencies

For cached checkpoints whose repo ID and filename do not identify a family, this call returns None even though both diffusion loaders accept the checkpoint with family_override. On an upgraded installation—where the newly introduced link-state file has never recorded the load—or after that state is lost, a generic pick such as some-owner/custom:model-Q4_K_M.gguf loaded with family_override="qwen-image" contributes no dependency, so its cached Qwen companion base is offered by Free up space and can be deleted while the supported checkpoint remains installed. Persist and consult the selected override (or otherwise fail closed for runnable but unclassifiable checkpoint files) when deriving dependencies.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one, and the premise is narrower than it reads. A family_override load goes through _resolve_base_repo like any other, and that calls _remember_companion_base -> record_companion_link with the base it resolved. So an override pick is recorded and protected from its first load on this build, and the recorded base is strictly better than a recorded override string, which would still have to be re-resolved.

What is left is an override install made before this PR existed and never loaded since. There is no on-disk trace of an override to reconstruct: it lives in the load request, not in the cache. family_override is also API-only, no UI sets it.

The proposed alternative, failing closed for runnable but unclassifiable checkpoint files, is the part I am rejecting outright. Any cached GGUF whose family does not resolve would then hold every curated base on disk, and a chat GGUF is exactly such a file. On a normal install that suppresses the entire Free up space list, which is the feature this PR is adding.

…es a row

The list the dialog acts on can be minutes old, and a download of the same repo finishing in
the background turns an orphaned companion into an installed checkpoint. Neither existing guard
catches that: begin_delete only refuses a download still in flight, and the companion guard
deliberately ignores the target repo as its own dependent. Remove would then delete the model
that had just finished downloading.

delete-cached takes only_if_orphan, which Free up space sends. The check runs inside the
destructive stage, after begin_delete has closed the repo to new downloads, so it cannot go
stale between the check and the unlink, and it answers 409 with the reason rather than deleting.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… files, bound each checkpoint's bases

- The recheck looked at every copy of the repo id, but the delete is scoped to one cache root and
  the listing emits one row per root for exactly that reason. A full-pipeline copy in another
  remembered cache made the listed companion-only row 409 forever. Filtered to the copy the
  cache_path names.
- repo_holds_denoiser accepted a top-level weight only for whole-pipeline families, so a
  transformer-only single_file checkpoint installed into its own curated base repo was read as
  companion-only, listed as orphaned, and deletable through the same precondition. Any top-level
  weight with a detected family now counts, except in the curated component repos, whose root
  asset IS the companion.
- _MAX_LINKS bounds checkpoints, not the bases recorded against one. A checkpoint resolved
  against a new explicit base each load grew the state file on its own, and every dependency
  check parses and mirror-expands the whole list. Capped per checkpoint, by recency.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d336faaa03

ℹ️ 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".

Comment on lines +845 to +846
copies = companion_cleanup._repos_by_id(cache_inventory.all_hf_cache_scans()).get(
repo_id.strip().lower(), []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Serialize cleanup against new dependent downloads

When a checkpoint from another repository starts downloading while Free up space removes this companion, begin_delete() reserves only the companion repo, so this scan and the later dependent check can both finish before the new checkpoint becomes visible. That different-repo download may then complete before the unlink, leaving an installed checkpoint without the shared assets it needs (and a concurrent load may lose files underneath it). Coordinate companion deletion with dependency-changing downloads/load starts rather than relying on this point-in-time recheck.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one.

The window is real but it is a millisecond-scale interleaving: a download of a DIFFERENT repo that needs this exact base has to start after _companion_share_blocks_delete has run and complete before the unlink, both inside one blocking delete. The dependent check already sits inside the destructive stage, immediately before the delete loop, so there is no larger gap to close by moving it.

The consequence is also not what the guard is for. Nothing the user installed is lost: the companion assets are fetched by the load path, so the newly downloaded checkpoint re-fetches the base on its first load. The bug this PR exists to fix is the opposite case, an ALREADY installed checkpoint silently losing the 8 GB it loads through, and that one is guarded from what the cache holds at the moment of the delete.

The remedy asked for, coordinating deletion with every dependency-changing download and load start, is a cross-subsystem lock spanning the download registry, the loaders and the cache. That is an architectural change with its own deadlock surface, and it is not something to land inside this PR.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 468088f478

ℹ️ 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".

Comment on lines +858 to +859
if scoped:
copies = scoped

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refuse orphan deletes when the target copy is absent from the scan

When an explicit cache_path targets a root that the current cache scan omitted—for example, because that root's scan failed—scoped is empty, so this code retains unrelated copies (or an empty list) and concludes that the target is still orphaned. The later no-entry deletion path can nevertheless call purge_repo_cache_dirs on that target root, deleting the actual directory even if it now contains a downloaded checkpoint. Fresh evidence beyond the earlier global-scan concern is this target-specific fail-open fallback: require the scoped copy to be present or inspect/refuse only that target when it cannot be scanned.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and it is my own fallback from d57c276. if scoped: copies = scoped meant an empty match silently reverted to the copies in other roots, and an empty match is exactly the case that matters: the target root is not in this scan, while the delete below can still purge that directory by path.

Fixed in 25199cf: no fallback. An empty scoped match raises, which lands in the same fail-closed 503 the rest of the recheck uses. Regression test: test_the_orphan_precondition_refuses_when_the_target_root_is_not_in_the_scan.

Comment on lines +84 to +85
def _matches(name: str) -> bool:
return _is_main_gguf_filename(name) and extract_quant_label(name).lower() == target

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use deletion's variant keys in the preview

For supported path-qualified or unknown variants such as distilled/ltx-2.3-22b-distilled-Q6_K and weights/model, the inventory and destructive path identify the row with gguf_variant_key, but this preview compares that requested key with extract_quant_label(name). The file therefore does not match and the dialog reports 0 B reclaimed; _remaining_main_gguf_variants makes the same comparison, so deleting the sole such checkpoint is also incorrectly described as retaining rather than orphaning its companions. Resolve variants with the same key and alias logic used by _variant_keys_to_delete.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. gguf_variant_key("distilled/ltx-2.3-22b-distilled-Q6_K.gguf") is the path-qualified key while extract_quant_label gives Q6_K, so the preview matched nothing: 0 B reclaimed, and _remaining_main_gguf_variants read the same repo as still holding a sibling, which described the companions as retained rather than freed.

Fixed in 25199cf: both the size and the remaining-variant scan resolve through the destructive path's own _variant_keys_to_delete, so the preview, the inventory and the delete agree on what a row is called, including the unambiguous bare-quant alias. Regression test: test_the_preview_reads_a_path_qualified_variant.

…nts by their key

- The scoped orphan recheck fell back to the other copies when nothing matched cache_path. An
  empty match means that root was not in the scan, and the delete can still purge the directory
  by path, so the fallback concluded orphan from copies it never looked at. It now fails closed
  with the same 503 the rest of the recheck uses.
- The delete preview matched files by quant label while the inventory and the destructive path
  identify a row by gguf_variant_key. A path-qualified checkpoint such as
  distilled/ltx-2.3-22b-distilled-Q6_K matched nothing: 0 B reclaimed, and the last checkpoint in
  a repo read as if a sibling survived, so its companions were described as retained rather than
  freed. Both the size and the remaining-variant scan now use the destructive path's own
  _variant_keys_to_delete.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: c49f52f8fd

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 90cd82b into main Aug 10, 2026
47 checks passed
@danielhanchen
danielhanchen deleted the i8116 branch August 10, 2026 08:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Clarify reuse and deletion of image-model companion assets

1 participant