Skip to content

Removal

modelmap.removal

Removing a record: what would go, and doing it once confirmed.

Nothing leaves the disk that the plan did not list. A plan is one of:

  • tool: the store's own tool removes the record. In Ollama and the Hugging Face cache the model is the unit of deletion, and deleting a blob by hand leaves manifests or links pointing at nothing. The syntax was read from ollama rm --help (Ollama 0.40) and hf cache rm --help (hf 2.4.0), and the hf forms were run with --dry-run on a real cache.
  • trash: the record's files, or its folder, move to the Trash. A folder moves whole only when every entry in it is one of the record's files; otherwise the listed files move one by one and the rest stays.
  • refuse: nothing is done, and the note says why.

Paths to move are built from the record's folder and each file's label, never from a resolved path: a file reached through a symlink must not take the other store's file with it. A record whose files are used by another record is refused for the same reason.

ollama rm has no store argument; it acts on the running Ollama. It is offered only for records in the Ollama provider's own store, only when OLLAMA_HOST names this machine, and only when the running Ollama lists every tag with the ID of the manifest in the scanned store: an Ollama using another models folder could share tag names and remove its own copy. Afterward the removal counts only if Ollama no longer lists the tags and the scanned store no longer holds them.

Plan(record, action, note, argv=list(), paths=list(), variants=list(), store='') dataclass

What removing a record would do.

Parameters:

Name Type Description Default
record ModelRecord

The record.

required
action str

tool, trash or refuse.

required
note str

One sentence for a person: what happens, or why not.

required
argv list[str]

The command a tool plan runs.

list()
paths list[str]

The files or folder a trash plan moves.

list()
variants list[str]

Ollama tags removed with the record that share its weights but differ in their settings; some may have been made with ollama create, and those settings cannot be pulled again.

list()
store str

For an ollama plan, the scanned store the tags must be gone from afterward.

''

execute(plan, env)

Carry out a tool or trash plan and check that it worked.

Returns:

Type Description
tuple[bool, str]

Whether the record's files are gone, and what went wrong if not.

Source code in src/modelmap/removal.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def execute(plan: Plan, env: Mapping[str, str] | None) -> tuple[bool, str]:
    """Carry out a ``tool`` or ``trash`` plan and check that it worked.

    :return: Whether the record's files are gone, and what went wrong if not.
    """
    if plan.action == "tool":
        command = [_which(plan.argv[0], env) or plan.argv[0], *plan.argv[1:]]
    elif plan.action == "trash":
        trash = trash_command(env)
        if not trash:
            return False, "No command to move files to the Trash was found."
        command = [*trash, *plan.paths]
    else:
        return False, plan.note
    try:
        result = subprocess.run(
            command, env=dict(env or {}), capture_output=True, text=True, timeout=600
        )
    except (OSError, subprocess.SubprocessError) as exc:
        return False, str(exc)
    output = (result.stderr or result.stdout).strip().splitlines()
    detail = output[-1] if output else f"exit status {result.returncode}"
    if result.returncode != 0:
        return False, detail

    if plan.action == "trash":
        left = [path for path in plan.paths if os.path.lexists(path)]
        return (not left, f"Still there: {', '.join(left)}" if left else "")
    if plan.argv[0] == "ollama":
        removed = plan.argv[2:]
        listed = _ollama_ids(env)
        if listed is None:
            # Not knowing is not success: the page must not say "Removed".
            return False, (
                "Ollama could not be asked afterward whether the tags are gone. "
                "Scan again to see what is left."
            )
        left = [tag for tag in removed if tag in listed]
        if left:
            return False, f"Ollama still lists {', '.join(left)}"
        kept = sorted(set(removed) & set(ollama.manifest_ids(plan.store))) if plan.store else []
        if kept:
            return False, (
                f"The store at {plan.store} still holds {', '.join(kept)}: the Ollama that "
                "answered uses another models folder."
            )
        return True, ""
    gone = not os.path.lexists(plan.record.path)
    return (gone, "" if gone else f"Still there: {plan.record.path}")

find(records, target)

The records a target names: provider:name, a path, or a name.

An Ollama tag names the record it is an alias of. Several matches mean the target is ambiguous.

