skippy-server 0.76.1

Embedded Skippy staged runtime server
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
use super::*;
use crate::frontend::EmbeddedOpenAiRequestDefaults;
use crate::frontend::SpeculativeDecodeConfig;
use crate::frontend::admission::GenerationTokenBudget;
use crate::frontend::generation::ADMISSION_STARVATION_BOUND_TURNS;
use crate::frontend::generation::OpenAiBackendMode;
use crate::frontend::iteration_scheduler::IterationScheduler;
use crate::runtime_state::RuntimeState;
use futures_util::StreamExt;
use openai_frontend::ChatCompletionChunk;
use openai_frontend::ChatCompletionRequest;
use openai_frontend::ChatCompletionResponse;
use openai_frontend::ChatHookOutcome;
use openai_frontend::FinishReason;
use openai_frontend::OpenAiHookPolicy;
use openai_frontend::Usage;
use openai_frontend::set_chat_mesh_hooks_enabled;
use serde_json::json;
use tokio::runtime::Runtime;

/// A disabled telemetry sink for `StreamEventSender` construction in tests.
///
/// `TelemetryLevel::Off` makes `emit` a no-op, so these tests exercise the
/// stall/drop control flow without needing a collector; the sink only has to
/// be a valid handle.
fn test_telemetry() -> crate::telemetry::Telemetry {
    let config: skippy_protocol::StageConfig = serde_json::from_value(json!({
        "run_id": "run",
        "topology_id": "topology",
        "model_id": "org/model:Q4_K_M",
        "stage_id": "stage-0",
        "stage_index": 0,
        "layer_start": 0,
        "layer_end": 4,
        "load_mode": "runtime-slice",
        "bind_addr": "127.0.0.1:0",
    }))
    .expect("minimal stage config for telemetry");
    crate::telemetry::Telemetry::new(None, 1, config, crate::telemetry::TelemetryLevel::Off)
}

fn trusted_ids(session_id: &str) -> OpenAiGenerationIds {
    OpenAiGenerationIds::new_with_trust(OpenAiCacheHints::default(), Some(session_id), true)
}

fn trusted_session_key(session_id: &str) -> String {
    trusted_generation_session_key(&trusted_ids(session_id)).expect("trusted session key")
}

fn admission_controller(
    generation_concurrency: usize,
    generation_queue_limit: usize,
) -> GenerationAdmissionController {
    admission_controller_with_budget(generation_concurrency, generation_queue_limit, 4_096)
}

fn admission_controller_with_budget(
    generation_concurrency: usize,
    generation_queue_limit: usize,
    token_capacity: usize,
) -> GenerationAdmissionController {
    GenerationAdmissionController {
        generation_limit: Arc::new(GenerationConcurrencyController::fixed(
            generation_concurrency,
        )),
        generation_queue_depth: Arc::new(AtomicUsize::new(0)),
        generation_queue_limit,
        generation_service_estimator: Arc::new(GenerationServiceEstimator::new(
            generation_concurrency,
        )),
        generation_session_locks: Arc::new(Mutex::new(BTreeMap::new())),
        generation_token_budget: Arc::new(GenerationTokenBudget::new(token_capacity)),
    }
}

fn result_error<T>(result: OpenAiResult<T>) -> OpenAiError {
    match result {
        Ok(_) => panic!("expected generation admission to fail"),
        Err(error) => error,
    }
}

