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.

feat(model-manager): stop a folder scan on demand

Josh Corbett79e8423a0555
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index b29a92de64..8bbbd6a24a 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -14,7 +14,7 @@ from tempfile import TemporaryDirectory
from typing import Any, List, Optional, Type
import huggingface_hub
-from fastapi import Body, Header, Path, Query, Response, UploadFile
+from fastapi import Body, Header, Path, Query, Request, Response, UploadFile
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.routing import APIRouter
from PIL import Image
@@ -49,7 +49,7 @@ from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LO
from invokeai.backend.model_manager.metadata.fetch.huggingface import HuggingFaceMetadataFetch
from invokeai.backend.model_manager.metadata.metadata_base import ModelMetadataWithFiles, UnknownMetadataException
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
-from invokeai.backend.model_manager.search import ModelSearch
+from invokeai.backend.model_manager.search import ModelSearch, ModelSearchCancelled
from invokeai.backend.model_manager.starter_models import (
STARTER_BUNDLES,
STARTER_MODELS,
@@ -473,7 +473,8 @@ class FoundModel(BaseModel):
status_code=200,
response_model=List[FoundModel],
)
-def scan_for_models(
+async def scan_for_models(
+ request: Request,
current_admin: AdminUserOrDefault,
scan_path: str = Query(description="Directory path to search for models", default=None),
) -> List[FoundModel]:
@@ -492,27 +493,44 @@ def scan_for_models(
if not path.is_dir():
raise scan_failed
- search = ModelSearch()
+ # The walk runs off the event loop and is polled against the request: a client that cancels the scan
+ # (or navigates away) disconnects, and the walk stops at the next directory instead of crawling on.
+ stop = threading.Event()
try:
- found_model_paths = search.search(path)
- models_path = ApiDependencies.invoker.services.configuration.models_path
+ search = ModelSearch(should_stop=stop.is_set)
+ walk = asyncio.ensure_future(asyncio.to_thread(search.search, path))
+ # A cancelled handler never awaits the walk; retrieving its outcome keeps asyncio from logging it at GC.
+ walk.add_done_callback(lambda task: None if task.cancelled() else task.exception())
+ try:
+ while not walk.done():
+ if await request.is_disconnected():
+ break
+ await asyncio.wait({walk}, timeout=0.25)
+ finally:
+ # Covers the disconnect branch and a cancelled handler alike: the thread must not keep crawling.
+ stop.set()
+ try:
+ found_model_paths = await walk
+ except ModelSearchCancelled:
+ return []
+
+ def classify_found_models() -> list[FoundModel]:
+ models_path = ApiDependencies.invoker.services.configuration.models_path
- # If the search path includes the main models directory, we need to exclude core models from the list.
- # TODO(MM2): Core models should be handled by the model manager so we can determine if they are installed
- # without needing to crawl the filesystem.
- core_models_path = pathlib.Path(models_path, "core").resolve()
- non_core_model_paths = [p for p in found_model_paths if not p.is_relative_to(core_models_path)]
+ # If the search path includes the main models directory, we need to exclude core models from the list.
+ # TODO(MM2): Core models should be handled by the model manager so we can determine if they are installed
+ # without needing to crawl the filesystem.
+ core_models_path = pathlib.Path(models_path, "core").resolve()
+ non_core_model_paths = [p for p in found_model_paths if not p.is_relative_to(core_models_path)]
- installed_models = ApiDependencies.invoker.services.model_manager.store.search_by_attr()
+ installed_models = ApiDependencies.invoker.services.model_manager.store.search_by_attr()
+ installed_paths = {str(models_path / m.path) for m in installed_models}
- scan_results: list[FoundModel] = []
+ # Check if the model is installed by comparing paths.
+ return [FoundModel(path=str(p), is_installed=str(p) in installed_paths) for p in non_core_model_paths]
- # Check if the model is installed by comparing paths, appending to the scan result.
- for p in non_core_model_paths:
- path = str(p)
- is_installed = any(str(models_path / m.path) == path for m in installed_models)
- found_model = FoundModel(path=path, is_installed=is_installed)
- scan_results.append(found_model)
+ # The store query and the path comparison are blocking work; this handler is async only to watch the request.
+ scan_results = await asyncio.to_thread(classify_found_models)
except Exception as e:
ApiDependencies.invoker.services.logger.error(
f"Error scanning '{scan_path}' for models: {type(e).__name__}: {e}"
diff --git a/invokeai/backend/model_manager/search.py b/invokeai/backend/model_manager/search.py
index 2e2462a1e1..f0a1d6af90 100644
--- a/invokeai/backend/model_manager/search.py
+++ b/invokeai/backend/model_manager/search.py
@@ -43,6 +43,10 @@ class SearchStats:
models_filtered = 0
+class ModelSearchCancelled(Exception):
+ """Raised out of `ModelSearch.search` when its `should_stop` predicate turns true mid-walk."""
+
+
class ModelSearch:
"""Searches a directory tree for models, using a callback to filter the results.
@@ -57,6 +61,7 @@ class ModelSearch:
on_search_started: Optional[Callable[[Path], None]] = None,
on_model_found: Optional[Callable[[Path], bool]] = None,
on_search_completed: Optional[Callable[[set[Path]], None]] = None,
+ should_stop: Optional[Callable[[], bool]] = None,
) -> None:
"""Create a new ModelSearch object.
@@ -65,12 +70,15 @@ class ModelSearch:
on_model_found: callback to be invoked when a model is found. The callback should return True if the model
should be included in the results.
on_search_completed: callback to be invoked when the search is completed
+ should_stop: polled before each directory is walked; returning True abandons the search with
+ `ModelSearchCancelled` (a scan whose requester has gone away should not keep crawling the disk).
"""
self.stats = SearchStats()
self.logger = InvokeAILogger.get_logger()
self.on_search_started = on_search_started
self.on_model_found = on_model_found
self.on_search_completed = on_search_completed
+ self.should_stop = should_stop
self.models_found: set[Path] = set()
def search_started(self) -> None:
@@ -99,6 +107,8 @@ class ModelSearch:
def _walk_directory(self, path: Path, max_depth: int = 20) -> None:
"""Recursively walk the directory tree, looking for models."""
+ if self.should_stop is not None and self.should_stop():
+ raise ModelSearchCancelled(f"model search of {self._directory} was cancelled")
absolute_path = Path(path)
if (
len(absolute_path.parts) - len(self._directory.parts) > max_depth
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index c32fdba1e0..e8a5629d5e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1311,6 +1311,7 @@
"saveDefaults": "Save Defaults",
"scan": "Scan",
"scanFailed": "Scan failed",
+ "stopScan": "Stop",
"scanFolderTooltip": "Scan this folder for model files",
"scanSummary_one": "{{count}} file in {{path}} · {{notInstalled}} not installed",
"scanSummary_other": "{{count}} files in {{path}} · {{notInstalled}} not installed",
diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
index a76a3094a1..db3ce9558f 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
@@ -2,7 +2,7 @@
import type { StarterModel } from '@features/models/core/types';
import type { ElementType } from 'react';
-import { Box, Checkbox, Flex, HStack, Icon, Input, InputGroup, Stack, Text } from '@chakra-ui/react';
+import { Box, Checkbox, Flex, HStack, Icon, Input, InputGroup, Spinner, Stack, Text } from '@chakra-ui/react';
import { collectBases, collectTypes } from '@features/models/core/library';
import {
DEFAULT_STARTER_MODEL_FILTERS,
@@ -92,6 +92,7 @@ export const AddModelsView = () => {
const [inplace, setInplace] = useState(true);
const { isBusy: isPulling, run: runPull } = useScopedAction();
const { isBusy: isScanning, run: runScan } = useScopedAction();
+ const scanAbortRef = useRef<AbortController | null>(null);
const [installingBundle, setInstallingBundle] = useState<string | null>(null);
const providerConfigs = useExternalProvidersSelector((snapshot) => snapshot.configs);
const configuredExternalProviders = useMemo<ReadonlySet<string>>(
@@ -271,17 +272,37 @@ export const AddModelsView = () => {
);
};
+ // Stop aborts the request; the server watches for the disconnect and
+ // abandons its directory walk, so a wrong folder does not keep crawling.
const handleScan = async () => {
+ // Enter in the field reaches here while the button reads Stop; a second
+ // scan must not replace the controller the running one is wired to.
+ if (scanAbortRef.current) {
+ return;
+ }
+
await runScan(
async (owner) => {
- const results = await scanFolderForModels(trimmed, owner.signal);
+ const abort = new AbortController();
- assertAccountScopeCurrent(owner);
- updateModelsUi({ scan: { path: trimmed, results } });
+ scanAbortRef.current = abort;
+ try {
+ const results = await scanFolderForModels(trimmed, AbortSignal.any([owner.signal, abort.signal]));
+
+ assertAccountScopeCurrent(owner);
+ updateModelsUi({ scan: { path: trimmed, results } });
+ } finally {
+ scanAbortRef.current = null;
+ }
},
- (message) => notify.error(t('models.scanFailed'), message)
+ (message, error) => {
+ if (!(error instanceof DOMException && error.name === 'AbortError')) {
+ notify.error(t('models.scanFailed'), message);
+ }
+ }
);
};
+ const handleStopScan = () => scanAbortRef.current?.abort();
return (
<Flex direction="column" h="full" minH="0">
@@ -318,9 +339,14 @@ export const AddModelsView = () => {
/>
) : null}
- {canScan ? (
+ {canScan && isScanning ? (
+ <Button size="sm" variant="outline" onClick={handleStopScan}>
+ <Spinner size="xs" />
+ {t('models.stopScan')}
+ </Button>
+ ) : canScan ? (
<Tooltip content={t('models.scanFolderTooltip')}>
- <Button loading={isScanning} size="sm" variant="solid" onClick={() => void handleScan()}>
+ <Button size="sm" variant="solid" onClick={() => void handleScan()}>
<Icon as={FolderSearchIcon} boxSize="3.5" />
{t('models.scan')}
</Button>
diff --git a/tests/app/routers/test_model_manager_authorization.py b/tests/app/routers/test_model_manager_authorization.py
index fbda8aca8b..cf1cc91182 100644
--- a/tests/app/routers/test_model_manager_authorization.py
+++ b/tests/app/routers/test_model_manager_authorization.py
@@ -5,6 +5,7 @@ routes carried no auth dependency at all, so an unauthenticated network attacker
impact was `GET /api/v2/models/scan_folder`, which enumerates an attacker-chosen filesystem path.
"""
+import time
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
@@ -131,6 +132,9 @@ def test_scan_folder_mid_scan_failure_is_a_generic_500(
"""
class ExplodingSearch:
+ def __init__(self, **kwargs: Any) -> None:
+ pass
+
def search(self, path: Path) -> None:
raise PermissionError("permission denied inside the tree")
@@ -143,6 +147,60 @@ def test_scan_folder_mid_scan_failure_is_a_generic_500(
assert "permission denied" not in response.text
+def test_scan_folder_stops_the_walk_when_the_client_disconnects(
+ enable_multiuser: Any, client: TestClient, admin_token: str, tmp_path: Path, monkeypatch: Any
+) -> None:
+ """A scan whose requester has gone away must not keep crawling: the handler signals the walker to stop."""
+ import threading
+
+ from invokeai.backend.model_manager.search import ModelSearchCancelled
+
+ observed = {"stopped": threading.Event()}
+
+ class BlockingSearch:
+ def __init__(self, should_stop: Any = None, **kwargs: Any) -> None:
+ self.should_stop = should_stop
+
+ def search(self, path: Path) -> set[Path]:
+ # Keeps walking until asked to stop; a walker that never sees the signal hangs the test.
+ deadline = time.monotonic() + 10
+ while not self.should_stop():
+ if time.monotonic() > deadline:
+ raise AssertionError("the walker was never told to stop")
+ time.sleep(0.01)
+ observed["stopped"].set()
+ raise ModelSearchCancelled("cancelled")
+
+ async def disconnected(self: Any) -> bool:
+ return True
+
+ monkeypatch.setattr("invokeai.app.api.routers.model_manager.ModelSearch", BlockingSearch)
+ monkeypatch.setattr("starlette.requests.Request.is_disconnected", disconnected)
+
+ response = client.get(f"/api/v2/models/scan_folder?scan_path={tmp_path}", headers=_auth(admin_token))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == []
+ assert observed["stopped"].is_set()
+
+
+def test_scan_folder_completes_normally_while_the_client_stays_connected(
+ enable_multiuser: Any, client: TestClient, admin_token: str, tmp_path: Path, monkeypatch: Any
+) -> None:
+ """The stop predicate exists only for a lost requester; a connected one gets the full result."""
+ (tmp_path / "model.safetensors").write_text("")
+
+ async def connected(self: Any) -> bool:
+ return False
+
+ monkeypatch.setattr("starlette.requests.Request.is_disconnected", connected)
+
+ response = client.get(f"/api/v2/models/scan_folder?scan_path={tmp_path}", headers=_auth(admin_token))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [item["path"] for item in response.json()] == [str(tmp_path / "model.safetensors")]
+
+
def test_create_image_upload_entry_requires_auth_before_the_501_stub(
enable_multiuser: Any, client: TestClient, user1_token: str
) -> None:
diff --git a/tests/test_model_search.py b/tests/test_model_search.py
index 5b5d0d34da..4ae04610ea 100644
--- a/tests/test_model_search.py
+++ b/tests/test_model_search.py
@@ -2,7 +2,7 @@ from pathlib import Path
import pytest
-from invokeai.backend.model_manager.search import ModelSearch
+from invokeai.backend.model_manager.search import ModelSearch, ModelSearchCancelled
@pytest.fixture
@@ -160,3 +160,22 @@ def test_model_search_handles_modular_diffusers_model_dirs(model_search: tuple[M
found = search.search(tmp_path)
assert found == {modular_dir}
+
+
+def test_model_search_stops_when_asked(tmp_path: Path):
+ """A stop request abandons the walk at the next directory instead of finishing the tree."""
+ visited: list[Path] = []
+ for index in range(4):
+ folder = tmp_path / f"folder{index}"
+ folder.mkdir()
+ (folder / "model.safetensors").write_text("")
+
+ def stop_after_first_model() -> bool:
+ return len(visited) > 0
+
+ search = ModelSearch(should_stop=stop_after_first_model, on_model_found=lambda path: visited.append(path) or True)
+
+ with pytest.raises(ModelSearchCancelled):
+ search.search(tmp_path)
+
+ assert len(visited) == 1