feat: OpenTelemetry foundation (#338 Phrase 1 of #279) #341
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
franciscojavierarceo
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-serverbinary. 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, bridgestracingspans to OpenTelemetry, and correlates local log lines with the exported trace.OTEL_configuration (telemetry/config.rs):OTEL_SDK_DISABLED,OTEL_{TRACES,METRICS}_EXPORTER(none|otlp, defaultnone— 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;grpcis rejected with a message naming the reason (the gRPC exporter needstonic 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_varisunsafein edition 2024).telemetry/lifecycle.rs): providers are built before the Tokio runtime and owned bymain. Afterserver::runreturns on any exit path,mainfirst 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 asyncshutdownexists for embedders).SdkMeterProvider::shutdown_with_timeoutignores 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 W3CTraceContextPropagatoris registered globally.telemetry/subscriber.rs): thefmtlayer keepsRUST_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 asrmcp,hyper, or the SDK are never exported, so export cannot feed back into itself). Log lines inside an exported span end withtrace_id=… span_id=…. The defaultRUST_LOGnow includesopentelemetry_sdk=warn,opentelemetry-otlp=warnso queue overflow and export failures are visible locally.telemetry/http.rs): onehttp.server.requestspan per request (semconv name and attributes, bounded — no query strings, headers, or client addresses;url.schemeis the listener's, never the client-controlled request-target scheme), parented on a valid incoming W3Ctraceparentso 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 (boundederror.type), plushttp.server.request.durationandhttp.server.active_requestsrecorded by aDropguard exactly once per request. Installed as the outermostRouter::layer.tower_http::TraceLayerwas considered and not used because it has no drop hook, which would let the active-request gauge drift on client disconnects.docs/deploying/observability.md— enabling, configuration reference, exported data, sampling, log correlation, overflow/shutdown budgets, Kubernetes example.Dependency delta:
opentelemetry0.32,opentelemetry_sdk0.32,opentelemetry-otlp0.32 (http-proto+reqwest-blocking-client+reqwest-rustls),tracing-opentelemetry0.33 (+http-body); all declarerust-version ≤ 1.85; notonic; reuses thereqwest 0.13line already present viarmcp.opentelemetry 0.33shipped this week buttracing-opentelemetrystill pins^0.32.agentic-server-coreis 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=truewins || Sampling |
parentbased_always_on(spec default); ratio sampling documented || Log filter |
RUST_LOGfor local output; bridge filter independent of it || Shutdown | gateway drain (8 s) →
Runtime::shutdown_timeout(1 s)→ telemetry flush (3 s) |Behaviour notes
mainis now a syncfnwith an explicit runtime. Previously#[tokio::main]waited indefinitely for in-flightspawn_blockingwork at exit; the process now stops the runtime 1 s after telemetry shutdown. Afterdrain_gatewayandwebsocket_tracker.wait_until_idle()no request work remains, and SQLite recovers an abandoned WAL checkpoint, so this is intentional.cargo +1.85.0 check --lockedfails onmaintoday 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 (requireTEST_POSTGRES_URL). Existing WebSocket suites pass with the body wrapper in place.-
telemetry::config(9): defaults, per-signal selection,OTEL_SDK_DISABLEDprecedence and strict booleans, unknown exporter values,grpcrejected on every protocol variable, service-name trimming, programmatic endpoint never read from env.-
telemetry::subscriber(8): bridge level filter, repository-crate allow-list (rmcp::serviceand other dependency spans rejected even atINFO), trace/span ids appended inside exported spans and inherited under non-exportedDEBUGspans, plain output without a bridge,RUST_LOG=errordoes not affect export, default filter surfaces SDK/exporter warnings.-
tests/telemetry_test.rs(7): disabled config builds nothing and opens no connection; exports carryservice.nameon 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 withactive_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 nohttp.routeand no URL/query, validtraceparentbecomes the parent, unsampledtraceparentsuppresses the span but not the metrics, invalidtraceparentstarts 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 receivesGET,GET /health,POST /v1/responsesspans, 3 duration samples,active_requests == 0, service identity on both signals.OTEL_set, requests, thenSIGTERM→ 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 --strictpasses.