A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add OTLP export and W3C trace context propagation to tracing (#9414)
Titi Ala'ilima1fe39e19e9af
diff --git a/development_docs/traces.md b/development_docs/traces.mdindex 06397c06fe..9418f60584 100644--- a/development_docs/traces.md+++ b/development_docs/traces.md@@ -2,22 +2,90 @@## Server traces-For debugging purposes, we emit OpenTelemetry traces from the server. We emit traces to `~/.marimo/traces/spans.jsonl`. We don't emit any sensitive information in the traces, and these traces stay local to your machine. The traces get wiped on each sever restart.+For debugging purposes, we emit OpenTelemetry traces from the server. By+default, traces are written to a local JSONL file. When an OTLP endpoint is+configured, traces are exported via OTLP instead, letting marimo participate in+distributed tracing stacks such as Jaeger, Grafana Tempo, or GCP Cloud Trace.-You can analyze the traces using tools like Jaeger or Zipkin, or our marimo notebook:+### Prerequisites++Tracing requires the `otel` extra (or a development install, which includes+the same packages):```bash-marimo edit scripts/analyze_traces.py+pip install "marimo[otel]"```### Enable Traces-To enable traces, set the `MARIMO_TRACING` environment variable to `true`:+Set `MARIMO_TRACING=true` to turn tracing on:++```bash+MARIMO_TRACING=true marimo run notebook.py+```++### Local file export (default)++With no additional configuration, spans are written to+`~/.marimo/traces/spans.jsonl` (the exact path depends on your platform's+XDG state directory). The file is cleared on each server restart and never+leaves your machine.++You can analyze local traces with Jaeger, Zipkin, or the bundled notebook:```bash-MARIMO_TRACING=true ./your_server_command+marimo edit scripts/analyze_traces.py```+### OTLP export++To export traces to a remote collector, set the standard OpenTelemetry+environment variables:++```bash+MARIMO_TRACING=true \+OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \+OTEL_SERVICE_NAME=marimo \+marimo run notebook.py+```++| Variable | Purpose | Default |+|---|---|---|+| `OTEL_EXPORTER_OTLP_ENDPOINT` | Endpoint of an OTLP collector for all signals | _(unset — file export)_ |+| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Trace-specific OTLP endpoint; takes precedence over `OTEL_EXPORTER_OTLP_ENDPOINT` | _(unset)_ |+| `OTEL_EXPORTER_OTLP_PROTOCOL` | OTLP protocol for all signals: `http/protobuf` or `grpc` | `http/protobuf` |+| `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | Trace-specific OTLP protocol; takes precedence over `OTEL_EXPORTER_OTLP_PROTOCOL` | _(unset)_ |+| `OTEL_SERVICE_NAME` | `service.name` resource attribute | `marimo` |+| `OTEL_RESOURCE_ATTRIBUTES` | Comma-separated `key=value` pairs added to the resource | _(empty)_ |++With the default `http/protobuf` protocol, a generic+`OTEL_EXPORTER_OTLP_ENDPOINT` is treated by the OpenTelemetry exporter as the+collector base URL and traces are sent to `/v1/traces`. For example,+`http://localhost:4318` exports traces to `http://localhost:4318/v1/traces`.+If you set `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, include the full traces path,+for example `http://localhost:4318/v1/traces`.++For gRPC collectors, set the protocol explicitly:++```bash+MARIMO_TRACING=true \+OTEL_EXPORTER_OTLP_PROTOCOL=grpc \+OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \+marimo run notebook.py+```++If the selected OTLP exporter package is not installed, or the configured+protocol is unsupported, marimo logs a warning and falls back to the local file+exporter.++### Distributed trace propagation++The `OpenTelemetryMiddleware` extracts incoming W3C `traceparent` headers, so+when another service calls marimo (e.g., via the MCP HTTP endpoint), the+resulting spans are linked as children of the caller's trace. No extra+configuration is needed — propagation works automatically whenever tracing is+enabled.+## Profiling the kernelYou can generate profiling statistics of the kernel in edit mode using thediff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex 6880c3d0b1..57c8a8a113 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -202,9 +202,14 @@ class OpenTelemetryMiddleware(BaseHTTPMiddleware):if not GLOBAL_SETTINGS.TRACING:return await call_next(request)+ from opentelemetry.propagate import extract++ ctx = extract(carrier=request.headers)+with server_tracer.start_as_current_span(f"{request.method} {request.url.path}",kind=self.trace.SpanKind.SERVER,+ context=ctx,attributes={"http.method": request.method,"http.target": request.url.path or "",diff --git a/marimo/_tracer.py b/marimo/_tracer.pyindex 28b98dc4c9..e98715ba5f 100644--- a/marimo/_tracer.py+++ b/marimo/_tracer.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport osfrom contextlib import contextmanager-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Literal, castfrom marimo import _loggersfrom marimo._config.settings import GLOBAL_SETTINGS@@ -81,6 +81,37 @@ class MockTracer:TRACE_FILENAME = os.path.join("traces", "spans.jsonl")+OTLPProtocol = Literal["grpc", "http/protobuf"]+++def _otlp_endpoint_configured() -> bool:+ return bool(+ os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")+ or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")+ )+++def _otlp_protocol() -> OTLPProtocol | None:+ protocol = (+ (+ os.environ.get("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")+ or os.environ.get("OTEL_EXPORTER_OTLP_PROTOCOL")+ or "http/protobuf"+ )+ .strip()+ .lower()+ )+ protocol = protocol or "http/protobuf"++ if protocol in ("grpc", "http/protobuf"):+ return cast(OTLPProtocol, protocol)++ LOGGER.warning(+ "Unsupported OTLP protocol %r; expected 'grpc' or "+ "'http/protobuf'. Falling back to file export.",+ protocol,+ )+ return Nonedef _set_tracer_provider() -> None:@@ -90,6 +121,7 @@ def _set_tracer_provider() -> None:DependencyManager.opentelemetry.require("for tracing.")from opentelemetry import trace+ from opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import ReadableSpan, TracerProviderfrom opentelemetry.sdk.trace.export import (BatchSpanProcessor,@@ -103,37 +135,80 @@ def _set_tracer_provider() -> None:except Exception:return- class FileExporter(SpanExporter):- def __init__(self, file_path: Path) -> None:- self.file_path = file_path- # Clear file- self.file_path.write_bytes(b"")-- def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:- try:- with self.file_path.open("a", encoding="utf-8") as f:- for span in spans:- f.write(span.to_json(cast(Any, None)))- f.write("\n")- return SpanExportResult.SUCCESS- except Exception as e:- LOGGER.exception(e)- return SpanExportResult.FAILURE-- def shutdown(self) -> None:- pass-- # Create a directory for logs if it doesn't exist- config_ready = ConfigReader.for_filename(TRACE_FILENAME)- filepath = config_ready.filepath- filepath.parent.mkdir(parents=True, exist_ok=True)-- # Create a file exporter- file_exporter: FileExporter = FileExporter(filepath)-- provider = TracerProvider()- processor = BatchSpanProcessor(file_exporter)- provider.add_span_processor(processor)+ otlp_protocol = _otlp_protocol() if _otlp_endpoint_configured() else None+ OTLPSpanExporter: Any | None = None+ if otlp_protocol == "grpc":+ try:+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (+ OTLPSpanExporter as GrpcOTLPSpanExporter,+ )++ OTLPSpanExporter = GrpcOTLPSpanExporter+ except ImportError:+ LOGGER.warning(+ "opentelemetry-exporter-otlp-proto-grpc not installed; "+ "install marimo[otel] for OTLP export. Falling back to file export.",+ )+ elif otlp_protocol == "http/protobuf":+ try:+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (+ OTLPSpanExporter as HttpOTLPSpanExporter,+ )++ OTLPSpanExporter = HttpOTLPSpanExporter+ except ImportError:+ LOGGER.warning(+ "opentelemetry-exporter-otlp-proto-http not installed; "+ "install marimo[otel] for OTLP export. Falling back to file export.",+ )++ if OTLPSpanExporter is not None:+ resource = Resource.create(+ {+ "service.name": "marimo",+ },+ )+ provider = TracerProvider(resource=resource)+ provider.add_span_processor(+ BatchSpanProcessor(+ OTLPSpanExporter(),+ ),+ )+ LOGGER.debug(+ "OTel tracer: OTLP export via %s",+ otlp_protocol,+ )+ else:++ class FileExporter(SpanExporter):+ def __init__(self, file_path: Path) -> None:+ self.file_path = file_path+ self.file_path.write_bytes(b"")++ def export(+ self,+ spans: Sequence[ReadableSpan],+ ) -> SpanExportResult:+ try:+ with self.file_path.open("a", encoding="utf-8") as f:+ for span in spans:+ f.write(span.to_json(cast(Any, None)))+ f.write("\n")+ return SpanExportResult.SUCCESS+ except Exception as e:+ LOGGER.exception(e)+ return SpanExportResult.FAILURE++ def shutdown(self) -> None:+ pass++ config_ready = ConfigReader.for_filename(TRACE_FILENAME)+ filepath = config_ready.filepath+ filepath.parent.mkdir(parents=True, exist_ok=True)++ provider = TracerProvider()+ provider.add_span_processor(BatchSpanProcessor(FileExporter(filepath)))+ LOGGER.debug("OTel tracer: file export to %s", filepath)# Sets the global default tracer providertrace.set_tracer_provider(provider)diff --git a/pyproject.toml b/pyproject.tomlindex 4214e53c4e..d193713bbb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -116,6 +116,13 @@ mcp = ["pydantic>2",]+otel = [+ "opentelemetry-api~=1.28.0",+ "opentelemetry-sdk~=1.28.0",+ "opentelemetry-exporter-otlp-proto-http~=1.28.0",+ "opentelemetry-exporter-otlp-proto-grpc~=1.28.0",+]+[dependency-groups]dev = [# Typo checking@@ -123,6 +130,8 @@ dev = [# For tracing debugging"opentelemetry-api~=1.28.0","opentelemetry-sdk~=1.28.0",+ "opentelemetry-exporter-otlp-proto-http~=1.28.0",+ "opentelemetry-exporter-otlp-proto-grpc~=1.28.0",# For SQL"duckdb>=1.0.0","sqlglot[c]>=26.8.0",diff --git a/tests/_server/api/test_opentelemetry_middleware.py b/tests/_server/api/test_opentelemetry_middleware.pynew file mode 100644index 0000000000..44e74892be--- /dev/null+++ b/tests/_server/api/test_opentelemetry_middleware.py@@ -0,0 +1,262 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import sys+from typing import TYPE_CHECKING, Any+from unittest.mock import patch++import pytest+from starlette.applications import Starlette+from starlette.responses import PlainTextResponse+from starlette.routing import Route+from starlette.testclient import TestClient++if TYPE_CHECKING:+ from collections.abc import Sequence++ from starlette.requests import Request+++def _reset_otel() -> None:+ """Reset the global OTel tracer provider so each test starts clean."""+ from opentelemetry import trace++ trace._TRACER_PROVIDER_SET_ONCE._done = False+ trace._TRACER_PROVIDER = None+++class _CollectingExporter:+ """Minimal span exporter that collects spans in a list."""++ def __init__(self) -> None:+ self.spans: list[Any] = []++ def export(self, spans: Sequence[Any]) -> Any:+ from opentelemetry.sdk.trace.export import SpanExportResult++ self.spans.extend(spans)+ return SpanExportResult.SUCCESS++ def shutdown(self) -> None:+ pass++ def force_flush(self, timeout_millis: int = 0) -> bool: # noqa: ARG002+ return True+++def _setup_tracing() -> tuple[Any, _CollectingExporter]:+ """Set up OTel with a collecting exporter, return (tracer, exporter)."""+ _reset_otel()++ from opentelemetry import trace+ from opentelemetry.sdk.trace import TracerProvider+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor++ exporter = _CollectingExporter()+ provider = TracerProvider()+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ trace.set_tracer_provider(provider)++ tracer = trace.get_tracer("marimo.server")+ return tracer, exporter+++def _make_app(tracing: bool = True) -> Starlette:+ """Build a minimal Starlette app with OpenTelemetryMiddleware."""+ from marimo._server.api.middleware import OpenTelemetryMiddleware++ async def homepage(request: Request) -> PlainTextResponse: # noqa: ARG001+ return PlainTextResponse("ok")++ app = Starlette(routes=[Route("/", homepage)])++ with patch("marimo._config.settings.GLOBAL_SETTINGS.TRACING", tracing):+ app.add_middleware(OpenTelemetryMiddleware)++ return app++[email protected]("opentelemetry")+class TestOpenTelemetryMiddleware:+ def setup_method(self) -> None:+ _reset_otel()++ def teardown_method(self) -> None:+ _reset_otel()++ def test_extracts_traceparent_creates_child_span(self) -> None:+ from opentelemetry import trace+ from opentelemetry.trace import TraceFlags++ tracer, exporter = _setup_tracing()++ parent_trace_id = "0af7651916cd43dd8448eb211c80319c"+ parent_span_id = "b7ad6b7169203331"+ traceparent = f"00-{parent_trace_id}-{parent_span_id}-01"++ with (+ patch("marimo._config.settings.GLOBAL_SETTINGS.TRACING", True),+ patch("marimo._server.api.middleware.server_tracer", tracer),+ ):+ app = _make_app(tracing=True)+ client = TestClient(app)+ response = client.get("/", headers={"traceparent": traceparent})++ assert response.status_code == 200+ assert len(exporter.spans) == 1++ span = exporter.spans[0]+ assert span.name == "GET /"+ assert span.kind == trace.SpanKind.SERVER++ span_context = span.parent+ assert span_context is not None+ assert format(span_context.trace_id, "032x") == parent_trace_id+ assert format(span_context.span_id, "016x") == parent_span_id+ assert span_context.trace_flags == TraceFlags(1)++ def test_root_span_when_no_traceparent(self) -> None:+ tracer, exporter = _setup_tracing()++ with (+ patch("marimo._config.settings.GLOBAL_SETTINGS.TRACING", True),+ patch("marimo._server.api.middleware.server_tracer", tracer),+ ):+ app = _make_app(tracing=True)+ client = TestClient(app)+ response = client.get("/")++ assert response.status_code == 200+ assert len(exporter.spans) == 1+ assert exporter.spans[0].parent is None++ def test_noop_when_tracing_disabled(self) -> None:+ tracer, exporter = _setup_tracing()++ with (+ patch("marimo._config.settings.GLOBAL_SETTINGS.TRACING", False),+ patch("marimo._server.api.middleware.server_tracer", tracer),+ ):+ app = _make_app(tracing=False)+ client = TestClient(app)+ response = client.get("/")++ assert response.status_code == 200+ assert len(exporter.spans) == 0++ def test_span_records_status_code(self) -> None:+ tracer, exporter = _setup_tracing()++ with (+ patch("marimo._config.settings.GLOBAL_SETTINGS.TRACING", True),+ patch("marimo._server.api.middleware.server_tracer", tracer),+ ):+ app = _make_app(tracing=True)+ client = TestClient(app)+ client.get("/")++ assert len(exporter.spans) == 1+ attrs = dict(exporter.spans[0].attributes or {})+ assert attrs["http.status_code"] == 200+ assert attrs["http.method"] == "GET"+ assert attrs["http.target"] == "/"++[email protected]("opentelemetry")+class TestTracePropagationThroughRealApp:+ """Integration tests using create_starlette_app + setup_mcp_server.++ These verify that OpenTelemetryMiddleware actually intercepts+ requests to MCP endpoints in the real application middleware stack,+ not a hand-built analogue that could drift from production.+ """++ def setup_method(self) -> None:+ _reset_otel()++ def teardown_method(self) -> None:+ _reset_otel()++ def _create_real_app(self) -> Starlette:+ """Build the real Starlette app and mount MCP, just like start.py."""+ from marimo._server.main import create_starlette_app+ from tests._server.mocks import get_mock_session_manager++ app = create_starlette_app(+ base_url="",+ enable_auth=False,+ skew_protection=False,+ )++ session_manager = get_mock_session_manager()+ app.state.session_manager = session_manager++ if "mcp" in sys.modules or _has_mcp():+ from marimo._mcp.setup import setup_mcp_server++ setup_mcp_server(app, "tools")++ return app++ def test_mcp_request_produces_span_with_traceparent(self) -> None:+ if not _has_mcp():+ pytest.skip("mcp package not installed")++ from opentelemetry.trace import TraceFlags++ tracer, exporter = _setup_tracing()++ parent_trace_id = "0af7651916cd43dd8448eb211c80319c"+ parent_span_id = "b7ad6b7169203331"+ traceparent = f"00-{parent_trace_id}-{parent_span_id}-01"++ with (+ patch("marimo._config.settings.GLOBAL_SETTINGS.TRACING", True),+ patch("marimo._server.api.middleware.server_tracer", tracer),+ ):+ app = self._create_real_app()+ client = TestClient(app, raise_server_exceptions=False)+ client.get(+ "/mcp/server",+ headers={"traceparent": traceparent},+ )++ mcp_spans = [s for s in exporter.spans if "/mcp" in (s.name or "")]+ assert len(mcp_spans) >= 1, (+ f"Expected a span for /mcp/server, got: {[s.name for s in exporter.spans]}"+ )++ span = mcp_spans[0]+ assert span.parent is not None, "Span should be a child, not a root"+ assert format(span.parent.trace_id, "032x") == parent_trace_id+ assert format(span.parent.span_id, "016x") == parent_span_id+ assert span.parent.trace_flags == TraceFlags(1)++ def test_mcp_request_root_span_without_traceparent(self) -> None:+ if not _has_mcp():+ pytest.skip("mcp package not installed")++ tracer, exporter = _setup_tracing()++ with (+ patch("marimo._config.settings.GLOBAL_SETTINGS.TRACING", True),+ patch("marimo._server.api.middleware.server_tracer", tracer),+ ):+ app = self._create_real_app()+ client = TestClient(app, raise_server_exceptions=False)+ client.get("/mcp/server")++ mcp_spans = [s for s in exporter.spans if "/mcp" in (s.name or "")]+ assert len(mcp_spans) >= 1, (+ f"Expected a span for /mcp/server, got: {[s.name for s in exporter.spans]}"+ )+ assert mcp_spans[0].parent is None+++def _has_mcp() -> bool:+ try:+ import mcp # noqa: F401++ return True+ except ImportError:+ return Falsediff --git a/tests/test_tracer.py b/tests/test_tracer.pynew file mode 100644index 0000000000..6420b00f0a--- /dev/null+++ b/tests/test_tracer.py@@ -0,0 +1,258 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from unittest.mock import MagicMock, patch++import pytest+++def _reset_otel() -> None:+ """Reset the global OTel tracer provider so each test starts clean."""+ from opentelemetry import trace++ trace._TRACER_PROVIDER_SET_ONCE._done = False+ trace._TRACER_PROVIDER = None++[email protected]("opentelemetry")+class TestSetTracerProvider:+ """Tests for _set_tracer_provider() exporter selection."""++ def setup_method(self) -> None:+ _reset_otel()++ def teardown_method(self) -> None:+ _reset_otel()++ def test_http_otlp_exporter_when_generic_endpoint_set(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ try:+ import opentelemetry.exporter.otlp.proto.http.trace_exporter # noqa: F401+ except ImportError:+ pytest.skip("opentelemetry-exporter-otlp-proto-http not installed")++ monkeypatch.setenv(+ "OTEL_EXPORTER_OTLP_ENDPOINT",+ "http://localhost:4318",+ )+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_PROTOCOL", raising=False)+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", raising=False)+ monkeypatch.setenv("OTEL_SERVICE_NAME", "test-marimo")++ mock_exporter_cls = MagicMock()+ mock_exporter_cls.return_value = MagicMock()++ from marimo._config.settings import GLOBAL_SETTINGS++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", True)++ with patch(+ "opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter",+ mock_exporter_cls,+ ):+ from marimo._tracer import _set_tracer_provider++ _set_tracer_provider()++ mock_exporter_cls.assert_called_once_with()++ def test_http_otlp_exporter_when_trace_endpoint_set(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ try:+ import opentelemetry.exporter.otlp.proto.http.trace_exporter # noqa: F401+ except ImportError:+ pytest.skip("opentelemetry-exporter-otlp-proto-http not installed")++ monkeypatch.setenv(+ "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",+ "http://localhost:4318/v1/traces",+ )+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_PROTOCOL", raising=False)+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", raising=False)+ mock_exporter_cls = MagicMock()+ mock_exporter_cls.return_value = MagicMock()++ from marimo._config.settings import GLOBAL_SETTINGS++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", True)++ with patch(+ "opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter",+ mock_exporter_cls,+ ):+ from marimo._tracer import _set_tracer_provider++ _set_tracer_provider()++ mock_exporter_cls.assert_called_once_with()++ def test_grpc_otlp_exporter_when_protocol_set(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ try:+ import opentelemetry.exporter.otlp.proto.grpc.trace_exporter # noqa: F401+ except ImportError:+ pytest.skip("opentelemetry-exporter-otlp-proto-grpc not installed")++ monkeypatch.setenv(+ "OTEL_EXPORTER_OTLP_ENDPOINT",+ "http://localhost:4317",+ )+ monkeypatch.setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc")+ mock_exporter_cls = MagicMock()+ mock_exporter_cls.return_value = MagicMock()++ from marimo._config.settings import GLOBAL_SETTINGS++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", True)++ with patch(+ "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.OTLPSpanExporter",+ mock_exporter_cls,+ ):+ from marimo._tracer import _set_tracer_provider++ _set_tracer_provider()++ mock_exporter_cls.assert_called_once_with()++ def test_file_exporter_when_no_endpoint(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_ENDPOINT", raising=False)+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", raising=False)+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_PROTOCOL", raising=False)+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", raising=False)++ from opentelemetry import trace+ from opentelemetry.sdk.trace import TracerProvider+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ from marimo._config.settings import GLOBAL_SETTINGS++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", True)++ from marimo._tracer import _set_tracer_provider++ _set_tracer_provider()++ provider = trace.get_tracer_provider()+ assert isinstance(provider, TracerProvider)++ processors = provider._active_span_processor._span_processors # type: ignore[attr-defined]+ assert len(processors) > 0+ processor = processors[0]+ assert isinstance(processor, BatchSpanProcessor)+ assert type(processor.span_exporter).__name__ == "FileExporter"++ def test_otlp_fallback_to_file_when_selected_exporter_missing(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.setenv(+ "OTEL_EXPORTER_OTLP_ENDPOINT",+ "http://localhost:4318",+ )++ from marimo._config.settings import GLOBAL_SETTINGS++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", True)++ with patch.dict(+ "sys.modules",+ {"opentelemetry.exporter.otlp.proto.http.trace_exporter": None},+ ):+ from marimo._tracer import _set_tracer_provider++ _set_tracer_provider()++ from opentelemetry import trace+ from opentelemetry.sdk.trace import TracerProvider+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ provider = trace.get_tracer_provider()+ assert isinstance(provider, TracerProvider)+ processors = provider._active_span_processor._span_processors # type: ignore[attr-defined]+ assert len(processors) > 0+ processor = processors[0]+ assert isinstance(processor, BatchSpanProcessor)+ assert type(processor.span_exporter).__name__ == "FileExporter"++ def test_otlp_fallback_to_file_when_protocol_unsupported(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.setenv(+ "OTEL_EXPORTER_OTLP_ENDPOINT",+ "http://localhost:4318",+ )+ monkeypatch.setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json")++ from marimo._config.settings import GLOBAL_SETTINGS++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", True)++ from marimo._tracer import _set_tracer_provider++ _set_tracer_provider()++ from opentelemetry import trace+ from opentelemetry.sdk.trace import TracerProvider+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ provider = trace.get_tracer_provider()+ assert isinstance(provider, TracerProvider)+ processors = provider._active_span_processor._span_processors # type: ignore[attr-defined]+ assert len(processors) > 0+ processor = processors[0]+ assert isinstance(processor, BatchSpanProcessor)+ assert type(processor.span_exporter).__name__ == "FileExporter"++ def test_noop_when_tracing_disabled(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ from opentelemetry import trace++ from marimo._config.settings import GLOBAL_SETTINGS++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", False)++ from marimo._tracer import _set_tracer_provider++ _set_tracer_provider()++ # Provider should still be the default proxy (nothing was set)+ provider = trace.get_tracer_provider()+ assert not hasattr(provider, "_active_span_processor")++[email protected]("opentelemetry")+class TestCreateTracer:+ def test_returns_mock_when_tracing_disabled(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ from marimo._config.settings import GLOBAL_SETTINGS+ from marimo._tracer import MockTracer, create_tracer++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", False)+ tracer = create_tracer("test")+ assert isinstance(tracer, MockTracer)++ def test_returns_real_tracer_when_enabled(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ from marimo._config.settings import GLOBAL_SETTINGS+ from marimo._tracer import MockTracer, create_tracer++ monkeypatch.setattr(GLOBAL_SETTINGS, "TRACING", True)+ tracer = create_tracer("test.real")+ assert not isinstance(tracer, MockTracer)