Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

73.1 KB
Raw Blame
import logging
import os
from pathlib import Path
from typing import Any

import pytest
from fastapi.testclient import TestClient
from PIL import Image

from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.api_app import app
from invokeai.backend.model_manager.configs.external_api import (
    ExternalApiModelConfig,
    ExternalModelCapabilities,
    ExternalModelPanelSchema,
)
from invokeai.backend.model_manager.configs.textual_inversion import TI_File_SD1_Config
from invokeai.backend.model_manager.taxonomy import ModelSourceType, ModelType


@pytest.fixture(autouse=True, scope="module")
def client(invokeai_root_dir: Path) -> TestClient:
    os.environ["INVOKEAI_ROOT"] = invokeai_root_dir.as_posix()
    return TestClient(app)


class DummyModelImages:
    def get_url(self, key: str) -> str:
        return f"https://example.com/models/{key}.png"


class DummyInvoker:
    def __init__(self, services: Any) -> None:
        self.services = services


class MockApiDependencies(ApiDependencies):
    invoker: DummyInvoker

    def __init__(self, invoker: DummyInvoker) -> None:
        self.invoker = invoker


def test_model_manager_external_config_round_trip(
    monkeypatch: Any, client: TestClient, mm2_model_manager: Any, mm2_app_config: Any
) -> None:
    config = ExternalApiModelConfig(
        key="external_test",
        name="External Test",
        provider_id="openai",
        provider_model_id="gpt-image-1",
        capabilities=ExternalModelCapabilities(modes=["txt2img"]),
    )
    mm2_model_manager.store.add_model(config)

    services = type("Services", (), {})()
    services.model_manager = mm2_model_manager
    services.model_images = DummyModelImages()
    services.configuration = mm2_app_config

    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.get("/api/v2/models/", params={"model_type": ModelType.ExternalImageGenerator.value})

    assert response.status_code == 200
    payload = response.json()
    assert len(payload["models"]) == 1
    assert payload["models"][0]["key"] == "external_test"
    assert payload["models"][0]["provider_id"] == "openai"
    assert payload["models"][0]["cover_image"] == "https://example.com/models/external_test.png"

    get_response = client.get("/api/v2/models/i/external_test")

    assert get_response.status_code == 200
    model_payload = get_response.json()
    assert model_payload["provider_model_id"] == "gpt-image-1"
    assert model_payload["cover_image"] == "https://example.com/models/external_test.png"


def test_model_manager_external_config_preserves_custom_panel_schema(
    monkeypatch: Any, client: TestClient, mm2_model_manager: Any, mm2_app_config: Any
) -> None:
    config = ExternalApiModelConfig(
        key="external_custom_schema",
        name="External Custom Schema",
        provider_id="custom",
        provider_model_id="custom-model",
        capabilities=ExternalModelCapabilities(modes=["txt2img"]),
        panel_schema=ExternalModelPanelSchema(
            prompts=[{"name": "reference_images"}],
            image=[{"name": "dimensions"}],
        ),
        source="external://custom/custom-model",
    )
    mm2_model_manager.store.add_model(config)

    services = type("Services", (), {})()
    services.model_manager = mm2_model_manager
    services.model_images = DummyModelImages()
    services.configuration = mm2_app_config

    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.get("/api/v2/models/i/external_custom_schema")

    assert response.status_code == 200
    payload = response.json()
    assert [control["name"] for control in payload["panel_schema"]["prompts"]] == ["reference_images"]
    assert [control["name"] for control in payload["panel_schema"]["image"]] == ["dimensions"]


def test_model_manager_external_starter_model_applies_panel_schema_overrides(
    monkeypatch: Any, client: TestClient, mm2_model_manager: Any, mm2_app_config: Any
) -> None:
    config = ExternalApiModelConfig(
        key="external_starter_schema",
        name="Starter Schema Test",
        provider_id="openai",
        provider_model_id="gpt-image-1",
        capabilities=ExternalModelCapabilities(
            modes=["txt2img"],
            supports_reference_images=False,
        ),
    )
    mm2_model_manager.store.add_model(config)

    services = type("Services", (), {})()
    services.model_manager = mm2_model_manager
    services.model_images = DummyModelImages()
    services.configuration = mm2_app_config

    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.get("/api/v2/models/i/external_starter_schema")

    assert response.status_code == 200
    payload = response.json()
    assert [control["name"] for control in payload["panel_schema"]["prompts"]] == ["reference_images"]
    assert [control["name"] for control in payload["panel_schema"]["image"]] == ["dimensions"]
    assert payload["panel_schema"]["generation"] == []


def test_model_manager_gemini_starter_model_applies_reference_and_resolution_overrides(
    monkeypatch: Any, client: TestClient, mm2_model_manager: Any, mm2_app_config: Any
) -> None:
    config = ExternalApiModelConfig(
        key="external_gemini_schema",
        name="Gemini Starter Schema Test",
        provider_id="gemini",
        provider_model_id="gemini-3.1-flash-image-preview",
        capabilities=ExternalModelCapabilities(modes=["txt2img"]),
        source="external://gemini/gemini-3.1-flash-image-preview",
    )
    mm2_model_manager.store.add_model(config)

    services = type("Services", (), {})()
    services.model_manager = mm2_model_manager
    services.model_images = DummyModelImages()
    services.configuration = mm2_app_config

    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.get("/api/v2/models/i/external_gemini_schema")

    assert response.status_code == 200
    payload = response.json()
    assert payload["capabilities"]["max_reference_images"] == 14
    assert payload["capabilities"]["max_image_size"] == {"width": 4096, "height": 4096}
    assert payload["capabilities"]["allowed_aspect_ratios"] == [
        "1:1",
        "1:4",
        "1:8",
        "2:3",
        "3:2",
        "3:4",
        "4:1",
        "4:3",
        "4:5",
        "5:4",
        "8:1",
        "9:16",
        "16:9",
        "21:9",
    ]


def _make_stats_services(ram_caches: dict) -> Any:
    class _Load:
        pass

    load = _Load()
    load.ram_caches = ram_caches

    class _ModelManager:
        pass

    mm = _ModelManager()
    mm.load = load
    services = type("Services", (), {})()
    services.model_manager = mm
    # The stats route requires auth; in single-user mode the auth dependency only reads
    # configuration.multiuser before returning the default admin user.
    services.configuration = type("Config", (), {"multiuser": False})()
    # empty_model_cache logs before clearing.
    services.logger = logging.getLogger("test.model_manager_router")
    return services


def test_get_stats_aggregates_per_device_caches(monkeypatch: Any, client: TestClient) -> None:
    """In multi-GPU mode there is one cache per device; the stats endpoint must not report only
    the API thread's default cache. All per-device caches share one global RamBudget, so each
    cache's cache_size is the SAME global capacity and its high_watermark observes the SAME global
    usage — the aggregate must not multiply those system-wide values by the number of caches."""
    from invokeai.backend.model_manager.load.model_cache.cache_stats import CacheStats

    class _Cache:
        def __init__(self, stats: CacheStats | None) -> None:
            self.stats = stats

    # Both caches report the shared global capacity (200). Their high watermarks sample the same
    # global usage at different moments, so the true system high watermark is the max (120).
    stats_0 = CacheStats(hits=3, misses=1, in_cache=2, cleared=1, cache_size=200, high_watermark=80, cache_used=55)
    stats_0.loaded_model_sizes = {"m1": 50}
    stats_1 = CacheStats(hits=5, misses=2, in_cache=1, cleared=0, cache_size=200, high_watermark=120, cache_used=70)
    stats_1.loaded_model_sizes = {"m2": 70}

    services = _make_stats_services({"cuda:0": _Cache(stats_0), "cuda:1": _Cache(stats_1)})
    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.get("/api/v2/models/stats")

    assert response.status_code == 200
    payload = response.json()
    assert payload["hits"] == 8
    assert payload["misses"] == 3
    assert payload["in_cache"] == 3
    assert payload["cleared"] == 1
    assert payload["cache_size"] == 200
    assert payload["high_watermark"] == 120
    # cache_used is this fork's *current* usage field. It observes the same global RamBudget as
    # cache_size, so it takes the max, not the sum. If it were dropped from the aggregate it would
    # report 0 and webv2's usage gauge would silently fall back to high_watermark (peak).
    assert payload["cache_used"] == 70
    assert payload["loaded_model_sizes"] == {"m1": 50, "m2": 70}