Source code in src/modelmap/removal.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def find(records: Sequence[ModelRecord], target: str) -> list[ModelRecord]:
    """The records a target names: ``provider:name``, a path, or a name.

    An Ollama tag names the record it is an alias of. Several matches mean
    the target is ambiguous.
    """
    exact = [
        r
        for r in records
        if target in (f"{r.provider}:{r.name}", *(f"{r.provider}:{a}" for a in r.aliases))
    ]
    if exact:
        return exact
    if os.path.lexists(os.path.expanduser(target)):
        wanted = os.path.realpath(os.path.expanduser(target))
        by_path = [r for r in records if os.path.realpath(r.path) == wanted]
        if by_path:
            return by_path
    return [r for r in records if target == r.name or target in r.aliases]

plan(record, ollama_stores=(), *, env=None, check_disk=True, home='~')

Work out how a record would be removed.

Parameters:

Name Type Description Default
record ModelRecord

The record.

required
ollama_stores Collection[str]

Resolved directories of the running Ollama's stores, as the Ollama provider found them.

()
env Mapping[str, str] | None

Environment whose PATH is searched for hf, ollama and the Trash command.

None
check_disk bool

Look at the disk and ask the tools. False to describe the plan only, as in a page made from an inventory.

True
home str

The home folder of the machine scanned; never moved whole.

'~'
Source code in src/modelmap/removal.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def plan(
    record: ModelRecord,
    ollama_stores: Collection[str] = (),
    *,
    env: Mapping[str, str] | None = None,
    check_disk: bool = True,
    home: str = "~",
) -> Plan:
    """Work out how a record would be removed.

    :param record: The record.
    :param ollama_stores: Resolved directories of the running Ollama's
        stores, as the Ollama provider found them.
    :param env: Environment whose ``PATH`` is searched for ``hf``,
        ``ollama`` and the Trash command.
    :param check_disk: Look at the disk and ask the tools. False to describe
        the plan only, as in a page made from an inventory.
    :param home: The home folder of the machine scanned; never moved whole.
    """
    name, path = record.name, record.path
    # A store's own tool handles sharing inside the store. A user in another
    # store (a loose file linked into this one) would be left broken.
    outside = sorted(
        {
            user
            for entry in record.file_list
            for user in entry.used_by
            if user.partition(":")[0] != record.provider
        }
    )
    if record.kind == "cache":
        return _refuse(record, "A cache: the tool that owns it rebuilds it when needed.")
    hub = _shared_store(path) if record.provider in ("hf", "llamacpp") else None
    if hub:
        prune = shlex.join(["hf", "cache", "prune", "--cache-dir", hub])
        return _refuse(
            record,
            f"No repository refers to this. `{prune}` removes it, together with everything "
            "else in the cache that nothing refers to; run it with --dry-run first.",
        )
    if record.kind == "unattributed":
        return _refuse(record, "Nothing refers to these files. modelmap does not remove them.")

    base = os.path.basename(path)
    repo_type = _HUB_TYPES.get(base.partition("--")[0]) if "--" in base else None
    if outside and (repo_type or record.provider == "ollama"):
        return _refuse(
            record,
            f"{', '.join(outside)} {'uses' if len(outside) == 1 else 'use'} files of this one "
            "through a link, and would break.",
        )
    if repo_type:
        argv = ["hf", "cache", "rm", f"{repo_type}/{name}", "--cache-dir", os.path.dirname(path)]
        if check_disk and not _which("hf", env):
            return _refuse(record, "The hf command is needed to remove this, and it is not found.")
        return Plan(
            record,
            "tool",
            f"Runs `{shlex.join(argv)}`: removes the repository from the Hugging Face cache.",
            [*argv, "--yes"],
        )

    if record.provider == "ollama":
        live = any(path == s or path.startswith(s + os.sep) for s in ollama_stores)
        if not live:
            return _refuse(
                record,
                "This Ollama store is not the one the Ollama on this machine uses, and "
                "`ollama rm` acts only on that one. Delete the store's folder yourself "
                "if you no longer need it.",
            )
        remote = _remote_ollama(env)
        if remote:
            return _refuse(
                record,
                f"OLLAMA_HOST is {remote}, another machine: `ollama rm` would act on the models "
                "there, not on the ones scanned here.",
            )
        tags = [name, *record.aliases]
        argv = ["ollama", "rm", *tags]
        own: list[str] = []
        store = ""
        if check_disk:
            listed = _ollama_ids(env)
            if listed is None:
                return _refuse(record, "Ollama is not running, or the ollama command is not found.")
            missing = [tag for tag in tags if tag not in listed]
            if missing:
                return _refuse(
                    record,
                    f"The running Ollama does not list {', '.join(missing)}. It may use another "
                    "store than the one scanned.",
                )
            store = next(s for s in ollama_stores if path == s or path.startswith(s + os.sep))
            ids = ollama.manifest_ids(store)
            foreign = [tag for tag in tags if listed[tag] != ids.get(tag)]
            if foreign:
                return _refuse(
                    record,
                    f"The running Ollama's {', '.join(foreign)} "
                    f"{'is' if len(foreign) == 1 else 'are'} not the one in {store}: it uses "
                    "another models folder, and `ollama rm` would remove its copy instead.",
                )
            own = [tag for tag in tags if tag in ollama.variants(store, name) or tag == name]
            own = own if len(own) > 1 else []
        what = "every tag of these weights" if record.aliases else "the model"
        note = f"Runs `{shlex.join(argv)}`: removes {what} from Ollama."
        if own:
            note += (
                f" These tags share the weights but differ in their settings: {', '.join(own)}. "
                "Settings made with `ollama create` are lost and cannot be pulled again."
            )
        return Plan(record, "tool", note, argv, variants=own, store=store)

    shared = sorted({user for entry in record.file_list for user in entry.used_by})
    if shared and not any(entry.charged for entry in record.file_list):
        return _refuse(
            record,
            f"This is another name for files of {', '.join(shared)}: removing it would free "
            "nothing. Remove that instead.",
        )
    if shared:
        return _refuse(
            record,
            f"Some of its files are also used by {', '.join(shared)}. Removing them would "
            "break those too.",
        )
    if not record.file_list:
        return _refuse(record, "The record has no files.")
    if not check_disk:
        return Plan(record, "trash", "Moves its files to the Trash.")
    if not trash_command(env):
        return _refuse(record, "No command to move files to the Trash was found.")
    paths, reason = _trash_paths(record, os.path.expanduser(home))
    if not paths:
        return _refuse(record, reason)
    if paths == [path] and os.path.isdir(path):
        note = f"Moves the folder, with its {len(record.file_list)} files, to the Trash."
    else:
        count = len(paths)
        note = f"Moves {'the file' if count == 1 else f'{count} files'} to the Trash."
    return Plan(record, "trash", note, paths=paths)

