Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ the fuller account of each version, including verification notes.

### Added

- `BudgetExceeded`, `BudgetCheckUnavailable` and `ByokCredentialRejected` in
`comfy_sdk.router_exceptions`, for the Router buckets `budget_exceeded`,
`budget_check_unavailable` and `byok_credential_rejected` from the synced Router spec.
`BudgetExceeded` is a `402` for a hard spend cap that has been reached; it is not
`InsufficientCredits`, and a bare `402` naming no bucket still reads as that.
`BudgetCheckUnavailable` is a `503` for a spend cap that could not be checked; the contract says
to retry after `Retry-After` (carried on `retry_after`), and like `ServiceUnavailable` the
default retry policy does not make that retry (`RetryPolicy(retry_possibly_in_flight=True)`
opts in, with the same `Idempotency-Key`). `ByokCredentialRejected` is a `401` for a provider
key supplied for the call that the provider refused; sending the same key again is refused the
same way. Before this, all three arrived as a bare `RouterError`.
- A `text/event-stream` success from `models.run` (the run route's stream-direct answer to a
body sending `stream: true`) is now a declared case: the event stream is read whole and
returned as a `BinaryResult`, as any other non-JSON success already was.

- `respond_async=True` on `models.run` and `models.run_detailed` (and the `AsyncModels` twins):
sends `Prefer: respond-async`, so Router may hand a long run to its queue and answer `202` with
a handle instead of holding the connection. A `202` carrying `Preference-Applied:
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1270,13 +1270,14 @@ firing is not by itself proof that Router answered. Keep an `except ComfyError`
outside the clause above if you need to handle the rest in the same place.

`RouterError` is exported from the package root because it is the handler most
callers write first. The twenty per-bucket classes stay in
callers write first. The twenty-three per-bucket classes stay in
`comfy_sdk.router_exceptions` — `InvalidInput`, `ContentPolicyViolation`,
`ProviderError`, `ProviderTimeout`, `InsufficientCredits`, `ModelNotFound`,
`ProviderError`, `ProviderTimeout`, `InsufficientCredits`, `BudgetExceeded`,
`BudgetCheckUnavailable`, `ModelNotFound`,
`Unauthorized`, `Forbidden`, `ConcurrencyLimitExceeded`, `ClientDisconnected`,
`InternalError`, `DeadlineExceeded`, `NotEnabled`, `ServiceUnavailable`,
`RateLimited`, `Cancelled`, `QueueTimeout`, `RequestNotFound`,
`QueueBacklogFull`, `ResultExpired` — one import path
`QueueBacklogFull`, `ResultExpired`, `ByokCredentialRejected` — one import path
for the whole set rather than half of it here and half of it there. A bucket added to Router after your installed version
arrives as `RouterError` itself, with the raw value readable on `.error_type`.

Expand Down
7 changes: 5 additions & 2 deletions scripts/check_drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,11 @@
#: JSON branch that decodes to a ``dict``, one catch-all binary branch that
#: comes back as a ``BinaryResult``. Unlike the path and host below, there is no
#: constant in the SDK to compare against, because the branch is control flow
#: rather than data; so the expectation lives here.
_BOUND_RUN_MEDIA_TYPES = ["*/*", "application/json"]
#: rather than data; so the expectation lives here. ``text/event-stream`` is
#: the stream-direct answer to a body sending ``stream: true``: it is not a
#: third branch, the SDK reads the event stream whole and returns it as a
#: ``BinaryResult`` like any other non-JSON success.
_BOUND_RUN_MEDIA_TYPES = ["*/*", "application/json", "text/event-stream"]


def _generate(out: Path) -> None:
Expand Down
168 changes: 148 additions & 20 deletions spec/router-openapi.yaml

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion src/comfy_low/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,10 @@ def is_json_media_type(media: str) -> bool:
including ``text/plain`` and ``text/html``: the SDK cannot tell a partner's
native text output from a proxy interstitial, and on this route the
contract says the body is the partner's, so it hands the bytes back rather
than throwing away a generation the caller was billed for.
than throwing away a generation the caller was billed for. The same holds
for ``text/event-stream``, the route's stream-direct answer to a body
sending ``stream: true``: the event stream is read whole and returned as
bytes, not parsed.
"""
return media == "application/json" or media.endswith("+json")

Expand Down
95 changes: 86 additions & 9 deletions src/comfy_sdk/router_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,13 +298,22 @@ class InvalidInput(RouterError):
class ContentPolicyViolation(RouterError):
"""The model's content policy refused the request.

Deterministic: the same input will be refused again, so this is never a
retry candidate. It is deliberately not a :class:`ProviderError` -- the two
differ in whether a retry can ever succeed.
A refusal of the caller's *input* is deterministic: the same input will be
refused again, so re-sending it unchanged is not a retry candidate. It is
deliberately not a :class:`ProviderError` -- the two differ in whether a
retry can ever succeed.

The exception is a refusal of the model's own generated *output*. On the
synchronous route, when Router can tell that is what the provider refused,
``detail`` says so and what may succeed: a changed prompt or references, or
for some providers the same input retried. The queued collect says so only
for the providers whose same input may succeed on a retry. The SDK's retry
policy never retries this bucket either way; read ``detail`` before
deciding to.
"""

error_type = "content_policy_violation"
_spec_meaning_digest: str = "bf2e91e6a6dd"
_spec_meaning_digest: str = "80a3d8b6f9cc"


class ProviderError(RouterError):
Expand Down Expand Up @@ -332,6 +341,21 @@ class InsufficientCredits(RouterError):
_spec_meaning_digest: str = "303c7b5e1b47"


class BudgetExceeded(RouterError):
"""A hard spend cap has been reached.

Returned under ``402``, which it shares with :class:`InsufficientCredits`
and is not the same thing: that one says the workspace has run out of
credits, this one says a spend cap set on the workspace has been reached,
whatever its balance. Re-sending the same call is refused the same way until
the cap resets or is raised. A bare ``402`` that names no bucket still reads
as :class:`InsufficientCredits`, the plain HTTP meaning of the status.
"""

error_type = "budget_exceeded"
_spec_meaning_digest: str = "946503260fd6"


class ModelNotFound(RouterError):
"""No such model Router can run. An unknown provider, an unenrolled id, an
id the catalog has retired past its sunset date, and a catalogued id the
Expand All @@ -355,6 +379,24 @@ class ModelNotFound(RouterError):
_spec_meaning_digest: str = "6c0e0e327e4d"


class ByokCredentialRejected(RouterError):
"""The provider rejected the key supplied for this call.

Returned under ``401``; an upstream ``403`` is the same refusal and is
returned as this ``401`` too, with the provider's own status on
``X-Comfy-Upstream-Status``. Check the key stored for this provider:
sending the same key again will be refused the same way, so do not retry.

It names the caller's *provider* key, not the caller's Comfy credential
(:class:`Unauthorized`, :class:`Forbidden`), and not an outage of the
provider (:class:`ProviderError`). The provider's response body is not
included.
"""

error_type = "byok_credential_rejected"
_spec_meaning_digest: str = "1e89db8bfad2"


# -- transport-level buckets -------------------------------------------------


Expand Down Expand Up @@ -496,15 +538,41 @@ class ServiceUnavailable(RouterError):
_spec_meaning_digest: str = "28b40d6c0f89"


class BudgetCheckUnavailable(RouterError):
"""A hard spend cap could not be checked, so the call was not run.

Returned under ``503``; the contract's advice is to retry after the
``Retry-After`` delay, which is carried on ``retry_after``. It is not
:class:`BudgetExceeded`: no cap is known to have been reached, the check
itself failed.

Like :class:`ServiceUnavailable`, the SDK does **not** make that retry by
default: the retry policy sorts a ``503`` by whether the one
``Idempotency-Key`` is provably spendable again, and no vendored contract
says this one releases it. ``RetryPolicy(retry_possibly_in_flight=True)``
opts in, keeps the one key across the retry and waits the ``Retry-After``
the server named. Calling ``models.run()`` again by hand mints a fresh key;
pass the same explicit ``idempotency_key=`` both times instead.
"""

error_type = "budget_check_unavailable"
_spec_meaning_digest: str = "9461ca3d07cf"


class RateLimited(RouterError):
"""The caller has spent an allowance measured over a *window* and must wait
for that window to roll.
for that window to roll, or the model provider throttled the call before
starting any generation.

It shares ``429`` with :class:`ConcurrencyLimitExceeded` and is not the same
thing: that one clears the moment one of the caller's own in-flight calls
finishes, so retrying in seconds is right, whereas nothing the caller does
drains this one early. On the Router surface, ``detail`` names the window,
and ``Retry-After`` the seconds to wait, carried on ``retry_after``.
and ``Retry-After`` the seconds to wait, carried on ``retry_after``. On a
provider's limit, ``X-Comfy-Upstream-Status`` carries the provider's
``429``, and ``Retry-After`` carries the provider's own wait only when it
sent one -- so ``retry_after`` can be ``None`` there, and a ``429`` without
a pace is not retried by default.

The window guarantee above is Router's. The v2 jobs/assets gateway raises
this same class for ``code == "rate_limited"``, and there it has two causes:
Expand All @@ -515,7 +583,7 @@ class RateLimited(RouterError):
"""

error_type = "rate_limited"
_spec_meaning_digest: str = "e94bd188240b"
_spec_meaning_digest: str = "24b19c6028a7"


# -- queue buckets -----------------------------------------------------------
Expand Down Expand Up @@ -683,8 +751,11 @@ class AlreadyCompleted(CancelRefused):
}


#: Every class in the closed set, in the order the error set declares it: the
#: request-level buckets, then the transport-level ones. The order is the
#: Every class in the closed set, in the order the error set declares it --
#: mostly the request-level buckets, then the transport-level ones, but the
#: spec places ``budget_check_unavailable`` beside ``budget_exceeded`` and
#: appends ``byok_credential_rejected`` last, so the tier sections above do not
#: dictate it. The order is the
#: vendored spec's ``x-comfy-error-types`` order, and
#: ``tests/test_router_spec_contract.py`` asserts that -- so this tuple cannot
#: drift from the contract two SDKs generate their surface from.
Expand All @@ -694,6 +765,8 @@ class AlreadyCompleted(CancelRefused):
ProviderError,
ProviderTimeout,
InsufficientCredits,
BudgetExceeded,
BudgetCheckUnavailable,
ModelNotFound,
Unauthorized,
Forbidden,
Expand All @@ -709,6 +782,7 @@ class AlreadyCompleted(CancelRefused):
RequestNotFound,
QueueBacklogFull,
ResultExpired,
ByokCredentialRejected,
)

_BY_ERROR_TYPE: dict[str, type[RouterError]] = {cls.error_type: cls for cls in ROUTER_EXCEPTIONS}
Expand Down Expand Up @@ -979,6 +1053,9 @@ def _detail_from(entry: Mapping[str, Any]) -> ValidationErrorDetail:
"ROUTER_ERROR_TYPES",
"ROUTER_EXCEPTIONS",
"AlreadyCompleted",
"BudgetCheckUnavailable",
"BudgetExceeded",
"ByokCredentialRejected",
"CancelRefused",
"Cancelled",
"ClientDisconnected",
Expand Down
3 changes: 3 additions & 0 deletions tests/test_exception_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
(502, "provider_error"),
(504, "provider_timeout"),
(402, "insufficient_credits"),
(402, "budget_exceeded"),
(503, "budget_check_unavailable"),
(404, "model_not_found"),
(401, "unauthorized"),
(403, "forbidden"),
Expand All @@ -71,6 +73,7 @@
(404, "request_not_found"),
(429, "queue_backlog_full"),
(410, "result_expired"),
(401, "byok_credential_rejected"),
(418, "something_invented_later"),
]

Expand Down
16 changes: 16 additions & 0 deletions tests/test_models_run_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ def test_an_audio_200_returns_the_bytes_verbatim(server) -> None:
assert server.state.model_run_generations == 1


def test_a_stream_direct_event_stream_200_comes_back_as_its_bytes(server) -> None:
# The run route's 200 also declares `text/event-stream`: a model enrolled
# in stream-direct may answer a body sending `stream: true` with the
# provider's own event stream. The SDK does not parse it; it reads the
# whole stream and hands it back as the binary branch's `BinaryResult`,
# so the generation the caller asked to stream is still delivered intact.
events = b'data: {"delta": "a"}\n\ndata: {"delta": "b"}\n\ndata: [DONE]\n\n'
server.state.model_run_binary_body = events
server.state.model_run_binary_content_type = "text/event-stream; charset=utf-8"
with Comfy(retry=NO_RETRY) as client:
result = client.models.run(MODEL, {**ARGS, "stream": True})
assert isinstance(result, BinaryResult)
assert result.content == events
assert result.content_type == "text/event-stream; charset=utf-8"


async def test_the_async_client_returns_the_same_binary_result(server) -> None:
_serve_audio(server)
server.state.model_run_request_id = "req_audio_01"
Expand Down
6 changes: 6 additions & 0 deletions tests/test_router_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
REQUEST_ID_HEADER,
ROUTER_ERROR_TYPES,
ROUTER_EXCEPTIONS,
BudgetCheckUnavailable,
BudgetExceeded,
ByokCredentialRejected,
Cancelled,
ClientDisconnected,
ConcurrencyLimitExceeded,
Expand Down Expand Up @@ -61,6 +64,8 @@
("provider_error", 502, ProviderError),
("provider_timeout", 504, ProviderTimeout),
("insufficient_credits", 402, InsufficientCredits),
("budget_exceeded", 402, BudgetExceeded),
("budget_check_unavailable", 503, BudgetCheckUnavailable),
("model_not_found", 404, ModelNotFound),
("unauthorized", 401, Unauthorized),
("forbidden", 403, Forbidden),
Expand All @@ -76,6 +81,7 @@
("request_not_found", 404, RequestNotFound),
("queue_backlog_full", 429, QueueBacklogFull),
("result_expired", 410, ResultExpired),
("byok_credential_rejected", 401, ByokCredentialRejected),
]

# Deliberately not in the set this SDK version knows: a later milestone adds it,
Expand Down
66 changes: 47 additions & 19 deletions tests/test_router_spec_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

from __future__ import annotations

import inspect
from dataclasses import MISSING, fields
from pathlib import Path
from typing import Any
Expand All @@ -46,7 +47,7 @@
_MODEL_SCHEMA_PATH_TEMPLATE,
model_catalog_path,
)
from comfy_sdk import COMFY_ROUTER_BASE_URL
from comfy_sdk import COMFY_ROUTER_BASE_URL, router_exceptions
from comfy_sdk.model_requests import CostEstimate
from comfy_sdk.models import RouterRunResult, _run_result
from comfy_sdk.router_exceptions import (
Expand Down Expand Up @@ -184,24 +185,47 @@ def test_the_spec_states_a_meaning_and_a_tier_for_every_bucket() -> None:
assert isinstance(entry.get("meaning"), str) and entry["meaning"].strip(), entry


def test_every_request_tier_bucket_precedes_every_transport_tier_one() -> None:
"""The assumption that lets the order check above stand in for a tier check.
def _section_line(marker: str) -> int:
"""The 1-based line in ``router_exceptions.py`` holding a section comment."""
lines = inspect.getsource(router_exceptions).splitlines()
matches = [number for number, line in enumerate(lines, start=1) if line.startswith(marker)]
assert len(matches) == 1, f"expected exactly one {marker!r} section in router_exceptions.py"
return matches[0]

Nothing else in this file reads ``tier``: the class table is compared as a
flat ordered list, which only carries the request/transport split as long
as the spec keeps the two runs contiguous and request-first. A sync that
interleaved them would leave the section comments in
``router_exceptions.py`` describing an order the spec no longer declares,
with every other assertion here green.

@pytest.mark.parametrize(
"entry", DECLARED_ENTRIES, ids=[entry["value"] for entry in DECLARED_ENTRIES]
)
def test_every_class_sits_in_the_section_its_spec_tier_names(entry: dict[str, Any]) -> None:
"""The tier check the flat order comparison above cannot make.

The class table is compared as a flat ordered list, and the spec does not
keep the tiers contiguous (``budget_check_unavailable`` is a transport
bucket declared beside ``budget_exceeded``; ``byok_credential_rejected`` is
a request bucket declared last), so order says nothing about tier. What
does is where each class is *defined*: a ``request``-tier class under the
request-level section comment of ``router_exceptions.py``, a
``transport``-tier one under the transport-level (or queue) sections. A sync
that moved a bucket between tiers would otherwise leave those section
comments describing a split the spec no longer declares, with every other
assertion here green.
"""
tiers = [entry["tier"] for entry in DECLARED_ENTRIES]
first_transport = tiers.index("transport") if "transport" in tiers else len(tiers)
assert "request" not in tiers[first_transport:], (
"the spec's x-comfy-error-types no longer declares every `request`-tier bucket "
f"before every `transport`-tier one: {tiers} -- the flat order comparison in this "
"file no longer implies the tier split the section comments in "
"src/comfy_sdk/router_exceptions.py describe"
)
request_start = _section_line("# -- request-level buckets")
transport_start = _section_line("# -- transport-level buckets")
transport_end = _section_line("# -- cancel refusals")
cls = exception_for(entry["value"])
assert cls is not RouterError, f"no class for {entry['value']!r}"
defined_at = inspect.getsourcelines(cls)[1]
if entry["tier"] == "request":
assert request_start < defined_at < transport_start, (
f"{cls.__name__} is a request-tier bucket but is not defined under the "
"request-level section of src/comfy_sdk/router_exceptions.py"
)
else:
assert transport_start < defined_at < transport_end, (
f"{cls.__name__} is a transport-tier bucket but is not defined under the "
"transport-level sections of src/comfy_sdk/router_exceptions.py"
)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -377,10 +401,14 @@ def test_the_run_200_declares_both_a_json_and_a_binary_branch() -> None:
SDK's behaviour rather than the server's contract.
"""
content = _run_200_content()
assert set(content) == {"application/json", "*/*"}, (
# `text/event-stream` is the stream-direct answer to a body sending
# `stream: true`; the SDK reads it whole and returns it down the binary
# branch, so it adds a declared type without adding a third case.
assert set(content) == {"application/json", "*/*", "text/event-stream"}, (
f"the vendored spec's runRouterModel 200 declares {sorted(content)}; "
"comfy_low.transport._Prepared.parse_run_result branches on exactly two "
"cases (JSON -> dict, anything else -> BinaryResult)"
"cases (JSON -> dict, anything else -- text/event-stream included -> "
"BinaryResult)"
)


Expand Down
Loading