def test_get_stats_counts_duplicate_cache_objects_once(monkeypatch: Any, client: TestClient) -> None:
    """ram_caches can map several device keys to the same cache object (the default cache is
    always included under its own device key); its stats must not be double-counted."""
    from invokeai.backend.model_manager.load.model_cache.cache_stats import CacheStats

    class _Cache:
        def __init__(self, stats: CacheStats | None) -> None:
            self.stats = stats

    shared = _Cache(CacheStats(hits=4, misses=2, in_cache=1, cache_size=100, high_watermark=60))
    services = _make_stats_services({"cuda:0": shared, "cpu": shared})
    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.get("/api/v2/models/stats")

    assert response.status_code == 200
    assert response.json()["hits"] == 4


def test_empty_model_cache_aggregates_per_device_results(monkeypatch: Any, client: TestClient) -> None:
    """Upstream's multi-GPU fan-out returns None from this route, but webv2's clearModelCache awaits
    the cleared-model count and freed bytes to build its toast. Every per-device cache must be
    cleared and their results summed."""
    from invokeai.backend.model_manager.load.model_cache.model_cache import CacheClearResult

    class _Cache:
        def __init__(self, models_cleared: int, bytes_freed: int, vram_release_refused: bool = False) -> None:
            self._result = CacheClearResult(
                models_cleared=models_cleared, bytes_freed=bytes_freed, vram_release_refused=vram_release_refused
            )
            self.requested: list[int] = []

        def make_room(self, bytes_needed: int) -> CacheClearResult:
            self.requested.append(bytes_needed)
            return self._result

    cache_0 = _Cache(models_cleared=2, bytes_freed=100, vram_release_refused=True)
    cache_1 = _Cache(models_cleared=3, bytes_freed=250)
    services = _make_stats_services({"cuda:0": cache_0, "cuda:1": cache_1})
    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.post("/api/v2/models/empty_model_cache")

    assert response.status_code == 200
    assert response.json() == {"models_cleared": 5, "bytes_freed": 350, "vram_release_refused": True}
    # Both devices were actually asked to clear, not just the API thread's default cache.
    assert len(cache_0.requested) == 1
    assert len(cache_1.requested) == 1


def test_empty_model_cache_clears_duplicate_cache_objects_once(monkeypatch: Any, client: TestClient) -> None:
    """ram_caches can map several device keys to one cache object. Clearing it twice would report
    the second (already-empty) pass, so the id() guard keeps the totals honest."""
    from invokeai.backend.model_manager.load.model_cache.model_cache import CacheClearResult

    class _Cache:
        def __init__(self) -> None:
            self.calls = 0

        def make_room(self, bytes_needed: int) -> CacheClearResult:
            self.calls += 1
            return CacheClearResult(models_cleared=2, bytes_freed=100, vram_release_refused=False)

    shared = _Cache()
    services = _make_stats_services({"cuda:0": shared, "cpu": shared})
    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.post("/api/v2/models/empty_model_cache")

    assert response.status_code == 200
    assert response.json() == {"models_cleared": 2, "bytes_freed": 100, "vram_release_refused": False}
    assert shared.calls == 1


def test_empty_model_cache_succeeds_when_the_device_refuses_to_release_its_cached_memory(
    monkeypatch: Any, client: TestClient
) -> None:
    """The models are dropped before the allocator is asked to hand its blocks back; a device context that refuses
    (here a CUDA error) must not turn the finished eviction into a server error."""
    import torch

    from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
    from invokeai.backend.util import devices
    from tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModule

    releases = []

    def refuse() -> None:
        releases.append("refused")
        # The type the report hit; older torch builds only have RuntimeError.
        raise getattr(torch, "AcceleratorError", RuntimeError)("CUDA error: out of memory")

    monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
    monkeypatch.setattr(torch.cuda, "empty_cache", refuse)
    monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)
    monkeypatch.setattr(devices, "_xpu_is_available", lambda: False)

    cache = ModelCache(
        execution_device_working_mem_gb=1.0,
        enable_partial_loading=False,
        keep_ram_copy_of_weights=True,
        execution_device="cpu",
        storage_device="cpu",
        logger=logging.getLogger("test.model_manager_router"),
    )
    cache.put("model", DummyModule())
    size = cache.get("model").cached_model.total_bytes()
    invoker = DummyInvoker(_make_stats_services({"cpu": cache}))
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.post("/api/v2/models/empty_model_cache")

    assert response.status_code == 200
    assert response.json() == {"models_cleared": 1, "bytes_freed": size, "vram_release_refused": True}
    assert "model" not in cache._cached_models
    assert releases == ["refused"]


def test_empty_model_cache_does_not_report_a_deferred_release_as_refused(monkeypatch: Any, client: TestClient) -> None:
    """A release skipped because another generation device is mid-session runs later; it is not a refusal, so the
    client must not warn about unreleased GPU memory."""
    import torch

    from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
    from invokeai.backend.util import devices
    from invokeai.backend.util.devices import TorchDevice
    from tests.backend.model_manager.load.model_cache.cached_model.utils import DummyModule

    releases = []

    monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
    monkeypatch.setattr(torch.cuda, "empty_cache", lambda: releases.append("released"))
    monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)
    monkeypatch.setattr(devices, "_xpu_is_available", lambda: False)
    monkeypatch.setattr(TorchDevice, "_another_generation_device_busy", classmethod(lambda cls: True))

    cache = ModelCache(
        execution_device_working_mem_gb=1.0,
        enable_partial_loading=False,
        keep_ram_copy_of_weights=True,
        execution_device="cpu",
        storage_device="cpu",
        logger=logging.getLogger("test.model_manager_router"),
    )
    cache.put("model", DummyModule())
    size = cache.get("model").cached_model.total_bytes()
    invoker = DummyInvoker(_make_stats_services({"cpu": cache}))
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.post("/api/v2/models/empty_model_cache")

    assert response.status_code == 200
    assert response.json() == {"models_cleared": 1, "bytes_freed": size, "vram_release_refused": False}
    assert "model" not in cache._cached_models
    assert releases == []


def test_get_stats_returns_null_when_no_stats(monkeypatch: Any, client: TestClient) -> None:
    class _Cache:
        def __init__(self) -> None:
            self.stats = None

    services = _make_stats_services({"cuda:0": _Cache(), "cuda:1": _Cache()})
    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    response = client.get("/api/v2/models/stats")

    assert response.status_code == 200
    assert response.json() is None


