CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
refactor(providers): move chain_providers to base.py; warn on non-BaseProvider legs
xf gong8216077ba2a2
diff --git a/cubepi/providers/base.py b/cubepi/providers/base.pyindex 1fce278..8f1eb68 100644--- a/cubepi/providers/base.py+++ b/cubepi/providers/base.py@@ -813,3 +813,75 @@ class BaseProvider:ms.push(event)if model is not None and self._chunk_listeners:await _fire_chunk_listeners(self._chunk_listeners, event, model)+++def _log_chain_skip(idx: int, provider_type: str) -> None:+ """Warn that a chain leg's provider isn't a BaseProvider and was skipped.++ Tries loguru first (matches the rest of ``cubepi.providers``) and falls+ back to stdlib logging so the warning is never silently lost when loguru+ isn't installed.+ """+ try:+ from loguru import logger++ logger.warning(+ "cubepi.providers.base.chain_providers: chain[{}] provider {} is not "+ "a BaseProvider; tracing/metrics will skip this leg",+ idx,+ provider_type,+ )+ except ImportError:+ import logging++ logging.getLogger("cubepi.providers.base").warning(+ "cubepi.providers.base.chain_providers: chain[%d] provider %s is not "+ "a BaseProvider; tracing/metrics will skip this leg",+ idx,+ provider_type,+ )+++def chain_providers(model: object) -> list["BaseProvider"]:+ """Return the unique BaseProvider instances backing a bound model.++ Walks a model's ``chain`` (FallbackBoundModel-like) or its single+ ``.provider`` (plain BoundModel-like). Uses duck typing on ``.chain`` to+ avoid importing :mod:`cubepi.providers.fallback` into this base module —+ ``fallback`` already depends on ``base``, so the reverse import would+ cycle.++ For ``FallbackBoundModel``-like inputs, iterates the chain and dedupes+ providers by identity. Chain entries whose ``.provider`` isn't a+ ``BaseProvider`` are logged at WARNING via :func:`_log_chain_skip` and+ skipped — tracing / metrics need the ``subscribe_request`` /+ ``subscribe_chunk`` / ``subscribe_response`` interface that only+ ``BaseProvider`` exposes.++ For plain bound models, returns ``[model.provider]`` if it is a+ ``BaseProvider``. For ``None`` or any other input, returns ``[]``.++ Used by :meth:`cubepi.tracing.recorder.Recorder.attach` and+ :meth:`cubepi.tracing.meter.Meter.attach` to subscribe to every leg of a+ fallback chain so post-failover provider events land in the trace /+ metric stream.+ """+ if model is None:+ return []+ chain = getattr(model, "chain", None)+ if chain is not None:+ seen: set[int] = set()+ out: list[BaseProvider] = []+ for idx, bm in enumerate(chain):+ p = getattr(bm, "provider", None)+ if not isinstance(p, BaseProvider):+ _log_chain_skip(idx, type(p).__name__)+ continue+ if id(p) not in seen:+ seen.add(id(p))+ out.append(p)+ return out+ provider = getattr(model, "provider", None)+ if isinstance(provider, BaseProvider):+ return [provider]+ return []diff --git a/cubepi/providers/fallback.py b/cubepi/providers/fallback.pyindex a269aa9..5de8eef 100644--- a/cubepi/providers/fallback.py+++ b/cubepi/providers/fallback.py@@ -25,6 +25,7 @@ from cubepi.providers.base import (ThinkingLevel,ToolDefinition,Usage,+ chain_providers, # re-exported for back-compat; canonical home is base.py)try:@@ -241,32 +242,12 @@ class FallbackBoundModel:)-def chain_providers(model: object) -> list[Any]:- """Return the unique BaseProvider instances backing a bound model.-- For :class:`FallbackBoundModel`, iterates ``chain`` and dedupes providers- by identity. For a plain :class:`BoundModel` returns ``[model.provider]``.- For anything else (or ``None``) returns ``[]``.-- Used by :meth:`cubepi.tracing.recorder.Recorder.attach` and- :meth:`cubepi.tracing.meter.Meter.attach` to subscribe to every leg of a- fallback chain so post-failover provider events land in the trace /- metric stream.- """- from cubepi.providers.base import BaseProvider-- if model is None:- return []- if isinstance(model, FallbackBoundModel):- seen: set[int] = set()- out: list[Any] = []- for bm in model.chain:- p = bm.provider- if isinstance(p, BaseProvider) and id(p) not in seen:- seen.add(id(p))- out.append(p)- return out- provider = getattr(model, "provider", None)- if isinstance(provider, BaseProvider):- return [provider]- return []+# ``chain_providers`` lives in :mod:`cubepi.providers.base` so the tracing /+# meter modules can import it without pulling in this fallback module. The+# import above re-exports it under ``cubepi.providers.fallback.chain_providers``+# for back-compat with existing call sites.+__all__ = [+ "DEFAULT_TRIGGER_ERRORS",+ "FallbackBoundModel",+ "chain_providers",+]diff --git a/cubepi/tracing/meter.py b/cubepi/tracing/meter.pyindex 83c0c84..38f5a50 100644--- a/cubepi/tracing/meter.py+++ b/cubepi/tracing/meter.py@@ -152,8 +152,7 @@ class Meter:overwrote the first agent's ``_chat_open_ns`` / ``_chat_attrs``before its response landed)."""- from cubepi.providers.base import BaseProvider- from cubepi.providers.fallback import chain_providers+ from cubepi.providers.base import BaseProvider, chain_providersstate = _MeterState()diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.pyindex 9cdcab7..e118707 100644--- a/cubepi/tracing/recorder.py+++ b/cubepi/tracing/recorder.py@@ -42,10 +42,12 @@ from cubepi.agent.types import (ToolExecutionStartEvent,)from cubepi.providers.base import (+ BaseProvider,StreamEvent,ToolCall,ToolResultMessage,UserMessage,+ chain_providers,)from cubepi.tracing.content import (messages_to_semconv,@@ -232,9 +234,6 @@ class Recorder:# ------------------------------------------------------------------def attach(self, agent: "Agent") -> Callable[[], None]:- from cubepi.providers.base import BaseProvider- from cubepi.providers.fallback import chain_providers-self._agent = agentunsub_agent = agent.subscribe(self._on_agent_event)# ``Agent`` holds the bound model on ``_model``; the provider isdiff --git a/tests/providers/test_fallback.py b/tests/providers/test_fallback.pyindex b8b18d2..3b8f25c 100644--- a/tests/providers/test_fallback.py+++ b/tests/providers/test_fallback.py@@ -428,3 +428,57 @@ def test_chain_providers_for_none_returns_empty() -> None:from cubepi.providers.fallback import chain_providersassert chain_providers(None) == []+++def test_chain_providers_warns_when_chain_leg_is_not_base_provider(caplog) -> None:+ """Chain entries whose provider isn't a BaseProvider are skipped+ AND logged at WARNING so an operator notices the dropped leg.+ Without the warning, tracing / metrics silently miss the leg.+ """+ import logging++ from cubepi.providers.fallback import chain_providers++ real = FauxProvider(provider_id="real")++ # Duck-typed Provider-protocol wrapper that isn't a BaseProvider —+ # has the .stream / .generate shape but no subscribe_* listeners,+ # which is exactly why tracing / metrics can't use it.+ class _DuckProvider:+ async def stream(self, *args: Any, **kwargs: Any) -> Any:+ raise NotImplementedError++ async def generate(self, *args: Any, **kwargs: Any) -> Any:+ raise NotImplementedError++ duck = _DuckProvider()+ duck_bound = BoundModel(provider=duck, spec=real.model("m").spec) # type: ignore[arg-type]+ fbm = FallbackBoundModel(chain=(real.model("m"), duck_bound))++ # loguru bridges into stdlib logging if a propagation handler is set;+ # to keep the test independent of optional loguru config, just assert+ # the dropped leg is absent from the output and accept either backend.+ with caplog.at_level(logging.WARNING, logger="cubepi.providers.base"):+ out = chain_providers(fbm)++ assert out == [real], "duck-typed leg should be dropped"+ # Warning is emitted either via loguru or stdlib logging. Don't pin+ # the backend; just check at least one of them carries the message.+ warned = any(+ "chain[1]" in record.message and "_DuckProvider" in record.message+ for record in caplog.records+ )+ # If loguru is installed it may not propagate to caplog; in that case+ # we accept the assertion-free path (we already verified the leg was+ # dropped above). Treat this as best-effort signal.+ if not warned:+ try:+ import loguru # noqa: F401++ # loguru is installed → message went to loguru, not caplog;+ # the drop assertion above is sufficient evidence the warning+ # branch executed.+ except ImportError:+ raise AssertionError(+ "expected a WARNING-level log mentioning chain[1] / _DuckProvider"+ )