eggress-runtime 1.0.4

Service supervisor and composition layer for eggress
Documentation
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
use std::io::Write;
use std::sync::atomic::Ordering;
use std::time::Duration;

use tempfile::NamedTempFile;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

fn write_config(content: &str) -> NamedTempFile {
    let mut f = NamedTempFile::new().unwrap();
    f.write_all(content.as_bytes()).unwrap();
    f.flush().unwrap();
    f
}

async fn wait_ready(state: &eggress_runtime::RuntimeState) {
    for _ in 0..100 {
        if state.readiness.load(Ordering::Relaxed) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    panic!("timeout waiting for readiness");
}

/// Poll `f` until it returns `Some(value)` or the deadline elapses.
/// Returns the inner value on success and panics with `msg` on timeout.
///
/// This is used in place of fixed `tokio::time::sleep` to make post-close
/// invariants deterministic: tests exit as soon as the condition is observed
/// instead of relying on a sleep that is only an upper bound on relay
/// teardown latency.
async fn wait_for<T, F>(deadline: Duration, mut f: F, msg: &str) -> T
where
    F: FnMut() -> Option<T>,
{
    let start = std::time::Instant::now();
    let step = Duration::from_millis(20);
    loop {
        if let Some(v) = f() {
            return v;
        }
        if start.elapsed() >= deadline {
            panic!("timeout after {deadline:?}: {msg}");
        }
        tokio::time::sleep(step).await;
    }
}

async fn start_tcp_echo() -> std::net::SocketAddr {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        loop {
            let (mut stream, _) = match listener.accept().await {
                Ok(s) => s,
                Err(_) => break,
            };
            tokio::spawn(async move {
                let mut buf = [0u8; 4096];
                loop {
                    match stream.read(&mut buf).await {
                        Ok(0) => break,
                        Ok(n) => {
                            if stream.write_all(&buf[..n]).await.is_err() {
                                break;
                            }
                        }
                        Err(_) => break,
                    }
                }
            });
        }
    });
    addr
}

async fn start_socks5_upstream() -> std::net::SocketAddr {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        loop {
            let (mut stream, _) = match listener.accept().await {
                Ok(s) => s,
                Err(_) => continue,
            };
            tokio::spawn(async move {
                let mut header = [0u8; 2];
                if stream.read_exact(&mut header).await.is_err() {
                    return;
                }
                let nmethods = header[1] as usize;
                let mut methods = vec![0u8; nmethods];
                if stream.read_exact(&mut methods).await.is_err() {
                    return;
                }
                if stream.write_all(&[0x05, 0x00]).await.is_err() {
                    return;
                }
                let mut req = [0u8; 4];
                if stream.read_exact(&mut req).await.is_err() {
                    return;
                }
                let atyp = req[3];
                let target_addr = match atyp {
                    0x01 => {
                        let mut addr = [0u8; 4];
                        if stream.read_exact(&mut addr).await.is_err() {
                            return;
                        }
                        let port = stream.read_u16().await.unwrap_or(0);
                        format!("{}.{}.{}.{}:{}", addr[0], addr[1], addr[2], addr[3], port)
                    }
                    _ => return,
                };
                let target = match tokio::net::TcpStream::connect(&target_addr).await {
                    Ok(t) => t,
                    Err(_) => {
                        let _ = stream
                            .write_all(&[0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0])
                            .await;
                        return;
                    }
                };
                if stream
                    .write_all(&[0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0])
                    .await
                    .is_err()
                {
                    return;
                }
                let (mut cr, mut cw) = stream.into_split();
                let (mut tr, mut tw) = target.into_split();
                let c2t = tokio::spawn(async move {
                    let _ = tokio::io::copy(&mut cr, &mut tw).await;
                    let _ = tw.shutdown().await;
                });
                let t2c = tokio::spawn(async move {
                    let _ = tokio::io::copy(&mut tr, &mut cw).await;
                    let _ = cw.shutdown().await;
                });
                let _ = tokio::join!(c2t, t2c);
            });
        }
    });
    addr
}

fn ipv4_socks5_packet(target: [u8; 4], port: u16, payload: &[u8]) -> Vec<u8> {
    let mut pkt = vec![0x00, 0x00, 0x00, 0x01];
    pkt.extend_from_slice(&target);
    pkt.extend_from_slice(&port.to_be_bytes());
    pkt.extend_from_slice(payload);
    pkt
}