@pytest.mark.anyio
async def test_update_model_record_runs_sync_work_off_the_event_loop(monkeypatch: Any) -> None:
    """The record write, its cache invalidation and the response preparation must not run on the event loop."""
    import threading
    from types import SimpleNamespace
    from unittest.mock import MagicMock

    import invokeai.app.api.routers.model_manager as model_manager_router

    event_loop_thread = threading.get_ident()
    service_threads: list[int] = []
    updated = object()

    def update_model_record(key: str, changes: Any) -> Any:
        service_threads.append(threading.get_ident())
        return updated

    def prepare(config: Any, _deps: Any) -> Any:
        service_threads.append(threading.get_ident())
        return config

    services = SimpleNamespace(
        logger=MagicMock(), model_manager=SimpleNamespace(update_model_record=update_model_record)
    )
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
    monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", prepare)

    result = await model_manager_router.update_model_record(
        key="model-key",
        changes=MagicMock(),
        current_admin=MagicMock(),
    )

    assert result is updated
    assert len(service_threads) == 2
    assert all(thread_id != event_loop_thread for thread_id in service_threads)


@pytest.fixture
def model_record_routes(monkeypatch: Any, mm2_model_manager: Any, mm2_app_config: Any) -> Any:
    """The model record routes over a real model manager; returns that manager."""
    services = type("Services", (), {})()
    services.model_manager = mm2_model_manager
    services.model_images = DummyModelImages()
    services.configuration = mm2_app_config
    services.logger = logging.getLogger("test.model_manager_router")
    invoker = DummyInvoker(services)
    # The load service reads the record it compares a change against through the invoker.
    mm2_model_manager.load.start(invoker)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))
    return mm2_model_manager


def test_update_model_record_answers_with_the_service_outcome(client: TestClient, model_record_routes: Any) -> None:
    key = "test_config_1"

    renamed = client.patch(f"/api/v2/models/i/{key}", json={"name": "renamed"})
    unknown = client.patch("/api/v2/models/i/no-such-model", json={"name": "renamed"})
    rejected = client.patch(f"/api/v2/models/i/{key}", json={"path": "x" * 800})
    # A VAE has no trigger phrases: the change is refused rather than dropped behind a success response.
    unsupported = client.patch(f"/api/v2/models/i/{key}", json={"trigger_phrases": ["phrase"]})

    assert renamed.status_code == 200
    assert renamed.json()["name"] == "renamed"
    assert renamed.json()["cover_image"] == f"https://example.com/models/{key}.png"
    assert model_record_routes.store.get_model(key).name == "renamed"
    assert unknown.status_code == 404
    assert rejected.status_code == 409
    assert "at most" in rejected.json()["detail"]
    assert unsupported.status_code == 409
    assert "trigger_phrases" in unsupported.json()["detail"]

    # Older clients still send `upcast_attention`, which no record stores; it is not a change, so it is ignored.
    legacy = client.patch(f"/api/v2/models/i/{key}", json={"name": "legacy", "upcast_attention": False})
    assert legacy.status_code == 200
    assert model_record_routes.store.get_model(key).name == "legacy"


def test_update_model_record_sets_keeps_and_clears_source_links(client: TestClient, model_record_routes: Any) -> None:
    key = "test_config_1"
    links = ["https://example.com/model", "https://example.com/quantized"]

    assert client.patch(f"/api/v2/models/i/{key}", json={"source_urls": links}).status_code == 200
    kept = client.patch(f"/api/v2/models/i/{key}", json={"name": "renamed"})
    assert kept.status_code == 200
    assert kept.json()["source_urls"] == links

    cleared = client.patch(f"/api/v2/models/i/{key}", json={"source_urls": None})
    assert cleared.status_code == 200
    assert cleared.json()["source_urls"] == []
    assert model_record_routes.store.get_model(key).source_urls == []


def test_reidentify_model_answers_with_the_service_outcome(
    client: TestClient, model_record_routes: Any, mm2_app_config: Any
) -> None:
    from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
    from tests.backend.model_manager.load.state_dicts import clip_g_comfy_keys
    from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors

    # A CLIP-G without the projection SD 3 needs: recognised, and refused as unusable.
    keys = dict(clip_g_comfy_keys.state_dict_keys)
    del keys["text_projection.weight"]
    write_header_only_safetensors(mm2_app_config.models_path / "clip-g.safetensors", keys)
    model_record_routes.store.add_model(
        Main_Checkpoint_SD1_Config(
            key="unusable",
            path="clip-g.safetensors",
            name="unusable",
            hash="hash",
            file_size=1,
            source="local-source",
            source_type=ModelSourceType.Path,
            prediction_type="epsilon",
            variant="normal",
        )
    )

    unusable = client.post("/api/v2/models/i/unusable/reidentify")
    unknown = client.post("/api/v2/models/i/no-such-model/reidentify")

    assert unusable.status_code == 400
    assert unknown.status_code == 404


def test_convert_model_rejects_a_second_conversion_while_one_is_running() -> None:
    """Conversions are serialized, and the loser is told so instead of being made to wait.

    Two conversions in flight means two models resident at once, which nothing bounds, and for
    the same key the second reads a record the first is midway through replacing. As `async def`
    handlers with no `await` they could not overlap; in the threadpool they can.
    """
    from unittest.mock import MagicMock

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers.model_manager import _MODEL_CONVERSION_LOCK, convert_model

    assert _MODEL_CONVERSION_LOCK.acquire(blocking=False), "lock leaked by an earlier test"
    try:
        with pytest.raises(HTTPException) as exc_info:
            # Never reaches the model store: the guard is the first thing the handler does.
            convert_model(MagicMock(), key="some-key")
    finally:
        _MODEL_CONVERSION_LOCK.release()

    assert exc_info.value.status_code == 409
    assert "already in progress" in exc_info.value.detail


def test_convert_model_releases_the_lock_when_the_conversion_fails() -> None:
    """A failed conversion must not wedge the endpoint for the rest of the process's life."""
    from unittest.mock import MagicMock, patch

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers.model_manager import _MODEL_CONVERSION_LOCK, convert_model

    with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=RuntimeError("boom")):
        with pytest.raises(RuntimeError):
            convert_model(MagicMock(), key="some-key")

    assert _MODEL_CONVERSION_LOCK.acquire(blocking=False), "the lock was not released on failure"
    _MODEL_CONVERSION_LOCK.release()

    # And the endpoint still works afterwards - the next caller gets past the guard.
    with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=HTTPException(424, "not found")):
        with pytest.raises(HTTPException) as exc_info:
            convert_model(MagicMock(), key="some-key")
    assert exc_info.value.status_code == 424


