← Back to Pull requests

feat: OpenTelemetry foundation (#338 Phrase 1 of #279) #341

Closed
unknown closed this pull request without merging on Sep 19, 2026 18:05 UTC
View on GitHub
unknown unknown commented on Sep 18, 2026 22:17 UTC
Author

Fix #338
Part of #279 — phase 1 of the three-phase sequence proposed on that issue (foundation → execution traces → metrics).

Summary

Adds an opt-in OpenTelemetry foundation to the agentic-server binary. With nothing selected the gateway creates no provider, exporter thread, or network connection and logs exactly as before. When enabled it exports OTLP over HTTP/protobuf, bridges tracing spans to OpenTelemetry, and correlates local log lines with the exported trace.

  • *Typed OTEL_ configuration (telemetry/config.rs): OTEL_SDK_DISABLED, OTEL_{TRACES,METRICS}_EXPORTER (none | otlp, default none — a documented deviation from the spec default so telemetry stays opt-in), OTEL_EXPORTER_OTLP_PROTOCOL (+ per-signal), OTEL_SERVICE_NAME. Invalid values are startup errors; grpc is rejected with a message naming the reason (the gRPC exporter needs tonic 0.14, rust-version 1.88, above the MSRV). Endpoint/headers/timeout/sampler/batch settings are read by the SDK and exporter directly with the standard precedence. The parser takes a lookup function so tests never touch the process environment (std::env::set_var is unsafe in edition 2024).

  • Provider lifecycle* (telemetry/lifecycle.rs): providers are built before the Tokio runtime and owned by main. After server::run returns on any exit path, main first stops the runtime (shutdown_timeout(1 s)) — dropping any connection task the gateway drain abandoned, which finalizes its span and metrics while the providers still accept them — and only then shuts the providers down from a plain thread under a 3 s deadline (TelemetryGuard::shutdown_blocking; an async shutdown exists for embedders). SdkMeterProvider::shutdown_with_timeout ignores its argument in SDK 0.32, so the deadline is enforced by the guard. Drain (8 s) + runtime (1 s) + telemetry (3 s) stays inside the 30 s Kubernetes grace period. The W3C TraceContextPropagator is registered globally.

  • Subscriber stack (telemetry/subscriber.rs): the fmt layer keeps RUST_LOG; the bridge layer has its own fixed filter (spans only, INFO+, and an allow-list of this repository's crates — spans declared by dependencies such as rmcp, hyper, or the SDK are never exported, so export cannot feed back into itself). Log lines inside an exported span end with trace_id=… span_id=…. The default RUST_LOG now includes opentelemetry_sdk=warn,opentelemetry-otlp=warn so queue overflow and export failures are visible locally.

  • Root HTTP span and metrics (telemetry/http.rs): one http.server.request span per request (semconv name and attributes, bounded — no query strings, headers, or client addresses; url.scheme is the listener's, never the client-controlled request-target scheme), parented on a valid incoming W3C traceparent so the parent-based sampler honours the caller's decision (absent/invalid → new root), held open by a response-body wrapper until the body completes or is dropped, marked as errored on 5xx, handler panics, and failed bodies (bounded error.type), plus http.server.request.duration and http.server.active_requests recorded by a Drop guard exactly once per request. Installed as the outermost Router::layer. tower_http::TraceLayer was considered and not used because it has no drop hook, which would let the active-request gauge drift on client disconnects.

  • Docs: docs/deploying/observability.md — enabling, configuration reference, exported data, sampling, log correlation, overflow/shutdown budgets, Kubernetes example.
  • Dependency delta: opentelemetry 0.32, opentelemetry_sdk 0.32, opentelemetry-otlp 0.32 (http-proto + reqwest-blocking-client + reqwest-rustls), tracing-opentelemetry 0.33 (+ http-body); all declare rust-version ≤ 1.85; no tonic; reuses the reqwest 0.13 line already present via rmcp. opentelemetry 0.33 shipped this week but tracing-opentelemetry still pins ^0.32. agentic-server-core is untouched.

    Design defaults (please object here if any is wrong)

    | Decision | Default |
    | --- | --- |
    | Transport | OTLP HTTP/protobuf only; gRPC deferred until the MSRV allows tonic 0.14 |
    | Opt-in | OTEL_TRACES_EXPORTER / OTEL_METRICS_EXPORTER = otlp; OTEL_SDK_DISABLED=true wins |
    | Sampling | parentbased_always_on (spec default); ratio sampling documented |
    | Log filter | RUST_LOG for local output; bridge filter independent of it |
    | Shutdown | gateway drain (8 s) → Runtime::shutdown_timeout(1 s) → telemetry flush (3 s) |

    Behaviour notes

  • main is now a sync fn with an explicit runtime. Previously #[tokio::main] waited indefinitely for in-flight spawn_blocking work at exit; the process now stops the runtime 1 s after telemetry shutdown. After drain_gateway and websocket_tracker.wait_until_idle() no request work remains, and SQLite recovers an abandoned WAL checkpoint, so this is intentional.

  • Correlated log lines are rendered without ANSI colour (the buffered formatter path); other lines are unchanged.

  • MSRV: cargo +1.85.0 check --locked fails on main today for reasons unrelated to this PR (home 0.5.12 → 1.88, process-wrap 9.1.0 → 1.87 with a real trait-upcasting compile error, icu_ 2.2.0 → 1.86). This PR adds nothing to that list; a CI MSRV job is therefore tracked separately rather than added here.
  • Deferred to phase 2 / 3

    Upstream context injection, execution-stage spans (rehydration, inference rounds, tools, compaction, persistence), WebSocket session/request spans, typed execution and delivery outcomes, gateway metrics and timing definitions, Collector compose example, overhead benchmarks.

    Test Plan

  • cargo fmt -- --check, cargo clippy --workspace --all-targets -- -D warnings, pre-commit run --all-files (including the Rust file-size policy): pass.

  • cargo test --workspace --no-fail-fast: 70 suites, 1672 passed, 0 failed, 11 ignored (require TEST_POSTGRES_URL). Existing WebSocket suites pass with the body wrapper in place.

  • New tests (+38):

  • - telemetry::config (9): defaults, per-signal selection, OTEL_SDK_DISABLED precedence and strict booleans, unknown exporter values, grpc rejected on every protocol variable, service-name trimming, programmatic endpoint never read from env.
    - telemetry::subscriber (8): bridge level filter, repository-crate allow-list (rmcp::service and other dependency spans rejected even at INFO), trace/span ids appended inside exported spans and inherited under non-exported DEBUG spans, plain output without a bridge, RUST_LOG=error does not affect export, default filter surfaces SDK/exporter warnings.
    - tests/telemetry_test.rs (7): disabled config builds nothing and opens no connection; exports carry service.name on traces and metrics (protobuf decoded by an in-process OTLP/HTTP stub); shutdown completes when the collector times out; the guard's deadline is honoured against an unresponsive collector (async and blocking paths); dropping an enabled guard inside the runtime does not panic; a request still streaming when the runtime is stopped reaches the collector with active_requests == 0.
    - tests/telemetry_http_test.rs (10): span attributes and allow-list, streaming span not finished until the body is consumed (gauge = 1 mid-stream), mid-stream body drop finalizes exactly once (gauge back to 0), 5xx marks error status, unmatched routes carry no http.route and no URL/query, valid traceparent becomes the parent, unsampled traceparent suppresses the span but not the metrics, invalid traceparent starts a new root, handler panics are recorded as errors and finalized once, failing bodies mark the span.
    - tests/telemetry_e2e_test.rs (1): telemetry::init + real router over TCP → stub receives GET, GET /health, POST /v1/responses spans, 3 duration samples, active_requests == 0, service identity on both signals.
  • Manual: real binary with OTEL_ set, requests, then SIGTERM → exit 0 in ~10 ms; the stub collector received the span export from the shutdown flush; the same with an unroutable endpoint exits cleanly. mkdocs build --strict passes.

  • Cassette decision: none needed — no client-facing or upstream wire contract, persistence, tool-loop, or streaming-event behaviour changes.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: franciscojavierarceo Review duration: 1188m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #341"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%