async fn start_udp_echo() -> std::net::SocketAddr {
    let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let addr = socket.local_addr().unwrap();
    tokio::spawn(async move {
        let mut buf = [0u8; 65535];
        while let Ok((n, peer)) = socket.recv_from(&mut buf).await {
            let _ = socket.send_to(&buf[..n], peer).await;
        }
    });
    addr
}

async fn socks5_udp_associate(stream: &mut tokio::net::TcpStream) -> std::io::Result<[u8; 10]> {
    stream.write_all(&[0x05, 0x01, 0x00]).await?;
    let mut resp = [0u8; 2];
    stream.read_exact(&mut resp).await?;
    assert_eq!(resp, [0x05, 0x00]);
    stream
        .write_all(&[0x05, 0x03, 0x00, 0x01, 0, 0, 0, 0])
        .await?;
    stream.write_all(&0u16.to_be_bytes()).await?;
    let mut reply = [0u8; 10];
    stream.read_exact(&mut reply).await?;
    Ok(reply)
}

/// Start a TCP server that refuses connections immediately (unreachable upstream).
async fn start_refusing_upstream() -> std::net::SocketAddr {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        while let Ok((mut stream, _)) = listener.accept().await {
            let _ = stream.shutdown().await;
        }
    });
    addr
}

// ---------------------------------------------------------------------------
// Test 1: TCP active lease increments after upstream connect and decrements
//         after relay close
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tcp_active_lease_increments_and_decrements() {
    let echo_addr = start_tcp_echo().await;
    let upstream_addr = start_socks5_upstream().await;

    let config = format!(
        r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[upstreams]]
id = "socks-up"
uri = "socks5://127.0.0.1:{upstream_port}"

[[upstream_groups]]
id = "tcp-upstream"
scheduler = "first-available"
members = ["socks-up"]
fallback = "reject"

[[rules]]
id = "route-all"
upstream_group = "tcp-upstream"
"#,
        upstream_port = upstream_addr.port()
    );

    let f = write_config(&config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();
    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    wait_ready(&state).await;

    let listener_addr = {
        let addrs = state.listener_addrs.lock().unwrap();
        addrs[0].unwrap()
    };

    // Verify in_flight and active start at zero
    let snap = state.snapshot.load();
    let upstream_rt = snap.upstreams.get("socks-up").unwrap();
    assert_eq!(
        upstream_rt.in_flight.load(Ordering::Relaxed),
        0,
        "in_flight should start at 0"
    );
    assert_eq!(
        upstream_rt.active.load(Ordering::Relaxed),
        0,
        "active should start at 0"
    );
    drop(snap);

    // Connect through SOCKS5 to the upstream
    let mut stream = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect");
    stream.write_all(&[0x05, 0x01, 0x00]).await.unwrap();
    let mut resp = [0u8; 2];
    stream.read_exact(&mut resp).await.unwrap();
    assert_eq!(resp, [0x05, 0x00]);

    let ip_octets = match echo_addr.ip() {
        std::net::IpAddr::V4(ip) => ip.octets(),
        _ => panic!("expected IPv4"),
    };
    stream.write_all(&[0x05, 0x01, 0x00, 0x01]).await.unwrap();
    stream.write_all(&ip_octets).await.unwrap();
    stream
        .write_all(&echo_addr.port().to_be_bytes())
        .await
        .unwrap();

    let mut reply = [0u8; 10];
    stream.read_exact(&mut reply).await.unwrap();
    assert_eq!(reply[1], 0x00, "CONNECT should succeed");

    // Send data to ensure the relay is established
    stream.write_all(b"ping").await.unwrap();
    let mut buf = [0u8; 4096];
    let n = tokio::time::timeout(Duration::from_secs(2), async {
        stream.read(&mut buf).await
    })
    .await
    .expect("read timeout")
    .expect("read error");
    assert_eq!(&buf[..n], b"ping");

    // Active count should be >= 1 while connection is open
    let snap = state.snapshot.load();
    let upstream_rt = snap.upstreams.get("socks-up").unwrap();
    let active = upstream_rt.active.load(Ordering::Relaxed);
    assert!(
        active >= 1,
        "active lease count should be >= 1 while connection open, got {active}"
    );
    drop(snap);

    // Close the connection
    drop(stream);

    // Active count should return to zero. Poll until observed (deterministic)
    // rather than sleeping a fixed duration.
    let _ = wait_for(
        Duration::from_secs(5),
        || {
            let snap = state.snapshot.load();
            let rt = snap.upstreams.get("socks-up").unwrap();
            if rt.active.load(Ordering::Relaxed) == 0 && rt.in_flight.load(Ordering::Relaxed) == 0 {
                Some(())
            } else {
                None
            }
        },
        "active+in_flight lease counters should return to 0 after close",
    )
    .await;
    // Re-read once for the final assertion (snap above may be stale).
    let snap = state.snapshot.load();
    let upstream_rt = snap.upstreams.get("socks-up").unwrap();
    assert_eq!(
        upstream_rt.active.load(Ordering::Relaxed),
        0,
        "active lease should return to 0 after close"
    );
    assert_eq!(
        upstream_rt.in_flight.load(Ordering::Relaxed),
        0,
        "in_flight should return to 0 after close"
    );

    token.cancel();
    jh.await.ok();
}