@pytest.mark.parametrize("source_urls", [[], ["https://example.com/model", "https://example.com/quantization"]])
def test_conversion_preserves_source_links_on_the_replacement_record(
    monkeypatch: Any, mm2_installer: Any, mm2_app_config: Any, diffusers_dir: Path, source_urls: list[str]
) -> None:
    import shutil
    from types import SimpleNamespace

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_images.model_images_common import ModelImageFileNotFoundException
    from invokeai.app.services.model_records import UnknownModelException
    from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
    from invokeai.backend.model_manager.taxonomy import ModelFormat, ModelVariantType, SchedulerPredictionType

    store = mm2_installer.record_store
    checkpoint = mm2_app_config.models_path / "original.safetensors"
    checkpoint.parent.mkdir(parents=True, exist_ok=True)
    checkpoint.write_bytes(b"original checkpoint")
    original = Main_Checkpoint_SD1_Config(
        key="original",
        path=checkpoint.name,
        name="Original Model",
        config_path="model.yaml",
        hash="original-hash",
        file_size=checkpoint.stat().st_size,
        source="org/original",
        source_type=ModelSourceType.HFRepoID,
        source_urls=source_urls,
        variant=ModelVariantType.Normal,
        prediction_type=SchedulerPredictionType.Epsilon,
    )
    store.add_model(original)

    class ConvertedPipeline:
        def save_pretrained(self, path: Path) -> None:
            shutil.copytree(diffusers_dir, path)

    class ModelImages(DummyModelImages):
        def get(self, _key: str) -> None:
            raise ModelImageFileNotFoundException()

    services = SimpleNamespace(
        model_manager=SimpleNamespace(
            store=store,
            install=mm2_installer,
            load=SimpleNamespace(load_model=lambda *_args, **_kwargs: SimpleNamespace(model=ConvertedPipeline())),
        ),
        configuration=mm2_app_config,
        model_images=ModelImages(),
        logger=logging.getLogger(__name__),
    )
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    converted = model_manager_router.convert_model(current_admin=SimpleNamespace(user_id="test-user"), key=original.key)

    assert converted.key != original.key
    assert converted.format == ModelFormat.Diffusers
    assert converted.source_urls == source_urls
    replacement = store.get_model(converted.key)
    assert replacement.name == "Original Model"
    assert replacement.source == "org/original"
    assert replacement.source_urls == source_urls
    assert (mm2_app_config.models_path / replacement.path).is_dir()
    with pytest.raises(UnknownModelException):
        store.get_model(original.key)
    assert not checkpoint.exists()


def test_convert_model_retains_recovery_source_and_restores_model_name(monkeypatch: Any, tmp_path: Path) -> None:
    from types import SimpleNamespace
    from unittest.mock import MagicMock

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_install.model_install_common import InstallRecoveryRequiredError
    from invokeai.app.services.model_records import ModelRecordChanges
    from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
    from invokeai.backend.model_manager.taxonomy import (
        BaseModelType,
        ModelFormat,
        ModelSourceType,
        ModelType,
        ModelVariantType,
        SchedulerPredictionType,
    )

    model_config = Main_Checkpoint_SD1_Config(
        key="model-key",
        path="/models/original.safetensors",
        name="Original Model",
        format=ModelFormat.Checkpoint,
        base=BaseModelType.StableDiffusion1,
        type=ModelType.Main,
        config_path="/configs/model.yaml",
        variant=ModelVariantType.Normal,
        hash="111222333444",
        file_size=8192,
        source="/models/original.safetensors",
        source_type=ModelSourceType.Path,
        prediction_type=SchedulerPredictionType.Epsilon,
    )

    class Store:
        def get_model(self, key: str) -> Main_Checkpoint_SD1_Config:
            assert key == model_config.key
            return model_config

        def update_model(self, key: str, changes: ModelRecordChanges) -> None:
            assert key == model_config.key
            if changes.name is not None:
                model_config.name = changes.name

    def save_pretrained(path: Path) -> None:
        path.mkdir()
        (path / "weights.safetensors").write_text("converted")

    def reject_recovery_source(path: Path, *, config: ModelRecordChanges) -> str:
        raise InstallRecoveryRequiredError(f"Install recovery required. Source: {path}; destination: /models/recovery")

    services = SimpleNamespace(
        model_manager=SimpleNamespace(
            store=Store(),
            load=SimpleNamespace(
                load_model=lambda *_args, **_kwargs: SimpleNamespace(
                    model=SimpleNamespace(save_pretrained=save_pretrained)
                )
            ),
            install=SimpleNamespace(install_path=reject_recovery_source),
        ),
        configuration=SimpleNamespace(models_path=tmp_path),
        logger=MagicMock(),
    )
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(HTTPException) as exc_info:
        model_manager_router.convert_model(
            current_admin=SimpleNamespace(user_id="test-user"),
            key=model_config.key,
        )

    assert exc_info.value.status_code == 409
    assert "Source:" in exc_info.value.detail
    recovery_path = Path(exc_info.value.detail.rsplit("retained at ", 1)[1].rstrip("."))
    assert recovery_path.is_dir()
    assert (recovery_path / "original" / "weights.safetensors").read_text() == "converted"
    assert model_config.name == "Original Model"


def test_cancel_model_install_does_not_map_unrelated_value_error_to_conflict(monkeypatch: Any) -> None:
    from types import SimpleNamespace

    from invokeai.app.api.routers import model_manager as model_manager_router

    class Installer:
        def get_job_by_id(self, _job_id: int) -> object:
            return object()

        def cancel_job(self, _job: object) -> None:
            raise ValueError("unrelated service failure")

    services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(ValueError, match="unrelated service failure"):
        model_manager_router.cancel_model_install_job(current_admin=None, id=42)


def test_prune_model_install_jobs_returns_exact_pruned_ids(monkeypatch: Any) -> None:
    from types import SimpleNamespace

    from invokeai.app.api.routers import model_manager as model_manager_router

    installer = SimpleNamespace(prune_jobs=lambda: [41, 42])
    services = SimpleNamespace(model_manager=SimpleNamespace(install=installer))
    dependencies = MockApiDependencies(DummyInvoker(services))
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", dependencies)

    result = model_manager_router.prune_model_install_jobs(current_admin=None)

    assert result == [41, 42]
    prune_route = next(
        route
        for route in model_manager_router.model_manager_router.routes
        if route.path.endswith("/models/install") and "DELETE" in route.methods
    )
    assert prune_route.status_code == 200
    assert prune_route.response_model == list[int]


@pytest.mark.parametrize("operation", ["restart_failed", "restart_file"])
def test_restart_recovery_required_install_returns_conflict(monkeypatch: Any, operation: str) -> None:
    from types import SimpleNamespace

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_install.model_install_common import InstallRecoveryRequiredError

    class Installer:
        def get_job_by_id(self, job_id: int) -> object:
            assert job_id == 42
            return object()

        def restart_failed(self, _job: object) -> None:
            raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery")

        def restart_file(self, _job: object, _source: str) -> None:
            raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery")

    services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(HTTPException) as exc_info:
        if operation == "restart_failed":
            model_manager_router.restart_failed_model_install_job(current_admin=None, id=42)
        else:
            model_manager_router.restart_model_install_file(
                current_admin=None, id=42, file_source="https://example.com/model.safetensors"
            )

    assert exc_info.value.status_code == 409
    assert "requires recovery" in exc_info.value.detail


@pytest.mark.parametrize("operation", ["cancel", "pause", "resume", "restart_failed", "restart_file"])
def test_remote_download_replacement_returns_conflict(monkeypatch: Any, operation: str) -> None:
    from types import SimpleNamespace

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_install.model_install_common import InstallDownloadConflictError

    class Installer:
        def get_job_by_id(self, job_id: int) -> object:
            assert job_id == 42
            return object()

        def resume_job(self, _job: object) -> None:
            raise InstallDownloadConflictError("A previous download is still active")

        def pause_job(self, _job: object) -> None:
            raise InstallDownloadConflictError("A previous download is still active")

        def cancel_job(self, _job: object) -> None:
            raise InstallDownloadConflictError("A previous download is still active")

        def restart_failed(self, _job: object) -> None:
            raise InstallDownloadConflictError("A previous download is still active")

        def restart_file(self, _job: object, _source: str) -> None:
            raise InstallDownloadConflictError("A previous download is still active")

    services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(HTTPException) as exc_info:
        if operation == "cancel":
            model_manager_router.cancel_model_install_job(current_admin=None, id=42)
        elif operation == "resume":
            model_manager_router.resume_model_install_job(current_admin=None, id=42)
        elif operation == "pause":
            model_manager_router.pause_model_install_job(current_admin=None, id=42)
        elif operation == "restart_failed":
            model_manager_router.restart_failed_model_install_job(current_admin=None, id=42)
        else:
            model_manager_router.restart_model_install_file(
                current_admin=None, id=42, file_source="https://example.com/model.safetensors"
            )

    assert exc_info.value.status_code == 409
    assert "previous download" in exc_info.value.detail


