Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(images): classified-error observer parity + Faux listener fanout

xf gong13d2bebb9f2c
diff --git a/cubepi/providers/images/faux.py b/cubepi/providers/images/faux.py
index cefc7cb..904f4ad 100644
--- a/cubepi/providers/images/faux.py
+++ b/cubepi/providers/images/faux.py
@@ -1,10 +1,15 @@
from __future__ import annotations
from cubepi.errors import ProviderError
-from cubepi.providers.base import ImageContent
+from cubepi.providers.base import (
+ ImageContent,
+ _fire_request_listeners,
+ _fire_response_listeners,
+)
from cubepi.providers.images.base import BaseImagesProvider
from cubepi.providers.images.types import (
AssistantImages,
+ ImagesAborted,
ImagesContext,
ImagesModel,
ImagesOptions,
@@ -38,11 +43,39 @@ class FauxImagesProvider(BaseImagesProvider):
*,
options: ImagesOptions | None = None,
) -> AssistantImages:
- # Honor a pre-set abort signal the same way the real provider does
- # — return ``stop_reason="aborted"`` without the happy-path image
- # so tests / local flows that exercise cancellation behave the same
- # against Faux as they would against ``OpenAIImagesProvider``.
- if options and options.signal and options.signal.is_set():
+ # Faux mirrors OpenAIImagesProvider's observability semantics so
+ # tests that exercise listener wiring against Faux see the same
+ # contract as production: subscribe_request fires before the
+ # "send"; subscribe_response fires in finally with body + exc.
+ body: dict | None = None
+ exc: BaseException | None = None
+ try:
+ # Pre-set abort short-circuit (no listeners observe a payload
+ # for a call that won't run, matching the real provider).
+ if options and options.signal and options.signal.is_set():
+ raise ImagesAborted("signal was already set before generate_images()")
+
+ # Synthetic payload for observers: same canonical shape the
+ # real provider would have assembled at minimum.
+ payload: dict = {"model": model.id, "prompt": context.prompt}
+ if self._request_listeners:
+ await _fire_request_listeners(self._request_listeners, payload, model) # type: ignore[arg-type]
+
+ if self._raise is not None:
+ raise self._raise(
+ f"injected by FauxImagesProvider for {model.provider_id}/{model.id}"
+ )
+
+ body = {"data": [{"b64_json": self._png_b64, "media_type": "image/png"}]}
+ return AssistantImages(
+ api=model.api,
+ provider_id=model.provider_id,
+ model=model.id,
+ output=[ImageContent(source=self._png_b64, media_type="image/png")],
+ stop_reason="stop",
+ )
+ except ImagesAborted as aborted:
+ exc = aborted
return AssistantImages(
api=model.api,
provider_id=model.provider_id,
@@ -50,14 +83,16 @@ class FauxImagesProvider(BaseImagesProvider):
output=[],
stop_reason="aborted",
)
- if self._raise is not None:
- raise self._raise(
- f"injected by FauxImagesProvider for {model.provider_id}/{model.id}"
- )
- return AssistantImages(
- api=model.api,
- provider_id=model.provider_id,
- model=model.id,
- output=[ImageContent(source=self._png_b64, media_type="image/png")],
- stop_reason="stop",
- )
+ except BaseException as raw:
+ # Includes the injected raise_on_call ProviderError. Record
+ # for observers, then re-raise unchanged.
+ exc = raw
+ raise
+ finally:
+ if self._response_listeners:
+ await _fire_response_listeners(
+ self._response_listeners,
+ body,
+ model, # type: ignore[arg-type]
+ exc,
+ )
diff --git a/cubepi/providers/images/openai_images.py b/cubepi/providers/images/openai_images.py
index 31f5581..f131507 100644
--- a/cubepi/providers/images/openai_images.py
+++ b/cubepi/providers/images/openai_images.py
@@ -158,8 +158,15 @@ class OpenAIImagesProvider(BaseImagesProvider):
exc = cancel
raise
except Exception as raw: # noqa: BLE001
- exc = raw
- classify_and_raise(raw, model=model)
+ # classify_and_raise() raises a typed ProviderError subclass
+ # chained from ``raw``. Catch the classified version so the
+ # response listener observes the same typed error the caller
+ # sees, not the underlying SDK exception.
+ try:
+ classify_and_raise(raw, model=model)
+ except BaseException as classified:
+ exc = classified
+ raise
finally:
if self._response_listeners:
await _fire_response_listeners(
diff --git a/tests/providers/images/test_faux_provider.py b/tests/providers/images/test_faux_provider.py
index 1bd5be1..5a9faa4 100644
--- a/tests/providers/images/test_faux_provider.py
+++ b/tests/providers/images/test_faux_provider.py
@@ -103,3 +103,102 @@ async def test_unset_signal_still_returns_happy_path_image():
assert out.stop_reason == "stop"
assert len(out.output) == 1
assert out.output[0].media_type == "image/png"
+
+
+async def test_subscribe_request_fires_on_happy_path():
+ """Faux fires subscribe_request with a synthetic payload so observability
+ tests work the same way against Faux and OpenAIImagesProvider."""
+ p = FauxImagesProvider(png_b64=_png_b64())
+ model = p.model("faux-1")
+ seen: list = []
+ p.subscribe_request(lambda payload, m: seen.append(payload))
+
+ await p.generate_images(model, ImagesContext(prompt="hello"))
+ assert len(seen) == 1
+ assert seen[0]["model"] == "faux-1"
+ assert seen[0]["prompt"] == "hello"
+
+
+async def test_subscribe_response_fires_on_happy_path_with_no_exc():
+ p = FauxImagesProvider(png_b64=_png_b64())
+ model = p.model("faux-1")
+ seen: list = []
+ p.subscribe_response(lambda body, m, exc: seen.append((body, exc)))
+
+ await p.generate_images(model, ImagesContext(prompt="x"))
+ assert len(seen) == 1
+ body, exc = seen[0]
+ assert body is not None and "data" in body
+ assert exc is None
+
+
+async def test_subscribe_response_fires_on_raise_on_call_with_typed_exc():
+ """When raise_on_call injects RateLimited, the observer must see
+ the same exception class the caller catches."""
+ p = FauxImagesProvider(png_b64=_png_b64(), raise_on_call=RateLimited)
+ model = p.model("faux-1")
+ seen: list = []
+ p.subscribe_response(lambda body, m, exc: seen.append((body, exc)))
+
+ with pytest.raises(RateLimited):
+ await p.generate_images(model, ImagesContext(prompt="x"))
+
+ assert len(seen) == 1
+ body, exc = seen[0]
+ assert body is None
+ assert isinstance(exc, RateLimited)
+
+
+async def test_subscribe_response_fires_on_pre_set_abort_with_images_aborted():
+ """Faux abort path must surface ImagesAborted to response observers
+ the same way OpenAIImagesProvider does."""
+ import asyncio
+
+ from cubepi.providers.images import ImagesAborted
+ from cubepi.providers.images.types import ImagesOptions
+
+ p = FauxImagesProvider(png_b64=_png_b64())
+ model = p.model("faux-1")
+ signal = asyncio.Event()
+ signal.set()
+
+ seen: list = []
+ p.subscribe_response(lambda body, m, exc: seen.append((body, exc)))
+
+ await p.generate_images(
+ model,
+ ImagesContext(prompt="x"),
+ options=ImagesOptions(signal=signal),
+ )
+ assert len(seen) == 1
+ body, exc = seen[0]
+ assert body is None
+ assert isinstance(exc, ImagesAborted)
+
+
+async def test_pre_set_abort_skips_request_listener_in_faux():
+ """Pre-set signal aborts before subscribe_request fires — same
+ contract as OpenAIImagesProvider."""
+ import asyncio
+
+ from cubepi.providers.images.types import ImagesOptions
+
+ p = FauxImagesProvider(png_b64=_png_b64())
+ model = p.model("faux-1")
+ signal = asyncio.Event()
+ signal.set()
+
+ seen_requests: list = []
+ p.subscribe_request(lambda payload, m: seen_requests.append(payload))
+
+ await p.generate_images(
+ model,
+ ImagesContext(prompt="x"),
+ options=ImagesOptions(signal=signal),
+ )
+ assert seen_requests == []
diff --git a/tests/providers/images/test_openai_images.py b/tests/providers/images/test_openai_images.py
index a6e9c10..e187833 100644
--- a/tests/providers/images/test_openai_images.py
+++ b/tests/providers/images/test_openai_images.py
@@ -675,3 +675,25 @@ async def test_pre_set_signal_does_not_invoke_on_payload():
)
assert out.stop_reason == "aborted"
assert invoked == []
+
+
+async def test_subscribe_response_sees_typed_provider_error_not_raw_sdk():
+ """When classify_and_raise() converts a raw SDK exception into a
+ typed ProviderError, the response observer must see the SAME typed
+ error the caller catches — not the underlying SDK exception."""
+ p = _provider(exc=_StatusErr("rate limited", 429))
+ model = p.model("gpt-image-1")
+ seen: list = []
+ p.subscribe_response(lambda body, m, exc: seen.append(exc))
+
+ with pytest.raises(RateLimited) as caller_exc:
+ await p.generate_images(model, ImagesContext(prompt="x"))
+
+ assert len(seen) == 1
+ observed = seen[0]
+ # Observer sees the SAME typed class the caller does, NOT the raw
+ # _StatusErr SDK-side exception.
+ assert isinstance(observed, RateLimited)
+ assert observed is caller_exc.value
+ assert not isinstance(observed, _StatusErr)