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): record failures and streamed response lifecycle (#404)
Attila László Nagye4e7ec0b4a42
diff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tplindex 07fb024fc..b7fc83619 100644--- a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl+++ b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl@@ -69,7 +69,7 @@ processors:value: {{ $cloudRegion | quote }}action: upsert{{- end }}-{{- if or $metricsEnabled (and $tracesEnabled $betterStack.enabled) }}+{{- if or $metricsEnabled $logsEnabled (and $tracesEnabled $betterStack.enabled) }}# Application producers share one receiver, so service.name is retained# only after the signal-specific allowlist accepts it. Environment and# region are still collector-authored routing dimensions.@@ -509,7 +509,7 @@ processors:- set(status.message, "")- set(trace_state, "")- set(links, [])- - 'set(name, "other") where name != "gateway.request" and name != "gateway.dispatch" and name != "gateway.dispatch.ipc" and name != "gateway.dispatch.i6pn" and name != "dispatcher.dispatch" and name != "dispatcher.modal.remote" and name != "dispatcher.modal.stream" and name != "dispatcher.modal.spawn" and name != "dispatcher.websocket" and name != "dispatcher.i6pn" and name != "dispatcher.fallback" and name != "sidecar.local_ingest" and name != "worker.local_ingest" 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"'+ - 'set(name, "other") where name != "gateway.request" and name != "gateway.response_body" and name != "gateway.generation_stream" and name != "gateway.dispatch" and name != "gateway.dispatch.ipc" and name != "gateway.dispatch.i6pn" and name != "dispatcher.dispatch" and name != "dispatcher.modal.remote" and name != "dispatcher.modal.stream" and name != "dispatcher.modal.spawn" and name != "dispatcher.websocket" and name != "dispatcher.i6pn" and name != "dispatcher.fallback" and name != "sidecar.local_ingest" and name != "worker.local_ingest" 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,@@ -535,7 +535,17 @@ processors:log_statements:- context: resourcestatements:- - keep_keys(attributes, ["service.name", "service.instance.id", "deployment.environment", "cloud.region", "service.version"])+ - set(cache["service.name"], attributes["service.name"])+ - set(cache["service.instance.id"], attributes["service.instance.id"])+ - set(cache["deployment.environment"], attributes["deployment.environment"])+ - set(cache["cloud.region"], attributes["cloud.region"])+ - set(cache["service.version"], attributes["service.version"])+ - keep_keys(attributes, [])+ - set(attributes["service.name"], cache["service.name"]) where cache["service.name"] != nil+ - set(attributes["service.instance.id"], cache["service.instance.id"]) where cache["service.instance.id"] != nil+ - set(attributes["deployment.environment"], cache["deployment.environment"]) where cache["deployment.environment"] != nil+ - set(attributes["cloud.region"], cache["cloud.region"]) where cache["cloud.region"] != nil+ - set(attributes["service.version"], cache["service.version"]) where cache["service.version"] != nil- set(schema_url, "")- context: scopestatements:@@ -545,7 +555,25 @@ processors:- set(schema_url, "")- context: logstatements:- - keep_keys(attributes, ["event.name", "event.schema.version", "operation", "outcome", "http.status_code", "model", "machine_profile", "duration_ms", "admission_outcome"])+ - set(cache["event.name"], attributes["event.name"])+ - set(cache["event.schema.version"], attributes["event.schema.version"])+ - set(cache["operation"], attributes["operation"])+ - set(cache["outcome"], attributes["outcome"])+ - set(cache["http.status_code"], attributes["http.status_code"])+ - set(cache["model"], attributes["model"])+ - set(cache["machine_profile"], attributes["machine_profile"])+ - set(cache["duration_ms"], attributes["duration_ms"])+ - set(cache["admission_outcome"], attributes["admission_outcome"])+ - keep_keys(attributes, [])+ - set(attributes["event.name"], cache["event.name"]) where cache["event.name"] != nil+ - set(attributes["event.schema.version"], cache["event.schema.version"]) where cache["event.schema.version"] != nil+ - set(attributes["operation"], cache["operation"]) where cache["operation"] != nil+ - set(attributes["outcome"], cache["outcome"]) where cache["outcome"] != nil+ - set(attributes["http.status_code"], cache["http.status_code"]) where cache["http.status_code"] != nil+ - set(attributes["model"], cache["model"]) where cache["model"] != nil+ - set(attributes["machine_profile"], cache["machine_profile"]) where cache["machine_profile"] != nil+ - set(attributes["duration_ms"], cache["duration_ms"]) where cache["duration_ms"] != nil+ - set(attributes["admission_outcome"], cache["admission_outcome"]) where cache["admission_outcome"] != nil# Canonical release domains are rechecked at the collector boundary# so malformed producer values cannot become vendor dimensions.- 'set(attributes["model"], "other") where attributes["event.schema.version"] == "2" and not IsMatch(attributes["model"], "^(BAAI/bge-m3|IDEA-Research/grounding-dino-base|Qwen/Qwen3-Embedding-4B|Qwen/Qwen3-Reranker-0[.]6B|Qwen/Qwen3-Reranker-4B|Qwen/Qwen3-VL-Reranker-2B|Qwen/Qwen3[.]5-4B|Qwen/Qwen3[.]6-27B|Snowflake/snowflake-arctic-embed-l-v2[.]0|docling|fastino/gliguard-LLMGuardrails-300M|fastino/gliner2-base-v1|fastino/gliner2-large-v1|google/owlv2-base-patch16-ensemble|google/siglip-so400m-patch14-384|google/siglip2-base-patch16-224|ibm-granite/granite-guardian-3[.]0-2b|knowledgator/gliclass-large-v3[.]0|lightonai/GTE-ModernColBERT-v1|lightonai/LightOnOCR-2-1B|numind/NuNER_Zero|openai/whisper-large-v3-turbo|other|prithivida/Splade_PP_en_v2|tencent/R3-embedding-0[.]6b|tencent/R3-rerank-0[.]6b|urchade/gliner_multi-v2[.]1|urchade/gliner_multi_pii-v1)$")'@@ -554,6 +582,77 @@ processors:- set(body, "inference.request.completed")- set(severity_text, "INFO")- set(severity_number, SEVERITY_NUMBER_INFO)+ # Fixed structured lifecycle records only; never a stdout/logging bridge.+ filter/lifecycle_logs:+ error_mode: propagate+ logs:+ log_record:+ - 'attributes["event.name"] != "inference.lifecycle.completed"'+ - 'body != "inference.lifecycle.completed"'+ - 'attributes["event.schema.version"] != "1"'+ - 'attributes["phase"] != "request" and attributes["phase"] != "response_body" and attributes["phase"] != "generation_stream" and attributes["phase"] != "worker_generation" and attributes["phase"] != "dispatch_attempt"'+ - 'attributes["operation"] != "encode" and attributes["operation"] != "score" and attributes["operation"] != "extract" and attributes["operation"] != "generate" and attributes["operation"] != "embeddings" and attributes["operation"] != "moderations" and attributes["operation"] != "other"'+ - 'attributes["outcome"] != "success" and attributes["outcome"] != "rejected" and attributes["outcome"] != "error" and attributes["outcome"] != "cancelled"'+ - 'attributes["error_class"] != "none" and attributes["error_class"] != "client_error" and attributes["error_class"] != "server_error" and attributes["error_class"] != "transport" and attributes["error_class"] != "timeout" and attributes["error_class"] != "worker" and attributes["error_class"] != "cancelled" and attributes["error_class"] != "protocol" and attributes["error_class"] != "other"'+ - 'not IsDouble(attributes["duration_ms"]) and not IsInt(attributes["duration_ms"])'+ - 'attributes["duration_ms"] != attributes["duration_ms"] or attributes["duration_ms"] < 0 or attributes["duration_ms"] > 86400000'+ - 'attributes["first_token_ms"] != nil and not IsDouble(attributes["first_token_ms"]) and not IsInt(attributes["first_token_ms"])'+ - 'attributes["first_token_ms"] != nil and (attributes["first_token_ms"] != attributes["first_token_ms"] or attributes["first_token_ms"] < 0 or attributes["first_token_ms"] > attributes["duration_ms"])'+ filter/gateway_lifecycle_logs:+ error_mode: propagate+ logs:+ log_record:+ - 'attributes["phase"] != "request" and attributes["phase"] != "response_body" and attributes["phase"] != "generation_stream"'+ filter/application_lifecycle_logs:+ error_mode: propagate+ logs:+ log_record:+ - 'not (resource.attributes["service.name"] == "sie-worker" and attributes["phase"] == "worker_generation") and not (resource.attributes["service.name"] == "sie-dispatcher" and attributes["phase"] == "dispatch_attempt")'+ transform/lifecycle_logs:+ error_mode: propagate+ log_statements:+ - context: resource+ statements:+ - set(cache["service.name"], attributes["service.name"])+ - set(cache["service.instance.id"], attributes["service.instance.id"])+ - set(cache["deployment.environment"], attributes["deployment.environment"])+ - set(cache["cloud.region"], attributes["cloud.region"])+ - set(cache["service.version"], attributes["service.version"])+ - keep_keys(attributes, [])+ - set(attributes["service.name"], cache["service.name"]) where cache["service.name"] != nil+ - set(attributes["service.instance.id"], cache["service.instance.id"]) where cache["service.instance.id"] != nil+ - set(attributes["deployment.environment"], cache["deployment.environment"]) where cache["deployment.environment"] != nil+ - set(attributes["cloud.region"], cache["cloud.region"]) where cache["cloud.region"] != nil+ - set(attributes["service.version"], cache["service.version"]) where cache["service.version"] != nil+ - set(schema_url, "")+ - context: scope+ statements:+ - keep_keys(attributes, [])+ - set(name, "")+ - set(version, "")+ - set(schema_url, "")+ - context: log+ statements:+ - set(cache["event.name"], attributes["event.name"])+ - set(cache["event.schema.version"], attributes["event.schema.version"])+ - set(cache["phase"], attributes["phase"])+ - set(cache["operation"], attributes["operation"])+ - set(cache["outcome"], attributes["outcome"])+ - set(cache["error_class"], attributes["error_class"])+ - set(cache["duration_ms"], attributes["duration_ms"])+ - set(cache["first_token_ms"], attributes["first_token_ms"])+ - keep_keys(attributes, [])+ - set(attributes["event.name"], cache["event.name"]) where cache["event.name"] != nil+ - set(attributes["event.schema.version"], cache["event.schema.version"]) where cache["event.schema.version"] != nil+ - set(attributes["phase"], cache["phase"]) where cache["phase"] != nil+ - set(attributes["operation"], cache["operation"]) where cache["operation"] != nil+ - set(attributes["outcome"], cache["outcome"]) where cache["outcome"] != nil+ - set(attributes["error_class"], cache["error_class"]) where cache["error_class"] != nil+ - set(attributes["duration_ms"], cache["duration_ms"]) where cache["duration_ms"] != nil+ - set(attributes["first_token_ms"], cache["first_token_ms"]) where cache["first_token_ms"] != nil+ - set(severity_text, "INFO")+ - set(severity_number, SEVERITY_NUMBER_INFO)+{{- end }}exporters:@@ -672,5 +771,13 @@ service:receivers: [otlp/gateway]processors: [memory_limiter, resource/gateway_identity, filter/contract_logs, transform/contract_logs, batch]exporters: {{ toJson $logExporters }}+ logs/lifecycle/gateway:+ receivers: [otlp/gateway]+ processors: [memory_limiter, resource/gateway_identity, filter/gateway_lifecycle_logs, filter/lifecycle_logs, transform/lifecycle_logs, batch]+ exporters: {{ toJson $logExporters }}+ logs/lifecycle/application:+ receivers: [otlp/application]+ processors: [memory_limiter, filter/application_lifecycle_logs, resource/application_identity, filter/lifecycle_logs, transform/lifecycle_logs, batch]+ exporters: {{ toJson $logExporters }}{{- end }}{{- end -}}diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex 5f129934d..e3b7aa38c 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -52,8 +52,10 @@ use std::convert::Infallible;use std::sync::Arc;use std::time::Duration;+use crate::observability::lifecycle::{ErrorClass, Lifecycle, Outcome};use axum::response::sse::{Event, KeepAlive, Sse};use axum::response::{IntoResponse, Response};+use opentelemetry::trace::FutureExt;use serde_json::{json, Value};use tokio::sync::broadcast;use tokio_stream::wrappers::ReceiverStream;@@ -303,31 +305,35 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {.map(|d| d.as_secs()).unwrap_or(0);- tokio::spawn(async move {- run_sse_driver(SseDriverArgs {- event_tx,- chunk_rx,- outcome_rx,- durability_completion,- publisher: driver_publisher,- demand_tracker: driver_demand_tracker,- physical_lane: driver_physical_lane,- request_id: driver_request_id,- model: driver_model.clone(),- pool: driver_pool.clone(),- bundle: driver_bundle,- gpu: driver_gpu,- endpoint,- stream_chat_id,- created,- first_chunk_timeout: timeout_config.first_chunk,- inter_chunk_timeout: timeout_config.inter_chunk,- overall_timeout: effective_overall,- was_direct_dispatched,- pool_fallback_lane_worker_count,- })- .await;- });+ let context = opentelemetry::Context::current();+ tokio::spawn(+ async move {+ run_sse_driver(SseDriverArgs {+ event_tx,+ chunk_rx,+ outcome_rx,+ durability_completion,+ publisher: driver_publisher,+ demand_tracker: driver_demand_tracker,+ physical_lane: driver_physical_lane,+ request_id: driver_request_id,+ model: driver_model.clone(),+ pool: driver_pool.clone(),+ bundle: driver_bundle,+ gpu: driver_gpu,+ endpoint,+ stream_chat_id,+ created,+ first_chunk_timeout: timeout_config.first_chunk,+ inter_chunk_timeout: timeout_config.inter_chunk,+ overall_timeout: effective_overall,+ was_direct_dispatched,+ pool_fallback_lane_worker_count,+ })+ .await;+ }+ .with_context(context),+ );let stream = ReceiverStream::new(event_rx);let sse = Sse::new(stream).keep_alive(KeepAlive::default());@@ -508,6 +514,12 @@ async fn wait_for_terminal_durability(/// timeout fires the SSE response has already started (`200 OK` +/// headers sent).async fn run_sse_driver(args: SseDriverArgs) {+ let lifecycle = crate::observability::tracing::request_telemetry_enabled()+ .then(|| Lifecycle::generation_stream(opentelemetry::Context::current()));+ run_sse_driver_with_lifecycle(args, lifecycle).await;+}++async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Option<Lifecycle>) {let SseDriverArgs {event_tx,mut chunk_rx,@@ -531,9 +543,26 @@ async fn run_sse_driver(args: SseDriverArgs) {pool_fallback_lane_worker_count,} = args;let wait_start = std::time::Instant::now();- let record_wait = |outcome| {- telemetry::record_queue_result_wait("generate", outcome, wait_start.elapsed());- };+ macro_rules! record_wait {+ ($outcome:expr) => {{+ let outcome = $outcome;+ telemetry::record_queue_result_wait("generate", outcome, wait_start.elapsed());+ if let Some(lifecycle) = lifecycle.as_mut() {+ let (outcome, class) = match outcome {+ telemetry::QueueResultOutcome::Success => (Outcome::Success, ErrorClass::None),+ telemetry::QueueResultOutcome::Cancelled => {+ (Outcome::Cancelled, ErrorClass::Cancelled)+ }+ telemetry::QueueResultOutcome::Timeout => (Outcome::Error, ErrorClass::Timeout),+ telemetry::QueueResultOutcome::WorkerError => {+ (Outcome::Error, ErrorClass::Worker)+ }+ _ => (Outcome::Error, ErrorClass::Transport),+ };+ lifecycle.finish(outcome, class);+ }+ }};+ }// Install the cancel-on-drop guard. Mirrors// `run_streaming_generate`: a normal completion path defuses it;@@ -616,7 +645,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::Timeout);+ record_wait!(telemetry::QueueResultOutcome::Timeout);cancel_guard.defuse();publisher.publish_cancel(&request_id).await;publisher.drop_pending_stream(&request_id);@@ -700,7 +729,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::Timeout);+ record_wait!(telemetry::QueueResultOutcome::Timeout);cancel_guard.defuse();publisher.publish_cancel(&request_id).await;publisher.drop_pending_stream(&request_id);@@ -720,7 +749,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::Timeout);+ record_wait!(telemetry::QueueResultOutcome::Timeout);cancel_guard.defuse();publisher.publish_cancel(&request_id).await;publisher.drop_pending_stream(&request_id);@@ -756,7 +785,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::DurabilityError);+ record_wait!(telemetry::QueueResultOutcome::DurabilityError);cancel_guard.defuse();return;}@@ -773,7 +802,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::DurabilityError);+ record_wait!(telemetry::QueueResultOutcome::DurabilityError);cancel_guard.defuse();return;}@@ -788,7 +817,7 @@ async fn run_sse_driver(args: SseDriverArgs) {// explicitly to the receiver's lifecycle closes that leak._ = event_tx.closed() => {debug!(request_id = %request_id, "SSE receiver dropped; tearing down driver");- record_wait(telemetry::QueueResultOutcome::Cancelled);+ record_wait!(telemetry::QueueResultOutcome::Cancelled);telemetry::record_generation_event(telemetry::GenerationEvent::Cancellation,if first_seen {@@ -843,7 +872,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::WorkerError);+ record_wait!(telemetry::QueueResultOutcome::WorkerError);cancel_guard.defuse();publisher.drop_pending_stream(&request_id);return;@@ -909,7 +938,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::WorkerError);+ record_wait!(telemetry::QueueResultOutcome::WorkerError);cancel_guard.defuse();// Only cancel the worker if the generation is still in flight.// A request whose terminal outcome already resolved Ok has@@ -943,7 +972,7 @@ async fn run_sse_driver(args: SseDriverArgs) {.await;send_done(&event_tx).await;}- record_wait(if stream_succeeded {+ record_wait!(if stream_succeeded {telemetry::QueueResultOutcome::Success} else {telemetry::QueueResultOutcome::ChannelClosed@@ -954,6 +983,16 @@ async fn run_sse_driver(args: SseDriverArgs) {};// Non-stale chunk arrived. Update timing trackers.+ if !chunk.text_delta.is_empty()+ || chunk+ .tool_calls+ .as_ref()+ .is_some_and(|calls| !calls.is_empty())+ {+ if let Some(lifecycle) = lifecycle.as_mut() {+ lifecycle.first_token();+ }+ }first_seen = true;last_chunk_at = Some(tokio::time::Instant::now());@@ -989,7 +1028,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::DurabilityError);+ record_wait!(telemetry::QueueResultOutcome::DurabilityError);cancel_guard.defuse();// Tear the stream down like the sibling durability arm// below. This exit writes no usage surface, so it never@@ -1014,7 +1053,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::DurabilityError);+ record_wait!(telemetry::QueueResultOutcome::DurabilityError);cancel_guard.defuse();publisher.publish_cancel(&request_id).await;publisher.drop_pending_stream(&request_id);@@ -1022,7 +1061,7 @@ async fn run_sse_driver(args: SseDriverArgs) {}TerminalDurabilityWait::ClientClosed => {debug!(request_id = %request_id, "SSE receiver dropped while awaiting terminal durability");- record_wait(telemetry::QueueResultOutcome::Cancelled);+ record_wait!(telemetry::QueueResultOutcome::Cancelled);telemetry::record_generation_event(telemetry::GenerationEvent::Cancellation,telemetry::GenerationEventReason::MidStream,@@ -1051,7 +1090,7 @@ async fn run_sse_driver(args: SseDriverArgs) {).await;send_done(&event_tx).await;- record_wait(telemetry::QueueResultOutcome::Timeout);+ record_wait!(telemetry::QueueResultOutcome::Timeout);cancel_guard.defuse();publisher.publish_cancel(&request_id).await;publisher.drop_pending_stream(&request_id);@@ -1122,7 +1161,7 @@ async fn run_sse_driver(args: SseDriverArgs) {// a detached task and can race the outer return / next// request).debug!(request_id = %request_id, "SSE client disconnected mid-stream");- record_wait(telemetry::QueueResultOutcome::Cancelled);+ record_wait!(telemetry::QueueResultOutcome::Cancelled);telemetry::record_generation_event(telemetry::GenerationEvent::Cancellation,if first_seen {@@ -1156,8 +1195,10 @@ async fn run_sse_driver(args: SseDriverArgs) {let _ = send_event(&event_tx, Event::default().data(body.to_string())).await;}send_done(&event_tx).await;- record_wait(if chunk.error.is_some() {+ record_wait!(if chunk.error.is_some() {telemetry::QueueResultOutcome::WorkerError+ } else if chunk.finish_reason.as_deref() == Some("cancelled") {+ telemetry::QueueResultOutcome::Cancelled} else {telemetry::QueueResultOutcome::Success});@@ -1942,6 +1983,50 @@ mod tests {AfterFirstDelta,}+ #[tokio::test(flavor = "current_thread")]+ async fn live_driver_records_structural_error_before_and_after_first_delta() {+ use opentelemetry::trace::TracerProvider;+ use tracing_subscriber::prelude::*;+ let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();+ let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()+ // Other tests change the process sampler environment; capture spans deterministically.+ .with_sampler(opentelemetry_sdk::trace::Sampler::AlwaysOn)+ .with_simple_exporter(exporter.clone())+ .build();+ let subscriber = tracing_subscriber::registry()+ .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));+ let _guard = tracing::subscriber::set_default(subscriber);+ // Keep two dispatchers alive so subscriber-less sibling tests cannot+ // cache shared callsites as disabled through tracing-core's fast path.+ let _callsite_guard = tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());+ for delivery in [+ WorkerTerminalDelivery::BackloggedBeforeFirstPoll,+ WorkerTerminalDelivery::AfterFirstDelta,+ ] {+ let _ = run_driver_worker_error_race(+ SseEndpoint::Generate,+ delivery,+ ChunkError {+ code: "inference_error".into(),+ message: "sensitive diagnostic".into(),+ param: None,+ retry_after_s: None,+ },+ )+ .await;+ }+ let spans = exporter.get_finished_spans().unwrap();+ let streams: Vec<_> = spans+ .iter()+ .filter(|span| span.name == "gateway.generation_stream")+ .collect();+ assert_eq!(streams.len(), 2);+ assert!(streams+ .iter()+ .all(|span| span.status == opentelemetry::trace::Status::error("")));+ assert!(streams.iter().all(|span| span.events.is_empty()));+ }+async fn run_driver_worker_error_race(endpoint: SseEndpoint,delivery: WorkerTerminalDelivery,@@ -2002,7 +2087,16 @@ mod tests {let mut payloads = Vec::new();if matches!(delivery, WorkerTerminalDelivery::AfterFirstDelta) {- let driver = tokio::spawn(run_sse_driver(args));+ use tracing::instrument::WithSubscriber;+ let driver = tokio::spawn(+ run_sse_driver_with_lifecycle(+ args,+ Some(Lifecycle::generation_stream(+ opentelemetry::Context::current(),+ )),+ )+ .with_current_subscriber(),+ );assert!(matches!(collector.apply(_delta_chunk(41, "partial")),ChunkApplied::Delta@@ -2054,7 +2148,13 @@ mod tests {outcome_tx.send(collector.build_outcome().expect("terminal outcome")).expect("outcome receiver is live");- run_sse_driver(args).await;+ run_sse_driver_with_lifecycle(+ args,+ Some(Lifecycle::generation_stream(+ opentelemetry::Context::current(),+ )),+ )+ .await;}loop {diff --git a/packages/sie_gateway/src/middleware/metrics.rs b/packages/sie_gateway/src/middleware/metrics.rsindex 9b16d812c..00edce296 100644--- a/packages/sie_gateway/src/middleware/metrics.rs+++ b/packages/sie_gateway/src/middleware/metrics.rs@@ -57,7 +57,9 @@ use std::time::Instant;use tower::{Layer, Service};use tracing_opentelemetry::OpenTelemetrySpanExt;+use crate::observability::lifecycle::{ErrorClass, Lifecycle, Outcome};use crate::observability::metrics as telemetry;+use hyper::body::{Body as HttpBody, Frame, SizeHint};#[cfg(test)]#[derive(Clone, Debug, PartialEq, Eq)]@@ -180,9 +182,16 @@ where.insert(telemetry::RequestTraceContext::new(request_cx.clone()));let start = Instant::now();+ let mut lifecycle = Lifecycle::request(request_span.clone(), endpoint);Box::pin(async move {- let response = inner.call(req).await?;+ let response = match inner.call(req).await {+ Ok(response) => response,+ Err(error) => {+ lifecycle.finish(Outcome::Error, ErrorClass::Transport);+ return Err(error);+ }+ };let status = response.status().as_u16();let elapsed = start.elapsed().as_secs_f64();@@ -234,6 +243,11 @@ where// existing audit/proxy `tracing` events (some with raw request or// error fields) into exported OTel span events and broaden the// privacy contract beyond this bounded request spine.+ lifecycle.finish_http(status);+ let body_lifecycle = Lifecycle::response_body(request_cx_for_log, endpoint);+ let (parts, body) = response.into_parts();+ let response =+ Response::from_parts(parts, Body::new(ObservedBody::new(body, body_lifecycle)));drop(request_span);Ok(response)}@@ -246,6 +260,55 @@ where}}+/// Observe transport lifecycle without inspecting payload bytes (SSE heartbeats+/// and role frames are not tokens). Dropping before EOF means cancellation; it+/// does not prove why the peer/server stopped consuming the response.+struct ObservedBody {+ inner: Body,+ lifecycle: Lifecycle,+}++impl ObservedBody {+ fn new(inner: Body, mut lifecycle: Lifecycle) -> Self {+ if inner.is_end_stream() {+ lifecycle.finish(Outcome::Success, ErrorClass::None);+ }+ Self { inner, lifecycle }+ }+}++impl HttpBody for ObservedBody {+ type Data = bytes::Bytes;+ type Error = axum::Error;++ fn poll_frame(+ mut self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {+ let context = self.lifecycle.context();+ let _guard = context.attach();+ let result = Pin::new(&mut self.inner).poll_frame(cx);+ match &result {+ Poll::Ready(Some(Err(_))) => {+ self.lifecycle.finish(Outcome::Error, ErrorClass::Transport)+ }+ Poll::Ready(None) => self.lifecycle.finish(Outcome::Success, ErrorClass::None),+ Poll::Ready(Some(Ok(_))) if self.inner.is_end_stream() => {+ self.lifecycle.finish(Outcome::Success, ErrorClass::None)+ }+ _ => {}+ }+ result+ }++ fn is_end_stream(&self) -> bool {+ self.inner.is_end_stream()+ }+ fn size_hint(&self) -> SizeHint {+ self.inner.size_hint()+ }+}+/// Return the endpoint label (`encode`, `score`, `extract`, `generate`,/// `embeddings`, `moderations`) when the path matches an inference route,/// otherwise `None`. Every generation surface@@ -296,6 +359,142 @@ mod tests {use std::time::Instant;use tower::ServiceExt;+ fn trace_capture() -> (+ opentelemetry_sdk::trace::SdkTracerProvider,+ opentelemetry_sdk::trace::InMemorySpanExporter,+ tracing::subscriber::DefaultGuard,+ tracing::Dispatch,+ ) {+ use opentelemetry::trace::TracerProvider;+ use tracing_subscriber::prelude::*;+ let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();+ let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()+ // Other tests change the process sampler environment; capture spans deterministically.+ .with_sampler(opentelemetry_sdk::trace::Sampler::AlwaysOn)+ .with_simple_exporter(exporter.clone())+ .build();+ let subscriber = tracing_subscriber::registry()+ .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));+ (+ provider,+ exporter,+ tracing::subscriber::set_default(subscriber),+ // Keep two dispatchers alive while subscriber-less sibling tests+ // register shared callsites; avoid tracing-core's single-dispatcher fast path.+ tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default()),+ )+ }++ #[tokio::test(flavor = "current_thread")]+ async fn response_ready_and_body_terminal_are_distinct() {+ use http_body_util::BodyExt;+ let (_provider, exporter, _guard, _callsite_guard) = trace_capture();+ let (tx, rx) = tokio::sync::mpsc::channel::<Result<bytes::Bytes, std::io::Error>>(2);+ let body = Body::from_stream(tokio_stream::wrappers::ReceiverStream::new(rx));+ let body = Arc::new(Mutex::new(Some(body)));+ let router = Router::new()+ .route(+ "/v1/generate/test",+ post(move || {+ let body = body.lock().unwrap().take().unwrap();+ async move { Response::new(body) }+ }),+ )+ .layer(MetricsLayer::new());+ let response = router+ .oneshot(+ Request::post("/v1/generate/test")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let spans = exporter.get_finished_spans().unwrap();+ assert_eq!(+ spans+ .iter()+ .map(|span| span.name.as_ref())+ .collect::<Vec<_>>(),+ ["gateway.request"]+ );+ let request_id = spans[0].span_context.span_id();+ let request_end = spans[0].end_time;+ let mut body = response.into_body();+ tx.send(Ok(bytes::Bytes::from_static(b"data: token\n\n")))+ .await+ .unwrap();+ assert!(body.frame().await.unwrap().is_ok());+ assert_eq!(exporter.get_finished_spans().unwrap().len(), 1);+ drop(tx);+ assert!(body.frame().await.is_none());+ // EOF closes the span even while the body value remains alive.+ let spans = exporter.get_finished_spans().unwrap();+ let terminal = spans+ .iter()+ .find(|span| span.name == "gateway.response_body")+ .unwrap();+ assert_eq!(terminal.parent_span_id, request_id);+ assert!(terminal.end_time >= request_end);+ assert_eq!(terminal.status, opentelemetry::trace::Status::Unset);+ }++ #[tokio::test(flavor = "current_thread")]+ async fn server_errors_survive_as_structural_status_but_rejections_do_not() {+ let (_provider, exporter, _guard, _callsite_guard) = trace_capture();+ for status in [StatusCode::BAD_REQUEST, StatusCode::SERVICE_UNAVAILABLE] {+ let router = Router::new()+ .route("/v1/encode/test", post(move || async move { status }))+ .layer(MetricsLayer::new());+ let _ = router+ .oneshot(+ Request::post("/v1/encode/test")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ }+ let spans = exporter.get_finished_spans().unwrap();+ let requests: Vec<_> = spans+ .iter()+ .filter(|span| span.name == "gateway.request")+ .collect();+ assert_eq!(requests.len(), 2);+ assert_eq!(requests[0].status, opentelemetry::trace::Status::Unset);+ assert_eq!(requests[1].status, opentelemetry::trace::Status::error(""));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn body_failure_and_client_drop_end_once_without_exception_text() {+ use http_body_util::BodyExt;+ let (_provider, exporter, _guard, _callsite_guard) = trace_capture();+ let stream = futures_util::stream::iter([+ Ok(bytes::Bytes::from_static(b"first")),+ Err(std::io::Error::other("private exception payload")),+ ]);+ let mut body = ObservedBody::new(+ Body::from_stream(stream),+ Lifecycle::response_body(opentelemetry::Context::new(), "generate"),+ );+ assert!(body.frame().await.unwrap().is_ok());+ assert!(body.frame().await.unwrap().is_err());+ drop(body);+ let pending = Body::from_stream(futures_util::stream::pending::<+ Result<bytes::Bytes, std::io::Error>,+ >());+ let body = ObservedBody::new(+ pending,+ Lifecycle::response_body(opentelemetry::Context::new(), "generate"),+ );+ assert_eq!(exporter.get_finished_spans().unwrap().len(), 1);+ drop(body);+ let spans = exporter.get_finished_spans().unwrap();+ assert_eq!(spans.len(), 2);+ assert_eq!(spans[0].status, opentelemetry::trace::Status::error(""));+ assert_eq!(spans[1].status, opentelemetry::trace::Status::Unset);+ assert!(spans.iter().all(|span| span.events.is_empty()));+ }+// A test handler that mimics the real proxy handler: write the// canonical machine_profile into the slot that `MetricsLayer`// installed. Real callers always normalize first, so the testsdiff --git a/packages/sie_gateway/src/observability/lifecycle.rs b/packages/sie_gateway/src/observability/lifecycle.rsnew file mode 100644index 000000000..74baaebab--- /dev/null+++ b/packages/sie_gateway/src/observability/lifecycle.rs@@ -0,0 +1,142 @@+//! Bounded lifecycle observations. These are sampled traces/logs, never metrics.+//! Body completion means the server consumed EOF, not client receipt of bytes.++use std::time::Instant;++use opentelemetry::trace::Status;+use tracing_opentelemetry::OpenTelemetrySpanExt;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Outcome {+ Success,+ Rejected,+ Error,+ Cancelled,+}++impl Outcome {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Success => "success",+ Self::Rejected => "rejected",+ Self::Error => "error",+ Self::Cancelled => "cancelled",+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ErrorClass {+ None,+ ClientError,+ ServerError,+ Transport,+ Timeout,+ Worker,+ Cancelled,+}++impl ErrorClass {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::None => "none",+ Self::ClientError => "client_error",+ Self::ServerError => "server_error",+ Self::Transport => "transport",+ Self::Timeout => "timeout",+ Self::Worker => "worker",+ Self::Cancelled => "cancelled",+ }+ }+}++pub struct Lifecycle {+ span: tracing::Span,+ phase: &'static str,+ operation: &'static str,+ started: Instant,+ first_token_ms: Option<f64>,+ finished: bool,+}++impl Lifecycle {+ pub fn request(span: tracing::Span, operation: &'static str) -> Self {+ Self::from_span(span, "request", operation)+ }++ pub fn response_body(parent: opentelemetry::Context, operation: &'static str) -> Self {+ let span =+ tracing::info_span!("gateway.response_body", otel.name = "gateway.response_body");+ let _ = span.set_parent(parent);+ Self::from_span(span, "response_body", operation)+ }++ pub fn generation_stream(parent: opentelemetry::Context) -> Self {+ let span = tracing::info_span!(+ "gateway.generation_stream",+ otel.name = "gateway.generation_stream"+ );+ let _ = span.set_parent(parent);+ Self::from_span(span, "generation_stream", "generate")+ }++ fn from_span(span: tracing::Span, phase: &'static str, operation: &'static str) -> Self {+ Self {+ span,+ phase,+ operation,+ started: Instant::now(),+ first_token_ms: None,+ finished: false,+ }+ }++ pub fn context(&self) -> opentelemetry::Context {+ self.span.context()+ }++ /// First non-empty text/tool delta observed by the SSE driver. This is not+ /// adapter TTFT and creates no histogram or per-token observation.+ pub fn first_token(&mut self) {+ self.first_token_ms+ .get_or_insert_with(|| self.started.elapsed().as_secs_f64() * 1000.0);+ }++ pub fn finish_http(&mut self, status: u16) {+ let (outcome, class) = match status {+ 500..=599 => (Outcome::Error, ErrorClass::ServerError),+ 400..=499 => (Outcome::Rejected, ErrorClass::ClientError),+ _ => (Outcome::Success, ErrorClass::None),+ };+ self.finish(outcome, class);+ }++ pub fn finish(&mut self, outcome: Outcome, error_class: ErrorClass) {+ if self.finished {+ return;+ }+ self.finished = true;+ // No free-form status description: the structural code survives remote+ // privacy filtering. Client rejection/cancellation are not server errors.+ if outcome == Outcome::Error {+ self.span.set_status(Status::error(""));+ }+ super::tracing::record_lifecycle_log(+ &self.span.context(),+ self.phase,+ self.operation,+ outcome,+ error_class,+ self.started.elapsed().as_secs_f64() * 1000.0,+ self.first_token_ms,+ );+ // End at the terminal observation even if the body object is retained.+ self.span = tracing::Span::none();+ }+}++impl Drop for Lifecycle {+ fn drop(&mut self) {+ self.finish(Outcome::Cancelled, ErrorClass::Cancelled);+ }+}diff --git a/packages/sie_gateway/src/observability/mod.rs b/packages/sie_gateway/src/observability/mod.rsindex 2780cd839..01d069bbb 100644--- a/packages/sie_gateway/src/observability/mod.rs+++ b/packages/sie_gateway/src/observability/mod.rs@@ -12,6 +12,7 @@//! changes. The helpers in [`propagation`] are only needed at the//! *edges* — inbound HTTP and outbound NATS publish.+pub mod lifecycle;pub mod metrics;pub mod propagation;pub mod tracing;diff --git a/packages/sie_gateway/src/observability/tracing.rs b/packages/sie_gateway/src/observability/tracing.rsindex e2356eea2..e8fe2929f 100644--- a/packages/sie_gateway/src/observability/tracing.rs+++ b/packages/sie_gateway/src/observability/tracing.rs@@ -668,6 +668,54 @@ pub fn record_inference_completion_log());}+/// Fixed lifecycle schema. Deliberately no message, exception, identifier, or+/// caller-defined attribute API. Like completion logs, failures are sampled.+pub fn record_lifecycle_log(+ context: &opentelemetry::Context,+ phase: &'static str,+ operation: &'static str,+ outcome: super::lifecycle::Outcome,+ error_class: super::lifecycle::ErrorClass,+ duration_ms: f64,+ first_token_ms: Option<f64>,+) {+ use opentelemetry::trace::TraceContextExt;+ let span = context.span();+ let Some(span_context) = sampled_log_span_context(Some(span.span_context())) else {+ return;+ };+ let Some(logger) = REQUEST_LOGGER.get() else {+ return;+ };+ let mut record = logger.create_log_record();+ record.set_timestamp(SystemTime::now());+ record.set_severity_number(Severity::Info);+ record.set_severity_text("INFO");+ record.set_body(AnyValue::from("inference.lifecycle.completed"));+ record.set_trace_context(+ span_context.trace_id(),+ span_context.span_id(),+ Some(span_context.trace_flags()),+ );+ record.add_attribute("event.name", "inference.lifecycle.completed");+ record.add_attribute("event.schema.version", "1");+ record.add_attribute("phase", phase);+ record.add_attribute(+ "operation",+ match operation {+ "encode" | "score" | "extract" | "generate" | "embeddings" | "moderations" => operation,+ _ => "other",+ },+ );+ record.add_attribute("outcome", outcome.as_str());+ record.add_attribute("error_class", error_class.as_str());+ record.add_attribute("duration_ms", duration_ms);+ if let Some(first_token_ms) = first_token_ms {+ record.add_attribute("first_token_ms", first_token_ms);+ }+ logger.emit(record);+}+fn sampled_log_span_context(span_context: Option<&SpanContext>) -> Option<&SpanContext> {span_context.filter(|cx| cx.is_valid() && cx.is_sampled())}diff --git a/packages/sie_server/src/sie_server/adapter_call_loop.py b/packages/sie_server/src/sie_server/adapter_call_loop.pyindex d08e0118b..a37b95332 100644--- a/packages/sie_server/src/sie_server/adapter_call_loop.py+++ b/packages/sie_server/src/sie_server/adapter_call_loop.py@@ -283,7 +283,7 @@ async def handle_run_batch("sie.adapter": "run_batch","sie.batch_size": len(req.items),},- ):+ ) as span:if op == "encode":result = await _dispatch_encode(executor, req)elif op == "score":@@ -299,6 +299,10 @@ async def handle_run_batch()result = _reject_all(req, RUN_BATCH_UNKNOWN_OP, f"unknown op {op!r}")+ if any(item.disposition != "publish_and_ack" for item in result.outcomes):+ # Errors returned as values still need structural status; never+ # copy the item's free-form message into status text.+ span.set_status(trace.StatusCode.ERROR)if started is not None:_record_run_batch_metrics(req, result, time.perf_counter() - started)return resultdiff --git a/packages/sie_server/src/sie_server/observability/lifecycle.py b/packages/sie_server/src/sie_server/observability/lifecycle.pynew file mode 100644index 000000000..ede682abb--- /dev/null+++ b/packages/sie_server/src/sie_server/observability/lifecycle.py@@ -0,0 +1,180 @@+"""Sampled, bounded lifecycle records; never a bridge from Python logging.++The trace's head-sampling decision also controls these logs, including failures.+No exception objects, strings, payloads, or caller-defined fields are accepted.+"""++from __future__ import annotations++import asyncio+import logging+import os+import time+from collections.abc import Iterator, Mapping+from contextlib import contextmanager+from contextvars import ContextVar+from dataclasses import dataclass+from typing import cast++from opentelemetry import trace+from opentelemetry._logs import LogRecord, SeverityNumber+from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter as GrpcLogExporter+from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter as HttpLogExporter+from opentelemetry.sdk._logs import LoggerProvider+from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogRecordExporter+from opentelemetry.sdk.resources import Resource++from sie_server.observability.worker_telemetry import worker_resource_attributes++_logger = logging.getLogger(__name__)+_provider: LoggerProvider | None = None+_current: ContextVar[Lifecycle | None] = ContextVar("sie_lifecycle", default=None)+_OUTCOMES = frozenset({"success", "rejected", "error", "cancelled"})+_CLIENT_ERROR_CODES = frozenset(+ {+ "invalid_request",+ "unsupported_field",+ "INPUT_TOO_LONG",+ "PAYLOAD_TOO_LARGE",+ "context_exceeded",+ "grammar_invalid",+ }+)+_ERROR_CLASSES = frozenset(+ {"none", "client_error", "server_error", "transport", "timeout", "worker", "cancelled", "protocol", "other"}+)+++def configure_lifecycle_logs(exporter: LogRecordExporter, resource: Resource) -> LoggerProvider:+ """Install a dedicated safe logger; deployment owns transport credentials."""+ global _provider+ if _provider is not None:+ return _provider+ provider = LoggerProvider(resource=resource, shutdown_on_exit=False)+ provider.add_log_record_processor(BatchLogRecordProcessor(exporter))+ _provider = provider+ return provider+++def setup_lifecycle_logs() -> None:+ """OSS transport setup. Signals are independently gated and fail open."""+ if _provider is not None or os.getenv("SIE_OTLP_LOGS_ENABLED", "").strip().lower() not in {"1", "true", "yes"}:+ return+ endpoint = os.getenv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "").strip()+ generic = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "").strip()+ protocol = (+ os.getenv("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL", "").strip()+ or os.getenv("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc").strip()+ ).lower()+ if not endpoint and not generic:+ return+ if protocol not in {"grpc", "http/protobuf"}:+ _logger.warning("Unsupported safe lifecycle log transport; export disabled")+ return+ if not endpoint:+ endpoint = generic if protocol == "grpc" else f"{generic.rstrip('/')}/v1/logs"+ try:+ exporter = (+ GrpcLogExporter(endpoint=endpoint, timeout=3)+ if protocol == "grpc"+ else HttpLogExporter(endpoint=endpoint, timeout=3)+ )+ configure_lifecycle_logs(exporter, Resource(worker_resource_attributes()))+ except Exception: # noqa: BLE001 - telemetry must not prevent serving+ _logger.warning("Safe lifecycle log exporter setup failed; export disabled")+++def shutdown_lifecycle_logs() -> None:+ global _provider+ provider, _provider = _provider, None+ if provider is not None:+ try:+ provider.shutdown()+ except Exception: # noqa: BLE001 - best effort telemetry teardown+ _logger.warning("Safe lifecycle log exporter shutdown failed")+++@dataclass+class Lifecycle:+ span: trace.Span+ started: float+ outcome: str = "error"+ error_class: str = "transport"+ terminal: bool = False++ def published_retry(self) -> None:+ """A confirmed retry handoff ends this attempt without completing generation."""+ if not self.terminal:+ self.terminal = True+ self.outcome, self.error_class = "rejected", "none"++ def published_terminal(self, envelope: dict[str, object]) -> None:+ """Terminal means successful transport publication, not client receipt."""+ if self.terminal:+ return+ self.terminal = True+ if envelope.get("finish_reason") == "cancelled":+ self.outcome, self.error_class = "cancelled", "cancelled"+ elif envelope.get("error") is not None or envelope.get("finish_reason") == "error":+ error = envelope.get("error")+ code = cast("Mapping[str, object]", error).get("code") if isinstance(error, dict) else None+ if isinstance(code, str) and code in _CLIENT_ERROR_CODES:+ self.outcome, self.error_class = "rejected", "client_error"+ elif code == "transport_failure":+ self.outcome, self.error_class = "error", "transport"+ else:+ self.outcome, self.error_class = "error", "worker"+ else:+ self.outcome, self.error_class = "success", "none"++ def finish(self) -> None:+ if self.outcome == "error":+ self.span.set_status(trace.StatusCode.ERROR)+ context = self.span.get_span_context()+ if _provider is None or not context.is_valid or not context.trace_flags.sampled:+ return+ _provider.get_logger("sie.lifecycle").emit(+ LogRecord(+ timestamp=time.time_ns(),+ context=trace.set_span_in_context(self.span),+ severity_text="INFO",+ severity_number=SeverityNumber.INFO,+ body="inference.lifecycle.completed",+ attributes={+ "event.name": "inference.lifecycle.completed",+ "event.schema.version": "1",+ "phase": "worker_generation",+ "operation": "generate",+ "outcome": self.outcome if self.outcome in _OUTCOMES else "error",+ "error_class": self.error_class if self.error_class in _ERROR_CLASSES else "other",+ "duration_ms": max(0.0, (time.perf_counter() - self.started) * 1000),+ },+ )+ )+++def current_lifecycle() -> Lifecycle | None:+ return _current.get()+++@contextmanager+def observe_generation() -> Iterator[None]:+ span = trace.get_current_span()+ if not span.is_recording() and _provider is None:+ yield+ return+ lifecycle = Lifecycle(span, time.perf_counter())+ token = _current.set(lifecycle)+ try:+ yield+ except asyncio.CancelledError:+ lifecycle.outcome, lifecycle.error_class = "cancelled", "cancelled"+ raise+ except Exception:+ lifecycle.outcome, lifecycle.error_class = "error", "worker"+ raise+ finally:+ try:+ lifecycle.finish()+ finally:+ _current.reset(token)diff --git a/packages/sie_server/src/sie_server/observability/tracing.py b/packages/sie_server/src/sie_server/observability/tracing.pyindex 941c7115d..4672b6b6e 100644--- a/packages/sie_server/src/sie_server/observability/tracing.py+++ b/packages/sie_server/src/sie_server/observability/tracing.py@@ -31,6 +31,7 @@ from opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom sie_server.observability.batch_fanin import BatchFanInSpanProcessor+from sie_server.observability.lifecycle import setup_lifecycle_logs, shutdown_lifecycle_logsfrom sie_server.observability.worker_telemetry import worker_resource_attributesif TYPE_CHECKING:@@ -144,6 +145,7 @@ def setup_tracing(app: FastAPI) -> None:No-op unless SIE_TRACING_ENABLED is true and an OTLP endpoint is set.All configuration is via standard OTel environment variables."""+ setup_lifecycle_logs()if not is_tracing_enabled():logger.debug("Tracing disabled (SIE_TRACING_ENABLED not set)")return@@ -216,6 +218,7 @@ def shutdown_tracing() -> None:``setup_tracing`` — each export attempt inside ``provider.shutdown()`` iscapped, so this returns promptly even when the collector is down."""+ shutdown_lifecycle_logs()global _providerprovider = _providerif provider is None:diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 5c014b205..ebf993c2e 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -80,6 +80,7 @@ from sie_server.core.video_frames import (sniff_video_container,)from sie_server.observability import worker_telemetry as _metrics+from sie_server.observability.lifecycle import current_lifecycle, observe_generationfrom sie_server.processors.grammar_cache import GrammarLRUfrom sie_server.processors.grammar_compile import compile_outlinesfrom sie_server.processors.tool_call_grammar import (@@ -1544,15 +1545,20 @@ class StreamingProcessor:parent_ctx = propagate.extract(carrier)tracer = _otel_trace.get_tracer("sie_server.processors.streaming")try:- with tracer.start_as_current_span(- "worker.streaming_processor",- context=parent_ctx,- attributes={- "sie.request_id": request_id,- "sie.attempt_id": attempt_id,- "sie.model": model_id,- "sie.adapter": "streaming",- },+ with (+ tracer.start_as_current_span(+ "worker.streaming_processor",+ context=parent_ctx,+ record_exception=False,+ set_status_on_exception=False,+ attributes={+ "sie.request_id": request_id,+ "sie.attempt_id": attempt_id,+ "sie.model": model_id,+ "sie.adapter": "streaming",+ },+ ),+ observe_generation(),):await self._process_inner(msg, model_id, wi, reply_subject, request_id, attempt_id, received_at)finally:@@ -2731,7 +2737,7 @@ class StreamingProcessor:await self._nc.publish(reply_subject, payload)# Empty in disabled mode, so no msgpack decode or attribute work lands# on the default serving path.- if self._completion_by_attempt:+ if self._completion_by_attempt or current_lifecycle() is not None:self._record_published_terminal(payload)def _record_published_terminal(self, payload: bytes) -> None:@@ -2750,6 +2756,8 @@ class StreamingProcessor:returnif not isinstance(envelope, dict) or envelope.get("kind") != "chunk" or envelope.get("done") is not True:return+ if lifecycle := current_lifecycle():+ lifecycle.published_terminal(envelope)attempt_id = str(envelope.get("attempt_id") or "")completion = self._completion_by_attempt.get(attempt_id)if completion is None or completion.completed:@@ -4033,6 +4041,8 @@ class StreamingProcessor:exc_info=True,)return False+ if lifecycle := current_lifecycle():+ lifecycle.published_retry()return Trueasync def _terminal_error_then_settle(diff --git a/packages/sie_server/tests/observability/test_lifecycle.py b/packages/sie_server/tests/observability/test_lifecycle.pynew file mode 100644index 000000000..547fc5e1f--- /dev/null+++ b/packages/sie_server/tests/observability/test_lifecycle.py@@ -0,0 +1,174 @@+"""Lifecycle status, cancellation, head sampling and safe record regression tests."""++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from opentelemetry import trace+from opentelemetry.sdk._logs import LoggerProvider+from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor+from opentelemetry.sdk.trace import TracerProvider+from opentelemetry.sdk.trace.export import SimpleSpanProcessor+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON+from sie_server import adapter_call_loop+from sie_server.ipc_types import BatchOutcome, RunBatchItem, RunBatchRequest+from sie_server.observability import lifecycle+from sie_server.processors.streaming import StreamingProcessor+++ ("terminal", "outcome", "status"),+ [+ ({"finish_reason": "stop"}, "success", trace.StatusCode.UNSET),+ ({"error": {"code": "private", "message": "secret payload"}}, "error", trace.StatusCode.ERROR),+ ({"finish_reason": "cancelled"}, "cancelled", trace.StatusCode.UNSET),+ (None, "error", trace.StatusCode.ERROR),+ ],+)+def test_terminal_status_and_bounded_correlated_record(monkeypatch, terminal, outcome, status):+ logs = InMemoryLogRecordExporter()+ log_provider = LoggerProvider()+ log_provider.add_log_record_processor(SimpleLogRecordProcessor(logs))+ monkeypatch.setattr(lifecycle, "_provider", log_provider)+ spans = InMemorySpanExporter()+ provider = TracerProvider(sampler=ALWAYS_ON)+ provider.add_span_processor(SimpleSpanProcessor(spans))+ with provider.get_tracer("test").start_as_current_span("worker.streaming_processor") as span:+ with lifecycle.observe_generation():+ if terminal is not None:+ lifecycle.current_lifecycle().published_terminal(terminal)+ # A duplicate success terminal must not erase the first failure.+ lifecycle.current_lifecycle().published_terminal({"finish_reason": "stop"})+ record = logs.get_finished_logs()[0].log_record+ assert record.body == "inference.lifecycle.completed"+ assert record.attributes["outcome"] == outcome+ assert record.attributes["phase"] == "worker_generation"+ assert record.trace_id == span.get_span_context().trace_id+ assert record.span_id == span.get_span_context().span_id+ assert "secret" not in str(record.attributes)+ assert set(record.attributes) == {+ "event.name",+ "event.schema.version",+ "phase",+ "operation",+ "outcome",+ "error_class",+ "duration_ms",+ }+ assert spans.get_finished_spans()[0].status.status_code == status+ assert not spans.get_finished_spans()[0].events+ assert lifecycle.current_lifecycle() is None+ log_provider.shutdown()+ provider.shutdown()+++ ("error", "outcome"), [(asyncio.CancelledError(), "cancelled"), (RuntimeError("secret"), "error")]+)+def test_exception_and_task_cancellation_are_safe_and_reraised(monkeypatch, error, outcome):+ logs = InMemoryLogRecordExporter()+ log_provider = LoggerProvider()+ log_provider.add_log_record_processor(SimpleLogRecordProcessor(logs))+ monkeypatch.setattr(lifecycle, "_provider", log_provider)+ provider = TracerProvider()+ with (+ pytest.raises(type(error)),+ provider.get_tracer("test").start_as_current_span(+ "worker.streaming_processor", record_exception=False, set_status_on_exception=False+ ),+ lifecycle.observe_generation(),+ ):+ raise error+ record = logs.get_finished_logs()[0].log_record+ assert record.attributes["outcome"] == outcome+ assert "secret" not in str(record.attributes)+ assert lifecycle.current_lifecycle() is None+ log_provider.shutdown()+ provider.shutdown()+++def test_head_unsampled_failure_does_not_emit_log(monkeypatch):+ logs = InMemoryLogRecordExporter()+ log_provider = LoggerProvider()+ log_provider.add_log_record_processor(SimpleLogRecordProcessor(logs))+ monkeypatch.setattr(lifecycle, "_provider", log_provider)+ provider = TracerProvider(sampler=ALWAYS_OFF)+ with (+ provider.get_tracer("test").start_as_current_span("worker.streaming_processor"),+ lifecycle.observe_generation(),+ ):+ lifecycle.current_lifecycle().published_terminal({"error": {"message": "secret"}})+ assert not logs.get_finished_logs()+ log_provider.shutdown()+ provider.shutdown()+++async def test_batch_error_values_set_structural_status(monkeypatch):+ spans = InMemorySpanExporter()+ provider = TracerProvider()+ provider.add_span_processor(SimpleSpanProcessor(spans))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr(adapter_call_loop.trace, "get_tracer", lambda *_args: tracer)+ request = RunBatchRequest(+ model_id="test", batch_id=1, lora_key="", total_cost=0, items=[RunBatchItem(op="invalid")]+ )+ executor = SimpleNamespace(process_encode_batch=AsyncMock(return_value=BatchOutcome(outcomes=[])))+ result = await adapter_call_loop.handle_run_batch(executor, request)+ assert result.outcomes[0].disposition == "publish_error_and_ack"+ assert spans.get_finished_spans()[0].status.status_code == trace.StatusCode.ERROR+ assert spans.get_finished_spans()[0].status.description is None+ provider.shutdown()+++ ("code", "outcome", "error_class"),+ [+ ("invalid_request", "rejected", "client_error"),+ ("grammar_invalid", "rejected", "client_error"),+ ("transport_failure", "error", "transport"),+ ("inference_error", "error", "worker"),+ ("secret-code", "error", "worker"),+ ],+)+def test_terminal_error_codes_are_bounded(code, outcome, error_class):+ provider = TracerProvider()+ with provider.get_tracer("test").start_as_current_span("worker.streaming_processor") as span:+ observed = lifecycle.Lifecycle(span, 0)+ observed.published_terminal({"error": {"code": code, "message": "secret"}, "finish_reason": "error"})+ assert (observed.outcome, observed.error_class) == (outcome, error_class)+ provider.shutdown()++[email protected]("publish_fails", [False, True])+async def test_actual_retry_publish_marks_rejected_only_after_success(monkeypatch, publish_fails):+ exporter = InMemoryLogRecordExporter()+ log_provider = LoggerProvider()+ log_provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))+ monkeypatch.setattr(lifecycle, "_provider", log_provider)+ spans = InMemorySpanExporter()+ provider = TracerProvider()+ provider.add_span_processor(SimpleSpanProcessor(spans))+ publish = AsyncMock(side_effect=RuntimeError("secret") if publish_fails else None)+ processor = SimpleNamespace(_nc=SimpleNamespace(publish=publish))+ with (+ provider.get_tracer("test").start_as_current_span("worker.streaming_processor"),+ lifecycle.observe_generation(),+ ):+ result = await StreamingProcessor._publish_nak_envelope(+ processor, "reply", request_id="fixture", attempt_id="fixture", reason="kv_budget"+ )+ assert result is not publish_fails+ record = exporter.get_finished_logs()[0].log_record+ assert record.attributes["outcome"] == ("error" if publish_fails else "rejected")+ assert record.attributes["error_class"] == ("transport" if publish_fails else "none")+ assert spans.get_finished_spans()[0].status.status_code == (+ trace.StatusCode.ERROR if publish_fails else trace.StatusCode.UNSET+ )+ assert "secret" not in str(record.attributes)+ publish.assert_awaited_once()+ log_provider.shutdown()+ provider.shutdown()diff --git a/packages/sie_server_rust/src/ipc.rs b/packages/sie_server_rust/src/ipc.rsindex acf1d64a0..9bfec056c 100644--- a/packages/sie_server_rust/src/ipc.rs+++ b/packages/sie_server_rust/src/ipc.rs@@ -256,7 +256,16 @@ impl IpcServer {}}}- let resp = self.backend.run_batch(req).instrument(span).await;+ let resp = self.backend.run_batch(req).instrument(span.clone()).await;+ if resp+ .outcomes+ .iter()+ .any(|item| item.disposition != crate::ipc_types::Disposition::PublishAndAck)+ {+ // Structural status survives the remote attribute filter.+ // Never put an item's error string into status text.+ span.set_status(opentelemetry::trace::Status::error(""));+ }response_ok(&envelope.request_id, resp)}METHOD_APPLY_MODEL_CONFIG => {diff --git a/telemetry/README.md b/telemetry/README.mdindex 0292f3b1a..c648fce18 100644--- a/telemetry/README.md+++ b/telemetry/README.md@@ -75,6 +75,51 @@ Collectors accept schema v1 only while older gateway pods drain during arolling update; they preserve its version and never relabel an incomplete v1record as v2.+### Request and generation lifecycle++`gateway.request`, `sie.gateway.requests`, `sie.gateway.request.duration`, and+`inference.request.completed` retain their response-ready boundary: the inner+HTTP service has returned headers. They do not measure a streamed body. HTTP+5xx and service errors set structural OTel ERROR with no status description;+4xx are rejections, not server span errors.++`gateway.response_body` is a child covering response-ready to body EOF, body+error, or drop. EOF means server-side body consumption, not acknowledgement by+the client. Drop before EOF is cancellation (client disconnect, server abort,+or a consumer that stops reading); telemetry cannot distinguish those causes.+`gateway.generation_stream` covers the SSE driver's lifetime after publication+until its semantic terminal observation. It records errors inside HTTP 200+streams, timeout and cancellation independently of HTTP status. Its optional+`first_token_ms` is the first nonempty text or tool delta observed by that driver,+measured from driver start; heartbeats, role-only frames and terminal-only+responses do not create this value. Existing adapter and gateway generation+TTFT/TPOT metrics retain their ownership and meaning; these additions create+no metrics.++The Python `worker.streaming_processor` observes a generation attempt through+terminal publication and handler exit. A published worker or transport error+terminal marks ERROR; bounded validation errors are rejected client errors. A+confirmed retry handoff ends this attempt as rejected without completing the+generation. A published cancelled terminal or task cancellation records+cancellation, and return without a confirmed terminal or retry handoff is a+transport failure. Exceptions are+classified without exporting their text or automatic exception events.++`inference.lifecycle.completed` schema v1 is a fixed OTLP-only record carrying+phase, operation, outcome, bounded error class, duration, optional first-content+timing, and structural trace/span IDs. Each phase emits once; no raw stdout or+logging bridge is enabled. Service/phase pairs and exact numeric/string types+are rechecked by the collector. Cancellation and rejection leave structural+status UNSET; their safe record carries the distinction.++**Retention is sampled and best effort.** Lifecycle logs require a valid sampled+span context and the enabled safe-log exporter. They follow the enclosing head+sampling decision, even for errors. A parent-based 5% root sampler therefore+cannot retain every failure trace or failure record; inbound sampling decisions+and exporter/collector loss also affect retention. Metrics remain unsampled.+These changes do not enable tail sampling, change sampling rates, or promise+complete error coverage.+Every deployment uses the same application path: OTel instruments and logrecords leave the process through OTLP. Prometheus is a collector exporter, notan application instrumentation API. The bundled OSS/Kubernetes collectordiff --git a/telemetry/contract.yaml b/telemetry/contract.yamlindex 8a0b94aa4..b18a1d7df 100644--- a/telemetry/contract.yaml+++ b/telemetry/contract.yaml@@ -698,6 +698,8 @@ traces:unknown: otherallow:- gateway.request+ - gateway.response_body+ - gateway.generation_stream- gateway.dispatch- gateway.dispatch.ipc- gateway.dispatch.i6pn@@ -738,6 +740,9 @@ enums:signup_review_status: [pending, approved, rejected, other]launch_credit_status: [pending, approved, rejected, other]request_outcome: [success, redirect, client_error, server_error, other]+ lifecycle_phase: [request, response_body, generation_stream, worker_generation, dispatch_attempt]+ lifecycle_outcome: [success, rejected, error, cancelled]+ lifecycle_error_class: [none, client_error, server_error, transport, timeout, worker, cancelled, protocol, other]admission_outcome:- admitted- unauthenticated@@ -2638,12 +2643,32 @@ logs:correlation: [trace_id, span_id]export: [structured_stdout, otlp]+ - event_name: inference.lifecycle.completed+ owner: application+ producers: [gateway, worker, dispatcher]+ facade_event: lifecycle.completed+ body: inference.lifecycle.completed+ severity: INFO+ sampling: enclosing_trace_sampled+ attributes:+ event.name: inference.lifecycle.completed+ event.schema.version: "1"+ phase: lifecycle_phase+ operation: operation+ outcome: lifecycle_outcome+ error_class: lifecycle_error_class+ duration_ms: nonnegative_phase_duration_ms+ first_token_ms: optional_nonnegative_first_content_delta_ms_from_phase_start+ correlation: [trace_id, span_id]+ export: [otlp]+log_processing:declared_events_only: trueaccepted_schema_versions: ["1", "2"]helm_receiver_binding:receiver: gateway- other_receivers: reject+ other_receivers: reject_completion_event+ lifecycle_application_receiver: sie-worker_worker_generation_or_sie-dispatcher_dispatch_attempt_onlyservice_name: collector_authoritative_sie-gatewayresource_identity:deployment.environment: collector_authoritativediff --git a/tools/ci/tests/test_collector_lifecycle_privacy.py b/tools/ci/tests/test_collector_lifecycle_privacy.pynew file mode 100644index 000000000..24ba0af20--- /dev/null+++ b/tools/ci/tests/test_collector_lifecycle_privacy.py@@ -0,0 +1,331 @@+"""Real pinned collector privacy regression; run with pytest -m docker.++Fixtures are synthetic. The test renders the production Helm partial and sends+OTLP through both existing receiver boundaries, capturing the actual protobuf.+"""++from __future__ import annotations++# ruff: noqa: S603, S607 - fixed local Docker/Helm fixture commands+import gzip+import queue+import shutil+import socket+import subprocess+import threading+import time+import urllib.request+import uuid+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++import pytest+import yaml+from opentelemetry._logs import LogRecord+from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter as GrpcExporter+from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter as HttpExporter+from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest+from opentelemetry.sdk._logs import LoggerProvider+from opentelemetry.sdk._logs.export import SimpleLogRecordProcessor+from opentelemetry.sdk.resources import Resource+from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags, TraceState, set_span_in_context++ROOT = Path(__file__).resolve().parents[3]+++def render_config(directory: Path, endpoint: str) -> dict:+ chart = directory / "chart"+ (chart / "templates").mkdir(parents=True)+ (chart / "Chart.yaml").write_text("apiVersion: v2\nname: lifecycle-test\nversion: 0.0.0\n")+ shutil.copyfile(+ ROOT / "deploy/helm/sie-cluster/templates/_otel-collector-config.tpl", chart / "templates/_collector.tpl"+ )+ (chart / "templates/config.yaml").write_text(+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: test\ndata:\n collector.yaml: |\n"+ ' {{- include "sie-cluster.otel.collectorConfig" .Values | nindent 4 }}\n'+ )+ values = {+ "metricsEnabled": False,+ "logsEnabled": True,+ "tracesEnabled": False,+ "prometheusEnabled": False,+ "collector": {},+ "traceEndpoint": "",+ "logEndpoint": endpoint,+ "betterStack": {"enabled": False},+ "deploymentEnvironment": "dev",+ "cloudRegion": "local",+ "localTraceExporters": [],+ "logExporters": ["otlphttp/logs"],+ }+ (chart / "values.yaml").write_text(yaml.safe_dump(values))+ rendered = subprocess.run(+ ["helm", "template", "test", str(chart)], check=True, capture_output=True, text=True+ ).stdout+ return yaml.safe_load(yaml.safe_load(rendered)["data"]["collector.yaml"])+++def test_lifecycle_allowlist_in_real_collector(tmp_path):+ received = queue.Queue()++ class Sink(BaseHTTPRequestHandler):+ def do_POST(self):+ data = self.rfile.read(int(self.headers["Content-Length"]))+ if self.headers.get("Content-Encoding") == "gzip":+ data = gzip.decompress(data)+ received.put(data)+ self.send_response(200)+ self.send_header("Content-Length", "0")+ self.end_headers()++ def log_message(self, *_args):+ pass++ sink = ThreadingHTTPServer(("0.0.0.0", 0), Sink) # noqa: S104 - local Docker fixture+ thread = threading.Thread(target=sink.serve_forever, daemon=True)+ thread.start()+ config = render_config(tmp_path, f"http://host.docker.internal:{sink.server_port}")+ config["processors"]["batch"]["timeout"] = "100ms"+ config_path = tmp_path / "collector.yaml"+ config_path.write_text(yaml.safe_dump(config))+ config_path.chmod(0o644)+ name = f"sie-lifecycle-{uuid.uuid4().hex[:10]}"+ providers = []+ try:+ subprocess.run(+ [+ "docker",+ "run",+ "--detach",+ "--name",+ name,+ "--add-host",+ "host.docker.internal:host-gateway",+ "--volume",+ f"{config_path}:/etc/otelcol/config.yaml:ro",+ "--publish",+ "127.0.0.1::4318",+ "--publish",+ "127.0.0.1::4327",+ "otel/opentelemetry-collector-contrib:0.119.0",+ "--config=/etc/otelcol/config.yaml",+ ],+ check=True,+ capture_output=True,+ text=True,+ )+ ports = {}+ for internal in (4318, 4327):+ port = int(+ subprocess.run(["docker", "port", name, f"{internal}/tcp"], check=True, capture_output=True, text=True)+ .stdout.strip()+ .rsplit(":", 1)[1]+ )+ ports[internal] = port+ deadline = time.monotonic() + 15+ while True:+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=0.1):+ break+ except OSError:+ assert time.monotonic() < deadline, subprocess.run(+ ["docker", "logs", name], capture_output=True, text=True, check=False+ ).stderr+ time.sleep(0.1)++ def send(service, phase, *, application=False, changes=None, body="inference.lifecycle.completed"):+ exporter = (+ GrpcExporter(endpoint=f"http://127.0.0.1:{ports[4327]}", insecure=True)+ if application+ else HttpExporter(endpoint=f"http://127.0.0.1:{ports[4318]}/v1/logs")+ )+ provider = LoggerProvider(+ resource=Resource(+ {"service.name": service, "service.instance.id": "fixture", "secret": "payload-secret"}+ ),+ shutdown_on_exit=False,+ )+ providers.append(provider)+ provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))+ attrs = {+ "event.name": "inference.lifecycle.completed",+ "event.schema.version": "1",+ "operation": "generate",+ "phase": phase,+ "outcome": "error",+ "error_class": "worker",+ "duration_ms": 12.0,+ "first_token_ms": 2.0,+ "exception.message": "payload-secret",+ }+ attrs.update(changes or {})+ context = set_span_in_context(+ NonRecordingSpan(SpanContext(0x1234567890, 0x12345678, False, TraceFlags(1), TraceState()))+ )+ provider.get_logger(+ "payload-secret", version="payload-secret", attributes={"secret": "payload-secret"}+ ).emit(+ LogRecord(+ timestamp=time.time_ns(),+ context=context,+ body=body,+ severity_text="payload-secret",+ attributes=attrs,+ )+ )++ # Three permitted service/phase pairs; hostile extra fields must vanish.+ send("untrusted-claimed-name", "response_body")+ send("sie-worker", "worker_generation", application=True)+ send("sie-dispatcher", "dispatch_attempt", application=True)+ # Malformed protobuf can repeat a key: filters read the first value,+ # while keep_keys alone retains both. Rebuild the validated scalars.+ duplicate = ExportLogsServiceRequest()+ resource = duplicate.resource_logs.add()+ for key, value in [+ ("service.name", "sie-worker"),+ ("service.version", "fixture"),+ ("service.version", "payload-secret"),+ ]:+ attr = resource.resource.attributes.add(key=key)+ attr.value.string_value = value+ scope = resource.scope_logs.add()+ record = scope.log_records.add(+ time_unix_nano=time.time_ns(),+ trace_id=(0x1234567890).to_bytes(16, "big"),+ span_id=(0x12345678).to_bytes(8, "big"),+ )+ record.body.string_value = "inference.lifecycle.completed"+ for key, value in {+ "event.name": "inference.lifecycle.completed",+ "event.schema.version": "1",+ "operation": "generate",+ "phase": "response_body",+ "outcome": "error",+ "error_class": "worker",+ "duration_ms": 12.0,+ "first_token_ms": 2.0,+ }.items():+ attr = record.attributes.add(key=key)+ if isinstance(value, float):+ attr.value.double_value = value+ else:+ attr.value.string_value = value+ record.attributes.add(key=key).value.string_value = "payload-secret"+ raw_request = urllib.request.Request(+ f"http://127.0.0.1:{ports[4318]}/v1/logs",+ data=duplicate.SerializeToString(),+ headers={"Content-Type": "application/x-protobuf"},+ method="POST",+ )+ with urllib.request.urlopen(raw_request, timeout=5) as response: # noqa: S310 - fixed loopback HTTP+ assert response.status == 200++ for version in ("1", "2"):+ completion = ExportLogsServiceRequest()+ completion.CopyFrom(duplicate)+ resource = completion.resource_logs[0]+ record = resource.scope_logs[0].log_records[0]+ record.body.string_value = "inference.request.completed"+ del record.attributes[:]+ attrs = {+ "event.name": "inference.request.completed",+ "event.schema.version": version,+ "operation": "generate",+ "outcome": "success",+ "http.status_code": 200,+ }+ if version == "2":+ attrs.update(model="other", machine_profile="other", duration_ms=12.0, admission_outcome="admitted")+ for key, value in attrs.items():+ attr = record.attributes.add(key=key)+ if isinstance(value, float):+ attr.value.double_value = value+ elif isinstance(value, int):+ attr.value.int_value = value+ else:+ attr.value.string_value = value+ record.attributes.add(key=key).value.string_value = "payload-secret"+ request = urllib.request.Request(+ f"http://127.0.0.1:{ports[4318]}/v1/logs",+ data=completion.SerializeToString(),+ headers={"Content-Type": "application/x-protobuf"},+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=5) as response: # noqa: S310 - fixed loopback HTTP+ assert response.status == 200++ # Invalid enum/type/body/service/phase fixtures must vanish completely.+ for changes in (+ {"error_class": "payload-secret"},+ {"outcome": "payload-secret"},+ {"operation": "payload-secret"},+ {"duration_ms": "payload-secret"},+ {"duration_ms": -1},+ {"duration_ms": float("nan")},+ {"first_token_ms": float("nan")},+ {"first_token_ms": "payload-secret"},+ {"first_token_ms": 100},+ {"event.schema.version": "2"},+ ):+ send("sie-worker", "worker_generation", application=True, changes=changes)+ send("sie-worker", "worker_generation", application=True, body="payload-secret")+ send("sie-worker", "response_body", application=True)+ send("sie-gateway", "request", application=True)+ send("unknown", "worker_generation", application=True)+ send("sie-worker", "worker_generation")+ for provider in providers:+ provider.shutdown()+ providers.clear()+ records = []+ completions = []+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ try:+ data = received.get(timeout=min(0.2, max(0.001, deadline - time.monotonic())))+ except queue.Empty:+ continue+ request = ExportLogsServiceRequest.FromString(data)+ assert b"payload-secret" not in request.SerializeToString()+ for resource_logs in request.resource_logs:+ resource = {item.key: item.value.string_value for item in resource_logs.resource.attributes}+ assert resource["deployment.environment"] == "dev"+ assert resource["cloud.region"] == "local"+ for scope in resource_logs.scope_logs:+ assert scope.scope.name in ("", "sie-gateway.request-completion")+ assert not scope.scope.version+ assert not scope.scope.attributes+ for record in scope.log_records:+ assert record.trace_id == (0x1234567890).to_bytes(16, "big")+ assert record.span_id == (0x12345678).to_bytes(8, "big")+ attrs = {a.key: a.value for a in record.attributes}+ assert len(attrs) == len(record.attributes)+ if record.body.string_value == "inference.request.completed":+ completions.append(attrs)+ else:+ records.append((resource["service.name"], attrs))+ if len(records) + len(completions) >= 6:+ deadline = min(deadline, time.monotonic() + 1)+ assert {service for service, _attrs in records} == {"sie-gateway", "sie-worker", "sie-dispatcher"}+ assert len(records) == 4+ assert len(completions) == 2+ assert {attrs["event.schema.version"].string_value for attrs in completions} == {"1", "2"}+ allowed = {+ "event.name",+ "event.schema.version",+ "phase",+ "operation",+ "outcome",+ "error_class",+ "duration_ms",+ "first_token_ms",+ }+ assert all(set(attrs) == allowed for _, attrs in records)+ finally:+ for provider in providers:+ provider.shutdown()+ subprocess.run(["docker", "rm", "--force", name], capture_output=True, check=False)+ sink.shutdown()+ sink.server_close()+ thread.join()