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
9 changes: 5 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,11 @@ uv run --extra codegen bash scripts/gen_models.sh # rewrites src/comfy_low/mod
uv run --extra codegen python scripts/check_drift.py # the exact check CI runs
```

`check_drift.py` runs two checks, not one: the byte-for-byte model comparison
above, and the Router error-type comparison described under "Other things that
are not obvious" below. Both run on every invocation, so a failure in one does
not hide the other.
`check_drift.py` runs four checks, not one: the byte-for-byte model comparison
above, the Router error-type comparison described under "Other things that are
not obvious" below, the bound model-run route, and `SpendBudgetDetail` against
the Router spec's `RouterSpendBudgetDetail`. All run on every invocation, so a
failure in one does not hide another.

Then commit `src/comfy_low/models/_generated.py`.

Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ the fuller account of each version, including verification notes.
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`.
- `budget` and `blocking_budgets` on `BudgetExceeded`: the exhausted budget and every exhausted hard
budget from the response body, as read-only `SpendBudgetDetail` objects (new in
`comfy_sdk.router_exceptions`). `None` and empty when the body does not carry them; identifiers,
mode and amounts are shown to the workspace Owner only. `comfy_low.ApiError` carries the same two
raw.
- `dropped_params` on `RequestHandle` and `AsyncRequestHandle`: Router's bounded disclosure of the
native fields a translated `models.submit` could not carry, from `X-Comfy-Router-Dropped-Params`
on the submit's response; a long list is cut or summarised, so it may be incomplete. `None` when
the header is absent, and always on a handle rebuilt with `models.handle`.
- 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.
Expand Down
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -845,9 +845,19 @@ and the settled charge in your workspace's usage and billing records is what you
pay. It is not a price lock either: the run is charged at the rates in force
when it is rated.

When Router translated the body for another provider and could not carry every
native field, `handle.dropped_params` discloses what was dropped and why, as it
does on a `run_detailed` result. Entries are sentences to read, and the list
is not guaranteed complete: Router bounds its size, so a long entry is cut (it
ends in `…`), one entry can stand for several fields, and entries that did not
fit are replaced by a final one stating how many were left out, a lower bound on
the fields affected. On the handle `submit` returned, `None` means no
translation ran or it dropped nothing; on a rebuilt handle (below) it is always
`None`, meaning "not disclosed", whatever the original submit dropped.

Rehydrate a handle in another process from the two ids that address the
request, with no call made (the cost quote does not come back with it, so keep
`handle.estimate` alongside the ids if a later process needs it):
request, with no call made (the cost quote and `dropped_params` do not come back
with it, so keep them alongside the ids if a later process needs them):

```python
handle = client.models.handle("fal-ai/flux-pro", request_id)
Expand Down Expand Up @@ -1257,6 +1267,11 @@ except RouterError as exc:
print(exc.error_type, exc.request_id) # every other bucket
```

`BudgetExceeded` carries the spend budgets that blocked the call as `budget` (one
`SpendBudgetDetail` or `None`) and `blocking_budgets` (a tuple, empty when the
response did not carry the list). Their ids, mode and amounts are shown to the
workspace Owner only and are `None` for anyone else.

`RouterError` covers every refusal Router itself answered with, including a
bucket newer than your installed version — Router names the bucket on every
error it sends, and that is what types the exception. A response that never
Expand Down
73 changes: 71 additions & 2 deletions scripts/check_drift.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Fail if the committed tree drifts from the vendored specs.

Three checks, one job:
Four checks, one job:

