Compare commits

...
Sign in to create a new pull request.

10 commits

Author SHA1 Message Date
Simon Pinfold
8da4669172 fix(assets): don't hit uninitialized database from /view hash resolution
With --disable-assets (or after a database init failure) init_db() never
runs and Session stays None, but /view?filename=blake3:<hash> still
called resolve_hash_to_path(), raising TypeError and returning a 500.
Workflows saved while assets were enabled trigger this on preview render
in disabled mode. Gate the hash branch on live assets availability and
return 404, which also fixes the pre-existing 500 on the degraded path.

Also copy output_ui in the disabled enrichment fast path so the
'returns a new dict' contract holds in both modes.
2026-07-28 09:22:57 +12:00
Simon Pinfold
b7c58c8371 fix(assets): harden --disable-assets from review feedback
- setup_database() also calls disable_assets_routes() so the off state
  does not depend on PromptServer construction order, and logs a notice
  when the deprecated --enable-assets no-op is passed alongside
- disabled-mode test fixture: fail fast if the server process exits
  during startup instead of burning the 90s readiness timeout, kill the
  process if terminate() hangs, and close log handles if Popen raises
- disabled enrichment test also asserts registration is never attempted
2026-07-28 08:47:42 +12:00
Simon Pinfold
d1014a5f92 feat(assets): add --disable-assets flag to turn the assets system off
With --enable-assets removed and the assets system always on, there is no
supported way to run without it. Add an explicit opt-out for the rollout
bake period: cloud multi-tenant sidecars need a guaranteed off-switch, and
QA needs a clean-fallback configuration.

When --disable-assets is passed:
- asset API routes are registered but disabled, returning a structured 503
- database initialization is skipped entirely (no sqlite file is created;
  the database currently has no non-asset users)
- the background seeder is disabled, covering startup, /object_info and
  post-execution enrich scans, and output registration
- workflow output enrichment and /upload/image asset registration are
  skipped
- the assets feature flag reports false, and supports_model_type_tags
  follows it since model_type tags are an assets-API capability