@pytest.mark.parametrize("operation", ["resume", "restart_failed", "restart_file"])
def test_vanished_pinned_revision_returns_conflict(monkeypatch: Any, operation: str) -> None:
    from types import SimpleNamespace

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.backend.model_manager.metadata import ModelRevisionUnavailableError

    def refuse(*_args: object) -> None:
        raise ModelRevisionUnavailableError("Revision 'abc' of 'org/repo' is no longer available")

    installer = SimpleNamespace(
        get_job_by_id=lambda _id: object(), resume_job=refuse, restart_failed=refuse, restart_file=refuse
    )
    services = SimpleNamespace(model_manager=SimpleNamespace(install=installer))
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(HTTPException) as exc_info:
        if operation == "resume":
            model_manager_router.resume_model_install_job(current_admin=None, id=42)
        elif operation == "restart_failed":
            model_manager_router.restart_failed_model_install_job(current_admin=None, id=42)
        else:
            model_manager_router.restart_model_install_file(
                current_admin=None, id=42, file_source="https://example.com/model.safetensors"
            )

    assert exc_info.value.status_code == 409
    assert "no longer available" in exc_info.value.detail


@pytest.mark.parametrize("operation", ["resume", "restart_failed", "restart_file"])
def test_install_path_claim_conflict_returns_conflict(monkeypatch: Any, operation: str) -> None:
    from types import SimpleNamespace

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_install.model_install_common import InstallCancellationConflictError

    class Installer:
        def get_job_by_id(self, job_id: int) -> object:
            assert job_id == 42
            return object()

        def resume_job(self, _job: object) -> None:
            raise InstallCancellationConflictError("Another operation owns the install path")

        def restart_failed(self, _job: object) -> None:
            raise InstallCancellationConflictError("Another operation owns the install path")

        def restart_file(self, _job: object, _source: str) -> None:
            raise InstallCancellationConflictError("Another operation owns the install path")

    services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(HTTPException) as exc_info:
        if operation == "resume":
            model_manager_router.resume_model_install_job(current_admin=None, id=42)
        elif operation == "restart_failed":
            model_manager_router.restart_failed_model_install_job(current_admin=None, id=42)
        else:
            model_manager_router.restart_model_install_file(
                current_admin=None, id=42, file_source="https://example.com/model.safetensors"
            )

    assert exc_info.value.status_code == 409
    assert "owns the install path" in exc_info.value.detail


@pytest.mark.parametrize("install_fails", [False, True])
def test_conversion_cleans_scratch_after_success_and_ordinary_failure(
    monkeypatch: Any, tmp_path: Path, install_fails: bool
) -> None:
    from types import SimpleNamespace
    from unittest.mock import MagicMock

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_images.model_images_common import ModelImageFileNotFoundException
    from invokeai.app.services.model_records import ModelRecordChanges
    from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config
    from invokeai.backend.model_manager.taxonomy import (
        BaseModelType,
        ModelFormat,
        ModelSourceType,
        ModelType,
        ModelVariantType,
        SchedulerPredictionType,
    )

    models_path = tmp_path / "models"
    models_path.mkdir()
    original = Main_Checkpoint_SD1_Config(
        key="model-key",
        path="original.safetensors",
        name="Original Model",
        format=ModelFormat.Checkpoint,
        base=BaseModelType.StableDiffusion1,
        type=ModelType.Main,
        config_path="model.yaml",
        variant=ModelVariantType.Normal,
        hash="111222333444",
        file_size=8192,
        source="local-source",
        source_type=ModelSourceType.Path,
        prediction_type=SchedulerPredictionType.Epsilon,
    )
    converted = SimpleNamespace(key="converted-key")

    class Store:
        def get_model(self, key: str) -> Any:
            return original if key == original.key else converted

        def update_model(self, key: str, changes: ModelRecordChanges) -> None:
            if changes.name is not None:
                original.name = changes.name

    def save_pretrained(path: Path) -> None:
        path.mkdir()
        (path / "weights.safetensors").write_bytes(b"weights")

    class Installer:
        def install_path(self, _path: Path, *, config: ModelRecordChanges) -> str:
            if install_fails:
                raise ValueError("ordinary install failure")
            return converted.key

        def delete(self, _key: str) -> None:
            return None

    def model_image(_key: str) -> None:
        raise ModelImageFileNotFoundException()

    services = SimpleNamespace(
        model_manager=SimpleNamespace(
            store=Store(),
            load=SimpleNamespace(
                load_model=lambda *_args, **_kwargs: SimpleNamespace(
                    model=SimpleNamespace(save_pretrained=save_pretrained)
                )
            ),
            install=Installer(),
        ),
        configuration=SimpleNamespace(models_path=models_path),
        model_images=SimpleNamespace(get=model_image),
        logger=MagicMock(),
    )
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))
    monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", lambda config, _deps: config)

    if install_fails:
        with pytest.raises(HTTPException) as exc_info:
            model_manager_router._convert_model(original.key, user_id="test-user")
        assert exc_info.value.status_code == 409
    else:
        assert model_manager_router._convert_model(original.key, user_id="test-user") is converted

    scratch_dir = models_path / model_manager_router.CONVERSION_SCRATCH_DIRNAME
    assert scratch_dir.exists()
    assert list(scratch_dir.iterdir()) == []


def test_cancel_recovery_required_install_returns_conflict(monkeypatch: Any) -> None:
    from types import SimpleNamespace

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_install.model_install_common import InstallRecoveryRequiredError

    class Installer:
        def get_job_by_id(self, job_id: int) -> object:
            assert job_id == 42
            return object()

        def cancel_job(self, _job: object) -> None:
            raise InstallRecoveryRequiredError("Cannot cancel an install that requires recovery")

    services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(HTTPException) as exc_info:
        model_manager_router.cancel_model_install_job(current_admin=None, id=42)

    assert exc_info.value.status_code == 409
    assert "requires recovery" in exc_info.value.detail


def test_cancel_active_install_returns_conflict(monkeypatch: Any) -> None:
    from types import SimpleNamespace

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager as model_manager_router
    from invokeai.app.services.model_install.model_install_common import InstallCancellationConflictError

    class Installer:
        def get_job_by_id(self, job_id: int) -> object:
            assert job_id == 43
            return object()

        def cancel_job(self, _job: object) -> None:
            raise InstallCancellationConflictError("Cannot cancel while install files are being moved")

    services = SimpleNamespace(model_manager=SimpleNamespace(install=Installer()))
    monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(DummyInvoker(services)))

    with pytest.raises(HTTPException) as exc_info:
        model_manager_router.cancel_model_install_job(current_admin=None, id=43)

    assert exc_info.value.status_code == 409
    assert "being moved" in exc_info.value.detail


