Skip to content
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@ the fuller account of each version, including verification notes.

### Added

- `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:
respond-async` is polled through the queue's status and result reads to the same native result
`run` returns for a `200`; a `200` is returned as always; a `202` with neither
`Preference-Applied` nor `Idempotent-Replayed` raises `ComfyError` (`code="invalid_response"`)
carrying the key and the `202` body. A handoff followed on a call that did not opt in is
polled only for what is left of a numeric `timeout` counted from the start of the call
(retries before the `202` keep the retry policy's own budget), and its `TimeoutError` carries `idempotency_key` / `request_id` /
`retry_after`; each poll and result read keeps the run's `timeout` (an `httpx.Timeout`, or
`None` for no limit, included) as its HTTP timeout. `RouterRunResult` gains `handed_off`, under which a missing
provider disclosure means "not disclosed". Off by default: the default call sends no `Prefer`
header. `comfy_low`'s `post_model_run` gains the same keyword and now
returns a `RunHandoff` (newly exported) for a `202`.
- `sso_required` (403) now raises `Forbidden` (code preserved) and carries `organization_id`, the
organization to start SSO with. `organization_id` is a new attribute on `ComfyError` and on
`comfy_low.ApiError`, `None` on every other code and when the server does not name the
Expand Down
42 changes: 41 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,8 @@ Three things follow from that, and they are the whole contract of this method:

`run` returns when the generation is **complete**. There is no submit step and
nothing to poll: where the platform has to submit-and-poll an upstream
provider, that happens server side inside this one call. The value you get back
provider, that happens server side inside this one call (or, if you opt in with
`respond_async=True` below, client side inside it — still one call). The value you get back
is the provider's own payload, handed over as-is. For a model that answers
JSON — most of them — that is a `dict` with no wrapper class between you and
what the provider produced. For a model whose partner answers a generation
Expand All @@ -547,6 +548,45 @@ async with AsyncComfy(api_key="comfyui-...") as client:
There is no `run_async()`, and there will not be one — one operation, one name,
and `await` is what makes it asynchronous.

#### Long runs without a held connection: `respond_async=True`

```python
result = client.models.run("bfl/flux-2-pro", {"prompt": "a cat"}, respond_async=True)
```

Same call, same result — but it sends `Prefer: respond-async`, which lets Router
hand a slow run to its queue and answer `202` with a handle instead of holding
the HTTP connection open until the model finishes. When Router does that (it
answers with `Preference-Applied: respond-async`), `run` polls the handle — the
same status and result reads `models.submit`'s handle makes, which are not
billed — and returns exactly what it would have returned for a `200`. When it
does not (the model is not one Router hands off, or the deployment has the
handoff switched off) the answer is the ordinary `200`, returned as always, so
the flag is safe to pass for any model. `run_detailed` and the async client
take the same keyword.

It is off by default: without it no `Prefer` header is sent and nothing changes.
On the handed-off path `timeout` bounds the run request and each status and
result read (an `httpx.Timeout` keeps its limits on every one, and `None` means
no limit on any of them, whatever the client's own timeout is), not the wait,
which lasts until the queue says the run is done — use `models.subscribe` if
you want a client-side bound on the whole wait. The `Idempotency-Key` is sent either way,
and a resend under the same key — with or without the flag — collects the
generation the first request started rather than starting another; a resend
*without* the flag that is answered with the handoff is followed only for what
is left of a numeric `timeout` counted from the start of the call, then raises
`TimeoutError` without cancelling the run — stamped with the `idempotency_key`,
`request_id` and `retry_after` a resend reads. Retries before the `202` keep the
retry policy's own budget; if they have used that window up, the queue is looked
at once and a run already done is returned. A `202` that
carries neither `Preference-Applied` nor `Idempotent-Replayed` is never returned
as output: it raises `ComfyError` (`code="invalid_response"`) carrying the key,
the response's request id and, on `details["handle"]`, the body — so a queue
`request_id` it names can still be collected with `models.handle()`. On a
handed-off `run_detailed`, `handed_off` is `True` and a missing
`serving_provider` / `dropped_params` means "not disclosed", since the run was
accepted before any provider was dispatched.

### Two result shapes — JSON, or the model's own bytes

Router forwards the partner's output *under the partner's own media type*, so
Expand Down
3 changes: 2 additions & 1 deletion src/comfy_low/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
sse_error_from_frame,
)
from .sse import RawEvent, SSEDecoder
from .transport import AsyncComfyLow, BinaryResult, ComfyLow
from .transport import AsyncComfyLow, BinaryResult, ComfyLow, RunHandoff