#[tokio::test]
async fn queued_admission_balances_shared_prefix_families_across_lane_wave() {
    let controller = admission_controller(1, 4);
    let work = GenerationAdmissionWork::new(4, 1);
    let active = controller
        .acquire_work(
            &trusted_ids("active"),
            &openai_frontend::CancellationToken::new(),
            Duration::from_secs(2),
            work,
        )
        .await
        .expect("active request admission");
    let (tx, mut rx) = tokio::sync::mpsc::channel(4);
    for (label, prompt) in [
        ("family-a-1", vec![1, 1, 3, 4]),
        ("family-a-2", vec![1, 1, 3, 5]),
        ("family-b-1", vec![2, 2, 3, 4]),
        ("family-b-2", vec![2, 2, 3, 5]),
    ] {
        let controller = controller.clone();
        let tx = tx.clone();
        tokio::spawn(async move {
            let cancellation = openai_frontend::CancellationToken::new();
            let admitted = controller
                .acquire_scheduled_work(
                    &trusted_ids(label),
                    &cancellation,
                    Duration::from_secs(2),
                    work,
                    GenerationAdmissionScheduling::new(
                        Arc::from(prompt),
                        Arc::new(skippy_scheduler::CacheAffinity::default),
                    ),
                )
                .await
                .expect("queued request admission");
            tx.send((label, admitted)).await.unwrap();
        });
    }
    drop(tx);
    tokio::time::timeout(Duration::from_secs(1), async {
        while controller.generation_queue_depth.load(Ordering::Acquire) != 4 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("all prompts become scheduler-visible");

    drop(active);
    let (first_label, first) = tokio::time::timeout(Duration::from_millis(250), rx.recv())
        .await
        .expect("first queued admission was promoted")
        .expect("first queued admission");
    drop(first);
    let (second_label, second) = rx.recv().await.expect("second queued admission");
    assert_ne!(
        first_label.split('-').nth(1),
        second_label.split('-').nth(1),
        "one family must not drain the whole lane wave"
    );
    drop(second);
    let (_, third) = rx.recv().await.expect("third queued admission");
    drop(third);
    let (_, fourth) = rx.recv().await.expect("fourth queued admission");
    drop(fourth);
}

#[tokio::test]
async fn capacity_waiter_holds_neither_a_lane_nor_kv_until_atomic_promotion() {
    let controller = admission_controller_with_budget(2, 2, 10);
    let active = controller
        .acquire_work(
            &trusted_ids("active"),
            &openai_frontend::CancellationToken::new(),
            Duration::ZERO,
            GenerationAdmissionWork::new(7, 0),
        )
        .await
        .expect("first capacity reservation");
    let waiting_controller = controller.clone();
    let waiter = tokio::spawn(async move {
        waiting_controller
            .acquire_work(
                &trusted_ids("waiting"),
                &openai_frontend::CancellationToken::new(),
                Duration::ZERO,
                GenerationAdmissionWork::new(7, 0),
            )
            .await
    });

    tokio::time::timeout(Duration::from_millis(100), async {
        while controller.generation_queue_depth.load(Ordering::Acquire) != 1 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("capacity waiter entered the queue");
    assert_eq!(controller.generation_limit.available_permits(), 1);
    assert_eq!(controller.generation_token_budget.active_tokens(), 7);

    drop(active);
    let promoted = tokio::time::timeout(Duration::from_millis(100), waiter)
        .await
        .expect("capacity waiter promoted")
        .expect("capacity waiter task completed")
        .expect("capacity waiter admission");
    assert_eq!(controller.generation_limit.available_permits(), 1);
    assert_eq!(controller.generation_token_budget.active_tokens(), 7);
    drop(promoted);
    assert_eq!(controller.generation_limit.available_permits(), 2);
    assert_eq!(controller.generation_token_budget.active_tokens(), 0);
}

#[tokio::test]
async fn capacity_waiters_drain_serially_after_each_kv_release() {
    let controller = admission_controller_with_budget(2, 4, 10);
    let active = controller
        .acquire_work(
            &trusted_ids("active"),
            &openai_frontend::CancellationToken::new(),
            Duration::ZERO,
            GenerationAdmissionWork::new(10, 0),
        )
        .await
        .expect("active capacity reservation");
    let (tx, mut rx) = tokio::sync::mpsc::channel(4);
    for index in 0..4 {
        let controller = controller.clone();
        let tx = tx.clone();
        tokio::spawn(async move {
            let cancellation = openai_frontend::CancellationToken::new();
            let admitted = controller
                .acquire_work(
                    &trusted_ids(&format!("waiting-{index}")),
                    &cancellation,
                    Duration::ZERO,
                    GenerationAdmissionWork::new(10, 0),
                )
                .await
                .expect("queued capacity admission");
            tx.send(admitted).await.unwrap();
        });
    }
    drop(tx);
    tokio::time::timeout(Duration::from_secs(1), async {
        while controller.generation_queue_depth.load(Ordering::Acquire) != 4 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("all capacity waiters entered the queue");

    drop(active);
    for _ in 0..4 {
        let admitted = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("next capacity waiter promoted")
            .expect("queued capacity admission");
        assert_eq!(controller.generation_token_budget.active_tokens(), 10);
        drop(admitted);
    }
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);
    assert_eq!(controller.generation_limit.available_permits(), 2);
    assert_eq!(controller.generation_token_budget.active_tokens(), 0);
}

#[tokio::test]
async fn full_pool_waiter_is_admitted_after_bounded_half_pool_bypasses() {
    let controller = admission_controller_with_budget(2, 4, 10);
    let half_pool_work = GenerationAdmissionWork::new(5, 0);
    let full_pool_work = GenerationAdmissionWork::new(10, 0);
    let active = controller
        .acquire_work(
            &trusted_ids("active-half-pool"),
            &openai_frontend::CancellationToken::new(),
            Duration::ZERO,
            half_pool_work,
        )
        .await
        .expect("initial half-pool admission");

    let full_pool_controller = controller.clone();
    let full_pool_waiter = tokio::spawn(async move {
        full_pool_controller
            .acquire_work(
                &trusted_ids("full-pool-waiter"),
                &openai_frontend::CancellationToken::new(),
                Duration::ZERO,
                full_pool_work,
            )
            .await
    });
    tokio::time::timeout(Duration::from_secs(1), async {
        while controller.generation_queue_depth.load(Ordering::Acquire) != 1 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("full-pool request entered the queue");

    // Keep one half-pool reservation active and repeatedly fill/release the
    // other half. The full-pool request cannot fit during these admissions.
    for wave in 0..ADMISSION_STARVATION_BOUND_TURNS {
        let bypass = tokio::time::timeout(
            Duration::from_secs(1),
            controller.acquire_work(
                &trusted_ids(&format!("half-pool-bypass-{wave}")),
                &openai_frontend::CancellationToken::new(),
                Duration::ZERO,
                half_pool_work,
            ),
        )
        .await
        .expect("fitting half-pool request completed before the timeout")
        .expect("fitting half-pool request admitted before the bound");
        assert_eq!(controller.generation_token_budget.active_tokens(), 10);
        drop(bypass);
    }

    // The next fitting arrival reaches the bound and must remain queued while
    // the controller drains capacity toward the older full-pool request.
    let bypass_controller = controller.clone();
    let blocked_bypass = tokio::spawn(async move {
        bypass_controller
            .acquire_work(
                &trusted_ids("half-pool-after-bound"),
                &openai_frontend::CancellationToken::new(),
                Duration::ZERO,
                half_pool_work,
            )
            .await
    });
    tokio::time::timeout(Duration::from_secs(1), async {
        while controller.generation_queue_depth.load(Ordering::Acquire) != 2 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("post-bound half-pool request remained queued");
    assert!(!full_pool_waiter.is_finished());
    assert!(!blocked_bypass.is_finished());

    drop(active);
    let admitted_full_pool = tokio::time::timeout(Duration::from_secs(1), full_pool_waiter)
        .await
        .expect("full-pool waiter admitted after capacity drained")
        .expect("full-pool waiter task completed")
        .expect("full-pool admission succeeded");
    assert_eq!(controller.generation_token_budget.active_tokens(), 10);
    assert!(!blocked_bypass.is_finished());

    drop(admitted_full_pool);
    let admitted_bypass = tokio::time::timeout(Duration::from_secs(1), blocked_bypass)
        .await
        .expect("younger half-pool waiter admitted after the senior completed")
        .expect("half-pool waiter task completed")
        .expect("half-pool admission succeeded");
    drop(admitted_bypass);
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);
    assert_eq!(controller.generation_limit.available_permits(), 2);
    assert_eq!(controller.generation_token_budget.active_tokens(), 0);
}

#[tokio::test]
async fn request_larger_than_the_kv_pool_fails_without_queueing_or_taking_a_lane() {
    let controller = admission_controller_with_budget(2, 2, 128);
    let error = result_error(
        controller
            .acquire_work(
                &trusted_ids("too-large"),
                &openai_frontend::CancellationToken::new(),
                Duration::ZERO,
                GenerationAdmissionWork::new(129, 0),
            )
            .await,
    );

    assert_eq!(error.status(), axum::http::StatusCode::BAD_REQUEST);
    assert_eq!(
        error.body().error.code.as_deref(),
        Some("context_length_exceeded")
    );
    assert!(
        error
            .body()
            .error
            .message
            .contains("runtime pool holds 128")
    );
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);
    assert_eq!(controller.generation_limit.available_permits(), 2);
    assert_eq!(controller.generation_token_budget.active_tokens(), 0);
}

#[tokio::test]
async fn cancelling_a_capacity_waiter_leaks_neither_lane_nor_kv_reservation() {
    let controller = admission_controller_with_budget(2, 2, 128);
    let active = controller
        .acquire_work(
            &trusted_ids("active"),
            &openai_frontend::CancellationToken::new(),
            Duration::ZERO,
            GenerationAdmissionWork::new(100, 0),
        )
        .await
        .expect("first capacity reservation");
    let cancellation = openai_frontend::CancellationToken::new();
    let waiter_cancellation = cancellation.clone();
    let waiting_controller = controller.clone();
    let waiter = tokio::spawn(async move {
        waiting_controller
            .acquire_work(
                &trusted_ids("waiting"),
                &waiter_cancellation,
                Duration::ZERO,
                GenerationAdmissionWork::new(64, 0),
            )
            .await
    });
    tokio::time::timeout(Duration::from_millis(100), async {
        while controller.generation_queue_depth.load(Ordering::Acquire) != 1 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("capacity waiter entered the queue");

    cancellation.cancel();
    let error = result_error(
        tokio::time::timeout(Duration::from_millis(100), waiter)
            .await
            .expect("cancelled capacity waiter returned")
            .expect("capacity waiter task completed"),
    );
    assert!(error.body().error.message.contains("request cancelled"));
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);
    assert_eq!(controller.generation_limit.available_permits(), 1);
    assert_eq!(controller.generation_token_budget.active_tokens(), 100);

    drop(active);
    assert_eq!(controller.generation_limit.available_permits(), 2);
    assert_eq!(controller.generation_token_budget.active_tokens(), 0);
}

#[tokio::test]
async fn predicted_wait_rejection_preserves_queue_capacity() {
    let controller = admission_controller(1, 2);
    let work = GenerationAdmissionWork::new(100, 100);
    controller
        .generation_service_estimator
        .observe_completed(work, 100.0, 100.0);
    let active = controller
        .acquire_work(
            &trusted_ids("agent-1"),
            &openai_frontend::CancellationToken::new(),
            Duration::from_secs(1),
            work,
        )
        .await
        .expect("active request admission");

    let error = result_error(
        controller
            .acquire_work(
                &trusted_ids("agent-2"),
                &openai_frontend::CancellationToken::new(),
                Duration::from_millis(199),
                work,
            )
            .await,
    );

    assert!(
        error
            .body()
            .error
            .message
            .contains("predicted generation wait")
    );
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);
    drop(active);
    assert_eq!(controller.generation_limit.available_permits(), 1);
}

#[test]
fn session_registry_counts_live_leases_and_cleans_replaced_entries() {
    let registry = Arc::new(Mutex::new(BTreeMap::new()));
    let first = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned())
        .expect("first session lease");
    let second = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned())
        .expect("second session lease");

    {
        let locks = registry.lock().expect("session registry lock");
        let entry = locks.get("agent-1").expect("shared session entry");
        assert_eq!(entry.users.load(Ordering::Acquire), 2);
    }

    drop(first);
    {
        let locks = registry.lock().expect("session registry lock");
        let entry = locks.get("agent-1").expect("live session entry");
        assert_eq!(entry.users.load(Ordering::Acquire), 1);
    }

    drop(second);
    assert!(registry.lock().expect("session registry lock").is_empty());

    let replacement = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned())
        .expect("replacement session lease");
    assert_eq!(registry.lock().expect("session registry lock").len(), 1);
    drop(replacement);
    assert!(registry.lock().expect("session registry lock").is_empty());
}

#[tokio::test]
async fn same_trusted_session_serializes_without_consuming_global_queue_capacity() {
    let controller = admission_controller(1, 1);
    let session_key = trusted_session_key("agent-1");
    let first_cancellation = openai_frontend::CancellationToken::new();
    let first = controller
        .acquire(
            &trusted_ids("agent-1"),
            &first_cancellation,
            Duration::from_secs(1),
        )
        .await
        .expect("first session admission");

    let second_controller = controller.clone();
    let second_cancellation = openai_frontend::CancellationToken::new();
    let waiter_cancellation = second_cancellation.clone();
    let waiter = tokio::spawn(async move {
        second_controller
            .acquire(
                &trusted_ids("agent-1"),
                &waiter_cancellation,
                Duration::from_secs(1),
            )
            .await
    });

    tokio::time::timeout(Duration::from_millis(100), async {
        loop {
            let users = controller
                .generation_session_locks
                .lock()
                .expect("session registry lock")
                .get(&session_key)
                .map_or(0, |entry| entry.users.load(Ordering::Acquire));
            if users == 2 {
                break;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("second turn registered its session wait");

    assert!(!waiter.is_finished());
    assert_eq!(
        controller.generation_queue_depth.load(Ordering::Acquire),
        0,
        "session contention must not consume global queue capacity"
    );

    second_cancellation.cancel();
    let error = result_error(
        tokio::time::timeout(Duration::from_millis(100), waiter)
            .await
            .expect("cancelled session waiter returned")
            .expect("session waiter task completed"),
    );
    assert!(error.body().error.message.contains("request cancelled"));
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);

    drop(first);
    assert_eq!(controller.generation_limit.available_permits(), 1);
    assert!(
        controller
            .generation_session_locks
            .lock()
            .expect("session registry lock")
            .is_empty()
    );
}

#[tokio::test]
async fn same_trusted_session_acquires_only_after_the_first_turn_releases() {
    let controller = admission_controller(1, 1);
    let first_cancellation = openai_frontend::CancellationToken::new();
    let first = controller
        .acquire(
            &trusted_ids("agent-1"),
            &first_cancellation,
            Duration::from_secs(1),
        )
        .await
        .expect("first session admission");

    let second_controller = controller.clone();
    let second = tokio::spawn(async move {
        second_controller
            .acquire(
                &trusted_ids("agent-1"),
                &openai_frontend::CancellationToken::new(),
                Duration::from_secs(1),
            )
            .await
    });

    tokio::time::sleep(Duration::from_millis(5)).await;
    assert!(!second.is_finished());
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);

    drop(first);
    let second = tokio::time::timeout(Duration::from_millis(100), second)
        .await
        .expect("second turn acquired after first released")
        .expect("second turn task completed")
        .expect("second session admission");
    assert_eq!(controller.generation_limit.available_permits(), 0);
    drop(second);
    assert_eq!(controller.generation_limit.available_permits(), 1);
}

#[tokio::test]
async fn session_and_global_admission_share_one_absolute_deadline() {
    let controller = admission_controller(1, 1);
    let first_cancellation = openai_frontend::CancellationToken::new();
    let (global_permit, session_permit) = controller
        .acquire(
            &trusted_ids("agent-1"),
            &first_cancellation,
            Duration::from_secs(1),
        )
        .await
        .expect("first session admission");
    let session_permit = session_permit.expect("trusted session permit");
    let release_session = tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(140)).await;
        drop(session_permit);
    });
    let started = Instant::now();

    let error = result_error(
        controller
            .acquire(
                &trusted_ids("agent-1"),
                &openai_frontend::CancellationToken::new(),
                Duration::from_millis(200),
            )
            .await,
    );

    assert!(error.body().error.message.contains("timed out waiting"));
    assert!(
        started.elapsed() < Duration::from_millis(300),
        "global-lane waiting must not restart the request admission timeout"
    );
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);
    release_session
        .await
        .expect("session release task completed");
    drop(global_permit);
}

#[tokio::test]
async fn unrelated_session_is_not_starved_by_a_same_session_waiter() {
    let controller = admission_controller(2, 2);
    let session_key = trusted_session_key("agent-1");
    let first_cancellation = openai_frontend::CancellationToken::new();
    let first = controller
        .acquire(
            &trusted_ids("agent-1"),
            &first_cancellation,
            Duration::from_secs(1),
        )
        .await
        .expect("first session admission");

    let duplicate_controller = controller.clone();
    let duplicate_cancellation = openai_frontend::CancellationToken::new();
    let waiter_cancellation = duplicate_cancellation.clone();
    let duplicate = tokio::spawn(async move {
        duplicate_controller
            .acquire(
                &trusted_ids("agent-1"),
                &waiter_cancellation,
                Duration::from_secs(1),
            )
            .await
    });

    tokio::time::timeout(Duration::from_millis(100), async {
        loop {
            let users = controller
                .generation_session_locks
                .lock()
                .expect("session registry lock")
                .get(&session_key)
                .map_or(0, |entry| entry.users.load(Ordering::Acquire));
            if users == 2 {
                break;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("duplicate turn registered its session wait");

    assert_eq!(controller.generation_limit.available_permits(), 1);
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);

    let unrelated = controller
        .acquire(
            &trusted_ids("agent-2"),
            &openai_frontend::CancellationToken::new(),
            Duration::from_millis(100),
        )
        .await
        .expect("unrelated session used the free global lane");
    assert_eq!(controller.generation_limit.available_permits(), 0);
    assert!(!duplicate.is_finished());

    duplicate_cancellation.cancel();
    let duplicate_error = result_error(
        tokio::time::timeout(Duration::from_millis(100), duplicate)
            .await
            .expect("duplicate waiter cancelled")
            .expect("duplicate waiter task completed"),
    );
    assert!(
        duplicate_error
            .body()
            .error
            .message
            .contains("request cancelled")
    );
    drop((first, unrelated));
    assert_eq!(controller.generation_limit.available_permits(), 2);
}

#[tokio::test]
async fn same_session_waiter_does_not_reserve_the_only_global_queue_slot() {
    let controller = admission_controller(1, 1);
    let session_key = trusted_session_key("agent-1");
    let first = controller
        .acquire(
            &trusted_ids("agent-1"),
            &openai_frontend::CancellationToken::new(),
            Duration::from_secs(1),
        )
        .await
        .expect("first session admission");

    let duplicate_controller = controller.clone();
    let duplicate_cancellation = openai_frontend::CancellationToken::new();
    let waiter_cancellation = duplicate_cancellation.clone();
    let duplicate = tokio::spawn(async move {
        duplicate_controller
            .acquire(
                &trusted_ids("agent-1"),
                &waiter_cancellation,
                Duration::from_secs(1),
            )
            .await
    });
    tokio::time::timeout(Duration::from_millis(100), async {
        loop {
            let users = controller
                .generation_session_locks
                .lock()
                .expect("session registry lock")
                .get(&session_key)
                .map_or(0, |entry| entry.users.load(Ordering::Acquire));
            if users == 2 {
                break;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("duplicate turn registered its session wait");
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);

    let unrelated_controller = controller.clone();
    let unrelated = tokio::spawn(async move {
        unrelated_controller
            .acquire(
                &trusted_ids("agent-2"),
                &openai_frontend::CancellationToken::new(),
                Duration::from_secs(1),
            )
            .await
    });
    tokio::time::timeout(Duration::from_millis(100), async {
        while controller.generation_queue_depth.load(Ordering::Acquire) != 1 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("unrelated turn reserved the only global queue slot");
    assert!(!unrelated.is_finished());

    duplicate_cancellation.cancel();
    let duplicate_error = result_error(
        tokio::time::timeout(Duration::from_millis(100), duplicate)
            .await
            .expect("duplicate waiter cancelled")
            .expect("duplicate waiter task completed"),
    );
    assert_eq!(duplicate_error.status().as_u16(), 499);

    drop(first);
    let unrelated = tokio::time::timeout(Duration::from_millis(100), unrelated)
        .await
        .expect("unrelated turn acquired the released lane")
        .expect("unrelated waiter task completed")
        .expect("unrelated session admission");
    assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0);
    drop(unrelated);
}

#[tokio::test]
async fn different_trusted_sessions_can_hold_generation_lanes_concurrently() {
    let controller = admission_controller(2, 2);
    let first_cancellation = openai_frontend::CancellationToken::new();
    let second_cancellation = openai_frontend::CancellationToken::new();
    let first_ids = trusted_ids("agent-1");
    let second_ids = trusted_ids("agent-2");

    let (first, second) = tokio::join!(
        controller.acquire(&first_ids, &first_cancellation, Duration::from_secs(1)),
        controller.acquire(&second_ids, &second_cancellation, Duration::from_secs(1)),
    );
    let first = first.expect("first session admission");
    let second = second.expect("second session admission");

    assert_eq!(controller.generation_limit.available_permits(), 0);
    assert_eq!(
        controller
            .generation_session_locks
            .lock()
            .expect("session registry lock")
            .len(),
        2
    );

    drop((first, second));
    assert_eq!(controller.generation_limit.available_permits(), 2);
    assert!(
        controller
            .generation_session_locks
            .lock()
            .expect("session registry lock")
            .is_empty()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn blocking_worker_holds_global_and_session_permits_until_work_finishes() {
    let controller = admission_controller(1, 1);
    let session_key = trusted_session_key("agent-1");
    let cancellation = openai_frontend::CancellationToken::new();
    let (global_permit, session_permit) = controller
        .acquire(
            &trusted_ids("agent-1"),
            &cancellation,
            Duration::from_secs(1),
        )
        .await
        .expect("worker admission");
    let worker_context = OpenAiRequestContext::new();
    let worker_started = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let release_worker = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let started = worker_started.clone();
    let release = release_worker.clone();

    let worker = tokio::spawn(run_blocking_generation_worker(
        global_permit,
        worker_context,
        move |_| {
            let _session_permit = session_permit;
            started.store(true, Ordering::Release);
            while !release.load(Ordering::Acquire) {
                std::thread::yield_now();
            }
        },
    ));

    tokio::time::timeout(Duration::from_millis(100), async {
        while !worker_started.load(Ordering::Acquire) {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("blocking generation worker started");

    assert_eq!(controller.generation_limit.available_permits(), 0);
    let entry = controller
        .generation_session_locks
        .lock()
        .expect("session registry lock")
        .get(&session_key)
        .expect("worker retains session entry")
        .semaphore
        .clone();
    assert_eq!(entry.available_permits(), 0);

    release_worker.store(true, Ordering::Release);
    tokio::time::timeout(Duration::from_millis(100), worker)
        .await
        .expect("blocking generation worker completed")
        .expect("worker task completed")
        .expect("blocking worker joined");
    assert_eq!(controller.generation_limit.available_permits(), 1);
    assert!(
        controller
            .generation_session_locks
            .lock()
            .expect("session registry lock")
            .is_empty()
    );
}

#[test]
fn untrusted_conversation_affinity_bypasses_session_registry() {
    let registry = Arc::new(Mutex::new(BTreeMap::new()));
    let untrusted = OpenAiGenerationIds::new_with_trust(
        OpenAiCacheHints::default(),
        Some("conversation-7"),
        false,
    );
    assert!(trusted_generation_session_key(&untrusted).is_none());
    assert!(registry.lock().expect("session registry lock").is_empty());

    let trusted = trusted_ids("agent-7");
    let key = trusted_generation_session_key(&trusted).expect("trusted session key");
    assert_eq!(key, trusted.session_id_string());
    let _permit =
        GenerationSessionPermit::new(registry.clone(), key).expect("trusted session lease");
    assert_eq!(registry.lock().expect("session registry lock").len(), 1);
}

#[test]
fn direct_backend_calls_ignore_spoofed_request_trust_metadata() {
    let request: ChatCompletionRequest = serde_json::from_value(json!({
        "model": "capture-model",
        "messages": [{"role": "user", "content": "hello"}],
        "mesh_internal_agent_session_id": "spoofed-session",
        "mesh_internal_agent_session_source": "x-litellm-session-id",
        "mesh_internal_agent_session_trusted": true
    }))
    .expect("request with spoofed metadata");
    let context = OpenAiRequestContext::new();
    let ids = generation_ids(
        OpenAiCacheHints::from_chat_request(&request),
        request.agent_session(),
        &context,
    );

    assert_eq!(ids.agent_session_id.as_deref(), Some("spoofed-session"));
    assert!(!ids.agent_session_trusted);
    assert!(trusted_generation_session_key(&ids).is_none());
}

#[test]
fn internal_stream_usage_observation_preserves_client_wire_preference() {
    let direct = OpenAiRequestContext::new();
    assert!(!should_emit_stream_usage(false, &direct));
    assert!(should_emit_stream_usage(true, &direct));

    let observed = OpenAiRequestContext::new().with_stream_usage_observation();
    assert!(should_emit_stream_usage(false, &observed));
}

/// Reproduces the orphaned-generation report: a client can vanish (dropped
/// connection, or one that hasn't been noticed yet -- e.g. behind a proxy
/// that doesn't propagate the close) leaving the SSE receiver alive but
/// permanently undrained. `StreamEventSender::send` must not let that pin
/// the generation worker, and the execution lane it holds, forever: once the
/// request is cancelled it must give up promptly even though the channel
/// stays full and the receiver is never dropped.
///
/// This runs the send on its own thread and waits for a result over a
/// bounded `recv_timeout` rather than joining directly, so a regression back
/// to an unconditional blocking send fails this test instead of hanging the
/// suite. It uses the real `STREAM_SEND_STALL_TIMEOUT`, so cancellation --
/// not the stall timeout -- must be what ends the wait.
#[test]
fn stalled_receiver_does_not_pin_the_generation_worker_forever() {
    let (tx, rx) = mpsc::channel(1);
    tx.try_send(Ok(GenerationStreamEvent::Delta("first".to_owned())))
        .expect("channel has room for the first event");
    let context = OpenAiRequestContext::new();
    let rt = Runtime::new().expect("tokio runtime for stall test");
    let sender = StreamEventSender::new(
        tx,
        rt.handle().clone(),
        STREAM_SEND_STALL_TIMEOUT,
        "test-request".to_owned(),
        test_telemetry(),
    );

    let sender_context = context.clone();
    let (done_tx, done_rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let result = sender.send(
            Ok(GenerationStreamEvent::Delta("second".to_owned())),
            &sender_context,
        );
        // Keep `rx` alive without draining it until after the send settles,
        // so a fix that works only because the channel closed doesn't pass.
        drop(rx);
        let _ = done_tx.send(result.is_err());
    });

    // Give the sender thread a chance to observe the full channel before
    // cancelling -- simulating cancellation arriving (e.g. from a
    // connection-drop observer) after the worker is already stuck sending.
    std::thread::sleep(Duration::from_millis(50));
    context.cancel();

    let cancelled = done_rx
        .recv_timeout(Duration::from_secs(5))
        .expect("a stalled send must be interrupted by cancellation, not block forever");
    assert!(cancelled, "cancelled send must return an error");
}

/// Covers the case the report actually flagged as unproven: nothing ever
/// calls `cancel()` -- the connection-drop observer (`CancelOnDropSseStream`)
/// simply never fires, e.g. because the client vanished behind a proxy that
/// kept the socket to mesh-llm open. A stalled, never-dropped, never-drained
/// receiver must still cause the send to give up and self-cancel once it has
/// been full for the (here, injected and short) stall timeout, so the lane
/// isn't held indefinitely.
#[test]
fn stalled_receiver_self_cancels_after_the_stall_timeout_with_no_external_cancel() {
    let (tx, rx) = mpsc::channel(1);
    tx.try_send(Ok(GenerationStreamEvent::Delta("first".to_owned())))
        .expect("channel has room for the first event");
    let context = OpenAiRequestContext::new();
    let rt = Runtime::new().expect("tokio runtime for stall test");
    let sender = StreamEventSender::new(
        tx,
        rt.handle().clone(),
        Duration::from_millis(50),
        "test-request".to_owned(),
        test_telemetry(),
    );

    let result = sender.send(
        Ok(GenerationStreamEvent::Delta("second".to_owned())),
        &context,
    );

    assert!(
        result.is_err(),
        "a send stalled past the timeout must fail rather than hang"
    );
    assert!(
        context.is_cancelled(),
        "a self-detected stall must cancel the request so the lane is freed"
    );
    drop(rx);
}

/// Red->green for the swallowed-terminal-frame defect: on the pre-fix code,
/// the `run_generation_stream` cancellation branch checked
/// `context.is_cancelled()` before sending, so an already-cancelled request
/// caused the cancellation error frame -- and, by the same shape, the
/// `parser.finish` error frame and the outer generation error frame -- to be
/// silently dropped instead of enqueued. That flips
/// `stream_lifecycle`'s terminal classification: without the `Err` frame,
/// `drop_outcome()` falls through to `StreamDropOutcome::Cancelled` instead
/// of the `BackendError`/`StreamTerminal` path `lifecycle.failed(error)`
/// drives. `send_terminal` must deliver the frame to a receiver that is
/// merely cancelled but still alive and draining, while `send` (used only
/// for in-flight events) must still refuse to send once cancelled.
#[test]
fn terminal_frames_are_delivered_after_the_request_is_cancelled() {
    let (tx, mut rx) = mpsc::channel(4);
    let context = OpenAiRequestContext::new();
    context.cancel();
    let rt = Runtime::new().expect("tokio runtime for terminal-delivery test");
    let sender = StreamEventSender::new(
        tx,
        rt.handle().clone(),
        STREAM_SEND_STALL_TIMEOUT,
        "test-request".to_owned(),
        test_telemetry(),
    );

    sender
        .send_terminal(Ok(GenerationStreamEvent::Done(FinishReason::Stop)))
        .expect("terminal frames must still reach a live, cancelled-but-draining receiver");

    let received = rx
        .try_recv()
        .expect("the terminal frame must be enqueued, not silently swallowed");
    assert!(matches!(
        received,
        Ok(GenerationStreamEvent::Done(FinishReason::Stop))
    ));

    let send_result = sender.send(
        Ok(GenerationStreamEvent::Delta("late".to_owned())),
        &context,
    );
    assert!(
        send_result.is_err(),
        "the cancellation check is bypassed only for terminal frames, not in-flight ones"
    );
}

/// Once streaming has committed HTTP 200, a native generation failure cannot
/// be converted into a new HTTP status. It must remain an `Err` item on the
/// backend stream so `openai-frontend` can frame an explicit SSE error event
/// before `[DONE]` instead of making the response look like a zero-token
/// success.
#[test]
fn backend_errors_are_delivered_as_terminal_stream_frames() {
    let (tx, mut rx) = mpsc::channel(4);
    let rt = Runtime::new().expect("tokio runtime for terminal-error test");
    let sender = StreamEventSender::new(
        tx,
        rt.handle().clone(),
        STREAM_SEND_STALL_TIMEOUT,
        "test-request".to_owned(),
        test_telemetry(),
    );

    sender
        .send_terminal(Err(OpenAiError::backend(
            "native decode failed to find a memory slot",
        )))
        .expect("backend failure must reach a live stream receiver");

    let error = match rx.try_recv().expect("backend failure must be enqueued") {
        Ok(_) => panic!("terminal item must remain an error"),
        Err(error) => error,
    };
    assert!(
        error
            .to_string()
            .contains("native decode failed to find a memory slot")
    );
}

/// Bounds the double-wait hazard: once an in-flight send has already proven
/// the receiver unreachable (stalled past the timeout, here injected short),
/// a subsequent terminal send must not wait out the same stall timeout a
/// second time -- that would double the execution lane's hold to
/// `2 * stall_timeout` and defeat the point of freeing it promptly.
#[test]
fn terminal_frames_are_dropped_once_the_receiver_is_proven_unreachable() {
    let (tx, rx) = mpsc::channel(1);
    tx.try_send(Ok(GenerationStreamEvent::Delta("first".to_owned())))
        .expect("channel has room for the first event");
    let context = OpenAiRequestContext::new();
    let rt = Runtime::new().expect("tokio runtime for double-wait test");
    // Inject a generous stall timeout so the short-circuit assertion has a wide
    // margin on a loaded CI runner: a terminal send that (wrongly) waited out
    // the stall again would take at least `stall_timeout`, while the correct
    // short-circuit is one atomic load. Deriving the bound from the timeout
    // instead of a fixed wall-clock number keeps the two coupled.
    let stall_timeout = Duration::from_millis(500);
    let sender = StreamEventSender::new(
        tx,
        rt.handle().clone(),
        stall_timeout,
        "test-request".to_owned(),
        test_telemetry(),
    );

    let stalled = sender.send(
        Ok(GenerationStreamEvent::Delta("second".to_owned())),
        &context,
    );
    assert!(
        stalled.is_err(),
        "the in-flight send must self-cancel once the receiver proves unreachable"
    );

    let started = Instant::now();
    let terminal = sender.send_terminal(Ok(GenerationStreamEvent::Done(FinishReason::Stop)));
    let elapsed = started.elapsed();

    assert!(
        terminal.is_err(),
        "a proven-unreachable receiver must not be handed a terminal frame either"
    );
    // The short-circuit must complete in a small fraction of the injected
    // stall timeout; a second wait would consume at least the whole timeout.
    assert!(
        elapsed < stall_timeout / 5,
        "terminal send must short-circuit instead of waiting out the stall timeout again, took {elapsed:?} (timeout {stall_timeout:?})"
    );
    drop(rx);
}

// --- Terminal-hook lifecycle wiring (mesh1437 production wiring) ---
//
// `chat_completion_with_hooks`/`chat_completion_stream_with_hooks` are unit
// tested directly with a fake `dispatch` closure rather than through the
// full `chat_completion_with_context`/`chat_completion_stream` trait methods:
// real generation needs a loaded GGUF (see `recurrent_test_backend` in
// `local_generation/tests.rs`, gated on `SKIPPY_RECURRENT_CACHE_TEST_MODEL`),
// but the hook lifecycle itself never touches `self.runtime` — it only reads
// `self.hook_policy` — so it's fully exercisable on a modelless backend.

fn hooks_test_backend(hook_policy: Option<Arc<dyn OpenAiHookPolicy>>) -> StageOpenAiBackend {
    let config: skippy_protocol::StageConfig = serde_json::from_value(json!({
        "run_id": "hooks-test",
        "topology_id": "hooks-test",
        "model_id": "hooks-test-model",
        "stage_id": "stage-0",
        "stage_index": 0,
        "layer_start": 0,
        "layer_end": 1,
        "load_mode": "runtime-slice",
        "bind_addr": "127.0.0.1:0",
    }))
    .expect("minimal stage config for hook lifecycle tests");
    let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(1)));
    let telemetry = crate::telemetry::Telemetry::new(
        None,
        1,
        config.clone(),
        crate::telemetry::TelemetryLevel::Off,
    );
    let iteration_scheduler =
        IterationScheduler::new(runtime.clone(), &config, 1, true, telemetry.clone())
            .expect("iteration scheduler for hook lifecycle tests");
    StageOpenAiBackend {
        runtime: runtime.clone(),
        config: config.clone(),
        telemetry,
        model_id: "hooks-test-model".to_string(),
        default_max_tokens: 16,
        request_defaults: EmbeddedOpenAiRequestDefaults::default(),
        ctx_size: 128,
        mode: OpenAiBackendMode::LocalRuntime,
        draft: None,
        speculative_window: 0,
        adaptive_speculative_window: false,
        ngram_max: 0,
        speculative: SpeculativeDecodeConfig::default(),
        generation_limit: Arc::new(GenerationConcurrencyController::fixed(1)),
        generation_queue_depth: Arc::new(AtomicUsize::new(0)),
        generation_queue_limit: 1,
        generation_admission_timeout: Duration::from_secs(10),
        generation_service_estimator: Arc::new(GenerationServiceEstimator::new(1)),
        generation_session_locks: Arc::new(Mutex::new(BTreeMap::new())),
        generation_token_budget: Arc::new(GenerationTokenBudget::new(128)),
        hook_policy,
        generation_receipt: None,
        linear_proposal_ingress: None,
        kv: None,
        iteration_scheduler,
    }
}

fn mesh_hooks_request(model: &str) -> ChatCompletionRequest {
    let mut request: ChatCompletionRequest = serde_json::from_value(json!({
        "model": model,
        "messages": [{"role": "user", "content": "hi"}],
    }))
    .expect("minimal chat completion request");
    set_chat_mesh_hooks_enabled(&mut request, true);
    request
}

#[derive(Debug, Clone, PartialEq)]
enum HookTerminalRecord {
    Success { model: String },
    Error { status: u16, message: String },
    Denied { status: u16, reason: String },
    Cancelled,
    StreamCompleted,
}

#[derive(Default)]
struct RecordingHookPolicy {
    deny: bool,
    hang_before_dispatch: bool,
    terminals: Mutex<Vec<HookTerminalRecord>>,
}

#[async_trait]
impl OpenAiHookPolicy for RecordingHookPolicy {
    async fn before_chat_completion(
        &self,
        _request: &mut ChatCompletionRequest,
    ) -> OpenAiResult<ChatHookOutcome> {
        if self.hang_before_dispatch {
            std::future::pending::<()>().await;
        }
        if self.deny {
            return Err(OpenAiError::invalid_request("denied by policy"));
        }
        Ok(ChatHookOutcome::none())
    }

    async fn on_chat_completion_terminal(
        &self,
        _request: &ChatCompletionRequest,
        _exchange_id: &str,
        outcome: &ChatCompletionOutcome<'_>,
    ) {
        let record = match outcome {
            ChatCompletionOutcome::Success { response } => HookTerminalRecord::Success {
                model: response.model.clone(),
            },
            ChatCompletionOutcome::Error { status, message } => HookTerminalRecord::Error {
                status: *status,
                message: (*message).to_string(),
            },
            ChatCompletionOutcome::Denied { status, reason } => HookTerminalRecord::Denied {
                status: *status,
                reason: (*reason).to_string(),
            },
            ChatCompletionOutcome::Cancelled => HookTerminalRecord::Cancelled,
            ChatCompletionOutcome::StreamCompleted => HookTerminalRecord::StreamCompleted,
            other => {
                unreachable!("unhandled ChatCompletionOutcome variant in test fixture: {other:?}")
            }
        };
        self.terminals.lock().unwrap().push(record);
    }
}

/// Terminal delivery for a dropped/streamed exchange fires from a detached
/// spawned task (see `TerminalGuard::drop`/`fire_detached`), so it lands
/// sometime after the driving future is aborted or the stream stops
/// yielding items, not synchronously at that instant.
async fn wait_for_hook_terminal(policy: &RecordingHookPolicy) {
    let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
    loop {
        if !policy.terminals.lock().unwrap().is_empty() {
            return;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "terminal event never fired"
        );
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
}

#[tokio::test]
async fn stage_backend_success_fires_terminal_exactly_once() {
    let policy = Arc::new(RecordingHookPolicy::default());
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");

    let response = backend
        .chat_completion_with_hooks(request, |request| async move {
            Ok(ChatCompletionResponse::new(
                request.model,
                "ok",
                Usage::new(1, 1),
            ))
        })
        .await
        .expect("fake dispatch succeeds");
    assert_eq!(response.model, "hooks-test-model");

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(
        terminals.as_slice(),
        [HookTerminalRecord::Success {
            model: "hooks-test-model".to_string()
        }]
    );
}

#[tokio::test]
async fn stage_backend_dispatch_error_fires_terminal_exactly_once() {
    let policy = Arc::new(RecordingHookPolicy::default());
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");

    let error = backend
        .chat_completion_with_hooks(request, |_request| async move {
            Err(OpenAiError::backend("upstream exploded"))
        })
        .await
        .expect_err("fake dispatch fails");
    assert_eq!(error.status().as_u16(), 502);

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(terminals.len(), 1);
    assert!(matches!(
        &terminals[0],
        HookTerminalRecord::Error { status: 502, message }
            if message.contains("upstream exploded")
    ));
}

#[tokio::test]
async fn stage_backend_denied_request_never_dispatches_and_fires_terminal_exactly_once() {
    let policy = Arc::new(RecordingHookPolicy {
        deny: true,
        ..RecordingHookPolicy::default()
    });
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");
    let dispatched = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let dispatched_flag = dispatched.clone();

    let error = backend
        .chat_completion_with_hooks(request, move |request| {
            dispatched_flag.store(true, Ordering::Release);
            async move {
                Ok(ChatCompletionResponse::new(
                    request.model,
                    "ok",
                    Usage::new(0, 0),
                ))
            }
        })
        .await
        .expect_err("policy denies the request");
    assert_eq!(error.status().as_u16(), 400);
    assert!(
        !dispatched.load(Ordering::Acquire),
        "a denied request must never reach dispatch"
    );

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(terminals.len(), 1);
    assert!(matches!(
        &terminals[0],
        HookTerminalRecord::Denied { status: 400, reason }
            if reason.contains("denied by policy")
    ));
}

#[tokio::test]
async fn stage_backend_dropped_during_admission_hook_fires_exactly_one_cancelled_terminal() {
    let policy = Arc::new(RecordingHookPolicy {
        hang_before_dispatch: true,
        ..RecordingHookPolicy::default()
    });
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");

    let handle = tokio::spawn(async move {
        backend
            .chat_completion_with_hooks(request, |request| async move {
                Ok(ChatCompletionResponse::new(
                    request.model,
                    "ok",
                    Usage::new(0, 0),
                ))
            })
            .await
    });

    // Let the task run until it's parked in `before_chat_completion`, then
    // cancel it the way an outer timeout or client disconnect would.
    tokio::task::yield_now().await;
    handle.abort();
    let _ = handle.await;
    wait_for_hook_terminal(&policy).await;

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(terminals.as_slice(), [HookTerminalRecord::Cancelled]);
}

#[tokio::test]
async fn stage_backend_stream_that_ends_normally_fires_stream_completed_terminal_exactly_once() {
    let policy = Arc::new(RecordingHookPolicy::default());
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");

    let mut stream = backend
        .chat_completion_stream_with_hooks(request, |request| async move {
            Ok(Box::pin(futures_util::stream::iter(vec![
                Ok(ChatCompletionChunk::delta(request.model.clone(), "hi")),
                Ok(ChatCompletionChunk::done(request.model)),
            ])) as ChatCompletionStream)
        })
        .await
        .expect("stream created");
    while stream
        .next()
        .await
        .transpose()
        .expect("no chunk errors")
        .is_some()
    {}
    wait_for_hook_terminal(&policy).await;

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(terminals.as_slice(), [HookTerminalRecord::StreamCompleted]);
}

/// The explicit case this wiring exists for: a client disconnects (or an
/// outer timeout fires) after a stream has already delivered a chunk but
/// before it ends on its own. Without `TerminalGuardedChatStream` wired into
/// `StageOpenAiBackend`, this exchange got zero terminal events.
#[tokio::test]
async fn stage_backend_stream_dropped_mid_stream_fires_exactly_one_cancelled_terminal() {
    let policy = Arc::new(RecordingHookPolicy::default());
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");

    let mut stream = backend
        .chat_completion_stream_with_hooks(request, |request| async move {
            let first = ChatCompletionChunk::delta(request.model, "partial");
            Ok(Box::pin(
                futures_util::stream::once(async move { Ok(first) })
                    .chain(futures_util::stream::pending()),
            ) as ChatCompletionStream)
        })
        .await
        .expect("stream created");
    let first = stream.next().await;
    assert!(matches!(first, Some(Ok(_))), "first chunk should flow");
    drop(stream);
    wait_for_hook_terminal(&policy).await;

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(terminals.as_slice(), [HookTerminalRecord::Cancelled]);
}

#[tokio::test]
async fn stage_backend_stream_error_chunk_fires_error_terminal_exactly_once() {
    let policy = Arc::new(RecordingHookPolicy::default());
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");

    let mut stream = backend
        .chat_completion_stream_with_hooks(request, |request| async move {
            Ok(Box::pin(futures_util::stream::iter(vec![
                Ok(ChatCompletionChunk::delta(request.model, "hi")),
                Err(OpenAiError::backend("upstream exploded")),
            ])) as ChatCompletionStream)
        })
        .await
        .expect("stream created");
    while let Some(item) = stream.next().await {
        let _ = item;
    }
    wait_for_hook_terminal(&policy).await;

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(terminals.len(), 1);
    assert!(matches!(
        &terminals[0],
        HookTerminalRecord::Error { status: 502, message }
            if message.contains("upstream exploded")
    ));
}

#[tokio::test]
async fn stage_backend_stream_denied_never_dispatches_and_fires_terminal_exactly_once() {
    let policy = Arc::new(RecordingHookPolicy {
        deny: true,
        ..RecordingHookPolicy::default()
    });
    let backend = hooks_test_backend(Some(policy.clone()));
    let request = mesh_hooks_request("hooks-test-model");

    let error = match backend
        .chat_completion_stream_with_hooks(request, |_request| async move {
            panic!("a denied request must never reach dispatch")
        })
        .await
    {
        Ok(_) => panic!("policy denies the request"),
        Err(error) => error,
    };
    assert_eq!(error.status().as_u16(), 400);

    let terminals = policy.terminals.lock().unwrap();
    assert_eq!(terminals.len(), 1);
    assert!(matches!(
        &terminals[0],
        HookTerminalRecord::Denied { status: 400, reason }
            if reason.contains("denied by policy")
    ));
}