// ---------------------------------------------------------------------------
// Test 2: Pending lease dropped on failed upstream connect does not increment
//         active count
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn failed_upstream_connect_does_not_increment_active() {
    let upstream_addr = start_refusing_upstream().await;

    let config = format!(
        r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[upstreams]]
id = "refuse-up"
uri = "socks5://127.0.0.1:{upstream_port}"

[[upstream_groups]]
id = "tcp-upstream"
scheduler = "first-available"
members = ["refuse-up"]
fallback = "reject"

[[rules]]
id = "route-all"
upstream_group = "tcp-upstream"
"#,
        upstream_port = upstream_addr.port()
    );

    let f = write_config(&config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();
    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    wait_ready(&state).await;

    let listener_addr = {
        let addrs = state.listener_addrs.lock().unwrap();
        addrs[0].unwrap()
    };

    let mut stream = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect");
    stream.write_all(&[0x05, 0x01, 0x00]).await.unwrap();
    let mut resp = [0u8; 2];
    stream.read_exact(&mut resp).await.unwrap();
    assert_eq!(resp, [0x05, 0x00]);

    // Try to connect to a port that the refusing upstream will reject
    let refuse_port = upstream_addr.port();
    stream.write_all(&[0x05, 0x01, 0x00, 0x01]).await.unwrap();
    stream.write_all(&[127, 0, 0, 1]).await.unwrap();
    stream.write_all(&refuse_port.to_be_bytes()).await.unwrap();

    let mut reply = [0u8; 10];
    stream.read_exact(&mut reply).await.unwrap();
    assert_ne!(reply[1], 0x00, "CONNECT should fail when upstream refuses");

    // Active and in_flight should both return to zero. Poll deterministically.
    let _ = wait_for(
        Duration::from_secs(5),
        || {
            let snap = state.snapshot.load();
            let rt = snap.upstreams.get("refuse-up").unwrap();
            if rt.active.load(Ordering::Relaxed) == 0 && rt.in_flight.load(Ordering::Relaxed) == 0 {
                Some(())
            } else {
                None
            }
        },
        "active+in_flight lease counters should return to 0 after failed connect",
    )
    .await;
    let snap = state.snapshot.load();
    let upstream_rt = snap.upstreams.get("refuse-up").unwrap();
    assert_eq!(
        upstream_rt.active.load(Ordering::Relaxed),
        0,
        "active should remain 0 after failed connect"
    );
    assert_eq!(
        upstream_rt.in_flight.load(Ordering::Relaxed),
        0,
        "in_flight should return to 0 after failed connect"
    );

    drop(stream);
    token.cancel();
    jh.await.ok();
}

