Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(telemetry): preserve safe per-request batch timing (#402)
Attila László Nagyf0cb86520843
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1e3d8bf2c..3d91b734b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -80,6 +80,10 @@ jobs:mise exec -- uv run --frozen --project . --no-sync ruff check --select E,F,I,UP,B tools/cimise exec -- uv run --frozen --project . --no-sync ruff check --select E9,F63,F7,F82 tools/mise_tasksmise exec -- uv run --frozen --project . --no-sync pytest -q tools/ci/tests --ignore tools/ci/tests/test_required_ci.py --ignore tools/ci/tests/test_public_tree.py --ignore tools/ci/tests/test_helm_render.py+ - name: Pinned collector trace privacy+ run: |+ mise run helm -- dependencies+ mise exec -- uv run --frozen --project . --no-sync pytest -q -m docker tools/ci/tests/test_collector_trace_privacy.pytypescript:name: CI / TypeScriptdiff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tplindex 83b65e3ca..26206f607 100644--- a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl+++ b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl@@ -301,7 +301,9 @@ processors:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(up|otelcol_exporter_queue_size|otelcol_exporter_queue_capacity|otelcol_receiver_refused_spans|otelcol_exporter_send_failed_spans|otelcol_receiver_refused_metric_points|otelcol_exporter_send_failed_metric_points|otelcol_receiver_refused_log_records|otelcol_exporter_send_failed_log_records|otelcol_receiver_refused_spans_total|otelcol_exporter_send_failed_spans_total|otelcol_receiver_refused_metric_points_total|otelcol_exporter_send_failed_metric_points_total|otelcol_receiver_refused_log_records_total|otelcol_exporter_send_failed_log_records_total)$")'+ - 'not IsMatch(name, "^(up|otelcol_exporter_queue_size|otelcol_exporter_queue_capacity|otelcol_receiver_refused_spans|otelcol_exporter_send_failed_spans|otelcol_receiver_refused_metric_points|otelcol_exporter_send_failed_metric_points|otelcol_receiver_refused_log_records|otelcol_exporter_send_failed_log_records|otelcol_receiver_refused_spans_total|otelcol_exporter_send_failed_spans_total|otelcol_receiver_refused_metric_points_total|otelcol_exporter_send_failed_metric_points_total|otelcol_receiver_refused_log_records_total|otelcol_exporter_send_failed_log_records_total|otelcol_processor_filter_spans_filtered|otelcol_processor_filter_spans_filtered_total)$")'+ datapoint:+ - 'IsMatch(metric.name, "^otelcol_processor_filter_spans_filtered(_total)?$") and attributes["filter"] != "filter/remote_linked_spans"'transform/collector_self_metrics:error_mode: propagatemetric_statements:@@ -318,6 +320,7 @@ processors:- set(schema_url, "")- context: metricstatements:+ - 'set(name, "otelcol_processor_filter_spans_filtered") where name == "otelcol_processor_filter_spans_filtered_total"'- 'set(name, "otelcol_receiver_refused_spans") where name == "otelcol_receiver_refused_spans_total"'- 'set(name, "otelcol_exporter_send_failed_spans") where name == "otelcol_exporter_send_failed_spans_total"'- 'set(name, "otelcol_receiver_refused_metric_points") where name == "otelcol_receiver_refused_metric_points_total"'@@ -329,6 +332,8 @@ processors:- context: datapointstatements:- 'keep_keys(attributes, []) where metric.name == "up"'+ - 'keep_keys(attributes, []) where metric.name == "otelcol_processor_filter_spans_filtered"'+ - 'set(attributes["filter"], "filter/remote_linked_spans") where metric.name == "otelcol_processor_filter_spans_filtered"'- 'keep_keys(attributes, ["exporter", "data_type"]) where IsMatch(metric.name, "^(otelcol_exporter_queue_size|otelcol_exporter_queue_capacity)$")'- 'keep_keys(attributes, ["receiver", "transport"]) where IsMatch(metric.name, "^(otelcol_receiver_refused_spans|otelcol_receiver_refused_metric_points|otelcol_receiver_refused_log_records)$")'- 'keep_keys(attributes, ["exporter", "transport"]) where IsMatch(metric.name, "^(otelcol_exporter_send_failed_spans|otelcol_exporter_send_failed_metric_points|otelcol_exporter_send_failed_log_records)$")'@@ -362,7 +367,8 @@ processors:- 'resource.attributes["service.name"] != "sie-config" and resource.attributes["service.name"] != "sie-dispatcher" and resource.attributes["service.name"] != "sie-worker" and resource.attributes["service.name"] != "sie-worker-sidecar"'# Collector 0.119 parses but does not execute in-place link-slice clearing.# Fail closed by dropping the complete linked span on the remote branch;- # the separate local trace branch remains byte-for-byte unchanged.+ # the separate local trace branch retains the original. Safe per-request+ # timing leaves (.request) have no links and survive this same guard.filter/remote_linked_spans:error_mode: propagatetraces:@@ -380,7 +386,17 @@ processors:trace_statements:- context: resourcestatements:- - keep_keys(attributes, ["service.name", "service.instance.id", "deployment.environment", "cloud.region", "service.version"])+ - set(cache["service.name"], attributes["service.name"]) where IsString(attributes["service.name"])+ - set(cache["service.instance.id"], attributes["service.instance.id"]) where IsString(attributes["service.instance.id"])+ - set(cache["deployment.environment"], attributes["deployment.environment"]) where IsString(attributes["deployment.environment"])+ - set(cache["cloud.region"], attributes["cloud.region"]) where IsString(attributes["cloud.region"])+ - set(cache["service.version"], attributes["service.version"]) where IsString(attributes["service.version"])+ - keep_keys(attributes, [])+ - set(attributes["service.name"], cache["service.name"])+ - set(attributes["service.instance.id"], cache["service.instance.id"])+ - set(attributes["deployment.environment"], cache["deployment.environment"])+ - set(attributes["cloud.region"], cache["cloud.region"])+ - set(attributes["service.version"], cache["service.version"])- set(schema_url, "")- context: scopestatements:@@ -394,7 +410,7 @@ processors:- set(status.message, "")- set(trace_state, "")- set(links, [])- - 'set(name, "other") where name != "gateway.request" and name != "gateway.publish" and name != "gateway.proxy" and name != "gateway.proxy_chat" and name != "gateway.proxy_request" and name != "gateway.proxy_generate" and name != "sidecar.dispatch" and name != "worker.run_batch" and name != "worker.streaming_processor" and name != "encode" and name != "score" and name != "extract" and name != "generate" and name != "openai_embeddings" and name != "chat_completions" and name != "rerank" and name != "other"'+ - 'set(name, "other") where name != "gateway.request" and name != "gateway.publish" and name != "gateway.proxy" and name != "gateway.proxy_chat" and name != "gateway.proxy_request" and name != "gateway.proxy_generate" and name != "sidecar.dispatch" and name != "worker.run_batch" and name != "worker.run_batch.request" and name != "sidecar.dispatch.request" and name != "worker.streaming_processor" and name != "encode" and name != "score" and name != "extract" and name != "generate" and name != "openai_embeddings" and name != "chat_completions" and name != "rerank" and name != "other"'{{- end }}{{- if $logsEnabled }}# Logs are allowlisted just like metrics are declared: only the fixed,diff --git a/packages/sie_server/src/sie_server/observability/batch_fanin.py b/packages/sie_server/src/sie_server/observability/batch_fanin.pynew file mode 100644index 000000000..48290c2bf--- /dev/null+++ b/packages/sie_server/src/sie_server/observability/batch_fanin.py@@ -0,0 +1,86 @@+"""Per-request timing views of shared batches, before the bounded export queue.++The original span (including links) remains available to local tracing. The+collector independently removes it from the remote branch. These leaf spans+represent the same shared interval, not additional execution or per-item work.+"""++from __future__ import annotations++from collections.abc import Iterator++from opentelemetry.context import Context+from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor+from opentelemetry.sdk.trace.id_generator import RandomIdGenerator+from opentelemetry.sdk.util.instrumentation import InstrumentationScope+from opentelemetry.trace import SpanContext, Status, TraceState++_BATCH_NAMES = {"worker.run_batch": "worker.run_batch.request", "sidecar.dispatch": "sidecar.dispatch.request"}+_IDS = RandomIdGenerator()+_SCOPE = InstrumentationScope("sie.batch_fanin")+++def batch_request_spans(span: ReadableSpan) -> Iterator[ReadableSpan]:+ """Project only recorded, sampled batches onto distinct sampled parents.++ Deduplicate by numeric trace/span identity, never by untrusted tracestate.+ No recovery is possible for an unsampled batch or SDK-discarded links.+ """+ name = _BATCH_NAMES.get(span.name)+ context = span.context+ if name is None or not span.links or context is None or not context.trace_flags.sampled:+ return+ seen: set[tuple[int, int]] = set()+ primary = (+ SpanContext(context.trace_id, span.parent.span_id, span.parent.is_remote, context.trace_flags, TraceState())+ if span.parent is not None+ else None+ )+ parents = [primary, *(link.context for link in span.links)]+ for parent in parents:+ if parent is None or not parent.is_valid or not parent.trace_flags.sampled:+ continue+ key = (parent.trace_id, parent.span_id)+ if key in seen:+ continue+ seen.add(key)+ safe_parent = SpanContext(parent.trace_id, parent.span_id, parent.is_remote, parent.trace_flags, TraceState())+ yield ReadableSpan(+ name=name,+ context=SpanContext(parent.trace_id, _IDS.generate_span_id(), False, parent.trace_flags, TraceState()),+ parent=safe_parent,+ resource=span.resource,+ attributes={},+ events=(),+ links=(),+ kind=span.kind,+ status=Status(span.status.status_code),+ start_time=span.start_time,+ end_time=span.end_time,+ instrumentation_scope=_SCOPE,+ )+++class BatchFanInSpanProcessor(SpanProcessor):+ """Keep originals and enqueue safe timing leaves through the same processor.++ Wrap the existing BatchSpanProcessor so its queue, batching, shutdown and+ loss behavior remain authoritative; never expand a batch after dequeueing.+ """++ def __init__(self, inner: SpanProcessor) -> None:+ self._inner = inner++ def on_start(self, span: Span, parent_context: Context | None = None) -> None:+ self._inner.on_start(span, parent_context)++ def on_end(self, span: ReadableSpan) -> None:+ self._inner.on_end(span)+ for request_span in batch_request_spans(span):+ self._inner.on_end(request_span)++ def shutdown(self) -> None:+ self._inner.shutdown()++ def force_flush(self, timeout_millis: int = 30000) -> bool:+ return self._inner.force_flush(timeout_millis)diff --git a/packages/sie_server/src/sie_server/observability/tracing.py b/packages/sie_server/src/sie_server/observability/tracing.pyindex 0bf44a2da..941c7115d 100644--- a/packages/sie_server/src/sie_server/observability/tracing.py+++ b/packages/sie_server/src/sie_server/observability/tracing.py@@ -30,6 +30,7 @@ from opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessor+from sie_server.observability.batch_fanin import BatchFanInSpanProcessorfrom sie_server.observability.worker_telemetry import worker_resource_attributesif TYPE_CHECKING:@@ -180,7 +181,7 @@ def setup_tracing(app: FastAPI) -> None:# can't stall on an unreachable collector.try:exporter = _build_span_exporter(config)- provider.add_span_processor(BatchSpanProcessor(exporter))+ provider.add_span_processor(BatchFanInSpanProcessor(BatchSpanProcessor(exporter)))logger.info("OTLP exporter configured for endpoint: %s (%s)",_endpoint_origin_for_log(config.endpoint),diff --git a/packages/sie_server/tests/observability/test_batch_fanin.py b/packages/sie_server/tests/observability/test_batch_fanin.pynew file mode 100644index 000000000..f6d25efd6--- /dev/null+++ b/packages/sie_server/tests/observability/test_batch_fanin.py@@ -0,0 +1,102 @@+"""Exercise real SDK span completion and the safe shared-duration representation."""++from unittest.mock import Mock++import pytest+from opentelemetry.sdk.resources import Resource+from opentelemetry.sdk.trace import SpanLimits, TracerProvider+from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanProcessor+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from opentelemetry.sdk.trace.sampling import ALWAYS_OFF+from opentelemetry.trace import (+ INVALID_SPAN_CONTEXT,+ Link,+ NonRecordingSpan,+ SpanContext,+ Status,+ StatusCode,+ TraceFlags,+ TraceState,+ set_span_in_context,+)+from sie_server.observability.batch_fanin import BatchFanInSpanProcessor, batch_request_spans+++def parent(trace_id: int = 1, span_id: int = 2, sampled: bool = True) -> SpanContext:+ return SpanContext(trace_id, span_id, True, TraceFlags(int(sampled)), TraceState([("vendor", "private")]))+++def record(name="worker.run_batch", links=(), *, span_limits=None, sampler=None):+ exporter = InMemorySpanExporter()+ kwargs = {"sampler": sampler} if sampler is not None else {}+ provider = TracerProvider(resource=Resource({"service.name": "sie-worker"}), span_limits=span_limits, **kwargs)+ provider.add_span_processor(BatchFanInSpanProcessor(SimpleSpanProcessor(exporter)))+ tracer = provider.get_tracer("local.scope", attributes={"secret": "private"})+ span = tracer.start_span(name, context=set_span_in_context(NonRecordingSpan(parent())), links=links, start_time=100)+ span.set_attribute("customer", "private")+ span.add_event("private exception", {"payload": "private"})+ span.set_status(Status(StatusCode.ERROR, "private error"))+ span.end(end_time=200)+ assert provider.force_flush()+ spans = exporter.get_finished_spans()+ provider.shutdown()+ return spans++[email protected]("name", ["worker.run_batch", "sidecar.dispatch"])+def test_projects_distinct_sampled_parents_without_mutating_local_span(name):+ # Two traces and two distinct parents within one trace; duplicates with+ # different tracestate must not make additional duration observations.+ links = [Link(parent(3, 4), {"customer": "private"}), Link(parent(1, 5)), Link(parent(3, 4))]+ original, *views = record(name, links)+ assert original.links == tuple(links)+ assert original.attributes["customer"] == "private"+ assert original.status.description == "private error"+ assert original.context.trace_state.get("vendor") == "private"+ assert len(original.events) == 1+ assert {(s.context.trace_id, s.parent.span_id) for s in views} == {(1, 2), (3, 4), (1, 5)}+ assert len({s.context.span_id for s in (original, *views)}) == 4+ for view in views:+ assert view.name == f"{name}.request"+ assert (view.start_time, view.end_time, view.kind) == (100, 200, original.kind)+ assert view.status.status_code == StatusCode.ERROR+ assert view.status.description is None+ assert not view.attributes+ assert not view.events+ assert not view.links+ assert not view.context.trace_state+ assert not view.parent.trace_state+ assert view.instrumentation_scope.name == "sie.batch_fanin"+ assert not view.instrumentation_scope.attributes+ # A projection is terminal: it cannot recursively generate more spans.+ assert not list(batch_request_spans(view))+++def test_one_parent_and_unknown_names_remain_unchanged():+ assert [s.name for s in record()] == ["worker.run_batch"]+ assert [s.name for s in record("arbitrary", [Link(parent(3, 4))])] == ["arbitrary"]+++def test_invalid_duplicate_and_unsampled_links_do_not_create_parents():+ spans = record(links=[Link(INVALID_SPAN_CONTEXT), Link(parent()), Link(parent(3, 4, False))])+ assert len(spans) == 2+ assert spans[1].parent.span_id == 2+++def test_projection_does_not_override_sampling_or_recover_sdk_dropped_links():+ assert record(links=[Link(parent(3, 4))], sampler=ALWAYS_OFF) == ()+ original, *views = record(links=[Link(parent(3, 4)), Link(parent(5, 6))], span_limits=SpanLimits(max_links=1))+ assert original.dropped_links == 1+ assert len(views) == 2 # primary and the single retained link only+++def test_processor_delegates_lifecycle_and_uses_original_queue():+ inner = Mock(spec=SpanProcessor)+ processor = BatchFanInSpanProcessor(inner)+ span = record()[0]+ processor.on_end(span)+ inner.on_end.assert_called_once_with(span)+ assert processor.force_flush(17) is inner.force_flush.return_value+ inner.force_flush.assert_called_once_with(17)+ processor.shutdown()+ inner.shutdown.assert_called_once_with()diff --git a/packages/sie_server_rust/src/observability/tracing.rs b/packages/sie_server_rust/src/observability/tracing.rsindex 073627ac7..529411f68 100644--- a/packages/sie_server_rust/src/observability/tracing.rs+++ b/packages/sie_server_rust/src/observability/tracing.rs@@ -111,7 +111,9 @@ fn init_tracer(config: &SignalExportConfig) -> Result<Tracer, String> {let provider = SdkTracerProvider::builder().with_resource(telemetry_resource())- .with_batch_exporter(exporter)+ .with_span_processor(sie_telemetry::batch_fanin::BatchFanInSpanProcessor::new(+ opentelemetry_sdk::trace::BatchSpanProcessor::builder(exporter).build(),+ )).build();let tracer = provider.tracer("sie-worker");global::set_tracer_provider(provider.clone());diff --git a/packages/sie_server_sidecar/src/observability/tracing.rs b/packages/sie_server_sidecar/src/observability/tracing.rsindex e3a5e61bc..625374043 100644--- a/packages/sie_server_sidecar/src/observability/tracing.rs+++ b/packages/sie_server_sidecar/src/observability/tracing.rs@@ -261,7 +261,9 @@ fn init_tracer(config: &SignalExportConfig) -> Result<Tracer, String> {let provider = SdkTracerProvider::builder().with_resource(otlp_resource(&service_name))- .with_batch_exporter(exporter)+ .with_span_processor(sie_telemetry::batch_fanin::BatchFanInSpanProcessor::new(+ opentelemetry_sdk::trace::BatchSpanProcessor::builder(exporter).build(),+ )).build();let tracer = provider.tracer("sie-worker-sidecar");global::set_tracer_provider(provider.clone());diff --git a/packages/sie_telemetry/src/batch_fanin.rs b/packages/sie_telemetry/src/batch_fanin.rsnew file mode 100644index 000000000..b4e2bc6ab--- /dev/null+++ b/packages/sie_telemetry/src/batch_fanin.rs@@ -0,0 +1,267 @@+//! Per-request timing leaves for shared batches, ahead of the bounded queue.+//!+//! Originals retain rich local links. Remote privacy filtering still drops+//! linked originals; these views carry only a parent, fresh ID, shared timing,+//! kind and status code. They are not additional execution or detailed parents.++use std::collections::HashSet;+use std::time::Duration;++use opentelemetry::trace::{SpanContext, Status, TraceState};+use opentelemetry::{Context, InstrumentationScope};+use opentelemetry_sdk::error::OTelSdkResult;+use opentelemetry_sdk::trace::{IdGenerator, RandomIdGenerator, Span, SpanData, SpanProcessor};+use opentelemetry_sdk::Resource;++/// Add timing leaves without bypassing the wrapped processor's queue limits.+#[derive(Debug)]+pub struct BatchFanInSpanProcessor<P> {+ inner: P,+}++impl<P> BatchFanInSpanProcessor<P> {+ pub fn new(inner: P) -> Self {+ Self { inner }+ }+}++impl<P: SpanProcessor> SpanProcessor for BatchFanInSpanProcessor<P> {+ fn on_start(&self, span: &mut Span, cx: &Context) {+ self.inner.on_start(span, cx);+ }++ fn on_end(&self, span: SpanData) {+ let projections = batch_request_spans(&span);+ self.inner.on_end(span);+ for projection in projections {+ self.inner.on_end(projection);+ }+ }++ fn force_flush(&self) -> OTelSdkResult {+ self.inner.force_flush()+ }++ fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult {+ self.inner.shutdown_with_timeout(timeout)+ }++ fn set_resource(&mut self, resource: &Resource) {+ self.inner.set_resource(resource);+ }+}++fn batch_request_spans(span: &SpanData) -> Vec<SpanData> {+ let name = match span.name.as_ref() {+ "worker.run_batch" => "worker.run_batch.request",+ "sidecar.dispatch" => "sidecar.dispatch.request",+ _ => return Vec::new(),+ };+ if span.links.links.is_empty() || !span.span_context.is_sampled() {+ return Vec::new();+ }+ // The recorded batch inherited its primary parent's sampling decision.+ let primary = SpanContext::new(+ span.span_context.trace_id(),+ span.parent_span_id,+ span.span_context.trace_flags(),+ span.parent_span_is_remote,+ TraceState::default(),+ );+ let mut seen = HashSet::new();+ std::iter::once(&primary)+ .chain(span.links.links.iter().map(|link| &link.span_context))+ .filter(|parent| {+ parent.is_valid()+ && parent.is_sampled()+ && seen.insert((parent.trace_id(), parent.span_id()))+ })+ .map(|parent| SpanData {+ span_context: SpanContext::new(+ parent.trace_id(),+ RandomIdGenerator::default().new_span_id(),+ parent.trace_flags(),+ false,+ TraceState::default(),+ ),+ parent_span_id: parent.span_id(),+ parent_span_is_remote: parent.is_remote(),+ span_kind: span.span_kind.clone(),+ name: name.into(),+ start_time: span.start_time,+ end_time: span.end_time,+ attributes: Vec::new(),+ dropped_attributes_count: 0,+ events: Default::default(),+ links: Default::default(),+ status: match span.status {+ Status::Error { .. } => Status::error(""),+ Status::Ok => Status::Ok,+ Status::Unset => Status::Unset,+ },+ instrumentation_scope: InstrumentationScope::builder("sie.batch_fanin").build(),+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use opentelemetry::trace::{+ Link, Span as _, SpanId, TraceContextExt, TraceFlags, TraceId, Tracer, TracerProvider,+ };+ use opentelemetry::KeyValue;+ use opentelemetry_sdk::trace::{+ InMemorySpanExporter, Sampler, SdkTracerProvider, SimpleSpanProcessor,+ };++ fn parent(trace: u128, span: u64, sampled: bool) -> SpanContext {+ SpanContext::new(+ TraceId::from(trace),+ SpanId::from(span),+ if sampled {+ TraceFlags::SAMPLED+ } else {+ TraceFlags::default()+ },+ true,+ TraceState::from_key_value([("vendor", "private")]).unwrap(),+ )+ }++ fn record(+ name: &'static str,+ links: Vec<Link>,+ sampler: Sampler,+ max_links: u32,+ ) -> Vec<SpanData> {+ let exporter = InMemorySpanExporter::default();+ let provider = SdkTracerProvider::builder()+ .with_sampler(sampler)+ .with_max_links_per_span(max_links)+ .with_span_processor(BatchFanInSpanProcessor::new(SimpleSpanProcessor::new(+ exporter.clone(),+ )))+ .build();+ let tracer = provider.tracer("local.scope");+ let cx = Context::new().with_remote_span_context(parent(1, 2, true));+ let mut span = tracer+ .span_builder(name)+ .with_links(links)+ .with_start_time(std::time::UNIX_EPOCH)+ .start_with_context(&tracer, &cx);+ span.set_attribute(KeyValue::new("customer", "private"));+ span.add_event(+ "private exception",+ vec![KeyValue::new("payload", "private")],+ );+ span.set_status(Status::error("private error"));+ span.end_with_timestamp(std::time::UNIX_EPOCH + Duration::from_secs(1));+ provider.force_flush().unwrap();+ let spans = exporter.get_finished_spans().unwrap();+ provider.shutdown().unwrap();+ spans+ }++ #[test]+ fn projects_distinct_parents_with_safe_fields_and_exact_timing() {+ for name in ["worker.run_batch", "sidecar.dispatch"] {+ let links = vec![+ Link::new(+ parent(3, 4, true),+ vec![KeyValue::new("customer", "private")],+ 0,+ ),+ Link::new(parent(1, 5, true), Vec::new(), 0),+ Link::new(parent(3, 4, true), Vec::new(), 0),+ ];+ let spans = record(name, links.clone(), Sampler::AlwaysOn, 128);+ assert_eq!(spans.len(), 4);+ let original = &spans[0];+ assert_eq!(original.links.links, links);+ assert_eq!(+ original.attributes,+ vec![KeyValue::new("customer", "private")]+ );+ assert_eq!(original.status, Status::error("private error"));+ assert_eq!(original.events.len(), 1);+ assert_eq!(+ original.span_context.trace_state().header(),+ "vendor=private"+ );+ let parents: HashSet<_> = spans[1..]+ .iter()+ .map(|s| (s.span_context.trace_id(), s.parent_span_id))+ .collect();+ assert_eq!(+ parents,+ [(1u128, 2u64), (3, 4), (1, 5)]+ .map(|(t, s)| (TraceId::from(t), SpanId::from(s)))+ .into()+ );+ assert_eq!(+ spans+ .iter()+ .map(|s| s.span_context.span_id())+ .collect::<HashSet<_>>()+ .len(),+ 4+ );+ for view in &spans[1..] {+ assert_eq!(view.name, format!("{name}.request"));+ assert_eq!(view.start_time, original.start_time);+ assert_eq!(view.end_time, original.end_time);+ assert_eq!(view.span_kind, original.span_kind);+ assert_eq!(view.status, Status::error(""));+ assert!(+ view.attributes.is_empty() && view.events.is_empty() && view.links.is_empty()+ );+ assert!(view.span_context.trace_state().header().is_empty());+ assert_eq!(view.instrumentation_scope.name(), "sie.batch_fanin");+ assert!(batch_request_spans(view).is_empty());+ }+ }+ }++ #[test]+ fn ignores_unlinked_unknown_invalid_duplicate_and_unsampled_contexts() {+ assert_eq!(+ record("worker.run_batch", Vec::new(), Sampler::AlwaysOn, 128).len(),+ 1+ );+ assert_eq!(+ record(+ "unknown",+ vec![Link::new(parent(3, 4, true), Vec::new(), 0)],+ Sampler::AlwaysOn,+ 128+ )+ .len(),+ 1+ );+ let spans = record(+ "worker.run_batch",+ vec![+ Link::new(SpanContext::empty_context(), Vec::new(), 0),+ Link::new(parent(1, 2, true), Vec::new(), 0),+ Link::new(parent(3, 4, false), Vec::new(), 0),+ ],+ Sampler::AlwaysOn,+ 128,+ );+ assert_eq!(spans.len(), 2);+ assert_eq!(spans[1].parent_span_id, SpanId::from(2u64));+ }++ #[test]+ fn respects_sampling_and_retained_link_limit() {+ let links = vec![+ Link::new(parent(3, 4, true), Vec::new(), 0),+ Link::new(parent(5, 6, true), Vec::new(), 0),+ ];+ assert!(record("worker.run_batch", links.clone(), Sampler::AlwaysOff, 128).is_empty());+ let spans = record("worker.run_batch", links, Sampler::AlwaysOn, 1);+ assert_eq!(spans[0].links.dropped_count, 1);+ assert_eq!(spans.len(), 3);+ }+}diff --git a/packages/sie_telemetry/src/lib.rs b/packages/sie_telemetry/src/lib.rsindex c8fedf025..1d9634dad 100644--- a/packages/sie_telemetry/src/lib.rs+++ b/packages/sie_telemetry/src/lib.rs@@ -13,6 +13,7 @@//! pipeline. Those are per-crate surfaces (their name sets are disjoint;//! see `telemetry/contract.yaml` and the parity test).+pub mod batch_fanin;pub mod env;pub mod exporters;pub mod propagation;diff --git a/telemetry/README.md b/telemetry/README.mdindex e1e9a926b..8fa4a271d 100644--- a/telemetry/README.md+++ b/telemetry/README.md@@ -13,10 +13,9 @@ lifecycle signals remain excluded until a deployed producer owns them;undeclared new instruments are not permitted.The current inventory is 122 application families: 120 may reach the remote-OTLP branch and two remain Prometheus-only controls. Nine additional,-exact collector-self families form a separate operational allowlist. The-Better Stack dashboard code therefore covers 129 remotely eligible families-without turning collector self-telemetry into a version-dependent wildcard.+OTLP branch and two remain Prometheus-only controls. Ten additional,+exact collector-self families form a separate operational allowlist without+turning collector self-telemetry into a version-dependent wildcard.`sie.gateway.pool.pinned_model.loaded` is intentionally Prometheus-only. Its`pool` attribute is an API-defined logical pool name (`logical_pool`), which is@@ -177,11 +176,43 @@ forwarder. It preserves trace/span/parent IDs, start/end timestamps, kind,status code, flags, a bounded span name, and the five safe resource identityfields declared in `contract.yaml`. It removes every span event and span/scopeattribute, clears status text, inbound trace-state text, and scope identity,-drops unknown resource attributes, and collapses unknown span names to `other`.+reconstructs the five retained string resource fields after receiver identity+stamping (discarding duplicate keys and non-string values), and collapses+unknown span names to `other`.Because each link can carry arbitrary attributes and trace-state text, and thepinned collector cannot reliably mutate links in place, the remote branch-drops the entire linked span. Unlinked sibling spans continue through the-allowlist; the unchanged local OSS branch may retain linked spans. When Helm is+drops the entire linked span. Do not remove this guard: Collector 0.119 accepts+`set(links, [])` but leaves the links untouched at runtime.++For `worker.run_batch` and `sidecar.dispatch`, the shared SDK processor adds+`.request` timing leaves when the recorded, sampled original has links. Each+leaf has a fresh span ID under a distinct valid contributing parent, the exact+shared start/end time and kind, and the original status code without text. It+contains no span attributes, events, links or tracestate. The original and its+rich links stay unchanged locally. Remote filtering drops the linked original+and retains the safe leaves; ordinary unlinked batches need no extra spans.+Repeated parent IDs are deduplicated even if tracestate differs, and unsampled+linked parents are not promoted into sampled traces.++These leaves show each request's participation in shared execution. Their+durations must not be summed as independent compute, and they do not reparent+detailed descendants: those still belong to the original shared span, which+is absent remotely. A sampled linked request cannot recover an unsampled+original batch. SDK-discarded links likewise cannot be reconstructed; the+original's dropped-link count remains visible locally. Leaves enter the same+bounded export queue as originals, so fan-in adds queue pressure and can incur+the existing exporter losses. No sampler, collector pin, metric/control path,+or log schema changes are required.++The collector's isolated self pipeline exports+`otelcol_processor_filter_spans_filtered` only for+`filter=filter/remote_linked_spans`, retaining no other point attributes. This+counts removed original spans, not lost requests: successfully projected leaves+can accompany each dropped original. It distinguishes privacy filtering from+receiver refusal or exporter failure. It cannot measure head-sampling loss,+producer queue drops, or SDK-discarded links.++Unlinked sibling spans continue through the allowlist. When Helm isconfigured with Tempo as well as Better Stack, those are separate collectorpipelines: the local OSS branch receives the producer trace unchanged, whileonly the remote branch runs the privacy processors. Producers still export onediff --git a/telemetry/contract.yaml b/telemetry/contract.yamlindex 643169dbb..31bb6ed1b 100644--- a/telemetry/contract.yaml+++ b/telemetry/contract.yaml@@ -632,6 +632,8 @@ traces:unknown_service: droplocal_oss_action: retain_producer_identity_unchangedresource_attributes:+ duplicate_keys: reconstruct_first_validated_scalar_after_receiver_identity_stamping+ non_string_identity: drop_fieldallow:- service.name- service.instance.id@@ -667,6 +669,23 @@ traces:reason: pinned_collector_cannot_reliably_clear_link_attributes_or_trace_statetransform_defense: set_links_empty_for_future_runtime_supportlocal_oss_action: retain_unchanged+ drop_counter: otelcol_processor_filter_spans_filtered+ drop_counter_filter: filter/remote_linked_spans+ request_views:+ producer: shared_sdk_processor_before_bounded_export_queue+ source_names: [worker.run_batch, sidecar.dispatch]+ names: [worker.run_batch.request, sidecar.dispatch.request]+ trigger: recorded_sampled_source_with_links+ parents: distinct_valid_sampled_trace_id_and_span_id_pairs+ primary_sampling: inherit_source_span_sampling+ span_id: fresh_per_view+ timing_and_kind: exact_source_interval_and_kind+ status: source_code_without_message+ attributes_events_links_trace_state: empty+ semantics: leaf_observation_of_shared_execution_not_additional_work+ descendants: remain_children_of_original_shared_span+ limits: source_sampling_and_sdk_link_limits_and_existing_export_queue+ loss: cannot_recover_unsampled_sources_or_discarded_linksname:unknown: otherallow:@@ -678,6 +697,8 @@ traces:- gateway.proxy_generate- sidecar.dispatch- worker.run_batch+ - worker.run_batch.request+ - sidecar.dispatch.request- worker.streaming_processor- encode- score@@ -2546,6 +2567,7 @@ collector_self_metrics:# Prometheus counter exposition adds `_total`; normalize only these exact# source aliases back to the stable OTLP family names below.prometheus_input_aliases:+ otelcol_processor_filter_spans_filtered_total: otelcol_processor_filter_spans_filteredotelcol_receiver_refused_spans_total: otelcol_receiver_refused_spansotelcol_exporter_send_failed_spans_total: otelcol_exporter_send_failed_spansotelcol_receiver_refused_metric_points_total: otelcol_receiver_refused_metric_points@@ -2553,6 +2575,10 @@ collector_self_metrics:otelcol_receiver_refused_log_records_total: otelcol_receiver_refused_log_recordsotelcol_exporter_send_failed_log_records_total: otelcol_exporter_send_failed_log_recordsmetrics:+ - name: otelcol_processor_filter_spans_filtered+ attributes: [filter]+ filter_allow: [filter/remote_linked_spans]+ meaning: original_linked_spans_removed_by_remote_privacy_not_transport_loss- name: upattributes: []- name: otelcol_exporter_queue_sizediff --git a/tools/ci/tests/test_collector_trace_privacy.py b/tools/ci/tests/test_collector_trace_privacy.pynew file mode 100644index 000000000..c37406f46--- /dev/null+++ b/tools/ci/tests/test_collector_trace_privacy.py@@ -0,0 +1,302 @@+"""Pinned collector runtime proof; no credentials, vendor traffic or deployment.++Run after `mise run helm -- dependencies` with pytest -m docker. Processor+lists and statements come from the real rendered chart, not a test facsimile.+Only receiver bindings, self-scrape interval and exporter destinations change.+"""++from __future__ import annotations++import copy+import json+import subprocess+import time+import urllib.request+from pathlib import Path++import pytest+import yaml+from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans+from opentelemetry.sdk.resources import Resource+from opentelemetry.sdk.trace import ReadableSpan, TracerProvider+from opentelemetry.sdk.trace.export import SimpleSpanProcessor+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from opentelemetry.trace import Link, Status, StatusCode, get_current_span+from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator+from sie_server.observability.batch_fanin import BatchFanInSpanProcessor++ROOT = Path(__file__).resolve().parents[3]+pytestmark = pytest.mark.docker+SENTINEL = "private-payload-sentinel"+++def run(*args: str, include_stderr: bool = False) -> str:+ result = subprocess.run(args, cwd=ROOT, text=True, capture_output=True, check=True, timeout=120) # noqa: S603 - fixed local test commands+ return (result.stdout + (result.stderr if include_stderr else "")).strip()+++def rendered_config():+ rendered = run(+ "mise",+ "exec",+ "--",+ "helm",+ "template",+ "sie",+ "deploy/helm/sie-cluster",+ "--namespace",+ "sie",+ "--show-only",+ "templates/otel-collector.yaml",+ "--set",+ "payloadStore.enabled=false",+ "--set",+ "observability.tracing.enabled=true",+ "--set",+ "observability.otel.collector.install=true",+ "--set",+ "observability.otel.collector.traces.endpoint=local:4317",+ "--set",+ "observability.otel.collector.betterStack.enabled=true",+ "--set",+ "observability.otel.collector.betterStack.endpoint=https://example.invalid",+ "--set",+ "observability.otel.collector.betterStack.existingSecret=synthetic",+ "--set",+ "observability.otel.resource.deploymentEnvironment=dev",+ "--set",+ "observability.otel.resource.cloudRegion=test-region",+ )+ documents = list(yaml.safe_load_all(rendered))+ config = next(d for d in documents if d and d.get("kind") == "ConfigMap")+ deployment = next(d for d in documents if d and d.get("kind") == "Deployment")+ image = deployment["spec"]["template"]["spec"]["containers"][0]["image"]+ return yaml.safe_load(config["data"]["collector.yaml"]), image+++def context(trace: int, parent: int, *, sampled=True):+ return TraceContextTextMapPropagator().extract(+ {+ "traceparent": f"00-{trace:032x}-{parent:016x}-{int(sampled):02x}",+ "tracestate": f"vendor={SENTINEL}",+ }+ )+++def sample_spans() -> list[ReadableSpan]:+ exporter = InMemorySpanExporter()+ provider = TracerProvider(+ resource=Resource(+ {+ "service.name": "sie-worker",+ "service.instance.id": "worker-instance",+ "service.version": "test-version",+ "customer": SENTINEL,+ }+ )+ )+ provider.add_span_processor(BatchFanInSpanProcessor(SimpleSpanProcessor(exporter)))+ tracer = provider.get_tracer(SENTINEL, attributes={"customer": SENTINEL})+ # Distinct traces, same-trace distinct parents, and duplicate parents.+ links = [+ Link(get_current_span(context(t, s)).get_span_context(), {"payload": SENTINEL})+ for t, s in [(3, 4), (1, 5), (3, 4)]+ ]+ links += [Link(get_current_span(context(7, 8, sampled=False)).get_span_context())]+ with tracer.start_as_current_span("worker.run_batch", context=context(1, 2), links=links) as span:+ span.set_attribute("customer", SENTINEL)+ span.add_event(SENTINEL, {"exception.message": SENTINEL})+ span.set_status(Status(StatusCode.ERROR, SENTINEL))+ with tracer.start_as_current_span(+ "sidecar.dispatch",+ context=context(11, 12),+ links=[Link(get_current_span(context(13, 14)).get_span_context())],+ ):+ pass+ # An ordinary one-parent batch survives unchanged structurally.+ with tracer.start_as_current_span("sidecar.dispatch", context=context(9, 10)):+ pass+ # Malformed W3C context becomes a root; never invent a contributing parent.+ invalid = TraceContextTextMapPropagator().extract({"traceparent": "not-a-context"})+ with tracer.start_as_current_span("worker.run_batch", context=invalid):+ pass+ provider.force_flush()+ spans = list(exporter.get_finished_spans())+ provider.shutdown()+ return spans+++def read_spans(path: Path) -> list[dict]:+ if not path.exists():+ return []+ lines = path.read_text().splitlines()+ try:+ return [+ span+ for line in lines+ for rs in json.loads(line).get("resourceSpans", [])+ for scope in rs["scopeSpans"]+ for span in scope["spans"]+ ]+ except json.JSONDecodeError:+ return [] # the file exporter may be finishing its last line+++def wait_for(predicate, seconds=15):+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ try:+ value = predicate()+ if value:+ return value+ except (OSError, ValueError):+ pass+ time.sleep(0.05)+ raise AssertionError("collector did not become ready or flush the expected output")++[email protected]("receiver", ["gateway", "application"])+def test_batch_fanin_survives_remote_privacy_with_local_links_intact(tmp_path, receiver):+ config, image = rendered_config()+ assert image.endswith(":0.119.0"), "revalidate the runtime proof when changing the pin"+ # Preserve production processor ordering; redirect only outputs and sockets.+ config["exporters"] = {+ f"file/{name}": {"path": f"/out/{name}.json", "flush_interval": "100ms"}+ for name in ["local", "remote", "self", "unsafe"]+ }+ for name, pipeline in config["service"]["pipelines"].items():+ sink = "self" if name.startswith("metrics/") else "remote" if "betterstack" in name else "local"+ pipeline["exporters"] = [f"file/{sink}"]+ # Prove that merely deleting the linked-span guard would leak on this pin.+ unsafe = copy.deepcopy(config["service"]["pipelines"][f"traces/betterstack/{receiver}"])+ unsafe["processors"].remove("filter/remote_linked_spans")+ unsafe["exporters"] = ["file/unsafe"]+ config["service"]["pipelines"]["traces/unsafe_reproduction"] = unsafe+ config["receivers"][f"otlp/{receiver}"]["protocols"]["http"] = {"endpoint": "0.0.0.0:4338"}+ telemetry_reader = config["service"]["telemetry"]["metrics"]["readers"][0]["pull"]["exporter"]["prometheus"]+ telemetry_reader["host"] = "0.0.0.0" # noqa: S104 - container-only; published on loopback+ config["processors"]["batch"]["timeout"] = "100ms"+ config["receivers"]["prometheus/self"]["config"]["scrape_configs"][0]["scrape_interval"] = "100ms"+ (tmp_path / "collector.yaml").write_text(yaml.safe_dump(config))+ container = run(+ "docker",+ "run",+ "-d",+ "--user",+ "0",+ "-p",+ "127.0.0.1::4338",+ "-p",+ "127.0.0.1::8888",+ "-p",+ "127.0.0.1::13133",+ "-v",+ f"{tmp_path}:/out",+ image,+ "--config=/out/collector.yaml",+ )+ try:+ ports = {port: run("docker", "port", container, f"{port}/tcp").split(":")[-1] for port in [4338, 8888, 13133]}+ wait_for(lambda: urllib.request.urlopen(f"http://127.0.0.1:{ports[13133]}", timeout=1).status == 200)+ source = sample_spans()+ wire = encode_spans(source)+ for resource_spans in wire.resource_spans:+ # OTTL reads the first key, while keep_keys can retain later+ # unvalidated duplicates. Remote reconstruction must remove both+ # string and nested duplicates after authoritative identity stamping.+ for key in [+ "service.name",+ "service.instance.id",+ "service.version",+ "deployment.environment",+ "cloud.region",+ ]:+ resource_spans.resource.attributes.add(key=key).value.string_value = SENTINEL+ nested = resource_spans.resource.attributes.add(key=key).value.kvlist_value+ nested.values.add(key="payload").value.string_value = SENTINEL+ # Inject fields the SDK normally validates: zero IDs and adversarial+ # link attributes/tracestate still must never cross the remote branch.+ linked = next(s for rs in wire.resource_spans for sc in rs.scope_spans for s in sc.spans if s.links)+ invalid_link = linked.links.add(trace_id=bytes(16), span_id=bytes(8), trace_state=SENTINEL)+ invalid_link.attributes.add(key="customer").value.string_value = SENTINEL+ payload = wire.SerializeToString()+ request = urllib.request.Request(+ f"http://127.0.0.1:{ports[4338]}/v1/traces",+ data=payload,+ headers={"Content-Type": "application/x-protobuf"},+ )+ with urllib.request.urlopen(request, timeout=5) as response: # noqa: S310 - fixed loopback HTTP+ assert response.status == 200+ local = wait_for(lambda: s if len(s := read_spans(tmp_path / "local.json")) == len(source) else None)+ remote = wait_for(lambda: s if len(s := read_spans(tmp_path / "remote.json")) == len(source) - 2 else None)+ unsafe_spans = wait_for(lambda: read_spans(tmp_path / "unsafe.json"))+ assert len(unsafe_spans) == len(source)+ assert any(s.get("links") for s in unsafe_spans), "0.119 no-op set(links, []) reproduction changed"+ assert SENTINEL in (tmp_path / "unsafe.json").read_text()+ assert SENTINEL in (tmp_path / "local.json").read_text()+ assert SENTINEL not in (tmp_path / "remote.json").read_text()+ for line in (tmp_path / "remote.json").read_text().splitlines():+ for resource_spans in json.loads(line)["resourceSpans"]:+ attrs = resource_spans["resource"]["attributes"]+ assert len({a["key"] for a in attrs}) == len(attrs)+ assert {a["key"]: a["value"] for a in attrs} == {+ "service.name": {"stringValue": "sie-gateway" if receiver == "gateway" else "sie-worker"},+ "service.instance.id": {"stringValue": "worker-instance"},+ "service.version": {"stringValue": "test-version"},+ "deployment.environment": {"stringValue": "dev"},+ "cloud.region": {"stringValue": "test-region"},+ }+ assert not any(+ s.get("links")+ or s.get("events")+ or s.get("attributes")+ or s.get("traceState")+ or s.get("status", {}).get("message")+ for s in remote+ )+ assert len([s for s in remote if s["name"] == "worker.run_batch.request"]) == 3+ assert len([s for s in remote if s["name"] == "sidecar.dispatch.request"]) == 2+ assert {s["spanId"] for s in remote} == {s["spanId"] for s in local if not s.get("links")}+ local_by_id = {s["spanId"]: s for s in local}+ for span in remote:+ before = local_by_id[span["spanId"]]+ for key in ["traceId", "spanId", "parentSpanId", "startTimeUnixNano", "endTimeUnixNano", "kind", "flags"]:+ assert span.get(key) == before.get(key)+ # Observe filter loss separately from transport/export failure, using+ # the pinned collector's own numeric counter (no request dimensions).+ with urllib.request.urlopen(f"http://127.0.0.1:{ports[8888]}/metrics", timeout=5) as response:+ metrics = response.read().decode()+ filtered = [+ line+ for line in metrics.splitlines()+ if line.startswith("otelcol_processor_filter_spans_filtered{")+ and 'filter="filter/remote_linked_spans"' in line+ ]+ assert filtered, metrics+ assert sum(float(line.rsplit(" ", 1)[1]) for line in filtered) == 2++ def self_points():+ path = tmp_path / "self.json"+ if not path.exists():+ return []+ points = [+ p+ for line in path.read_text().splitlines()+ for rs in json.loads(line).get("resourceMetrics", [])+ for scope in rs["scopeMetrics"]+ for metric in scope["metrics"]+ if metric["name"] == "otelcol_processor_filter_spans_filtered"+ for p in metric["sum"]["dataPoints"]+ ]+ return points if any(int(p.get("asInt", p.get("asDouble", 0))) == 2 for p in points) else []++ points = wait_for(self_points)+ for point in points:+ assert point["attributes"] == [{"key": "filter", "value": {"stringValue": "filter/remote_linked_spans"}}]+ finally:+ try:+ run("docker", "stop", "--time", "10", container)+ logs = run("docker", "logs", container, include_stderr=True)+ assert "Error: " not in logs, logs+ finally:+ run("docker", "rm", "-f", container)