litellm/tests/unit/integrations/arize/test_arize_otel_coexistence.py
yuneng-jiang cf491d1df9
test: move tests/test_litellm integrations and secret_managers into tests/unit (#43194)
* ci: run the unit_selection.sh shard files on every event instead of only fork pull requests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci: rename fork-flag to unit-flag now that it applies on every event

* test: move tests/test_litellm root and small trees into tests/unit

Pure renames, no content changes. Follow-up commits in this PR fix
references, merge the three files that already existed in tests/unit,
keep live-provider tests in tests/test_litellm and wire CI.

* test: carry tests/test_litellm conftest isolation into tests/unit

Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS,
proxy-URL and keychain env, and session-end client cleanup now reset for
unit tests too. The environment isolation owns its MonkeyPatch so a test's
own monkeypatch is undone before the model-cost teardown runs.

* test: merge, split and prune the moved root and small-tree tests

Merge batches/test_batch_utils.py and the chat_completions and messages
dispatch tests into the files that already existed in tests/unit. Keep
the live Gemini interactions tests, the async image-fetch format test and
the OpenAI embedding scorer test in tests/test_litellm since they need
real network or keys. Put test_router.py under tests/unit/test_router so
the existing package no longer shadows it. Delete eight tests the audit
found superseded by stronger ones kept in this move.

* ci: run the moved root and small-tree tests under their legacy flags

Add the misc and responses-caching-types flags to unit_selection.sh and
CircleCI, extend enterprise-routing and mcp-integration, and point the
legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest
and change classifier at the new paths.

* test: make the new tests/unit directories packages

tests/unit/test_package_layout.py requires every directory to carry an
__init__.py, and without one the moved and retained
test_litellm_responses_bridge.py modules collide on import.

* test: scope the unit socket block to tests/unit in shared sessions

The GHA shards collect the legacy test-path and the unit selection in one
pytest session. The unit conftest's loopback-only block leaked into legacy
modules that reach the network at import. The legacy conftest now lifts the
restriction at collect and setup time, and the unit conftest re-applies it
when collecting its own modules.

* test: move tests/test_litellm/llms into tests/unit/llms

Rename-only. Moves the provider tests and the fine-tuning fixtures they
load, mirroring the old paths. Follow-up commits merge, split and wire them.

* test: merge, split and prune the moved llms tests

Merges the Databricks chat transformation tests into the existing unit
file, keeps the tests that need real keys or the network in
tests/test_litellm, deletes the audited tests a stronger unit test
already covers, and points imports at tests.unit.llms.

* ci: run the moved llms tests under their legacy flags

The Vertex AI and All Other Providers shards keep their legacy test-path
for the retained files and add the llm-vertex-ai and llm-other-providers
unit selections. CircleCI gets matching unit jobs.

* test: make the tests/unit/llms directories packages

Adds __init__.py to the moved dirs and drops the legacy ones whose
directories no longer hold tests.

* test: drop script runners and path hacks the llms split left dangling

The __main__ runners in the split openai_like files and the Databricks e2e
runner called tests that now live in the other half of the split or were
deleted. The retained legacy halves also no longer need sys.path edits.

* test: give the shard-script tests their own GITHUB_OUTPUT

They only passed where the runner set it. The CircleCI unit job's env
allowlist drops it, so the script's redirect failed there.

* test: point the router and module-deletion checks at tests/unit

router_code_coverage and code_qa_check_tests only searched tests/test_litellm,
so the moved router tests no longer counted. The two silent-experiment tests
the audit deleted were the only direct callers of those methods; they are
replaced with tests that assert the forwarded shadow request and the
recursion guard.

* test: move tests/test_litellm integrations and secret_managers into tests/unit

Rename-only. Mirrors the old paths, including the directory conftests
and the prompt and JSON fixtures. Follow-up commits prune and wire them.

* test: prune and repoint the moved integrations tests

Deletes the 7 audited tests a stronger test in the same tree already
covers, imports the TLS sink helpers from their new conftest path, and
restores os.environ after each integrations test. Some presets write
OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the
legacy tree's test ordering that header leaked into the AgentOps tests.

* ci: run the moved integrations tests under their legacy flag

The integrations GHA shard and a new CircleCI job run the integrations
unit selection. secret_managers joins the misc selection.

* docs: point integrations and secret_managers references at tests/unit

* test: make the moved integrations directories packages

* test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path

The Databricks e2e file is a manual script whose main() calls the tests
that were pruned, so pruning them broke the documented run. It is back to
its main version. The SageMaker Nova docstring now points at the file's
real location in tests/local_testing.

* test: keep the job's UNIT_FLAG out of the shard-script tests

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-25 12:57:07 -07:00

235 lines
8.9 KiB
Python

"""
Tests that Arize Phoenix / Arize and the generic ``otel`` callback can
coexist, each sending spans to their own independent exporter.
Covers the three root-cause fixes:
1. ArizePhoenixLogger / ArizeLogger create *dedicated* TracerProviders.
2. The ``otel`` dedup check does NOT match Arize subclasses.
3. Arize loggers do NOT overwrite ``proxy_server.open_telemetry_logger``.
4. Phoenix creates nested spans (parent + child) in proxy mode.
5. Auto-initialization of Phoenix when env vars are detected.
"""
import os
import unittest
from unittest.mock import patch
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_otel_logger(exporter: InMemorySpanExporter) -> OpenTelemetry:
"""Create a generic ``otel`` callback backed by an in-memory exporter.
We build a dedicated TracerProvider explicitly so the test is isolated
from whatever global provider state may exist.
"""
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
config = OpenTelemetryConfig(exporter=exporter)
return OpenTelemetry(config=config, callback_name="otel", tracer_provider=provider)
def _make_arize_phoenix_logger(exporter: InMemorySpanExporter):
"""Create an ``arize_phoenix`` callback backed by an in-memory exporter.
ArizePhoenixLogger._init_tracing creates its own TracerProvider, so we
pass the exporter via config and let it build the provider internally.
"""
from litellm.integrations.arize.arize_phoenix import ArizePhoenixLogger
config = OpenTelemetryConfig(exporter=exporter)
return ArizePhoenixLogger(config=config, callback_name="arize_phoenix")
def _make_arize_logger(exporter: InMemorySpanExporter):
"""Create an ``arize`` callback backed by an in-memory exporter.
ArizeLogger._init_tracing creates its own TracerProvider, so we pass
the exporter via config and let it build the provider internally.
"""
from litellm.integrations.arize.arize import ArizeLogger
config = OpenTelemetryConfig(exporter=exporter)
return ArizeLogger(config=config, callback_name="arize")
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestIndependentTracerProviders(unittest.TestCase):
"""Each integration must get its own TracerProvider so spans go to the right exporter."""
def test_otel_and_arize_phoenix_have_different_tracer_providers(self):
otel_exporter = InMemorySpanExporter()
phoenix_exporter = InMemorySpanExporter()
otel_logger = _make_otel_logger(otel_exporter)
phoenix_logger = _make_arize_phoenix_logger(phoenix_exporter)
# The tracers must come from different providers
assert otel_logger.tracer is not phoenix_logger.tracer
def test_otel_and_arize_have_different_tracer_providers(self):
otel_exporter = InMemorySpanExporter()
arize_exporter = InMemorySpanExporter()
otel_logger = _make_otel_logger(otel_exporter)
arize_logger = _make_arize_logger(arize_exporter)
assert otel_logger.tracer is not arize_logger.tracer
def test_arize_phoenix_and_arize_have_different_tracer_providers(self):
phoenix_exporter = InMemorySpanExporter()
arize_exporter = InMemorySpanExporter()
phoenix_logger = _make_arize_phoenix_logger(phoenix_exporter)
arize_logger = _make_arize_logger(arize_exporter)
assert phoenix_logger.tracer is not arize_logger.tracer
class TestSpansRoutedToCorrectExporter(unittest.TestCase):
"""Spans created by each logger must land in its own exporter, not the other's."""
def test_spans_go_to_respective_exporters(self):
otel_exporter = InMemorySpanExporter()
phoenix_exporter = InMemorySpanExporter()
otel_logger = _make_otel_logger(otel_exporter)
phoenix_logger = _make_arize_phoenix_logger(phoenix_exporter)
# Create a span on each — SimpleSpanProcessor exports synchronously on end()
otel_span = otel_logger.tracer.start_span("otel_test_span")
otel_span.end()
phoenix_span = phoenix_logger.tracer.start_span("phoenix_test_span")
phoenix_span.end()
# Read spans *before* shutdown (shutdown clears the in-memory store)
otel_span_names = [s.name for s in otel_exporter.get_finished_spans()]
phoenix_span_names = [s.name for s in phoenix_exporter.get_finished_spans()]
assert "otel_test_span" in otel_span_names
assert "phoenix_test_span" not in otel_span_names
assert "phoenix_test_span" in phoenix_span_names
assert "otel_test_span" not in phoenix_span_names
class TestOtelDedupCheck(unittest.TestCase):
"""The ``otel`` callback dedup must use exact type check, not isinstance."""
def test_arize_phoenix_logger_is_not_matched_by_otel_dedup(self):
from litellm.integrations.arize.arize_phoenix import ArizePhoenixLogger
phoenix_logger = _make_arize_phoenix_logger(InMemorySpanExporter())
# isinstance would match — but type() must not
assert isinstance(phoenix_logger, OpenTelemetry)
assert type(phoenix_logger) is not OpenTelemetry
def test_arize_logger_is_not_matched_by_otel_dedup(self):
from litellm.integrations.arize.arize import ArizeLogger
arize_logger = _make_arize_logger(InMemorySpanExporter())
assert isinstance(arize_logger, OpenTelemetry)
assert type(arize_logger) is not OpenTelemetry
def test_otel_logger_matches_own_dedup(self):
otel_logger = _make_otel_logger(InMemorySpanExporter())
assert type(otel_logger) is OpenTelemetry
class TestProxyLoggerNotOverwritten(unittest.TestCase):
"""Arize / Phoenix must not overwrite ``proxy_server.open_telemetry_logger``."""
@patch("litellm.proxy.proxy_server.open_telemetry_logger", None)
def test_arize_phoenix_does_not_set_proxy_otel_logger(self):
from litellm.proxy import proxy_server
_make_arize_phoenix_logger(InMemorySpanExporter())
assert proxy_server.open_telemetry_logger is None
@patch("litellm.proxy.proxy_server.open_telemetry_logger", None)
def test_arize_does_not_set_proxy_otel_logger(self):
from litellm.proxy import proxy_server
_make_arize_logger(InMemorySpanExporter())
assert proxy_server.open_telemetry_logger is None
class TestPhoenixAutoInitWithOtelOnly(unittest.TestCase):
"""When only 'otel' is configured but Phoenix env vars are set,
ArizePhoenixLogger should be auto-initialized and receive spans."""
def setUp(self):
"""Save original callbacks to restore after each test."""
import litellm
self._original_callbacks = litellm.callbacks[:]
def tearDown(self):
"""Restore original callbacks to prevent global state leakage."""
import litellm
litellm.callbacks = self._original_callbacks
@patch.dict(
os.environ,
{
"PHOENIX_COLLECTOR_HTTP_ENDPOINT": "http://localhost:6006/v1/traces",
},
clear=False,
)
def test_auto_init_creates_phoenix_logger(self):
from litellm.integrations.arize.arize_phoenix import ArizePhoenixLogger
from litellm.litellm_core_utils.litellm_logging import (
_maybe_auto_initialize_arize_phoenix,
)
_in_memory_loggers = []
_maybe_auto_initialize_arize_phoenix(_in_memory_loggers)
phoenix_loggers = [
cb for cb in _in_memory_loggers if isinstance(cb, ArizePhoenixLogger)
]
assert (
len(phoenix_loggers) == 1
), "Phoenix logger should be auto-initialized when env vars are set"
def test_no_auto_init_without_env_vars(self):
from litellm.integrations.arize.arize_phoenix import ArizePhoenixLogger
from litellm.litellm_core_utils.litellm_logging import (
_maybe_auto_initialize_arize_phoenix,
)
env_keys = [
"PHOENIX_API_KEY",
"PHOENIX_COLLECTOR_HTTP_ENDPOINT",
"PHOENIX_COLLECTOR_ENDPOINT",
]
with patch.dict(os.environ, {k: "" for k in env_keys}, clear=False):
for k in env_keys:
os.environ.pop(k, None)
_in_memory_loggers = []
_maybe_auto_initialize_arize_phoenix(_in_memory_loggers)
phoenix_loggers = [
cb for cb in _in_memory_loggers if isinstance(cb, ArizePhoenixLogger)
]
assert len(phoenix_loggers) == 0
if __name__ == "__main__":
unittest.main()