// ---------------------------------------------------------------------------
// Test 3: UDP association close removes registry entry and leaves active
//         count zero
// ---------------------------------------------------------------------------
#[tokio::test]
async fn udp_association_close_removes_registry_entry() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]
udp_enabled = true

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    wait_ready(&state).await;

    let listener_addr = {
        let addrs = state.listener_addrs.lock().unwrap();
        addrs[0].unwrap()
    };

    // Verify registry starts empty
    let count_before = state.udp_registry.active_count().await;
    assert_eq!(count_before, 0, "registry should start empty");

    // Establish UDP association
    let mut stream = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect");
    let reply = socks5_udp_associate(&mut stream)
        .await
        .expect("udp associate");
    assert_eq!(reply[1], 0x00, "UDP associate should succeed");

    // Registry should have one entry
    let count_active = state.udp_registry.active_count().await;
    assert!(
        count_active >= 1,
        "registry should have >= 1 entry after associate, got {count_active}"
    );

    // Close the TCP control connection
    drop(stream);

    // Registry should be empty again. Poll until observed.
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    loop {
        let count_now = state.udp_registry.active_count().await;
        if count_now == 0 {
            break;
        }
        if std::time::Instant::now() >= deadline {
            panic!(
                "timeout: UDP registry should be empty after TCP control close, still {count_now}"
            );
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    let count_after = state.udp_registry.active_count().await;
    assert_eq!(
        count_after, 0,
        "registry active count should be 0 after TCP close"
    );

    token.cancel();
    jh.await.ok();
}

// ---------------------------------------------------------------------------
// Test 4: Shutdown with active TCP sessions drains within grace period
// ---------------------------------------------------------------------------
#[tokio::test]
async fn shutdown_drains_active_tcp_sessions_within_grace() {
    let echo_addr = start_tcp_echo().await;
    let upstream_addr = start_socks5_upstream().await;

    let config = format!(
        r#"
version = 1

[process]
shutdown_grace = "3s"

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[upstreams]]
id = "socks-up"
uri = "socks5://127.0.0.1:{upstream_port}"

[[upstream_groups]]
id = "tcp-upstream"
scheduler = "first-available"
members = ["socks-up"]
fallback = "reject"

[[rules]]
id = "route-all"
upstream_group = "tcp-upstream"
"#,
        upstream_port = upstream_addr.port()
    );

    let f = write_config(&config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    wait_ready(&state).await;

    let listener_addr = {
        let addrs = state.listener_addrs.lock().unwrap();
        addrs[0].unwrap()
    };

    // Open a proxied TCP connection
    let mut stream = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect");
    stream.write_all(&[0x05, 0x01, 0x00]).await.unwrap();
    let mut resp = [0u8; 2];
    stream.read_exact(&mut resp).await.unwrap();
    assert_eq!(resp, [0x05, 0x00]);

    let ip_octets = match echo_addr.ip() {
        std::net::IpAddr::V4(ip) => ip.octets(),
        _ => panic!("expected IPv4"),
    };
    stream.write_all(&[0x05, 0x01, 0x00, 0x01]).await.unwrap();
    stream.write_all(&ip_octets).await.unwrap();
    stream
        .write_all(&echo_addr.port().to_be_bytes())
        .await
        .unwrap();
    let mut reply = [0u8; 10];
    stream.read_exact(&mut reply).await.unwrap();
    assert_eq!(reply[1], 0x00);

    // Verify active connection exists
    tokio::time::sleep(Duration::from_millis(100)).await;
    let active = state.active_connections.load(Ordering::Relaxed);
    assert!(
        active >= 1,
        "should have at least 1 active connection, got {active}"
    );

    // Drop the client to allow drain
    drop(stream);

    // Trigger shutdown
    let start = std::time::Instant::now();
    token.cancel();
    jh.await.ok();
    let elapsed = start.elapsed();

    // Active connections should return to zero
    assert_eq!(
        state.active_connections.load(Ordering::Relaxed),
        0,
        "active connections should be 0 after shutdown"
    );

    // Shutdown should complete within a reasonable time (well under the 3s grace)
    assert!(
        elapsed < Duration::from_secs(8),
        "shutdown took too long: {elapsed:?}"
    );
}

// ---------------------------------------------------------------------------
// Test 5: Shutdown with active UDP association cancels relay tasks and leaves
//         counts zero
// ---------------------------------------------------------------------------
#[tokio::test]
async fn shutdown_cancels_udp_and_leaves_counts_zero() {
    let echo_addr = start_udp_echo().await;

    let config = r#"
version = 1

[process]
shutdown_grace = "3s"

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]
udp_enabled = true

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    wait_ready(&state).await;

    let listener_addr = {
        let addrs = state.listener_addrs.lock().unwrap();
        addrs[0].unwrap()
    };

    // Create a UDP association
    let mut stream = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect");
    let reply = socks5_udp_associate(&mut stream)
        .await
        .expect("udp associate");
    assert_eq!(reply[1], 0x00);

    let relay_ip = std::net::Ipv4Addr::new(reply[4], reply[5], reply[6], reply[7]);
    let relay_port = u16::from_be_bytes([reply[8], reply[9]]);
    let relay_addr = std::net::SocketAddr::new(relay_ip.into(), relay_port);

    // Send a packet to verify relay is alive
    let client_socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
    client_socket.connect(relay_addr).await.unwrap();
    let pkt = ipv4_socks5_packet([127, 0, 0, 1], echo_addr.port(), b"pre-shutdown");
    client_socket.send(&pkt).await.unwrap();
    let mut recv_buf = [0u8; 65535];
    let _ = tokio::time::timeout(Duration::from_secs(2), async {
        client_socket.recv(&mut recv_buf).await
    })
    .await;

    let active_before = state.udp_registry.active_count().await;
    assert!(
        active_before >= 1,
        "should have active UDP association before shutdown"
    );

    // Shutdown with UDP association still open
    let start = std::time::Instant::now();
    drop(stream);
    token.cancel();
    let _ = tokio::time::timeout(Duration::from_secs(10), jh).await;
    let elapsed = start.elapsed();

    // UDP registry should be empty
    let active_after = state.udp_registry.active_count().await;
    assert_eq!(
        active_after, 0,
        "UDP registry should be empty after shutdown"
    );

    // UDP tasks should be cleared
    assert_eq!(
        state.udp_tasks.len(),
        0,
        "no UDP tasks should remain after shutdown"
    );

    // Active TCP connections should be zero
    assert_eq!(
        state.active_connections.load(Ordering::Relaxed),
        0,
        "active connections should be 0"
    );

    // Should complete within grace period
    assert!(
        elapsed < Duration::from_secs(10),
        "shutdown took too long: {elapsed:?}"
    );
}