def test_delete_is_refused_while_the_same_model_is_being_converted() -> None:
    """A delete landing mid-conversion must not pull the source out from under it.

    Conversion is a read-modify-replace spanning many service calls: it loads the model, writes a
    diffusers copy, installs that copy, then deletes the original. As `async def` bodies with no
    `await` neither route could interleave with the other; in the threadpool they can. A delete
    slipping into the middle removes the record the conversion is still working from, the
    conversion's own final delete then fails, and the copy it already installed survives — so the
    admin is answered 204 and the model reappears under a new key.
    """
    import threading
    from unittest.mock import MagicMock, patch

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers.model_manager import convert_model, delete_model

    conversion_running = threading.Event()
    release_conversion = threading.Event()
    installer = MagicMock()

    def blocking_conversion(key: str, user_id: str) -> object:
        conversion_running.set()
        assert release_conversion.wait(timeout=30)
        return MagicMock()

    with patch("invokeai.app.api.routers.model_manager.ApiDependencies") as deps:
        deps.invoker.services.model_manager.install = installer
        with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=blocking_conversion):
            conversion = threading.Thread(target=convert_model, args=(MagicMock(),), kwargs={"key": "model-key"})
            conversion.start()
            try:
                assert conversion_running.wait(timeout=30)

                with pytest.raises(HTTPException) as exc_info:
                    delete_model(MagicMock(), key="model-key")

                assert exc_info.value.status_code == 409
                # The refusal has to happen before the installer is touched, not after.
                installer.delete.assert_not_called()

                # A different model is untouched by the claim.
                delete_model(MagicMock(), key="other-key")
                installer.delete.assert_called_once_with("other-key")
            finally:
                release_conversion.set()
                conversion.join(timeout=30)
                assert not conversion.is_alive()

        # Once the conversion is done the key is free again.
        delete_model(MagicMock(), key="model-key")
    assert installer.delete.call_args_list[-1].args == ("model-key",)


def test_bulk_delete_reports_a_busy_key_instead_of_racing_it() -> None:
    """Bulk deletion claims each key separately, so one busy model does not stall or corrupt the rest."""
    import threading
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers.model_manager import BulkDeleteModelsRequest, bulk_delete_models, convert_model

    conversion_running = threading.Event()
    release_conversion = threading.Event()
    installer = MagicMock()

    def blocking_conversion(key: str, user_id: str) -> object:
        conversion_running.set()
        assert release_conversion.wait(timeout=30)
        return MagicMock()

    with patch("invokeai.app.api.routers.model_manager.ApiDependencies") as deps:
        deps.invoker.services.model_manager.install = installer
        with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=blocking_conversion):
            conversion = threading.Thread(target=convert_model, args=(MagicMock(),), kwargs={"key": "busy-key"})
            conversion.start()
            try:
                assert conversion_running.wait(timeout=30)

                response = bulk_delete_models(
                    MagicMock(), request=BulkDeleteModelsRequest(keys=["free-key", "busy-key"])
                )
            finally:
                release_conversion.set()
                conversion.join(timeout=30)
                assert not conversion.is_alive()

    assert response.deleted == ["free-key"]
    assert [entry["key"] for entry in response.failed] == ["busy-key"]
    assert "already in progress" in response.failed[0]["error"]
    installer.delete.assert_called_once_with("free-key")


@pytest.fixture
def conversion_in_flight():
    """Hold a conversion of `busy-key` at a barrier for the duration of the test.

    Yields the mocked installer/store/model_images so a test can assert what the racing request
    did or did not reach.
    """
    import threading
    from contextlib import contextmanager
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers.model_manager import convert_model

    @contextmanager
    def _run(key: str = "busy-key"):
        running = threading.Event()
        release = threading.Event()

        def blocking_conversion(key: str, user_id: str) -> object:
            running.set()
            assert release.wait(timeout=30)
            return MagicMock()

        with patch("invokeai.app.api.routers.model_manager.ApiDependencies") as deps:
            with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=blocking_conversion):
                conversion = threading.Thread(target=convert_model, args=(MagicMock(),), kwargs={"key": key})
                conversion.start()
                try:
                    assert running.wait(timeout=30)
                    yield deps
                finally:
                    release.set()
                    conversion.join(timeout=30)
                    assert not conversion.is_alive()

    return _run


def test_reidentify_is_refused_while_the_same_model_is_being_converted(conversion_in_flight) -> None:
    """Reidentification rewrites the record a conversion is about to replace from its own snapshot."""
    from unittest.mock import MagicMock

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers.model_manager import reidentify_model

    with conversion_in_flight() as deps:
        with pytest.raises(HTTPException) as exc_info:
            reidentify_model(key="busy-key", current_admin=MagicMock())

        assert exc_info.value.status_code == 409
        deps.invoker.services.model_manager.reidentify_model.assert_not_called()


@pytest.mark.anyio
async def test_update_model_record_is_refused_while_the_same_model_is_being_converted(
    conversion_in_flight,
) -> None:
    """An edit accepted mid-conversion would be reported as saved and then dropped.

    The conversion writes the name, description, hash and source it read *before* it started into
    the replacement record, so anything written in between never reaches the new key.
    """
    from unittest.mock import MagicMock

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers.model_manager import update_model_record
    from invokeai.app.services.model_records import ModelRecordChanges

    with conversion_in_flight() as deps:
        with pytest.raises(HTTPException) as exc_info:
            await update_model_record(
                key="busy-key", changes=ModelRecordChanges(name="renamed"), current_admin=MagicMock()
            )

        assert exc_info.value.status_code == 409
        deps.invoker.services.model_manager.update_model_record.assert_not_called()


def test_model_image_writes_are_refused_while_the_same_model_is_being_converted(conversion_in_flight) -> None:
    """A conversion moves the image to the replacement's key, so writes in between are lost."""
    from unittest.mock import MagicMock

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers.model_manager import delete_model_image

    with conversion_in_flight() as deps:
        with pytest.raises(HTTPException) as exc_info:
            delete_model_image(MagicMock(), key="busy-key")

        assert exc_info.value.status_code == 409
        deps.invoker.services.model_images.delete.assert_not_called()


@pytest.mark.anyio
async def test_model_image_upload_claims_before_read() -> None:
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers import model_manager

    image = MagicMock()
    image.content_type = "image/png"

    async def read() -> bytes:
        assert "upload-key" in model_manager._CLAIMED_MODEL_KEYS
        return b"image"

    image.read = read

    with patch.object(model_manager, "ApiDependencies") as deps:
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_images = MagicMock()
        with patch.object(model_manager.Image, "open", return_value=MagicMock()):
            await model_manager.update_model_image("upload-key", image, MagicMock())


def test_converted_model_key_is_claimed_after_install() -> None:
    from pathlib import Path
    from unittest.mock import MagicMock, patch

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager
    from invokeai.app.api.routers.model_manager import delete_model

    installer = MagicMock()
    installer.install_path.return_value = "replacement-key"
    install_config = MagicMock()

    with patch.object(model_manager, "ApiDependencies") as deps:
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_manager.install = installer
        with model_manager._install_and_claim_model(installer, Path("/tmp/converted"), install_config) as new_key:
            assert new_key == "replacement-key"
            with pytest.raises(HTTPException) as exc_info:
                delete_model(MagicMock(), key="replacement-key")

            assert exc_info.value.status_code == 409
            installer.delete.assert_not_called()


def test_model_mutations_document_claim_conflicts() -> None:
    from invokeai.app.api.routers.model_manager import model_manager_router

    routes = {route.operation_id: route for route in model_manager_router.routes if route.operation_id}

    for operation_id in ("reidentify_model", "update_model_image", "delete_model", "delete_model_image"):
        assert 409 in routes[operation_id].responses