# The exact set of operationIds the transport must cover; the spec-coverage test
# asserts this equals the set of operationIds in spec/openapi.yaml.
Expand Down Expand Up @@ -78,6 +78,7 @@
"ComfyLow",
"AsyncComfyLow",
"BinaryResult",
"RunHandoff",
"RawEvent",
"SSEDecoder",
"ApiError",
Expand Down
81 changes: 74 additions & 7 deletions src/comfy_low/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,31 @@ def __repr__(self) -> str:
)


@dataclass(frozen=True)
class RunHandoff:
"""A model run Router answered ``202``: handed to its queue, not finished.

What ``post_model_run`` returns in place of a result when Comfy Router
accepts the run but answers before the generation is done. Router does
that only for a caller that asked for it with ``Prefer: respond-async``
(RFC 7240) on a model it is configured to hand off; every other run keeps
the ``200`` that carries the finished output. The answer to the ``Prefer``
is ``Preference-Applied: respond-async`` on the response, which this
carrier does not read -- the response headers travel beside it, as they do
for every run, so the layer above decides what a ``202`` without it means.

The body is the queue handle -- the same ``request_id`` / ``status_url`` /
``response_url`` the queued submit answers with -- kept as the decoded
JSON object rather than modelled, so a field the server adds reaches the
caller untouched. It is a separate type rather than a ``dict`` so a handle
can never be mistaken for a partner's native output, which is also a
``dict``.
"""

#: The ``202`` body verbatim: the queue handle for the handed-off run.
handle: dict[str, Any]


def media_type(content_type: str | None) -> str:
"""The bare, lowercased media type of a ``Content-Type`` header value.

Expand Down Expand Up @@ -349,6 +374,7 @@ def model_run_request(
model_provider: str | None = None,
strict_mode: bool | None = None,
fallback_provider: bool | str | None = None,
respond_async: bool = False,
) -> tuple[str, dict[str, Any], dict[str, str]]:
"""Sans-IO ``(path, json_body, headers)`` for one model run.