plan_digest(step)

A fingerprint of everything a plan would do and the files it covers.

modelmap serve shows a plan, then plans again from a new scan before acting; the two digests must match, so what goes is what was shown.

Source code in src/modelmap/removal.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def plan_digest(step: Plan) -> str:
    """A fingerprint of everything a plan would do and the files it covers.

    ``modelmap serve`` shows a plan, then plans again from a new scan before
    acting; the two digests must match, so what goes is what was shown.
    """
    record = step.record
    parts = [
        step.action,
        record.provider,
        record.path,
        *step.argv,
        "",
        *step.paths,
        "",
        *step.variants,
        "",
        *(f"{entry.path}\t{entry.size_bytes}" for entry in record.file_list),
    ]
    return hashlib.sha256("\x1f".join(parts).encode("utf-8", "surrogateescape")).hexdigest()

target_of(record, records)

The shortest target that names this record and no other.

Source code in src/modelmap/removal.py
397
398
399
400
401
def target_of(record: ModelRecord, records: Sequence[ModelRecord]) -> str:
    """The shortest target that names this record and no other."""
    label = f"{record.provider}:{record.name}"
    clashes = [r for r in records if r is not record and find([r], label)]
    return record.path if clashes else label

trash_command(env)

The command that moves files to the Trash, or None if there is none.

macOS has /usr/bin/trash; on Linux the trash of trash-cli or gio trash from GLib.

Source code in src/modelmap/removal.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def trash_command(env: Mapping[str, str] | None) -> list[str] | None:
    """The command that moves files to the Trash, or None if there is none.

    macOS has ``/usr/bin/trash``; on Linux the ``trash`` of trash-cli or
    ``gio trash`` from GLib.
    """
    found = _which("trash", env)
    if found:
        return [found]
    gio = _which("gio", env)
    return [gio, "trash"] if gio else None