dynamo-llm 1.6.2

Dynamo LLM Library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! The `disconnect` module provides a mechanism for our axum http services to monitoring and responding
//! to disconnects from the client.
//!
//! There are two potential phases in any request where we need to handle the disconnect.
//!
//! For unary, request-response, there is just a single phase where the primary task that axum kicks off
//! to handle the request will be dropped if the client disconnects. In order for us to have a long running
//! task, like an LLM request, we need to spawn our long running task in a separate task and then spawn
//! a second task that will monitor for disconnects from the client. The primary task which spawned the
//! two tasks will hold an "armed" [`ConnectionHandle`] which will issue a [`ConnectionStatus::ClosedUnexpectedly`]
//! if the task is dropped before it is [`ConnectionHandle::disarm`]ed.
//!
//! For the streaming case, request in - stream out, we need a second [`ConnectionHandle`] which will be owned
//! by the stream. A streaming response is when the [`axum::response::Response]] is a [axum::response::Sse] stream.
//! This means the primary task handle will go out of scope when it returns the stream. When we create our
//! SSE stream, we capture the second [`ConnectionHandle`] and arm it. If the stream closes gracefully, the
//! second handle will be disarmed, otherwise, the stream was dropped and the [`Drop`] trait on the [`ConnectionHandle`]
//! triggers a [`ConnectionStatus::ClosedUnexpectedly`] signal.
//!
//! The [`ConnectionHandle`] is a simple wrapper around a [`tokio::sync::oneshot::Sender`] which will send a
//! [`ConnectionStatus`] enum to the primary task. The primary task will then use this to determine if it should
//! cancel the request or not.
//!
//! The [`ConnectionHandle`] is also used to signal to the client that the request has been cancelled. This is
//! done by sending a [`axum::response::sse::Event`] with the event type "error" and the data "`[DONE]`".
//!

use axum::{http::StatusCode, response::sse::Event};
use dynamo_runtime::engine::AsyncEngineContext;
use futures::{Stream, StreamExt};
use std::ops::{Deref, DerefMut};
use std::sync::{
    Arc, OnceLock,
    atomic::{AtomicBool, Ordering},
};
use std::time::Duration;
use tokio::sync::mpsc;

use crate::http::service::error::{ClientErrorAction, SanitizedError, http_action_for_error};
use crate::http::service::metrics::{CancellationLabels, ErrorType, InflightGuard, Metrics};
use dynamo_runtime::error::{DynamoError, ErrorClass};

use dynamo_runtime::config::environment_names::llm::DYN_HTTP_BACKEND_STREAM_TIMEOUT_SECS as BACKEND_STREAM_TIMEOUT_ENV;

/// Read the backend stream inactivity timeout from the environment.
/// Returns `None` if unset or zero (timeout disabled).
///
/// The HTTP-layer timeout uses a 2x multiplier over the configured value so that
/// the request-plane timeout in `push_router` (which uses the raw value) always
/// fires first and triggers `report_instance_down()` for worker quarantine.
/// This layer is strictly a safety net for gauge cleanup.
pub fn backend_stream_timeout() -> Option<Duration> {
    std::env::var(BACKEND_STREAM_TIMEOUT_ENV)
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .filter(|&secs| secs > 0)
        .map(|secs| Duration::from_secs(secs.saturating_mul(2)))
}

#[derive(Clone, Copy)]
pub enum ConnectionStatus {
    Disabled,
    ClosedUnexpectedly,
    ClosedGracefully,
}

pub struct ConnectionHandle {
    sender: Option<tokio::sync::oneshot::Sender<ConnectionStatus>>,
    on_drop: ConnectionStatus,
}

/// One-shot application error reported by an SSE producer.
///
/// The producer records the error when it is detected, then marks the terminal
/// protocol event immediately before yielding it. The disconnect monitor reads
/// only when the source stream ends or its guards are dropped, avoiding
/// synchronization on successful per-token events.
struct StreamFailure {
    error_type: ErrorType,
    semantic_error: Option<DynamoError>,
}

#[derive(Default)]
struct StreamErrorState {
    failure: OnceLock<StreamFailure>,
    terminal_event_emitted: AtomicBool,
}

#[derive(Clone, Default)]
pub(super) struct StreamErrorSignal(Arc<StreamErrorState>);

impl StreamErrorSignal {
    pub(super) fn set(&self, error_type: ErrorType) {
        let _ = self.0.failure.set(StreamFailure {
            error_type,
            semantic_error: None,
        });
    }

    pub(super) fn set_semantic(&self, error_type: ErrorType, error: &DynamoError) {
        let _ = self.0.failure.set(StreamFailure {
            error_type,
            semantic_error: Some(error.clone()),
        });
    }

    fn get(&self) -> Option<&ErrorType> {
        self.0.failure.get().map(|failure| &failure.error_type)
    }

    pub(super) fn error_type(&self) -> Option<ErrorType> {
        self.get().cloned()
    }

    pub(super) fn mark_terminal_event_emitted(&self) {
        self.0.terminal_event_emitted.store(true, Ordering::Release);
    }

    pub(super) fn terminal_event_emitted(&self) -> bool {
        self.0.terminal_event_emitted.load(Ordering::Acquire)
    }

    pub(super) fn semantic_error(&self) -> Option<&DynamoError> {
        self.0
            .failure
            .get()
            .and_then(|failure| failure.semantic_error.as_ref())
    }

    fn record_delivered_failure(&self) {
        if !self.terminal_event_emitted() {
            return;
        }
        let Some(failure) = self.0.failure.get() else {
            return;
        };
        if let Some(error) = &failure.semantic_error {
            if error.class() != ErrorClass::Cancelled {
                crate::http::service::metrics::record_failure(error);
            }
            return;
        }

        let class = match &failure.error_type {
            ErrorType::Validation => ErrorClass::InvalidRequest,
            ErrorType::NotFound => ErrorClass::NotFound,
            ErrorType::Overload => ErrorClass::CapacityExhausted,
            ErrorType::Unavailable => ErrorClass::Unavailable,
            ErrorType::Cancelled => return,
            ErrorType::ResponseTimeout => ErrorClass::DeadlineExceeded,
            ErrorType::NotImplemented => ErrorClass::NotImplemented,
            ErrorType::None | ErrorType::Internal => ErrorClass::Internal,
        };
        crate::http::service::metrics::record_failure(&DynamoError::builder().class(class).build());
    }
}

struct SignaledInflightGuard {
    guard: InflightGuard,
    error_signal: Option<StreamErrorSignal>,
}

impl SignaledInflightGuard {
    fn new(guard: InflightGuard, error_signal: Option<StreamErrorSignal>) -> Self {
        Self {
            guard,
            error_signal,
        }
    }

    fn signaled_error_type(&self) -> Option<ErrorType> {
        self.error_signal
            .as_ref()
            .and_then(StreamErrorSignal::get)
            .cloned()
    }
}

impl Deref for SignaledInflightGuard {
    type Target = InflightGuard;

    fn deref(&self) -> &Self::Target {
        &self.guard
    }
}