def test_bulk_reidentify_reports_a_busy_key_instead_of_racing_it(conversion_in_flight) -> None:
    from unittest.mock import MagicMock

    from invokeai.app.api.routers.model_manager import BulkReidentifyModelsRequest, bulk_reidentify_models

    with conversion_in_flight() as deps:
        response = bulk_reidentify_models(
            MagicMock(), request=BulkReidentifyModelsRequest(keys=["free-key", "busy-key"])
        )

    assert response.succeeded == ["free-key"]
    assert [entry["key"] for entry in response.failed] == ["busy-key"]
    assert "already in progress" in response.failed[0]["error"]
    deps.invoker.services.model_manager.reidentify_model.assert_called_once_with("free-key")


@pytest.fixture
def real_model_images(tmp_path: Path):
    from unittest.mock import MagicMock

    from invokeai.app.services.model_images.model_images_default import ModelImageFileStorageDisk

    storage = ModelImageFileStorageDisk(tmp_path / "model_images")
    storage.start(MagicMock())
    return storage


def test_delete_model_image_removes_the_image_of_a_deleted_model(real_model_images) -> None:
    """Deleting a model leaves its cover image behind, and this route is how that orphan is cleaned up - so it must
    not require the model's record to still exist."""
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers import model_manager
    from invokeai.app.services.model_records.model_records_base import UnknownModelException

    real_model_images.save(Image.new("RGB", (8, 8)), "deleted-model")
    image_path = real_model_images.get_path("deleted-model")
    assert image_path.exists()

    with patch.object(model_manager, "ApiDependencies") as deps:
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_images = real_model_images
        deps.invoker.services.model_manager.store.get_model.side_effect = UnknownModelException("deleted-model")

        model_manager.delete_model_image(MagicMock(), key="deleted-model")

    assert not image_path.exists()


# `../escaped` is the case that matters on posix: the backslash and `..` shapes are literal (and missing) filenames
# there, so they would 404 even with no key validation at all.
@pytest.mark.parametrize("key", ["no-such-model", "../escaped", "..\\escaped", ".."])
def test_delete_model_image_404s_for_a_missing_image_or_an_unsafe_key(real_model_images, key: str) -> None:
    """A missing image and a key that is not a plain filename are both 404s - not 500s, and never an unlink of a
    path outside the images folder. A file is planted at the traversal target so a missing guard would show."""
    from unittest.mock import MagicMock, patch

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager

    images_dir = real_model_images._model_images_folder
    images_dir.mkdir(parents=True, exist_ok=True)
    planted = images_dir.parent / "escaped.webp"
    planted.write_bytes(b"not yours")

    with patch.object(model_manager, "ApiDependencies") as deps:
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_images = real_model_images

        with pytest.raises(HTTPException) as exc_info:
            model_manager.delete_model_image(MagicMock(), key=key)

    assert exc_info.value.status_code == 404
    assert planted.exists()
    assert key not in model_manager._CLAIMED_MODEL_KEYS


@pytest.mark.anyio
@pytest.mark.parametrize("key", ["no-such-model", "..\\..\\pwned", ".."])
async def test_update_model_image_404s_for_a_key_that_names_no_model(key: str) -> None:
    from unittest.mock import MagicMock, patch

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager
    from invokeai.app.services.model_records.model_records_base import UnknownModelException

    image = MagicMock()
    image.content_type = "image/png"

    with patch.object(model_manager, "ApiDependencies") as deps:
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_images = MagicMock()
        deps.invoker.services.model_manager.store.get_model.side_effect = UnknownModelException(key)

        with pytest.raises(HTTPException) as exc_info:
            await model_manager.update_model_image(key, image, MagicMock())

        assert exc_info.value.status_code == 404
        deps.invoker.services.model_images.save.assert_not_called()
        assert key not in model_manager._CLAIMED_MODEL_KEYS


@pytest.mark.anyio
async def test_update_model_image_404s_for_a_legacy_unsafe_model_key(real_model_images) -> None:
    """A persisted legacy record can outlive current key validation, but an upload must still return a client error
    when the storage layer rejects its key instead of surfacing a 500."""
    from io import BytesIO
    from unittest.mock import MagicMock, patch

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager

    key = "../escaped"
    escaped_image_path = real_model_images._model_images_folder.parent / "escaped.webp"
    image_bytes = BytesIO()
    Image.new("RGB", (8, 8)).save(image_bytes, format="PNG")
    image = MagicMock()
    image.content_type = "image/png"

    async def read() -> bytes:
        return image_bytes.getvalue()

    async def run_in_thread(function: Any, *args: Any, **kwargs: Any) -> Any:
        return function(*args, **kwargs)

    image.read = read

    with (
        patch.object(model_manager, "ApiDependencies") as deps,
        patch.object(model_manager.asyncio, "to_thread", run_in_thread),
    ):
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_images = real_model_images
        # Simulate a model record written before unsafe model keys were rejected.
        deps.invoker.services.model_manager.store.get_model.return_value = MagicMock()

        with pytest.raises(HTTPException) as exc_info:
            await model_manager.update_model_image(key, image, MagicMock())

    assert exc_info.value.status_code == 404
    assert not escaped_image_path.exists()
    assert key not in model_manager._CLAIMED_MODEL_KEYS


@pytest.mark.anyio
async def test_update_model_image_checks_the_record_while_holding_the_claim() -> None:
    """Deletion and conversion claim the key too, so checking the record under the claim is what stops one of them
    from removing the model between the check and the save - which would leave an orphan image behind a 200."""
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers import model_manager

    image = MagicMock()
    image.content_type = "image/png"
    claimed_during_lookup: list[bool] = []

    def get_model(key: str) -> MagicMock:
        claimed_during_lookup.append(key in model_manager._CLAIMED_MODEL_KEYS)
        return MagicMock()

    async def read() -> bytes:
        return b"irrelevant"

    image.read = read

    with (
        patch.object(model_manager, "ApiDependencies") as deps,
        patch.object(model_manager.Image, "open", return_value=MagicMock()),
    ):
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_images = MagicMock()
        deps.invoker.services.model_manager.store.get_model.side_effect = get_model

        await model_manager.update_model_image("some-model", image, MagicMock())

    assert claimed_during_lookup == [True]
    deps.invoker.services.model_images.save.assert_called_once()


@pytest.mark.anyio
async def test_record_writes_run_while_holding_the_claim() -> None:
    """A conversion of the same key carries a snapshot of the record into its replacement, so an edit or
    re-identification that ran outside the claim would be reported as saved and then lost."""
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers import model_manager
    from invokeai.app.services.model_records import ModelRecordChanges

    claimed_during_write: list[tuple[str, bool]] = []

    def record(operation: str):
        def write(key: str, *_args: Any) -> MagicMock:
            claimed_during_write.append((operation, key in model_manager._CLAIMED_MODEL_KEYS))
            return MagicMock()

        return write

    with (
        patch.object(model_manager, "ApiDependencies") as deps,
        patch.object(model_manager, "prepare_model_config_for_response", lambda config, _deps: config),
    ):
        deps.invoker.services.model_manager.update_model_record.side_effect = record("update")
        deps.invoker.services.model_manager.reidentify_model.side_effect = record("reidentify")

        await model_manager.update_model_record("some-model", ModelRecordChanges(name="renamed"), MagicMock())
        model_manager.reidentify_model("some-model", MagicMock())
        model_manager.bulk_reidentify_models(
            MagicMock(), request=model_manager.BulkReidentifyModelsRequest(keys=["some-model"])
        )

    assert claimed_during_write == [("update", True), ("reidentify", True), ("reidentify", True)]
    assert not model_manager._CLAIMED_MODEL_KEYS


