Files
crewAI/lib/crewai/tests/telemetry/test_tracer_isolation.py
João Moura 094b94e8d0
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
fix(core): scope span export to our own tracer provider (#6954)
* fix(telemetry): stop exporting third-party spans to the collector

set_tracer() installed CrewAI's TracerProvider as the global one, so every
OTel-instrumented library in the host process - HTTP servers, Redis clients,
ORMs - resolved trace.get_tracer() to our provider and exported to CrewAI's
endpoint. A 20M-row sample of the telemetry table found 18,866 distinct
operation names under our serviceName; CrewAI emits 21.

The same wiring lost data in the other direction: when an application had
already installed its own provider, our spans were created by theirs and went
to their collector, so CrewAI received nothing from instrumented processes.

Spans are now created from the private provider in both packages. Deletes
_attach_common_attributes and its WeakSet/lock, whose multi-provider dedupe
guarded a state that can no longer occur.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(telemetry): keep process context on crewai-core spans

Isolating each package to its own TracerProvider removed an accident the CLI
spans depended on: crewai_core.telemetry had no CommonAttributesSpanProcessor,
so its spans only ever carried coding_agent/runtime_context/project_id by
riding the global provider that crewai installed at import.

A differential capture of every span reaching the exporter showed 8 of 54 spans
losing those attributes - Feature Usage (cli_usage:*), Start Deployment,
Template Installed, Create Crew Deployment, Get Crew Logs, Remove Crew,
Deploy Signup Error and Flow Creation.

Moves the marker tables and the detect_* helpers to crewai_core.runtime_env and
the processor plus common_span_attributes() to crewai_core.telemetry, so both
implementations share one source of truth. crewai.telemetry.utils and
crewai.utilities.constants re-export the moved names, so their import paths are
unchanged.

Also fixes a gap that predates the isolation change: a CLI-only process never
imports crewai, so it never reported either attribute. It does now.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(core): type test helpers and stop tests reaching the collector

mypy runs over lib/crewai-core/tests (the one test tree not excluded), so the
new test file needed full annotations and a narrowed span.attributes.

Also patches SafeOTLPSpanExporter before Telemetry is constructed and shuts the
provider down afterwards: __init__ wires a BatchSpanProcessor around the real
OTLP exporter, so each test was attempting a live export and leaving its batch
worker thread running.

Corrects the marker-precedence docstring, which named Cursor third when the
table checks it last so that assistants running inside its terminal are not
masked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* style(core): use one import form per module in telemetry tests

Both test modules imported their telemetry module twice - once aliased for the
monkeypatch target and once via from-import for the names. Dropping the alias
in favour of monkeypatch's dotted-string target leaves a single import form and
removes the need to qualify every reference.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* docs(core): drop comments that restate the code

The TRACER_NAME constants were annotated with what their name and
set_tracer()'s docstring already say, and the test fixtures narrated
provider.shutdown() and the exporter patch at more length than either needed.

Keeps the ones carrying something the code cannot: the resource-attribute
ingestion quirk, why the marker tables moved packages, and the two ordering
traps the fixtures exist to avoid.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 00:16:27 +00:00

129 lines
4.5 KiB
Python

"""Telemetry must export our spans and only our spans.
Regression cover for the collector receiving third-party application traces:
``set_tracer()`` used to install CrewAI's ``TracerProvider`` as the global one,
so every OTel-instrumented library in the host process - HTTP servers, Redis
clients, ORMs - resolved ``trace.get_tracer()`` to our provider and shipped its
spans to CrewAI's endpoint.
"""
from typing import Any
from unittest.mock import patch
import opentelemetry.trace as ot
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExportResult
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
import pytest
from crewai.telemetry.constants import TRACER_NAME
from crewai.telemetry.telemetry import Telemetry
class _NullExporter:
"""Stands in for the OTLP exporter so no test attempts a real export."""
def export(self, spans: Any) -> SpanExportResult:
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
pass
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
@pytest.fixture
def telemetry_with_exporter(monkeypatch):
"""A fresh Telemetry whose provider exports into memory.
Telemetry is a process-wide singleton that registers atexit and signal
handlers on init, so the instance is replaced for the duration of the test
and lifecycle registration is suppressed.
"""
monkeypatch.setattr(Telemetry, "_instance", None)
monkeypatch.setattr(Telemetry, "_register_shutdown_handlers", lambda self: None)
# Set for the whole test: _is_telemetry_disabled() is re-read on every span
# call, and the suite runs with OTEL_SDK_DISABLED set.
monkeypatch.setenv("CREWAI_DISABLE_TELEMETRY", "false")
monkeypatch.setenv("CREWAI_DISABLE_TRACKING", "false")
monkeypatch.setenv("OTEL_SDK_DISABLED", "false")
# Patched before construction: __init__ wires the real OTLP exporter, which
# would make every test here attempt a live export.
monkeypatch.setattr(
"crewai.telemetry.telemetry.SafeOTLPSpanExporter",
lambda **_kwargs: _NullExporter(),
)
telemetry = Telemetry()
exporter = InMemorySpanExporter()
telemetry.provider.add_span_processor(SimpleSpanProcessor(exporter))
try:
yield telemetry, exporter
finally:
telemetry.provider.shutdown()
Telemetry._instance = None
def test_third_party_spans_never_reach_our_exporter(telemetry_with_exporter):
"""A dependency instrumenting itself must not export to CrewAI."""
telemetry, exporter = telemetry_with_exporter
telemetry.set_tracer()
ot.get_tracer("redis.client").start_span("XLEN").end()
ot.get_tracer("opentelemetry.instrumentation.asgi").start_span(
"GET /status http send"
).end()
assert exporter.get_finished_spans() == ()
def test_our_own_spans_still_reach_our_exporter(telemetry_with_exporter):
"""The isolation must not cost us the telemetry we do want."""
telemetry, exporter = telemetry_with_exporter
telemetry.set_tracer()
telemetry.feature_usage_span("cli_usage:view_traces")
assert [span.name for span in exporter.get_finished_spans()] == ["Feature Usage"]
def test_our_spans_are_unaffected_by_an_application_provider(telemetry_with_exporter):
"""An app that installs its own provider must not divert our telemetry.
Resolving our tracer globally meant that in an already-instrumented
application our spans were created by the application's provider and went
to its collector, so CrewAI received nothing at all from those processes.
"""
telemetry, exporter = telemetry_with_exporter
app_exporter = InMemorySpanExporter()
app_provider = TracerProvider()
app_provider.add_span_processor(SimpleSpanProcessor(app_exporter))
with patch.object(ot, "get_tracer_provider", return_value=app_provider):
telemetry.set_tracer()
telemetry.feature_usage_span("cli_usage:deploy")
assert [span.name for span in exporter.get_finished_spans()] == ["Feature Usage"]
assert app_exporter.get_finished_spans() == ()
def test_set_tracer_is_idempotent(telemetry_with_exporter):
"""Repeated calls must not stack processors or duplicate exports."""
telemetry, exporter = telemetry_with_exporter
telemetry.set_tracer()
telemetry.set_tracer()
telemetry.set_tracer()
telemetry.provider.get_tracer(TRACER_NAME).start_span("Crew Created").end()
assert len(exporter.get_finished_spans()) == 1