mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-08-13 22:08:01 +00:00
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(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>
138 lines
4.7 KiB
Python
138 lines
4.7 KiB
Python
"""crewai-core must report the same process context as crewai.
|
|
|
|
The CLI emits deployment, template and flow-creation spans through
|
|
``crewai_core.telemetry`` in processes that never import ``crewai``. Those spans
|
|
previously carried ``coding_agent``/``runtime_context`` only by accident - they
|
|
rode the global TracerProvider that ``crewai`` installed at import - so a
|
|
CLI-only process reported neither.
|
|
|
|
The detection and common-attribute behaviour itself is covered against the
|
|
shared implementation in ``lib/crewai/tests/telemetry/``; only what is specific
|
|
to crewai-core standing alone is tested here.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Iterator
|
|
|
|
from crewai_core.runtime_env import (
|
|
CODING_AGENT_ENV_MARKERS,
|
|
GENERIC_AGENT_ENV_VARS,
|
|
RUNTIME_CONTEXT_ENV_MARKERS,
|
|
detect_coding_agent,
|
|
detect_runtime_context,
|
|
)
|
|
from crewai_core.telemetry import Telemetry, common_span_attributes
|
|
from opentelemetry.sdk.trace.export import SpanExportResult
|
|
import pytest
|
|
|
|
|
|
class _NullExporter:
|
|
"""Stands in for the OTLP exporter so no test attempts a real export."""
|
|
|
|
def export(self, spans: object) -> SpanExportResult:
|
|
return SpanExportResult.SUCCESS
|
|
|
|
def shutdown(self) -> None:
|
|
pass
|
|
|
|
def force_flush(self, timeout_millis: int = 30000) -> bool:
|
|
return True
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_cache() -> Iterator[None]:
|
|
common_span_attributes.cache_clear()
|
|
yield
|
|
common_span_attributes.cache_clear()
|
|
|
|
|
|
@pytest.fixture
|
|
def clean_env(monkeypatch: pytest.MonkeyPatch) -> pytest.MonkeyPatch:
|
|
"""Remove every marker the detectors read, so results are deterministic."""
|
|
for _, env_vars in (*CODING_AGENT_ENV_MARKERS, *RUNTIME_CONTEXT_ENV_MARKERS):
|
|
for var in env_vars:
|
|
monkeypatch.delenv(var, raising=False)
|
|
for var in (*GENERIC_AGENT_ENV_VARS, "TERM_PROGRAM", "TERMINAL_EMULATOR"):
|
|
monkeypatch.delenv(var, raising=False)
|
|
return monkeypatch
|
|
|
|
|
|
def test_detection_works_from_crewai_core(clean_env: pytest.MonkeyPatch) -> None:
|
|
"""The detectors resolve here, not only through the crewai re-export."""
|
|
clean_env.setenv("CLAUDECODE", "1")
|
|
clean_env.setenv("GITHUB_ACTIONS", "true")
|
|
|
|
assert detect_coding_agent() == "claude_code"
|
|
assert detect_runtime_context() == "ci"
|
|
|
|
|
|
def test_runtime_env_does_not_import_crewai() -> None:
|
|
"""crewai-core is the leaf package; importing crewai here would invert it.
|
|
|
|
Asserted on the module's imports rather than on ``sys.modules``, which
|
|
reflects whatever else the test session has already loaded and would make
|
|
this depend on ordering.
|
|
"""
|
|
import ast
|
|
import inspect
|
|
|
|
from crewai_core import runtime_env
|
|
|
|
tree = ast.parse(inspect.getsource(runtime_env))
|
|
imported: set[str] = set()
|
|
for node in ast.walk(tree):
|
|
if isinstance(node, ast.Import):
|
|
imported |= {alias.name for alias in node.names}
|
|
elif isinstance(node, ast.ImportFrom) and node.module:
|
|
imported.add(node.module)
|
|
|
|
assert not [
|
|
module
|
|
for module in imported
|
|
if module == "crewai" or module.startswith("crewai.")
|
|
]
|
|
|
|
|
|
def test_cli_spans_carry_the_process_context(
|
|
clean_env: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""The regression: CLI spans must carry coding_agent and runtime_context."""
|
|
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
|
|
InMemorySpanExporter,
|
|
)
|
|
|
|
clean_env.setenv("CLAUDECODE", "1")
|
|
clean_env.setenv("GITHUB_ACTIONS", "true")
|
|
monkeypatch.delenv("OTEL_SDK_DISABLED", raising=False)
|
|
monkeypatch.delenv("CREWAI_DISABLE_TELEMETRY", raising=False)
|
|
monkeypatch.delenv("CREWAI_DISABLE_TRACKING", raising=False)
|
|
|
|
Telemetry._instance = None
|
|
monkeypatch.setattr(Telemetry, "_register_shutdown_handlers", lambda self: None)
|
|
# Patched before construction: __init__ wires the real OTLP exporter.
|
|
monkeypatch.setattr(
|
|
"crewai_core.telemetry.SafeOTLPSpanExporter",
|
|
lambda **_kwargs: _NullExporter(),
|
|
)
|
|
telemetry = Telemetry()
|
|
|
|
exporter = InMemorySpanExporter()
|
|
telemetry.provider.add_span_processor(SimpleSpanProcessor(exporter))
|
|
|
|
try:
|
|
telemetry.feature_usage_span("cli_usage:deploy")
|
|
telemetry.template_installed_span("crew-template")
|
|
finally:
|
|
telemetry.provider.shutdown()
|
|
Telemetry._instance = None
|
|
|
|
exported = exporter.get_finished_spans()
|
|
assert [span.name for span in exported] == ["Feature Usage", "Template Installed"]
|
|
for span in exported:
|
|
attributes = span.attributes
|
|
assert attributes is not None
|
|
assert attributes["coding_agent"] == "claude_code"
|
|
assert attributes["runtime_context"] == "ci"
|