The hidden --enable-assets no-op remains accepted for launcher
compatibility; --disable-assets takes precedence since the former gates
nothing.
2026-07-28 05:44:53 +12:00
Matt Miller
c78d436b4e Merge origin/master into matt/be-786-phase-1-remove-enable-assets-from-oss-assets-always-on-cloud
Resolve server.py conflict: keep ungated asset registration (this PR)
while preserving master's subfolder tag support via get_known_subfolder_tags.
2026-07-08 22:41:32 -07:00
Matt Miller
d224df799b chore(assets): log when assets disabled due to missing DB deps
Addresses CodeRabbit review: the missing-optional-dependency fallback in
setup_database() silently disabled the assets system with no startup
message, unlike the exception path which logs. Add a warning so operators
can tell why /api/assets/* returns 503.
2026-07-01 00:39:43 -07:00
Matt Miller
a5ff07fe63 Merge remote-tracking branch 'origin/master' into matt/be-786-phase-1-remove-enable-assets-from-oss-assets-always-on-cloud 2026-07-01 00:38:27 -07:00
Matt Miller
b369532116 fix(assets): fail safe to 503 when DB unavailable; keep --enable-assets as no-op
Address automated review feedback on the always-on assets change:
- setup_database(): on DB init failure or missing dependencies, call
  disable_assets_routes() + asset_seeder.disable() so /api/assets/* returns a
  clean 503 instead of 500s against an uninitialized DB (restores the fail-safe
  the removed else-branch used to provide).
- feature_flags: derive the advertised 'assets' capability from live backend
  availability instead of hardcoding True, so clients degrade gracefully.
- cli_args: re-add --enable-assets as a hidden deprecated no-op so existing
  launchers still passing the flag don't abort argparse.
- routes: add assets_enabled() accessor for the feature-flag derivation.
2026-06-30 15:25:26 -07:00
Matt Miller
5bcb2b085c
Merge branch 'master' into matt/be-786-phase-1-remove-enable-assets-from-oss-assets-always-on-cloud 2026-06-30 14:56:56 -07:00
Matt Miller
a5446a0001
Merge branch 'master' into matt/be-786-phase-1-remove-enable-assets-from-oss-assets-always-on-cloud 2026-06-30 14:28:25 -07:00
Matt Miller
50f33ab900 feat(assets): enable asset system by default; remove --enable-assets
The asset system is now always on. Removes the --enable-assets opt-in
flag and the conditional registration it gated:

- Asset API routes are always registered (with the user manager)
- The background asset scanner always runs (hashing stays opt-in via
  --enable-asset-hashing, default off — no new blake3 cost on a default launch)
- /upload/image asset registration and output enrichment always active
- The "assets" server feature flag is now unconditionally true
- A database-init failure degrades gracefully instead of hard-exiting,
  matching the prior default-path behavior
2026-06-30 14:19:29 -07:00
11 changed files with 243 additions and 38 deletions

View file

@ -55,7 +55,7 @@ def _require_assets_feature_enabled(handler):
return _build_error_response(
503,
"SERVICE_DISABLED",
"Assets system is disabled. Start the server with --enable-assets to use this feature.",
"Assets system is unavailable.",
)
return await handler(request)
@ -103,6 +103,15 @@ def disable_assets_routes() -> None:
_ASSETS_ENABLED = False
def assets_enabled() -> bool:
"""Return whether the asset routes are currently serving requests.
Reflects live backend availability: False once disable_assets_routes() has
been called (e.g. after a database init failure or missing dependencies).
"""
return _ASSETS_ENABLED
def _build_error_response(
status: int, code: str, message: str, details: dict | None = None
) -> web.Response:

View file

@ -240,7 +240,10 @@ database_default_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "user", "comfyui.db")
)
parser.add_argument("--database-url", type=str, default=f"sqlite:///{database_default_path}", help="Specify the database URL, e.g. for an in-memory database you can use 'sqlite:///:memory:'.")
parser.add_argument("--enable-assets", action="store_true", help="Enable the assets system (API routes, database synchronization, and background scanning).")
# Deprecated no-op: the asset system is now always enabled. Kept (hidden) so that
# existing launchers/containers still passing --enable-assets don't fail argparse.
parser.add_argument("--enable-assets", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--disable-assets", action="store_true", help="Disable the assets system: asset API routes return 503, the asset database is not initialized, no background scanning runs, and uploads and workflow outputs are not registered as assets.")
parser.add_argument("--enable-asset-hashing", action="store_true", help="Compute blake3 content hashes when scanning assets. Hashing enables future asset-portability features (deduplication, cross-machine model resolution) but adds startup cost and per-output cost on large models directories. Off by default; enable to opt in.")
parser.add_argument("--feature-flag", type=str, action='append', default=[], metavar="KEY[=VALUE]", help="Set a server feature flag. Use KEY=VALUE to set an explicit value, or bare KEY to set it to true. Can be specified multiple times. Boolean values (true/false) and numbers are auto-converted. Examples: --feature-flag show_signin_button=true or --feature-flag show_signin_button")
parser.add_argument("--list-feature-flags", action="store_true", help="Print the registry of known CLI-settable feature flags as JSON and exit.")

View file

@ -104,7 +104,7 @@ _CORE_FEATURE_FLAGS: dict[str, Any] = {
"max_upload_size": args.max_upload_size * 1024 * 1024, # Convert MB to bytes
"extension": {"manager": {"supports_v4": True}},
"node_replacements": True,
"assets": args.enable_assets,
"assets": True,
}
# CLI-provided flags cannot overwrite core flags
@ -163,4 +163,17 @@ def get_server_features() -> dict[str, Any]:
Returns:
Dictionary of server feature flags
"""
return SERVER_FEATURE_FLAGS.copy()
features = SERVER_FEATURE_FLAGS.copy()
# Advertise the assets capability based on live backend availability rather
# than a static default, so clients degrade gracefully when the database
# failed to initialize or its dependencies are missing.
try:
from app.assets.api.routes import assets_enabled
features["assets"] = assets_enabled()
except Exception:
features["assets"] = False
if not features["assets"]:
# model_type tags are an assets-API capability; don't advertise them
# when the assets backend is disabled or unavailable.
features["supports_model_type_tags"] = False
return features

View file

@ -6,14 +6,14 @@ import os
def enrich_output_with_assets(output_ui: dict) -> dict:
"""Register file-type output entries as assets and inject their ``id``.
Runs at output-processing time, once per produced output, when
--enable-assets is set. Returns a new dict; entries without a resolvable
Runs at output-processing time, once per produced output, unless
--disable-assets is set. Returns a new dict; entries without a resolvable
on-disk file path are left unchanged. Errors are caught per-entry so a
failure never blocks execution or the other entries.
"""
from comfy.cli_args import args
if not args.enable_assets:
return output_ui
if args.disable_assets:
return dict(output_ui)
import folder_paths
from app.assets.services.ingest import register_file_in_place, DependencyMissingError

34
main.py
View file

@ -20,6 +20,7 @@ from app.logger import setup_logger
setup_logger(log_level=args.verbose, use_stdout=args.log_stdout)
from app.assets.seeder import asset_seeder
from app.assets.api.routes import disable_assets_routes
from app.assets.services import register_output_files
import itertools
import utils.extra_config
@ -458,12 +459,25 @@ def cleanup_temp():
def setup_database():
if args.disable_assets:
logging.info("Assets system disabled via --disable-assets; skipping database initialization and asset scanning.")
if args.enable_assets:
logging.info("--enable-assets is a deprecated no-op and does not override --disable-assets.")
disable_assets_routes()
asset_seeder.disable()
return
try:
if dependencies_available():
init_db()
if args.enable_assets:
if asset_seeder.start(roots=("models", "input", "output"), prune_first=True, compute_hashes=args.enable_asset_hashing):
logging.info("Background asset scan initiated for models, input, output")
if asset_seeder.start(roots=("models", "input", "output"), prune_first=True, compute_hashes=args.enable_asset_hashing):
logging.info("Background asset scan initiated for models, input, output")
else:
# Optional DB dependencies are missing, so init_db() is skipped and the
# asset backend has no database. Disable assets so /api/assets/* returns
# a clean 503 instead of 500s against an uninitialized DB.
logging.warning("Optional database dependencies are missing; assets system disabled.")
disable_assets_routes()
asset_seeder.disable()
except Exception as e:
if "database is locked" in str(e):
logging.error(
@ -472,16 +486,10 @@ def setup_database():
" --database-url sqlite:///path/to/another.db"
)
sys.exit(1)
if args.enable_assets:
logging.error(
f"Failed to initialize database: {e}\n"
"The --enable-assets flag requires a working database connection.\n"
"To resolve this, try one of the following:\n"
" 1. Install the latest requirements: pip install -r requirements.txt\n"
" 2. Specify an alternative database URL: --database-url sqlite:///path/to/your.db\n"
" 3. Use an in-memory database: --database-url sqlite:///:memory:"
)
sys.exit(1)
# The database is unusable. Fail safe by disabling assets so endpoints
# return 503 (service unavailable) rather than 500s on every request.
disable_assets_routes()
asset_seeder.disable()
logging.error(f"Failed to initialize database. Please ensure you have installed the latest requirements. If the error persists, please report this as in future the database will be required: {e}")

View file

@ -44,7 +44,7 @@ from comfyui_version import __version__
from app.frontend_management import FrontendManager, parse_version
from comfy_api.internal import _ComfyNodeInternal
from app.assets.seeder import asset_seeder
from app.assets.api.routes import register_assets_routes
from app.assets.api.routes import register_assets_routes, assets_enabled
from app.assets.services.ingest import register_file_in_place
from app.assets.services.path_utils import get_known_subfolder_tags
from app.assets.services.asset_management import resolve_hash_to_path
@ -253,11 +253,12 @@ class PromptServer():
else args.front_end_root
)
logging.info(f"[Prompt Server] web root: {self.web_root}")
if args.enable_assets:
register_assets_routes(self.app, self.user_manager)
else:
if args.disable_assets:
# Register the routes without enabling them so /api/assets/* returns
# a structured 503 rather than a 404.
register_assets_routes(self.app)
asset_seeder.disable()
else:
register_assets_routes(self.app, self.user_manager)
routes = web.RouteTableDef()
self.routes = routes
self.last_node_id = None
@ -439,7 +440,7 @@ class PromptServer():
resp = {"name" : filename, "subfolder": subfolder, "type": image_upload_type}
if args.enable_assets:
if not args.disable_assets:
try:
tag = image_upload_type if image_upload_type in ("input", "output") else "input"
tags = [tag]
@ -522,6 +523,12 @@ 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:"):
# Hash resolution requires the asset database. When assets
# are disabled (--disable-assets) or unavailable (DB init
# failure) the database was never initialized, so treat the
# hash as unresolvable rather than erroring on a session.
if not assets_enabled():
return web.Response(status=404)
owner_id = self.user_manager.get_request_user_id(request)
result = resolve_hash_to_path(filename, owner_id=owner_id)
if result is None:

View file

@ -109,7 +109,6 @@ def comfy_url_and_proc(comfy_tmp_base_dir: Path, request: pytest.FixtureRequest)
"main.py",
f"--base-directory={str(comfy_tmp_base_dir)}",
f"--database-url={db_url}",
"--enable-assets",
"--listen",
"127.0.0.1",
"--port",

View file

@ -0,0 +1,135 @@
"""Boot ComfyUI with --disable-assets and verify the assets system is inert."""
import contextlib
import socket
import subprocess
import sys
import time
from pathlib import Path
import pytest
import requests
@pytest.fixture(autouse=True)
def autoclean_unit_test_assets():
"""Override the package-level autouse cleaner: it boots the regular
(assets-enabled) server, which this module does not need."""
yield
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _wait_assets_disabled(base: str, proc: subprocess.Popen, timeout: float = 90.0) -> None:
start = time.time()
last_err = None
while time.time() - start < timeout:
if proc.poll() is not None:
raise RuntimeError(f"ComfyUI exited early with code {proc.returncode}")
try:
r = requests.get(base + "/api/assets", timeout=5)
if r.status_code == 503:
return
last_err = RuntimeError(f"unexpected status {r.status_code}")
except Exception as e:
last_err = e
time.sleep(0.25)
raise RuntimeError(f"ComfyUI HTTP did not become ready: {last_err}")
@pytest.fixture(scope="module")
def disabled_comfy(tmp_path_factory: pytest.TempPathFactory):
"""Boot a ComfyUI subprocess with --disable-assets.
Yields (base_url, db_path) where db_path is where the sqlite database
would be created if the assets system initialized it.
"""
base_dir = tmp_path_factory.mktemp("comfyui-assets-disabled")
for sub in ("models", "custom_nodes", "input", "output", "temp", "user"):
(base_dir / sub).mkdir(parents=True, exist_ok=True)
db_path = base_dir / "assets-disabled.sqlite3"
logs_dir = base_dir / "logs"
logs_dir.mkdir(exist_ok=True)
out_log = open(logs_dir / "stdout.log", "w", buffering=1)
err_log = open(logs_dir / "stderr.log", "w", buffering=1)
comfy_root = Path(__file__).resolve().parent.parent.parent
port = _free_port()
try:
proc = subprocess.Popen(
args=[
sys.executable,
"main.py",
f"--base-directory={str(base_dir)}",
f"--database-url=sqlite:///{db_path}",
"--disable-assets",
"--listen",
"127.0.0.1",
"--port",
str(port),
"--cpu",
],
stdout=out_log,
stderr=err_log,
cwd=str(comfy_root),
)
except Exception:
out_log.close()
err_log.close()
raise
base_url = f"http://127.0.0.1:{port}"
try:
_wait_assets_disabled(base_url, proc)
yield base_url, db_path
finally:
if proc.poll() is None:
with contextlib.suppress(Exception):
proc.terminate()
try:
proc.wait(timeout=15)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=15)
out_log.close()
err_log.close()
def test_assets_routes_return_503(disabled_comfy):
base_url, _ = disabled_comfy
for path in ("/api/assets", "/api/tags", "/api/assets/seed/status"):
r = requests.get(base_url + path, timeout=30)
assert r.status_code == 503, (path, r.text)
assert r.json()["error"]["code"] == "SERVICE_DISABLED"
def test_database_not_created(disabled_comfy):
_, db_path = disabled_comfy
assert not db_path.exists()
def test_seed_scan_rejected(disabled_comfy):
base_url, _ = disabled_comfy
r = requests.post(base_url + "/api/assets/seed", json={"roots": ["models"]}, timeout=30)
assert r.status_code == 503
def test_view_blake3_hash_returns_404(disabled_comfy):
base_url, _ = disabled_comfy
r = requests.get(base_url + "/view", params={"filename": "blake3:" + "0" * 64}, timeout=30)
assert r.status_code == 404
def test_upload_image_skips_asset_registration(disabled_comfy):
base_url, db_path = disabled_comfy
files = {"image": ("disabled-mode-test.png", b"\x89PNG fake bytes", "image/png")}
r = requests.post(base_url + "/upload/image", files=files, timeout=30)
assert r.status_code == 200, r.text
body = r.json()
assert body["name"] == "disabled-mode-test.png"
assert "asset" not in body
assert not db_path.exists()

View file

@ -5,9 +5,9 @@ import unittest
from unittest.mock import MagicMock, patch
def _make_args(enable_assets: bool):
def _make_args(disable_assets: bool):
a = types.SimpleNamespace()
a.enable_assets = enable_assets
a.disable_assets = disable_assets
return a
@ -22,9 +22,9 @@ def _make_register_result(ref_id="ref-id-2"):
_DEFAULT_BASE = os.path.join(__import__("tempfile").gettempdir(), "asset-enrichment-test-base")
def _mocked_modules(*, enable_assets=True, register_file_in_place=None, directory=_DEFAULT_BASE):
def _mocked_modules(*, disable_assets=False, register_file_in_place=None, directory=_DEFAULT_BASE):
return {
"comfy.cli_args": MagicMock(args=_make_args(enable_assets)),
"comfy.cli_args": MagicMock(args=_make_args(disable_assets)),
"folder_paths": MagicMock(get_directory_by_type=MagicMock(return_value=directory)),
"app.assets.services.ingest": MagicMock(
register_file_in_place=register_file_in_place or MagicMock(return_value=_make_register_result()),
@ -33,10 +33,10 @@ def _mocked_modules(*, enable_assets=True, register_file_in_place=None, director
}
def _call(output_ui, *, enable_assets=True, file_exists=True, register_result=None, directory=_DEFAULT_BASE):
def _call(output_ui, *, disable_assets=False, file_exists=True, register_result=None, directory=_DEFAULT_BASE):
register_mock = MagicMock(return_value=register_result or _make_register_result())
mocked = _mocked_modules(
enable_assets=enable_assets,
disable_assets=disable_assets,
register_file_in_place=register_mock,
directory=directory,
)
@ -54,9 +54,19 @@ def _call(output_ui, *, enable_assets=True, file_exists=True, register_result=No
class TestEnrichOutputWithAssets(unittest.TestCase):
def test_disabled_returns_unchanged(self):
register_mock = MagicMock(return_value=_make_register_result())
mocked = _mocked_modules(disable_assets=True, register_file_in_place=register_mock)
output = {"images": [{"filename": "a.png", "subfolder": "", "type": "output"}]}
result = _call(output, enable_assets=False)
with patch.dict("sys.modules", mocked), \
patch("os.path.isfile", return_value=True):
import importlib
import comfy_execution.asset_enrichment as mod
importlib.reload(mod)
result = mod.enrich_output_with_assets(output)
self.assertNotIn("id", result["images"][0])
register_mock.assert_not_called()
def test_non_list_value_passed_through(self):
output = {"text": "hello"}

View file

@ -1,5 +1,7 @@
"""Tests for feature flags functionality."""
from unittest.mock import patch
import pytest
from comfy_api.feature_flags import (
@ -26,7 +28,8 @@ class TestFeatureFlags:
def test_get_server_features_contains_expected_flags(self):
"""Test that server features contain expected flags."""
features = get_server_features()
with patch("app.assets.api.routes.assets_enabled", return_value=True):
features = get_server_features()
assert "supports_preview_metadata" in features
assert features["supports_preview_metadata"] is True
assert "supports_model_type_tags" in features
@ -34,6 +37,20 @@ class TestFeatureFlags:
assert "max_upload_size" in features
assert isinstance(features["max_upload_size"], (int, float))
def test_assets_flag_reflects_live_availability(self):
"""The assets capability mirrors assets_enabled() rather than a static default."""
with patch("app.assets.api.routes.assets_enabled", return_value=True):
assert get_server_features()["assets"] is True
with patch("app.assets.api.routes.assets_enabled", return_value=False):
assert get_server_features()["assets"] is False
def test_model_type_tags_follow_assets_availability(self):
"""supports_model_type_tags is an assets capability: off when assets are off."""
with patch("app.assets.api.routes.assets_enabled", return_value=False):
features = get_server_features()
assert features["assets"] is False
assert features["supports_model_type_tags"] is False
def test_get_connection_feature_with_missing_sid(self):
"""Test getting feature for non-existent session ID."""
sockets_metadata = {}

View file

@ -1,4 +1,6 @@
"""Simplified tests for WebSocket feature flags functionality."""
from unittest.mock import patch
from comfy_api import feature_flags
@ -7,7 +9,8 @@ class TestWebSocketFeatureFlags:
def test_server_feature_flags_response(self):
"""Test server feature flags are properly formatted."""
features = feature_flags.get_server_features()
with patch("app.assets.api.routes.assets_enabled", return_value=True):
features = feature_flags.get_server_features()
# Check expected server features
assert "supports_preview_metadata" in features
@ -67,7 +70,8 @@ class TestWebSocketFeatureFlags:
assert "supports_preview_metadata" in client_message["data"]
# Server response format (what would be sent)
server_features = feature_flags.get_server_features()
with patch("app.assets.api.routes.assets_enabled", return_value=True):
server_features = feature_flags.get_server_features()
server_message = {
"type": "feature_flags",
"data": server_features