Expand All @@ -366,6 +392,11 @@ def model_run_request(

``arguments`` is copied into a plain dict so any ``Mapping`` is accepted and
the caller's object is never handed to the JSON encoder directly.

``respond_async`` adds ``Prefer: respond-async`` (RFC 7240), the opt-in
under which Router may answer ``202`` with a queue handle instead of
holding the connection for the result. Off, no ``Prefer`` is sent at all,
so the request is byte-for-byte the one this route has always made.
"""
provider, name = parse_model_id(model)
path = _MODEL_RUN_PATH_TEMPLATE.format(
Expand All @@ -376,6 +407,8 @@ def model_run_request(
path = f"{path}?{query}"
body: dict[str, Any] = dict(arguments)
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
if respond_async:
headers["Prefer"] = "respond-async"
return path, body, headers


Expand Down Expand Up @@ -701,6 +734,26 @@ def parse_or_raise(self, resp: httpx.Response, ok: tuple[int, ...]) -> dict[str,
return self._decode_json(resp)
self._raise_for_response(resp)

def parse_run_outcome(self, resp: httpx.Response) -> dict[str, Any] | BinaryResult | RunHandoff:
"""A model run's answer: its finished result, or the ``202`` handoff.

The ``202`` body is the queue handle, which is JSON whatever the model
produces, so it is decoded as :meth:`parse_or_raise` decodes any
document; everything else is :meth:`parse_run_result`'s, unchanged.
"""
if resp.status_code == 202:
handle: Any = self.parse_or_raise(resp, (202,))
if not isinstance(handle, dict):
raise ApiError(
"The 202 model run handoff is not a JSON object",
code="invalid_response",
http_status=resp.status_code,
request_id=_request_id(resp),
body_excerpt=_body_excerpt(resp),
)
return RunHandoff(handle=handle)
return self.parse_run_result(resp, (200, 201))

def parse_run_result(
self, resp: httpx.Response, ok: tuple[int, ...]
) -> dict[str, Any] | BinaryResult:
Expand Down Expand Up @@ -1387,17 +1440,19 @@ def post_model_run(
model_provider: str | None = None,
strict_mode: bool | None = None,
fallback_provider: bool | str | None = None,
respond_async: bool = False,
timeout: Any = MODEL_RUN_TIMEOUT,
) -> tuple[dict[str, Any] | BinaryResult, Mapping[str, str]]:
) -> tuple[dict[str, Any] | BinaryResult | RunHandoff, Mapping[str, str]]:
"""POST ``{router_base_url}/v2/models/{provider}/{model}`` — awaited server-side.

Addressed to Comfy Router, not to the ``/api/v2`` deployment
:attr:`base_url` names: the URL is built absolute against
:attr:`router_base_url` precisely so it does not pick up the ``/api/v2``
prefix ``_Prepared.url`` adds to a relative path.

One request, one response: the server does not answer until the
generation is complete, so the decoded body *is* the finished result.
One request, one response: unless ``respond_async`` asks otherwise (see
below), the server does not answer until the generation is complete, so
the decoded body *is* the finished result.
That holds for a submit/poll provider too — the polling happens server
side, inside this call, which is why the default ``timeout`` is
:data:`MODEL_RUN_TIMEOUT` rather than the client's own.
Expand Down Expand Up @@ -1431,6 +1486,15 @@ def post_model_run(
schema could not carry every field. Returning the body alone discarded
both, so a caller could not tell an alt-provider run from a native one.

``respond_async`` sends ``Prefer: respond-async``. A ``202`` -- which
Router sends only to a caller that asked, on a model it hands off --
comes back as a :class:`RunHandoff` holding the queue handle rather
than as a result; following it is the caller's. A ``202`` is accepted
whether or not this call asked, because a resend under an
``Idempotency-Key`` whose first request was handed off can be answered
with that handoff again, and raising on it would leave the caller no
way back to a generation it already started.

Raises ``TypeError``/``ValueError`` from :func:`parse_model_id` before
any request when ``model`` is not a ``{provider}/{model}`` id.
"""
Expand All @@ -1441,10 +1505,11 @@ def post_model_run(
model_provider=model_provider,
strict_mode=strict_mode,
fallback_provider=fallback_provider,
respond_async=respond_async,
)
url = self._p.router_base_url + path
resp = self.raw_request("POST", url, headers=headers, json=body, timeout=timeout)
return self._p.parse_run_result(resp, (200, 201)), resp.headers
return self._p.parse_run_outcome(resp), resp.headers

# -- models: the queued form ------------------------------------------
#
Expand Down Expand Up @@ -1913,8 +1978,9 @@ async def post_model_run(
model_provider: str | None = None,
strict_mode: bool | None = None,
fallback_provider: bool | str | None = None,
respond_async: bool = False,
timeout: Any = MODEL_RUN_TIMEOUT,
) -> tuple[dict[str, Any] | BinaryResult, Mapping[str, str]]:
) -> tuple[dict[str, Any] | BinaryResult | RunHandoff, Mapping[str, str]]:
"""Async :meth:`ComfyLow.post_model_run` — same ``dict | BinaryResult`` body."""
path, body, headers = model_run_request(
model,
Expand All @@ -1923,10 +1989,11 @@ async def post_model_run(
model_provider=model_provider,
strict_mode=strict_mode,
fallback_provider=fallback_provider,
respond_async=respond_async,
)
url = self._p.router_base_url + path
resp = await self.raw_request("POST", url, headers=headers, json=body, timeout=timeout)
return self._p.parse_run_result(resp, (200, 201)), resp.headers
return self._p.parse_run_outcome(resp), resp.headers

# -- models: the queued form ------------------------------------------
async def post_model_submit(
Expand Down Expand Up @@ -2004,4 +2071,4 @@ def _looks_like_path(s: str) -> bool:
return s.startswith("http") or s.startswith("/")


__all__ = ["ComfyLow", "AsyncComfyLow", "ApiError", "BinaryResult"]
__all__ = ["ComfyLow", "AsyncComfyLow", "ApiError", "BinaryResult", "RunHandoff"]
54 changes: 42 additions & 12 deletions src/comfy_sdk/model_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@
#: transport failure rather than an answer.
_MIN_HTTP_TIMEOUT = 1.0

#: "No HTTP timeout of its own: use the client's." Distinct from ``None``, which
#: is a caller's explicit "no limit" and has to reach the request as that.
_INHERIT_TIMEOUT: Any = object()

#: HTTP timeout, in seconds, for the best-effort cleanup cancel ``subscribe``
#: issues after its own timeout -- see ``RequestHandle._cancel_best_effort``.
_CANCEL_TIMEOUT = 10.0
Expand Down Expand Up @@ -582,14 +586,16 @@ def _bounded(policy: RetryPolicy, budget: float | None) -> RetryPolicy:
)


def _http_timeout(budget: float | None) -> dict[str, Any]:
def _http_timeout(budget: float | None, fallback: Any = _INHERIT_TIMEOUT) -> dict[str, Any]:
"""Keyword arguments bounding one low-level call's HTTP timeout by ``budget``.

Empty when there is no budget, so the client's own timeout applies. Floored
at :data:`_MIN_HTTP_TIMEOUT` for the reason given there.
With no budget, ``fallback`` applies -- ``None`` included, which is an
explicit "no limit" -- unless it is :data:`_INHERIT_TIMEOUT`, when the
client's own timeout does. A budget is floored at
:data:`_MIN_HTTP_TIMEOUT` for the reason given there.
"""
if budget is None:
return {}
return {} if fallback is _INHERIT_TIMEOUT else {"timeout": fallback}
return {"timeout": max(budget, _MIN_HTTP_TIMEOUT)}


Expand All @@ -600,6 +606,13 @@ class _RequestHandleBase:
_request_id: str
_retry: RetryPolicy
_estimate: CostEstimate | 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``
#: handoff sets the run's own ``timeout`` here (``None``, no limit,
#: included), so each read keeps the limits the run was called with rather
#: than falling back to the client's.
_request_timeout: Any = _INHERIT_TIMEOUT

@property
def model(self) -> str:
Expand Down Expand Up @@ -690,7 +703,7 @@ def _status(self, *, budget: float | None) -> QueueUpdate:
with translating():
payload, headers = self._call(
lambda: self._low.get_model_request_status(
self._model, self._request_id, **_http_timeout(budget)
self._model, self._request_id, **_http_timeout(budget, self._request_timeout)
),
budget=budget,
)
Expand Down Expand Up @@ -786,11 +799,22 @@ def _collect(
``budget`` is what is left of the caller's deadline, and bounds the
fetch the way :meth:`_status` bounds a poll.
"""
return self._collect_with_headers(completion, budget=budget)[0]

def _collect_with_headers(
self, completion: QueueUpdate, *, budget: float | None = None
) -> tuple[dict[str, Any] | BinaryResult, httpx.Headers]:
""":meth:`_collect`, plus the result fetch's response headers.

For ``models.run_detailed`` following a ``202`` handoff, whose
:class:`~comfy_sdk.models.RouterRunResult` is read off the headers of
the response that carried the output.
"""
_raise_for_completion(completion.raw, request_id=self._request_id)
with translating():
payload, _headers = self._call(
payload, headers = self._call(
lambda: self._low.get_model_request_result(
self._model, self._request_id, **_http_timeout(budget)
self._model, self._request_id, **_http_timeout(budget, self._request_timeout)
),
budget=budget,
)
Expand All @@ -799,7 +823,7 @@ def _collect(
# is how a failure gets returned as a result. A `BinaryResult` is not a
# `Mapping` and so never carries one -- it is bytes, not an envelope.
_raise_for_completion(payload, request_id=self._request_id, envelope_only=True)
return payload
return payload, headers

def cancel(self) -> QueueUpdate:
"""Ask the server to cancel this request.
Expand Down Expand Up @@ -891,7 +915,7 @@ async def _status(self, *, budget: float | None) -> QueueUpdate:
with translating():
payload, headers = await self._call(
lambda: self._low.get_model_request_status(
self._model, self._request_id, **_http_timeout(budget)
self._model, self._request_id, **_http_timeout(budget, self._request_timeout)
),
budget=budget,
)
Expand Down Expand Up @@ -930,16 +954,22 @@ async def _collect(
self, completion: QueueUpdate, *, budget: float | None = None
) -> dict[str, Any] | BinaryResult:
"""Async :meth:`RequestHandle._collect`."""
return (await self._collect_with_headers(completion, budget=budget))[0]

async def _collect_with_headers(
self, completion: QueueUpdate, *, budget: float | None = None
) -> tuple[dict[str, Any] | BinaryResult, httpx.Headers]:
"""Async :meth:`RequestHandle._collect_with_headers`."""
_raise_for_completion(completion.raw, request_id=self._request_id)
with translating():
payload, _headers = await self._call(
payload, headers = await self._call(
lambda: self._low.get_model_request_result(
self._model, self._request_id, **_http_timeout(budget)
self._model, self._request_id, **_http_timeout(budget, self._request_timeout)
),
budget=budget,
)
_raise_for_completion(payload, request_id=self._request_id, envelope_only=True)
return payload
return payload, headers

async def cancel(self) -> QueueUpdate:
"""Async :meth:`RequestHandle.cancel` — a request, not a guarantee."""
Expand Down
Loading
Loading