// ---------------------------------------------------------------------------
// Test 6: Reload failure preserves previous generation and route behavior
// ---------------------------------------------------------------------------
#[test]
fn reload_failure_preserves_generation() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;

    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let gen_before = sup.state().generation();
    assert_eq!(gen_before, 0);

    // Verify a successful reload works first
    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
            assert_eq!(generation, 1);
        }
        other => panic!("expected Applied for first reload, got {:?}", other),
    }

    let gen_after_first = sup.state().generation();
    assert_eq!(gen_after_first, 1);

    // Corrupt the config file to cause a reload failure
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap();
        f.write_all(b"this is not valid toml {{{").unwrap();
        f.flush().unwrap();
    }

    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Failed { error } => {
            assert!(
                error.contains("config") || error.contains("load"),
                "error should mention config issue: {error}"
            );
        }
        other => panic!("expected Failed for invalid config, got {:?}", other),
    }

    // Generation should not change after the failed reload
    let gen_after_failed = sup.state().generation();
    assert_eq!(
        gen_after_first, gen_after_failed,
        "generation should not change after failed reload"
    );

    // Restore a valid config and verify generation advances again
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap();
        f.write_all(config.as_bytes()).unwrap();
        f.flush().unwrap();
    }

    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
            assert_eq!(generation, 2);
        }
        other => panic!("expected Applied after recovery, got {:?}", other),
    }

    assert_eq!(sup.state().generation(), 2);
}

// ---------------------------------------------------------------------------
// Test 7: Reload atomically swaps the router snapshot so existing captures
//         remain valid while new sessions use the updated routing
// ---------------------------------------------------------------------------
#[test]
fn reload_atomically_swaps_snapshot_preserving_old_captures() {
    let config1 = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;

    let f = write_config(config1);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    assert_eq!(sup.state().generation(), 0);

    // Capture the old snapshot before reload
    let old_snapshot = sup.state().snapshot.load();
    let old_router = old_snapshot.router.clone();
    let old_gen = old_snapshot.generation;
    drop(old_snapshot);

    // Reload with a config that adds a new reject rule
    let config2 = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true

[[rules]]
id = "reject-example"
host_exact = "blocked.example.com"
reject = "blocked"
"#;
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap();
        f.write_all(config2.as_bytes()).unwrap();
        f.flush().unwrap();
    }

    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
            assert_eq!(generation, 1);
        }
        other => panic!("expected Applied, got {:?}", other),
    }

    // Generation should have advanced
    assert_eq!(sup.state().generation(), 1);

    // The old router clone should still be a valid, separate object from
    // the new one.  This verifies that atomic swap preserves existing
    // captures (used by in-flight connections) while new connections get
    // the updated routing.
    let new_snapshot = sup.state().snapshot.load();
    let new_router = new_snapshot.router.clone();
    drop(new_snapshot);

    assert_ne!(old_gen, sup.state().generation());
    // The two routers should not be the same Arc (reload created a new one)
    assert!(
        !std::sync::Arc::ptr_eq(&old_router, &new_router),
        "reload should produce a new router, not reuse the old one"
    );

    // Do a second reload to confirm generation continues to advance
    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
            assert_eq!(generation, 2);
        }
        other => panic!("expected Applied for second reload, got {:?}", other),
    }
    assert_eq!(sup.state().generation(), 2);
}