impl DerefMut for SignaledInflightGuard {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.guard
    }
}

impl Drop for SignaledInflightGuard {
    fn drop(&mut self) {
        if let Some(error_signal) = &self.error_signal
            && error_signal.terminal_event_emitted()
        {
            error_signal.record_delivered_failure();
            if self.guard.error_type() == &ErrorType::Cancelled
                && let Some(error_type) = self.signaled_error_type()
            {
                self.guard.mark_error(error_type);
            }
        }
    }
}

/// Disarms a stream handle on drop only after its terminal error event was
/// handed to the disconnect monitor.
struct SignaledConnectionHandle {
    handle: ConnectionHandle,
    error_signal: Option<StreamErrorSignal>,
}

impl SignaledConnectionHandle {
    fn new(handle: ConnectionHandle, error_signal: Option<StreamErrorSignal>) -> Self {
        Self {
            handle,
            error_signal,
        }
    }

    fn disarm(&mut self) {
        self.handle.disarm();
    }
}

impl Drop for SignaledConnectionHandle {
    fn drop(&mut self) {
        if self
            .error_signal
            .as_ref()
            .is_some_and(StreamErrorSignal::terminal_event_emitted)
        {
            self.handle.disarm();
        }
    }
}

impl ConnectionHandle {
    /// Handle which by default will issue a [`ConnectionStatus::ClosedGracefully`] signal when dropped.
    pub fn create_disarmed(sender: tokio::sync::oneshot::Sender<ConnectionStatus>) -> Self {
        Self {
            sender: Some(sender),
            on_drop: ConnectionStatus::ClosedGracefully,
        }
    }

    /// Handle which will issue a [`ConnectionStatus::ClosedUnexpectedly`] signal when dropped.
    pub fn create_armed(sender: tokio::sync::oneshot::Sender<ConnectionStatus>) -> Self {
        Self {
            sender: Some(sender),
            on_drop: ConnectionStatus::ClosedUnexpectedly,
        }
    }

    /// Handle which will not issue a signal when dropped.
    pub fn create_disabled(sender: tokio::sync::oneshot::Sender<ConnectionStatus>) -> Self {
        Self {
            sender: Some(sender),
            on_drop: ConnectionStatus::Disabled,
        }
    }

    /// Handle which will issue a [`ConnectionStatus::ClosedGracefully`] signal when dropped.
    pub fn disarm(&mut self) {
        self.on_drop = ConnectionStatus::ClosedGracefully;
    }

    /// Handle which will issue a [`ConnectionStatus::ClosedUnexpectedly`] signal when dropped.
    pub fn arm(&mut self) {
        self.on_drop = ConnectionStatus::ClosedUnexpectedly;
    }
}

impl Drop for ConnectionHandle {
    fn drop(&mut self) {
        if let Some(sender) = self.sender.take() {
            let _ = sender.send(self.on_drop);
        }
    }
}

/// Creates a pair of handles which will monitor for disconnects from the client.
///
/// The first handle is armed and will issue a [`ConnectionStatus::ClosedUnexpectedly`] signal when dropped.
/// The second handle is disarmed and will issue a [`ConnectionStatus::ClosedGracefully`] signal when dropped.
///
/// The handles are returned in the order of the first being armed and the second being disarmed.
pub async fn create_connection_monitor(
    engine_context: Arc<dyn AsyncEngineContext>,
    metrics: Option<Arc<Metrics>>,
    cancellation_labels: CancellationLabels,
) -> (ConnectionHandle, ConnectionHandle) {
    // these oneshot channels monitor possible disconnects from the client in two different scopes:
    // - the local task (connection_handle)
    // - an optionally streaming response (stream_handle)
    let (connection_tx, connection_rx) = tokio::sync::oneshot::channel();
    let (stream_tx, stream_rx) = tokio::sync::oneshot::channel();

    // detached task that will naturally close when both handles are dropped
    tokio::spawn(connection_monitor(
        engine_context.clone(),
        connection_rx,
        stream_rx,
        metrics,
        cancellation_labels,
    ));

    // Two handles, the first is armed, the second is disarmed
    (
        ConnectionHandle::create_armed(connection_tx),
        ConnectionHandle::create_disabled(stream_tx),
    )
}

#[tracing::instrument(level = "trace", skip_all, fields(request_id = %engine_context.id()))]
async fn connection_monitor(
    engine_context: Arc<dyn AsyncEngineContext>,
    connection_rx: tokio::sync::oneshot::Receiver<ConnectionStatus>,
    stream_rx: tokio::sync::oneshot::Receiver<ConnectionStatus>,
    metrics: Option<Arc<Metrics>>,
    cancellation_labels: CancellationLabels,
) {
    match connection_rx.await {
        Err(_) | Ok(ConnectionStatus::ClosedUnexpectedly) => {
            // the client has disconnected, no need to gracefully cancel, just kill the context
            tracing::warn!("Connection closed unexpectedly; issuing cancellation");
            if let Some(metrics) = &metrics {
                metrics.inc_client_disconnect();
                metrics.inc_cancellation(&cancellation_labels);
            }
            engine_context.kill();
        }
        Ok(ConnectionStatus::ClosedGracefully) => {
            tracing::trace!("Connection closed gracefully");
        }
        Ok(ConnectionStatus::Disabled) => {}
    }

    match stream_rx.await {
        Err(_) | Ok(ConnectionStatus::ClosedUnexpectedly) => {
            tracing::warn!("Stream closed unexpectedly; issuing cancellation");
            if let Some(metrics) = &metrics {
                metrics.inc_client_disconnect();
                metrics.inc_cancellation(&cancellation_labels);
            }
            engine_context.kill();
        }
        Ok(ConnectionStatus::ClosedGracefully) => {
            tracing::trace!("Stream closed gracefully");
        }
        Ok(ConnectionStatus::Disabled) => {}
    }
}

