The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.
fix(assets): Start without the assets packages; --enable-assets reports what is missing and runs with assets disabled (#16580)
Simon Pinfoldd669bcfeb15c
diff --git a/app/assets/lifecycle.py b/app/assets/lifecycle.pyindex 2a2f240b4..02f86e7ab 100644--- a/app/assets/lifecycle.py+++ b/app/assets/lifecycle.py@@ -12,16 +12,21 @@ import osimport shutilimport folder_paths-from sqlalchemy import select--from app.assets.database.models import Asset, AssetContent-from app.assets.database.queries.records import delete_record-from app.assets.helpers import sql_path_under_prefix-from app.assets.services.hash_mode_state import enqueue_transition_work-from app.assets.services.hash_mode_state import record_transition_intent-from app.database.db import can_create_session, create_session++from app.database.db import can_create_session, create_session, dependencies_availablefrom comfy.cli_args import args+# Startup imports this module even without the database packages; the functions+# that need these are only called when a session can be created.+if dependencies_available():+ from sqlalchemy import select++ from app.assets.database.models import Asset, AssetContent+ from app.assets.database.queries.records import delete_record+ from app.assets.helpers import sql_path_under_prefix+ from app.assets.services.hash_mode_state import enqueue_transition_work+ from app.assets.services.hash_mode_state import record_transition_intent+_excluded_scan_roots: set[str] = set()_hash_mode_transition: str | None = Nonediff --git a/app/assets/manager.py b/app/assets/manager.pyindex 73e20bc32..73c351266 100644--- a/app/assets/manager.py+++ b/app/assets/manager.py@@ -4,25 +4,32 @@and chooses ``NoAssets`` when the requested mode cannot run."""+from __future__ import annotations+import loggingfrom typing import Any, Callable, Protocolfrom aiohttp import webfrom app.assets import mode-from app.assets.api.routes import register_assets_routesfrom app.assets.lifecycle import record_hash_mode_transition_intent, run_shutdown, run_startup-from app.assets.seeder import ScanPhase, asset_seeder-from app.assets.services.ingest import (- register_cached_output as ingest_register_cached_output,- register_executed_output as ingest_register_executed_output,- register_file_in_place,-)-from app.assets.services.path_utils import get_known_subfolder_tags-from app.assets.services.schemas import RegisteredAsset, UploadAssetView-from app.database.db import dependencies_available+from app.database.db import dependencies_available, missing_dependenciesfrom app.user_manager import UserManagerfrom comfy.cli_args import args+from utils.install_util import get_missing_requirements_message++# These need the database packages. Without them only NoAssets is used, and it+# does not touch these names.+if dependencies_available():+ from app.assets.api.routes import register_assets_routes+ from app.assets.seeder import ScanPhase, asset_seeder+ from app.assets.services.ingest import (+ register_cached_output as ingest_register_cached_output,+ register_executed_output as ingest_register_executed_output,+ register_file_in_place,+ )+ from app.assets.services.path_utils import get_known_subfolder_tags+ from app.assets.services.schemas import RegisteredAsset, UploadAssetViewclass AssetManager(Protocol):@@ -72,7 +79,8 @@ class _ArgsLike(Protocol):def _shutdown_assets() -> None:- asset_seeder.shutdown()+ if dependencies_available():+ asset_seeder.shutdown()run_shutdown()@@ -95,6 +103,8 @@ class NoAssets:def register_routes(self, app: web.Application, user_manager: UserManager | None) -> None:+ if not dependencies_available():+ returnregister_assets_routes(app)asset_seeder.disable()@@ -225,9 +235,10 @@ class AssetsEnabled:def default_asset_manager() -> AssetManager:if args.enable_assets and not dependencies_available():- logging.warning(- "Assets requested but database dependencies unavailable; asset endpoints "- "will answer 503. Please install the updated requirements.txt file."+ missing = ", ".join(missing_dependencies()) or "see the import error above"+ logging.error(+ f"--enable-assets requires packages that could not be imported: {missing}. "+ f"Assets are disabled.\n{get_missing_requirements_message()}")return NoAssets(args)return AssetsEnabled(args) if args.enable_assets else NoAssets(args)diff --git a/app/database/db.py b/app/database/db.pyindex 81ee0880a..32065ccac 100644--- a/app/database/db.py+++ b/app/database/db.py@@ -1,3 +1,4 @@+import importlibimport loggingimport osimport shutil@@ -13,6 +14,8 @@ _DB_AVAILABLE = FalseSession = NoneWriteSession = None+# The packages the imports below need; keep in step with them.+_DEPENDENCIES = ("sqlalchemy", "alembic", "blake3")try:from alembic import command@@ -48,6 +51,17 @@ def dependencies_available():return _DB_AVAILABLE+def missing_dependencies():+ """Names of the database packages that fail to import."""+ missing = []+ for name in _DEPENDENCIES:+ try:+ importlib.import_module(name)+ except ImportError:+ missing.append(name)+ return missing++def can_create_session():"""Temporary function to check if the database is available to create a sessiondiff --git a/server.py b/server.pyindex ac8719110..de0076a76 100644--- a/server.py+++ b/server.py@@ -44,8 +44,11 @@ import node_helpersfrom comfyui_version import __version__from app.frontend_management import FrontendManager, parse_versionfrom comfy_api.internal import _ComfyNodeInternal-from app.assets.services.asset_management import resolve_hash_to_pathfrom app.assets.event_log import emit+from app.database.db import dependencies_available++if dependencies_available():+ from app.assets.services.asset_management import resolve_hash_to_pathfrom app.user_manager import UserManagerfrom app.model_manager import ModelFileManager@@ -523,6 +526,8 @@ class PromptServer():# node preview, it constructs /view?filename=<asset_hash>, so this# endpoint must resolve blake3 hashes to their on-disk file paths.if filename.startswith("blake3:"):+ if not self.asset_manager.enabled:+ return web.Response(status=404)# Side-effect call: get_request_user_id raises KeyError for an unknown or# system user in multi-user mode, which is what gates hash resolution.# The returned id is deliberately unused (resolution is not owner-scoped).diff --git a/tests-unit/assets_test/services/test_noassets_parity.py b/tests-unit/assets_test/services/test_noassets_parity.pyindex 5c7b646b6..121582f95 100644--- a/tests-unit/assets_test/services/test_noassets_parity.py+++ b/tests-unit/assets_test/services/test_noassets_parity.py@@ -189,7 +189,8 @@ def test_default_asset_manager_disables_assets_when_dependencies_are_unavailableasset_manager = manager.default_asset_manager()assert isinstance(asset_manager, NoAssets)- assert "asset endpoints will answer 503" in caplog.text+ assert "--enable-assets requires packages that could not be imported" in caplog.text+ assert "Assets are disabled." in caplog.textassert "requirements.txt" in caplog.textdiff --git a/tests-unit/assets_test/test_startup_without_asset_dependencies.py b/tests-unit/assets_test/test_startup_without_asset_dependencies.pynew file mode 100644index 000000000..db783d0c9--- /dev/null+++ b/tests-unit/assets_test/test_startup_without_asset_dependencies.py@@ -0,0 +1,68 @@+import subprocess+import sys+from pathlib import Path++import pytest+++# A None entry in sys.modules makes any import of that package raise ImportError.+STARTUP_SCRIPT = (+ "import sys, runpy, comfy_kitchen; "+ "sys.modules.update(dict.fromkeys(('sqlalchemy', 'alembic', 'blake3'))); "+ "comfy_kitchen.int8_attention_is_available=lambda: False; "+ 'runpy.run_path("main.py", run_name="__main__")'+)++[email protected](autouse=True)+def autoclean_unit_test_assets():+ yield+++def run_quick_startup(tmp_path: Path, *flags: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ [+ sys.executable,+ "-c",+ STARTUP_SCRIPT,+ "--cpu",+ "--quick-test-for-ci",+ "--disable-all-custom-nodes",+ "--disable-api-nodes",+ f"--base-directory={tmp_path}",+ f"--front-end-root={tmp_path}",+ f"--database-url=sqlite:///{tmp_path / 'assets.sqlite3'}",+ *flags,+ ],+ cwd=Path(__file__).resolve().parents[2],+ capture_output=True,+ text=True,+ timeout=120,+ )+++def test_starts_without_asset_dependencies_when_assets_disabled(tmp_path: Path) -> None:+ stale_temp_file = tmp_path / "temp" / "stale.png"+ stale_temp_file.parent.mkdir()+ stale_temp_file.write_bytes(b"")++ result = run_quick_startup(tmp_path)++ assert result.returncode == 0, result.stdout + result.stderr+ assert "Traceback" not in result.stderr+ assert not stale_temp_file.exists()+++def test_enable_assets_without_dependencies_names_them_and_starts_with_assets_disabled(+ tmp_path: Path,+) -> None:+ result = run_quick_startup(tmp_path, "--enable-assets")+ output = result.stdout + result.stderr++ assert result.returncode == 0, output+ assert (+ "--enable-assets requires packages that could not be imported: "+ "sqlalchemy, alembic, blake3. Assets are disabled." in output+ )+ assert "-m pip install -r" in output+ assert "Traceback" not in output