1. **Models vs ``spec/openapi.yaml``.** Regenerates the models into a temp file
and diffs against the committed one, so a spec edit without a regen (or a
Expand Down Expand Up @@ -30,6 +30,10 @@
``application/json`` success decodes to a ``dict`` and any other one comes
back as a ``BinaryResult``, so a branch added or dropped upstream changes
what ``post_model_run`` returns.
4. **The budget detail vs ``spec/router-openapi.yaml``.** Also hand-written:
``SpendBudgetDetail`` in ``comfy_sdk.router_exceptions`` models
``RouterSpendBudgetDetail`` field by field, and has no ``raw`` escape hatch,
so a property a sync adds would never reach a caller until it is added here.

``tests/test_router_spec_contract.py`` asserts the same things from the test
suite. Both exist on purpose: the suite is where a contributor sees it, and
Expand Down Expand Up @@ -443,6 +447,70 @@ def _check_router_error_types() -> int:
return 0


def _check_router_budget_detail() -> int:
if not ROUTER_SPEC.exists():
print(f"ERROR: {ROUTER_SPEC.name} is missing from spec/", file=sys.stderr)
return 1
sys.path.insert(0, str(ROOT / "src"))
from dataclasses import fields
from typing import get_args, get_type_hints

import yaml

from comfy_sdk.router_exceptions import SpendBudgetDetail
Comment thread
mattmillerai marked this conversation as resolved.
Resolved

doc = yaml.safe_load(ROUTER_SPEC.read_text(encoding="utf-8"))
schemas = doc["components"]["schemas"]
declared = set(schemas["RouterSpendBudgetDetail"]["properties"])
Comment thread
mattmillerai marked this conversation as resolved.
Resolved
modelled = {f.name for f in fields(SpendBudgetDetail)}
if declared != modelled:
print(
"DRIFT: comfy_sdk.router_exceptions.SpendBudgetDetail does not match "
"RouterSpendBudgetDetail in spec/router-openapi.yaml\n"
f" not modelled by the SDK: {sorted(declared - modelled)}\n"
f" not declared by the spec: {sorted(modelled - declared)}",
file=sys.stderr,
)
return 1
# Names alone are not enough: `_budget_from` reads a non-`int` amount as
# "not disclosed", so a sync that retyped an amount would blank it for
# Owners too. Each property's type, and whether it is required, must match
# the dataclass annotation -- required fields are the non-optional ones.
spec_types = {"string": str, "integer": int}
required = set(schemas["RouterSpendBudgetDetail"].get("required", []))
hints = get_type_hints(SpendBudgetDetail)
mismatched = []
for name, prop in schemas["RouterSpendBudgetDetail"]["properties"].items():
members = set(get_args(hints[name])) or {hints[name]}
optional = type(None) in members
if members - {type(None)} != {spec_types.get(prop.get("type"))} or optional == (
name in required
):
mismatched.append(name)
if mismatched:
print(
"DRIFT: comfy_sdk.router_exceptions.SpendBudgetDetail types or "
"requiredness differ from RouterSpendBudgetDetail in "
f"spec/router-openapi.yaml for: {sorted(mismatched)}",
file=sys.stderr,
)
return 1
ref = "#/components/schemas/RouterSpendBudgetDetail"
body = schemas["RouterErrorResponse"]["properties"]
if body["budget"] != {"$ref": ref} or body["blocking_budgets"].get("items") != {"$ref": ref}:
Comment thread
mattmillerai marked this conversation as resolved.
Resolved
print(
"DRIFT: RouterErrorResponse no longer declares `budget` and "
"`blocking_budgets` as RouterSpendBudgetDetail",
file=sys.stderr,
)
return 1
print(
"OK: SpendBudgetDetail models every field of RouterSpendBudgetDetail, "
"with matching types and requiredness"
)
return 0


def _run(name: str, check: Callable[[], int]) -> int:
"""One check's exit code, with a raised exception counted as a failure.

Expand All @@ -461,13 +529,14 @@ def _run(name: str, check: Callable[[], int]) -> int:


def main() -> int:
# All three run every time: reporting only the first failure would hide the
# All four run every time: reporting only the first failure would hide the
# others behind a fix for it. `max` over the results rather than a
# short-circuit for the same reason.
return max(
_run("models", _check_models),
_run("router error types", _check_router_error_types),
_run("router run route", _check_router_run_route),
_run("router budget detail", _check_router_budget_detail),
)


Expand Down
2 changes: 1 addition & 1 deletion spec/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Vendored copies of the canonical HTTP contracts this SDK is built against, synced one-way — do not hand-edit either file. The sync strips any operation tagged `internal` / `x-internal: true` (this is a public repo).

- **`openapi.yaml`** — the **Comfy API v2** contract (OpenAPI 3.0.3), pinned by `VERSION`. Regenerate `src/comfy_low/models/` from it with `scripts/gen_models.sh`; CI (`scripts/check_drift.py`) fails on drift.
- **`router-openapi.yaml`** — the **Comfy Router** public contract (OpenAPI 3.0.2): the model catalog and the model-ID-addressed invocation routes, with the error buckets they return. Nothing is generated from it today. What it does gate is the typed error surface: its `RouterErrorType.x-comfy-error-types` list is the closed error set, and `scripts/check_drift.py` fails unless `comfy_sdk.router_exceptions.ROUTER_ERROR_TYPES` is **exactly that list of values, in exactly that order** — so a bucket added, removed or reordered upstream all fail it, not only an addition. It also fails when an entry's `meaning` prose changes, against the per-class `_spec_meaning_digest` read markers described below. `tests/test_router_spec_contract.py` asserts the same things from the suite.
- **`router-openapi.yaml`** — the **Comfy Router** public contract (OpenAPI 3.0.2): the model catalog and the model-ID-addressed invocation routes, with the error buckets they return. Nothing is generated from it today. What it does gate is the typed error surface: its `RouterErrorType.x-comfy-error-types` list is the closed error set, and `scripts/check_drift.py` fails unless `comfy_sdk.router_exceptions.ROUTER_ERROR_TYPES` is **exactly that list of values, in exactly that order** — so a bucket added, removed or reordered upstream all fail it, not only an addition. It also fails when an entry's `meaning` prose changes, against the per-class `_spec_meaning_digest` read markers described below. And it fails when `RouterSpendBudgetDetail`'s properties and `comfy_sdk.router_exceptions.SpendBudgetDetail`'s fields differ. `tests/test_router_spec_contract.py` asserts the same things from the suite.

**Syncing a new Router spec is therefore a three-step change** — the new spec, the class table, and a re-bless of the docstrings whose prose moved — and the drift check is what makes the second and third steps unskippable. After dropping in the new `router-openapi.yaml`, reconcile `src/comfy_sdk/router_exceptions.py` against it:

Expand Down
35 changes: 35 additions & 0 deletions src/comfy_low/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ def __init__(
error_type: str | None = None,
validation_errors: Sequence[Mapping[str, Any]] = (),
organization_id: str | None = None,
budget: Mapping[str, Any] | None = None,
blocking_budgets: Sequence[Mapping[str, Any]] = (),
) -> None:
super().__init__(message)
self.message = message
Expand Down Expand Up @@ -208,6 +210,14 @@ def __init__(
#: read, so an ``sso_required`` refusal of one surfaces as a plain
#: ``forbidden`` with this left ``None``.
self.organization_id = organization_id
#: On Router's ``budget_exceeded``: the body's ``budget`` object and the
#: mapping members of its ``blocking_budgets`` array, raw. ``None`` and
#: ``()`` on every other code and when the body carried none. Untyped
#: for the reason :attr:`validation_errors` is: the typed view is
#: ``comfy_sdk.router_exceptions.SpendBudgetDetail``, converted at the
#: translation boundary onto ``BudgetExceeded``.
self.budget = budget
self.blocking_budgets: tuple[Mapping[str, Any], ...] = tuple(blocking_budgets)

def __str__(self) -> str:
"""``message``, plus the body excerpt whenever there is one.
Expand Down Expand Up @@ -485,6 +495,28 @@ def _cancel_refusal_code(http_status: int, body: dict[str, Any] | None) -> str |
return _CODE_BY_CANCEL_STATUS.get(status.upper()) if status else None


def raw_budgets(
body: Any,
) -> tuple[Mapping[str, Any] | None, tuple[Mapping[str, Any], ...]]:
"""The ``budget`` and ``blocking_budgets`` a ``budget_exceeded`` body carries, raw.

Never raises: a missing or wrongly-typed value reads as absent, and a
member of the array that is not a mapping is dropped, because this runs
while handling a failure and one malformed member must not cost the caller
the others. Shared with ``comfy_sdk.router_exceptions`` so both surfaces
read one wire body the same way.
"""
if not isinstance(body, Mapping):
return None, ()
budget, blocking = body.get("budget"), body.get("blocking_budgets")
if not isinstance(blocking, Sequence) or isinstance(blocking, (str, bytes)):
blocking = ()
return (
budget if isinstance(budget, Mapping) else None,
tuple(entry for entry in blocking if isinstance(entry, Mapping)),
)


def error_from_envelope(
http_status: int,
body: dict[str, Any] | None,
Expand Down Expand Up @@ -655,6 +687,7 @@ def error_from_envelope(
# 429. Reduced to an id-shaped token, so a non-string, empty or malformed
# value reads as absent rather than reaching a URL.
organization_id = clean_organization_id(raw_organization_id) if code == "sso_required" else None
budget, blocking_budgets = raw_budgets(body) if code == "budget_exceeded" else (None, ())
cls = _BY_CODE.get(code, ApiError)
return cls(
message,
Expand All @@ -667,6 +700,8 @@ def error_from_envelope(
error_type=bucket,
validation_errors=validation_errors,
organization_id=organization_id,
budget=budget,
blocking_budgets=blocking_budgets,
)


Expand Down
2 changes: 2 additions & 0 deletions src/comfy_sdk/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
RateLimited,
RouterError,
Unauthorized,
_budget_kwargs,
_detail_from,
)

Expand Down Expand Up @@ -298,6 +299,7 @@ def to_sdk_error(exc: ApiError) -> ComfyError:
retry_after=exc.retry_after,
errors=tuple(_detail_from(entry) for entry in exc.validation_errors),
organization_id=exc.organization_id,
**_budget_kwargs(cls, exc.budget, exc.blocking_budgets),
)
# No `errors=` below, deliberately: `.errors` is a `RouterError` attribute
# and none of the remaining classes takes the argument. A validation body
Expand Down
31 changes: 29 additions & 2 deletions src/comfy_sdk/model_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,7 @@ class _RequestHandleBase:
_request_id: str
_retry: RetryPolicy
_estimate: CostEstimate | None
_dropped_params: tuple[str, ...] | None
#: The per-request HTTP timeout a poll or result fetch uses when it has no
#: budget of its own. :data:`_INHERIT_TIMEOUT` -- every handle a caller
#: builds -- is the client's timeout; ``models.run`` following a ``202``
Expand Down Expand Up @@ -648,6 +649,27 @@ def estimate(self) -> CostEstimate | None:
"""
return self._estimate

@property
def dropped_params(self) -> tuple[str, ...] | None:
"""Router's disclosure of what translation could not carry, or ``None``.

Read from ``X-Comfy-Router-Dropped-Params`` on the submit's own
response; entries name dropped native fields and why, as
:attr:`~comfy_sdk.RouterRunResult.dropped_params` does for a run. Like
it, the disclosure is bounded in size, so it may not be a complete list:
an entry may be cut (it ends in ``…``) or stand for several fields, and
a final entry may state how many were left out, a lower bound on the
fields affected.

On a handle ``client.models.submit`` returned, ``None`` means no
translation ran or it dropped nothing. The queue's status and result
responses do not carry the header, so it is always ``None``, meaning
"not disclosed", on a handle rebuilt with ``client.models.handle``. A
same-key replay of the submit carries the original's value, unlike
:attr:`estimate`.
"""
return self._dropped_params

def __repr__(self) -> str:
estimate = "" if self._estimate is None else f", estimate={self._estimate.source!r}"
return (
Expand All @@ -662,8 +684,9 @@ class RequestHandle(_RequestHandleBase):
Built by ``client.models.submit`` and by ``client.models.handle``; there is
nothing to construct by hand, and nothing in it that a second process
cannot rebuild from :attr:`model` and :attr:`request_id` -- except
:attr:`estimate`, which only the submitting process ever holds. Keep the
quote alongside the two ids if a later process needs it.
:attr:`estimate` and :attr:`dropped_params`, which arrive only on the
submit's response. Keep them alongside the two ids if a later process needs
them.
"""

def __init__(
Expand All @@ -674,12 +697,14 @@ def __init__(
retry: RetryPolicy = DEFAULT_RETRY,
*,
estimate: CostEstimate | None = None,
dropped_params: tuple[str, ...] | None = None,
) -> None:
self._low = low
self._model = model
self._request_id = request_id
self._retry = retry
self._estimate = estimate
self._dropped_params = dropped_params

# -- polling (authoritative) ------------------------------------------
def status(self) -> QueueUpdate:
Expand Down Expand Up @@ -899,12 +924,14 @@ def __init__(
retry: RetryPolicy = DEFAULT_RETRY,
*,
estimate: CostEstimate | None = None,
dropped_params: tuple[str, ...] | None = None,
) -> None:
self._low = low
self._model = model
self._request_id = request_id
self._retry = retry
self._estimate = estimate
self._dropped_params = dropped_params

async def status(self) -> QueueUpdate:
"""Awaitable :meth:`RequestHandle.status` — one authoritative poll."""
Expand Down
Loading
Loading