def test_update_model_image_documents_its_404(client: TestClient) -> None:
    operation = client.get("/openapi.json").json()["paths"]["/api/v2/models/i/{key}/image"]["patch"]
    assert "404" in operation["responses"]


def test_a_case_variant_of_a_claimed_key_is_refused() -> None:
    """Cover images are `<key>.webp`, which is one file for `K` and `k` on a case-insensitive filesystem - so a
    claim on one must block the other, or an image delete could race a conversion of the same model."""
    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager

    with model_manager._claim_model_key("abc-model"):
        with pytest.raises(HTTPException) as exc_info:
            with model_manager._claim_model_key("ABC-Model"):
                pass
        assert exc_info.value.status_code == 409

    assert not model_manager._CLAIMED_MODEL_KEYS


def test_a_normalization_variant_of_a_claimed_key_is_refused() -> None:
    """APFS ignores Unicode normalization, so `é.webp` and `é.webp` are one file there - the claims must
    conflict just like case variants do."""
    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager

    with model_manager._claim_model_key("café"):
        with pytest.raises(HTTPException) as exc_info:
            with model_manager._claim_model_key("CAFÉ"):
                pass
        assert exc_info.value.status_code == 409

    assert not model_manager._CLAIMED_MODEL_KEYS


@pytest.mark.anyio
@pytest.mark.parametrize("new_key", ["../../pwned", "..:stream", "a-different-but-valid-key"])
async def test_update_model_record_refuses_to_change_the_key(new_key: str) -> None:
    """`update_model` copies every set field into the stored config, so a `key` in the body is written into the
    blob while the row id keeps the old one. The record then answers to a key nothing can look it up by:
    `replace_model` (and so reidentify) raises UnknownModelException forever after, and the UI caches the model
    under the new key so every later request 404s. Note the last case - a *valid* key does this too, so the guard
    is on the key changing, not on it being unsafe."""
    from unittest.mock import MagicMock, patch

    from starlette.exceptions import HTTPException

    from invokeai.app.api.routers import model_manager
    from invokeai.app.services.model_records.model_records_base import ModelRecordChanges

    with patch.object(model_manager, "ApiDependencies") as deps:
        with pytest.raises(HTTPException) as exc_info:
            await model_manager.update_model_record(
                key="real-key", changes=ModelRecordChanges(key=new_key, name="x"), current_admin=MagicMock()
            )

        assert exc_info.value.status_code == 422
        deps.invoker.services.model_manager.update_model_record.assert_not_called()


@pytest.mark.anyio
async def test_update_model_record_accepts_the_forms_unchanged_key_echo() -> None:
    """`ModelEdit.tsx` seeds its form from the whole config, so the key rides along on every save. That echo must
    go through - including for a key that predates key validation, which has no other way to be edited."""
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers import model_manager
    from invokeai.app.services.model_records.model_records_base import ModelRecordChanges

    for key in ("ecd3b3a5-6c4f-4a5f-9a0e-4b1c2d3e4f50", "legacy:key", "legacy?key"):
        with patch.object(model_manager, "_update_model_record") as update:
            await model_manager.update_model_record(
                key=key, changes=ModelRecordChanges(key=key, name="renamed"), current_admin=MagicMock()
            )
            assert update.call_args.args[0] == key


@pytest.mark.anyio
@pytest.mark.skipif(os.name == "nt", reason="Legacy colon keys could only have been stored on POSIX filesystems")
async def test_a_legacy_posix_key_can_still_replace_and_delete_its_cover(real_model_images) -> None:
    """No released version checked model keys, so a posix install can hold a model keyed `legacy:key` with a cover
    already on disk. The image routes must keep managing it rather than 404ing on a Windows-only rule."""
    from io import BytesIO
    from unittest.mock import MagicMock, patch

    from invokeai.app.api.routers import model_manager

    key = "legacy:key"
    image_bytes = BytesIO()
    Image.new("RGB", (8, 8)).save(image_bytes, format="PNG")
    image = MagicMock()
    image.content_type = "image/png"

    async def read() -> bytes:
        return image_bytes.getvalue()

    image.read = read

    with patch.object(model_manager, "ApiDependencies") as deps:
        deps.invoker.services.logger = MagicMock()
        deps.invoker.services.model_images = real_model_images
        deps.invoker.services.model_manager.store.get_model.return_value = MagicMock()

        await model_manager.update_model_image(key, image, MagicMock())
        image_path = real_model_images._model_images_folder / f"{key}.webp"
        assert image_path.exists()

        model_manager.delete_model_image(MagicMock(), key=key)
        assert not image_path.exists()


def test_model_image_url_encodes_the_key() -> None:
    """Unencoded, a stored key like `X?y` makes the cover URL address the route for model `X` instead."""
    from invokeai.app.services.urls.urls_default import LocalUrlService

    urls = LocalUrlService()
    assert urls.get_model_image_url("X?y") == "api/v2/models/i/X%3Fy/image"
    assert urls.get_model_image_url("a#b%c") == "api/v2/models/i/a%23b%25c/image"
    assert urls.get_model_image_url("openai-dall-e-3") == "api/v2/models/i/openai-dall-e-3/image"


def test_an_encoded_key_reaches_the_image_route_intact(client: TestClient, tmp_path: Path) -> None:
    """The other half of the encoding: the server decodes `%3F` back into the key, rather than routing on it."""
    from unittest.mock import patch

    from invokeai.app.api.routers import model_manager

    cover = tmp_path / "cover.webp"
    Image.new("RGB", (8, 8)).save(cover, format="webp")

    with patch.object(model_manager, "ApiDependencies") as deps:
        deps.invoker.services.model_images.get_path.return_value = cover
        response = client.get("/api/v2/models/i/X%3Fy/image")

    assert response.status_code == 200
    deps.invoker.services.model_images.get_path.assert_called_once_with("X?y")


def test_the_orphan_routes_scan_with_the_model_records(
    monkeypatch: Any, client: TestClient, mm2_model_manager: Any, mm2_app_config: Any
) -> None:
    models_path: Path = mm2_app_config.models_path
    for directory in ("registered", "unregistered"):
        (models_path / directory).mkdir(parents=True, exist_ok=True)
        (models_path / directory / "model.safetensors").write_bytes(b"not really a model")
    mm2_model_manager.store.add_model(
        TI_File_SD1_Config(
            path="registered/model.safetensors",
            name="registered",
            hash="ABC123",
            file_size=18,
            source="test/source/",
            source_type=ModelSourceType.Path,
        )
    )
    services = type("Services", (), {})()
    services.model_manager = mm2_model_manager
    services.configuration = mm2_app_config
    invoker = DummyInvoker(services)
    monkeypatch.setattr("invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(invoker))
    monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", MockApiDependencies(invoker))

    found = client.get("/api/v2/models/sync/orphaned")

    assert found.status_code == 200, found.text
    reported = {orphan["path"] for orphan in found.json()}
    assert "unregistered" in reported and "registered" not in reported

    deleted = client.request("DELETE", "/api/v2/models/sync/orphaned", json={"paths": ["unregistered"]})

    assert deleted.status_code == 200, deleted.text
    assert deleted.json() == {"deleted": ["unregistered"], "errors": {}}
    assert (models_path / "registered").exists() and not (models_path / "unregistered").exists()