Skip to content

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

fix(images): use ImagesAborted (not CancelledError) for signal-abort observers

xf gong75908e6f3413
diff --git a/cubepi/__init__.py b/cubepi/__init__.py
index 1d71dd4..f22708f 100644
--- a/cubepi/__init__.py
+++ b/cubepi/__init__.py
@@ -52,6 +52,7 @@ from cubepi.providers.capability import (
from cubepi.providers.images import (
AssistantImages,
BaseImagesProvider,
+ ImagesAborted,
ImagesCapabilityDescriptor,
ImagesContext,
ImagesCost,
@@ -75,6 +76,7 @@ __all__ = [
"BoundModel",
"CapabilityDescriptor",
"ContextLengthExceeded",
+ "ImagesAborted",
"ImagesCapabilityDescriptor",
"ImagesContext",
"ImagesCost",
diff --git a/cubepi/providers/images/__init__.py b/cubepi/providers/images/__init__.py
index d16172a..43418bd 100644
--- a/cubepi/providers/images/__init__.py
+++ b/cubepi/providers/images/__init__.py
@@ -12,6 +12,7 @@ from cubepi.providers.images.faux import FauxImagesProvider
from cubepi.providers.images.openai_images import OpenAIImagesProvider
from cubepi.providers.images.types import (
AssistantImages,
+ ImagesAborted,
ImagesContext,
ImagesCost,
ImagesModel,
@@ -22,6 +23,7 @@ __all__ = [
"AssistantImages",
"BaseImagesProvider",
"FauxImagesProvider",
+ "ImagesAborted",
"ImagesCapabilityDescriptor",
"ImagesContext",
"ImagesCost",
diff --git a/cubepi/providers/images/openai_images.py b/cubepi/providers/images/openai_images.py
index e9611b1..d1d45df 100644
--- a/cubepi/providers/images/openai_images.py
+++ b/cubepi/providers/images/openai_images.py
@@ -20,6 +20,7 @@ from cubepi.providers.images.base import BaseImagesProvider
from cubepi.providers.images.capability import ImagesCapabilityDescriptor
from cubepi.providers.images.types import (
AssistantImages,
+ ImagesAborted,
ImagesContext,
ImagesModel,
ImagesOptions,
@@ -38,17 +39,6 @@ _OUTPUT_FORMAT_MEDIA_TYPE = {
}
-class _SignalAborted(Exception):
- """Internal sentinel raised by ``_run_with_signal`` when
- ``ImagesOptions.signal`` triggers an abort.
-
- Distinct from :class:`asyncio.CancelledError` so that external
- cancellation (``task.cancel()``, ``asyncio.wait_for``, parent task
- teardown) propagates cleanly instead of being silently swallowed
- into ``AssistantImages(stop_reason="aborted")``.
- """
-
-
class OpenAIImagesProvider(BaseImagesProvider):
"""OpenAI-shape image provider.
@@ -132,11 +122,15 @@ class OpenAIImagesProvider(BaseImagesProvider):
return self._parse_response(sdk_resp, model, context, cap)
- except _SignalAborted:
+ except ImagesAborted as aborted:
# Signal-triggered abort: return as AssistantImages, do not re-raise.
- # A synthetic CancelledError is surfaced to response observers so
- # tracing can distinguish abort from successful completion.
- exc = asyncio.CancelledError("aborted via ImagesOptions.signal")
+ # The ImagesAborted instance is surfaced to response observers so
+ # tracing can distinguish abort from successful completion. It is
+ # deliberately NOT an asyncio.CancelledError — that would push the
+ # listener fanout onto its synchronous fast-path, scheduling async
+ # observers as detached tasks that asyncio.run() teardown can
+ # cancel before they ever run.
+ exc = aborted
return AssistantImages(
api=model.api,
provider_id=model.provider_id,
@@ -171,7 +165,7 @@ class OpenAIImagesProvider(BaseImagesProvider):
) -> Any:
"""Run ``sdk_call(**payload)`` while listening to ``signal``.
- Raises :class:`_SignalAborted` if ``signal`` fires first.
+ Raises :class:`ImagesAborted` if ``signal`` fires first.
Lets :class:`asyncio.CancelledError` from external cancellation
propagate unchanged so callers can detect it.
"""
@@ -187,7 +181,7 @@ class OpenAIImagesProvider(BaseImagesProvider):
)
if signal_task in done and not sdk_task.done():
sdk_task.cancel()
- raise _SignalAborted
+ raise ImagesAborted("aborted via ImagesOptions.signal")
signal_task.cancel()
return sdk_task.result()
finally:
diff --git a/cubepi/providers/images/types.py b/cubepi/providers/images/types.py
index 355ff0f..61eb52f 100644
--- a/cubepi/providers/images/types.py
+++ b/cubepi/providers/images/types.py
@@ -19,6 +19,7 @@ from cubepi.types import JsonObject
# under ``from __future__ import annotations``.
__all__ = [
"AssistantImages",
+ "ImagesAborted",
"ImagesContext",
"ImagesCost",
"ImagesModel",
@@ -27,6 +28,22 @@ __all__ = [
]
+class ImagesAborted(Exception):
+ """Signals that a :meth:`generate_images` call was aborted via
+ :attr:`ImagesOptions.signal`.
+
+ Surfaced to ``subscribe_response`` observers as the ``exc`` argument so
+ tracing / audit listeners can distinguish a deliberate abort from a
+ normal completion (``exc=None``) or a real failure (``ProviderError``
+ subclass). Deliberately **not** an :class:`asyncio.CancelledError` —
+ the response-listener fanout takes a synchronous fast-path when ``exc``
+ is a cancellation, which schedules async listeners as detached tasks
+ that can be cancelled by ``asyncio.run()`` teardown before they run.
+ Using a distinct, non-cancellation exception keeps observers on the
+ awaited path so they finish before the call returns.
+ """
+
+
class ImagesCost(BaseModel):
"""Image-generation pricing (per-image is dominant; per-megapixel for Imagen-like models)."""
diff --git a/tests/providers/images/test_openai_images.py b/tests/providers/images/test_openai_images.py
index 31893ce..9d633c6 100644
--- a/tests/providers/images/test_openai_images.py
+++ b/tests/providers/images/test_openai_images.py
@@ -280,9 +280,16 @@ def test_base_url_accepted_and_constructor_works():
@pytest.mark.asyncio
-async def test_subscribe_response_fires_on_abort_with_cancelled_error():
- """Abort path must surface CancelledError to response listeners so tracing
- can distinguish abort from successful completion (spec §6.5)."""
+async def test_subscribe_response_fires_on_abort_with_images_aborted():
+ """Signal-abort surfaces ImagesAborted (NOT CancelledError) to
+ response listeners. Two contracts are pinned here:
+ 1. Observers can distinguish abort from success — exc is non-None.
+ 2. exc is NOT an asyncio.CancelledError, so the listener fanout
+ takes the normal awaited path. If it were CancelledError, the
+ sync fast-path would schedule async listeners as detached tasks
+ that asyncio.run() teardown could cancel before they run."""
+ from cubepi.providers.images import ImagesAborted
+
p = _provider(sleep=0.5)
model = p.model("gpt-image-1")
signal = asyncio.Event()
@@ -306,7 +313,53 @@ async def test_subscribe_response_fires_on_abort_with_cancelled_error():
assert len(seen) == 1
body, exc = seen[0]
assert body is None
- assert isinstance(exc, asyncio.CancelledError)
+ assert isinstance(exc, ImagesAborted)
+ assert not isinstance(exc, asyncio.CancelledError)
+
+
+async def test_async_response_observer_awaited_on_abort():
+ """Regression: an *async* subscribe_response observer must finish
+ running before generate_images returns on the abort path.
+
+ Previously the observer was scheduled as a detached task (sync
+ fast-path triggered by exc being a CancelledError); under
+ asyncio.run() teardown those detached tasks were getting cancelled
+ before they could record the abort."""
+ from cubepi.providers.images import ImagesAborted
+
+ p = _provider(sleep=0.5)
+ model = p.model("gpt-image-1")
+ signal = asyncio.Event()
+ observed_exc: list[BaseException | None] = []
+
+ async def async_observer(body, m, exc):
+ # Yield to the event loop to prove we ran under normal awaited
+ # semantics rather than as a detached task that could be
+ # interrupted by teardown.
+ await asyncio.sleep(0)
+ observed_exc.append(exc)
+
+ p.subscribe_response(async_observer)
+
+ async def trigger():
+ await asyncio.sleep(0.05)
+ signal.set()
+
+ async with asyncio.TaskGroup() as tg:
+ tg.create_task(trigger())
+ task = tg.create_task(
+ p.generate_images(
+ model, ImagesContext(prompt="x"), options=ImagesOptions(signal=signal)
+ )
+ )
+
+ result = task.result()
+ assert result.stop_reason == "aborted"
+ # The async observer must have completed and recorded the abort
+ # before generate_images returned.
+ assert len(observed_exc) == 1
+ assert isinstance(observed_exc[0], ImagesAborted)
@pytest.mark.asyncio
diff --git a/tests/providers/images/test_types.py b/tests/providers/images/test_types.py
index 0a02c82..4510f26 100644
--- a/tests/providers/images/test_types.py
+++ b/tests/providers/images/test_types.py
@@ -143,6 +143,7 @@ def test_top_level_re_exports():
for name in (
"AssistantImages",
"BaseImagesProvider",
+ "ImagesAborted",
"ImagesCapabilityDescriptor",
"ImagesContext",
"ImagesCost",
diff --git a/website/docs/guides/providers/image-generation.md b/website/docs/guides/providers/image-generation.md
index ba785b1..3ffa88f 100644
--- a/website/docs/guides/providers/image-generation.md
+++ b/website/docs/guides/providers/image-generation.md
@@ -103,8 +103,27 @@ opts = ImagesOptions(
```
When `signal` is set mid-call, the SDK request is cancelled and the
-provider returns `AssistantImages(stop_reason="aborted", output=[])` —
-the `CancelledError` does not escape.
+provider returns `AssistantImages(stop_reason="aborted", output=[])`.
+The cancellation does not escape — external `task.cancel()` and
+`asyncio.wait_for(...)` cancellations still propagate as
+`asyncio.CancelledError`, only the signal-driven abort is converted.
+
+Response observers see the abort via an `ImagesAborted` exception (a
+plain `Exception` subclass, intentionally distinct from
+`asyncio.CancelledError` so async listeners still run on the awaited
+fast-path before the call returns):
+
+```python
+from cubepi.providers.images import ImagesAborted
+
+def on_response(body, model, exc):
+ if isinstance(exc, ImagesAborted):
+ ... # signal-driven abort — body is None
+ elif exc is not None:
+ ... # real failure (a ProviderError subclass)
+ else:
+ ... # success — body holds the assembled response
+```
`on_payload` and `on_response` are per-call hooks; for persistent
observers (tracing, audit), use `provider.subscribe_request()` /
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.md
index 7b75043..cf0bdc2 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.md
@@ -97,9 +97,26 @@ opts = ImagesOptions(
)
```
-中途 `signal.set()` 时,SDK 请求会被取消,provider 返回
-`AssistantImages(stop_reason="aborted", output=[])`,`CancelledError` 不
-冒出来。
+中途 `signal.set()` 时,SDK 请求被取消,provider 返回
+`AssistantImages(stop_reason="aborted", output=[])`,不向外抛出。
+外部的 `task.cancel()` / `asyncio.wait_for(...)` 取消仍以
+`asyncio.CancelledError` 形式正常传播——只有 signal 触发的 abort 会被转换。
+
+Response 观察者通过 `ImagesAborted` 异常(普通 `Exception` 子类,**故意不**
+继承 `asyncio.CancelledError`,这样 async listener 还能走 awaited 快路径
+在 generate 返回前完成)来看到 abort:
+
+```python
+from cubepi.providers.images import ImagesAborted
+
+def on_response(body, model, exc):
+ if isinstance(exc, ImagesAborted):
+ ... # signal 触发的 abort —— body 为 None
+ elif exc is not None:
+ ... # 真实失败(ProviderError 子类)
+ else:
+ ... # 成功 —— body 是已拼好的响应
+```
`on_payload` / `on_response` 是 per-call hook;对于持久观察者(tracing、
审计),用 `provider.subscribe_request()` / `provider.subscribe_response()`
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.7/guides/providers/image-generation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.7/guides/providers/image-generation.md
index 7b75043..cf0bdc2 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.7/guides/providers/image-generation.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.7/guides/providers/image-generation.md
@@ -97,9 +97,26 @@ opts = ImagesOptions(
)
```
-中途 `signal.set()` 时,SDK 请求会被取消,provider 返回
-`AssistantImages(stop_reason="aborted", output=[])`,`CancelledError` 不
-冒出来。
+中途 `signal.set()` 时,SDK 请求被取消,provider 返回
+`AssistantImages(stop_reason="aborted", output=[])`,不向外抛出。
+外部的 `task.cancel()` / `asyncio.wait_for(...)` 取消仍以
+`asyncio.CancelledError` 形式正常传播——只有 signal 触发的 abort 会被转换。
+
+Response 观察者通过 `ImagesAborted` 异常(普通 `Exception` 子类,**故意不**
+继承 `asyncio.CancelledError`,这样 async listener 还能走 awaited 快路径
+在 generate 返回前完成)来看到 abort:
+
+```python
+from cubepi.providers.images import ImagesAborted
+
+def on_response(body, model, exc):
+ if isinstance(exc, ImagesAborted):
+ ... # signal 触发的 abort —— body 为 None
+ elif exc is not None:
+ ... # 真实失败(ProviderError 子类)
+ else:
+ ... # 成功 —— body 是已拼好的响应
+```
`on_payload` / `on_response` 是 per-call hook;对于持久观察者(tracing、
审计),用 `provider.subscribe_request()` / `provider.subscribe_response()`
diff --git a/website/versioned_docs/version-0.7/guides/providers/image-generation.md b/website/versioned_docs/version-0.7/guides/providers/image-generation.md
index ba785b1..3ffa88f 100644
--- a/website/versioned_docs/version-0.7/guides/providers/image-generation.md
+++ b/website/versioned_docs/version-0.7/guides/providers/image-generation.md
@@ -103,8 +103,27 @@ opts = ImagesOptions(
```
When `signal` is set mid-call, the SDK request is cancelled and the
-provider returns `AssistantImages(stop_reason="aborted", output=[])` —
-the `CancelledError` does not escape.
+provider returns `AssistantImages(stop_reason="aborted", output=[])`.
+The cancellation does not escape — external `task.cancel()` and
+`asyncio.wait_for(...)` cancellations still propagate as
+`asyncio.CancelledError`, only the signal-driven abort is converted.
+
+Response observers see the abort via an `ImagesAborted` exception (a
+plain `Exception` subclass, intentionally distinct from
+`asyncio.CancelledError` so async listeners still run on the awaited
+fast-path before the call returns):
+
+```python
+from cubepi.providers.images import ImagesAborted
+
+def on_response(body, model, exc):
+ if isinstance(exc, ImagesAborted):
+ ... # signal-driven abort — body is None
+ elif exc is not None:
+ ... # real failure (a ProviderError subclass)
+ else:
+ ... # success — body holds the assembled response
+```
`on_payload` and `on_response` are per-call hooks; for persistent
observers (tracing, audit), use `provider.subscribe_request()` /