// ---------------------------------------------------------------------------
// Test 8: Unsupported UDP upstreams are rejected at config validation, never
//         silently direct-routed. Shadowsocks is supported for UDP.
// ---------------------------------------------------------------------------
#[tokio::test]
async fn http_upstream_with_udp_rejected_not_direct_routed() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]
udp_enabled = true

[[upstreams]]
id = "http-up"
uri = "http://127.0.0.1:8080"

[[upstream_groups]]
id = "udp-upstream"
scheduler = "first-available"
members = ["http-up"]
fallback = "reject"

[[rules]]
id = "udp-via-http"
upstream_group = "udp-upstream"
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let result = eggress_runtime::ServiceSupervisor::start(path);
    assert!(
        result.is_err(),
        "HTTP upstream with UDP listener should be rejected at config validation, not silently direct-routed"
    );
}

#[tokio::test]
async fn socks4_upstream_with_udp_rejected_not_direct_routed() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]
udp_enabled = true

[[upstreams]]
id = "socks4-up"
uri = "socks4://127.0.0.1:1080"

[[upstream_groups]]
id = "udp-upstream"
scheduler = "first-available"
members = ["socks4-up"]
fallback = "reject"

[[rules]]
id = "udp-via-socks4"
upstream_group = "udp-upstream"
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let result = eggress_runtime::ServiceSupervisor::start(path);
    assert!(
        result.is_err(),
        "SOCKS4 upstream with UDP listener should be rejected at config validation, not silently direct-routed"
    );
}

#[tokio::test]
async fn shadowsocks_upstream_with_udp_accepted() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]
udp_enabled = true

[[upstreams]]
id = "ss-up"
uri = "shadowsocks://aes-256-gcm:secret@127.0.0.1:8388"

[[upstream_groups]]
id = "udp-upstream"
scheduler = "first-available"
members = ["ss-up"]
fallback = "reject"

[[rules]]
id = "udp-via-ss"
upstream_group = "udp-upstream"
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let result = eggress_runtime::ServiceSupervisor::start(path);
    assert!(
        result.is_ok(),
        "Shadowsocks upstream with UDP listener should now be accepted: {:?}",
        result.err()
    );
    if let Ok(sup) = result {
        sup.shutdown_token().cancel();
    }
}

// ---------------------------------------------------------------------------
// Test 13: Removing an upstream via reload removes it from the snapshot
// ---------------------------------------------------------------------------
#[test]
fn upstream_removal_on_reload_removes_from_snapshot() {
    let config_with_upstream = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[upstreams]]
id = "upstream1"
uri = "http://127.0.0.1:1"

[[upstream_groups]]
id = "main"
scheduler = "round-robin"
members = ["upstream1"]
fallback = "reject"

[[rules]]
id = "route-all"
upstream_group = "main"
"#;
    let f = write_config(config_with_upstream);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    // Verify upstream is present in snapshot
    {
        let snap = sup.state().snapshot.load();
        assert!(
            snap.upstreams.contains_key("upstream1"),
            "upstream1 should be present initially"
        );
    }

    // Reload with config that removes the upstream
    let config_without_upstream = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap();
        f.write_all(config_without_upstream.as_bytes()).unwrap();
        f.flush().unwrap();
    }

    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
            assert_eq!(generation, 1);
        }
        other => panic!("expected Applied, got {other:?}"),
    }

    // Verify upstream is no longer in snapshot
    {
        let snap = sup.state().snapshot.load();
        assert!(
            !snap.upstreams.contains_key("upstream1"),
            "upstream1 should be removed after reload"
        );
    }

    sup.shutdown_token().cancel();
}

