From b19c1412b0d68add5cfa6dc4e48675067b0893c7 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Sat, 25 Jul 2026 02:44:59 +0200 Subject: [PATCH 1/2] feat(ingester): continue the caller's trace across the ingest spawn (RFC 0039 slice 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both OTLP receivers create their `ingest logs` span inside `ingest_bound`, past a `tokio::spawn` that ambient context does not cross, so the caller's `traceparent` never reached it. Each handler now extracts the context from its own carrier before the spawn and attaches it to the whole spawned block, so the span is minted under it (RFC0039.3). The gRPC arm extracts from tonic metadata in `export` rather than from the tower auth layer as RFC 0039 §3.3 first proposed. That design contradicted §6 -- whose test drives `export` directly, with no tower stack, and so would never have exercised the extraction -- and put propagation inside a layer named for authentication. OTel prescribes extracting in the handler that receives the call, as the OTel Demo's own C++ gRPC service does with a carrier over `client_metadata()`. Cost is the `MetadataExtractor` that §3.4 had hoped to avoid; both RFC sections are amended in place. The new test is its own binary because it needs the process-global tracer (RFC0028.2) and `rfc0038_3_spawn_boundary.rs` owns the no-inbound-context case; leaving that file untouched keeps both cases covered. It fails with each arm's span in a freshly minted trace when the two handler changes are reverted. Signed-off-by: Jens Holdgaard Pedersen --- crates/ourios-ingester/src/receiver.rs | 4 +- crates/ourios-ingester/src/receiver/grpc.rs | 12 +- crates/ourios-ingester/src/receiver/http.rs | 20 ++- .../src/receiver/propagation.rs | 98 +++++++++++- crates/ourios-ingester/tests/README.md | 5 + .../tests/rfc0039_3_ingest_propagation.rs | 146 ++++++++++++++++++ .../0039-inbound-trace-context-propagation.md | 86 +++++++---- 7 files changed, 331 insertions(+), 40 deletions(-) create mode 100644 crates/ourios-ingester/tests/rfc0039_3_ingest_propagation.rs diff --git a/crates/ourios-ingester/src/receiver.rs b/crates/ourios-ingester/src/receiver.rs index 397f4c5f2..0ded64eb4 100644 --- a/crates/ourios-ingester/src/receiver.rs +++ b/crates/ourios-ingester/src/receiver.rs @@ -48,5 +48,7 @@ pub use commit::CommitCoordinator; pub use decode::{DecodeError, decode_json, decode_protobuf}; pub use materialize::{materialize_record, materialize_resource_logs}; pub use pipeline::{IngestPipeline, Journal, ReceiveError, SharedPipeline}; -pub use propagation::{HeaderExtractor, extract_context}; +pub use propagation::{ + HeaderExtractor, MetadataExtractor, extract_context, extract_context_from_metadata, +}; pub use tenant::{TenantResolutionError, TenantRule, fan_out}; diff --git a/crates/ourios-ingester/src/receiver/grpc.rs b/crates/ourios-ingester/src/receiver/grpc.rs index 69f7ec65c..0e2595313 100644 --- a/crates/ourios-ingester/src/receiver/grpc.rs +++ b/crates/ourios-ingester/src/receiver/grpc.rs @@ -29,8 +29,11 @@ use opentelemetry_proto::tonic::collector::logs::v1::{ }; use tonic::{Request, Response, Status}; +use opentelemetry::context::FutureExt as _; + use crate::receiver::auth::{AuthBinding, AuthResolver}; use crate::receiver::pipeline::{ReceiveError, SharedPipeline}; +use crate::receiver::propagation::extract_context_from_metadata; /// The authentication gate for the gRPC listener (RFC 0026 §3.2 / /// RFC 0029 §3.3), applied as a tower layer on the tonic server. A tower @@ -153,6 +156,12 @@ impl LogsService for LogsReceiver { &self, request: Request, ) -> Result, Status> { + // RFC 0039 §3.3: the `ingest logs` span is born inside `ingest_bound`, + // past the `tokio::spawn` below — which ambient context does not cross. + // So the caller's context is extracted here, while the request (and its + // metadata) is still in hand, and re-attached inside the task where the + // span is actually created. + let parent = extract_context_from_metadata(request.metadata()); // The [`AuthInterceptor`]'s binding, when auth is enabled — the // pipeline enforces the §3.2 tenant binding against it. let binding = request.extensions().get::().cloned(); @@ -165,7 +174,8 @@ impl LogsService for LogsReceiver { // so this is `spawn`, not `spawn_blocking`. let pipeline = self.pipeline.clone(); match tokio::spawn( - async move { pipeline.ingest_bound(export, binding.as_ref(), false).await }, + async move { pipeline.ingest_bound(export, binding.as_ref(), false).await } + .with_context(parent), ) .await { diff --git a/crates/ourios-ingester/src/receiver/http.rs b/crates/ourios-ingester/src/receiver/http.rs index 7e4cdbb13..314f4887e 100644 --- a/crates/ourios-ingester/src/receiver/http.rs +++ b/crates/ourios-ingester/src/receiver/http.rs @@ -24,9 +24,12 @@ use axum::routing::post; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceResponse; use prost::Message; +use opentelemetry::context::FutureExt as _; + use crate::receiver::auth::AuthResolver; use crate::receiver::decode::{decode_json, decode_protobuf}; use crate::receiver::pipeline::{ReceiveError, SharedPipeline}; +use crate::receiver::propagation::extract_context; /// OTLP/HTTP listener configuration. #[derive(Debug, Clone)] @@ -142,12 +145,19 @@ async fn handle_logs(State(state): State, headers: HeaderMap, body: By // handler just awaits. Run it on its own task so a panic in the // pipeline/miner is contained as a 500 (the handler promises not to // panic) rather than aborting the connection. + // RFC 0039 §3.3: as on the gRPC arm, the `ingest logs` span is created + // inside `ingest_bound` past this spawn, so the caller's context is + // extracted from the request headers here and re-attached inside the task. + let parent = extract_context(&headers); let pipeline = state.pipeline.clone(); - match tokio::spawn(async move { - pipeline - .ingest_bound(request, binding.as_ref(), lenient_json) - .await - }) + match tokio::spawn( + async move { + pipeline + .ingest_bound(request, binding.as_ref(), lenient_json) + .await + } + .with_context(parent), + ) .await { Ok(Ok(_)) => success_response(format), diff --git a/crates/ourios-ingester/src/receiver/propagation.rs b/crates/ourios-ingester/src/receiver/propagation.rs index 0ed973baa..699d64724 100644 --- a/crates/ourios-ingester/src/receiver/propagation.rs +++ b/crates/ourios-ingester/src/receiver/propagation.rs @@ -1,10 +1,16 @@ //! Inbound W3C trace-context extraction (RFC 0039). //! -//! Every Ourios ingress — OTLP gRPC/HTTP, the query API, the MCP tools — -//! receives its caller's trace context as HTTP headers, so one -//! [`HeaderExtractor`] over [`http::HeaderMap`] serves all of them (the gRPC -//! path extracts from the raw HTTP headers at its tower layer, so no tonic -//! `MetadataMap` adapter is needed). +//! Every Ourios ingress receives its caller's trace context as HTTP headers, so +//! [`HeaderExtractor`] over [`http::HeaderMap`] serves the axum-side ingresses +//! (OTLP/HTTP, the query API, the MCP tools). gRPC metadata *is* HTTP/2 headers, +//! but tonic models it as `HeaderMap` rather than +//! `http::HeaderMap`, so the OTLP/gRPC ingress needs its own carrier adapter: +//! [`MetadataExtractor`]. Extraction happens in the handler that receives the +//! call, which is where OpenTelemetry puts it — "if you work on a library or a +//! service that receives upstream calls, extract context from the incoming +//! request", the one context on the wire becoming the parent of the span the +//! receiver creates (cf. the `OTel` Demo's `C++` `GrpcServerCarrier` over +//! `client_metadata()`). //! //! [`extract_context`] resolves the context through the globally installed //! propagator (`ourios-telemetry` installs `TraceContextPropagator` in `init`). @@ -17,6 +23,7 @@ use axum::http::HeaderMap; use opentelemetry::Context; use opentelemetry::propagation::Extractor; +use tonic::metadata::{KeyRef, MetadataMap}; /// Reads W3C trace-context headers out of an [`http::HeaderMap`]. pub struct HeaderExtractor<'a>(pub &'a HeaderMap); @@ -42,6 +49,37 @@ pub fn extract_context(headers: &HeaderMap) -> Context { }) } +/// Reads W3C trace-context entries out of tonic gRPC [`MetadataMap`]. +pub struct MetadataExtractor<'a>(pub &'a MetadataMap); + +impl Extractor for MetadataExtractor<'_> { + fn get(&self, key: &str) -> Option<&str> { + self.0.get(key).and_then(|value| value.to_str().ok()) + } + + fn keys(&self) -> Vec<&str> { + // Binary (`-bin`) metadata cannot hold a text-map entry, so those keys + // are not carrier candidates — only the ascii half is offered. + self.0 + .keys() + .filter_map(|key| match key { + KeyRef::Ascii(key) => Some(key.as_str()), + KeyRef::Binary(_) => None, + }) + .collect() + } +} + +/// The caller's trace context from gRPC `metadata` — the [`extract_context`] +/// counterpart for the OTLP/gRPC ingress, with identical absent/malformed +/// behaviour (RFC0039.2 / RFC0039.5). +#[must_use] +pub fn extract_context_from_metadata(metadata: &MetadataMap) -> Context { + opentelemetry::global::get_text_map_propagator(|propagator| { + propagator.extract(&MetadataExtractor(metadata)) + }) +} + #[cfg(test)] mod tests { use opentelemetry::trace::TraceContextExt as _; @@ -76,6 +114,56 @@ mod tests { assert!(sc.is_remote(), "an extracted context is remote"); } + /// The gRPC carrier reaches the same remote `SpanContext` as the HTTP one: + /// a `traceparent` in tonic metadata extracts identically (RFC0039.1, gRPC + /// arm). Guards the `MetadataExtractor` adapter, which is the only reason + /// the gRPC ingress is not simply reusing `HeaderExtractor`. + #[test] + fn traceparent_in_grpc_metadata_round_trips_identically() { + use opentelemetry::propagation::TextMapPropagator as _; + use opentelemetry_sdk::propagation::TraceContextPropagator; + use tonic::metadata::MetadataMap; + + let mut metadata = MetadataMap::new(); + metadata.insert( + "traceparent", + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" + .parse() + .expect("valid metadata value"), + ); + let cx = TraceContextPropagator::new().extract(&super::MetadataExtractor(&metadata)); + let sc = cx.span().span_context().clone(); + assert_eq!( + sc.trace_id().to_string(), + "4bf92f3577b34da6a3ce929d0e0e4736" + ); + assert_eq!(sc.span_id().to_string(), "00f067aa0ba902b7"); + assert!(sc.is_remote(), "an extracted context is remote"); + } + + /// A binary (`-bin`) metadata key cannot carry a text-map entry, so it must + /// not be offered as a carrier key — `keys()` returning it would hand the + /// propagator a key whose `get` can never resolve. + #[test] + fn binary_metadata_keys_are_not_offered_as_carrier_keys() { + use opentelemetry::propagation::Extractor as _; + use tonic::metadata::{MetadataMap, MetadataValue}; + + let mut metadata = MetadataMap::new(); + metadata.insert("traceparent", "00-a-b-01".parse().expect("valid value")); + metadata.insert_bin( + "trace-proto-bin", + MetadataValue::from_bytes(b"\x00\x01\x02"), + ); + let extractor = super::MetadataExtractor(&metadata); + let keys = extractor.keys(); + assert!(keys.contains(&"traceparent"), "ascii keys are offered"); + assert!( + !keys.iter().any(|key| key.ends_with("-bin")), + "binary keys are withheld, got {keys:?}", + ); + } + /// No `traceparent` yields no remote span, so the span run under it roots /// itself (RFC0039.2). Goes through the global propagator, which is a no-op /// propagator unless something installed one — either way the result must diff --git a/crates/ourios-ingester/tests/README.md b/crates/ourios-ingester/tests/README.md index ee154daec..f6dc36239 100644 --- a/crates/ourios-ingester/tests/README.md +++ b/crates/ourios-ingester/tests/README.md @@ -26,6 +26,11 @@ one-per-binary: a global (not scoped) tracer is required to capture the `ingest logs` / `sweep partitions` spans across the receiver's `tokio::spawn` and the compactor's `spawn_blocking` (RFC0038.3). +- `rfc0039_3_ingest_propagation.rs` — the same global **tracer** need, for the + inbound-`traceparent` half: that the batch span joins the *caller's* trace + across that spawn, on both OTLP transports (RFC0039.3). Separate from + `rfc0038_3` because a process holds one tracer install and that file owns + the no-inbound-context (root) case. `fixtures/` holds the crash-fixture **`[[bin]]` targets** (SIGKILL'd by harness tests via `CARGO_BIN_EXE_*`), not test binaries. diff --git a/crates/ourios-ingester/tests/rfc0039_3_ingest_propagation.rs b/crates/ourios-ingester/tests/rfc0039_3_ingest_propagation.rs new file mode 100644 index 000000000..8591fe17f --- /dev/null +++ b/crates/ourios-ingester/tests/rfc0039_3_ingest_propagation.rs @@ -0,0 +1,146 @@ +//! RFC0039.3 — the caller's trace context survives the ingest `tokio::spawn`. +//! +//! Harness-exempt (RFC0028.2, see `tests/README.md`): installs the +//! **process-global** `OTel` tracer, which cannot share a process with the +//! consolidated `it` harness or another global installer. +//! +//! The `ingest logs` span is created inside `ingest_bound`, *after* the +//! receivers' `tokio::spawn` — a boundary ambient context does not cross. Both +//! handlers therefore extract the caller's context while the request is still in +//! hand and re-attach it inside the spawned task (RFC 0039 §3.3). What follows +//! asserts the observable consequence for both OTLP transports: the batch span, +//! and the `commit wal` child minted under it, land in the *caller's* trace +//! rather than a fresh one. +//! +//! The two arms carry **different** traces so a single exporter can hold both +//! and each span still be attributed unambiguously. +//! `rfc0038_3_spawn_boundary.rs` covers this same boundary with no inbound +//! context (the root case, RFC0039.2) and is deliberately left untouched. + +#[path = "it/ingest_support/mod.rs"] +mod ingest_support; + +use axum::body::Body; +use axum::http::{Request, header}; +use ingest_support::{request, resource_logs, shared_wal_pipeline}; +use opentelemetry::trace::TracerProvider as _; +use opentelemetry_proto::tonic::collector::logs::v1::logs_service_server::LogsService as _; +use opentelemetry_sdk::propagation::TraceContextPropagator; +use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider, SpanData}; +use ourios_ingester::receiver::grpc::LogsReceiver; +use ourios_ingester::receiver::http::{HttpConfig, router}; +use prost::Message as _; +use tower::ServiceExt as _; +use tracing_subscriber::prelude::*; + +/// The trace the gRPC caller claims to be inside. +const GRPC_TRACE: &str = "4bf92f3577b34da6a3ce929d0e0e4736"; +const GRPC_SPAN: &str = "00f067aa0ba902b7"; +/// …and the HTTP caller's, distinct from it. +const HTTP_TRACE: &str = "0af7651916cd43dd8448eb211c80319c"; +const HTTP_SPAN: &str = "b7ad6b7169203331"; + +fn traceparent(trace: &str, span: &str) -> String { + format!("00-{trace}-{span}-01") +} + +/// The spans named `name` that resolved into trace `trace`. +fn spans_in_trace<'a>(spans: &'a [SpanData], trace: &str, name: &str) -> Vec<&'a SpanData> { + spans + .iter() + .filter(|s| s.name.as_ref() == name && s.span_context.trace_id().to_string() == trace) + .collect() +} + +/// Assert that one `ingest logs` span joined `trace` as a child of `parent_span`, +/// and that its `commit wal` child nests under it inside that same trace. +fn assert_batch_joined_caller_trace(spans: &[SpanData], trace: &str, parent_span: &str, arm: &str) { + let batch = spans_in_trace(spans, trace, "ingest logs"); + assert_eq!( + batch.len(), + 1, + "{arm}: exactly one `ingest logs` span in the caller's trace, got {:?}", + spans + .iter() + .map(|s| (s.name.clone(), s.span_context.trace_id().to_string())) + .collect::>(), + ); + assert_eq!( + batch[0].parent_span_id.to_string(), + parent_span, + "{arm}: the batch span is parented to the caller's span across the spawn", + ); + + let commit = spans_in_trace(spans, trace, "commit wal"); + assert_eq!( + commit.len(), + 1, + "{arm}: exactly one `commit wal` span in the caller's trace", + ); + assert_eq!( + commit[0].parent_span_id, + batch[0].span_context.span_id(), + "{arm}: `commit wal` still nests under `ingest logs` once the batch span has a remote parent", + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn rfc0039_3_extracted_context_survives_the_ingest_spawn() { + // The global tracer, as in `rfc0038_3_spawn_boundary.rs`: only the global + // default reaches a span opened inside a spawned task. The global + // *propagator* is what the handlers' extraction resolves through — in + // production `ourios_telemetry::init` installs it (RFC 0039 §3.1). + let exporter = InMemorySpanExporter::default(); + let provider = SdkTracerProvider::builder() + .with_simple_exporter(exporter.clone()) + .build(); + tracing_subscriber::registry() + .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("ourios-test"))) + .try_init() + .expect("install global subscriber"); + opentelemetry::global::set_tracer_provider(provider.clone()); + opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new()); + + // --- Arm A: OTLP/gRPC. The spawn is inside `export`, which awaits it, so + // the batch span is finished by the time this returns. --- + let grpc_tmp = tempfile::tempdir().expect("temp"); + let receiver = LogsReceiver::new(shared_wal_pipeline(grpc_tmp.path())); + let mut grpc_request = + tonic::Request::new(request(vec![resource_logs("checkout", &["alpha", "beta"])])); + grpc_request.metadata_mut().insert( + "traceparent", + traceparent(GRPC_TRACE, GRPC_SPAN) + .parse() + .expect("valid metadata value"), + ); + receiver.export(grpc_request).await.expect("export acks"); + + // --- Arm B: OTLP/HTTP, driven in-process through the real router. --- + let http_tmp = tempfile::tempdir().expect("temp"); + let config = HttpConfig::default(); + let app = router(shared_wal_pipeline(http_tmp.path()), &config); + let body = request(vec![resource_logs("payments", &["gamma"])]).encode_to_vec(); + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri(&config.path) + .header(header::CONTENT_TYPE, "application/x-protobuf") + .header("traceparent", traceparent(HTTP_TRACE, HTTP_SPAN)) + .body(Body::from(body)) + .expect("build request"), + ) + .await + .expect("oneshot"); + assert!( + response.status().is_success(), + "the HTTP export should be acked, got {}", + response.status(), + ); + + provider.force_flush().expect("spans flush"); + let spans = exporter.get_finished_spans().expect("spans exported"); + + assert_batch_joined_caller_trace(&spans, GRPC_TRACE, GRPC_SPAN, "gRPC"); + assert_batch_joined_caller_trace(&spans, HTTP_TRACE, HTTP_SPAN, "HTTP"); +} diff --git a/docs/rfcs/0039-inbound-trace-context-propagation.md b/docs/rfcs/0039-inbound-trace-context-propagation.md index e46d36a21..d2299e33f 100644 --- a/docs/rfcs/0039-inbound-trace-context-propagation.md +++ b/docs/rfcs/0039-inbound-trace-context-propagation.md @@ -70,7 +70,7 @@ incoming `traceparent` lives — is not always co-located with the span: | # | Span | Site (file:line) | Carrier & where it is reachable | |---|---|---|---| -| A | `ingest logs` (gRPC) | span in `ingest_bound` (`pipeline.rs:291`); entry `LogsReceiver::export` (`grpc.rs:152`) | raw `http::HeaderMap` in the tower auth layer `AuthService::call` (`grpc.rs:102`, already reads `request.headers()`) | +| A | `ingest logs` (gRPC) | span in `ingest_bound` (`pipeline.rs:291`); entry `LogsReceiver::export` (`grpc.rs:152`) | tonic `MetadataMap`, on the request in `export` itself (§3.4) | | B | `ingest logs` (HTTP) | span in `ingest_bound`; entry `handle_logs` (`http.rs:95`) | axum `HeaderMap` (`http.rs:95`) | | C | `POST /v1/query` | `handle_query` (`querier.rs:421`) | axum `HeaderMap` (`querier.rs:423`) | | D | `execute_tool ` (×3) | the three `_traced` fns (`mcp.rs:333/416/488`), each via a thin `#[tool]` delegate | `ctx.extensions.get::()?.headers` (as `mcp_session_id` reads, `mcp.rs:223`) | @@ -95,16 +95,35 @@ span-producing future under the extracted context. One contract, every site: router extracts `cx` from the request `HeaderMap` and runs the downstream as `next.run(req).with_context(cx)`. `handle_query`'s root span inherits `cx`; the handler is unchanged. -- **gRPC ingest (A):** the same extraction in the existing tower auth layer - (`AuthService::call`, `grpc.rs:102`), stashing `cx` in the request extensions - beside the auth binding. +- **gRPC ingest (A):** extraction happens in `LogsService::export` itself, from + the request's tonic `MetadataMap` (§3.4) — *not* in the tower auth layer, as + an earlier revision of this section proposed. Extraction belongs with the + handler that receives the call, which is both what OpenTelemetry prescribes + for a service receiving upstream calls and what makes it testable: the + RFC0039.3 harness drives `export` directly (no tower stack), so a + layer-extracted context would leave the extraction itself uncovered. See the + amendment note below. - **The `tokio::spawn` boundary (A/B):** the `ingest logs` span is born inside - `ingest_bound`, *after* the spawn (`grpc.rs:167`, `http.rs:146`), which a - layer's `with_context` does not cross. So the handler reads `cx` (from the - extension for A, extracts directly for B), moves it into the spawned closure, - and runs `ingest_bound(...).with_context(cx).await`. The span, first polled - under `cx`, inherits it — **no `ingest_bound` signature change, no - `set_parent`.** + `ingest_bound`, *after* the spawn (`grpc.rs:167`, `http.rs:146`), which + ambient context does not cross. So the handler extracts `cx` from its own + carrier before the spawn, moves it into the spawned closure, and attaches it + to the **whole** spawned block — `async move { ingest_bound(...).await + }.with_context(cx)` — rather than to `ingest_bound`'s future alone. Wrapping + the block is deliberate: it holds whether `#[tracing::instrument]` mints its + span at call time or on first poll, so the span cannot be created outside + `cx`. **No `ingest_bound` signature change, no `set_parent`.** + +> **Amendment (slice 2).** §3.3's gRPC bullet and §3.4 originally routed +> extraction through the tower auth layer into a request extension. That was +> withdrawn during implementation for two reasons: it contradicted §6, whose +> RFC0039.3 test calls `export` directly and so would have exercised only the +> spawn hand-off and never the extraction; and it put a propagation concern +> inside a layer named for authentication. The OTel guidance is explicit that a +> service receiving upstream calls extracts in the receiving handler ("the one +> context on the wire becomes the parent of the new span the library creates"), +> and the OTel Demo's own C++ gRPC service does exactly this with a +> `GrpcServerCarrier` over `client_metadata()`. The cost of the correction is +> the ~15-line `MetadataExtractor` that §3.4 had hoped to avoid. - **MCP (D):** the un-instrumented `#[tool]` delegate extracts `cx` from `ctx`'s forwarded headers and runs `self._traced(...).with_context(cx).await`; the `_traced` span inherits `cx` across rmcp's own dispatch spawn. @@ -116,13 +135,20 @@ the earlier draft's split between an explicit parameter and a request extension. ### 3.4 The extractor shim `opentelemetry::propagation::Extractor` is a two-method trait (`get`, `keys`). -One adapter suffices: `struct HeaderExtractor<'a>(&'a http::HeaderMap)`, since -`http::HeaderMap` is the carrier for **every** site — the gRPC path extracts from -the raw HTTP headers at the tower auth layer (`grpc.rs:102`), so no tonic -`MetadataMap` adapter is needed. Extraction goes through the propagator installed -in §3.1: `global::get_text_map_propagator(|p| p.extract(&HeaderExtractor(headers)))`. -`opentelemetry-http` ships an equivalent `HeaderExtractor`; the ~10-line local -one avoids a dependency (revisit if a metadata extractor is ever needed). +**Two** adapters are needed, both in `receiver/propagation.rs`: + +- `HeaderExtractor<'a>(&'a http::HeaderMap)` — the axum-side ingresses (OTLP/HTTP, + the query API, the MCP tools), whose carrier is an `http::HeaderMap`. +- `MetadataExtractor<'a>(&'a tonic::metadata::MetadataMap)` — the OTLP/gRPC + ingress. gRPC metadata *is* HTTP/2 headers, but tonic models it as + `HeaderMap`, not `http::HeaderMap`, and exposes no cheap + `&HeaderMap` view, so it needs its own carrier. `keys()` offers only the ascii + half: a binary (`-bin`) key can never resolve as a text-map entry. + +Both resolve through the propagator installed in §3.1, e.g. +`global::get_text_map_propagator(|p| p.extract(&HeaderExtractor(headers)))`. +`opentelemetry-http` ships an equivalent `HeaderExtractor`; the local pair avoids +that dependency and keeps both carriers described in one place. ### 3.5 Dependency promotion (the one production-surface change) @@ -180,11 +206,14 @@ and every `#[tracing::instrument]` span is entered for its body, so the parent i silently dropped (§3.3). The attach-the-context idiom (`with_context`) is the correct primitive and is what §3.3 adopts. -**Per-handler extraction with no shared layer.** Workable but repetitive: each -handler would extract and wrap. The `PropagationLayer` (§3.3) centralises the -request-local sites (B/C); only the spawn-crossed span (A/B's `ingest_bound`) and -MCP (D, behind rmcp's dispatch) need the explicit `with_context` hand-off, which -no layer can do for them anyway. +**A shared `PropagationLayer` instead of per-handler extraction.** Attractive on +paper — one layer for every axum-side ingress — but it buys less than it looks. +Neither ingest arm can use it: their span is born past a `tokio::spawn`, so they +need the explicit `with_context` hand-off regardless (§3.3), and a layer that +extracted for them would only duplicate what the handler must do anyway. That +leaves the query arm as the sole beneficiary of a whole tower layer, for the two +lines it already spends extracting directly. Per-handler extraction also keeps +each site's carrier visible at the site, which is where OTel puts it. **Adopt `opentelemetry-http`'s `HeaderExtractor` as a dependency.** Reasonable, but it is one more crate for a ~10-line shim; the RFC inlines the extractor. If @@ -260,12 +289,13 @@ Mapped to `CLAUDE.md` §6.2: ## 7. Open questions -- [ ] Confirm `FutureExt::with_context` correctly re-attaches the extracted - context inside the spawned `ingest_bound` task (§3.3) — the spawn-boundary - test (RFC0039.3) is the check. (The carry-channel and site-A/metadata-vs- - header questions the earlier draft left open are now settled by §3.3/§3.4: - one `HeaderExtractor` over the raw `http::HeaderMap`, `cx` in the request - extension across the spawn, no `ingest_bound` signature change.) +- [x] **Resolved (slice 2).** `FutureExt::with_context` does re-attach the + extracted context inside the spawned `ingest_bound` task, on both + transports — `rfc0039_3_ingest_propagation.rs` passes, and fails with + each arm's span in a freshly minted trace when the two handler changes are + reverted. Site A's carrier is the tonic `MetadataMap`, read in `export` + (§3.4 amendment); no request extension and no `ingest_bound` signature + change are involved. - [ ] MCP tool spans are `otel.kind = "internal"` and lack an enclosing Ourios SERVER span for `/mcp` (rmcp's `serve_inner` is muted by the `rmcp=off` loop-guard, RFC0038.7). An INTERNAL span continuing a *remote* parent is From 9858adc2c7391bbd7e7fbfb87c83f6700ad9d47b Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Sat, 25 Jul 2026 02:53:02 +0200 Subject: [PATCH 2/2] docs(rfc): drop rotting line refs; test the gRPC malformed-carrier arm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-ups on #628: - CodeRabbit flagged three stale file:line references. Rather than correct the numbers a second time, §3.2's site table and §3.3 now name file + function only -- line numbers rot on every touch of surrounding code. - Copilot: §3.3's first bullet still described a tower PropagationLayer for the query and HTTP-ingest arms, which neither uses. Rewritten to the implemented per-handler extraction, pointing at §4 for why no layer. - Copilot: assert the gRPC carrier treats a malformed traceparent as absent (RFC0039.5, gRPC arm). The two carriers reach the propagator through different Extractor impls, so this was genuinely uncovered. Signed-off-by: Jens Holdgaard Pedersen --- .../src/receiver/propagation.rs | 22 ++++++++++++++++ .../0039-inbound-trace-context-propagation.md | 26 ++++++++++++------- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/crates/ourios-ingester/src/receiver/propagation.rs b/crates/ourios-ingester/src/receiver/propagation.rs index 699d64724..8668dbb33 100644 --- a/crates/ourios-ingester/src/receiver/propagation.rs +++ b/crates/ourios-ingester/src/receiver/propagation.rs @@ -194,4 +194,26 @@ mod tests { ); } } + + /// The gRPC carrier rejects a malformed `traceparent` the same way the + /// `HeaderMap` one does (RFC0039.5, gRPC arm). Worth asserting separately: + /// the two carriers reach the propagator through different `Extractor` + /// impls, so a carrier-specific parsing difference would otherwise let a + /// bogus parent through on one transport only. + #[test] + fn malformed_traceparent_in_grpc_metadata_is_treated_as_absent() { + use opentelemetry::propagation::TextMapPropagator as _; + use opentelemetry_sdk::propagation::TraceContextPropagator; + use tonic::metadata::MetadataMap; + + for bad in ["not-a-traceparent", "00-tooshort-00f067aa0ba902b7-01", ""] { + let mut metadata = MetadataMap::new(); + metadata.insert("traceparent", bad.parse().expect("valid metadata value")); + let cx = TraceContextPropagator::new().extract(&super::MetadataExtractor(&metadata)); + assert!( + !cx.span().span_context().is_valid(), + "malformed traceparent {bad:?} must not yield a parent over gRPC", + ); + } + } } diff --git a/docs/rfcs/0039-inbound-trace-context-propagation.md b/docs/rfcs/0039-inbound-trace-context-propagation.md index d2299e33f..72b3b5d1c 100644 --- a/docs/rfcs/0039-inbound-trace-context-propagation.md +++ b/docs/rfcs/0039-inbound-trace-context-propagation.md @@ -68,12 +68,16 @@ functions in all, since the MCP category is three tool functions. The count is stated so test coverage (RFC0039.1/.3/.6) omits no site. The carrier — where the incoming `traceparent` lives — is not always co-located with the span: -| # | Span | Site (file:line) | Carrier & where it is reachable | +Sites are named by file and function, deliberately without line numbers — those +rot on every touch of the surrounding code and have already been corrected twice +in review. + +| # | Span | Site | Carrier & where it is reachable | |---|---|---|---| -| A | `ingest logs` (gRPC) | span in `ingest_bound` (`pipeline.rs:291`); entry `LogsReceiver::export` (`grpc.rs:152`) | tonic `MetadataMap`, on the request in `export` itself (§3.4) | -| B | `ingest logs` (HTTP) | span in `ingest_bound`; entry `handle_logs` (`http.rs:95`) | axum `HeaderMap` (`http.rs:95`) | -| C | `POST /v1/query` | `handle_query` (`querier.rs:421`) | axum `HeaderMap` (`querier.rs:423`) | -| D | `execute_tool ` (×3) | the three `_traced` fns (`mcp.rs:333/416/488`), each via a thin `#[tool]` delegate | `ctx.extensions.get::()?.headers` (as `mcp_session_id` reads, `mcp.rs:223`) | +| A | `ingest logs` (gRPC) | span in `IngestPipeline::ingest_bound` (`pipeline.rs`); entry `LogsReceiver::export` (`grpc.rs`) | tonic `MetadataMap`, on the request in `export` itself (§3.4) | +| B | `ingest logs` (HTTP) | span in `ingest_bound`; entry `handle_logs` (`http.rs`) | axum `HeaderMap`, a `handle_logs` extractor | +| C | `POST /v1/query` | `handle_query_traced`, behind the `handle_query` wrapper (`querier.rs`) | axum `HeaderMap`, a `handle_query` extractor | +| D | `execute_tool ` (×3) | the three `_traced` fns (`mcp.rs`), each via a thin `#[tool]` delegate | `ctx.extensions.get::()?.headers` (as `mcp_session_id` reads) | The mechanism is uniform (§3.3): extract the caller's `opentelemetry::Context` and make it the **current** context around the span-producing future, so the @@ -91,10 +95,12 @@ span is built; `tracing-opentelemetry` then parents a root span to `opentelemetry::trace::FutureExt::with_context(future, cx)` — run the span-producing future under the extracted context. One contract, every site: -- **Query (C) and HTTP ingest (B):** a tower `PropagationLayer` on the axum - router extracts `cx` from the request `HeaderMap` and runs the downstream as - `next.run(req).with_context(cx)`. `handle_query`'s root span inherits `cx`; the - handler is unchanged. +- **Query (C):** an un-instrumented `handle_query` wrapper extracts `cx` from the + request `HeaderMap` and awaits the instrumented `handle_query_traced` under it + — `handle_query_traced(..).with_context(cx).await`. No tower layer: an earlier + revision of this bullet proposed a shared `PropagationLayer`, but neither ingest + arm can use one (their span is born past a `tokio::spawn`, below), which would + leave the query arm as its sole beneficiary — see §4. - **gRPC ingest (A):** extraction happens in `LogsService::export` itself, from the request's tonic `MetadataMap` (§3.4) — *not* in the tower auth layer, as an earlier revision of this section proposed. Extraction belongs with the @@ -104,7 +110,7 @@ span-producing future under the extracted context. One contract, every site: layer-extracted context would leave the extraction itself uncovered. See the amendment note below. - **The `tokio::spawn` boundary (A/B):** the `ingest logs` span is born inside - `ingest_bound`, *after* the spawn (`grpc.rs:167`, `http.rs:146`), which + `ingest_bound`, *after* the spawn in `export` / `handle_logs`, which ambient context does not cross. So the handler extracts `cx` from its own carrier before the spawn, moves it into the spawned closure, and attaches it to the **whole** spawned block — `async move { ingest_bound(...).await