Skip to main content

dynamo_runtime/pipeline/network/ingress/
push_handler.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use super::*;
5
6use crate::engine::AsyncEngineContext;
7use crate::error::DynamoError;
8use crate::metrics::prometheus_names::work_handler;
9use crate::metrics::work_handler_perf::{
10    WORK_HANDLER_NETWORK_TRANSIT_SECONDS, WORK_HANDLER_TIME_TO_FIRST_RESPONSE_SECONDS,
11};
12use crate::pipeline::network::{StreamPrologueError, velo_response};
13use crate::pipeline::{ManyIn, RequestStream};
14use crate::telemetry::{LifecycleStage, LifecycleTrace};
15use crate::{dynamo_nvtx_mark, dynamo_nvtx_range};
16use futures::StreamExt;
17use prometheus::{Histogram, IntCounter, IntCounterVec, IntGauge};
18use serde::Deserialize;
19use std::sync::Arc;
20use std::time::Instant;
21use tracing::Instrument;
22use tracing::info_span;
23
24/// Metrics configuration for profiling work handlers
25#[derive(Clone, Debug)]
26pub struct WorkHandlerMetrics {
27    pub request_counter: IntCounter,
28    pub request_duration: Histogram,
29    pub inflight_requests: IntGauge,
30    pub request_bytes: IntCounter,
31    pub response_bytes: IntCounter,
32    pub error_counter: IntCounterVec,
33    pub cancellation_total: IntCounter,
34}
35
36impl WorkHandlerMetrics {
37    pub fn new(
38        request_counter: IntCounter,
39        request_duration: Histogram,
40        inflight_requests: IntGauge,
41        request_bytes: IntCounter,
42        response_bytes: IntCounter,
43        error_counter: IntCounterVec,
44        cancellation_total: IntCounter,
45    ) -> Self {
46        Self {
47            request_counter,
48            request_duration,
49            inflight_requests,
50            request_bytes,
51            response_bytes,
52            error_counter,
53            cancellation_total,
54        }
55    }
56
57    /// Create WorkHandlerMetrics from an endpoint using its built-in labeling
58    pub fn from_endpoint(
59        endpoint: &crate::component::Endpoint,
60        metrics_labels: Option<&[(&str, &str)]>,
61    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
62        let metrics_labels = metrics_labels.unwrap_or(&[]);
63        let metrics = endpoint.metrics();
64        let request_counter = metrics.create_intcounter(
65            work_handler::REQUESTS_TOTAL,
66            "Total number of requests processed by work handler",
67            metrics_labels,
68        )?;
69
70        // Custom buckets for inference workloads: retain sub-second resolution for
71        // fast operations, extend well beyond the default 10s ceiling to capture
72        // long-running generation requests that can last minutes.
73        let request_duration_buckets = vec![
74            0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0,
75            300.0, 600.0,
76        ];
77        let request_duration = metrics.create_histogram(
78            work_handler::REQUEST_DURATION_SECONDS,
79            "Time spent processing requests by work handler",
80            metrics_labels,
81            Some(request_duration_buckets),
82        )?;
83
84        let inflight_requests = metrics.create_intgauge(
85            work_handler::INFLIGHT_REQUESTS,
86            "Number of requests currently being processed by work handler",
87            metrics_labels,
88        )?;
89
90        let request_bytes = metrics.create_intcounter(
91            work_handler::REQUEST_BYTES_TOTAL,
92            "Total number of bytes received in requests by work handler",
93            metrics_labels,
94        )?;
95
96        let response_bytes = metrics.create_intcounter(
97            work_handler::RESPONSE_BYTES_TOTAL,
98            "Total number of bytes sent in responses by work handler",
99            metrics_labels,
100        )?;
101
102        let error_counter = metrics.create_intcountervec(
103            work_handler::ERRORS_TOTAL,
104            "Total number of errors in work handler processing",
105            &[work_handler::ERROR_TYPE_LABEL],
106            metrics_labels,
107        )?;
108
109        let cancellation_total = metrics.create_intcounter(
110            work_handler::CANCELLATION_TOTAL,
111            "Total number of requests cancelled by work handler",
112            metrics_labels,
113        )?;
114
115        Ok(Self::new(
116            request_counter,
117            request_duration,
118            inflight_requests,
119            request_bytes,
120            response_bytes,
121            error_counter,
122            cancellation_total,
123        ))
124    }
125}
126
127// RAII guard to ensure inflight gauge is decremented, request duration is observed,
128// and lifecycle logs are emitted on all code paths.
129struct RequestMetricsGuard {
130    inflight_requests: prometheus::IntGauge,
131    request_duration: prometheus::Histogram,
132    start_time: Instant,
133    request_id: Option<String>,
134}
135
136impl Drop for RequestMetricsGuard {
137    fn drop(&mut self) {
138        self.inflight_requests.dec();
139        self.request_duration
140            .observe(self.start_time.elapsed().as_secs_f64());
141        if let Some(request_id) = &self.request_id {
142            tracing::info!(request_id = %request_id, "request completed");
143        }
144    }
145}
146
147trait ResponsePublisher {
148    async fn send(&self, payload: Bytes) -> anyhow::Result<()>;
149    async fn send_prologue(&mut self, error: Option<String>) -> anyhow::Result<()>;
150
151    /// Send a failure prologue keeping the worker's [`crate::error::ErrorType`]
152    /// where the transport can carry it.
153    ///
154    /// The default drops the type and sends the text alone. TCP and QUIC
155    /// override this so a typed refusal survives the response plane.
156    async fn send_prologue_typed(
157        &mut self,
158        error: Option<StreamPrologueError>,
159    ) -> anyhow::Result<()> {
160        self.send_prologue(error.map(|error| error.message)).await
161    }
162    async fn finish(&mut self) -> anyhow::Result<()>;
163    async fn abort(&mut self) -> anyhow::Result<()>;
164
165    fn reset_on_stop(&self) -> bool {
166        false
167    }
168
169    fn strict_prologue(&self) -> bool {
170        false
171    }
172}
173
174impl ResponsePublisher for velo_response::VeloResponseSender {
175    async fn send(&self, payload: Bytes) -> anyhow::Result<()> {
176        velo_response::VeloResponseSender::send(self, payload).await
177    }
178    async fn send_prologue(&mut self, error: Option<String>) -> anyhow::Result<()> {
179        velo_response::VeloResponseSender::send_prologue(
180            self,
181            error.map(StreamPrologueError::from_message),
182        )
183        .await
184    }
185    async fn send_prologue_typed(
186        &mut self,
187        error: Option<StreamPrologueError>,
188    ) -> anyhow::Result<()> {
189        velo_response::VeloResponseSender::send_prologue(self, error).await
190    }
191    async fn finish(&mut self) -> anyhow::Result<()> {
192        velo_response::VeloResponseSender::finish(self).await
193    }
194    async fn abort(&mut self) -> anyhow::Result<()> {
195        velo_response::VeloResponseSender::abort(self).await
196    }
197    // `reset_on_stop` stays false on purpose. `stop_generating` does not
198    // invalidate results already in the stream, so after a graceful Stop the
199    // frontend still gets what the engine yields, final chunk included. TCP
200    // and QUIC instead end the stream at the worker.
201    fn strict_prologue(&self) -> bool {
202        true
203    }
204}
205
206impl ResponsePublisher for quic_response::QuicResponseSender {
207    async fn send(&self, payload: Bytes) -> anyhow::Result<()> {
208        quic_response::QuicResponseSender::send(self, payload).await
209    }
210
211    async fn send_prologue(&mut self, error: Option<String>) -> anyhow::Result<()> {
212        quic_response::QuicResponseSender::send_prologue(self, error)
213            .await
214            .map_err(anyhow::Error::msg)
215    }
216
217    async fn send_prologue_typed(
218        &mut self,
219        error: Option<StreamPrologueError>,
220    ) -> anyhow::Result<()> {
221        quic_response::QuicResponseSender::send_prologue_typed(self, error)
222            .await
223            .map_err(anyhow::Error::msg)
224    }
225
226    async fn finish(&mut self) -> anyhow::Result<()> {
227        quic_response::QuicResponseSender::finish(self).await
228    }
229
230    async fn abort(&mut self) -> anyhow::Result<()> {
231        quic_response::QuicResponseSender::abort(self).await
232    }
233
234    fn reset_on_stop(&self) -> bool {
235        true
236    }
237
238    fn strict_prologue(&self) -> bool {
239        true
240    }
241}
242
243impl ResponsePublisher for StreamSender {
244    async fn send(&self, payload: Bytes) -> anyhow::Result<()> {
245        StreamSender::send(self, payload).await
246    }
247
248    async fn send_prologue(&mut self, error: Option<String>) -> anyhow::Result<()> {
249        StreamSender::send_prologue(self, error)
250            .await
251            .map_err(anyhow::Error::msg)
252    }
253
254    async fn send_prologue_typed(
255        &mut self,
256        error: Option<StreamPrologueError>,
257    ) -> anyhow::Result<()> {
258        StreamSender::send_prologue_typed(self, error)
259            .await
260            .map_err(anyhow::Error::msg)
261    }
262
263    async fn finish(&mut self) -> anyhow::Result<()> {
264        Ok(())
265    }
266
267    async fn abort(&mut self) -> anyhow::Result<()> {
268        Ok(())
269    }
270}
271
272impl<Req, Resp, Adapter> Ingress<Req, Resp, Adapter>
273where
274    Req: PipelineIO + Sync,
275    Resp: PipelineIO,
276    Adapter: Send + Sync + 'static,
277{
278    /// Pump every chunk from the engine's response stream out to the
279    /// upstream response transport, plus the terminal complete-final
280    /// frame. Captures the per-frame metrics, the publish-failure error
281    /// classification (client-side disconnect vs. real failure), and the
282    /// health-check notifier policy (notify only on non-error chunks and
283    /// at clean stream end).
284    async fn pump_response_stream<U>(
285        &self,
286        mut stream: ManyOut<U>,
287        publisher: &impl ResponsePublisher,
288        payload_codec: RequestPlanePayloadCodec,
289    ) where
290        U: Data + std::fmt::Debug,
291        Adapter: IngressResponseEncoder<U>,
292    {
293        let context = stream.context();
294
295        // TODO: Detect end-of-stream using Server-Sent Events (SSE)
296        let mut send_complete_final = true;
297        let mut saw_error_response = false;
298        while let Some(resp) = stream.next().await {
299            // Everything inside this range is Dynamo-side egress work for one
300            // chunk. The gaps *between* consecutive `worker.egress.chunk` ranges
301            // are the engine producing the next token — that split is the whole
302            // point of the worker annotations. (Frontend-side receive/decode is
303            // a separate, currently unannotated cost; do not attribute it here.)
304            let _nvtx_chunk = dynamo_nvtx_range!("worker.egress.chunk");
305            tracing::trace!("Sending response: {:?}", resp);
306            let nvtx_encode = dynamo_nvtx_range!("worker.egress.encode");
307            let encoded = match self
308                .payload_adapter
309                .encode_response(payload_codec, Some(resp), false)
310                .await
311            {
312                Ok(encoded) => encoded,
313                Err(err) => {
314                    tracing::error!(%err, "failed to encode request-plane response");
315                    saw_error_response = true;
316                    send_complete_final = false;
317                    if let Some(m) = self.metrics() {
318                        m.error_counter
319                            .with_label_values(&[work_handler::error_types::SERIALIZATION])
320                            .inc();
321                    }
322                    break;
323                }
324            };
325            drop(nvtx_encode);
326            let is_error = encoded.is_error;
327            saw_error_response |= is_error;
328            // Notify before the publish: engine progress counts even if the send fails.
329            // Error chunks do not prove health, so they never reset the canary.
330            if !is_error && let Some(notifier) = self.endpoint_health_check_notifier.get() {
331                notifier.notify_one();
332            }
333            let resp_bytes = encoded.bytes;
334            if let Some(m) = self.metrics() {
335                m.response_bytes.inc_by(resp_bytes.len() as u64);
336            }
337            let nvtx_publish = dynamo_nvtx_range!("worker.egress.publish");
338            let publish_result = publisher.send(resp_bytes).await;
339            drop(nvtx_publish);
340            if let Err(send_err) = publish_result {
341                send_complete_final = false;
342                if context.is_stopped() {
343                    // Say there are 2 threads accessing `context`, the sequence can be either:
344                    // 1. context.stop_generating (other) -> publisher.send failure (this)
345                    //    -> context.is_stopped (this)
346                    // 2. publisher.send failure (this) -> context.stop_generating (other)
347                    //    -> context.is_stopped (this)
348                    // Case 1 can happen when client closed the connection after receiving the
349                    // complete response from frontend. Hence, send failure can be expected in this
350                    // case.
351                    tracing::warn!(
352                        error = %send_err,
353                        "Failed to publish response for stream {}",
354                        context.id()
355                    );
356                } else {
357                    // Otherwise, this is an error.
358                    tracing::error!(
359                        error = %send_err,
360                        "Failed to publish response for stream {}",
361                        context.id()
362                    );
363                    context.stop_generating();
364                }
365                // Account errors in all cases, including cancellation. Therefore this metric can be
366                // inflated.
367                if let Some(m) = self.metrics() {
368                    m.error_counter
369                        .with_label_values(&[work_handler::error_types::PUBLISH_RESPONSE])
370                        .inc();
371                }
372                break;
373            }
374            if encoded.stop_stream {
375                // Dropping the engine stream after the terminal frame is sent
376                // propagates cancellation to a producer that is still running.
377                // Stopping the context here can close the response transport
378                // before the queued error and clean terminal frames are read.
379                break;
380            }
381        }
382        // The TCP response writer exits without its clean sentinel when the
383        // worker context is stopped. Preserve that behavior on QUIC: the
384        // caller sends a logical reset instead of a clean terminal frame.
385        if publisher.reset_on_stop() && context.is_stopped() && !context.is_killed() {
386            send_complete_final = false;
387        }
388        if send_complete_final {
389            let encoded = match self
390                .payload_adapter
391                .encode_response(payload_codec, None, true)
392                .await
393            {
394                Ok(encoded) => encoded,
395                Err(err) => {
396                    tracing::error!(%err, "failed to encode request-plane final response");
397                    if let Some(m) = self.metrics() {
398                        m.error_counter
399                            .with_label_values(&[work_handler::error_types::PUBLISH_FINAL])
400                            .inc();
401                    }
402                    return;
403                }
404            };
405            let resp_bytes = encoded.bytes;
406            if let Some(m) = self.metrics() {
407                m.response_bytes.inc_by(resp_bytes.len() as u64);
408            }
409            if (publisher.send(resp_bytes).await).is_err() {
410                // `is_stopped()` is `state != Live`, so it is also true after
411                // `kill()` — which the response-stream reader does on a TCP read
412                // error. Excluding killed narrows this to `state == Stopped` so
413                // real connection failures stay counted. `&&` reads `is_killed()`
414                // last, so a Stopped -> Killed upgrade between the two reads
415                // falls to the error path.
416                //
417                // Reachable only with a peer-sent `Stop`: the local
418                // `stop_generating()` above clears `send_complete_final` and
419                // breaks first. That invariant is load-bearing.
420                if context.is_stopped() && !context.is_killed() {
421                    // The peer asked us to stop, so a failed marker write is
422                    // attributable to that teardown, not to a fault here. Unlike
423                    // the per-frame branch, this also skips the counter.
424                    tracing::debug!(
425                        "Failed to publish complete final for stream {}; client already torn down",
426                        context.id()
427                    );
428                } else {
429                    // Still attached, or killed (hard cancel, protocol violation,
430                    // connection error): the client sees a stream with no
431                    // end-of-stream marker, so this stays a counted error.
432                    tracing::error!(
433                        "Failed to publish complete final for stream {}",
434                        context.id()
435                    );
436                    if let Some(m) = self.metrics() {
437                        m.error_counter
438                            .with_label_values(&[work_handler::error_types::PUBLISH_FINAL])
439                            .inc();
440                    }
441                }
442            }
443            // Only notify on stream completion if no error responses were seen
444            if let (false, Some(notifier)) = (
445                saw_error_response,
446                self.endpoint_health_check_notifier.get(),
447            ) {
448                notifier.notify_one();
449            }
450        }
451    }
452
453    /// Decode the wire envelope into its [`RequestControlMessage`] and the
454    /// optional data payload, shared by every [`IngressDispatch`] shape:
455    ///   - `HeaderAndData` → `(control, Some(data))` — the unary wire shape,
456    ///     where the request body travels in the data half.
457    ///   - `HeaderOnly` → `(control, None)` — the bidirectional wire shape,
458    ///     where request frames flow on the request-stream socket instead.
459    ///
460    /// The caller decides whether its path expects the data payload. The
461    /// deserialization and invalid-message error counters are incremented
462    /// here so every shape reports them consistently.
463    fn decode_control_message(
464        &self,
465        payload: Bytes,
466    ) -> Result<(RequestControlMessage, Option<Bytes>), PipelineError> {
467        let msg = TwoPartCodec::default()
468            .decode_message(payload)?
469            .into_message_type();
470
471        let (header, data) = match msg {
472            TwoPartMessageType::HeaderAndData(header, data) => (header, Some(data)),
473            TwoPartMessageType::HeaderOnly(header) => (header, None),
474            _ => {
475                if let Some(m) = self.metrics() {
476                    m.error_counter
477                        .with_label_values(&[work_handler::error_types::INVALID_MESSAGE])
478                        .inc();
479                }
480                return Err(PipelineError::Generic(String::from(
481                    "Unexpected message from work queue; expected a header-only or header-and-data TwoPartMessage",
482                )));
483            }
484        };
485
486        let control_msg: RequestControlMessage =
487            serde_json::from_slice(&header).map_err(|err| {
488                if let Some(m) = self.metrics() {
489                    m.error_counter
490                        .with_label_values(&[work_handler::error_types::DESERIALIZATION])
491                        .inc();
492                }
493                let json_str = String::from_utf8_lossy(&header);
494                PipelineError::DeserializationError(format!(
495                    "Failed deserializing to RequestControlMessage. err={err}, json_str={json_str}, header_len={}",
496                    header.len(),
497                ))
498            })?;
499
500        Ok((control_msg, data))
501    }
502}
503/// The output of [`IngressDispatch::parse_and_build_request`]: the typed
504/// request the engine consumes, plus the bits of the on-wire control
505/// message the shared handler needs after parsing (the response-stream
506/// connection info and the frontend send timestamp).
507struct ParsedRequest<Req> {
508    request: Req,
509    response_connection_info: ConnectionInfo,
510    frontend_send_ts_ns: Option<u64>,
511    payload_codec: RequestPlanePayloadCodec,
512}
513
514#[derive(Clone, Copy)]
515struct ResponsePlaneModes {
516    configured: ResponsePlaneMode,
517    advertised: ResponsePlaneMode,
518}
519
520/// Per-shape strategy for turning a raw payload into a typed engine
521/// request. Captures the wire-shape divergence between the unary
522/// (`HeaderAndData`) and bidirectional (`HeaderOnly` + dial-in for the
523/// request stream) paths; everything else — metrics-guard, response stream
524/// open, `segment.generate`, prologue, pump — lives in
525/// [`Ingress::handle_payload_shared`] below.
526#[async_trait]
527trait IngressDispatch: Send + Sync {
528    type Request: PipelineIO;
529
530    async fn parse_and_build_request(
531        &self,
532        control_msg: RequestControlMessage,
533        data: Option<Bytes>,
534    ) -> Result<ParsedRequest<Self::Request>, PipelineError>;
535}
536
537#[async_trait]
538impl<T, U, Adapter> IngressDispatch for Ingress<SingleIn<T>, ManyOut<U>, Adapter>
539where
540    T: Data + for<'de> Deserialize<'de> + std::fmt::Debug,
541    U: Data + std::fmt::Debug,
542    Adapter: IngressRequestDecoder<T> + Send + Sync + 'static,
543{
544    type Request = SingleIn<T>;
545
546    async fn parse_and_build_request(
547        &self,
548        control_msg: RequestControlMessage,
549        data: Option<Bytes>,
550    ) -> Result<ParsedRequest<SingleIn<T>>, PipelineError> {
551        // The unary path carries the request body in the data half; a
552        // header-only envelope means the sender used the bidirectional shape.
553        let data = data.ok_or_else(|| {
554            if let Some(m) = self.metrics() {
555                m.error_counter
556                    .with_label_values(&[work_handler::error_types::INVALID_MESSAGE])
557                    .inc();
558            }
559            PipelineError::Generic(String::from(
560                "unary engine received a header-only envelope; expected a request payload",
561            ))
562        })?;
563        let payload_codec = control_msg.payload_codec;
564        let request_t: T = self
565            .payload_adapter
566            .decode_request(payload_codec, data)
567            .await
568            .inspect_err(|_| {
569                if let Some(m) = self.metrics() {
570                    m.error_counter
571                        .with_label_values(&[work_handler::error_types::DESERIALIZATION])
572                        .inc();
573                }
574            })?;
575
576        tracing::trace!(
577            request_id = %control_msg.id,
578            metadata_entries = control_msg.metadata.len(),
579            "received control message"
580        );
581        tracing::trace!("received request: {:?}", request_t);
582
583        let request: context::Context<T> =
584            Context::with_id_and_metadata(request_t, control_msg.id, control_msg.metadata);
585
586        Ok(ParsedRequest {
587            request,
588            response_connection_info: control_msg.connection_info,
589            frontend_send_ts_ns: control_msg.frontend_send_ts_ns,
590            payload_codec,
591        })
592    }
593}
594
595#[async_trait]
596impl<T, U, Adapter> IngressDispatch for Ingress<ManyIn<T>, ManyOut<U>, Adapter>
597where
598    T: Data + for<'de> Deserialize<'de> + std::fmt::Debug,
599    U: Data + std::fmt::Debug,
600    Adapter: IngressRequestDecoder<T> + Send + Sync + 'static,
601{
602    type Request = ManyIn<T>;
603
604    async fn parse_and_build_request(
605        &self,
606        control_msg: RequestControlMessage,
607        data: Option<Bytes>,
608    ) -> Result<ParsedRequest<ManyIn<T>>, PipelineError> {
609        // Bidirectional envelopes are header-only — all request frames
610        // (including the first) flow on the request-stream socket once it's
611        // dialed in. A data payload means the sender used the unary wire
612        // shape; reject it.
613        if data.is_some() {
614            if let Some(m) = self.metrics() {
615                m.error_counter
616                    .with_label_values(&[work_handler::error_types::INVALID_MESSAGE])
617                    .inc();
618            }
619            return Err(PipelineError::Generic(String::from(
620                "bidirectional engine received a non-header-only envelope",
621            )));
622        }
623
624        if !matches!(control_msg.request_type, RequestType::ManyIn) {
625            if let Some(m) = self.metrics() {
626                m.error_counter
627                    .with_label_values(&[work_handler::error_types::INVALID_MESSAGE])
628                    .inc();
629            }
630            return Err(PipelineError::Generic(String::from(
631                "bidirectional engine received a non-ManyIn request envelope",
632            )));
633        }
634
635        let req_stream_conn_info = control_msg
636            .request_stream_connection_info
637            .clone()
638            .ok_or_else(|| {
639                PipelineError::Generic(String::from(
640                    "bidirectional control message missing request_stream_connection_info",
641                ))
642            })?;
643
644        let request_context: context::Context<()> = context::Context::with_id_and_metadata(
645            (),
646            control_msg.id.clone(),
647            control_msg.metadata.clone(),
648        );
649        let payload_codec = control_msg.payload_codec;
650        let context_arc: Arc<dyn AsyncEngineContext> = request_context.context();
651
652        // Open the request stream (upstream → worker) up front. The shared
653        // handler opens the response stream uniformly after we return. If
654        // response-stream open subsequently fails, the forwarder task
655        // spawned below exits cleanly when `frame_tx.send` observes the
656        // dropped `frame_rx`.
657        let request_stream_recv = tcp::client::TcpClient::create_request_stream(
658            context_arc.clone(),
659            req_stream_conn_info,
660            None,
661        )
662        .await
663        .map_err(|e| {
664            if let Some(m) = self.metrics() {
665                m.error_counter
666                    .with_label_values(&[work_handler::error_types::RESPONSE_STREAM])
667                    .inc();
668            }
669            PipelineError::Generic(format!("Failed to create request stream: {e}"))
670        })?;
671
672        // Forwarder: deserialize raw bytes off the request socket into `T`
673        // and feed the engine's `ManyIn<T>` input. Every request frame
674        // (including the first) flows over this socket — the envelope is
675        // header-only.
676        let (frame_tx, frame_rx) = tokio::sync::mpsc::channel::<T>(8);
677        let forwarder_ctx = context_arc.clone();
678        let payload_adapter = self.payload_adapter.clone();
679        tokio::spawn(async move {
680            let mut rx = request_stream_recv.rx;
681            while let Some(bytes) = rx.recv().await {
682                // Stop forwarding on either kill or soft-stop, matching the
683                // send-side `spawn_request_stream_forwarder`. Without the
684                // `stopped()` check, a `stop_generating()` would leave this
685                // task pumping frames into a channel the engine has abandoned.
686                if forwarder_ctx.is_killed() || forwarder_ctx.is_stopped() {
687                    break;
688                }
689                match payload_adapter.decode_request(payload_codec, bytes).await {
690                    Ok(item) => {
691                        if frame_tx.send(item).await.is_err() {
692                            tracing::debug!(
693                                "engine consumer dropped; bidirectional input forwarder exiting"
694                            );
695                            break;
696                        }
697                    }
698                    Err(e) => {
699                        tracing::error!(
700                            error = %e,
701                            codec = payload_codec.name(),
702                            "failed to deserialize bidirectional request frame; killing context"
703                        );
704                        forwarder_ctx.kill();
705                        break;
706                    }
707                }
708            }
709        });
710
711        let input_stream: crate::engine::DataStream<T> =
712            Box::pin(tokio_stream::wrappers::ReceiverStream::new(frame_rx));
713        let request: ManyIn<T> = request_context.map(|_| RequestStream::new(input_stream));
714
715        Ok(ParsedRequest {
716            request,
717            response_connection_info: control_msg.connection_info,
718            frontend_send_ts_ns: control_msg.frontend_send_ts_ns,
719            payload_codec,
720        })
721    }
722}
723
724impl<Req, U, Adapter> Ingress<Req, ManyOut<U>, Adapter>
725where
726    Req: PipelineIO + Sync,
727    U: Data + std::fmt::Debug,
728    Adapter: IngressResponseEncoder<U> + Send + Sync + 'static,
729{
730    async fn generate_and_publish<P>(
731        &self,
732        request: Req,
733        payload_codec: RequestPlanePayloadCodec,
734        start_time: Instant,
735        response_modes: ResponsePlaneModes,
736        lifecycle: &LifecycleTrace,
737        mut publisher: P,
738    ) -> Result<(), PipelineError>
739    where
740        Self: IngressDispatch<Request = Req>,
741        P: ResponsePublisher,
742    {
743        let ResponsePlaneModes {
744            configured: configured_mode,
745            advertised: advertised_mode,
746        } = response_modes;
747
748        if configured_mode != advertised_mode {
749            let message = format!(
750                "response plane mismatch: frontend requested {}, worker configured {}",
751                advertised_mode.name(),
752                configured_mode.name()
753            );
754            let _ = publisher.send_prologue(Some(message.clone())).await;
755            let _ = publisher.finish().await;
756            return Err(PipelineError::Generic(message));
757        }
758
759        let request_context = request.context();
760        tracing::trace!("calling generate");
761        let worker_operation = lifecycle.start_worker_operation();
762        // Dispatch into the engine. For a Python worker this covers the pyo3
763        // bridge crossing that builds the response generator, not token
764        // generation itself.
765        let nvtx_generate = dynamo_nvtx_range!("worker.ingress.generate");
766        let stream = async {
767            self.segment
768                .get()
769                .expect("segment not set")
770                .generate(request)
771                .instrument(lifecycle.start(LifecycleStage::RequestDispatch))
772                .await
773        }
774        .instrument(worker_operation.clone())
775        .await
776        .map_err(|error| {
777            if let Some(metrics) = self.metrics() {
778                metrics
779                    .error_counter
780                    .with_label_values(&[work_handler::error_types::GENERATE])
781                    .inc();
782            }
783            PipelineError::GenerateError(error)
784        });
785        drop(nvtx_generate);
786
787        let stream = match stream {
788            Ok(stream) => {
789                tracing::trace!("Successfully generated response stream; sending prologue");
790                let result = publisher.send_prologue(None).await;
791                // Marked only on a successful send: the prologue is what tells the
792                // frontend the stream is live, so a marker on the failure path would
793                // put an acknowledgement on the timeline that the frontend never got.
794                let prologue_sent = result.is_ok();
795                if publisher.strict_prologue() {
796                    result.map_err(|error| {
797                        if let Some(metrics) = self.metrics() {
798                            metrics
799                                .error_counter
800                                .with_label_values(&[work_handler::error_types::RESPONSE_STREAM])
801                                .inc();
802                        }
803                        PipelineError::Generic(format!(
804                            "Failed to open {} response stream: {error}",
805                            configured_mode.name()
806                        ))
807                    })?;
808                }
809                if prologue_sent {
810                    dynamo_nvtx_mark!("worker.ingress.prologue_sent");
811                }
812                WORK_HANDLER_TIME_TO_FIRST_RESPONSE_SECONDS
813                    .observe(start_time.elapsed().as_secs_f64());
814                stream
815            }
816            Err(error) => {
817                let error_string = error.to_string();
818
819                #[cfg(debug_assertions)]
820                tracing::debug!(
821                    "Failed to generate response stream (with debug backtrace): {:?}",
822                    error
823                );
824                #[cfg(not(debug_assertions))]
825                tracing::error!("Failed to generate response stream: {error_string}");
826
827                if publisher.reset_on_stop()
828                    && request_context.is_stopped()
829                    && !request_context.is_killed()
830                {
831                    let _ = publisher.abort().await;
832                } else {
833                    // Send the worker's error type with the display text, so a
834                    // frontend can tell a request the backend cannot serve from
835                    // a transport failure.
836                    let prologue_error = StreamPrologueError::new(
837                        error_string,
838                        typed_error_from_pipeline_error(&error),
839                    );
840                    let _ = publisher.send_prologue_typed(Some(prologue_error)).await;
841                }
842                return Err(error);
843            }
844        };
845
846        async {
847            self.pump_response_stream(stream, &publisher, payload_codec)
848                .instrument(lifecycle.start_worker_response_streaming())
849                .await
850        }
851        .instrument(worker_operation)
852        .await;
853        let finish = if publisher.reset_on_stop()
854            && request_context.is_stopped()
855            && !request_context.is_killed()
856        {
857            publisher.abort().await
858        } else {
859            publisher.finish().await
860        };
861        finish.map_err(|error| {
862            PipelineError::Generic(format!(
863                "Failed to finish {} response stream: {error}",
864                configured_mode.name()
865            ))
866        })
867    }
868
869    /// Shared body of `PushWorkHandler::handle_payload` for every
870    /// `Ingress<Req, ManyOut<U>>` shape that has an [`IngressDispatch`]
871    /// impl. Sets up the inflight metrics guard, calls
872    /// `parse_and_build_request` for the wire-shape-specific request
873    /// building, opens the response stream uniformly, dispatches via
874    /// the engine, sends the prologue, and pumps the response through
875    /// [`Self::pump_response_stream`].
876    async fn handle_payload_shared(
877        &self,
878        payload: Bytes,
879        request_id: Option<String>,
880    ) -> Result<(), PipelineError>
881    where
882        Self: IngressDispatch<Request = Req>,
883    {
884        // Outer band for one request's entire time inside the worker, from wire
885        // arrival to terminal frame. Held across awaits, hence a start/end range.
886        let _nvtx_request = dynamo_nvtx_range!("worker.ingress.request");
887
888        let t2_wallclock_ns = std::time::SystemTime::now()
889            .duration_since(std::time::UNIX_EPOCH)
890            .unwrap_or_default()
891            .as_nanos() as u64;
892        let start_time = std::time::Instant::now();
893        // Increment inflight and ensure it's decremented on all exits via RAII guard
894        let _inflight_guard = self.metrics().map(|m| {
895            m.request_counter.inc();
896            m.inflight_requests.inc();
897            m.request_bytes.inc_by(payload.len() as u64);
898            if let Some(rid) = &request_id {
899                tracing::info!(request_id = %rid, "request received");
900            }
901            RequestMetricsGuard {
902                inflight_requests: m.inflight_requests.clone(),
903                request_duration: m.request_duration.clone(),
904                start_time,
905                request_id: request_id.clone(),
906            }
907        });
908
909        let (control_msg, data) = self.decode_control_message(payload)?;
910        let lifecycle = match self.registered_lifecycle_role() {
911            Some(role)
912                if control_msg
913                    .metadata
914                    .get(crate::telemetry::LIFECYCLE_ROOT_METADATA_KEY)
915                    .is_some_and(|version| version == "v1") =>
916            {
917                LifecycleTrace::from_request_id_with_role(control_msg.id.clone(), role)
918            }
919            _ => LifecycleTrace::new(false),
920        };
921
922        // Admission begins after the envelope selects capture, before payload
923        // decoding and response setup. Hold without entering it: response
924        // readers capture the current span and live until the request ends.
925        // They must inherit handle_payload, not prolong worker.admission.
926        let worker_admission = lifecycle.start(LifecycleStage::WorkerAdmission);
927        let nvtx_parse = dynamo_nvtx_range!("worker.ingress.parse_request");
928        let ParsedRequest {
929            request,
930            response_connection_info,
931            frontend_send_ts_ns,
932            payload_codec,
933        } = self.parse_and_build_request(control_msg, data).await?;
934        drop(nvtx_parse);
935
936        // Compute network transit time (T2 - T1) using cross-process wall-clock timestamps
937        if let Some(t1_ns) = frontend_send_ts_ns {
938            let transit_ns = t2_wallclock_ns.saturating_sub(t1_ns);
939            WORK_HANDLER_NETWORK_TRANSIT_SECONDS.observe(transit_ns as f64 / 1_000_000_000.0);
940        }
941
942        let advertised_mode =
943            ResponsePlaneMode::from_transport_name(&response_connection_info.transport)
944                .map_err(|error| PipelineError::Generic(error.to_string()))?;
945        let configured_mode = match self.response_plane.get() {
946            Some(mode) => *mode,
947            None => ResponsePlaneMode::configured()
948                .map_err(|error| PipelineError::Generic(error.to_string()))?,
949        };
950        let response_modes = ResponsePlaneModes {
951            configured: configured_mode,
952            advertised: advertised_mode,
953        };
954        let cancellation_counter = self
955            .metrics()
956            .map(|metrics| metrics.cancellation_total.clone());
957
958        match advertised_mode {
959            ResponsePlaneMode::Tcp => {
960                tracing::trace!("creating tcp response stream");
961                let nvtx_open = dynamo_nvtx_range!("worker.ingress.open_response_stream");
962                let publisher = tcp::client::TcpClient::create_response_stream(
963                    request.context(),
964                    response_connection_info,
965                    cancellation_counter,
966                )
967                .await
968                .map_err(|error| {
969                    if let Some(metrics) = self.metrics() {
970                        metrics
971                            .error_counter
972                            .with_label_values(&[work_handler::error_types::RESPONSE_STREAM])
973                            .inc();
974                    }
975                    PipelineError::Generic(format!("Failed to create response stream: {error}"))
976                })?;
977                drop(nvtx_open);
978                drop(worker_admission);
979                self.generate_and_publish(
980                    request,
981                    payload_codec,
982                    start_time,
983                    response_modes,
984                    &lifecycle,
985                    publisher,
986                )
987                .await?;
988            }
989            ResponsePlaneMode::Velo => {
990                let context = request.context();
991                let publisher = async {
992                    let service = self.velo_response_service().await?;
993                    service
994                        .sender(
995                            context.clone(),
996                            response_connection_info,
997                            cancellation_counter,
998                        )
999                        .await
1000                }
1001                .await
1002                .map_err(|error| {
1003                    if let Some(metrics) = self.metrics() {
1004                        metrics
1005                            .error_counter
1006                            .with_label_values(&[work_handler::error_types::RESPONSE_STREAM])
1007                            .inc();
1008                    }
1009                    PipelineError::Generic(format!(
1010                        "Failed to create Velo response stream: {error}"
1011                    ))
1012                })?;
1013                drop(worker_admission);
1014                tokio::select! {
1015                    biased;
1016                    _ = context.killed() => return Ok(()),
1017                    result = self.generate_and_publish(request, payload_codec, start_time, response_modes, &lifecycle, publisher) => result?,
1018                }
1019            }
1020            ResponsePlaneMode::Quic => {
1021                tracing::trace!("creating QUIC response sender");
1022                let nvtx_open = dynamo_nvtx_range!("worker.ingress.open_response_stream");
1023                let response_pool = self.quic_response_client_pool()?;
1024                let publisher = response_pool
1025                    .sender_with_cancellation_metric(
1026                        request.context(),
1027                        response_connection_info,
1028                        cancellation_counter,
1029                    )
1030                    .await
1031                    .map_err(|error| {
1032                        if let Some(metrics) = self.metrics() {
1033                            metrics
1034                                .error_counter
1035                                .with_label_values(&[work_handler::error_types::RESPONSE_STREAM])
1036                                .inc();
1037                        }
1038                        PipelineError::Generic(format!(
1039                            "Failed to create QUIC response stream: {error}"
1040                        ))
1041                    })?;
1042                drop(nvtx_open);
1043                drop(worker_admission);
1044                self.generate_and_publish(
1045                    request,
1046                    payload_codec,
1047                    start_time,
1048                    response_modes,
1049                    &lifecycle,
1050                    publisher,
1051                )
1052                .await?;
1053            }
1054        }
1055
1056        // Ensure the metrics guard is not dropped until the end of the function.
1057        // Drop fires "request completed" log via RAII.
1058        drop(_inflight_guard);
1059
1060        Ok(())
1061    }
1062}
1063
1064#[async_trait]
1065impl<T, U, Adapter> PushWorkHandler for Ingress<SingleIn<T>, ManyOut<U>, Adapter>
1066where
1067    T: Data + for<'de> Deserialize<'de> + std::fmt::Debug,
1068    U: Data + std::fmt::Debug,
1069    Adapter: IngressPayloadAdapter<T, U> + Send + Sync + 'static,
1070{
1071    fn bind_endpoint(&self, endpoint: &crate::component::Endpoint) {
1072        self.bind_endpoint_config(endpoint);
1073    }
1074
1075    fn add_metrics(
1076        &self,
1077        endpoint: &crate::component::Endpoint,
1078        metrics_labels: Option<&[(&str, &str)]>,
1079    ) -> Result<()> {
1080        // Call the inherent `Ingress::add_metrics`, not this trait method.
1081        Ingress::add_metrics(self, endpoint, metrics_labels)
1082    }
1083
1084    fn set_endpoint_health_check_notifier(&self, notifier: Arc<tokio::sync::Notify>) -> Result<()> {
1085        self.endpoint_health_check_notifier
1086            .set(notifier)
1087            .map_err(|_| anyhow::anyhow!("Endpoint health check notifier already set"))?;
1088        Ok(())
1089    }
1090
1091    async fn handle_payload(
1092        &self,
1093        payload: Bytes,
1094        request_id: Option<String>,
1095    ) -> Result<(), PipelineError> {
1096        self.handle_payload_shared(payload, request_id).await
1097    }
1098}
1099
1100#[async_trait]
1101impl<T, U, Adapter> PushWorkHandler for Ingress<ManyIn<T>, ManyOut<U>, Adapter>
1102where
1103    T: Data + for<'de> Deserialize<'de> + std::fmt::Debug,
1104    U: Data + std::fmt::Debug,
1105    Adapter: IngressPayloadAdapter<T, U> + Send + Sync + 'static,
1106{
1107    fn bind_endpoint(&self, endpoint: &crate::component::Endpoint) {
1108        self.bind_endpoint_config(endpoint);
1109    }
1110
1111    fn add_metrics(
1112        &self,
1113        endpoint: &crate::component::Endpoint,
1114        metrics_labels: Option<&[(&str, &str)]>,
1115    ) -> Result<()> {
1116        // Call the inherent `Ingress::add_metrics`, not this trait method.
1117        Ingress::add_metrics(self, endpoint, metrics_labels)
1118    }
1119
1120    fn set_endpoint_health_check_notifier(&self, notifier: Arc<tokio::sync::Notify>) -> Result<()> {
1121        self.endpoint_health_check_notifier
1122            .set(notifier)
1123            .map_err(|_| anyhow::anyhow!("Endpoint health check notifier already set"))?;
1124        Ok(())
1125    }
1126
1127    async fn handle_payload(
1128        &self,
1129        payload: Bytes,
1130        request_id: Option<String>,
1131    ) -> Result<(), PipelineError> {
1132        self.handle_payload_shared(payload, request_id).await
1133    }
1134}
1135
1136/// Recover the worker's typed error from a pipeline failure, for the prologue.
1137///
1138/// `GenerateError` must unwrap its `anyhow::Error` payload first. `anyhow::Error`
1139/// does not implement `std::error::Error`, so that variant exposes no `source()`
1140/// and converting the enclosing `PipelineError` yields a bare
1141/// `ErrorType::Unknown`, losing the worker error type. Any other variant carries
1142/// no worker error and converts to `ErrorType::Unknown`.
1143///
1144/// A [`PipelineError::DuplicateRequestId`] refusal is typed
1145/// [`crate::error::ErrorType::Conflict`]: the worker is healthy and still serving
1146/// the earlier request with that id, so fault detection must not quarantine it.
1147pub(crate) fn typed_error_from_pipeline_error(e: &PipelineError) -> DynamoError {
1148    let source: &(dyn std::error::Error + 'static) = match e {
1149        PipelineError::GenerateError(inner) => inner.as_ref(),
1150        other => other,
1151    };
1152    let is_duplicate_id = std::iter::successors(Some(source), |e| e.source()).any(|e| {
1153        matches!(
1154            e.downcast_ref::<PipelineError>(),
1155            Some(PipelineError::DuplicateRequestId(_))
1156        )
1157    });
1158    if is_duplicate_id {
1159        return DynamoError::builder()
1160            .error_type(crate::error::ErrorType::Conflict)
1161            .message(source.to_string())
1162            .build();
1163    }
1164    DynamoError::from(source)
1165}
1166
1167#[cfg(test)]
1168mod tests {
1169    use super::*;
1170    use crate::pipeline::network::{Ingress, RequestPlanePayloadCodec, StreamSender};
1171    use crate::pipeline::{Context, ManyOut, ResponseStream, SingleIn};
1172    use crate::protocols::annotated::Annotated;
1173    use futures::{FutureExt, Stream, stream};
1174    use prometheus::{Histogram, HistogramOpts, IntCounter, IntCounterVec, IntGauge, Opts};
1175    use std::sync::atomic::{AtomicBool, Ordering};
1176
1177    use crate::error::{BackendError, ErrorType};
1178
1179    type TestRequest = serde_json::Value;
1180    type TestResponse = Annotated<serde_json::Value>;
1181    type TestIngress = Ingress<SingleIn<TestRequest>, ManyOut<TestResponse>>;
1182
1183    /// The positive half of the recovery hop: a worker's typed refusal, boxed
1184    /// into the `anyhow::Error` payload of `PipelineError::GenerateError`,
1185    /// comes back out with its type intact.
1186    #[test]
1187    fn generate_error_payload_keeps_the_workers_error_type() {
1188        let e = PipelineError::GenerateError(anyhow::Error::new(
1189            DynamoError::builder()
1190                .error_type(ErrorType::Backend(BackendError::InvalidArgument))
1191                .message("multimodal input is not supported by this backend")
1192                .build(),
1193        ));
1194
1195        assert_eq!(
1196            typed_error_from_pipeline_error(&e).error_type(),
1197            ErrorType::Backend(BackendError::InvalidArgument),
1198            "the worker's type must survive the anyhow payload"
1199        );
1200    }
1201
1202    /// The negative half: a failure that is not a worker's `generate()` error
1203    /// has no worker classification and uses the canonical internal fallback.
1204    #[test]
1205    fn non_generate_pipeline_error_is_internal_unclassified() {
1206        let e = PipelineError::DeserializationError("bad request payload".to_string());
1207        let error = typed_error_from_pipeline_error(&e);
1208
1209        assert_eq!(error.class(), ErrorType::Internal);
1210        assert_eq!(error.reason().as_str(), "runtime.unclassified");
1211    }
1212
1213    #[test]
1214    fn duplicate_request_id_is_a_conflict() {
1215        let e = PipelineError::GenerateError(anyhow::Error::new(
1216            PipelineError::DuplicateRequestId("same-id".to_string()),
1217        ));
1218        let error = typed_error_from_pipeline_error(&e);
1219
1220        assert_eq!(error.class(), ErrorType::Conflict);
1221        assert_eq!(error.reason().as_str(), "request.conflict");
1222    }
1223
1224    #[derive(Clone, Default)]
1225    struct AdmissionCapture {
1226        started: Arc<AtomicBool>,
1227        closed: Arc<AtomicBool>,
1228    }
1229
1230    impl<S> tracing_subscriber::Layer<S> for AdmissionCapture
1231    where
1232        S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
1233    {
1234        fn on_new_span(
1235            &self,
1236            attrs: &tracing::span::Attributes<'_>,
1237            _id: &tracing::span::Id,
1238            _ctx: tracing_subscriber::layer::Context<'_, S>,
1239        ) {
1240            if attrs.metadata().name() == "worker.admission" {
1241                self.started.store(true, Ordering::SeqCst);
1242            }
1243        }
1244
1245        fn on_close(&self, id: tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
1246            if ctx.span(&id).unwrap().metadata().name() == "worker.admission" {
1247                self.closed.store(true, Ordering::SeqCst);
1248            }
1249        }
1250    }
1251
1252    struct AdmissionProbe(AdmissionCapture, bool);
1253
1254    #[async_trait]
1255    impl crate::engine::AsyncEngine<SingleIn<TestRequest>, ManyOut<TestResponse>, anyhow::Error>
1256        for AdmissionProbe
1257    {
1258        async fn generate(
1259            &self,
1260            _request: SingleIn<TestRequest>,
1261        ) -> anyhow::Result<ManyOut<TestResponse>> {
1262            assert_eq!(self.0.started.load(Ordering::SeqCst), self.1);
1263            assert_eq!(
1264                self.0.closed.load(Ordering::SeqCst),
1265                self.1,
1266                "admission must close before generation, while the TCP reader is still alive"
1267            );
1268            anyhow::bail!("admission probe finished")
1269        }
1270    }
1271
1272    #[tokio::test]
1273    async fn lifecycle_admission_closes_before_generation_and_skips_control_calls() {
1274        use tracing::instrument::WithSubscriber;
1275        use tracing_subscriber::prelude::*;
1276
1277        // Configuration is process-scoped. Isolate this enabled-mode test from
1278        // other tests which may have initialized the disabled default already.
1279        const CHILD: &str = "DYNAMO_LIFECYCLE_ADMISSION_TEST_CHILD";
1280        if std::env::var_os(CHILD).is_none() {
1281            let status = std::process::Command::new(std::env::current_exe().unwrap())
1282                .args([
1283                    "--exact",
1284                    "pipeline::network::ingress::push_handler::tests::lifecycle_admission_closes_before_generation_and_skips_control_calls",
1285                    "--nocapture",
1286                ])
1287                .env(CHILD, "1")
1288                .env("DYN_LIFECYCLE_TRACE_ENABLED", "true")
1289                .status()
1290                .unwrap();
1291            assert!(status.success(), "isolated admission regression failed");
1292            return;
1293        }
1294
1295        temp_env::async_with_vars(
1296            [
1297                ("DYN_LIFECYCLE_TRACE_ENABLED", Some("true")),
1298                ("DYN_RESPONSE_PLANE", Some("tcp")),
1299            ],
1300            async {
1301                for (inference, rooted) in
1302                    [(true, true), (true, false), (false, true), (false, false)]
1303                {
1304                    let capture = AdmissionCapture::default();
1305                    let _interest_guard = crate::test_utils::tracing_interest_guard();
1306                    let subscriber = tracing_subscriber::registry().with(capture.clone());
1307                    async {
1308                        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1309                        let address = listener.local_addr().unwrap().to_string();
1310                        let peer = tokio::spawn(async move {
1311                            let (mut socket, _) = listener.accept().await.unwrap();
1312                            let _ = tokio::io::copy(&mut socket, &mut tokio::io::sink()).await;
1313                        });
1314                        let engine = Arc::new(AdmissionProbe(capture, inference && rooted));
1315                        let ingress = if inference {
1316                            TestIngress::for_engine_with_lifecycle_role(
1317                                engine,
1318                                crate::telemetry::LifecycleOperationRole::Worker,
1319                            )
1320                        } else {
1321                            TestIngress::for_engine(engine)
1322                        }
1323                        .unwrap();
1324                        let connection: ConnectionInfo = tcp::TcpStreamConnectionInfo {
1325                            address,
1326                            subject: "admission-probe".to_string(),
1327                            context: "admission-probe".to_string(),
1328                            stream_type: crate::pipeline::network::StreamType::Response,
1329                        }
1330                        .into();
1331                        let metadata = if rooted {
1332                            std::collections::BTreeMap::from([(
1333                                crate::telemetry::LIFECYCLE_ROOT_METADATA_KEY,
1334                                "v1",
1335                            )])
1336                        } else {
1337                            std::collections::BTreeMap::new()
1338                        };
1339                        let header = serde_json::to_vec(&serde_json::json!({
1340                            "id": "admission-probe",
1341                            "request_type": "single_in",
1342                            "response_type": "many_out",
1343                            "connection_info": connection,
1344                            "metadata": metadata,
1345                        }))
1346                        .unwrap();
1347                        let payload = TwoPartCodec::default()
1348                            .encode_message(TwoPartMessage::from_parts(
1349                                header.into(),
1350                                Bytes::from_static(b"{}"),
1351                            ))
1352                            .unwrap();
1353                        let error = tokio::time::timeout(
1354                            std::time::Duration::from_secs(10),
1355                            ingress
1356                                .handle_payload_shared(payload, Some("admission-probe".to_string()))
1357                                .instrument(tracing::info_span!("handle_payload")),
1358                        )
1359                        .await
1360                        .expect("local admission probe timed out")
1361                        .unwrap_err();
1362                        assert!(error.to_string().contains("admission probe finished"));
1363                        peer.abort();
1364                        let _ = peer.await;
1365                    }
1366                    .with_subscriber(subscriber)
1367                    .await;
1368                }
1369            },
1370        )
1371        .await;
1372    }
1373
1374    #[derive(Default)]
1375    struct MismatchPublisher {
1376        prologue: Arc<std::sync::Mutex<Option<Option<String>>>>,
1377        finished: Arc<AtomicBool>,
1378    }
1379
1380    impl ResponsePublisher for MismatchPublisher {
1381        async fn send(&self, _payload: Bytes) -> anyhow::Result<()> {
1382            panic!("mismatch must not send response data")
1383        }
1384
1385        async fn send_prologue(&mut self, error: Option<String>) -> anyhow::Result<()> {
1386            *self.prologue.lock().unwrap() = Some(error);
1387            Ok(())
1388        }
1389
1390        async fn finish(&mut self) -> anyhow::Result<()> {
1391            self.finished.store(true, Ordering::Release);
1392            Ok(())
1393        }
1394
1395        async fn abort(&mut self) -> anyhow::Result<()> {
1396            panic!("mismatch must finish with a frontend-visible error")
1397        }
1398    }
1399
1400    #[tokio::test]
1401    async fn response_plane_mismatch_reports_error_before_generate() {
1402        for (configured, advertised) in [
1403            (ResponsePlaneMode::Tcp, ResponsePlaneMode::Quic),
1404            (ResponsePlaneMode::Quic, ResponsePlaneMode::Tcp),
1405        ] {
1406            let ingress = TestIngress::new();
1407            let publisher = MismatchPublisher::default();
1408            let prologue = publisher.prologue.clone();
1409            let finished = publisher.finished.clone();
1410            let lifecycle = LifecycleTrace::new(false);
1411
1412            let error = ingress
1413                .generate_and_publish(
1414                    Context::new(serde_json::json!({})),
1415                    RequestPlanePayloadCodec::Json,
1416                    Instant::now(),
1417                    ResponsePlaneModes {
1418                        configured,
1419                        advertised,
1420                    },
1421                    &lifecycle,
1422                    publisher,
1423                )
1424                .await
1425                .expect_err("mismatched response planes must fail");
1426
1427            let expected = format!(
1428                "response plane mismatch: frontend requested {}, worker configured {}",
1429                advertised.name(),
1430                configured.name()
1431            );
1432            assert!(error.to_string().contains(&expected));
1433            assert_eq!(*prologue.lock().unwrap(), Some(Some(expected)));
1434            assert!(finished.load(Ordering::Acquire));
1435        }
1436    }
1437
1438    /// Standalone metrics, not bound to an `Endpoint`, so the test needs no DRT.
1439    fn test_metrics() -> WorkHandlerMetrics {
1440        WorkHandlerMetrics::new(
1441            IntCounter::with_opts(Opts::new("requests_total", "t")).unwrap(),
1442            Histogram::with_opts(HistogramOpts::new("request_duration_seconds", "t")).unwrap(),
1443            IntGauge::with_opts(Opts::new("inflight_requests", "t")).unwrap(),
1444            IntCounter::with_opts(Opts::new("request_bytes_total", "t")).unwrap(),
1445            IntCounter::with_opts(Opts::new("response_bytes_total", "t")).unwrap(),
1446            IntCounterVec::new(
1447                Opts::new(work_handler::ERRORS_TOTAL, "t"),
1448                &[work_handler::ERROR_TYPE_LABEL],
1449            )
1450            .unwrap(),
1451            IntCounter::with_opts(Opts::new("cancellation_total", "t")).unwrap(),
1452        )
1453    }
1454
1455    #[tokio::test]
1456    async fn velo_setup_failures_count_response_stream_errors() {
1457        // An ingress not bound to a runtime endpoint has no Velo service.
1458        let ingress = TestIngress::new();
1459        let metrics = Arc::new(test_metrics());
1460        ingress.metrics.set(metrics.clone()).unwrap();
1461        ingress.response_plane.set(ResponsePlaneMode::Velo).unwrap();
1462        let control = RequestControlMessage {
1463            id: "test".into(),
1464            request_type: RequestType::SingleIn,
1465            response_type: ResponseType::ManyOut,
1466            payload_codec: RequestPlanePayloadCodec::Json,
1467            connection_info: ConnectionInfo {
1468                transport: velo_response::TRANSPORT_NAME.into(),
1469                info: "{}".into(),
1470            },
1471            metadata: Default::default(),
1472            frontend_send_ts_ns: None,
1473            request_stream_connection_info: None,
1474        };
1475        let payload = TwoPartCodec::default()
1476            .encode_message(TwoPartMessage::from_parts(
1477                serde_json::to_vec(&control).unwrap().into(),
1478                Bytes::from_static(b"{}"),
1479            ))
1480            .unwrap();
1481        let error = ingress
1482            .handle_payload_shared(payload, None)
1483            .await
1484            .unwrap_err();
1485        assert!(
1486            error.to_string().contains("live runtime endpoint"),
1487            "{error}"
1488        );
1489        assert_eq!(
1490            metrics
1491                .error_counter
1492                .with_label_values(&[work_handler::error_types::RESPONSE_STREAM])
1493                .get(),
1494            1
1495        );
1496    }
1497
1498    #[test]
1499    fn test_quic_client_pool_initializes_without_add_metrics() {
1500        let ingress = TestIngress::new();
1501        assert!(ingress.metrics().is_none());
1502
1503        let first = ingress.quic_response_client_pool().unwrap();
1504        let second = ingress.quic_response_client_pool().unwrap();
1505        assert!(Arc::ptr_eq(&first, &second));
1506    }
1507
1508    /// Which half of the teardown race a given run exercises.
1509    #[derive(Clone, Copy, Debug)]
1510    enum Teardown {
1511        /// Frontend sent `ControlMessage::Stop`; the control reader called
1512        /// `context.stop()` (see `tcp/client.rs`).
1513        Stop,
1514        /// Frontend sent `ControlMessage::Kill`; the control reader called
1515        /// `context.kill()`.
1516        Kill,
1517        /// The response-stream reader hit a TCP read error and called
1518        /// `context.kill()` (`tcp/client.rs`, "tcp stream read error").
1519        /// Indistinguishable from `Kill` at the context level, which is
1520        /// exactly why `is_stopped()` alone is too coarse a guard.
1521        ConnectionReadError,
1522        /// The transport died with the client still attached and the context
1523        /// live — a genuine failure that must stay classified as an error.
1524        TransportOnly,
1525    }
1526
1527    /// Drive `pump_response_stream` through the client-teardown ordering:
1528    /// the engine emits `content_frames` chunks, then the upstream reader goes
1529    /// away (mirroring `handle_writer` exiting on `context.stopped()`) while the
1530    /// trailing `complete_final` frame is still unsent.
1531    ///
1532    /// Returns (publish_final count, publish_response count).
1533    async fn run_teardown_race(content_frames: usize, teardown: Teardown) -> (u64, u64) {
1534        let ingress = TestIngress::new();
1535        let metrics = Arc::new(test_metrics());
1536        ingress
1537            .metrics
1538            .set(metrics.clone())
1539            .expect("metrics already set");
1540
1541        // Capacity covers every content frame, so a send only fails once the
1542        // receiver is gone — never merely because the channel is full.
1543        let (tx, mut rx) = tokio::sync::mpsc::channel(content_frames + 8);
1544        let publisher = StreamSender { tx, prologue: None };
1545
1546        let ctx = Context::new(serde_json::json!({}));
1547        let engine_ctx = ctx.context();
1548
1549        // The stream yields its content, then parks until the test has torn the
1550        // receiver down. Ending after the gate (rather than on a timer) is what
1551        // makes the race deterministic.
1552        let (gate_tx, gate_rx) = tokio::sync::oneshot::channel::<()>();
1553        let content: Vec<TestResponse> = (0..content_frames)
1554            .map(|i| Annotated::from_data(serde_json::json!({ "token": i })))
1555            .collect();
1556        let tail = stream::unfold(Some(gate_rx), |state| async move {
1557            // Awaiting then yielding `None` ends the stream, so
1558            // `send_complete_final` stays true and the final frame is attempted.
1559            let gate = state?;
1560            let _ = gate.await;
1561            None
1562        });
1563        let response_stream: ManyOut<TestResponse> = ResponseStream::new(
1564            Box::pin(stream::iter(content).chain(tail)),
1565            engine_ctx.clone(),
1566        );
1567
1568        let pump = tokio::spawn({
1569            let ingress = ingress.clone();
1570            async move {
1571                ingress
1572                    .pump_response_stream(
1573                        response_stream,
1574                        &publisher,
1575                        RequestPlanePayloadCodec::Json,
1576                    )
1577                    .await;
1578            }
1579        });
1580
1581        // Drain the content frames so the pump is past the per-frame branch.
1582        for _ in 0..content_frames {
1583            rx.recv().await.expect("content frame");
1584        }
1585
1586        // Now reproduce the teardown: the frontend has everything it needs and
1587        // drops the request, which kills the worker's writer task.
1588        match teardown {
1589            Teardown::Stop => engine_ctx.stop(),
1590            Teardown::Kill | Teardown::ConnectionReadError => engine_ctx.kill(),
1591            Teardown::TransportOnly => {}
1592        }
1593        drop(rx);
1594        let _ = gate_tx.send(());
1595
1596        pump.await.expect("pump task panicked");
1597
1598        let errors = &metrics.error_counter;
1599        (
1600            errors
1601                .with_label_values(&[work_handler::error_types::PUBLISH_FINAL])
1602                .get(),
1603            errors
1604                .with_label_values(&[work_handler::error_types::PUBLISH_RESPONSE])
1605                .get(),
1606        )
1607    }
1608
1609    /// Losing the `complete_final` send to a client that has already
1610    /// torn down is not a worker error. The per-frame branch already makes this
1611    /// distinction; the final-marker branch must make it too.
1612    #[tokio::test]
1613    async fn test_publish_final_race_with_stopped_context_is_not_an_error() {
1614        let (publish_final, publish_response) = run_teardown_race(3, Teardown::Stop).await;
1615        assert_eq!(
1616            publish_final, 0,
1617            "complete_final lost to a stopped context must not count as an error"
1618        );
1619        assert_eq!(
1620            publish_response, 0,
1621            "content frames were all delivered before teardown"
1622        );
1623    }
1624
1625    /// A killed context must stay a counted error. `is_stopped()` is
1626    /// `state != Live`, so it is true after `kill()` as well — but the
1627    /// response-stream reader kills the context on a TCP read error, so
1628    /// suppressing on `is_stopped()` alone would hide real connection
1629    /// failures from the very counter meant to surface them.
1630    #[tokio::test]
1631    async fn test_publish_final_with_killed_context_is_still_an_error() {
1632        let (publish_final, _) = run_teardown_race(3, Teardown::Kill).await;
1633        assert_eq!(
1634            publish_final, 1,
1635            "a killed context is not a graceful teardown and must still be counted"
1636        );
1637    }
1638
1639    /// The concrete regression: `tcp/client.rs` calls `context.kill()` on a TCP
1640    /// read error ("tcp stream read error, closing connection"). That path must
1641    /// remain visible in `dynamo_component_errors_total`.
1642    #[tokio::test]
1643    async fn test_publish_final_after_connection_read_error_is_still_an_error() {
1644        let (publish_final, _) = run_teardown_race(3, Teardown::ConnectionReadError).await;
1645        assert_eq!(
1646            publish_final, 1,
1647            "a dropped connection must not be silently reclassified as a benign teardown"
1648        );
1649    }
1650
1651    /// Guards against suppressing too much: with the context still live, a failed
1652    /// `complete_final` is a real transport failure and must still be counted.
1653    #[tokio::test]
1654    async fn test_publish_final_failure_without_stop_is_still_an_error() {
1655        let (publish_final, _) = run_teardown_race(3, Teardown::TransportOnly).await;
1656        assert_eq!(
1657            publish_final, 1,
1658            "a genuine complete_final failure must still be counted"
1659        );
1660    }
1661
1662    /// The marker itself is the transport-level end-of-stream signal that
1663    /// non-chat consumers (KV-router worker index queries, disaggregated
1664    /// prefill→decode) rely on to tell a clean end from a truncated one. The
1665    /// classification change must not disturb the clean path: every content
1666    /// frame plus a `complete_final: true` frame still goes out, and nothing is
1667    /// counted as an error.
1668    #[tokio::test]
1669    async fn test_complete_final_marker_still_sent_on_clean_stream() {
1670        let ingress = TestIngress::new();
1671        let metrics = Arc::new(test_metrics());
1672        ingress.metrics.set(metrics.clone()).unwrap();
1673
1674        let content_frames = 3;
1675        let (tx, mut rx) = tokio::sync::mpsc::channel(content_frames + 8);
1676        let publisher = StreamSender { tx, prologue: None };
1677
1678        let ctx = Context::new(serde_json::json!({}));
1679        let content: Vec<TestResponse> = (0..content_frames)
1680            .map(|i| Annotated::from_data(serde_json::json!({ "token": i })))
1681            .collect();
1682        let response_stream: ManyOut<TestResponse> =
1683            ResponseStream::new(Box::pin(stream::iter(content)), ctx.context());
1684
1685        ingress
1686            .pump_response_stream(response_stream, &publisher, RequestPlanePayloadCodec::Json)
1687            .await;
1688        drop(publisher);
1689
1690        let mut frames = Vec::new();
1691        while let Some(msg) = rx.recv().await {
1692            let (_header, data) = msg.into_parts();
1693            frames.push(serde_json::from_slice::<serde_json::Value>(&data).unwrap());
1694        }
1695
1696        assert_eq!(
1697            frames.len(),
1698            content_frames + 1,
1699            "expected every content frame plus the trailing marker"
1700        );
1701        for (i, frame) in frames.iter().take(content_frames).enumerate() {
1702            assert_eq!(frame["complete_final"], false, "content frame {i}");
1703        }
1704        assert_eq!(
1705            frames[content_frames]["complete_final"], true,
1706            "trailing frame must carry the end-of-stream marker"
1707        );
1708
1709        let errors = &metrics.error_counter;
1710        assert_eq!(
1711            errors
1712                .with_label_values(&[work_handler::error_types::PUBLISH_FINAL])
1713                .get(),
1714            0
1715        );
1716        assert_eq!(
1717            errors
1718                .with_label_values(&[work_handler::error_types::PUBLISH_RESPONSE])
1719                .get(),
1720            0
1721        );
1722    }
1723
1724    /// Run the pump with a health-check notifier set and a publisher whose
1725    /// receiver is already gone, so every `send` fails. This models a client
1726    /// that left before the engine produced its first chunk.
1727    /// Returns whether the pump left a notification permit for the canary.
1728    async fn pump_with_dead_publisher(
1729        engine: impl Stream<Item = TestResponse> + Send + 'static,
1730    ) -> bool {
1731        let ingress = TestIngress::new();
1732        let notifier = Arc::new(tokio::sync::Notify::new());
1733        ingress
1734            .set_endpoint_health_check_notifier(notifier.clone())
1735            .unwrap();
1736
1737        let (tx, rx) = tokio::sync::mpsc::channel(8);
1738        drop(rx);
1739        let publisher = StreamSender { tx, prologue: None };
1740
1741        let ctx = Context::new(serde_json::json!({}));
1742        let response_stream: ManyOut<TestResponse> =
1743            ResponseStream::new(Box::pin(engine), ctx.context());
1744        ingress
1745            .pump_response_stream(response_stream, &publisher, RequestPlanePayloadCodec::Json)
1746            .await;
1747
1748        // `notify_one` stores a permit when no task is waiting, so a pending
1749        // notification resolves immediately here.
1750        notifier.notified().now_or_never().is_some()
1751    }
1752
1753    /// Issue #15707: under overload the client often leaves before the engine
1754    /// sends its first chunk, so every publish fails. The engine is still
1755    /// making progress, so the canary timer must be reset.
1756    #[tokio::test]
1757    async fn publish_failure_with_engine_progress_still_resets_canary() {
1758        let chunk = TestResponse::from_data(serde_json::json!({ "token": 0 }));
1759        assert!(
1760            pump_with_dead_publisher(stream::iter([chunk])).await,
1761            "a produced non-error chunk must reset the canary even when the publish fails"
1762        );
1763    }
1764
1765    /// Error chunks do not prove the engine is healthy, so they must not reset
1766    /// the canary timer even though they are engine output.
1767    #[tokio::test]
1768    async fn error_only_output_does_not_reset_canary() {
1769        assert!(
1770            !pump_with_dead_publisher(stream::iter(vec![TestResponse::from_error("boom")])).await,
1771            "an error-only chunk must not reset the canary"
1772        );
1773    }
1774}