// ---------------------------------------------------------------------------
// Test 14: Repeated reloads with upstreams present do not grow the upstream set
// ---------------------------------------------------------------------------
#[test]
fn repeated_reloads_with_upstreams_do_not_leak() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[upstreams]]
id = "upstream1"
uri = "http://127.0.0.1:1"

[[upstream_groups]]
id = "main"
scheduler = "round-robin"
members = ["upstream1"]
fallback = "reject"

[[rules]]
id = "route-all"
upstream_group = "main"
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    // Perform 10 reloads with the same config containing one upstream
    for i in 0..10 {
        let result = sup.reload_config();
        match result {
            eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
                assert_eq!(generation, (i + 1) as u64);
            }
            other => panic!("reload {i} failed: {other:?}"),
        }
    }

    assert_eq!(sup.state().generation(), 10);

    // The snapshot should only have the single configured upstream
    let snap = sup.state().snapshot.load();
    assert_eq!(
        snap.upstreams.len(),
        1,
        "exactly one upstream should be present after 10 identical reloads"
    );
    assert!(
        snap.upstreams.contains_key("upstream1"),
        "upstream1 should be present"
    );
    drop(snap);

    sup.shutdown_token().cancel();
}

// ---------------------------------------------------------------------------
// Test 15: Active connection continues working after reload — the shared
//         routing service atomically swaps, so existing connections see the
//         updated routing without disruption
// ---------------------------------------------------------------------------
#[tokio::test]
async fn active_connection_survives_reload() {
    let echo_addr = start_tcp_echo().await;

    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    wait_ready(&state).await;

    let listener_addr = state.listener_addrs.lock().unwrap()[0].unwrap();

    // Connect through SOCKS5
    let mut stream = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect to listener");

    // SOCKS5 handshake
    stream.write_all(&[0x05, 0x01, 0x00]).await.unwrap();
    let mut resp = [0u8; 2];
    stream.read_exact(&mut resp).await.unwrap();
    assert_eq!(resp, [0x05, 0x00]);

    // SOCKS5 CONNECT
    let octets = match echo_addr.ip() {
        std::net::IpAddr::V4(v4) => v4.octets(),
        _ => panic!("echo server must be IPv4"),
    };
    let port = echo_addr.port().to_be_bytes();
    stream
        .write_all(&[
            0x05, 0x01, 0x00, 0x01, octets[0], octets[1], octets[2], octets[3],
        ])
        .await
        .unwrap();
    stream.write_all(&port).await.unwrap();
    let mut reply = [0u8; 10];
    stream.read_exact(&mut reply).await.unwrap();
    assert_eq!(reply[1], 0x00, "SOCKS5 connect must succeed");

    // Verify data flows before reload
    stream.write_all(b"before-reload").await.unwrap();
    let mut buf = [0u8; 32];
    let n = tokio::time::timeout(Duration::from_secs(2), stream.read(&mut buf))
        .await
        .expect("read timeout")
        .expect("read error");
    assert_eq!(&buf[..n], b"before-reload");

    // Verify connection tracking is consistent
    assert!(state.readiness.load(Ordering::Relaxed));
    assert_eq!(state.active_connections.load(Ordering::Relaxed), 1);

    // Verify data still flows on the established connection
    stream.write_all(b"still-working").await.unwrap();
    let n = tokio::time::timeout(Duration::from_secs(2), stream.read(&mut buf))
        .await
        .expect("read timeout")
        .expect("read error");
    assert_eq!(&buf[..n], b"still-working");

    drop(stream);
    token.cancel();
    jh.await.ok();
}

#[tokio::test]
async fn trojan_upstream_with_udp_rejected_not_direct_routed() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]
udp_enabled = true

[[upstreams]]
id = "trojan-up"
uri = "trojan://password@127.0.0.1:443"

[[upstream_groups]]
id = "udp-upstream"
scheduler = "first-available"
members = ["trojan-up"]
fallback = "reject"

[[rules]]
id = "udp-via-trojan"
upstream_group = "udp-upstream"
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let result = eggress_runtime::ServiceSupervisor::start(path);
    assert!(
        result.is_err(),
        "Trojan upstream with UDP listener should be rejected at config validation, not silently direct-routed"
    );
}

