diff --git a/.env.example b/.env.example index 6de00d97..c6ceddec 100644 --- a/.env.example +++ b/.env.example @@ -46,7 +46,13 @@ CONSERVER_START_METHOD= # ── OpenTelemetry ───────────────────────────────────────────────────────────── -# Leave OTEL_EXPORTER_OTLP_ENDPOINT blank to disable tracing. +# Leave OTEL_EXPORTER_OTLP_ENDPOINT blank to disable all export (traces and metrics). +# OTEL_EXPORTER_OTLP_PROTOCOL is honored by both: grpc or http/protobuf. When it is unset the +# server uses grpc. With http/protobuf the server appends /v1/traces and /v1/metrics to the +# endpoint; set OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or OTEL_EXPORTER_OTLP_METRICS_ENDPOINT to +# override either full URL. Langfuse accepts traces only, so use a collector to also send metrics. +# Spans carry tenant.id and call.session_id on the chain span only, never on metrics. JSON logs +# carry trace_id and span_id inside a span. No vCon content is added to spans or logs. # # Local Langfuse (add 'langfuse' to COMPOSE_PROFILES, then use pre-seeded creds): # OTEL_EXPORTER_OTLP_ENDPOINT=http://langfuse-server:3000/api/public/otel diff --git a/common/lib/json_log_formatter.py b/common/lib/json_log_formatter.py new file mode 100644 index 00000000..373eb27d --- /dev/null +++ b/common/lib/json_log_formatter.py @@ -0,0 +1,34 @@ +"""JSON log formatter that carries the active trace and span ids.""" + +import os + +from pythonjsonlogger.jsonlogger import JsonFormatter + + +def _is_set(hex_id): + """The instrumentation writes "0" (or all zeros) when no span is active.""" + try: + return bool(hex_id) and int(hex_id, 16) != 0 + except (TypeError, ValueError): + return False + + +class TraceJsonFormatter(JsonFormatter): + """JsonFormatter plus ``trace_id`` and ``span_id``. + + The ids come from the OpenTelemetry logging instrumentation, which stamps ``otelTraceID`` and + ``otelSpanID`` on every record (see ``lib.logging_utils``). Outside a span, with no + OTEL_EXPORTER_OTLP_ENDPOINT set, or with the instrumentation off, the two fields are left out and every other field is unchanged. + """ + + def add_fields(self, log_record, record, message_dict): + super().add_fields(log_record, record, message_dict) + trace_id = getattr(record, "otelTraceID", None) + span_id = getattr(record, "otelSpanID", None) + # The instrumentation's own attributes would otherwise appear as extra keys. + for key in ("otelTraceID", "otelSpanID", "otelTraceSampled", "otelServiceName"): + log_record.pop(key, None) + # Telemetry off (no endpoint) leaves the log format exactly as it was. + if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") and _is_set(trace_id) and _is_set(span_id): + log_record["trace_id"] = trace_id + log_record["span_id"] = span_id diff --git a/common/lib/logging_utils.py b/common/lib/logging_utils.py index 7949ea7d..9e05b545 100644 --- a/common/lib/logging_utils.py +++ b/common/lib/logging_utils.py @@ -4,6 +4,15 @@ logging.config.fileConfig(LOGGING_CONFIG_FILE) +try: + # Stamp otelTraceID and otelSpanID on every log record so the JSON formatter can emit + # trace_id and span_id. set_logging_format=False leaves our own format alone. + from opentelemetry.instrumentation.logging import LoggingInstrumentor + + LoggingInstrumentor().instrument(set_logging_format=False) +except Exception: # pragma: no cover - logging must never fail to start + logging.getLogger(__name__).warning("OpenTelemetry log correlation unavailable", exc_info=True) + def init_logger(name): return logging.getLogger(name) diff --git a/common/lib/metrics.py b/common/lib/metrics.py index 4b3ad768..3258f9c3 100644 --- a/common/lib/metrics.py +++ b/common/lib/metrics.py @@ -5,15 +5,26 @@ from opentelemetry import metrics from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter as OTLPHttpMetricExporter from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.resources import Resource +from lib.otlp_config import ( + EXPORT_TIMEOUT_S, + HTTP_PROTOBUF, + METRIC_SHUTDOWN_BUDGET_S, + http_signal_url, + otlp_protocol, + run_bounded, +) + OTEL_EXPORTER_OTLP_ENDPOINT = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") OTEL_SERVICE_NAME = os.environ.get("OTEL_SERVICE_NAME", "vcon-server") OTEL_METRIC_EXPORT_INTERVAL = int(os.environ.get("OTEL_METRIC_EXPORT_INTERVAL", "5000")) meter = None +_meter_provider = None counter_metrics = {} histogram_metrics = {} observable_gauges = {} @@ -80,7 +91,7 @@ def _init_otel_metrics(): CONSERVER_VCON_CONCURRENCY=128, peak in-flight should reach ~256 per pod, but the collapsed series only shows one worker's count (≤128). """ - global meter, _otel_initialized_pid + global meter, _meter_provider, _otel_initialized_pid current_pid = os.getpid() # Already initialized in this process — bail. @@ -104,9 +115,16 @@ def _init_otel_metrics(): "service.instance.id": instance_id, }) - otlp_exporter = OTLPMetricExporter( - endpoint=OTEL_EXPORTER_OTLP_ENDPOINT, - ) + if otlp_protocol("metrics") == HTTP_PROTOBUF: + otlp_exporter = OTLPHttpMetricExporter( + endpoint=http_signal_url("metrics", OTEL_EXPORTER_OTLP_ENDPOINT), + timeout=EXPORT_TIMEOUT_S, + ) + else: + otlp_exporter = OTLPMetricExporter( + endpoint=OTEL_EXPORTER_OTLP_ENDPOINT, + timeout=EXPORT_TIMEOUT_S, + ) reader = PeriodicExportingMetricReader( exporter=otlp_exporter, @@ -139,6 +157,7 @@ def _init_otel_metrics(): # metrics continue to flow through their own pipeline. Both end up # at the OTel collector independently. meter = provider.get_meter(__name__) + _meter_provider = provider # Flush our provider's metric reader on process exit. The # auto-instrumentation MeterProvider registers its own atexit @@ -173,6 +192,19 @@ def _init_otel_metrics(): _otel_initialized_pid = current_pid +def shutdown_meter_provider(): + """Flush and shut down this process's own meter provider, waiting at most a couple of seconds. + + A forked worker leaves through ``os._exit`` and never runs the ``atexit`` hook, so it calls this + before it returns. A provider inherited from another pid is left alone. + """ + global _meter_provider + provider = _meter_provider + if provider is not None and _otel_initialized_pid == os.getpid(): + _meter_provider = None + run_bounded(provider.shutdown, METRIC_SHUTDOWN_BUDGET_S, "metrics") + + def increment_counter(metric_name, value=1, attributes=None): """Increment a counter metric in OpenTelemetry. diff --git a/common/lib/otlp_config.py b/common/lib/otlp_config.py new file mode 100644 index 00000000..37a2fa97 --- /dev/null +++ b/common/lib/otlp_config.py @@ -0,0 +1,76 @@ +"""Shared OTLP settings for the metrics and trace exporters.""" + +import logging +import os +import threading + +logger = logging.getLogger(__name__) + +GRPC = "grpc" +HTTP_PROTOBUF = "http/protobuf" + + +def otlp_protocol(signal): + """Return ``grpc`` or ``http/protobuf`` for ``signal`` (``metrics`` or ``traces``). + + Reads ``OTEL_EXPORTER_OTLP__PROTOCOL`` first, then ``OTEL_EXPORTER_OTLP_PROTOCOL``. + Unset keeps the historic gRPC default. Any other value (``http/json``) falls back to gRPC + with a warning, since no exporter for it is installed. + """ + specific = { + "metrics": os.environ.get("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"), + "traces": os.environ.get("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"), + }[signal] + raw = specific or os.environ.get("OTEL_EXPORTER_OTLP_PROTOCOL") + value = (raw or GRPC).strip().lower() + if value in (GRPC, HTTP_PROTOBUF): + return value + logger.warning("Unsupported OTEL_EXPORTER_OTLP_PROTOCOL %r for %s, using grpc", raw, signal) + return GRPC + + +def http_signal_url(signal, base_endpoint): + """Full OTLP/HTTP URL for ``signal``. + + An explicit endpoint passed to an HTTP exporter is used as given, with no path added, so the + ``/v1/`` suffix has to be appended here. A per-signal endpoint variable is used as is. + """ + specific = { + "metrics": os.environ.get("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"), + "traces": os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"), + }[signal] + if specific: + return specific + return f"{base_endpoint.rstrip('/')}/v1/{signal}" + + +# Bounds on telemetry work at exit. A dead collector must not hold a worker for the SDK defaults, +# which add up to about a minute (30 s trace shutdown plus the metrics export timeout). +EXPORT_TIMEOUT_S = 2 +TRACE_SHUTDOWN_BUDGET_S = 3.0 +METRIC_SHUTDOWN_BUDGET_S = 2.0 + + +def run_bounded(fn, budget_s, what): + """Run ``fn`` on a daemon thread and give up waiting after ``budget_s`` seconds. + + Returns True when ``fn`` finished in time. A late thread is abandoned: it is a daemon, so it + cannot keep the process alive, and whatever it had not exported is dropped. + """ + error = [] + + def target(): + try: + fn() + except Exception as e: # noqa: BLE001 + error.append(e) + + thread = threading.Thread(target=target, name=f"otel-shutdown-{what}", daemon=True) + thread.start() + thread.join(budget_s) + if thread.is_alive(): + logger.warning("OpenTelemetry %s shutdown still running after %.1f s, abandoning it", what, budget_s) + return False + if error: + logger.warning("Failed to shut down OpenTelemetry %s: %s", what, error[0]) + return True diff --git a/common/lib/span_attributes.py b/common/lib/span_attributes.py new file mode 100644 index 00000000..9556f2ec --- /dev/null +++ b/common/lib/span_attributes.py @@ -0,0 +1,49 @@ +"""Span attributes that tie a chain run to a tenant and a call. + +These go on spans only. A per-call value on a metric creates one series per call. +""" + +from typing import Optional + +from vcon import Vcon + +TELNYX_SESSION_TAG = "telnyx_call_session_id" +_MAX_LEN = 128 + + +def _clean(value) -> Optional[str]: + if isinstance(value, bool) or not isinstance(value, (str, int)): + return None + text = str(value).strip() + return text[:_MAX_LEN] if text else None + + +def vcon_correlation_attributes(vcon_dict: Optional[dict]) -> dict: + """Return ``tenant.id`` and ``call.session_id`` for a vCon dict, leaving out what is absent. + + ``tenant.id`` is the ``id`` in the body of the ``tenant`` attachment. ``call.session_id`` is + the value of the ``telnyx_call_session_id`` tag. Nothing else from the vCon is read, so no + dialog, transcript or other body content can reach a span through here. + """ + if not vcon_dict: + return {} + vcon = Vcon(vcon_dict) + attrs = {} + + try: + tenant_body = Vcon.decoded_body(vcon.find_attachment_by_purpose("tenant")) + except Exception: + tenant_body = None + if isinstance(tenant_body, dict): + tenant_id = _clean(tenant_body.get("id")) + if tenant_id: + attrs["tenant.id"] = tenant_id + + try: + session_id = _clean(vcon.get_tag(TELNYX_SESSION_TAG)) + except Exception: + session_id = None + if session_id: + attrs["call.session_id"] = session_id + + return attrs diff --git a/common/lib/tracing.py b/common/lib/tracing.py index e1bc008c..9c0b981a 100644 --- a/common/lib/tracing.py +++ b/common/lib/tracing.py @@ -1,25 +1,149 @@ +import atexit import logging +import os +import socket +import threading + +from opentelemetry import trace +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter as OTLPHttpSpanExporter +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +from lib.otlp_config import ( + EXPORT_TIMEOUT_S, + HTTP_PROTOBUF, + TRACE_SHUTDOWN_BUDGET_S, + http_signal_url, + otlp_protocol, + run_bounded, +) logger = logging.getLogger(__name__) +# The provider is tracked by pid, like the meter provider in lib.metrics. A forked worker inherits +# the parent's module state, including a span exporter whose threads and channels did not survive +# the fork, so it builds its own provider with its own service.instance.id. +_tracer_provider = None +_tracer_provider_pid = None +_init_lock = threading.Lock() + + +def init_tracer_provider(): + """Build this process's TracerProvider once per pid, when an OTLP endpoint is set. + + The provider is not installed as the global one: ``set_tracer_provider`` is single-call and + ``opentelemetry-instrument`` has usually set it already. Spans the server opens by hand come + from ``get_tracer`` and export through this provider. Auto-instrumented spans (FastAPI, Redis, + httpx) keep using the global one. Both share the active span context, so they join one trace. + + The pid marker is set only after the build, under a lock, so a second thread waits for the + provider instead of seeing "initialized" with nothing built. + """ + global _tracer_provider, _tracer_provider_pid + pid = os.getpid() + if _tracer_provider_pid == pid: + return _tracer_provider + with _init_lock: + if _tracer_provider_pid == pid: + return _tracer_provider + provider = None + endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") + if endpoint: + try: + host = socket.gethostname() + resource = Resource.create( + { + "service.name": os.environ.get("OTEL_SERVICE_NAME", "vcon-server"), + "host.name": host, + "service.instance.id": f"{host}-pid-{pid}", + } + ) + if otlp_protocol("traces") == HTTP_PROTOBUF: + exporter = OTLPHttpSpanExporter( + endpoint=http_signal_url("traces", endpoint), timeout=EXPORT_TIMEOUT_S + ) + else: + exporter = OTLPSpanExporter(endpoint=endpoint, timeout=EXPORT_TIMEOUT_S) + # shutdown_on_exit=False: the SDK's own atexit hook can block for 30 s on a dead + # collector. shutdown_tracer_provider (registered below) does it with a time bound. + provider = TracerProvider(resource=resource, shutdown_on_exit=False) + provider.add_span_processor(BatchSpanProcessor(exporter, export_timeout_millis=EXPORT_TIMEOUT_S * 1000)) + _register_atexit_once() + logger.info("OpenTelemetry tracing initialized: pid=%d", pid) + except Exception as e: + provider = None + logger.warning("Failed to initialize OpenTelemetry tracing: %s", e) + _tracer_provider = provider + _tracer_provider_pid = pid + return provider + + +def tracing_enabled(): + """True when an export endpoint is configured and this process has its own provider.""" + return init_tracer_provider() is not None + + +_atexit_registered = False -def init_tracing(): - """Instrument OpenAI calls with LLM-specific OTEL spans. - Adds model name, token counts, and message content to traces so that - any configured OTEL exporter (via OTEL_EXPORTER_OTLP_ENDPOINT) receives - full LLM span data. Routing to specific backends (SigNoz, Arize, etc.) - is handled by the OTEL Collector — not here. +def _register_atexit_once(): + global _atexit_registered + if not _atexit_registered: + _atexit_registered = True + atexit.register(shutdown_tracer_provider) + + +def shutdown_tracer_provider(): + """Flush and shut down this process's own provider, waiting at most a few seconds. + + A forked multiprocessing child leaves through ``os._exit``, which skips ``atexit``, so a worker + calls this itself before it returns. A provider inherited from another pid is left alone. With + the collector down the wait is capped, and spans still queued are dropped. """ + global _tracer_provider + provider = _tracer_provider + if provider is not None and _tracer_provider_pid == os.getpid(): + _tracer_provider = None + run_bounded(provider.shutdown, TRACE_SHUTDOWN_BUDGET_S, "tracing") + + +def get_tracer(name): + """Tracer for the server's own spans: this process's provider when set, else the global one.""" + provider = init_tracer_provider() + if provider is not None: + return provider.get_tracer(name) + return trace.get_tracer(name) + + +def init_tracing(build_provider=True): + """Prepare tracing in this process. + + Builds the per-process tracer provider unless ``build_provider`` is false (the multi-worker + parent skips it, since each worker builds its own), then instruments OpenAI through openinference when that + package is installed. It is not a project dependency, so by default this does nothing more. + When it is installed, prompt and reply content stays off the spans: inputs, outputs, message + text and embeddings are hidden. Model name and token counts remain. + """ + if build_provider: + init_tracer_provider() try: + from openinference.instrumentation import TraceConfig from openinference.instrumentation.openai import OpenAIInstrumentor - OpenAIInstrumentor().instrument() - logger.info("OpenAI instrumentation enabled (LLM spans active)") - except ImportError: - logger.warning( - "openinference-instrumentation-openai not installed; " - "OpenAI calls will not produce LLM spans" + config = TraceConfig( + hide_inputs=True, + hide_outputs=True, + hide_input_messages=True, + hide_output_messages=True, + hide_input_text=True, + hide_output_text=True, + hide_embedding_vectors=True, ) + OpenAIInstrumentor().instrument(config=config) + logger.info("OpenAI instrumentation enabled (LLM spans active, content hidden)") + except ImportError: + logger.warning("openinference-instrumentation-openai not installed; " "OpenAI calls will not produce LLM spans") except Exception as e: logger.warning("Failed to instrument OpenAI: %s", e) diff --git a/common/logging.conf b/common/logging.conf index 93208473..041d1e38 100644 --- a/common/logging.conf +++ b/common/logging.conf @@ -48,7 +48,7 @@ args = (sys.stderr,) keys = json, simple [formatter_json] -class = pythonjsonlogger.jsonlogger.JsonFormatter +class = lib.json_log_formatter.TraceJsonFormatter format = %(asctime)s %(levelname)s %(name)s %(message)s [formatter_simple] diff --git a/common/tests/lib/test_tracing.py b/common/tests/lib/test_tracing.py index 67840d51..6a217a62 100644 --- a/common/tests/lib/test_tracing.py +++ b/common/tests/lib/test_tracing.py @@ -15,6 +15,7 @@ def test_init_tracing_instruments_when_dependency_is_available(): instrumentation_module = types.ModuleType("openinference.instrumentation") openinference_module.instrumentation = instrumentation_module instrumentation_module.openai = openai_module + instrumentation_module.TraceConfig = Mock(name="TraceConfig") original_modules = sys.modules.copy() sys.modules.update( @@ -31,6 +32,13 @@ def test_init_tracing_instruments_when_dependency_is_available(): sys.modules.update(original_modules) instrumentor.instrument.assert_called_once() + # LLM content capture stays off: every content switch is passed as hidden. + config_kwargs = instrumentation_module.TraceConfig.call_args.kwargs + assert config_kwargs["hide_inputs"] is True + assert config_kwargs["hide_outputs"] is True + assert config_kwargs["hide_input_messages"] is True + assert config_kwargs["hide_output_messages"] is True + assert instrumentor.instrument.call_args.kwargs["config"] is instrumentation_module.TraceConfig.return_value def test_init_tracing_logs_when_dependency_is_missing(monkeypatch, caplog): @@ -58,6 +66,7 @@ def test_init_tracing_logs_when_instrumentor_fails(caplog): instrumentation_module = types.ModuleType("openinference.instrumentation") openinference_module.instrumentation = instrumentation_module instrumentation_module.openai = openai_module + instrumentation_module.TraceConfig = Mock(name="TraceConfig") original_modules = sys.modules.copy() sys.modules.update( diff --git a/common/tests/test_otel_correlation.py b/common/tests/test_otel_correlation.py new file mode 100644 index 00000000..6314cfd1 --- /dev/null +++ b/common/tests/test_otel_correlation.py @@ -0,0 +1,330 @@ +"""Traceparent at the API, trace ids in JSON logs, and chain span attributes. + +The vCons built here are minimal fixtures with a tenant attachment and a tag. They carry no +lawful_basis attachment: nothing in these tests reads or depends on one. +""" + +import io +import json +import logging +from unittest.mock import MagicMock, patch + +import pytest +from opentelemetry import trace +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import InMemoryMetricReader +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 lib.span_attributes import vcon_correlation_attributes + +TRACE_ID = "0af7651916cd43dd8448eb211c80319c" +TRACEPARENT = f"00-{TRACE_ID}-b7ad6b7169203331-01" + +TENANT_ID = 4242 +SESSION_ID = "session-abc-123" + + +def _vcon_dict(): + return { + "uuid": "0192f0f0-0000-7000-8000-000000000001", + "vcon": "0.4.0", + "attachments": [ + {"purpose": "tenant", "encoding": "json", "body": {"id": TENANT_ID}}, + { + "purpose": "tags", + "encoding": "json", + "body": [f"telnyx_call_session_id:{SESSION_ID}", "other:x"], + }, + ], + "dialog": [{"type": "text", "body": "SECRET DIALOG TEXT"}], + "analysis": [], + } + + +@pytest.fixture(autouse=True) +def keep_loggers_enabled(): + """Importing lib.logging_utils or main runs fileConfig, which disables loggers that already + exist. Put them back so other test modules still see their log output.""" + manager = logging.root.manager + before = {name: getattr(lg, "disabled", False) for name, lg in manager.loggerDict.items()} + yield + for name, disabled in before.items(): + manager.loggerDict[name].disabled = disabled + + +@pytest.fixture +def log_correlation(): + import lib.logging_utils # noqa: F401 fileConfig plus the OTel log record factory + + yield + + +@pytest.fixture +def span_exporter(): + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + yield exporter, provider + provider.shutdown() + + +# --- traceparent at the API ----------------------------------------------------------------- + + +def test_api_honors_incoming_traceparent(span_exporter): + from fastapi.testclient import TestClient + from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor + + import api + + exporter, provider = span_exporter + # Another test may already have served a request, which builds and caches the middleware stack. + api.app.middleware_stack = None + FastAPIInstrumentor.instrument_app(api.app, tracer_provider=provider) + try: + response = TestClient(api.app).get("/health", headers={"traceparent": TRACEPARENT}) + assert response.status_code == 200 + finally: + FastAPIInstrumentor.uninstrument_app(api.app) + api.app.middleware_stack = None + + server_spans = [s for s in exporter.get_finished_spans() if s.kind == trace.SpanKind.SERVER] + assert server_spans, "no server span recorded" + assert all(format(s.context.trace_id, "032x") == TRACE_ID for s in server_spans) + assert format(server_spans[0].parent.span_id, "016x") == "b7ad6b7169203331" + + +# --- trace ids in JSON logs ----------------------------------------------------------------- + + +def _json_logger(name): + from lib.json_log_formatter import TraceJsonFormatter + + stream = io.StringIO() + handler = logging.StreamHandler(stream) + handler.setFormatter(TraceJsonFormatter("%(asctime)s %(levelname)s %(name)s %(message)s")) + log = logging.getLogger(name) + log.handlers[:] = [handler] + log.propagate = False + log.setLevel(logging.INFO) + return log, stream + + +def test_json_log_record_carries_trace_and_span_ids(span_exporter, log_correlation, monkeypatch): + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4317") + _, provider = span_exporter + log, stream = _json_logger("o6.test.logs.inside") + tracer = provider.get_tracer("t") + with tracer.start_as_current_span("work") as span: + log.info("hello", extra={"vcon_processing_time": 1.5}) + ctx = span.get_span_context() + + record = json.loads(stream.getvalue()) + assert record["trace_id"] == format(ctx.trace_id, "032x") + assert record["span_id"] == format(ctx.span_id, "016x") + # Existing fields are unchanged. + assert record["message"] == "hello" + assert record["levelname"] == "INFO" + assert record["name"] == "o6.test.logs.inside" + assert "asctime" in record + assert record["vcon_processing_time"] == 1.5 + assert not [k for k in record if k.startswith("otel")] + + +def test_json_log_record_outside_a_span_has_no_ids(log_correlation, monkeypatch): + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4317") + log, stream = _json_logger("o6.test.logs.outside") + log.info("no span") + record = json.loads(stream.getvalue()) + assert "trace_id" not in record and "span_id" not in record + assert record["message"] == "no span" + + +def test_logging_conf_uses_the_trace_formatter(): + import configparser + from pathlib import Path + + conf = configparser.ConfigParser() + conf.read(Path(__file__).parent.parent / "logging.conf") + assert conf["formatter_json"]["class"] == "lib.json_log_formatter.TraceJsonFormatter" + + +# --- chain span attributes ------------------------------------------------------------------ + + +def test_correlation_attributes_from_vcon(): + assert vcon_correlation_attributes(_vcon_dict()) == { + "tenant.id": str(TENANT_ID), + "call.session_id": SESSION_ID, + } + + +def test_correlation_attributes_absent_when_not_in_vcon(): + assert vcon_correlation_attributes({"uuid": "u", "attachments": [], "dialog": []}) == {} + assert vcon_correlation_attributes(None) == {} + # A malformed tenant body gives nothing, and no body text is ever returned. + bad = {"uuid": "u", "attachments": [{"purpose": "tenant", "body": "not json", "encoding": "none"}]} + assert vcon_correlation_attributes(bad) == {} + + +VCON_UUID = "0192f0f0-0000-7000-8000-000000000001" + + +def _run_chain(span_provider, meter_reader, vcon_dict, tracing_on=True): + """Run one chain with an in-memory span provider. + + Returns the mock standing in for ``main.VconRedis`` so tests can count reads, and the Redis + client that ``main.r`` is patched to. + """ + import os + + import main as main_module + from main import VconChainRequest + from vcon import Vcon + + chain = {"name": "o6_chain", "links": ["mock_link"], "storages": [], "egress_lists": []} + main_module.config = {"links": {"mock_link": {"module": "mock_module", "options": {}}}} + link_module = MagicMock() + link_module.run.return_value = VCON_UUID + vcon_redis_cls = MagicMock() + vcon_redis_cls.return_value.get_vcon.return_value = Vcon(vcon_dict) if vcon_dict is not None else None + redis_client = MagicMock() + + meter_provider = MeterProvider(metric_readers=[meter_reader]) + with ( + patch.dict("main.imported_modules", {"mock_module": link_module}), + patch("main.get_tracer", side_effect=lambda name: span_provider.get_tracer(name)), + patch("main.VconRedis", vcon_redis_cls), + patch("main.r", redis_client), + patch.multiple( + "lib.metrics", + meter=meter_provider.get_meter("t"), + _otel_initialized_pid=os.getpid(), + OTEL_EXPORTER_OTLP_ENDPOINT="http://x:4317", + counter_metrics={}, + histogram_metrics={}, + updown_counter_metrics={}, + observable_gauges={}, + ), + patch("main.tracing_enabled", return_value=tracing_on), + ): + VconChainRequest(chain, VCON_UUID, context=None).process() + meter_provider.shutdown() + return vcon_redis_cls, redis_client + + +def test_chain_span_has_tenant_and_session_but_metrics_do_not(span_exporter): + exporter, provider = span_exporter + reader = InMemoryMetricReader() + _run_chain(provider, reader, _vcon_dict()) + + chain_spans = [s for s in exporter.get_finished_spans() if s.name == "vcon_processing.o6_chain"] + assert len(chain_spans) == 1 + attrs = dict(chain_spans[0].attributes) + assert attrs["tenant.id"] == str(TENANT_ID) + assert attrs["call.session_id"] == SESSION_ID + # No vCon body content on any span. + for span in exporter.get_finished_spans(): + assert "SECRET DIALOG TEXT" not in json.dumps(dict(span.attributes), default=str) + + data = reader.get_metrics_data() + seen = 0 + for rm in data.resource_metrics: + for sm in rm.scope_metrics: + for metric in sm.metrics: + for point in metric.data.data_points: + seen += 1 + keys = set(point.attributes) + assert "tenant.id" not in keys and "call.session_id" not in keys + assert str(TENANT_ID) not in map(str, point.attributes.values()) + assert SESSION_ID not in map(str, point.attributes.values()) + assert seen > 0 + + +def test_chain_span_without_tenant_or_tag_omits_both(span_exporter): + exporter, provider = span_exporter + plain = {"uuid": "0192f0f0-0000-7000-8000-000000000001", "attachments": [], "dialog": []} + _run_chain(provider, InMemoryMetricReader(), plain) + chain_span = next(s for s in exporter.get_finished_spans() if s.name == "vcon_processing.o6_chain") + assert "tenant.id" not in chain_span.attributes + assert "call.session_id" not in chain_span.attributes + + +# --- no extra read, and nothing unless an endpoint is configured --------------------------- + + +def test_chain_span_adds_no_vcon_read(span_exporter): + """The attributes come from the vCon the link step already loads: one get_vcon per link, and no + other Redis or storage call from the correlation code.""" + exporter, provider = span_exporter + with ( + patch("lib.vcon_redis.VconRedis.get_vcon_dict") as get_dict, + patch("lib.vcon_redis.VconRedis._load_from_storage") as storage, + ): + vcon_redis_cls, redis_client = _run_chain(provider, InMemoryMetricReader(), _vcon_dict()) + assert vcon_redis_cls.return_value.get_vcon.call_count == 1 + assert not redis_client.get.called + assert not get_dict.called and not storage.called + + +def test_no_attributes_when_no_endpoint_is_configured(span_exporter, monkeypatch): + """The distro's SDK provider records spans even with nothing exporting. With no endpoint the + correlation attributes are not computed at all.""" + monkeypatch.delenv("OTEL_EXPORTER_OTLP_ENDPOINT", raising=False) + import lib.tracing as tracing_lib + + monkeypatch.setattr(tracing_lib, "_tracer_provider", None) + monkeypatch.setattr(tracing_lib, "_tracer_provider_pid", None) + exporter, provider = span_exporter + with patch("main.vcon_correlation_attributes") as attrs: + _run_chain_real_gate(provider) + assert not attrs.called + span = next(s for s in exporter.get_finished_spans() if s.name == "vcon_processing.o6_chain") + assert "tenant.id" not in span.attributes + + +def _run_chain_real_gate(provider): + import main as main_module + from main import VconChainRequest + from vcon import Vcon + + chain = {"name": "o6_chain", "links": ["mock_link"], "storages": [], "egress_lists": []} + main_module.config = {"links": {"mock_link": {"module": "mock_module", "options": {}}}} + link_module = MagicMock() + link_module.run.return_value = VCON_UUID + vcon_redis_cls = MagicMock() + vcon_redis_cls.return_value.get_vcon.return_value = Vcon(_vcon_dict()) + with ( + patch.dict("main.imported_modules", {"mock_module": link_module}), + patch("main.get_tracer", side_effect=lambda n: provider.get_tracer(n)), + patch("main.VconRedis", vcon_redis_cls), + ): + VconChainRequest(chain, VCON_UUID, context=None).process() + + +def test_missing_vcon_with_endpoint_set_is_harmless(span_exporter): + exporter, provider = span_exporter + with ( + patch("lib.vcon_redis.VconRedis._load_from_storage") as storage, + patch("lib.vcon_redis.VconRedis._cache_back_to_redis") as cache_back, + ): + vcon_redis_cls, redis_client = _run_chain(provider, InMemoryMetricReader(), None, tracing_on=True) + assert not redis_client.get.called and not storage.called and not cache_back.called + span = next(s for s in exporter.get_finished_spans() if s.name == "vcon_processing.o6_chain") + assert "tenant.id" not in span.attributes and "call.session_id" not in span.attributes + + +# --- log ids only when telemetry is on --------------------------------------------------------- + + +def test_json_log_has_no_ids_when_no_endpoint_is_set(span_exporter, log_correlation, monkeypatch): + monkeypatch.delenv("OTEL_EXPORTER_OTLP_ENDPOINT", raising=False) + _, provider = span_exporter + log, stream = _json_logger("o6.test.logs.off") + with provider.get_tracer("t").start_as_current_span("work"): + log.info("telemetry off") + record = json.loads(stream.getvalue()) + assert "trace_id" not in record and "span_id" not in record + assert not [k for k in record if k.startswith("otel")] diff --git a/common/tests/test_otel_protocol_and_tracer_init.py b/common/tests/test_otel_protocol_and_tracer_init.py new file mode 100644 index 00000000..09827996 --- /dev/null +++ b/common/tests/test_otel_protocol_and_tracer_init.py @@ -0,0 +1,305 @@ +"""Metrics over OTLP/HTTP, protocol selection, and the per-process tracer provider.""" + +import os +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer +from unittest.mock import MagicMock, patch + +import pytest + + +class _Collector: + """A bare HTTP endpoint that records the paths OTLP/HTTP posts to.""" + + def __init__(self): + self.paths = [] + self.bodies = [] + outer = self + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers.get("Content-Length", 0)) + outer.bodies.append(self.rfile.read(length)) + outer.paths.append(self.path) + self.send_response(200) + self.send_header("Content-Type", "application/x-protobuf") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + self.server = HTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self.server.server_port}" + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + + def __enter__(self): + self.thread.start() + return self + + def __exit__(self, *exc): + self.server.shutdown() + self.server.server_close() + + +def _reset_metrics(metrics): + metrics._otel_initialized_pid = None + metrics.meter = None + metrics._meter_provider = None + for cache in ( + metrics.counter_metrics, + metrics.histogram_metrics, + metrics.updown_counter_metrics, + metrics.observable_gauges, + ): + cache.clear() + + +def test_metrics_export_over_http_protobuf(monkeypatch): + """CON-1407: OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf must send OTLP/HTTP, not gRPC.""" + from lib import metrics + + monkeypatch.setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf") + monkeypatch.delenv("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", raising=False) + monkeypatch.delenv("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL", raising=False) + _reset_metrics(metrics) + try: + with ( + _Collector() as collector, + patch("lib.metrics.atexit.register"), + patch.object(metrics, "OTEL_EXPORTER_OTLP_ENDPOINT", collector.url), + ): + metrics.increment_counter("o6.test.counter", attributes={"chain.name": "c"}) + assert metrics._meter_provider is not None + metrics._meter_provider.force_flush() + metrics._meter_provider.shutdown() + assert set(collector.paths) == {"/v1/metrics"} + assert b"o6.test.counter" in collector.bodies[0] + finally: + _reset_metrics(metrics) + + +def test_metrics_default_protocol_is_grpc(monkeypatch): + from lib import metrics + + monkeypatch.delenv("OTEL_EXPORTER_OTLP_PROTOCOL", raising=False) + monkeypatch.delenv("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL", raising=False) + _reset_metrics(metrics) + try: + with ( + patch("lib.metrics.OTLPMetricExporter") as grpc_exp, + patch("lib.metrics.OTLPHttpMetricExporter") as http_exp, + patch("lib.metrics.MeterProvider"), + patch("lib.metrics.atexit.register"), + patch.object(metrics, "OTEL_EXPORTER_OTLP_ENDPOINT", "http://fake:4317"), + ): + metrics._init_otel_metrics() + grpc_exp.assert_called_once_with(endpoint="http://fake:4317", timeout=2) + assert not http_exp.called + finally: + _reset_metrics(metrics) + + +def test_unknown_protocol_falls_back_to_grpc(monkeypatch): + from lib.otlp_config import otlp_protocol + + monkeypatch.setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json") + assert otlp_protocol("metrics") == "grpc" + monkeypatch.setenv("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL", "http/protobuf") + assert otlp_protocol("metrics") == "http/protobuf" + assert otlp_protocol("traces") == "grpc" + + +@pytest.fixture +def tracing_module(): + from lib import tracing + + tracing._tracer_provider = None + tracing._tracer_provider_pid = None + yield tracing + tracing._tracer_provider = None + tracing._tracer_provider_pid = None + + +def test_tracer_provider_not_built_without_endpoint(tracing_module, monkeypatch): + monkeypatch.delenv("OTEL_EXPORTER_OTLP_ENDPOINT", raising=False) + assert tracing_module.init_tracer_provider() is None + assert tracing_module._tracer_provider_pid == os.getpid() + + +def test_tracer_provider_exports_over_http_protobuf(tracing_module, monkeypatch): + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4318") + monkeypatch.setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf") + monkeypatch.delenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", raising=False) + with ( + patch("lib.tracing.OTLPHttpSpanExporter") as http_exp, + patch("lib.tracing.OTLPSpanExporter") as grpc_exp, + patch("lib.tracing.BatchSpanProcessor"), + ): + tracing_module.init_tracer_provider() + http_exp.assert_called_once_with(endpoint="http://collector:4318/v1/traces", timeout=2) + assert not grpc_exp.called + + +def test_tracer_provider_is_rebuilt_in_a_forked_child(tracing_module, monkeypatch): + """A child that inherits the parent's pid marker must build its own provider and instance id.""" + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4317") + monkeypatch.delenv("OTEL_EXPORTER_OTLP_PROTOCOL", raising=False) + tracing_module._tracer_provider = MagicMock(name="parent_provider") + tracing_module._tracer_provider_pid = os.getpid() + 1000 + + with patch("lib.tracing.OTLPSpanExporter"), patch("lib.tracing.BatchSpanProcessor"): + provider = tracing_module.init_tracer_provider() + + assert provider is tracing_module._tracer_provider + assert not isinstance(provider, MagicMock) + assert dict(provider.resource.attributes)["service.instance.id"].endswith(f"-pid-{os.getpid()}") + assert tracing_module._tracer_provider_pid == os.getpid() + + # Same pid again: no rebuild. + assert tracing_module.init_tracer_provider() is provider + + +def test_get_tracer_uses_process_provider(tracing_module, monkeypatch): + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4317") + with patch("lib.tracing.OTLPSpanExporter"), patch("lib.tracing.BatchSpanProcessor"): + tracer = tracing_module.get_tracer("x") + assert tracer is not None + assert tracing_module._tracer_provider is not None + + +def test_pid_marker_is_set_only_after_the_provider_is_built(tracing_module, monkeypatch): + """A second thread must not see 'initialized' while the first is still building.""" + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4317") + monkeypatch.delenv("OTEL_EXPORTER_OTLP_PROTOCOL", raising=False) + seen = {} + + def exporter_factory(**kwargs): + seen["pid_during_build"] = tracing_module._tracer_provider_pid + return MagicMock() + + with patch("lib.tracing.OTLPSpanExporter", side_effect=exporter_factory), patch("lib.tracing.BatchSpanProcessor"): + provider = tracing_module.init_tracer_provider() + assert seen["pid_during_build"] is None + assert provider is not None and tracing_module._tracer_provider_pid == os.getpid() + + +def test_init_tracing_can_skip_building_the_provider(tracing_module, monkeypatch): + """The multi-worker parent skips the provider so each child builds its own after the fork.""" + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4317") + with patch("lib.tracing.OTLPSpanExporter") as exp: + tracing_module.init_tracing(build_provider=False) + assert not exp.called + assert tracing_module._tracer_provider is None and tracing_module._tracer_provider_pid is None + + +# --- a forked worker flushes before it returns --------------------------------------------------- + + +# A fresh interpreter does the forking. Forking the pytest process after other tests have loaded +# gRPC can crash the child on macOS, which has nothing to do with what is under test. +_FORK_DRIVER = """ +import multiprocessing, os, sys +import main +from lib import metrics, tracing + +url, fail = sys.argv[1], sys.argv[2] == "1" +os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = url +os.environ["OTEL_EXPORTER_OTLP_PROTOCOL"] = "http/protobuf" +metrics.OTEL_EXPORTER_OTLP_ENDPOINT = url + + +def body(worker_id): + with tracing.get_tracer("t").start_as_current_span("child.work"): + pass + metrics.increment_counter("o6.child.counter") + if fail: + raise RuntimeError("worker crashed") + + +def child(): + # Runs in a forked child, which leaves through os._exit and never runs atexit hooks. + main._worker_loop_inner = body + try: + main.worker_loop(1) + except RuntimeError: + pass + + +if __name__ == "__main__": + proc = multiprocessing.get_context("fork").Process(target=child) + proc.start() + proc.join(timeout=60) + sys.exit(proc.exitcode) +""" + + +@pytest.mark.parametrize("fail", [False, True]) +def test_forked_worker_exports_spans_and_metrics_without_a_manual_flush(fail, tmp_path): + import subprocess + import sys + + root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join(os.path.join(root, d) for d in ("", "common", "conserver", "api")) + env.pop("OTEL_EXPORTER_OTLP_PROTOCOL", None) + driver = tmp_path / "fork_driver.py" + driver.write_text(_FORK_DRIVER) + with _Collector() as collector: + result = subprocess.run( + [sys.executable, str(driver), collector.url, "1" if fail else "0"], + env=env, + cwd=root, + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 0, result.stderr[-2000:] + assert "/v1/traces" in collector.paths + assert b"child.work" in b"".join(collector.bodies) + assert "/v1/metrics" in collector.paths + + +# --- shutdown is bounded when the collector is down ---------------------------------------------- + + +@pytest.mark.parametrize( + "protocol,mode", [("grpc", "refused"), ("http/protobuf", "refused"), ("http/protobuf", "hang")] +) +def test_worker_shutdown_returns_quickly_with_an_unreachable_collector(monkeypatch, protocol, mode): + """A dead collector must not hold a worker for the SDK defaults (about a minute).""" + import socket + import time + + from lib import metrics, tracing + + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + if mode == "hang": + sock.listen(128) # accepts connections at the kernel level, never answers + else: + sock.close() # nothing listening: connection refused + url = f"http://127.0.0.1:{port}" + monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", url) + monkeypatch.setenv("OTEL_EXPORTER_OTLP_PROTOCOL", protocol) + monkeypatch.setattr(metrics, "OTEL_EXPORTER_OTLP_ENDPOINT", url) + for module, names in ((tracing, ("_tracer_provider", "_tracer_provider_pid")), (metrics, ())): + for n in names: + monkeypatch.setattr(module, n, None) + _reset_metrics(metrics) + try: + tracer = tracing.get_tracer("t") + for i in range(3000): + tracer.start_span(f"s{i}").end() + metrics.increment_counter("o6.down.counter") + + started = time.monotonic() + tracing.shutdown_tracer_provider() + metrics.shutdown_meter_provider() + elapsed = time.monotonic() - started + finally: + if mode == "hang": + sock.close() + _reset_metrics(metrics) + assert elapsed < 7, f"shutdown took {elapsed:.1f}s" diff --git a/conserver/main.py b/conserver/main.py index 6e30e203..c793f311 100644 --- a/conserver/main.py +++ b/conserver/main.py @@ -36,9 +36,10 @@ from settings import VCON_DLQ_EXPIRY from lib.context_utils import retrieve_context, store_context_sync, extract_otel_trace_context from lib.queue import VconQueue -from lib.tracing import init_tracing +from lib.tracing import init_tracing, get_tracer, tracing_enabled, shutdown_tracer_provider +from lib.span_attributes import vcon_correlation_attributes from lib.error_tracking import init_error_tracker -from lib.metrics import record_histogram, increment_counter, add_updown_counter +from lib.metrics import record_histogram, increment_counter, add_updown_counter, shutdown_meter_provider from storage.base import Storage # OpenTelemetry trace context propagation @@ -228,6 +229,7 @@ def __init__(self, chain_details: ChainConfig, vcon_id: str, context: Optional[D self.context = context self._span = None self._span_context_manager = None + self._correlation_set = False def process(self) -> None: """Process the vCon through all configured chain links. @@ -243,7 +245,6 @@ def process(self) -> None: """ self._span_context_manager = self._create_span_from_context() self._span = self._span_context_manager.__enter__() - vcon_started = time.time() logger.debug( "Started processing vCon %s with chain %s", @@ -296,6 +297,24 @@ def process(self) -> None: except Exception as e: logger.debug(f"Failed to end span: {e}") + def _set_correlation_attributes(self, vcon_dict) -> None: + """Put ``tenant.id`` and ``call.session_id`` on the chain span. + + Takes the vCon that ``_process_link`` has already loaded for its after-link hook, so it adds + no Redis or storage read. Span attributes only. Never copy them onto a metric: one series + per call fills the metrics store. Skipped unless an export endpoint is configured. + """ + if self._correlation_set: + return + self._correlation_set = True + try: + if self._span is None or not self._span.is_recording() or not tracing_enabled(): + return + for key, value in vcon_correlation_attributes(vcon_dict).items(): + self._span.set_attribute(key, value) + except Exception as e: + logger.debug(f"Failed to set correlation attributes for vCon {self.vcon_id}: {e}") + def _create_span_from_context(self): """Open a vcon_processing root span for this chain run. @@ -313,7 +332,7 @@ def _create_span_from_context(self): Returns: The span context manager (never None). """ - tracer = trace.get_tracer(__name__) + tracer = get_tracer(__name__) links = [] if self.context: try: @@ -394,7 +413,7 @@ def _process_storage(self, storage_name: str) -> None: storage_name: Name of the storage backend to use """ # Create a span for this storage operation - automatically inherits parent span context - tracer = trace.get_tracer(__name__) + tracer = get_tracer(__name__) with tracer.start_as_current_span( f"storage.{storage_name}", attributes={ @@ -560,7 +579,7 @@ def _process_link(self, links: list[str], link_index: int) -> bool: logger.debug("Processing link %s for vCon: %s", link_name, self.vcon_id) link = config["links"][link_name] # Create a span for this link - automatically inherits parent span context - tracer = trace.get_tracer(__name__) + tracer = get_tracer(__name__) with tracer.start_as_current_span( f"link.{link_name}", attributes={ @@ -585,6 +604,8 @@ def _process_link(self, links: list[str], link_index: int) -> bool: parties = [] try: _vcon = VconRedis().get_vcon(self.vcon_id) + if _vcon is not None: + self._set_correlation_attributes(_vcon.vcon_dict) for party in (_vcon.parties or []) if _vcon else []: tel = party.get("tel") if isinstance(party, dict) else getattr(party, "tel", None) mailto = party.get("mailto") if isinstance(party, dict) else getattr(party, "mailto", None) @@ -772,6 +793,20 @@ def _handle_vcon( def worker_loop(worker_id: int) -> None: + """Run one worker and flush its telemetry on the way out, normal or not. + + A forked multiprocessing child exits through ``os._exit``, which skips ``atexit``, so the + ``atexit`` hooks on the tracer and meter providers never run there. Without this, the last + batch of spans and metrics from every worker is lost. + """ + try: + _worker_loop_inner(worker_id) + finally: + shutdown_tracer_provider() + shutdown_meter_provider() + + +def _worker_loop_inner(worker_id: int) -> None: """Worker process main loop for vCon processing. Each worker independently polls Redis queues and processes vCons. @@ -951,9 +986,11 @@ def main() -> None: version_info["build_time"] ) - init_tracing() - worker_count = get_worker_count() + # With several workers each child builds its own tracer provider after the fork, so the parent + # skips it and does not hand every child an idle one. + init_tracing(build_provider=worker_count <= 1) + parallel_storage = is_parallel_storage_enabled() start_method = get_start_method() diff --git a/docker/Dockerfile b/docker/Dockerfile index e8bcf28c..c9d23d89 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -37,10 +37,8 @@ RUN uv venv --seed /opt/venv && \ UV_PROJECT_ENVIRONMENT=/opt/venv uv sync --frozen --group conserver --group api --group dev --group storage-milvus ENV PATH="/opt/venv/bin:$PATH" -# Auto-install OTel instrumentation packages for the installed libraries. -# || true: bootstrap raises on version conflicts between auto-detected packages; -# instrumentation still works for packages that installed cleanly. -RUN opentelemetry-bootstrap -a install || true +# The OTel instrumentations (Redis, httpx, requests, logging, and FastAPI in the api group) are pinned +# dependencies in pyproject.toml, so a missing one fails the sync above instead of the build passing silently. COPY . /app diff --git a/docker/Dockerfile.api b/docker/Dockerfile.api index ab6601b1..7a643fc1 100644 --- a/docker/Dockerfile.api +++ b/docker/Dockerfile.api @@ -27,14 +27,11 @@ COPY pyproject.toml uv.lock /app/ # Install core + API-specific dependencies (FastAPI, uvicorn, peewee, etc.). # Venv at /opt/venv (not /app) so docker-compose volume mounts don't wipe it. -# --seed adds pip so opentelemetry-bootstrap can use it. RUN uv venv --seed /opt/venv && UV_PROJECT_ENVIRONMENT=/opt/venv uv sync --frozen --no-dev --group api ENV PATH="/opt/venv/bin:$PATH" -# Auto-install OTel instrumentation packages for the installed libraries. -# || true: bootstrap raises on version conflicts between auto-detected packages; -# instrumentation still works for packages that installed cleanly. -RUN opentelemetry-bootstrap -a install || true +# The OTel instrumentations (Redis, httpx, requests, logging, and FastAPI in the api group) are pinned +# dependencies in pyproject.toml, so a missing one fails the sync above instead of the build passing silently. COPY common/ /app/common/ COPY api/ /app/api/ diff --git a/docker/Dockerfile.conserver b/docker/Dockerfile.conserver index 20baae24..7e4a2e41 100644 --- a/docker/Dockerfile.conserver +++ b/docker/Dockerfile.conserver @@ -32,15 +32,12 @@ COPY pyproject.toml uv.lock /app/ # Install core + all optional groups needed for processing links and storage backends. # Venv at /opt/venv (not /app) so docker-compose volume mounts don't wipe it. -# --seed adds pip so opentelemetry-bootstrap can use it. # watchdog (used by docker-compose watchmedo hot-reload) is included in the conserver group. RUN uv venv --seed /opt/venv && UV_PROJECT_ENVIRONMENT=/opt/venv uv sync --frozen --no-dev --group conserver ENV PATH="/opt/venv/bin:$PATH" -# Auto-install OTel instrumentation packages for the installed libraries. -# || true: bootstrap raises on version conflicts between auto-detected packages; -# instrumentation still works for packages that installed cleanly. -RUN opentelemetry-bootstrap -a install || true +# The OTel instrumentations (Redis, httpx, requests, logging, and FastAPI in the api group) are pinned +# dependencies in pyproject.toml, so a missing one fails the sync above instead of the build passing silently. COPY common/ /app/common/ COPY conserver/ /app/conserver/ diff --git a/docs/operations/logging.md b/docs/operations/logging.md index 53eeb155..aeb9e630 100644 --- a/docs/operations/logging.md +++ b/docs/operations/logging.md @@ -31,7 +31,7 @@ Both shipped files stop at `INFO`, including `logging_dev.conf`, because the roo ## Read the JSON output -The JSON formatter is `pythonjsonlogger`. Fields passed through `extra` become top-level keys. +The JSON formatter is `TraceJsonFormatter`, a `pythonjsonlogger` subclass. Fields passed through `extra` become top-level keys. With `OTEL_EXPORTER_OTLP_ENDPOINT` set, a record written inside an OpenTelemetry span also has `trace_id` and `span_id`. ```json {"asctime": "2026-11-03 17:46:27,793", "levelname": "INFO", "name": "storage.base", "message": "Finished storage postgres module storage.postgres save for vCon: 018f0000-0000-8000-8000-000000000001 in 0.12 seconds.", "taskName": null, "storage_processing_time": 0.12} diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index f6856343..2914a20b 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -62,9 +62,15 @@ Take CPU, memory, disk and network figures from your container platform. The ser The server has two separate OpenTelemetry pipelines. -**Metrics** go through `common/lib/metrics.py`. They publish only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set, and always over OTLP gRPC, whatever `OTEL_EXPORTER_OTLP_PROTOCOL` says. Each process exports with its own `service.instance.id`, so sum across instances for a total. +**Metrics** go through `common/lib/metrics.py`. They publish only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set. The exporter follows `OTEL_EXPORTER_OTLP_PROTOCOL`: `grpc`, or `http/protobuf`, which posts to `/v1/metrics`. Unset means `grpc`. `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` and `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` override one signal. Each process exports with its own `service.instance.id`, so sum across instances for a total. -**Traces** come from `opentelemetry-instrument`, which wraps both processes in `docker-compose.yml`. Workers open one span per vCon, with `link.*` and `storage.*` children, and `init_tracing` adds OpenAI LLM spans. The API has only auto-instrumented request spans. +**Traces** come from `opentelemetry-instrument`, which wraps both processes in `docker-compose.yml`, and from spans the worker opens itself. The images install the Redis, httpx, requests, logging and FastAPI instrumentations as pinned dependencies, so a build fails if one is missing. The API honors an incoming `traceparent` header: its request span joins the caller's trace. Workers open one span per vCon, `vcon_processing.`, with `link.*` and `storage.*` children. The chain span carries `tenant.id`, from the vCon's `tenant` attachment, and `call.session_id`, from a `telnyx_call_session_id` tag, when the vCon has them and an export endpoint is set. They are read from the vCon the link step already loads, so they add no Redis or storage read. They are span attributes only and never go on a metric, since one series per call grows without bound. + +The worker spans export through a tracer provider that each worker process builds for itself, with its own `service.instance.id`, the same way metrics do. A worker flushes both providers when it returns, because a forked worker never runs `atexit`. It follows the same protocol variables, plus `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` and `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. + +Spans and logs carry no vCon bodies, dialog, transcripts or prompts. If the optional `openinference` OpenAI instrumentation is installed, `init_tracing` turns it on with prompt and reply content hidden, so only model names and token counts remain. + +**Logs** are JSON. With an export endpoint set, a record written inside a span also has `trace_id` and `span_id`, so a log line can be matched to its trace. Outside a span, or with no endpoint, the two fields are absent. Set the endpoint in `.env`. `docker-compose.yml` passes the `OTEL_EXPORTER_OTLP_*` variables through. @@ -134,7 +140,7 @@ service: ### Send traces to Langfuse -Langfuse accepts traces over OTLP HTTP. Metrics cannot follow, since the metrics exporter is gRPC only. If you want metrics too, use [a collector to fan out](#fan-out-to-several-backends). +Langfuse accepts traces over OTLP HTTP and does not ingest metrics, so the metrics export to it fails. If you want metrics too, use [a collector to fan out](#fan-out-to-several-backends). In Langfuse, open the API keys page in its settings and copy your public and secret keys. Then build the auth header: diff --git a/docs/reference/environment.md b/docs/reference/environment.md index 68fece05..68290678 100644 --- a/docs/reference/environment.md +++ b/docs/reference/environment.md @@ -11,7 +11,7 @@ A default of `none` means the read returns nothing when the variable is unset. ` Each process reads these values when it starts, so restart it after a change. For help choosing values, see the [environment guide](../configuration/environment-variables.md). -The code reads 40 variables. +The code reads 45 variables. | Variable | Default | Type | Read in | Description | |---|---|---|---|---| @@ -32,9 +32,14 @@ The code reads 40 variables. | `LOGGING_CONFIG_FILE` | `logging.conf` beside `common/settings.py` | string | `common/settings.py` | Path passed to `logging.config.fileConfig`. The repo also ships `common/logging_dev.conf`. | | `LOG_LEVEL` | `DEBUG` | string | `common/settings.py` | Read into `settings`, but no code uses that setting. The logging config file sets log levels. | | `OPENAI_API_KEY` | `""` in `conserver/links/detect_engagement/__init__.py`
none in `common/settings.py` | string | `common/settings.py`
`conserver/links/detect_engagement/__init__.py` | Default `OPENAI_API_KEY` option for the `detect_engagement` link. The `settings` value is unused. Other links take the key from link options. | -| `OTEL_EXPORTER_OTLP_ENDPOINT` | none | string | `common/lib/metrics.py` | OTLP endpoint for metrics, passed to the gRPC exporter in `common/lib/metrics.py`. Unset or empty, the metric helpers do nothing. | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | none | string | `common/lib/json_log_formatter.py`
`common/lib/metrics.py`
`common/lib/tracing.py` | OTLP endpoint for the worker's metrics and its own spans. Unset or empty, neither is exported. With `http/protobuf` the code appends `/v1/metrics` or `/v1/traces`. | +| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | none | string | `common/lib/otlp_config.py` | Full OTLP/HTTP URL for metrics. Overrides the path built from `OTEL_EXPORTER_OTLP_ENDPOINT`. | +| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | none | string | `common/lib/otlp_config.py` | Use `grpc` or `http/protobuf` for metrics only. Overrides `OTEL_EXPORTER_OTLP_PROTOCOL`. | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | none | string | `common/lib/otlp_config.py` | Export protocol for metrics and spans, `grpc` or `http/protobuf`. Unset means `grpc`. Other values fall back to `grpc` with a warning. | +| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | none | string | `common/lib/otlp_config.py` | Full OTLP/HTTP URL for spans. Overrides the path built from `OTEL_EXPORTER_OTLP_ENDPOINT`. | +| `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | none | string | `common/lib/otlp_config.py` | Use `grpc` or `http/protobuf` for spans only. Overrides `OTEL_EXPORTER_OTLP_PROTOCOL`. | | `OTEL_METRIC_EXPORT_INTERVAL` | `5000` | integer | `common/lib/metrics.py` | Metric export interval in milliseconds. | -| `OTEL_SERVICE_NAME` | `vcon-server` | string | `common/lib/metrics.py` | Value of the `service.name` resource attribute on metrics. The Compose file sets `conserver` and `api`. | +| `OTEL_SERVICE_NAME` | `vcon-server` | string | `common/lib/metrics.py`
`common/lib/tracing.py` | Value of the `service.name` resource attribute on metrics and spans. The Compose file sets `conserver` and `api`. | | `REDIS_URL` | `redis://localhost` | string | `common/settings.py` | Redis connection URL. `docker/wait_for_redis.sh` reads it too, and skips its wait when it is unset or empty. | | `SENTRY_DSN` | none | string | `common/lib/error_tracking.py` | Sentry DSN. Unset, Sentry stays off. Set, `ENV` must be in the process environment too. | | `SXT_API_KEY` | none | string | `common/storage/spaceandtime/__init__.py` | Space and Time API key for the `spaceandtime` storage adapter. | diff --git a/pyproject.toml b/pyproject.toml index f2bd560d..e8684558 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,12 @@ dependencies = [ "opentelemetry-sdk>=1.38.0", "opentelemetry-exporter-otlp>=1.38.0", "opentelemetry-distro==0.59b0", + # Instrumentations the images rely on, pinned to the distro's release so a build fails if one is + # missing. FastAPI is in the api group. + "opentelemetry-instrumentation-redis==0.59b0", + "opentelemetry-instrumentation-httpx==0.59b0", + "opentelemetry-instrumentation-requests==0.59b0", + "opentelemetry-instrumentation-logging==0.59b0", "redis==4.6.0", "pyyaml>=6.0.1", "sentry-sdk>=2.8.0", @@ -56,6 +62,7 @@ storage-milvus = [ api = [ {include-group = "storage"}, "fastapi==0.115.6", + "opentelemetry-instrumentation-fastapi==0.59b0", "uvicorn==0.23.2", "gunicorn>=23.0.0", "starlette>=0.40.0", diff --git a/scripts/docs/descriptions.yml b/scripts/docs/descriptions.yml index 73dcbc08..08a6c82a 100644 --- a/scripts/docs/descriptions.yml +++ b/scripts/docs/descriptions.yml @@ -56,9 +56,14 @@ environment: description: Path passed to `logging.config.fileConfig`. The repo also ships `common/logging_dev.conf`. default: "`logging.conf` beside `common/settings.py`" OPENAI_API_KEY: Default `OPENAI_API_KEY` option for the `detect_engagement` link. The `settings` value is unused. Other links take the key from link options. - OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint for metrics, passed to the gRPC exporter in `common/lib/metrics.py`. Unset or empty, the metric helpers do nothing. + OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint for the worker's metrics and its own spans. Unset or empty, neither is exported. With `http/protobuf` the code appends `/v1/metrics` or `/v1/traces`. + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: Full OTLP/HTTP URL for metrics. Overrides the path built from `OTEL_EXPORTER_OTLP_ENDPOINT`. + OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: Use `grpc` or `http/protobuf` for metrics only. Overrides `OTEL_EXPORTER_OTLP_PROTOCOL`. + OTEL_EXPORTER_OTLP_PROTOCOL: Export protocol for metrics and spans, `grpc` or `http/protobuf`. Unset means `grpc`. Other values fall back to `grpc` with a warning. + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: Full OTLP/HTTP URL for spans. Overrides the path built from `OTEL_EXPORTER_OTLP_ENDPOINT`. + OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: Use `grpc` or `http/protobuf` for spans only. Overrides `OTEL_EXPORTER_OTLP_PROTOCOL`. OTEL_METRIC_EXPORT_INTERVAL: Metric export interval in milliseconds. - OTEL_SERVICE_NAME: Value of the `service.name` resource attribute on metrics. The Compose file sets `conserver` and `api`. + OTEL_SERVICE_NAME: Value of the `service.name` resource attribute on metrics and spans. The Compose file sets `conserver` and `api`. REDIS_URL: Redis connection URL. `docker/wait_for_redis.sh` reads it too, and skips its wait when it is unset or empty. SENTRY_DSN: description: Sentry DSN. Unset, Sentry stays off. Set, `ENV` must be in the process environment too. diff --git a/uv.lock b/uv.lock index e644899f..90ba0e41 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.12, <3.14" resolution-markers = [ "python_full_version >= '3.13' and sys_platform == 'win32'", @@ -132,6 +132,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/38/0e/27be9fdef66e72d64c0cdc3cc2823101b80585f8119b5c112c2e8f5f7dab/anyio-4.12.1-py3-none-any.whl", hash = "sha256:d405828884fc140aa80a3c667b8beed277f1dfedec42ba031bd6ac3db606ab6c", size = 113592, upload-time = "2026-01-06T11:45:19.497Z" }, ] +[[package]] +name = "asgiref" +version = "3.13.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6b/90/f5fce14e95fccf53b58e8e2c47cd84d40d105d64073ae1ac75166db150e0/asgiref-3.13.0.tar.gz", hash = "sha256:034cc8cbf72d00553b4be256703ac545120b4e50af13b49dec99da899aeeecb4", size = 52941, upload-time = "2026-10-23T08:13:14.715Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/b0/ec211e1f7966247cb6469158d856bac9aa4c2fe13621bd6a352e4f850453/asgiref-3.13.0-py3-none-any.whl", hash = "sha256:f9596a2434512686473d50f96ff6207fbba49ae1a785dfac614df4aeb085674d", size = 27593, upload-time = "2026-10-23T08:13:13.394Z" }, +] + [[package]] name = "asn1crypto" version = "1.5.1" @@ -1295,6 +1304,97 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/f5/7a40ff3f62bfe715dad2f633d7f1174ba1a7dd74254c15b2558b3401262a/opentelemetry_instrumentation-0.59b0-py3-none-any.whl", hash = "sha256:44082cc8fe56b0186e87ee8f7c17c327c4c2ce93bdbe86496e600985d74368ee", size = 33020, upload-time = "2025-10-16T08:38:31.463Z" }, ] +[[package]] +name = "opentelemetry-instrumentation-asgi" +version = "0.59b0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asgiref" }, + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "opentelemetry-util-http" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b7/a4/cfbb6fc1ec0aa9bf5a93f548e6a11ab3ac1956272f17e0d399aa2c1f85bc/opentelemetry_instrumentation_asgi-0.59b0.tar.gz", hash = "sha256:2509d6fe9fd829399ce3536e3a00426c7e3aa359fc1ed9ceee1628b56da40e7a", size = 25116, upload-time = "2025-10-16T08:39:36.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f3/88/fe02d809963b182aafbf5588685d7a05af8861379b0ec203d48e360d4502/opentelemetry_instrumentation_asgi-0.59b0-py3-none-any.whl", hash = "sha256:ba9703e09d2c33c52fa798171f344c8123488fcd45017887981df088452d3c53", size = 16797, upload-time = "2025-10-16T08:38:37.214Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-fastapi" +version = "0.59b0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-instrumentation-asgi" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "opentelemetry-util-http" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ab/a7/7a6ce5009584ce97dbfd5ce77d4f9d9570147507363349d2cb705c402bcf/opentelemetry_instrumentation_fastapi-0.59b0.tar.gz", hash = "sha256:e8fe620cfcca96a7d634003df1bc36a42369dedcdd6893e13fb5903aeeb89b2b", size = 24967, upload-time = "2025-10-16T08:39:46.056Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/27/5914c8bf140ffc70eff153077e225997c7b054f0bf28e11b9ab91b63b18f/opentelemetry_instrumentation_fastapi-0.59b0-py3-none-any.whl", hash = "sha256:0d8d00ff7d25cca40a4b2356d1d40a8f001e0668f60c102f5aa6bb721d660c4f", size = 13492, upload-time = "2025-10-16T08:38:52.312Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-httpx" +version = "0.59b0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "opentelemetry-util-http" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/6b/1bdf36b68cace9b4eae3cbbade4150c71c90aa392b127dda5bb5c2a49307/opentelemetry_instrumentation_httpx-0.59b0.tar.gz", hash = "sha256:a1cb9b89d9f05a82701cc9ab9cfa3db54fd76932489449778b350bc1b9f0e872", size = 19886, upload-time = "2025-10-16T08:39:48.428Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/16/c1e0745d20af392ec9060693531d7f01239deb2d81e460d0c379719691b8/opentelemetry_instrumentation_httpx-0.59b0-py3-none-any.whl", hash = "sha256:7dc9f66aef4ca3904d877f459a70c78eafd06131dc64d713b9b1b5a7d0a48f05", size = 15197, upload-time = "2025-10-16T08:38:55.507Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-logging" +version = "0.59b0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/be/88/9c5f70fa8b8d96d30be378fc6eb1776e13aea456db15009f4eaef4928847/opentelemetry_instrumentation_logging-0.59b0.tar.gz", hash = "sha256:1b51116444edc74f699daf9002ded61529397100c9bc903c8b9aaa75a5218c76", size = 9969, upload-time = "2025-10-16T08:39:51.653Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/a0/340cc45d71437c2f7e27f13c1d2e335b18bbc7a24fd7d174018500b3c7ba/opentelemetry_instrumentation_logging-0.59b0-py3-none-any.whl", hash = "sha256:fdd4eddbd093fc421df8f7d356ecb15b320a1f3396b56bce5543048a5c457eea", size = 12577, upload-time = "2025-10-16T08:38:58.064Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-redis" +version = "0.59b0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7f/f8/58bf83b10a97f67c7f06505bc4c4accbea7d961dec653a8c9e91fb65887e/opentelemetry_instrumentation_redis-0.59b0.tar.gz", hash = "sha256:d7f1c7c55ab57e10e0155c4c65d028a7e436aec7ccc7ccbf1d77e8cd12b55abd", size = 13922, upload-time = "2025-10-16T08:39:59.507Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/87/fef04827239ce84e2729b11611e8d5be7892288f620961ee9b9bafd035c5/opentelemetry_instrumentation_redis-0.59b0-py3-none-any.whl", hash = "sha256:8f7494dede5a6bfe5d8f20da67b371a502883398081856378380efef27da0bdf", size = 14946, upload-time = "2025-10-16T08:39:07.887Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-requests" +version = "0.59b0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "opentelemetry-util-http" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/49/01/31282a46b09684dfc636bc066deb090bae6973e71e85e253a8c74e727b1f/opentelemetry_instrumentation_requests-0.59b0.tar.gz", hash = "sha256:9af2ffe3317f03074d7f865919139e89170b6763a0251b68c25e8e64e04b3400", size = 15186, upload-time = "2025-10-16T08:40:00.558Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/ea/c282ba418b2669e4f730cb3f68b02a0ca65f4baf801e971169a4cc449ffb/opentelemetry_instrumentation_requests-0.59b0-py3-none-any.whl", hash = "sha256:d43121532877e31a46c48649279cec2504ee1e0ceb3c87b80fe5ccd7eafc14c1", size = 12966, upload-time = "2025-10-16T08:39:09.919Z" }, +] + [[package]] name = "opentelemetry-proto" version = "1.38.0" @@ -1334,6 +1434,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/7d/c88d7b15ba8fe5c6b8f93be50fc11795e9fc05386c44afaf6b76fe191f9b/opentelemetry_semantic_conventions-0.59b0-py3-none-any.whl", hash = "sha256:35d3b8833ef97d614136e253c1da9342b4c3c083bbaf29ce31d572a1c3825eed", size = 207954, upload-time = "2025-10-16T08:35:48.054Z" }, ] +[[package]] +name = "opentelemetry-util-http" +version = "0.59b0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/34/f7/13cd081e7851c42520ab0e96efb17ffbd901111a50b8252ec1e240664020/opentelemetry_util_http-0.59b0.tar.gz", hash = "sha256:ae66ee91be31938d832f3b4bc4eb8a911f6eddd38969c4a871b1230db2a0a560", size = 9412, upload-time = "2025-10-16T08:40:11.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/56/62282d1d4482061360449dacc990c89cad0fc810a2ed937b636300f55023/opentelemetry_util_http-0.59b0-py3-none-any.whl", hash = "sha256:6d036a07563bce87bf521839c0671b507a02a0d39d7ea61b88efa14c6e25355d", size = 7648, upload-time = "2025-10-16T08:39:25.706Z" }, +] + [[package]] name = "orjson" version = "3.11.7" @@ -2404,6 +2513,10 @@ dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-distro" }, { name = "opentelemetry-exporter-otlp" }, + { name = "opentelemetry-instrumentation-httpx" }, + { name = "opentelemetry-instrumentation-logging" }, + { name = "opentelemetry-instrumentation-redis" }, + { name = "opentelemetry-instrumentation-requests" }, { name = "opentelemetry-sdk" }, { name = "pycose" }, { name = "pydantic" }, @@ -2427,6 +2540,7 @@ api = [ { name = "fastapi" }, { name = "gunicorn" }, { name = "msal" }, + { name = "opentelemetry-instrumentation-fastapi" }, { name = "peewee" }, { name = "psycopg2-binary" }, { name = "pymongo" }, @@ -2484,6 +2598,10 @@ requires-dist = [ { name = "opentelemetry-api", specifier = ">=1.38.0" }, { name = "opentelemetry-distro", specifier = "==0.59b0" }, { name = "opentelemetry-exporter-otlp", specifier = ">=1.38.0" }, + { name = "opentelemetry-instrumentation-httpx", specifier = "==0.59b0" }, + { name = "opentelemetry-instrumentation-logging", specifier = "==0.59b0" }, + { name = "opentelemetry-instrumentation-redis", specifier = "==0.59b0" }, + { name = "opentelemetry-instrumentation-requests", specifier = "==0.59b0" }, { name = "opentelemetry-sdk", specifier = ">=1.38.0" }, { name = "pycose", specifier = ">=1.0.1" }, { name = "pydantic", specifier = ">=2.6.2" }, @@ -2507,6 +2625,7 @@ api = [ { name = "fastapi", specifier = "==0.115.6" }, { name = "gunicorn", specifier = ">=23.0.0" }, { name = "msal", specifier = ">=1.32.3" }, + { name = "opentelemetry-instrumentation-fastapi", specifier = "==0.59b0" }, { name = "peewee", specifier = ">=3.17.1" }, { name = "psycopg2-binary", specifier = ">=2.9.9" }, { name = "pymongo", specifier = ">=4.7.2" },