From 12d2b9ff5312d4349b53e0052105365e70a222fa Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 22 Nov 2026 16:59:51 -0500 Subject: [PATCH 1/6] Make OpenTelemetry export correct when an endpoint is set. Metrics now honor OTEL_EXPORTER_OTLP_PROTOCOL (grpc or http/protobuf), and the worker's own spans export through a tracer provider built per process. The images install the Redis, httpx, requests, logging and FastAPI instrumentations as pinned dependencies instead of a bootstrap step that could fail silently. JSON logs gain trace_id and span_id inside a span. The chain span gains tenant.id and call.session_id as span attributes only. OpenAI LLM instrumentation, when installed, hides prompt and reply content. Co-Authored-By: Claude Opus 5.5 --- .env.example | 8 +- common/lib/json_log_formatter.py | 31 +++ common/lib/logging_utils.py | 9 + common/lib/metrics.py | 18 +- common/lib/otlp_config.py | 43 ++++ common/lib/span_attributes.py | 49 ++++ common/lib/tracing.py | 99 +++++++- common/logging.conf | 2 +- common/tests/lib/test_tracing.py | 9 + common/tests/test_otel_correlation.py | 237 ++++++++++++++++++ .../test_otel_protocol_and_tracer_init.py | 168 +++++++++++++ conserver/main.py | 27 +- docker/Dockerfile | 6 +- docker/Dockerfile.api | 7 +- docker/Dockerfile.conserver | 7 +- docs/operations/logging.md | 2 +- docs/operations/monitoring.md | 12 +- docs/reference/environment.md | 11 +- pyproject.toml | 7 + scripts/docs/descriptions.yml | 9 +- uv.lock | 121 ++++++++- 21 files changed, 836 insertions(+), 46 deletions(-) create mode 100644 common/lib/json_log_formatter.py create mode 100644 common/lib/otlp_config.py create mode 100644 common/lib/span_attributes.py create mode 100644 common/tests/test_otel_correlation.py create mode 100644 common/tests/test_otel_protocol_and_tracer_init.py 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..4492abef --- /dev/null +++ b/common/lib/json_log_formatter.py @@ -0,0 +1,31 @@ +"""JSON log formatter that carries the active trace and span ids.""" + +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, 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) + if _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..7e23b60e 100644 --- a/common/lib/metrics.py +++ b/common/lib/metrics.py @@ -5,15 +5,19 @@ 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 HTTP_PROTOBUF, http_signal_url, otlp_protocol + 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 +84,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 +108,14 @@ 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), + ) + else: + otlp_exporter = OTLPMetricExporter( + endpoint=OTEL_EXPORTER_OTLP_ENDPOINT, + ) reader = PeriodicExportingMetricReader( exporter=otlp_exporter, @@ -139,6 +148,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 diff --git a/common/lib/otlp_config.py b/common/lib/otlp_config.py new file mode 100644 index 00000000..566e268e --- /dev/null +++ b/common/lib/otlp_config.py @@ -0,0 +1,43 @@ +"""Shared OTLP settings for the metrics and trace exporters.""" + +import logging +import os + +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}" 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..84f2ead8 100644 --- a/common/lib/tracing.py +++ b/common/lib/tracing.py @@ -1,25 +1,102 @@ import logging +import os +import socket + +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 HTTP_PROTOBUF, http_signal_url, otlp_protocol 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 + + +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. + """ + global _tracer_provider, _tracer_provider_pid + pid = os.getpid() + if _tracer_provider_pid == pid: + return _tracer_provider + + _tracer_provider_pid = pid + _tracer_provider = None + + endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") + if not endpoint: + return None + + 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)) + else: + exporter = OTLPSpanExporter(endpoint=endpoint) + provider = TracerProvider(resource=resource) + provider.add_span_processor(BatchSpanProcessor(exporter)) + # TracerProvider registers its own atexit shutdown, which flushes buffered spans on a clean + # exit. Each forked child builds a provider, so each registers its own. + _tracer_provider = provider + logger.info("OpenTelemetry tracing initialized: pid=%d", pid) + except Exception as e: + logger.warning("Failed to initialize OpenTelemetry tracing: %s", e) + return _tracer_provider + + +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(): - """Instrument OpenAI calls with LLM-specific OTEL spans. + """Prepare tracing in this process. - 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. + Builds the per-process tracer provider, 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. """ + 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..37009ff4 --- /dev/null +++ b/common/tests/test_otel_correlation.py @@ -0,0 +1,237 @@ +"""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): + _, 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): + 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) == {} + + +def _run_chain(span_provider, meter_reader, vcon_dict): + import main as main_module + from main import VconChainRequest + + 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 = "0192f0f0-0000-7000-8000-000000000001" + redis_instance = MagicMock() + redis_instance.get_vcon_dict.return_value = vcon_dict + + meter_provider = MeterProvider(metric_readers=[meter_reader]) + import os + + 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", return_value=redis_instance), + 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={}, + ), + ): + VconChainRequest(chain, "0192f0f0-0000-7000-8000-000000000001", context=None).process() + meter_provider.shutdown() + + +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 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..13b7a9fa --- /dev/null +++ b/common/tests/test_otel_protocol_and_tracer_init.py @@ -0,0 +1,168 @@ +"""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") + 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") + 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 diff --git a/conserver/main.py b/conserver/main.py index 6e30e203..f17faab8 100644 --- a/conserver/main.py +++ b/conserver/main.py @@ -36,7 +36,8 @@ 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 +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 storage.base import Storage @@ -243,7 +244,8 @@ def process(self) -> None: """ self._span_context_manager = self._create_span_from_context() self._span = self._span_context_manager.__enter__() - + self._set_correlation_attributes() + vcon_started = time.time() logger.debug( "Started processing vCon %s with chain %s", @@ -296,6 +298,21 @@ def process(self) -> None: except Exception as e: logger.debug(f"Failed to end span: {e}") + def _set_correlation_attributes(self) -> None: + """Put ``tenant.id`` and ``call.session_id`` on the chain span. + + Span attributes only. Never copy them onto a metric: one series per call fills the metrics + store. Skipped when the span is not recording, which saves the Redis read. + """ + try: + if self._span is None or not self._span.is_recording(): + return + vcon_dict = VconRedis().get_vcon_dict(self.vcon_id) + 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 +330,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 +411,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 +577,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={ 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..37fbdfa6 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. 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..bf0353a7 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. 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. 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. Inside a span, each record also has `trace_id` and `span_id`, so a log line can be matched to its trace. Outside a span 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..3ce77ad3 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/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" }, From c9e2ba98a7e2237259a7d9ca7d5759337a7efc63 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 22 Nov 2026 17:13:59 -0500 Subject: [PATCH 2/6] Fix review findings on OpenTelemetry export. Chain span attributes now come from the vCon the link step already loads, only when an export endpoint is set, so there is no extra Redis or storage read. A worker flushes its tracer and meter providers when it returns, including after an error, since a forked worker never runs atexit. The tracer pid marker is set after the build under a lock, log trace ids appear only with an endpoint set, and the multi-worker parent no longer builds a provider its children would carry idle. Co-Authored-By: Claude Opus 5.5 --- common/lib/json_log_formatter.py | 9 +- common/lib/metrics.py | 55 ++++++--- common/lib/tracing.py | 85 ++++++++----- common/tests/test_otel_correlation.py | 113 ++++++++++++++++-- .../test_otel_protocol_and_tracer_init.py | 72 +++++++++++ conserver/main.py | 42 +++++-- docs/operations/logging.md | 2 +- docs/operations/monitoring.md | 6 +- 8 files changed, 308 insertions(+), 76 deletions(-) diff --git a/common/lib/json_log_formatter.py b/common/lib/json_log_formatter.py index 4492abef..373eb27d 100644 --- a/common/lib/json_log_formatter.py +++ b/common/lib/json_log_formatter.py @@ -1,5 +1,7 @@ """JSON log formatter that carries the active trace and span ids.""" +import os + from pythonjsonlogger.jsonlogger import JsonFormatter @@ -15,8 +17,8 @@ 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, or with the - instrumentation off, the two fields are left out and every other field is unchanged. + ``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): @@ -26,6 +28,7 @@ def add_fields(self, log_record, record, message_dict): # The instrumentation's own attributes would otherwise appear as extra keys. for key in ("otelTraceID", "otelSpanID", "otelTraceSampled", "otelServiceName"): log_record.pop(key, None) - if _is_set(trace_id) and _is_set(span_id): + # 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/metrics.py b/common/lib/metrics.py index 7e23b60e..106214b4 100644 --- a/common/lib/metrics.py +++ b/common/lib/metrics.py @@ -53,7 +53,8 @@ def _prepare_attributes(metric_name, attributes): _warned_per_vcon_metrics.add(metric_name) logger.warning( "Dropping per-vCon attribute(s) %s from metric %s: unbounded cardinality", - sorted(dropped), metric_name, + sorted(dropped), + metric_name, ) return {k: v for k, v in attributes.items() if k not in PER_VCON_ATTRIBUTE_KEYS} @@ -102,11 +103,13 @@ def _init_otel_metrics(): # multiple processes in the same pod into one fingerprint. instance_id = f"{host_name}-pid-{current_pid}" - resource = Resource.create({ - "service.name": OTEL_SERVICE_NAME, - "host.name": host_name, - "service.instance.id": instance_id, - }) + resource = Resource.create( + { + "service.name": OTEL_SERVICE_NAME, + "host.name": host_name, + "service.instance.id": instance_id, + } + ) if otlp_protocol("metrics") == HTTP_PROTOBUF: otlp_exporter = OTLPHttpMetricExporter( @@ -175,7 +178,8 @@ def _init_otel_metrics(): _otel_initialized_pid = current_pid logger.info( "OpenTelemetry metrics initialized: pid=%d, instance_id=%s", - current_pid, instance_id, + current_pid, + instance_id, ) except Exception as e: logger.warning("Failed to initialize OpenTelemetry metrics: %s", e) @@ -183,12 +187,27 @@ def _init_otel_metrics(): _otel_initialized_pid = current_pid +def shutdown_meter_provider(): + """Flush and shut down this process's own meter provider (see ``lib.tracing``). + + 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 + if _meter_provider is not None and _otel_initialized_pid == os.getpid(): + try: + _meter_provider.shutdown() + except Exception as e: + logger.warning("Failed to shut down OpenTelemetry metrics: %s", e) + _meter_provider = None + + def increment_counter(metric_name, value=1, attributes=None): """Increment a counter metric in OpenTelemetry. - + Only publishes if OpenTelemetry endpoint is configured. Initializes OpenTelemetry automatically on first call if not already initialized. - + Args: metric_name: Name of the metric value: Counter increment value (default: 1) @@ -196,21 +215,21 @@ def increment_counter(metric_name, value=1, attributes=None): """ # Lazy initialization on first use _init_otel_metrics() - + if not OTEL_EXPORTER_OTLP_ENDPOINT or not meter: return - + try: # Host is already in the resource; per-vCon keys are dropped. attributes = _prepare_attributes(metric_name, attributes) - + # Get or create counter metric if metric_name not in counter_metrics: counter_metrics[metric_name] = meter.create_counter( name=metric_name, description=f"Counter metric for {metric_name}", ) - + # Record the increment counter_metrics[metric_name].add(value, attributes=attributes) except Exception as e: @@ -290,10 +309,10 @@ def register_observable_gauge(metric_name, callback, description=None): def record_histogram(metric_name, value, attributes=None): """Record a value in a histogram metric in OpenTelemetry. - + Only publishes if OpenTelemetry endpoint is configured. Initializes OpenTelemetry automatically on first call if not already initialized. - + Args: metric_name: Name of the metric value: Value to record in the histogram @@ -304,18 +323,18 @@ def record_histogram(metric_name, value, attributes=None): if not OTEL_EXPORTER_OTLP_ENDPOINT or not meter: return - + try: # Host is already in the resource; per-vCon keys are dropped. attributes = _prepare_attributes(metric_name, attributes) - + # Get or create histogram metric if metric_name not in histogram_metrics: histogram_metrics[metric_name] = meter.create_histogram( name=metric_name, description=f"Histogram metric for {metric_name}", ) - + # Record the value histogram_metrics[metric_name].record(value, attributes=attributes) except Exception as e: diff --git a/common/lib/tracing.py b/common/lib/tracing.py index 84f2ead8..3f914d45 100644 --- a/common/lib/tracing.py +++ b/common/lib/tracing.py @@ -1,6 +1,7 @@ import logging import os import socket +import threading from opentelemetry import trace from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter @@ -18,6 +19,7 @@ # 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(): @@ -27,41 +29,62 @@ def init_tracer_provider(): ``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)) + else: + exporter = OTLPSpanExporter(endpoint=endpoint) + provider = TracerProvider(resource=resource) + provider.add_span_processor(BatchSpanProcessor(exporter)) + 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 - _tracer_provider_pid = pid - _tracer_provider = None - endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") - if not endpoint: - return None +def tracing_enabled(): + """True when an export endpoint is configured and this process has its own provider.""" + return init_tracer_provider() is not None - 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)) - else: - exporter = OTLPSpanExporter(endpoint=endpoint) - provider = TracerProvider(resource=resource) - provider.add_span_processor(BatchSpanProcessor(exporter)) - # TracerProvider registers its own atexit shutdown, which flushes buffered spans on a clean - # exit. Each forked child builds a provider, so each registers its own. - _tracer_provider = provider - logger.info("OpenTelemetry tracing initialized: pid=%d", pid) - except Exception as e: - logger.warning("Failed to initialize OpenTelemetry tracing: %s", e) - return _tracer_provider + +def shutdown_tracer_provider(): + """Flush and shut down this process's own provider. + + 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. + """ + global _tracer_provider + if _tracer_provider is not None and _tracer_provider_pid == os.getpid(): + try: + _tracer_provider.shutdown() + except Exception as e: + logger.warning("Failed to shut down OpenTelemetry tracing: %s", e) + _tracer_provider = None def get_tracer(name): @@ -72,15 +95,17 @@ def get_tracer(name): return trace.get_tracer(name) -def init_tracing(): +def init_tracing(build_provider=True): """Prepare tracing in this process. - Builds the per-process tracer provider, then instruments OpenAI through openinference when that + 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. """ - init_tracer_provider() + if build_provider: + init_tracer_provider() try: from openinference.instrumentation import TraceConfig from openinference.instrumentation.openai import OpenAIInstrumentor diff --git a/common/tests/test_otel_correlation.py b/common/tests/test_otel_correlation.py index 37009ff4..6314cfd1 100644 --- a/common/tests/test_otel_correlation.py +++ b/common/tests/test_otel_correlation.py @@ -112,7 +112,8 @@ def _json_logger(name): return log, stream -def test_json_log_record_carries_trace_and_span_ids(span_exporter, log_correlation): +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") @@ -132,7 +133,8 @@ def test_json_log_record_carries_trace_and_span_ids(span_exporter, log_correlati assert not [k for k in record if k.startswith("otel")] -def test_json_log_record_outside_a_span_has_no_ids(log_correlation): +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()) @@ -167,24 +169,35 @@ def test_correlation_attributes_absent_when_not_in_vcon(): assert vcon_correlation_attributes(bad) == {} -def _run_chain(span_provider, meter_reader, vcon_dict): +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 = "0192f0f0-0000-7000-8000-000000000001" - redis_instance = MagicMock() - redis_instance.get_vcon_dict.return_value = vcon_dict + 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]) - import os - 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", return_value=redis_instance), + patch("main.VconRedis", vcon_redis_cls), + patch("main.r", redis_client), patch.multiple( "lib.metrics", meter=meter_provider.get_meter("t"), @@ -195,9 +208,11 @@ def _run_chain(span_provider, meter_reader, vcon_dict): updown_counter_metrics={}, observable_gauges={}, ), + patch("main.tracing_enabled", return_value=tracing_on), ): - VconChainRequest(chain, "0192f0f0-0000-7000-8000-000000000001", context=None).process() + 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): @@ -235,3 +250,81 @@ def test_chain_span_without_tenant_or_tag_omits_both(span_exporter): 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 index 13b7a9fa..b7884bf1 100644 --- a/common/tests/test_otel_protocol_and_tracer_init.py +++ b/common/tests/test_otel_protocol_and_tracer_init.py @@ -166,3 +166,75 @@ def test_get_tracer_uses_process_provider(tracing_module, monkeypatch): 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 --------------------------------------------------- + + +def _forked_worker(url, fail): + """Runs in a forked child, which leaves through os._exit and so never runs atexit hooks.""" + import main + from lib import metrics, tracing + + os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = url + os.environ["OTEL_EXPORTER_OTLP_PROTOCOL"] = "http/protobuf" + tracing._tracer_provider = None + tracing._tracer_provider_pid = None + metrics.OTEL_EXPORTER_OTLP_ENDPOINT = url + metrics._otel_initialized_pid = None + metrics._meter_provider = None + + 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") + + main._worker_loop_inner = body + try: + main.worker_loop(1) + except RuntimeError: + pass + + +@pytest.mark.parametrize("fail", [False, True]) +def test_forked_worker_exports_spans_and_metrics_without_a_manual_flush(fail): + import multiprocessing + + import main # noqa: F401 imported before the fork, as the real parent has + + with _Collector() as collector: + ctx = multiprocessing.get_context("fork") + proc = ctx.Process(target=_forked_worker, args=(collector.url, fail)) + proc.start() + proc.join(timeout=60) + assert proc.exitcode == 0 + assert "/v1/traces" in collector.paths + assert b"child.work" in b"".join(collector.bodies) + assert "/v1/metrics" in collector.paths diff --git a/conserver/main.py b/conserver/main.py index f17faab8..c793f311 100644 --- a/conserver/main.py +++ b/conserver/main.py @@ -36,10 +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, get_tracer +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 @@ -229,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. @@ -244,8 +245,6 @@ def process(self) -> None: """ self._span_context_manager = self._create_span_from_context() self._span = self._span_context_manager.__enter__() - self._set_correlation_attributes() - vcon_started = time.time() logger.debug( "Started processing vCon %s with chain %s", @@ -298,16 +297,19 @@ def process(self) -> None: except Exception as e: logger.debug(f"Failed to end span: {e}") - def _set_correlation_attributes(self) -> None: + def _set_correlation_attributes(self, vcon_dict) -> None: """Put ``tenant.id`` and ``call.session_id`` on the chain span. - Span attributes only. Never copy them onto a metric: one series per call fills the metrics - store. Skipped when the span is not recording, which saves the Redis read. + 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(): + if self._span is None or not self._span.is_recording() or not tracing_enabled(): return - vcon_dict = VconRedis().get_vcon_dict(self.vcon_id) for key, value in vcon_correlation_attributes(vcon_dict).items(): self._span.set_attribute(key, value) except Exception as e: @@ -602,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) @@ -789,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. @@ -968,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/docs/operations/logging.md b/docs/operations/logging.md index 37fbdfa6..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 `TraceJsonFormatter`, a `pythonjsonlogger` subclass. Fields passed through `extra` become top-level keys. A record written inside an OpenTelemetry span also has `trace_id` and `span_id`. +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 bf0353a7..2914a20b 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -64,13 +64,13 @@ The server has two separate OpenTelemetry pipelines. **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`, 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. They are span attributes only and never go on a metric, since one series per call grows without bound. +**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. It follows the same protocol variables, plus `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` and `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`. +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. Inside a span, each record also has `trace_id` and `span_id`, so a log line can be matched to its trace. Outside a span the two fields are absent. +**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. From aef6229534f3c65ce96922ad3eeb492f74974d74 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 22 Nov 2026 17:17:22 -0500 Subject: [PATCH 3/6] Run the forked-worker flush test in a fresh interpreter and refresh the generated environment page. Forking the pytest process after other tests load gRPC crashed the child with SIGSEGV on macOS. The driver now forks from a clean process. Co-Authored-By: Claude Opus 5.5 --- .../test_otel_protocol_and_tracer_init.py | 72 ++++++++++++------- docs/reference/environment.md | 2 +- 2 files changed, 47 insertions(+), 27 deletions(-) diff --git a/common/tests/test_otel_protocol_and_tracer_init.py b/common/tests/test_otel_protocol_and_tracer_init.py index b7884bf1..714865f1 100644 --- a/common/tests/test_otel_protocol_and_tracer_init.py +++ b/common/tests/test_otel_protocol_and_tracer_init.py @@ -196,26 +196,29 @@ def test_init_tracing_can_skip_building_the_provider(tracing_module, monkeypatch # --- a forked worker flushes before it returns --------------------------------------------------- -def _forked_worker(url, fail): - """Runs in a forked child, which leaves through os._exit and so never runs atexit hooks.""" - import main - from lib import metrics, tracing +# 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 - os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = url - os.environ["OTEL_EXPORTER_OTLP_PROTOCOL"] = "http/protobuf" - tracing._tracer_provider = None - tracing._tracer_provider_pid = None - metrics.OTEL_EXPORTER_OTLP_ENDPOINT = url - metrics._otel_initialized_pid = None - metrics._meter_provider = None +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 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) @@ -223,18 +226,35 @@ def body(worker_id): pass -@pytest.mark.parametrize("fail", [False, True]) -def test_forked_worker_exports_spans_and_metrics_without_a_manual_flush(fail): - import multiprocessing +if __name__ == "__main__": + proc = multiprocessing.get_context("fork").Process(target=child) + proc.start() + proc.join(timeout=60) + sys.exit(proc.exitcode) +""" - import main # noqa: F401 imported before the fork, as the real parent has +@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: - ctx = multiprocessing.get_context("fork") - proc = ctx.Process(target=_forked_worker, args=(collector.url, fail)) - proc.start() - proc.join(timeout=60) - assert proc.exitcode == 0 + 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 diff --git a/docs/reference/environment.md b/docs/reference/environment.md index 3ce77ad3..68290678 100644 --- a/docs/reference/environment.md +++ b/docs/reference/environment.md @@ -32,7 +32,7 @@ The code reads 45 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`
`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_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. | From 58932eff6a7fc63d3298b37ed39e6774c227ed59 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 22 Nov 2026 17:54:44 -0500 Subject: [PATCH 4/6] Bound the worker's telemetry shutdown to about five seconds. With the collector down, the SDK defaults held a worker's exit for up to a minute. Exporters get a 2 s timeout, and the tracer and meter shutdowns each run on a daemon thread with a 3 s and 2 s budget. The tracer provider no longer uses the SDK's own atexit hook, which could block for 30 s. Co-Authored-By: Claude Opus 5.5 --- common/lib/ai_usage.py | 19 ++-- common/lib/context_utils.py | 96 ++++++------------- common/lib/error_tracking.py | 4 +- common/lib/metrics.py | 21 ++-- common/lib/openai_client.py | 13 +-- common/lib/otlp_config.py | 33 +++++++ common/lib/queue.py | 10 +- common/lib/queue_metrics.py | 8 +- common/lib/tracing.py | 46 ++++++--- common/lib/vcon_compat.py | 1 - common/lib/vcon_egress_compat.py | 3 +- common/lib/vcon_redis.py | 51 +++++----- .../test_otel_protocol_and_tracer_init.py | 49 +++++++++- 13 files changed, 206 insertions(+), 148 deletions(-) diff --git a/common/lib/ai_usage.py b/common/lib/ai_usage.py index bbf2d7a9..92af550a 100644 --- a/common/lib/ai_usage.py +++ b/common/lib/ai_usage.py @@ -3,14 +3,13 @@ from datetime import datetime, timezone from typing import Optional - logger = init_logger(__name__) def send_ai_usage_data_for_tracking( vcon_uuid: str, - input_units: int, - output_units: int, + input_units: int, + output_units: int, unit_type: str, type: str, send_ai_usage_data_to_url: str, @@ -31,17 +30,15 @@ def send_ai_usage_data_for_tracking( } if send_ai_usage_data_to_url: response = requests.post( - send_ai_usage_data_to_url, - json=data, - headers={"Authorization": f"Bearer {ai_usage_api_token}"}, - timeout=30 + send_ai_usage_data_to_url, json=data, headers={"Authorization": f"Bearer {ai_usage_api_token}"}, timeout=30 ) if response.ok: logger.info(f"AI usage data sent to portal endpoint for tracking: {data}") else: - logger.error(f"Failed to send AI usage data to portal endpoint for tracking: {response.status_code} {response.text}") + logger.error( + f"Failed to send AI usage data to portal endpoint for tracking: {response.status_code} {response.text}" + ) else: logger.info( - "AI usage data not sent to portal endpoint as " - "send_ai_usage_data_to_url is not provided for tracking" - ) \ No newline at end of file + "AI usage data not sent to portal endpoint as " "send_ai_usage_data_to_url is not provided for tracking" + ) diff --git a/common/lib/context_utils.py b/common/lib/context_utils.py index 93ce2522..1fc30727 100644 --- a/common/lib/context_utils.py +++ b/common/lib/context_utils.py @@ -21,11 +21,11 @@ def get_context_key(ingress_list: str, vcon_uuid: str) -> str: """Generate the Redis key for storing context data. - + Args: ingress_list: Name of the ingress list vcon_uuid: UUID of the vCon - + Returns: Redis key string in format: context:{ingress_list}:{vcon_uuid} """ @@ -33,17 +33,14 @@ def get_context_key(ingress_list: str, vcon_uuid: str) -> str: async def store_context_async( - redis_client: RedisAsync, - ingress_list: str, - vcon_uuid: str, - context: Dict[str, Any] + redis_client: RedisAsync, ingress_list: str, vcon_uuid: str, context: Dict[str, Any] ) -> None: """Store context data for a vCon UUID in an ingress list. - + Context data is stored as a list in Redis, allowing multiple context entries for the same vCon UUID (since it can be added multiple times). The list will expire after VCON_CONTEXT_EXPIRY seconds. - + Args: redis_client: Async Redis client ingress_list: Name of the ingress list @@ -53,34 +50,25 @@ async def store_context_async( if not context: logger.debug(f"No context data provided for vCon {vcon_uuid} in ingress list {ingress_list}") return - + try: key = get_context_key(ingress_list, vcon_uuid) context_json = json.dumps(context) await redis_client.rpush(key, context_json) # Set expiration on the list (will apply to all items) await redis_client.expire(key, VCON_CONTEXT_EXPIRY) - logger.debug( - f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}" - ) + logger.debug(f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}") except Exception as e: - logger.warning( - f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" - ) + logger.warning(f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") -def store_context_sync( - redis_client: Redis, - ingress_list: str, - vcon_uuid: str, - context: Dict[str, Any] -) -> None: +def store_context_sync(redis_client: Redis, ingress_list: str, vcon_uuid: str, context: Dict[str, Any]) -> None: """Store context data for a vCon UUID in an ingress list (synchronous version). - + Context data is stored as a list in Redis, allowing multiple context entries for the same vCon UUID (since it can be added multiple times). The list will expire after VCON_CONTEXT_EXPIRY seconds. - + Args: redis_client: Synchronous Redis client ingress_list: Name of the ingress list @@ -90,39 +78,31 @@ def store_context_sync( if not context: logger.debug(f"No context data provided for vCon {vcon_uuid} in ingress list {ingress_list}") return - + try: key = get_context_key(ingress_list, vcon_uuid) context_json = json.dumps(context) redis_client.rpush(key, context_json) # Set expiration on the list (will apply to all items) redis_client.expire(key, VCON_CONTEXT_EXPIRY) - logger.debug( - f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}" - ) + logger.debug(f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}") except Exception as e: - logger.warning( - f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" - ) + logger.warning(f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") -def retrieve_context( - redis_client: Redis, - ingress_list: str, - vcon_uuid: str -) -> Optional[Dict[str, Any]]: +def retrieve_context(redis_client: Redis, ingress_list: str, vcon_uuid: str) -> Optional[Dict[str, Any]]: """Retrieve the oldest context data for a vCon UUID from an ingress list. - + Since the same vCon UUID can be added multiple times, this function retrieves the oldest context entry (leftmost item in the list, which is the first one added) using FIFO queue behavior. The context entry is removed from the list after retrieval. - + Args: redis_client: Synchronous Redis client ingress_list: Name of the ingress list vcon_uuid: UUID of the vCon - + Returns: Dictionary containing context data, or None if no context is found """ @@ -131,34 +111,26 @@ def retrieve_context( # Pop the leftmost (oldest) context entry for FIFO queue behavior context_json = redis_client.lpop(key) if not context_json: - logger.debug( - f"No context found for vCon {vcon_uuid} in ingress list {ingress_list}" - ) + logger.debug(f"No context found for vCon {vcon_uuid} in ingress list {ingress_list}") return None - + context = json.loads(context_json) - logger.debug( - f"Retrieved context for vCon {vcon_uuid} from ingress list {ingress_list}: {context}" - ) + logger.debug(f"Retrieved context for vCon {vcon_uuid} from ingress list {ingress_list}: {context}") return context except json.JSONDecodeError as e: - logger.warning( - f"Failed to parse context JSON for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" - ) + logger.warning(f"Failed to parse context JSON for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") return None except Exception as e: - logger.warning( - f"Failed to retrieve context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" - ) + logger.warning(f"Failed to retrieve context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") return None def extract_otel_trace_context() -> Optional[Dict]: """Extract trace context from OpenTelemetry instrumentation. - + When using opentelemetry-instrument, trace context is automatically available. This function extracts the current span's trace context as a JSON object. - + Returns: Dictionary containing trace context data (trace_id, span_id, trace_flags), or None if not available """ @@ -166,28 +138,22 @@ def extract_otel_trace_context() -> Optional[Dict]: span = trace.get_current_span() if not span: return None - + span_context = span.get_span_context() if not span_context or not span_context.is_valid: return None - + # Format trace_id and span_id as hex strings trace_id = format(span_context.trace_id, '032x') span_id = format(span_context.span_id, '016x') - + # Extract trace_flags (sampled or not) trace_flags = span_context.trace_flags & trace.TraceFlags.SAMPLED is_sampled = bool(trace_flags) - - context = { - "trace_id": trace_id, - "span_id": span_id, - "trace_flags": int(trace_flags), - "is_sampled": is_sampled - } - + + context = {"trace_id": trace_id, "span_id": span_id, "trace_flags": int(trace_flags), "is_sampled": is_sampled} + return context except Exception as e: logger.debug(f"Failed to extract OpenTelemetry trace context: {e}") return None - diff --git a/common/lib/error_tracking.py b/common/lib/error_tracking.py index 2bdce1da..44961f1a 100644 --- a/common/lib/error_tracking.py +++ b/common/lib/error_tracking.py @@ -41,9 +41,7 @@ def init_error_tracker(): try: ext.enrich() except Exception: - logging.getLogger(__name__).exception( - "error_tracking_ext.enrich() raised; continuing without enrichment" - ) + logging.getLogger(__name__).exception("error_tracking_ext.enrich() raised; continuing without enrichment") def capture_exception(e): diff --git a/common/lib/metrics.py b/common/lib/metrics.py index 106214b4..6ba4a16b 100644 --- a/common/lib/metrics.py +++ b/common/lib/metrics.py @@ -10,7 +10,14 @@ from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.resources import Resource -from lib.otlp_config import HTTP_PROTOBUF, http_signal_url, otlp_protocol +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") @@ -114,10 +121,12 @@ def _init_otel_metrics(): 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( @@ -188,18 +197,16 @@ def _init_otel_metrics(): def shutdown_meter_provider(): - """Flush and shut down this process's own meter provider (see ``lib.tracing``). + """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 - if _meter_provider is not None and _otel_initialized_pid == os.getpid(): - try: - _meter_provider.shutdown() - except Exception as e: - logger.warning("Failed to shut down OpenTelemetry metrics: %s", e) + 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): diff --git a/common/lib/openai_client.py b/common/lib/openai_client.py index 569353e3..798d67c3 100644 --- a/common/lib/openai_client.py +++ b/common/lib/openai_client.py @@ -8,6 +8,7 @@ All links and storage that call OpenAI should use get_openai_client(opts) so LLM provider and proxy can be switched in one place. """ + from openai import OpenAI, AzureOpenAI, AsyncOpenAI, AsyncAzureOpenAI from lib.logging_utils import init_logger @@ -66,11 +67,7 @@ def get_openai_client(opts=None, max_retries=0): max_retries=max_retries, ) - openai_api_key = ( - opts.get("OPENAI_API_KEY") - or opts.get("openai_api_key") - or opts.get("api_key") - ) + openai_api_key = opts.get("OPENAI_API_KEY") or opts.get("openai_api_key") or opts.get("api_key") if openai_api_key: logger.info("Using public OpenAI client") organization = opts.get("organization") or opts.get("organization_key") @@ -189,11 +186,7 @@ def get_async_openai_client(opts=None): max_retries=0, ) - openai_api_key = ( - opts.get("OPENAI_API_KEY") - or opts.get("openai_api_key") - or opts.get("api_key") - ) + openai_api_key = opts.get("OPENAI_API_KEY") or opts.get("openai_api_key") or opts.get("api_key") if openai_api_key: logger.info("Using public OpenAI client (async)") return AsyncOpenAI(api_key=openai_api_key, timeout=120.0, max_retries=0) diff --git a/common/lib/otlp_config.py b/common/lib/otlp_config.py index 566e268e..37a2fa97 100644 --- a/common/lib/otlp_config.py +++ b/common/lib/otlp_config.py @@ -2,6 +2,7 @@ import logging import os +import threading logger = logging.getLogger(__name__) @@ -41,3 +42,35 @@ def http_signal_url(signal, base_endpoint): 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/queue.py b/common/lib/queue.py index 6151ed1d..1dac46b3 100644 --- a/common/lib/queue.py +++ b/common/lib/queue.py @@ -128,7 +128,11 @@ def enqueue_storage_dlq(self, storage_name: str, vcon_id: str, retention_seconds end return redis.call('RPUSH', KEYS[2], ARGV[1]) """, - 2, _vcon_key(vcon_id), dlq_name, vcon_id, retention_seconds, + 2, + _vcon_key(vcon_id), + dlq_name, + vcon_id, + retention_seconds, ) if result == -1: raise ValueError(f"Cannot dead-letter missing vCon body: {vcon_id}") @@ -146,9 +150,7 @@ def set_vcon_ttl(self, vcon_id: str, seconds: int) -> bool: # ---- Async queue ops ------------------------------------------- - async def enqueue_async( - self, redis_async, list_name: str, *vcon_ids: str - ) -> int: + async def enqueue_async(self, redis_async, list_name: str, *vcon_ids: str) -> int: """Async RPUSH one or more vCon ids onto the tail of a queue. Accepts ``*vcon_ids`` so batched ingestion paths (e.g., the diff --git a/common/lib/queue_metrics.py b/common/lib/queue_metrics.py index 1483767f..1b603585 100644 --- a/common/lib/queue_metrics.py +++ b/common/lib/queue_metrics.py @@ -69,7 +69,10 @@ def _callback(): except Exception as e: logger.warning( "LLEN failed for %s (ingress_list=%s, kind=%s): %s", - key, ingress_list, kind, e, + key, + ingress_list, + kind, + e, ) continue observations.append( @@ -151,7 +154,6 @@ def register_redis_memory_gauge(client): metric_name="conserver.redis.memory_used_bytes", callback=_build_redis_memory_callback(client), description=( - "Current Redis memory usage in bytes (used_memory from INFO memory). " - "One series per conserver pod." + "Current Redis memory usage in bytes (used_memory from INFO memory). " "One series per conserver pod." ), ) diff --git a/common/lib/tracing.py b/common/lib/tracing.py index 3f914d45..9c0b981a 100644 --- a/common/lib/tracing.py +++ b/common/lib/tracing.py @@ -1,3 +1,4 @@ +import atexit import logging import os import socket @@ -10,7 +11,14 @@ from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -from lib.otlp_config import HTTP_PROTOBUF, http_signal_url, otlp_protocol +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__) @@ -53,11 +61,16 @@ def init_tracer_provider(): } ) if otlp_protocol("traces") == HTTP_PROTOBUF: - exporter = OTLPHttpSpanExporter(endpoint=http_signal_url("traces", endpoint)) + exporter = OTLPHttpSpanExporter( + endpoint=http_signal_url("traces", endpoint), timeout=EXPORT_TIMEOUT_S + ) else: - exporter = OTLPSpanExporter(endpoint=endpoint) - provider = TracerProvider(resource=resource) - provider.add_span_processor(BatchSpanProcessor(exporter)) + 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 @@ -72,19 +85,28 @@ def tracing_enabled(): return init_tracer_provider() is not None +_atexit_registered = False + + +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. + """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. + 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 - if _tracer_provider is not None and _tracer_provider_pid == os.getpid(): - try: - _tracer_provider.shutdown() - except Exception as e: - logger.warning("Failed to shut down OpenTelemetry tracing: %s", e) + 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): diff --git a/common/lib/vcon_compat.py b/common/lib/vcon_compat.py index 75cdbfea..a12f7846 100644 --- a/common/lib/vcon_compat.py +++ b/common/lib/vcon_compat.py @@ -32,7 +32,6 @@ from typing import Any, Dict, List - _TOP_LEVEL_RENAMES = { "appended": "amended", "must_support": "critical", diff --git a/common/lib/vcon_egress_compat.py b/common/lib/vcon_egress_compat.py index 34b3b79b..4520d8a4 100644 --- a/common/lib/vcon_egress_compat.py +++ b/common/lib/vcon_egress_compat.py @@ -119,8 +119,7 @@ def to_legacy(vcon_dict: Dict[str, Any], target_version: str) -> Dict[str, Any]: """ if target_version not in SUPPORTED_VERSIONS: raise ValueError( - f"Unsupported egress_format_version {target_version!r}; " - f"supported: {sorted(SUPPORTED_VERSIONS)}" + f"Unsupported egress_format_version {target_version!r}; " f"supported: {sorted(SUPPORTED_VERSIONS)}" ) if not isinstance(vcon_dict, dict): return vcon_dict diff --git a/common/lib/vcon_redis.py b/common/lib/vcon_redis.py index 997aba26..23309172 100644 --- a/common/lib/vcon_redis.py +++ b/common/lib/vcon_redis.py @@ -31,7 +31,7 @@ class VconRedis: Attributes: DEFAULT_TTL: Default TTL in seconds from VCON_REDIS_EXPIRY setting (3600s). """ - + DEFAULT_TTL = VCON_REDIS_EXPIRY @staticmethod @@ -128,13 +128,16 @@ def _load_from_storage(vcon_id: str) -> Optional[dict]: except Exception as e: logger.warning( "Storage fallback %s raised while loading vCon %s: %s", - storage_name, vcon_id, e, + storage_name, + vcon_id, + e, ) continue if vcon_dict: logger.info( "vCon %s missed Redis but recovered from storage %s", - vcon_id, storage_name, + vcon_id, + storage_name, ) return vcon_dict return None @@ -162,7 +165,9 @@ def _cache_back_to_redis(self, vcon_id: str, vcon_dict: dict) -> None: except (ValueError, TypeError) as e: logger.debug( "Skipping sorted-set add for vCon %s (created_at=%r): %s", - vcon_id, created_at, e, + vcon_id, + created_at, + e, ) def get_vcon(self, vcon_id: str) -> Optional[vcon.Vcon]: @@ -182,7 +187,7 @@ def get_vcon(self, vcon_id: str) -> Optional[vcon.Vcon]: def store_vcon_dict(self, vcon_dict: dict, ttl: Optional[int] = None) -> None: """Stores a vcon dictionary into redis with optional TTL. - + Args: vcon_dict (dict): The vCon as a dictionary to store. ttl (Optional[int]): Time-to-live in seconds. If None, existing expiry is retained; new keys are persistent. @@ -225,11 +230,11 @@ def get_vcon_dict(self, vcon_id: str) -> Optional[dict]: def set_expiry(self, vcon_id: str, ttl: int) -> bool: """Sets or updates the TTL on an existing vCon. - + Args: vcon_id (str): The vCon UUID. ttl (int): Time-to-live in seconds. - + Returns: bool: True if the expiry was set, False if the key doesn't exist. """ @@ -241,10 +246,10 @@ def set_expiry(self, vcon_id: str, ttl: int) -> bool: def get_ttl(self, vcon_id: str) -> int: """Gets the remaining TTL on a vCon. - + Args: vcon_id (str): The vCon UUID. - + Returns: int: Remaining TTL in seconds, -1 if no expiry is set, -2 if the key doesn't exist. @@ -254,10 +259,10 @@ def get_ttl(self, vcon_id: str) -> int: def remove_expiry(self, vcon_id: str) -> bool: """Removes the TTL from a vCon, making it persistent. - + Args: vcon_id (str): The vCon UUID. - + Returns: bool: True if the expiry was removed, False if the key doesn't exist or had no expiry. @@ -268,12 +273,7 @@ def remove_expiry(self, vcon_id: str) -> bool: logger.debug(f"Removed TTL from vCon {vcon_id}") return bool(result) - async def store_vcon_async( - self, - redis_async, - vCon: vcon.Vcon, - ttl: Optional[int] = None - ) -> None: + async def store_vcon_async(self, redis_async, vCon: vcon.Vcon, ttl: Optional[int] = None) -> None: """Asynchronously stores the vcon into redis with optional TTL. Args: @@ -288,14 +288,9 @@ async def store_vcon_async( if ttl is not None: logger.debug(f"Set TTL of {ttl}s on vCon {vCon.uuid}") - async def store_vcon_dict_async( - self, - redis_async, - vcon_dict: dict, - ttl: Optional[int] = None - ) -> None: + async def store_vcon_dict_async(self, redis_async, vcon_dict: dict, ttl: Optional[int] = None) -> None: """Asynchronously stores a vcon dictionary into redis with optional TTL. - + Args: redis_async: Async Redis client instance. vcon_dict (dict): The vCon as a dictionary to store. @@ -310,12 +305,12 @@ async def store_vcon_dict_async( async def set_expiry_async(self, redis_async, vcon_id: str, ttl: int) -> bool: """Asynchronously sets or updates the TTL on an existing vCon. - + Args: redis_async: Async Redis client instance. vcon_id (str): The vCon UUID. ttl (int): Time-to-live in seconds. - + Returns: bool: True if the expiry was set, False if the key doesn't exist. """ @@ -327,11 +322,11 @@ async def set_expiry_async(self, redis_async, vcon_id: str, ttl: int) -> bool: async def get_ttl_async(self, redis_async, vcon_id: str) -> int: """Asynchronously gets the remaining TTL on a vCon. - + Args: redis_async: Async Redis client instance. vcon_id (str): The vCon UUID. - + Returns: int: Remaining TTL in seconds, -1 if no expiry is set, -2 if the key doesn't exist. diff --git a/common/tests/test_otel_protocol_and_tracer_init.py b/common/tests/test_otel_protocol_and_tracer_init.py index 714865f1..09827996 100644 --- a/common/tests/test_otel_protocol_and_tracer_init.py +++ b/common/tests/test_otel_protocol_and_tracer_init.py @@ -94,7 +94,7 @@ def test_metrics_default_protocol_is_grpc(monkeypatch): patch.object(metrics, "OTEL_EXPORTER_OTLP_ENDPOINT", "http://fake:4317"), ): metrics._init_otel_metrics() - grpc_exp.assert_called_once_with(endpoint="http://fake:4317") + grpc_exp.assert_called_once_with(endpoint="http://fake:4317", timeout=2) assert not http_exp.called finally: _reset_metrics(metrics) @@ -137,7 +137,7 @@ def test_tracer_provider_exports_over_http_protobuf(tracing_module, monkeypatch) patch("lib.tracing.BatchSpanProcessor"), ): tracing_module.init_tracer_provider() - http_exp.assert_called_once_with(endpoint="http://collector:4318/v1/traces") + http_exp.assert_called_once_with(endpoint="http://collector:4318/v1/traces", timeout=2) assert not grpc_exp.called @@ -258,3 +258,48 @@ def test_forked_worker_exports_spans_and_metrics_without_a_manual_flush(fail, tm 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" From 3e598e493d8a0a9b83ed7ed95f0efee77ebeba37 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 22 Nov 2026 18:07:51 -0500 Subject: [PATCH 5/6] Restore nine files that only picked up formatting changes. Co-Authored-By: Claude Opus 5.5 --- common/lib/ai_usage.py | 19 ++++--- common/lib/context_utils.py | 96 +++++++++++++++++++++----------- common/lib/error_tracking.py | 4 +- common/lib/openai_client.py | 13 ++++- common/lib/queue.py | 10 ++-- common/lib/queue_metrics.py | 8 +-- common/lib/vcon_compat.py | 1 + common/lib/vcon_egress_compat.py | 3 +- common/lib/vcon_redis.py | 51 +++++++++-------- 9 files changed, 127 insertions(+), 78 deletions(-) diff --git a/common/lib/ai_usage.py b/common/lib/ai_usage.py index 92af550a..bbf2d7a9 100644 --- a/common/lib/ai_usage.py +++ b/common/lib/ai_usage.py @@ -3,13 +3,14 @@ from datetime import datetime, timezone from typing import Optional + logger = init_logger(__name__) def send_ai_usage_data_for_tracking( vcon_uuid: str, - input_units: int, - output_units: int, + input_units: int, + output_units: int, unit_type: str, type: str, send_ai_usage_data_to_url: str, @@ -30,15 +31,17 @@ def send_ai_usage_data_for_tracking( } if send_ai_usage_data_to_url: response = requests.post( - send_ai_usage_data_to_url, json=data, headers={"Authorization": f"Bearer {ai_usage_api_token}"}, timeout=30 + send_ai_usage_data_to_url, + json=data, + headers={"Authorization": f"Bearer {ai_usage_api_token}"}, + timeout=30 ) if response.ok: logger.info(f"AI usage data sent to portal endpoint for tracking: {data}") else: - logger.error( - f"Failed to send AI usage data to portal endpoint for tracking: {response.status_code} {response.text}" - ) + logger.error(f"Failed to send AI usage data to portal endpoint for tracking: {response.status_code} {response.text}") else: logger.info( - "AI usage data not sent to portal endpoint as " "send_ai_usage_data_to_url is not provided for tracking" - ) + "AI usage data not sent to portal endpoint as " + "send_ai_usage_data_to_url is not provided for tracking" + ) \ No newline at end of file diff --git a/common/lib/context_utils.py b/common/lib/context_utils.py index 1fc30727..93ce2522 100644 --- a/common/lib/context_utils.py +++ b/common/lib/context_utils.py @@ -21,11 +21,11 @@ def get_context_key(ingress_list: str, vcon_uuid: str) -> str: """Generate the Redis key for storing context data. - + Args: ingress_list: Name of the ingress list vcon_uuid: UUID of the vCon - + Returns: Redis key string in format: context:{ingress_list}:{vcon_uuid} """ @@ -33,14 +33,17 @@ def get_context_key(ingress_list: str, vcon_uuid: str) -> str: async def store_context_async( - redis_client: RedisAsync, ingress_list: str, vcon_uuid: str, context: Dict[str, Any] + redis_client: RedisAsync, + ingress_list: str, + vcon_uuid: str, + context: Dict[str, Any] ) -> None: """Store context data for a vCon UUID in an ingress list. - + Context data is stored as a list in Redis, allowing multiple context entries for the same vCon UUID (since it can be added multiple times). The list will expire after VCON_CONTEXT_EXPIRY seconds. - + Args: redis_client: Async Redis client ingress_list: Name of the ingress list @@ -50,25 +53,34 @@ async def store_context_async( if not context: logger.debug(f"No context data provided for vCon {vcon_uuid} in ingress list {ingress_list}") return - + try: key = get_context_key(ingress_list, vcon_uuid) context_json = json.dumps(context) await redis_client.rpush(key, context_json) # Set expiration on the list (will apply to all items) await redis_client.expire(key, VCON_CONTEXT_EXPIRY) - logger.debug(f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}") + logger.debug( + f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}" + ) except Exception as e: - logger.warning(f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") + logger.warning( + f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" + ) -def store_context_sync(redis_client: Redis, ingress_list: str, vcon_uuid: str, context: Dict[str, Any]) -> None: +def store_context_sync( + redis_client: Redis, + ingress_list: str, + vcon_uuid: str, + context: Dict[str, Any] +) -> None: """Store context data for a vCon UUID in an ingress list (synchronous version). - + Context data is stored as a list in Redis, allowing multiple context entries for the same vCon UUID (since it can be added multiple times). The list will expire after VCON_CONTEXT_EXPIRY seconds. - + Args: redis_client: Synchronous Redis client ingress_list: Name of the ingress list @@ -78,31 +90,39 @@ def store_context_sync(redis_client: Redis, ingress_list: str, vcon_uuid: str, c if not context: logger.debug(f"No context data provided for vCon {vcon_uuid} in ingress list {ingress_list}") return - + try: key = get_context_key(ingress_list, vcon_uuid) context_json = json.dumps(context) redis_client.rpush(key, context_json) # Set expiration on the list (will apply to all items) redis_client.expire(key, VCON_CONTEXT_EXPIRY) - logger.debug(f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}") + logger.debug( + f"Stored context for vCon {vcon_uuid} in ingress list {ingress_list}: {context}" + ) except Exception as e: - logger.warning(f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") + logger.warning( + f"Failed to store context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" + ) -def retrieve_context(redis_client: Redis, ingress_list: str, vcon_uuid: str) -> Optional[Dict[str, Any]]: +def retrieve_context( + redis_client: Redis, + ingress_list: str, + vcon_uuid: str +) -> Optional[Dict[str, Any]]: """Retrieve the oldest context data for a vCon UUID from an ingress list. - + Since the same vCon UUID can be added multiple times, this function retrieves the oldest context entry (leftmost item in the list, which is the first one added) using FIFO queue behavior. The context entry is removed from the list after retrieval. - + Args: redis_client: Synchronous Redis client ingress_list: Name of the ingress list vcon_uuid: UUID of the vCon - + Returns: Dictionary containing context data, or None if no context is found """ @@ -111,26 +131,34 @@ def retrieve_context(redis_client: Redis, ingress_list: str, vcon_uuid: str) -> # Pop the leftmost (oldest) context entry for FIFO queue behavior context_json = redis_client.lpop(key) if not context_json: - logger.debug(f"No context found for vCon {vcon_uuid} in ingress list {ingress_list}") + logger.debug( + f"No context found for vCon {vcon_uuid} in ingress list {ingress_list}" + ) return None - + context = json.loads(context_json) - logger.debug(f"Retrieved context for vCon {vcon_uuid} from ingress list {ingress_list}: {context}") + logger.debug( + f"Retrieved context for vCon {vcon_uuid} from ingress list {ingress_list}: {context}" + ) return context except json.JSONDecodeError as e: - logger.warning(f"Failed to parse context JSON for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") + logger.warning( + f"Failed to parse context JSON for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" + ) return None except Exception as e: - logger.warning(f"Failed to retrieve context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}") + logger.warning( + f"Failed to retrieve context for vCon {vcon_uuid} in ingress list {ingress_list}: {e}" + ) return None def extract_otel_trace_context() -> Optional[Dict]: """Extract trace context from OpenTelemetry instrumentation. - + When using opentelemetry-instrument, trace context is automatically available. This function extracts the current span's trace context as a JSON object. - + Returns: Dictionary containing trace context data (trace_id, span_id, trace_flags), or None if not available """ @@ -138,22 +166,28 @@ def extract_otel_trace_context() -> Optional[Dict]: span = trace.get_current_span() if not span: return None - + span_context = span.get_span_context() if not span_context or not span_context.is_valid: return None - + # Format trace_id and span_id as hex strings trace_id = format(span_context.trace_id, '032x') span_id = format(span_context.span_id, '016x') - + # Extract trace_flags (sampled or not) trace_flags = span_context.trace_flags & trace.TraceFlags.SAMPLED is_sampled = bool(trace_flags) - - context = {"trace_id": trace_id, "span_id": span_id, "trace_flags": int(trace_flags), "is_sampled": is_sampled} - + + context = { + "trace_id": trace_id, + "span_id": span_id, + "trace_flags": int(trace_flags), + "is_sampled": is_sampled + } + return context except Exception as e: logger.debug(f"Failed to extract OpenTelemetry trace context: {e}") return None + diff --git a/common/lib/error_tracking.py b/common/lib/error_tracking.py index 44961f1a..2bdce1da 100644 --- a/common/lib/error_tracking.py +++ b/common/lib/error_tracking.py @@ -41,7 +41,9 @@ def init_error_tracker(): try: ext.enrich() except Exception: - logging.getLogger(__name__).exception("error_tracking_ext.enrich() raised; continuing without enrichment") + logging.getLogger(__name__).exception( + "error_tracking_ext.enrich() raised; continuing without enrichment" + ) def capture_exception(e): diff --git a/common/lib/openai_client.py b/common/lib/openai_client.py index 798d67c3..569353e3 100644 --- a/common/lib/openai_client.py +++ b/common/lib/openai_client.py @@ -8,7 +8,6 @@ All links and storage that call OpenAI should use get_openai_client(opts) so LLM provider and proxy can be switched in one place. """ - from openai import OpenAI, AzureOpenAI, AsyncOpenAI, AsyncAzureOpenAI from lib.logging_utils import init_logger @@ -67,7 +66,11 @@ def get_openai_client(opts=None, max_retries=0): max_retries=max_retries, ) - openai_api_key = opts.get("OPENAI_API_KEY") or opts.get("openai_api_key") or opts.get("api_key") + openai_api_key = ( + opts.get("OPENAI_API_KEY") + or opts.get("openai_api_key") + or opts.get("api_key") + ) if openai_api_key: logger.info("Using public OpenAI client") organization = opts.get("organization") or opts.get("organization_key") @@ -186,7 +189,11 @@ def get_async_openai_client(opts=None): max_retries=0, ) - openai_api_key = opts.get("OPENAI_API_KEY") or opts.get("openai_api_key") or opts.get("api_key") + openai_api_key = ( + opts.get("OPENAI_API_KEY") + or opts.get("openai_api_key") + or opts.get("api_key") + ) if openai_api_key: logger.info("Using public OpenAI client (async)") return AsyncOpenAI(api_key=openai_api_key, timeout=120.0, max_retries=0) diff --git a/common/lib/queue.py b/common/lib/queue.py index 1dac46b3..6151ed1d 100644 --- a/common/lib/queue.py +++ b/common/lib/queue.py @@ -128,11 +128,7 @@ def enqueue_storage_dlq(self, storage_name: str, vcon_id: str, retention_seconds end return redis.call('RPUSH', KEYS[2], ARGV[1]) """, - 2, - _vcon_key(vcon_id), - dlq_name, - vcon_id, - retention_seconds, + 2, _vcon_key(vcon_id), dlq_name, vcon_id, retention_seconds, ) if result == -1: raise ValueError(f"Cannot dead-letter missing vCon body: {vcon_id}") @@ -150,7 +146,9 @@ def set_vcon_ttl(self, vcon_id: str, seconds: int) -> bool: # ---- Async queue ops ------------------------------------------- - async def enqueue_async(self, redis_async, list_name: str, *vcon_ids: str) -> int: + async def enqueue_async( + self, redis_async, list_name: str, *vcon_ids: str + ) -> int: """Async RPUSH one or more vCon ids onto the tail of a queue. Accepts ``*vcon_ids`` so batched ingestion paths (e.g., the diff --git a/common/lib/queue_metrics.py b/common/lib/queue_metrics.py index 1b603585..1483767f 100644 --- a/common/lib/queue_metrics.py +++ b/common/lib/queue_metrics.py @@ -69,10 +69,7 @@ def _callback(): except Exception as e: logger.warning( "LLEN failed for %s (ingress_list=%s, kind=%s): %s", - key, - ingress_list, - kind, - e, + key, ingress_list, kind, e, ) continue observations.append( @@ -154,6 +151,7 @@ def register_redis_memory_gauge(client): metric_name="conserver.redis.memory_used_bytes", callback=_build_redis_memory_callback(client), description=( - "Current Redis memory usage in bytes (used_memory from INFO memory). " "One series per conserver pod." + "Current Redis memory usage in bytes (used_memory from INFO memory). " + "One series per conserver pod." ), ) diff --git a/common/lib/vcon_compat.py b/common/lib/vcon_compat.py index a12f7846..75cdbfea 100644 --- a/common/lib/vcon_compat.py +++ b/common/lib/vcon_compat.py @@ -32,6 +32,7 @@ from typing import Any, Dict, List + _TOP_LEVEL_RENAMES = { "appended": "amended", "must_support": "critical", diff --git a/common/lib/vcon_egress_compat.py b/common/lib/vcon_egress_compat.py index 4520d8a4..34b3b79b 100644 --- a/common/lib/vcon_egress_compat.py +++ b/common/lib/vcon_egress_compat.py @@ -119,7 +119,8 @@ def to_legacy(vcon_dict: Dict[str, Any], target_version: str) -> Dict[str, Any]: """ if target_version not in SUPPORTED_VERSIONS: raise ValueError( - f"Unsupported egress_format_version {target_version!r}; " f"supported: {sorted(SUPPORTED_VERSIONS)}" + f"Unsupported egress_format_version {target_version!r}; " + f"supported: {sorted(SUPPORTED_VERSIONS)}" ) if not isinstance(vcon_dict, dict): return vcon_dict diff --git a/common/lib/vcon_redis.py b/common/lib/vcon_redis.py index 23309172..997aba26 100644 --- a/common/lib/vcon_redis.py +++ b/common/lib/vcon_redis.py @@ -31,7 +31,7 @@ class VconRedis: Attributes: DEFAULT_TTL: Default TTL in seconds from VCON_REDIS_EXPIRY setting (3600s). """ - + DEFAULT_TTL = VCON_REDIS_EXPIRY @staticmethod @@ -128,16 +128,13 @@ def _load_from_storage(vcon_id: str) -> Optional[dict]: except Exception as e: logger.warning( "Storage fallback %s raised while loading vCon %s: %s", - storage_name, - vcon_id, - e, + storage_name, vcon_id, e, ) continue if vcon_dict: logger.info( "vCon %s missed Redis but recovered from storage %s", - vcon_id, - storage_name, + vcon_id, storage_name, ) return vcon_dict return None @@ -165,9 +162,7 @@ def _cache_back_to_redis(self, vcon_id: str, vcon_dict: dict) -> None: except (ValueError, TypeError) as e: logger.debug( "Skipping sorted-set add for vCon %s (created_at=%r): %s", - vcon_id, - created_at, - e, + vcon_id, created_at, e, ) def get_vcon(self, vcon_id: str) -> Optional[vcon.Vcon]: @@ -187,7 +182,7 @@ def get_vcon(self, vcon_id: str) -> Optional[vcon.Vcon]: def store_vcon_dict(self, vcon_dict: dict, ttl: Optional[int] = None) -> None: """Stores a vcon dictionary into redis with optional TTL. - + Args: vcon_dict (dict): The vCon as a dictionary to store. ttl (Optional[int]): Time-to-live in seconds. If None, existing expiry is retained; new keys are persistent. @@ -230,11 +225,11 @@ def get_vcon_dict(self, vcon_id: str) -> Optional[dict]: def set_expiry(self, vcon_id: str, ttl: int) -> bool: """Sets or updates the TTL on an existing vCon. - + Args: vcon_id (str): The vCon UUID. ttl (int): Time-to-live in seconds. - + Returns: bool: True if the expiry was set, False if the key doesn't exist. """ @@ -246,10 +241,10 @@ def set_expiry(self, vcon_id: str, ttl: int) -> bool: def get_ttl(self, vcon_id: str) -> int: """Gets the remaining TTL on a vCon. - + Args: vcon_id (str): The vCon UUID. - + Returns: int: Remaining TTL in seconds, -1 if no expiry is set, -2 if the key doesn't exist. @@ -259,10 +254,10 @@ def get_ttl(self, vcon_id: str) -> int: def remove_expiry(self, vcon_id: str) -> bool: """Removes the TTL from a vCon, making it persistent. - + Args: vcon_id (str): The vCon UUID. - + Returns: bool: True if the expiry was removed, False if the key doesn't exist or had no expiry. @@ -273,7 +268,12 @@ def remove_expiry(self, vcon_id: str) -> bool: logger.debug(f"Removed TTL from vCon {vcon_id}") return bool(result) - async def store_vcon_async(self, redis_async, vCon: vcon.Vcon, ttl: Optional[int] = None) -> None: + async def store_vcon_async( + self, + redis_async, + vCon: vcon.Vcon, + ttl: Optional[int] = None + ) -> None: """Asynchronously stores the vcon into redis with optional TTL. Args: @@ -288,9 +288,14 @@ async def store_vcon_async(self, redis_async, vCon: vcon.Vcon, ttl: Optional[int if ttl is not None: logger.debug(f"Set TTL of {ttl}s on vCon {vCon.uuid}") - async def store_vcon_dict_async(self, redis_async, vcon_dict: dict, ttl: Optional[int] = None) -> None: + async def store_vcon_dict_async( + self, + redis_async, + vcon_dict: dict, + ttl: Optional[int] = None + ) -> None: """Asynchronously stores a vcon dictionary into redis with optional TTL. - + Args: redis_async: Async Redis client instance. vcon_dict (dict): The vCon as a dictionary to store. @@ -305,12 +310,12 @@ async def store_vcon_dict_async(self, redis_async, vcon_dict: dict, ttl: Optiona async def set_expiry_async(self, redis_async, vcon_id: str, ttl: int) -> bool: """Asynchronously sets or updates the TTL on an existing vCon. - + Args: redis_async: Async Redis client instance. vcon_id (str): The vCon UUID. ttl (int): Time-to-live in seconds. - + Returns: bool: True if the expiry was set, False if the key doesn't exist. """ @@ -322,11 +327,11 @@ async def set_expiry_async(self, redis_async, vcon_id: str, ttl: int) -> bool: async def get_ttl_async(self, redis_async, vcon_id: str) -> int: """Asynchronously gets the remaining TTL on a vCon. - + Args: redis_async: Async Redis client instance. vcon_id (str): The vCon UUID. - + Returns: int: Remaining TTL in seconds, -1 if no expiry is set, -2 if the key doesn't exist. From bd2d1a5b420e45d3b875a56cd5dd5ce8af9e2a50 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 22 Nov 2026 18:09:32 -0500 Subject: [PATCH 6/6] Keep only the real changes in metrics.py. Co-Authored-By: Claude Opus 5.5 --- common/lib/metrics.py | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/common/lib/metrics.py b/common/lib/metrics.py index 6ba4a16b..3258f9c3 100644 --- a/common/lib/metrics.py +++ b/common/lib/metrics.py @@ -60,8 +60,7 @@ def _prepare_attributes(metric_name, attributes): _warned_per_vcon_metrics.add(metric_name) logger.warning( "Dropping per-vCon attribute(s) %s from metric %s: unbounded cardinality", - sorted(dropped), - metric_name, + sorted(dropped), metric_name, ) return {k: v for k, v in attributes.items() if k not in PER_VCON_ATTRIBUTE_KEYS} @@ -110,13 +109,11 @@ def _init_otel_metrics(): # multiple processes in the same pod into one fingerprint. instance_id = f"{host_name}-pid-{current_pid}" - resource = Resource.create( - { - "service.name": OTEL_SERVICE_NAME, - "host.name": host_name, - "service.instance.id": instance_id, - } - ) + resource = Resource.create({ + "service.name": OTEL_SERVICE_NAME, + "host.name": host_name, + "service.instance.id": instance_id, + }) if otlp_protocol("metrics") == HTTP_PROTOBUF: otlp_exporter = OTLPHttpMetricExporter( @@ -187,8 +184,7 @@ def _init_otel_metrics(): _otel_initialized_pid = current_pid logger.info( "OpenTelemetry metrics initialized: pid=%d, instance_id=%s", - current_pid, - instance_id, + current_pid, instance_id, ) except Exception as e: logger.warning("Failed to initialize OpenTelemetry metrics: %s", e) @@ -211,10 +207,10 @@ def shutdown_meter_provider(): def increment_counter(metric_name, value=1, attributes=None): """Increment a counter metric in OpenTelemetry. - + Only publishes if OpenTelemetry endpoint is configured. Initializes OpenTelemetry automatically on first call if not already initialized. - + Args: metric_name: Name of the metric value: Counter increment value (default: 1) @@ -222,21 +218,21 @@ def increment_counter(metric_name, value=1, attributes=None): """ # Lazy initialization on first use _init_otel_metrics() - + if not OTEL_EXPORTER_OTLP_ENDPOINT or not meter: return - + try: # Host is already in the resource; per-vCon keys are dropped. attributes = _prepare_attributes(metric_name, attributes) - + # Get or create counter metric if metric_name not in counter_metrics: counter_metrics[metric_name] = meter.create_counter( name=metric_name, description=f"Counter metric for {metric_name}", ) - + # Record the increment counter_metrics[metric_name].add(value, attributes=attributes) except Exception as e: @@ -316,10 +312,10 @@ def register_observable_gauge(metric_name, callback, description=None): def record_histogram(metric_name, value, attributes=None): """Record a value in a histogram metric in OpenTelemetry. - + Only publishes if OpenTelemetry endpoint is configured. Initializes OpenTelemetry automatically on first call if not already initialized. - + Args: metric_name: Name of the metric value: Value to record in the histogram @@ -330,18 +326,18 @@ def record_histogram(metric_name, value, attributes=None): if not OTEL_EXPORTER_OTLP_ENDPOINT or not meter: return - + try: # Host is already in the resource; per-vCon keys are dropped. attributes = _prepare_attributes(metric_name, attributes) - + # Get or create histogram metric if metric_name not in histogram_metrics: histogram_metrics[metric_name] = meter.create_histogram( name=metric_name, description=f"Histogram metric for {metric_name}", ) - + # Record the value histogram_metrics[metric_name].record(value, attributes=attributes) except Exception as e: