Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.
fix(tracing): report tracing sent usage from the grant exporter (#7810)
João Moura243e81995209
diff --git a/lib/crewai/src/crewai/telemetry/tracing/grants.py b/lib/crewai/src/crewai/telemetry/tracing/grants.pyindex 353f633ba..df0ce2c34 100644--- a/lib/crewai/src/crewai/telemetry/tracing/grants.py+++ b/lib/crewai/src/crewai/telemetry/tracing/grants.py@@ -27,6 +27,7 @@ from crewai.events.listeners.tracing.utils import (is_tui_mode,should_suppress_tracing_messages,)+from crewai.telemetry.telemetry import Telemetryfrom crewai.telemetry.tracing import last_runfrom crewai.telemetry.tracing.session import MAX_EXPORT_BATCH_SIZE, otlp_exporter@@ -293,15 +294,19 @@ class GrantSpanExporter(SpanExporter):self._recorded = Trueexecution_uuid = self._grant.execution_uuidapi = getattr(self._client, "_api", None)+ tier = getattr(self._client, "_tier", None)last_run.record_last_run(execution_id=execution_uuid,- tier=getattr(self._client, "_tier", None),+ tier=tier,started_at_ns=self._first_start_ns,finished_at_ns=self._last_end_ns,amp_base_url=getattr(api, "base_url", None),trace_url=self._trace_url,)logger.debug("Traces exported for execution %s", execution_uuid)+ # Counts that a trace reached AMP, never its contents. The legacy+ # TraceBatchManager emits the same names for runs outside a kickoff.+ Telemetry().feature_usage_span(f"tracing:{tier}_sent")self._show_trace_link()def _show_trace_link(self) -> None:diff --git a/lib/crewai/tests/telemetry/test_session_trace_export.py b/lib/crewai/tests/telemetry/test_session_trace_export.pyindex 426a99d25..55e5593e0 100644--- a/lib/crewai/tests/telemetry/test_session_trace_export.py+++ b/lib/crewai/tests/telemetry/test_session_trace_export.py@@ -847,3 +847,142 @@ def test_invalid_buffer_limits_use_safe_defaults(monkeypatch, invalid):buffer = EphemeralSpanBuffer()assert buffer._max_spans == 1000 and buffer._max_bytes == 8388608buffer.shutdown()+++def sent_features(monkeypatch):+ """The `tracing:*` Feature Usage names emitted, in order."""+ from crewai.telemetry.telemetry import Telemetry++ features = []+ monkeypatch.setattr(+ Telemetry,+ "feature_usage_span",+ lambda self, feature: features.append(feature)+ if feature.startswith("tracing:")+ else None,+ )+ return features+++ ("authenticated", "approved", "grant_status", "export_status", "expected"),+ [+ (True, True, 200, 200, ["tracing:authenticated_sent"]),+ (False, True, 200, 200, ["tracing:ephemeral_sent"]),+ (False, False, 200, 200, []),+ (True, True, 200, 401, []),+ (False, True, 200, 401, []),+ (False, True, 500, 200, []),+ ],+)+def test_a_trace_that_reaches_amp_is_counted_once_by_tier(+ collector,+ sent_features,+ monkeypatch,+ authenticated,+ approved,+ grant_status,+ export_status,+ expected,+):+ """Declined consent, a refused grant, or a rejected export never counts."""+ from crewai.execution import begin_execution, end_execution+ from crewai.telemetry.tracing.context import get_trace_session++ collector.grant_status = grant_status+ collector.export_status = export_status+ if authenticated:+ monkeypatch.setenv("CREWAI_USER_PAT", "synthetic-pat")++ def run():+ with trace_consent(lambda: approved):+ token = begin_execution(tracing=True)+ try:+ record(get_trace_session())+ nested = begin_execution(tracing=True)+ end_execution(nested)+ finally:+ end_execution(token)++ copy_context().run(run)+ assert sent_features == expected+++def test_a_deferred_run_is_counted_once_when_it_finally_ends(+ collector, sent_features, monkeypatch+):+ from crewai.execution import begin_execution, end_execution+ from crewai.telemetry.tracing.context import get_trace_session++ monkeypatch.setenv("CREWAI_USER_PAT", "synthetic-pat")+ token = begin_execution(tracing=True)+ try:+ session = get_trace_session()+ record(session)+ session.flush()+ finally:+ lifetime = end_execution(token, defer=True)+ assert sent_features == [] # spans reached AMP, but the run is not over++ token = begin_execution(tracing=True, trace_session=lifetime)+ try:+ record(get_trace_session(), "second turn")+ finally:+ end_execution(token)+ assert sent_features == ["tracing:authenticated_sent"]+++def test_recording_the_same_export_twice_counts_it_once(collector, sent_features):+ client = TraceGrantClient(None)+ grant = client.create(str(uuid4()))+ exporter = GrantSpanExporter(client, grant)+ session = TraceSession(grant.execution_uuid, [exporter])+ try:+ record(session)+ finally:+ session.shutdown()+ exporter.record_export()+ exporter.record_export()+ assert sent_features == ["tracing:ephemeral_sent"]+++def test_a_truncated_ephemeral_trace_is_not_counted(+ collector, sent_features, monkeypatch+):+ """It is uploaded, but like the `crewai eval` record it is not a whole run."""+ monkeypatch.setenv("CREWAI_EPHEMERAL_TRACE_MAX_SPANS", "1")+ with trace_consent(lambda: True), ephemeral_tracing(str(uuid4())) as session:+ record(session, "first")+ record(session, "second")+ assert len(collector.batches) == 1+ assert sent_features == []++[email protected]("authenticated", [True, False])[email protected]("use_async", [False, True])+def test_a_flow_kickoff_counts_its_trace(+ collector, sent_features, monkeypatch, authenticated, use_async+):+ from crewai.flow.flow import Flow, start++ if authenticated:+ monkeypatch.setenv("CREWAI_USER_PAT", "synthetic-pat")++ class Greeting(Flow):+ @start()+ def greet(self):+ return "hello"++ def run():+ with trace_consent(lambda: True):+ flow = Greeting(tracing=True)+ if use_async:+ return asyncio.run(flow.kickoff_async())+ return flow.kickoff()++ assert copy_context().run(run) == "hello"+ assert collector.batches+ assert sent_features == [+ "tracing:authenticated_sent" if authenticated else "tracing:ephemeral_sent"+ ]