Repository navigation
feat(generate): take comfy-sdk as a function-scope-only dependency #1209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
209b0df
feat(generate): take comfy-sdk as a function-scope-only dependency
mattmillerai ba128aa
fix(generate): scope the Router base-URL bridge and name a broken SDK
mattmillerai ff7344c
fix(generate): serialise the Router base-URL bridge across overlappin…
mattmillerai faa67ce
docs(adr): record comfy-sdk as a function-scope-only dependency
mattmillerai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| """Thin accessor for the Router-backed ``comfy generate`` models API. | ||
|
|
||
| The ``comfy-sdk`` ``Comfy`` client pulls in pydantic, which loads the compiled | ||
| ``pydantic_core`` extension. A ``comfy`` process that has loaded it holds the | ||
| .pyd/.so open for its whole lifetime, and on Windows an open DLL cannot be | ||
| replaced — so if it were loaded on a path ``comfy install`` walks, uv could not | ||
| upgrade pydantic_core when ComfyUI's ``requirements.txt`` resolves a different | ||
| version (os error 5). ``generate`` is a ``LazyCommand`` in ``comfy_cli.cmdline``, | ||
| so the import stays reachable only from the Router ``generate`` path. | ||
|
|
||
| **Lazy-import rule:** ``comfy_sdk`` must be imported *only* inside a function, | ||
| never at module scope — not here and not anywhere else reachable from | ||
| ``comfy_cli.cmdline``. ``tests/comfy_cli/test_tracking_lazy_import.py`` guards | ||
| this: importing this module (and ``generate.app``) must not load ``comfy_sdk`` | ||
| or ``pydantic_core``. Importing this module from ``app.py`` is fine — it stays | ||
| SDK-free at module scope. The decision is recorded in | ||
| ``docs/adr/DEPENDENCIES-0019-load-comfy-sdk-only-inside-the-router-generate-path.md``. | ||
|
|
||
| **Auth:** the SDK sends the key as ``Authorization: Bearer`` to Router — that is | ||
| the SDK's own contract with Router and cannot be changed from here. It is *not* | ||
| what the partner-API proxy accepts: comfy-api's ``comfy_firebase_auth.go`` reads | ||
| ``comfyui-`` keys from ``X-API-Key`` only and validates a Bearer value as a | ||
| Firebase JWT, which is why ``client._auth_headers`` splits the two. Confirm Router | ||
| accepts a Bearer ``comfyui-`` key end to end when the first caller lands. The SDK | ||
| client also does not send the ``Comfy-Env`` / ``Comfy-Usage-Source`` / | ||
| ``User-Agent`` headers that ``client._auth_headers`` adds. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import contextlib | ||
| import os | ||
| import threading | ||
|
|
||
| from comfy_cli.command.generate.client import ApiError | ||
|
|
||
| # The bridge mutates the process environment, so overlapping calls must not | ||
| # interleave their guard / override / construction / restore. | ||
| _BRIDGE_LOCK = threading.Lock() | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def _router_base_url_bridge(router_var: str): | ||
| """Point the SDK's Router variable at ``COMFY_API_BASE_URL`` for one construction. | ||
|
|
||
| The SDK's ``Comfy()`` has no base-URL kwarg and resolves the Router host from | ||
| its Router variable at construction only, so a custom ``COMFY_API_BASE_URL`` | ||
| deployment is bridged onto it while ``Comfy()`` runs — when the Router | ||
| variable is unset — and the process environment is restored afterwards so | ||
| later calls and child processes see what the user set. The whole lifecycle | ||
| runs under ``_BRIDGE_LOCK`` so overlapping calls each construct against the | ||
| configured target. | ||
| """ | ||
| # TODO: drop once comfy-sdk exposes router_base_url= | ||
| with _BRIDGE_LOCK: | ||
| # Normalised like ``spec.base_url()``; blank counts as unset. | ||
| api_base_url = (os.environ.get("COMFY_API_BASE_URL") or "").strip().rstrip("/") | ||
| if (os.environ.get(router_var) or "").strip() or not api_base_url: | ||
| yield | ||
| return | ||
| previous = os.environ.get(router_var) | ||
| os.environ[router_var] = api_base_url | ||
| try: | ||
| yield | ||
| finally: | ||
| if previous is None: | ||
| os.environ.pop(router_var, None) | ||
| else: | ||
| os.environ[router_var] = previous | ||
|
|
||
|
|
||
| def router_models(api_key: str, *, timeout: float | None = None): | ||
| """Return the ``models`` API of a Router-backed ``comfy-sdk`` client. | ||
|
|
||
| Imports ``comfy_sdk`` lazily (see the module docstring); a missing SDK is | ||
| wrapped into an :class:`ApiError` telling the user how to recover rather | ||
| than surfacing a bare ``ImportError``, and an SDK that is installed but fails | ||
| to import (e.g. a broken pydantic) names the real cause. | ||
| """ | ||
| try: | ||
| from comfy_sdk import ROUTER_BASE_URL_ENV_VAR, Comfy | ||
| except ImportError as exc: | ||
| if isinstance(exc, ModuleNotFoundError) and exc.name == "comfy_sdk": | ||
| msg = "comfy generate needs comfy-sdk; run `pip install -U comfy-cli`" | ||
| else: | ||
| msg = ( | ||
| f"comfy-sdk is installed but failed to import ({exc}); its install or a " | ||
| "dependency such as pydantic is broken — reinstall it with " | ||
| "`pip install --force-reinstall comfy-sdk`" | ||
| ) | ||
| # The message is also the body: callers that render ``status`` + ``body`` | ||
| # for HTTP errors still show the recovery hint. | ||
| raise ApiError(0, msg, msg) from exc | ||
|
|
||
| with _router_base_url_bridge(ROUTER_BASE_URL_ENV_VAR): | ||
| # ``Comfy(timeout=None)`` disables the SDK's own 30s default, so only pass | ||
| # an explicit timeout through. | ||
| if timeout is None: | ||
| return Comfy(api_key=api_key).models | ||
| return Comfy(api_key=api_key, timeout=timeout).models | ||
106 changes: 106 additions & 0 deletions
106
docs/adr/DEPENDENCIES-0019-load-comfy-sdk-only-inside-the-router-generate-path.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| # ADR-DEPENDENCIES-0019: Load comfy-sdk Only Inside the Router Generate Path | ||
|
|
||
| Date: 2026-11-27 | ||
|
|
||
| ## Status | ||
|
|
||
| Proposed | ||
|
|
||
| Relation: Builds on | ||
| [ADR-DEPENDENCIES-0001](DEPENDENCIES-0001-delegate-unified-resolution-to-comfyui-manager.md). | ||
| comfy-cli still delegates unified dependency resolution to ComfyUI-Manager; | ||
| this record only governs when the CLI's own runtime dependency on `comfy-sdk` | ||
| may be loaded. | ||
|
|
||
| ## Context | ||
|
|
||
| `comfy generate` is moving onto Comfy's Router service, whose first-party | ||
| Python client is `comfy-sdk`. The SDK depends on pydantic, which loads the | ||
| compiled `pydantic_core` extension. A `comfy` process that has loaded that | ||
| extension keeps the `.pyd`/`.so` open for its lifetime, and on Windows an open | ||
| DLL cannot be replaced. `comfy install` runs `uv pip install` of ComfyUI's | ||
| requirements into the same environment, so if the extension were loaded on that | ||
| path, uv could not upgrade `pydantic_core` when ComfyUI resolves a different | ||
| version (os error 5). The existing `mixpanel<5` pin exists for the same reason. | ||
|
|
||
| The SDK also resolves the Router host only from its own environment variable | ||
| (`ROUTER_BASE_URL_ENV_VAR`, currently `COMFY_ROUTER_BASE_URL`) at client | ||
| construction, with no base-URL argument, while comfy-cli users point the CLI at | ||
| a non-production deployment with `COMFY_API_BASE_URL`. | ||
|
|
||
| ## Decision | ||
|
|
||
| - `comfy-sdk>=0.6.0` is a regular runtime dependency of comfy-cli. | ||
| - `comfy_sdk` is imported only inside a function, never at module scope in any | ||
| module reachable from `comfy_cli.cmdline`. The single entry point is | ||
| `router_models()` in `comfy_cli/command/generate/router_client.py`; the | ||
| `generate` command is a `LazyCommand`, so the import is reachable only from | ||
| the Router `generate` path. | ||
| - A missing SDK, or an installed SDK that fails to import, becomes an | ||
| `ApiError` that names the cause and the recovery command, not a bare | ||
| `ImportError`. | ||
| - Compatibility contract: when the SDK's Router variable is unset and | ||
| `COMFY_API_BASE_URL` is set, `router_models()` copies the normalised | ||
| `COMFY_API_BASE_URL` into the variable the SDK publishes, only while the | ||
| client is constructed and under a module lock, and restores the environment | ||
| afterwards. | ||
|
|
||
| ## Alternatives considered | ||
|
|
||
| - Import the SDK at module scope like other dependencies. Rejected: it loads | ||
| `pydantic_core` on every `comfy` invocation, including `comfy install`, and | ||
| reintroduces the Windows locked-DLL failure. | ||
| - Make the SDK an optional extra. Rejected: `comfy generate` would fail on a | ||
| default install, and the lazy import already removes the install-time cost. | ||
| - Vendor or reimplement the Router client. Rejected: it creates a second client | ||
| that drifts from the first-party SDK as Router changes. | ||
| - Set the Router variable for the whole process. Rejected: later calls and | ||
| child processes (including ComfyUI started by the CLI) would inherit a value | ||
| the user never set. | ||
|
|
||
| ## What we reject | ||
|
|
||
| - A module-scope `import comfy_sdk` (or any module that imports it at module | ||
| scope) anywhere reachable from `comfy_cli.cmdline`. | ||
| - Hardcoding the SDK's Router variable name instead of reading the one the SDK | ||
| publishes, which would let an SDK rename silently send traffic to production. | ||
|
|
||
| ## Consequences | ||
|
|
||
| ### Positive | ||
|
|
||
| - Installs and non-generate commands never load pydantic, so the Windows | ||
| `comfy install` path keeps working. | ||
| - Router calls use the first-party client, so Router changes arrive with SDK | ||
| upgrades. | ||
|
|
||
| ### Negative | ||
|
|
||
| - Every new Router caller must go through the lazy accessor; a careless import | ||
| elsewhere breaks the invariant (the guard test catches it). | ||
| - The environment bridge is a workaround tied to undocumented SDK behaviour. | ||
|
|
||
| ### Known limits | ||
|
|
||
| - The SDK sends the key as `Authorization: Bearer`; Router accepting a | ||
| `comfyui-` key that way must be confirmed end to end when the first caller | ||
| lands. | ||
| - `router_models()` returns the SDK's `models` API, not the owning client, so | ||
| callers cannot close its connection pool deterministically. Revisit the | ||
| return shape when the first caller lands. | ||
|
|
||
| ## Validation | ||
|
|
||
| - `tests/comfy_cli/test_tracking_lazy_import.py` fails if importing | ||
| `comfy_cli.command.generate.app` or `router_client` loads `comfy_sdk`, | ||
| `comfy_low` or `pydantic_core`, and checks the missing- and broken-SDK errors. | ||
| - `tests/comfy_cli/command/generate/test_router_client.py` covers the bridge's | ||
| scoping, restore, normalisation and overlapping calls, and pins that the | ||
| installed SDK still names `COMFY_ROUTER_BASE_URL`. | ||
|
|
||
| ## Revisit triggers | ||
|
|
||
| - `comfy-sdk` exposes a base-URL argument: remove the environment bridge. | ||
| - `comfy-sdk` ships a new major version, or drops pydantic. | ||
| - Router changes how it accepts `comfyui-` keys. | ||
| - A Windows `comfy install` regression is traced to a loaded `pydantic_core`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| """Tests for the Router client accessor — base-URL bridge and timeout pass-through. | ||
|
|
||
| A fake ``comfy_sdk`` stands in for the real one so these record what the | ||
| accessor hands ``Comfy()``; the real import is covered in | ||
| ``tests/comfy_cli/test_tracking_lazy_import.py``. | ||
| """ | ||
|
|
||
| import os | ||
| import sys | ||
| import threading | ||
| import types | ||
|
|
||
| import pytest | ||
|
|
||
| from comfy_cli.command.generate import router_client | ||
|
|
||
|
|
||
| class _FakeComfy: | ||
| calls: list[dict] = [] | ||
|
|
||
| router_urls: list[str | None] = [] | ||
|
|
||
| def __init__(self, **kwargs): | ||
| _FakeComfy.calls.append(kwargs) | ||
| # The real SDK reads the Router host at construction, so record it here. | ||
| _FakeComfy.router_urls.append(os.environ.get("COMFY_ROUTER_BASE_URL")) | ||
| self.models = ("models", kwargs) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def fake_sdk(monkeypatch): | ||
| _FakeComfy.calls = [] | ||
| _FakeComfy.router_urls = [] | ||
| monkeypatch.setitem( | ||
| sys.modules, | ||
| "comfy_sdk", | ||
| types.SimpleNamespace(Comfy=_FakeComfy, ROUTER_BASE_URL_ENV_VAR="COMFY_ROUTER_BASE_URL"), | ||
| ) | ||
| # setenv first so teardown restores the pre-test state even after | ||
| # router_models writes the var itself. | ||
| monkeypatch.setenv("COMFY_ROUTER_BASE_URL", "") | ||
| monkeypatch.delenv("COMFY_ROUTER_BASE_URL") | ||
| monkeypatch.delenv("COMFY_API_BASE_URL", raising=False) | ||
| return _FakeComfy | ||
|
|
||
|
|
||
| def test_returns_the_clients_models_api(fake_sdk): | ||
| assert router_client.router_models("comfyui-k") == ("models", {"api_key": "comfyui-k"}) | ||
|
|
||
|
|
||
| def test_omitted_timeout_keeps_the_sdk_default(fake_sdk): | ||
| router_client.router_models("comfyui-k") | ||
| assert "timeout" not in fake_sdk.calls[-1] | ||
|
|
||
|
|
||
| def test_explicit_timeout_is_passed_through(fake_sdk): | ||
| router_client.router_models("comfyui-k", timeout=5.0) | ||
| assert fake_sdk.calls[-1]["timeout"] == 5.0 | ||
|
|
||
|
|
||
| def test_api_base_url_is_bridged_onto_the_router_var(fake_sdk, monkeypatch): | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", "https://stagingapi.example") | ||
| router_client.router_models("comfyui-k") | ||
| assert fake_sdk.router_urls[-1] == "https://stagingapi.example" | ||
|
|
||
|
|
||
| def test_bridge_is_scoped_to_construction(fake_sdk, monkeypatch): | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", "https://stagingapi.example") | ||
| router_client.router_models("comfyui-k") | ||
| assert "COMFY_ROUTER_BASE_URL" not in os.environ | ||
| # A later change to COMFY_API_BASE_URL is honoured, not shadowed by the first call. | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", "https://other.example") | ||
| router_client.router_models("comfyui-k") | ||
| assert fake_sdk.router_urls[-1] == "https://other.example" | ||
|
|
||
|
|
||
| def test_bridged_url_is_normalised(fake_sdk, monkeypatch): | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", " https://stagingapi.example/ ") | ||
| router_client.router_models("comfyui-k") | ||
| assert fake_sdk.router_urls[-1] == "https://stagingapi.example" | ||
|
|
||
|
|
||
| def test_blank_api_base_url_is_not_bridged(fake_sdk, monkeypatch): | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", " ") | ||
| router_client.router_models("comfyui-k") | ||
| assert fake_sdk.router_urls[-1] is None | ||
|
|
||
|
|
||
| def test_explicit_router_base_url_wins(fake_sdk, monkeypatch): | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", "https://stagingapi.example") | ||
| monkeypatch.setenv("COMFY_ROUTER_BASE_URL", "https://router.example") | ||
| router_client.router_models("comfyui-k") | ||
| assert fake_sdk.router_urls[-1] == "https://router.example" | ||
| assert os.environ["COMFY_ROUTER_BASE_URL"] == "https://router.example" | ||
|
|
||
|
|
||
| def test_no_base_url_leaves_the_router_var_unset(fake_sdk): | ||
| router_client.router_models("comfyui-k") | ||
| assert fake_sdk.router_urls[-1] is None | ||
| assert "COMFY_ROUTER_BASE_URL" not in os.environ | ||
|
|
||
|
|
||
| def test_bridge_is_restored_when_construction_raises(fake_sdk, monkeypatch): | ||
| def boom(**kwargs): | ||
| raise ValueError("bad url") | ||
|
|
||
| monkeypatch.setattr(sys.modules["comfy_sdk"], "Comfy", boom) | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", "https://stagingapi.example") | ||
| with pytest.raises(ValueError): | ||
| router_client.router_models("comfyui-k") | ||
| assert "COMFY_ROUTER_BASE_URL" not in os.environ | ||
|
|
||
|
|
||
| def test_real_sdk_reads_the_router_var_the_bridge_sets(): | ||
| """The bridge writes whatever variable the installed SDK names; pin that the | ||
| SDK still reads it, so an SDK rename cannot silently route to production.""" | ||
| comfy_sdk = pytest.importorskip("comfy_sdk") | ||
| assert comfy_sdk.ROUTER_BASE_URL_ENV_VAR == "COMFY_ROUTER_BASE_URL" | ||
|
|
||
|
|
||
| def test_overlapping_calls_each_construct_against_the_bridged_url(fake_sdk, monkeypatch): | ||
| # Without serialisation, B sees A's override as a user-set Router var, skips its | ||
| # own, and then constructs after A has restored the env — on the SDK default. | ||
| a_in_construction = threading.Event() | ||
| b_entering_bridge = threading.Event() | ||
| a_done = threading.Event() | ||
| seen: dict[str, str | None] = {} | ||
| real_lock = router_client._BRIDGE_LOCK | ||
|
|
||
| class _SignallingLock: | ||
| def __enter__(self): | ||
| if threading.current_thread().name == "b": | ||
| b_entering_bridge.set() | ||
| return real_lock.__enter__() | ||
|
|
||
| def __exit__(self, *exc): | ||
| return real_lock.__exit__(*exc) | ||
|
|
||
| def comfy(**kwargs): | ||
| name = threading.current_thread().name | ||
| if name == "a": | ||
| a_in_construction.set() | ||
| # Hold A's override until B has reached the bridge. | ||
| assert b_entering_bridge.wait(timeout=5) | ||
| else: | ||
| a_done.wait(timeout=5) | ||
| seen[name] = os.environ.get("COMFY_ROUTER_BASE_URL") | ||
| return types.SimpleNamespace(models="models") | ||
|
|
||
| def run_a(): | ||
| router_client.router_models("comfyui-k") | ||
| a_done.set() | ||
|
|
||
| monkeypatch.setattr(sys.modules["comfy_sdk"], "Comfy", comfy) | ||
| monkeypatch.setattr(router_client, "_BRIDGE_LOCK", _SignallingLock()) | ||
| monkeypatch.setenv("COMFY_API_BASE_URL", "https://stagingapi.example") | ||
| a = threading.Thread(target=run_a, name="a") | ||
| b = threading.Thread(target=router_client.router_models, args=("comfyui-k",), name="b") | ||
| a.start() | ||
| assert a_in_construction.wait(timeout=5) | ||
| b.start() | ||
| a.join(timeout=10) | ||
| b.join(timeout=10) | ||
| assert seen == {"a": "https://stagingapi.example", "b": "https://stagingapi.example"} | ||
| assert "COMFY_ROUTER_BASE_URL" not in os.environ |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.