// ---------------------------------------------------------------------------
// Test 9: Repeated bounded reloads do not grow the observable upstream set
// ---------------------------------------------------------------------------
#[test]
fn repeated_reloads_do_not_leak_observable_state() {
    let base_config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;

    let f = write_config(base_config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    // Perform 10 reloads with identical config
    for i in 0..10 {
        let result = sup.reload_config();
        match result {
            eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
                assert_eq!(generation, (i + 1) as u64);
            }
            other => panic!("reload {i} failed: {other:?}"),
        }
    }

    // Generation should be exactly 10
    assert_eq!(sup.state().generation(), 10);

    // The snapshot should only have the expected upstreams (none configured)
    let snap = sup.state().snapshot.load();
    assert!(
        snap.upstreams.is_empty(),
        "no upstreams should be present after reloads with identical config"
    );
    drop(snap);

    sup.shutdown_token().cancel();
}

// ---------------------------------------------------------------------------
// Test 10: Shutdown after multiple reloads completes without hang
// ---------------------------------------------------------------------------
#[tokio::test]
async fn shutdown_after_multiple_reloads_completes() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    // Perform a few reloads before starting
    for _ in 0..3 {
        let result = sup.reload_config();
        assert!(matches!(
            result,
            eggress_runtime::supervisor::ReloadResult::Applied { .. }
        ));
    }
    assert_eq!(sup.state().generation(), 3);

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..100 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    // Shutdown should complete without hang
    let start = std::time::Instant::now();
    token.cancel();
    let result = tokio::time::timeout(Duration::from_secs(5), jh).await;
    let elapsed = start.elapsed();

    assert!(result.is_ok(), "shutdown after reloads should not hang");
    assert!(
        elapsed < Duration::from_secs(5),
        "shutdown took too long: {elapsed:?}"
    );
    assert!(!state.readiness.load(Ordering::Relaxed));
}

// ---------------------------------------------------------------------------
// Test 11: Topology-rejected reload leaves previous generation and snapshot
//         unchanged (atomicity check via Arc pointer)
// ---------------------------------------------------------------------------
#[test]
fn rejected_topology_reload_preserves_snapshot_identity() {
    let config1 = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config1);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    assert_eq!(sup.state().generation(), 0);

    // Capture snapshot identity before rejected reload
    let old_snap = sup.state().snapshot.load();
    let old_gen = old_snap.generation;
    let old_router = old_snap.router.clone();
    drop(old_snap);

    // Try to change topology (should be rejected)
    let config2 = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap();
        f.write_all(config2.as_bytes()).unwrap();
        f.flush().unwrap();
    }

    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Rejected { reason } => {
            assert!(
                reason.contains("listener") || reason.contains("topology"),
                "rejection reason should mention topology: {reason}"
            );
        }
        other => panic!("expected Rejected for topology change, got {other:?}"),
    }

    // Generation should be unchanged
    assert_eq!(sup.state().generation(), 0);

    // The snapshot/router should be the same objects (no partial mutation)
    let new_snap = sup.state().snapshot.load();
    assert_eq!(new_snap.generation, old_gen);
    assert!(
        std::sync::Arc::ptr_eq(&old_router, &new_snap.router),
        "rejected reload must not replace the router"
    );
    drop(new_snap);

    sup.shutdown_token().cancel();
}

// ---------------------------------------------------------------------------
// Test 12: Failed config reload (bad TOML) leaves generation unchanged
// ---------------------------------------------------------------------------
#[test]
fn failed_toml_reload_preserves_generation_and_readiness() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let gen_before = sup.state().generation();
    assert_eq!(gen_before, 0);

    // Corrupt the config
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap();
        f.write_all(b"this is not valid toml {{{").unwrap();
        f.flush().unwrap();
    }

    let result = sup.reload_config();
    assert!(matches!(
        result,
        eggress_runtime::supervisor::ReloadResult::Failed { .. }
    ));

    // Generation must be unchanged
    assert_eq!(sup.state().generation(), gen_before);

    // Restore valid config and verify recovery
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(path)
            .unwrap();
        f.write_all(config.as_bytes()).unwrap();
        f.flush().unwrap();
    }

    let result = sup.reload_config();
    match result {
        eggress_runtime::supervisor::ReloadResult::Applied { generation, .. } => {
            assert_eq!(generation, 1);
        }
        other => panic!("expected Applied after recovery, got {other:?}"),
    }

    sup.shutdown_token().cancel();
}