type StreamErrorFormatter = fn(&(dyn std::error::Error + 'static)) -> (ErrorType, String);

#[derive(Default)]
struct StreamMonitorOptions {
    activity_rx: Option<mpsc::UnboundedReceiver<()>>,
    error_signal: Option<StreamErrorSignal>,
}

fn openai_stream_error(_error: &(dyn std::error::Error + 'static)) -> (ErrorType, String) {
    let error = SanitizedError::Internal;
    let body = serde_json::json!({
        "error": {
            "message": error.to_string(),
            "type": error.openai_type_slug(),
            "code": error.status().as_u16(),
        }
    })
    .to_string();
    (ErrorType::Internal, body)
}

fn openai_semantic_stream_error(error: &DynamoError) -> (ErrorType, String) {
    let (status, message) = match http_action_for_error(error) {
        ClientErrorAction::Respond {
            status,
            public_message,
        } => (status, public_message),
        ClientErrorAction::NoDelivery => (
            StatusCode::from_u16(499).expect("499 is a valid extension status"),
            "Request cancelled",
        ),
    };
    let message = error.public_message().unwrap_or(message);
    let error_type = if status == crate::http::service::error::overload_status_code() {
        "service_unavailable"
    } else {
        match status {
            StatusCode::BAD_REQUEST
            | StatusCode::CONFLICT
            | StatusCode::PAYLOAD_TOO_LARGE
            | StatusCode::UNSUPPORTED_MEDIA_TYPE => "invalid_request_error",
            StatusCode::UNAUTHORIZED => "authentication_error",
            StatusCode::FORBIDDEN => "permission_error",
            StatusCode::NOT_FOUND => "not_found_error",
            StatusCode::TOO_MANY_REQUESTS => "rate_limit_error",
            StatusCode::SERVICE_UNAVAILABLE => "service_unavailable",
            StatusCode::GATEWAY_TIMEOUT => "timeout_error",
            StatusCode::NOT_IMPLEMENTED => "not_implemented_error",
            _ if status.as_u16() == 499 => "request_cancelled",
            _ => "internal_server_error",
        }
    };
    let body = serde_json::json!({
        "error": {
            "message": message,
            "type": error_type,
            "code": status.as_u16(),
        }
    })
    .to_string();
    (
        crate::http::service::openai::metric_error_type_for_class(error.class()),
        body,
    )
}

/// This method will consume a stream of SSE events and monitor for disconnects or context cancellation.
///
/// Uses `tokio::select!` to choose between receiving events from the source stream or detecting when
/// the context is killed. A graceful `stop_generating()` leaves in-flight results valid, so we
/// continue draining the source, including any chained terminal events. If the source stream ends
/// naturally, we mark the request as successful and send the final `[DONE]` event. The configured
/// inactivity timeout still applies while draining; a stop does not introduce a separate deadline.
///
/// A configurable inactivity timeout (see [`BACKEND_STREAM_TIMEOUT_ENV`]) adds a third arm: if no
/// SSE event is received from the backend within the timeout window, the engine context is killed and
/// the inflight guard is dropped, preventing permanent gauge inflation caused by zombie workers that
/// hold a live TCP connection but produce no output.
pub fn monitor_for_disconnects(
    stream: impl Stream<Item = Result<Event, axum::Error>>,
    context: Arc<dyn AsyncEngineContext>,
    inflight_guard: InflightGuard,
    stream_handle: ConnectionHandle,
) -> impl Stream<Item = Result<Event, axum::Error>> {
    monitor_for_disconnects_with_timeout_error_and_keep_alive(
        stream,
        context,
        inflight_guard,
        stream_handle,
        backend_stream_timeout(),
        openai_stream_error,
        StreamMonitorOptions::default(),
    )
}

pub(crate) fn monitor_for_disconnects_with_error(
    stream: impl Stream<Item = Result<Event, axum::Error>>,
    context: Arc<dyn AsyncEngineContext>,
    inflight_guard: InflightGuard,
    stream_handle: ConnectionHandle,
    error_formatter: StreamErrorFormatter,
) -> impl Stream<Item = Result<Event, axum::Error>> {
    monitor_for_disconnects_with_timeout_error_and_keep_alive(
        stream,
        context,
        inflight_guard,
        stream_handle,
        backend_stream_timeout(),
        error_formatter,
        StreamMonitorOptions::default(),
    )
}

pub(super) fn monitor_for_disconnects_with_error_signal(
    stream: impl Stream<Item = Result<Event, axum::Error>>,
    context: Arc<dyn AsyncEngineContext>,
    inflight_guard: InflightGuard,
    stream_handle: ConnectionHandle,
    error_signal: StreamErrorSignal,
) -> impl Stream<Item = Result<Event, axum::Error>> {
    monitor_for_disconnects_with_timeout_error_and_keep_alive(
        stream,
        context,
        inflight_guard,
        stream_handle,
        backend_stream_timeout(),
        openai_stream_error,
        StreamMonitorOptions {
            error_signal: Some(error_signal),
            ..Default::default()
        },
    )
}

pub fn monitor_for_disconnects_with_activity(
    stream: impl Stream<Item = Result<Event, axum::Error>>,
    context: Arc<dyn AsyncEngineContext>,
    inflight_guard: InflightGuard,
    stream_handle: ConnectionHandle,
    activity_rx: mpsc::UnboundedReceiver<()>,
) -> impl Stream<Item = Result<Event, axum::Error>> {
    monitor_for_disconnects_with_timeout_error_and_keep_alive(
        stream,
        context,
        inflight_guard,
        stream_handle,
        backend_stream_timeout(),
        openai_stream_error,
        StreamMonitorOptions {
            activity_rx: Some(activity_rx),
            ..Default::default()
        },
    )
}

pub(super) fn monitor_for_disconnects_with_activity_and_error_signal(
    stream: impl Stream<Item = Result<Event, axum::Error>>,
    context: Arc<dyn AsyncEngineContext>,
    inflight_guard: InflightGuard,
    stream_handle: ConnectionHandle,
    activity_rx: mpsc::UnboundedReceiver<()>,
    error_signal: StreamErrorSignal,
) -> impl Stream<Item = Result<Event, axum::Error>> {
    monitor_for_disconnects_with_timeout_error_and_keep_alive(
        stream,
        context,
        inflight_guard,
        stream_handle,
        backend_stream_timeout(),
        openai_stream_error,
        StreamMonitorOptions {
            activity_rx: Some(activity_rx),
            error_signal: Some(error_signal),
        },
    )
}

#[cfg(test)]
fn monitor_for_disconnects_with_timeout(
    stream: impl Stream<Item = Result<Event, axum::Error>>,
    context: Arc<dyn AsyncEngineContext>,
    inflight_guard: InflightGuard,
    stream_handle: ConnectionHandle,
    inactivity_timeout: Option<Duration>,
) -> impl Stream<Item = Result<Event, axum::Error>> {
    monitor_for_disconnects_with_timeout_error_and_keep_alive(
        stream,
        context,
        inflight_guard,
        stream_handle,
        inactivity_timeout,
        openai_stream_error,
        StreamMonitorOptions::default(),
    )
}

fn monitor_for_disconnects_with_timeout_error_and_keep_alive(
    stream: impl Stream<Item = Result<Event, axum::Error>>,
    context: Arc<dyn AsyncEngineContext>,
    mut inflight_guard: InflightGuard,
    mut stream_handle: ConnectionHandle,
    inactivity_timeout: Option<Duration>,
    error_formatter: StreamErrorFormatter,
    options: StreamMonitorOptions,
) -> impl Stream<Item = Result<Event, axum::Error>> {
    stream_handle.arm();

    let StreamMonitorOptions {
        mut activity_rx,
        error_signal,
    } = options;

    // Default to Cancelled: if the stream is dropped unexpectedly (e.g. client
    // disconnect causing a broken-pipe on the SSE write), the guard will report
    // "cancelled" instead of "internal". The happy path overrides this via mark_ok().
    inflight_guard.mark_error(ErrorType::Cancelled);
    let mut stream_handle = SignaledConnectionHandle::new(stream_handle, error_signal.clone());
    let mut inflight_guard = SignaledInflightGuard::new(inflight_guard, error_signal.clone());

    async_stream::try_stream! {
        tokio::pin!(stream);
        // Keep the context's watch-backed cancellation future alive across body frames.
        // Recreating it for every token repeatedly clones a receiver and churns Notify state.
        let killed = context.killed();
        tokio::pin!(killed);
        let mut inactivity_deadline =
            inactivity_timeout.map(|timeout| tokio::time::Instant::now() + timeout);
        loop {
            tokio::select! {
                // Drain any ready SSE event before honoring a cancel or the
                // inactivity timeout. This preserves already-buffered output on
                // disconnect and lets a source stream that emits its own
                // finalizer-on-cancel (e.g. the Anthropic converter) flush those
                // terminal events before this monitor records the cancellation.
                biased;
                event = stream.next() => {
                    match event {
                        Some(Ok(event)) => {
                            inactivity_deadline = inactivity_timeout
                                .map(|timeout| tokio::time::Instant::now() + timeout);
                            yield event;
                        }
                        Some(Err(err)) => {
                            let semantic_error = inflight_guard
                                .error_signal
                                .as_ref()
                                .and_then(StreamErrorSignal::semantic_error);
                            let (fallback_error_type, fallback_error_body) =
                                error_formatter(&err);
                            let (error_type, error_body) = match semantic_error {
                                Some(error) => openai_semantic_stream_error(error),
                                None => (fallback_error_type, fallback_error_body),
                            };
                            let error_type = error_signal
                                .as_ref()
                                .and_then(StreamErrorSignal::get)
                                .cloned()
                                .unwrap_or(error_type);
                            inflight_guard.mark_error(error_type.clone());
                            if let Some(error_signal) = &error_signal {
                                error_signal.set(error_type.clone());
                            }
                            // We're terminating the stream intentionally here with a
                            // structured error + [DONE]; disarm so the stream handle
                            // doesn't later record this as ClosedUnexpectedly (which
                            // would mis-attribute the fault as a client disconnect).
                            stream_handle.disarm();
                            if let Some(error_signal) = &inflight_guard.error_signal {
                                error_signal.mark_terminal_event_emitted();
                                if let Some(error) = error_signal.semantic_error() {
                                    if matches!(
                                        error.class(),
                                        dynamo_runtime::error::ErrorClass::Internal
                                            | dynamo_runtime::error::ErrorClass::BackendProtocol
                                    ) {
                                        tracing::error!(
                                            class = %error.class(),
                                            reason = %error.reason(),
                                            diagnostic = ?error.diagnostic().map(dynamo_runtime::error::Diagnostic::as_str),
                                            "Semantic streaming failure"
                                        );
                                    } else {
                                        tracing::debug!(
                                            class = %error.class(),
                                            reason = %error.reason(),
                                            diagnostic = ?error.diagnostic().map(dynamo_runtime::error::Diagnostic::as_str),
                                            "Semantic streaming failure"
                                        );
                                    }
                                } else {
                                    tracing::error!(%error_type, %err, "Streaming failure");
                                }
                            } else {
                                tracing::error!(%error_type, %err, "Streaming failure");
                            }
                            yield Event::default().data(error_body);
                            yield Event::default().data("[DONE]");
                            // Break to prevent any subsequent mark_ok() from overwriting the error
                            break;
                        }
                        None => {
                            if let Some(error_type) = inflight_guard.signaled_error_type() {
                                inflight_guard.mark_error(error_type);
                            } else {
                                inflight_guard.mark_ok();
                            }
                            stream_handle.disarm();

                            // todo: if we yield a dynamo sentinel event, we need to do it before the done or the
                            // async-openai client will chomp it.
                            yield Event::default().data("[DONE]");
                            break;
                        }
                    }
                }
                _ = &mut killed => {
                    // Client disconnects kill the context; graceful stops keep draining.
                    inflight_guard.mark_error(ErrorType::Cancelled);
                    // Token counts (input_tokens, output_tokens) are recorded on
                    // the enclosing span by ResponseMetricCollector::Drop.
                    tracing::warn!(
                        request_id = %inflight_guard.request_id(),
                        model = %inflight_guard.model(),
                        endpoint = %inflight_guard.endpoint(),
                        request_type = %inflight_guard.request_type(),
                        error_type = "cancelled",
                        elapsed_ms = %inflight_guard.elapsed_ms(),
                        "request cancelled"
                    );
                    break;
                }
                activity = async {
                    match activity_rx.as_mut() {
                        Some(rx) => rx.recv().await,
                        None => std::future::pending::<Option<()>>().await,
                    }
                } => {
                    if activity.is_some() {
                        inactivity_deadline = inactivity_timeout
                            .map(|timeout| tokio::time::Instant::now() + timeout);
                    } else {
                        activity_rx = None;
                    }
                }
                // Circuit breaker for zombie backend workers: if the backend holds a live TCP
                // connection but produces no output for `inactivity_timeout`, kill the engine
                // context so that InflightGuard::drop() fires and dec() corrects the gauge.
                // Only real stream activity resets this deadline. Client heartbeats must not
                // keep a dead backend alive indefinitely.
                _ = async {
                    match inactivity_deadline {
                        Some(deadline) => tokio::time::sleep_until(deadline).await,
                        None => std::future::pending::<()>().await,
                    }
                } => {
                    inflight_guard.mark_error(ErrorType::ResponseTimeout);
                    if let Some(error_signal) = &error_signal {
                        error_signal.set(ErrorType::ResponseTimeout);
                    }
                    stream_handle.disarm();
                    tracing::warn!(
                        request_id = %inflight_guard.request_id(),
                        model = %inflight_guard.model(),
                        endpoint = %inflight_guard.endpoint(),
                        request_type = %inflight_guard.request_type(),
                        error_type = "response_timeout",
                        elapsed_ms = %inflight_guard.elapsed_ms(),
                        timeout_secs = ?inactivity_timeout.map(|d| d.as_secs()),
                        "backend stream inactivity timeout; killing engine context to release inflight gauge"
                    );
                    context.kill();
                    break;
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::service::metrics::{Endpoint, ErrorType, RequestType, Status};
    use dynamo_runtime::pipeline::context::Controller;
    use futures::StreamExt;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Debug, Default)]
    struct MockContext {
        killed_polls: AtomicUsize,
        killed: std::sync::atomic::AtomicBool,
        track_kill: bool,
    }

    impl MockContext {
        fn new() -> Self {
            Self::default()
        }

        fn with_kill_tracking() -> Self {
            Self {
                track_kill: true,
                ..Default::default()
            }
        }
    }

    #[async_trait::async_trait]
    impl dynamo_runtime::engine::AsyncEngineContext for MockContext {
        fn id(&self) -> &str {
            "test"
        }
        fn stop(&self) {}
        fn stop_generating(&self) {}
        fn kill(&self) {
            if self.track_kill {
                self.killed.store(true, std::sync::atomic::Ordering::SeqCst);
            }
        }
        fn is_stopped(&self) -> bool {
            false
        }
        fn is_killed(&self) -> bool {
            self.track_kill && self.killed.load(std::sync::atomic::Ordering::SeqCst)
        }
        async fn stopped(&self) {
            std::future::pending::<()>().await;
        }
        async fn killed(&self) {
            self.killed_polls.fetch_add(1, Ordering::Relaxed);
            std::future::pending::<()>().await;
        }
        fn link_child(&self, _: Arc<dyn dynamo_runtime::engine::AsyncEngineContext>) {}
    }

    fn hanging_stream()
    -> impl futures::Stream<Item = Result<axum::response::sse::Event, axum::Error>> {
        async_stream::try_stream! {
            std::future::pending::<()>().await;
            yield axum::response::sse::Event::default().data("unreachable");
        }
    }

    fn timed_token_stream(
        count: usize,
        interval: Duration,
    ) -> impl futures::Stream<Item = Result<axum::response::sse::Event, axum::Error>> {
        async_stream::try_stream! {
            for i in 0..count {
                tokio::time::sleep(interval).await;
                yield axum::response::sse::Event::default().data(format!("token-{i}"));
            }
        }
    }

    fn setup_test(
        model: &str,
        req_id: &str,
    ) -> (
        Arc<Metrics>,
        InflightGuard,
        Arc<dyn AsyncEngineContext>,
        ConnectionHandle,
    ) {
        let metrics = Arc::new(Metrics::new());
        let guard =
            metrics
                .clone()
                .create_inflight_guard(model, Endpoint::ChatCompletions, true, req_id);
        let context: Arc<dyn AsyncEngineContext> = Arc::new(MockContext::new());
        let (tx, _rx) = tokio::sync::oneshot::channel();
        let handle = ConnectionHandle::create_disabled(tx);
        (metrics, guard, context, handle)
    }

    #[tokio::test(start_paused = true)]
    async fn test_graceful_stop_delivers_delayed_terminal_event() {
        for timeout in [None, Some(Duration::from_secs(2))] {
            let model = "graceful-stop";
            let (metrics, guard, _, handle) = setup_test(model, "req-stop");
            let context = Arc::new(Controller::default());
            let producer_context = context.clone();
            let source = async_stream::try_stream! {
                yield Event::default().data("token-0");
                producer_context.stop_generating();
                // Buffered events already win the biased select on main. The
                // regression requires the source to be Pending after the stop.
                tokio::time::sleep(Duration::from_secs(1)).await;
                yield Event::default().data("token-1");
            };
            let terminal = futures::stream::once(async {
                Ok(Event::default()
                    .event("response.completed")
                    .data(r#"{"type":"response.completed"}"#))
            });
            let monitored = monitor_for_disconnects_with_timeout(
                source.chain(terminal),
                context.clone(),
                guard,
                handle,
                timeout,
            );
            let body = tokio::time::timeout(Duration::from_secs(3), collect_sse_body(monitored))
                .await
                .expect("gracefully stopped source must finish");

            assert_eq!(
                body,
                "data: token-0\n\ndata: token-1\n\nevent: response.completed\n\
                 data: {\"type\":\"response.completed\"}\n\ndata: [DONE]\n\n"
            );
            assert!(context.is_stopped());
            assert!(!context.is_killed());
            assert_eq!(metrics.get_inflight_count(model), 0);
            assert_eq!(
                metrics.get_request_counter(
                    model,
                    &Endpoint::ChatCompletions,
                    &RequestType::Stream,
                    &Status::Success,
                    &ErrorType::None,
                ),
                1
            );
        }
    }

    #[tokio::test]
    async fn test_kill_terminates_pending_stream_before_or_after_stop() {
        for stop_first in [false, true] {
            let model = "killed-stream";
            let (metrics, guard, _, handle) = setup_test(model, "req-kill");
            let context = Arc::new(Controller::default());
            let mut monitored = Box::pin(monitor_for_disconnects_with_timeout(
                hanging_stream(),
                context.clone(),
                guard,
                handle,
                None,
            ));
            assert!(futures::poll!(monitored.next()).is_pending());
            if stop_first {
                context.stop_generating();
                assert!(futures::poll!(monitored.next()).is_pending());
            }
            context.kill();
            assert!(
                tokio::time::timeout(Duration::from_secs(1), monitored.next())
                    .await
                    .expect("kill must terminate without an inactivity timeout")
                    .is_none(),
                "kill must not emit a success sentinel"
            );
            drop(monitored);
            assert_eq!(metrics.get_inflight_count(model), 0);
            assert_eq!(
                metrics.get_request_counter(
                    model,
                    &Endpoint::ChatCompletions,
                    &RequestType::Stream,
                    &Status::Error,
                    &ErrorType::Cancelled,
                ),
                1
            );
        }
    }

    #[tokio::test(start_paused = true)]
    async fn test_graceful_stop_preserves_inactivity_timeout() {
        let model = "stopped-inactive-stream";
        let (metrics, guard, _, handle) = setup_test(model, "req-stop-timeout");
        let context = Arc::new(Controller::default());
        context.stop_generating();
        let started = tokio::time::Instant::now();
        let monitored = monitor_for_disconnects_with_timeout(
            hanging_stream(),
            context.clone(),
            guard,
            handle,
            Some(Duration::from_secs(2)),
        );
        let body = tokio::time::timeout(Duration::from_secs(3), collect_sse_body(monitored))
            .await
            .expect("stopped source must still time out when inactive");

        assert!(body.is_empty(), "timeout must not emit a success sentinel");
        assert_eq!(started.elapsed(), Duration::from_secs(2));
        assert!(context.is_killed());
        assert_eq!(metrics.get_inflight_count(model), 0);
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::ChatCompletions,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::ResponseTimeout,
            ),
            1
        );
    }

    #[tokio::test]
    async fn test_monitor_reuses_killed_future_across_events() {
        let model = "reuse-killed-future";
        let metrics = Arc::new(Metrics::new());
        let guard = metrics.clone().create_inflight_guard(
            model,
            Endpoint::ChatCompletions,
            true,
            "req-reuse",
        );
        let context = Arc::new(MockContext::new());
        let engine_context: Arc<dyn AsyncEngineContext> = context.clone();
        let (tx, _rx) = tokio::sync::oneshot::channel();
        let handle = ConnectionHandle::create_disabled(tx);
        let stream = futures::stream::unfold(0, |index| async move {
            tokio::task::yield_now().await;
            (index < 4).then(|| {
                (
                    Ok(Event::default().data(format!("token-{index}"))),
                    index + 1,
                )
            })
        });

        let monitored =
            monitor_for_disconnects_with_timeout(stream, engine_context, guard, handle, None);
        tokio::pin!(monitored);
        while monitored.next().await.is_some() {}

        assert_eq!(
            context.killed_polls.load(Ordering::Relaxed),
            1,
            "the same killed future should remain pending across all response events"
        );
    }

    #[tokio::test]
    #[serial_test::serial(failure_metrics)]
    async fn signaled_error_drop_after_terminal_event_is_not_a_cancellation() {
        let model = "drop-after-response-failed";
        let metrics = Arc::new(Metrics::new());
        let guard = metrics.clone().create_inflight_guard(
            model,
            Endpoint::Responses,
            true,
            "req-drop-after-response-failed",
        );
        let context = Arc::new(MockContext::with_kill_tracking());
        let engine_context: Arc<dyn AsyncEngineContext> = context.clone();
        let (connection_tx, connection_rx) = tokio::sync::oneshot::channel();
        let (stream_tx, stream_rx) = tokio::sync::oneshot::channel();
        let cancellation_labels = CancellationLabels {
            model: model.to_string(),
            endpoint: Endpoint::Responses.to_string(),
            request_type: RequestType::Stream.to_string(),
        };
        let connection_monitor = tokio::spawn(connection_monitor(
            engine_context.clone(),
            connection_rx,
            stream_rx,
            Some(metrics.clone()),
            cancellation_labels,
        ));
        let mut connection_handle = ConnectionHandle::create_armed(connection_tx);
        let stream_handle = ConnectionHandle::create_disabled(stream_tx);
        connection_handle.disarm();
        drop(connection_handle);
        let error_signal = StreamErrorSignal::default();
        let semantic_counter = crate::http::service::metrics::DYNAM_FAILURES_TOTAL
            .with_label_values(&["Internal", "runtime.internal"]);
        let semantic_before = semantic_counter.get();
        let producer_error_signal = error_signal.clone();
        let stream = futures::stream::once(async move {
            producer_error_signal.set(ErrorType::Internal);
            producer_error_signal.mark_terminal_event_emitted();
            Ok::<_, axum::Error>(
                Event::default()
                    .event("response.failed")
                    .data(r#"{"type":"response.failed"}"#),
            )
        })
        .chain(futures::stream::pending());

        let mut monitored = Box::pin(monitor_for_disconnects_with_timeout_error_and_keep_alive(
            stream,
            engine_context,
            guard,
            stream_handle,
            None,
            openai_stream_error,
            StreamMonitorOptions {
                error_signal: Some(error_signal),
                ..Default::default()
            },
        ));
        assert!(monitored.next().await.is_some());
        drop(monitored);
        tokio::time::timeout(Duration::from_secs(5), connection_monitor)
            .await
            .expect("connection monitor did not finish")
            .expect("connection monitor task failed");

        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::Responses,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Internal,
            ),
            1
        );
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::Responses,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Cancelled,
            ),
            0
        );
        let cancellation_labels = CancellationLabels {
            model: model.to_string(),
            endpoint: Endpoint::Responses.to_string(),
            request_type: RequestType::Stream.to_string(),
        };
        assert_eq!(metrics.get_cancellation_count(&cancellation_labels), 0);
        assert_eq!(metrics.get_client_disconnect_count(), 0);
        assert!(!context.is_killed());
        assert_eq!(semantic_counter.get() - semantic_before, 1);
    }

    #[tokio::test]
    async fn signaled_semantic_err_is_classified_when_terminal_frame_is_emitted() {
        let model = "delivered-semantic-error";
        let metrics = Arc::new(Metrics::new());
        let guard = metrics.clone().create_inflight_guard(
            model,
            Endpoint::ChatCompletions,
            true,
            "req-delivered-semantic-error",
        );
        let context: Arc<dyn AsyncEngineContext> = Arc::new(MockContext::with_kill_tracking());
        let (stream_tx, _stream_rx) = tokio::sync::oneshot::channel();
        let stream_handle = ConnectionHandle::create_disabled(stream_tx);
        let error_signal = StreamErrorSignal::default();
        let producer_error_signal = error_signal.clone();
        let stream = futures::stream::once(async move {
            let error = DynamoError::builder()
                .class(dynamo_runtime::error::ErrorClass::InvalidRequest)
                .reason(
                    dynamo_runtime::error::ErrorReason::new("request.invalid_argument").unwrap(),
                )
                .diagnostic("PRIVATE_STREAM_DIAGNOSTIC")
                .public_message("CLIENT_SAFE_STREAM_ERROR")
                .build();
            producer_error_signal.set_semantic(ErrorType::Validation, &error);
            Err::<Event, _>(axum::Error::new("semantic stream error"))
        });
        let monitored = monitor_for_disconnects_with_timeout_error_and_keep_alive(
            stream,
            context,
            guard,
            stream_handle,
            None,
            openai_stream_error,
            StreamMonitorOptions {
                error_signal: Some(error_signal),
                ..Default::default()
            },
        );
        let body = collect_sse_body(monitored).await;

        assert!(body.contains("CLIENT_SAFE_STREAM_ERROR"));
        assert!(body.contains("\"code\":400"));
        assert!(body.contains("invalid_request_error"));
        assert!(!body.contains("PRIVATE_STREAM_DIAGNOSTIC"));
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::ChatCompletions,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Validation,
            ),
            1
        );
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::ChatCompletions,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Internal,
            ),
            0
        );
    }

    #[test]
    fn semantic_overload_stream_error_is_retryable() {
        let error = DynamoError::builder()
            .class(dynamo_runtime::error::ErrorClass::CapacityExhausted)
            .reason(dynamo_runtime::error::ErrorReason::new("capacity.exhausted").unwrap())
            .build();

        let (_, body) = openai_semantic_stream_error(&error);
        let body: serde_json::Value = serde_json::from_str(&body).unwrap();

        assert_eq!(body["error"]["type"], "service_unavailable");
        assert_eq!(
            body["error"]["code"],
            crate::http::service::error::overload_status_code().as_u16()
        );
    }

    #[tokio::test]
    async fn signaled_error_before_terminal_event_keeps_disconnect_handle_armed() {
        let error_signal = StreamErrorSignal::default();
        error_signal.set(ErrorType::Internal);
        let (tx, rx) = tokio::sync::oneshot::channel();
        let handle =
            SignaledConnectionHandle::new(ConnectionHandle::create_armed(tx), Some(error_signal));

        drop(handle);

        assert!(matches!(
            rx.await.expect("stream handle did not report its status"),
            ConnectionStatus::ClosedUnexpectedly
        ));
    }

    #[test]
    fn undelivered_signaled_error_preserves_cancellation_classification() {
        let model = "undelivered-terminal-error";
        let metrics = Arc::new(Metrics::new());
        let mut guard = metrics.clone().create_inflight_guard(
            model,
            Endpoint::Responses,
            true,
            "req-undelivered-terminal-error",
        );
        guard.mark_error(ErrorType::Cancelled);
        let error_signal = StreamErrorSignal::default();
        error_signal.set(ErrorType::Internal);

        drop(SignaledInflightGuard::new(guard, Some(error_signal)));

        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::Responses,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Cancelled,
            ),
            1
        );
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::Responses,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Internal,
            ),
            0
        );
    }

    fn generate_cancellation_labels() -> CancellationLabels {
        CancellationLabels {
            model: "test-model".to_string(),
            endpoint: Endpoint::Generate.to_string(),
            request_type: "unary".to_string(),
        }
    }

    async fn wait_for_kill(context: &Arc<MockContext>) {
        for _ in 0..100 {
            if context.is_killed() {
                return;
            }
            tokio::task::yield_now().await;
        }
    }

    #[tokio::test]
    async fn armed_handle_drop_kills_generate_context() {
        let context = Arc::new(MockContext::with_kill_tracking());
        let engine_context: Arc<dyn AsyncEngineContext> = context.clone();
        let (connection_handle, stream_handle) =
            create_connection_monitor(engine_context, None, generate_cancellation_labels()).await;

        drop(connection_handle);
        drop(stream_handle);

        wait_for_kill(&context).await;
        assert!(context.is_killed());
    }

    #[tokio::test]
    async fn disarmed_handle_does_not_kill_generate_context() {
        let context = Arc::new(MockContext::with_kill_tracking());
        let engine_context: Arc<dyn AsyncEngineContext> = context.clone();
        let (mut connection_handle, stream_handle) =
            create_connection_monitor(engine_context, None, generate_cancellation_labels()).await;

        connection_handle.disarm();
        drop(connection_handle);
        drop(stream_handle);

        for _ in 0..100 {
            tokio::task::yield_now().await;
        }
        assert!(!context.is_killed());
    }

    /// Zombie backend with hanging stream is terminated by inactivity timeout.
    #[tokio::test(start_paused = true)]
    async fn test_backend_inactivity_timeout_releases_inflight_gauge() {
        let model = "zombie-model";
        // Config value "1" → HTTP-layer timeout is 2s (2x safety-net multiplier)
        let (metrics, guard, context, handle) = setup_test(model, "req-zombie");
        assert_eq!(metrics.get_inflight_count(model), 1);

        let monitored = monitor_for_disconnects_with_timeout(
            hanging_stream(),
            context,
            guard,
            handle,
            Some(Duration::from_secs(2)),
        );
        tokio::pin!(monitored);

        tokio::time::advance(Duration::from_secs(3)).await;

        let completed = tokio::time::timeout(Duration::from_secs(2), async move {
            while monitored.next().await.is_some() {}
        })
        .await;

        completed.expect("stream did not terminate — backend inactivity timeout is broken");
        assert_eq!(
            metrics.get_inflight_count(model),
            0,
            "inflight gauge leaked"
        );

        // Verify the error was categorized as ResponseTimeout, not Cancelled
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::ChatCompletions,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::ResponseTimeout,
            ),
            1,
            "inactivity timeout should be recorded as ResponseTimeout"
        );
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::ChatCompletions,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Cancelled,
            ),
            0,
            "inactivity timeout should NOT be recorded as Cancelled"
        );
    }

    /// Inactivity timeout resets on each token; only fires after a true gap.
    #[tokio::test(start_paused = true)]
    async fn test_inactivity_timeout_resets_on_each_token() {
        let model = "reset-model";

        // Phase 1: tokens arrive every 2s with a 5s config (10s HTTP timeout after 2x multiplier)
        // — stream completes normally because each token resets the timer.
        let (metrics, guard_1, ctx_1, handle_1) = setup_test(model, "phase1");
        assert_eq!(metrics.get_inflight_count(model), 1);

        let token_count = 5;
        let monitored_1 = monitor_for_disconnects_with_timeout(
            timed_token_stream(token_count, Duration::from_secs(2)),
            ctx_1,
            guard_1,
            handle_1,
            Some(Duration::from_secs(10)),
        );
        tokio::pin!(monitored_1);

        let mut received = Vec::new();
        let phase1 = tokio::time::timeout(Duration::from_secs(30), async {
            while let Some(event) = monitored_1.next().await {
                received.push(event);
            }
        })
        .await;

        assert!(
            phase1.is_ok(),
            "inactivity timeout incorrectly fired as a hard deadline"
        );
        assert_eq!(received.len(), token_count + 1); // tokens + [DONE]
        assert_eq!(metrics.get_inflight_count(model), 0);

        // Phase 2: hanging stream — timeout DOES fire.
        let guard_2 =
            metrics
                .clone()
                .create_inflight_guard(model, Endpoint::ChatCompletions, true, "phase2");
        assert_eq!(metrics.get_inflight_count(model), 1);

        let ctx_2: Arc<dyn AsyncEngineContext> = Arc::new(MockContext::new());
        let (tx_2, _rx_2) = tokio::sync::oneshot::channel();
        let handle_2 = ConnectionHandle::create_disabled(tx_2);

        let monitored_2 = monitor_for_disconnects_with_timeout(
            hanging_stream(),
            ctx_2,
            guard_2,
            handle_2,
            Some(Duration::from_secs(10)),
        );
        tokio::pin!(monitored_2);

        // Config "5" → HTTP timeout 10s (2x multiplier). Advance past it.
        tokio::time::advance(Duration::from_secs(11)).await;

        let phase2 = tokio::time::timeout(Duration::from_secs(10), async {
            while monitored_2.next().await.is_some() {}
        })
        .await;

        assert!(
            phase2.is_ok(),
            "hanging stream was not terminated by inactivity timeout"
        );
        assert_eq!(
            metrics.get_inflight_count(model),
            0,
            "inflight gauge leaked in phase 2"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn test_activity_signal_resets_inactivity_timeout() {
        let model = "keep-alive-model";
        let (metrics, guard, _context, handle) = setup_test(model, "req-keep-alive");
        let tracked_context = Arc::new(MockContext::with_kill_tracking());
        let engine_context: Arc<dyn AsyncEngineContext> = tracked_context.clone();
        let (activity_tx, activity_rx) = mpsc::unbounded_channel();

        let monitored = monitor_for_disconnects_with_timeout_error_and_keep_alive(
            hanging_stream(),
            engine_context,
            guard,
            handle,
            Some(Duration::from_secs(10)),
            openai_stream_error,
            StreamMonitorOptions {
                activity_rx: Some(activity_rx),
                ..Default::default()
            },
        );
        tokio::pin!(monitored);

        let next = monitored.next();
        tokio::pin!(next);

        tokio::time::advance(Duration::from_secs(9)).await;
        activity_tx.send(()).unwrap();
        tokio::task::yield_now().await;
        tokio::time::advance(Duration::from_secs(2)).await;
        assert!(!tracked_context.is_killed());

        tokio::time::advance(Duration::from_secs(8)).await;
        assert!(next.await.is_none());
        assert!(tracked_context.is_killed());
        assert_eq!(metrics.get_inflight_count(model), 0);
    }

    // ─────────────────────────────────────────────────────────────────────────────
    // mid-stream fault SSE contract
    //
    // When the upstream stream yields `Err(_)` mid-stream — e.g. an upstream
    // worker dies and the mpsc channel reports
    // `Disconnected: Stream ended before generation completed`, or the Python
    // chat-processor raises and the Rust→Python `tx.send()` fails with
    // `Failed to send response: SendError { .. }` — the client MUST receive:
    //   1. a structured `data: {"error":{"message":..., "type":... or "code":...}}` frame, then
    //   2. a `data: [DONE]` terminator.
    // Before the fix, the code emitted the bare SSE trailer
    // `event: error\n: <comment>\n\n` with no `[DONE]`, which violates the
    // OpenAI SSE contract and is silently skipped by naive `data:`-line parsers.
    // The two tests below pin the post-fix contract.
    // ─────────────────────────────────────────────────────────────────────────────

    /// Builds a stream that yields `data_chunks` successful events, then yields an
    /// `Err` carrying `err_msg`, simulating a mid-stream upstream fault.
    fn simulate_mid_stream_error(
        data_chunks: usize,
        err_msg: &'static str,
    ) -> impl futures::Stream<Item = Result<axum::response::sse::Event, axum::Error>> {
        async_stream::try_stream! {
            for i in 0..data_chunks {
                yield axum::response::sse::Event::default().data(format!("chunk-{i}"));
            }
            Err(axum::Error::new(err_msg))?;
        }
    }

    /// Collect the wire-format SSE body from a monitored stream.
    async fn collect_sse_body(
        stream: impl Stream<Item = Result<Event, axum::Error>> + Send + 'static,
    ) -> String {
        use axum::body::to_bytes;
        use axum::response::{IntoResponse, Sse};
        let response = Sse::new(stream).into_response();
        let body = to_bytes(response.into_body(), 1 << 20)
            .await
            .expect("body bytes");
        String::from_utf8(body.to_vec()).expect("utf8 body")
    }

    /// Assert the post-fix SSE fault contract: a parsed structured error frame
    /// carrying the sanitized static message/type/code, positioned before
    /// `[DONE]`, with no bare `event: error` trailer, and crucially with no trace
    /// of `leaked_detail` (the raw backend error) anywhere in the body.
    fn assert_fault_contract(case: &str, text: &str, leaked_detail: &str) {
        let done_pos = text.find("data: [DONE]").unwrap_or_else(|| {
            panic!("[{case}] body does not terminate with `data: [DONE]`. Body:\n{text}")
        });

        let (error_line, error_frame) = text
            .lines()
            .find_map(|line| {
                let payload = line.strip_prefix("data: ")?;
                serde_json::from_str::<serde_json::Value>(payload)
                    .ok()
                    .filter(|v| v.get("error").is_some())
                    .map(|v| (line, v))
            })
            .unwrap_or_else(|| {
                panic!(
                    "[{case}] body missing structured JSON `data: {{\"error\":{{...}}}}` frame. Body:\n{text}"
                )
            });

        let error_pos = text.find(error_line).unwrap_or_default();
        assert!(
            error_pos < done_pos,
            "[{case}] structured error frame must precede `data: [DONE]`. Body:\n{text}"
        );

        let error = error_frame
            .get("error")
            .and_then(|v| v.as_object())
            .unwrap_or_else(|| panic!("[{case}] `error` field is not an object. Body:\n{text}"));
        let expected = SanitizedError::Internal;
        let expected_message = expected.to_string();
        assert_eq!(
            error.get("message").and_then(|v| v.as_str()),
            Some(expected_message.as_str()),
            "[{case}] structured error `message` must be the sanitized static string. Body:\n{text}"
        );
        assert_eq!(
            error.get("type").and_then(|v| v.as_str()),
            Some(expected.openai_type_slug()),
            "[{case}] structured error `type` mismatch. Body:\n{text}"
        );
        assert_eq!(
            error.get("code").and_then(serde_json::Value::as_u64),
            Some(expected.status().as_u16().into()),
            "[{case}] structured error `code` mismatch. Body:\n{text}"
        );
        assert!(
            !text.contains("event: error\n: "),
            "[{case}] body contains bare `event: error\\n: <comment>` trailer (pre-fix bug). Body:\n{text}"
        );
        assert!(
            !text.contains(leaked_detail),
            "[{case}] SSE body leaked raw backend error detail to the client. \
             Expected `{leaked_detail}` to be absent. Body:\n{text}"
        );
    }

    /// Upstream worker killed mid-stream → mpsc channel reports `Disconnected` to the
    /// HTTP layer. Client MUST receive structured error + `[DONE]`.
    #[tokio::test]
    async fn test_simulate_worker_kill_emits_structured_error_and_done() {
        let (_metrics, guard, ctx, handle) = setup_test("worker-kill-model", "req-wk");
        let backend_detail = "Disconnected: Stream ended before generation completed";
        let stream = simulate_mid_stream_error(3, backend_detail);
        let monitored = monitor_for_disconnects_with_timeout(stream, ctx, guard, handle, None);
        let body = collect_sse_body(monitored).await;
        assert_fault_contract("worker_kill", &body, backend_detail);
    }

    /// Python chat-processor raises mid-stream → Rust→Python `tx.send()` fails with
    /// `SendError`. Client MUST receive structured error + `[DONE]`.
    #[tokio::test]
    async fn test_simulate_python_consumer_drop_emits_structured_error_and_done() {
        let (_metrics, guard, ctx, handle) = setup_test("py-drop-model", "req-py");
        let backend_detail = "Failed to send response: SendError { .. }";
        let stream = simulate_mid_stream_error(3, backend_detail);
        let monitored = monitor_for_disconnects_with_timeout(stream, ctx, guard, handle, None);
        let body = collect_sse_body(monitored).await;
        assert_fault_contract("python_consumer_drop", &body, backend_detail);
    }

    #[tokio::test]
    async fn typed_producer_error_overrides_generic_stream_error_classification() {
        let model = "typed-timeout-model";
        let (metrics, guard, ctx, handle) = setup_test(model, "req-typed-timeout");
        let error_signal = StreamErrorSignal::default();
        error_signal.set(ErrorType::ResponseTimeout);
        let stream = simulate_mid_stream_error(0, "request-plane response timeout");
        let monitored = monitor_for_disconnects_with_timeout_error_and_keep_alive(
            stream,
            ctx,
            guard,
            handle,
            None,
            openai_stream_error,
            StreamMonitorOptions {
                error_signal: Some(error_signal),
                ..Default::default()
            },
        );

        let _body = collect_sse_body(monitored).await;
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::ChatCompletions,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::ResponseTimeout,
            ),
            1
        );
        assert_eq!(
            metrics.get_request_counter(
                model,
                &Endpoint::ChatCompletions,
                &RequestType::Stream,
                &Status::Error,
                &ErrorType::Internal,
            ),
            0
        );
    }

    /// A backend error carrying sensitive internals (file paths, panic text,
    /// Python exception details) MUST NOT reach the streaming client. The client
    /// receives only the sanitized static frame; the detail stays server-side.
    #[tokio::test]
    async fn test_mid_stream_error_does_not_leak_internal_details() {
        let (_metrics, guard, ctx, handle) = setup_test("leak-model", "req-leak");
        let backend_detail = "panicked at '/opt/dynamo/lib/python3.12/site-packages/engine/worker.py:512: ValueError: secret tensor shape mismatch'";
        let stream = simulate_mid_stream_error(2, backend_detail);
        let monitored = monitor_for_disconnects_with_timeout(stream, ctx, guard, handle, None);
        let body = collect_sse_body(monitored).await;
        assert_fault_contract("internal_detail_leak", &body, backend_detail);
        // Spot-check the most damaging fragments explicitly.
        assert!(!body.contains("site-packages"), "leaked a filesystem path");
        assert!(!body.contains("panicked at"), "leaked panic text");
        assert!(!body.contains("ValueError"), "leaked exception type");
    }
}