fn0 0.1.0

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

type CodeId = u128;
type NodeId = u128;

struct WarmUpMapNode {
    map: RwLock<BTreeMap<CodeId, BTreeSet<NodePresence>>>,
    event_queue: RwLock<BTreeMap<CodeId, BTreeSet<NodePresence>>>,
}

#[derive(Clone, Debug)]
struct NodePresence {
    id: NodeId,
    addr: Ipv4Addr,
    updated_at: u64,
    is_alive: bool,
}
impl PartialEq for NodePresence {
    fn eq(&self, other: &Self) -> bool {
        self.addr == other.addr
    }
}
impl Eq for NodePresence {}
impl PartialOrd for NodePresence {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for NodePresence {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.addr.cmp(&other.addr)
    }
}

impl EventDelegate for WarmUpMapNode {
    type Id = NodeId;
    type Address = Ipv4Addr;

    async fn notify_join(&self, node: Arc<NodeState<Self::Id, Self::Address>>) {
        let mut map = self.map.write().await;
        let id = node.id;
        let addr = node.addr;
        for set in map.values_mut() {
            set.retain(|node| !(node.addr == addr && node.id != id));
        }
    }
    async fn notify_update(&self, _node: Arc<NodeState<Self::Id, Self::Address>>) {}

    async fn notify_leave(&self, node: Arc<NodeState<Self::Id, Self::Address>>) {
        let mut map = self.map.write().await;
        let id = node.id;
        for set in map.values_mut() {
            set.retain(|node| node.id != id);
        }
    }
}

impl NodeDelegate for WarmUpMapNode {
    async fn notify_message(&self, msg: Cow<'_, [u8]>) {
        /*
        message format
        - loop [
            node_id: u128
            ipv4 address: u32
            code id: u128
            updated_at: u64
            is_alive(alive: 1, dead: 0): u8
        ]
        */

        let mut map = self.map.write().await;
        let mut event_map = self.event_queue.write().await;
        let mut reader = msg.as_ref();
        while !reader.is_empty() {
            let id = reader.get_u128();
            let addr = Ipv4Addr::from(reader.get_u32());
            let code_id = reader.get_u128();
            let updated_at = reader.get_u64();
            let is_alive = reader.get_u8() == 1;

            let nodes = map.entry(code_id).or_default();

            let node_from_msg = NodePresence {
                id,
                addr,
                updated_at,
                is_alive,
            };

            let node_in_memory = nodes.get(&node_from_msg);
            let is_updated = match node_in_memory {
                Some(node_in_memory) => {
                    node_in_memory.is_alive != is_alive || node_in_memory.updated_at < updated_at
                }
                None => true,
            };

            if is_updated {
                event_map
                    .entry(code_id)
                    .or_default()
                    .replace(node_from_msg.clone());
                nodes.replace(node_from_msg);
            }
        }
    }

    async fn broadcast_messages<F>(
        &self,
        limit: usize,
        encoded_len: F,
    ) -> impl Iterator<Item = Bytes> + Send
    where
        F: Fn(Bytes) -> (usize, Bytes) + Send + Sync + 'static,
    {
        let mut total_size = 0;
        let mut event_map = self.event_queue.write().await;
        let mut vec = vec![];
        'out: {
            while let Some(mut entry) = event_map.first_entry() {
                let code_id = *entry.key();
                let set = entry.get_mut();
                while let Some(node) = set.pop_first() {
                    let mut bytes = BytesMut::with_capacity(45);
                    bytes.put_u128(node.id);
                    bytes.put_u32(node.addr.to_bits());
                    bytes.put_u128(code_id);
                    bytes.put_u64(node.updated_at);
                    bytes.put_u8(if node.is_alive { 1 } else { 0 });
                    let bytes = bytes.freeze();

                    let (len, bytes) = encoded_len(bytes);

                    if total_size + len > limit {
                        set.insert(node);
                        break 'out;
                    }

                    total_size += len;
                    vec.push(bytes);
                }
                entry.remove();
            }
        }

        vec.into_iter()
    }

    async fn local_state(&self, _join: bool) -> Bytes {
        let map = self.map.read().await;
        let mut bytes =
            BytesMut::with_capacity(map.values().map(|nodes| nodes.len()).sum::<usize>() * 45);
        for (code_id, set) in map.iter() {
            for node in set {
                bytes.put_u128(node.id);
                bytes.put_u32(node.addr.to_bits());
                bytes.put_u128(*code_id);
                bytes.put_u64(node.updated_at);
                bytes.put_u8(if node.is_alive { 1 } else { 0 });
            }
        }

        bytes.freeze()
    }

    async fn merge_remote_state(&self, buf: &[u8], _join: bool) {
        NodeDelegate::notify_message(self, buf.into()).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;

    mod node_precense_tests {
        use super::*;

        #[test]
        fn test_equality_based_on_addr() {
            let node1 = NodePresence {
                id: 1,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 100,
                is_alive: true,
            };
            let node2 = NodePresence {
                id: 2,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 200,
                is_alive: false,
            };
            let node3 = NodePresence {
                id: 3,
                addr: Ipv4Addr::new(192, 168, 1, 2),
                updated_at: 100,
                is_alive: true,
            };

            assert_eq!(node1, node2);
            assert_ne!(node1, node3);
        }

        #[test]
        fn test_ordering_based_on_addr() {
            let node1 = NodePresence {
                id: 1,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 100,
                is_alive: true,
            };
            let node2 = NodePresence {
                id: 2,
                addr: Ipv4Addr::new(192, 168, 1, 2),
                updated_at: 50,
                is_alive: false,
            };

            assert!(node1 < node2);
            assert!(node2 > node1);
        }

        #[test]
        fn test_btreeset_deduplication() {
            let mut set = BTreeSet::new();
            let node1 = NodePresence {
                id: 1,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 100,
                is_alive: true,
            };
            let node2 = NodePresence {
                id: 2,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 200,
                is_alive: false,
            };

            set.insert(node1);
            set.replace(node2.clone());

            assert_eq!(set.len(), 1);
            assert_eq!(set.iter().next().unwrap().updated_at, 200);
        }
    }

    mod notify_message_tests {
        use super::*;

        #[tokio::test]
        async fn test_single_node_message() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg = BytesMut::new();
            msg.put_u128(999); // node_id
            msg.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg.put_u128(12345);
            msg.put_u64(1000);
            msg.put_u8(1); // is_alive

            node.notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                .await;

            let map = node.map.read().await;
            let nodes = map.get(&12345).unwrap();
            assert_eq!(nodes.len(), 1);
            let node_data = nodes.iter().next().unwrap();
            assert_eq!(node_data.id, 999);
            assert_eq!(node_data.addr, Ipv4Addr::new(192, 168, 1, 1));
            assert_eq!(node_data.updated_at, 1000);
            assert!(node_data.is_alive);

            let event_queue = node.event_queue.read().await;
            assert_eq!(event_queue.get(&12345).unwrap().len(), 1);
        }

        #[tokio::test]
        async fn test_multiple_nodes_message() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg = BytesMut::new();
            msg.put_u128(999);
            msg.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg.put_u128(12345);
            msg.put_u64(1000);
            msg.put_u8(1);
            msg.put_u128(888);
            msg.put_u32(Ipv4Addr::new(192, 168, 1, 2).to_bits());
            msg.put_u128(12345);
            msg.put_u64(2000);
            msg.put_u8(0);

            node.notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                .await;

            let map = node.map.read().await;
            let nodes = map.get(&12345).unwrap();
            assert_eq!(nodes.len(), 2);
        }

        #[tokio::test]
        async fn test_update_with_newer_timestamp() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg1 = BytesMut::new();
            msg1.put_u128(999);
            msg1.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg1.put_u128(12345);
            msg1.put_u64(1000);
            msg1.put_u8(1);
            node.notify_message(Cow::Borrowed(msg1.freeze().as_ref()))
                .await;

            let mut msg2 = BytesMut::new();
            msg2.put_u128(999);
            msg2.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg2.put_u128(12345);
            msg2.put_u64(2000);
            msg2.put_u8(0);
            node.notify_message(Cow::Borrowed(msg2.freeze().as_ref()))
                .await;

            let map = node.map.read().await;
            let nodes = map.get(&12345).unwrap();
            assert_eq!(nodes.len(), 1);
            let node_data = nodes.iter().next().unwrap();
            assert_eq!(node_data.updated_at, 2000);
            assert!(!node_data.is_alive);
        }

        #[tokio::test]
        async fn test_ignore_older_timestamp() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg1 = BytesMut::new();
            msg1.put_u128(999);
            msg1.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg1.put_u128(12345);
            msg1.put_u64(2000);
            msg1.put_u8(1);
            node.notify_message(Cow::Borrowed(msg1.freeze().as_ref()))
                .await;

            let _event_queue_before = node.event_queue.read().await.len();

            let mut msg2 = BytesMut::new();
            msg2.put_u128(999);
            msg2.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg2.put_u128(12345);
            msg2.put_u64(1000);
            msg2.put_u8(1);
            node.notify_message(Cow::Borrowed(msg2.freeze().as_ref()))
                .await;

            let map = node.map.read().await;
            let nodes = map.get(&12345).unwrap();
            let node_data = nodes.iter().next().unwrap();
            assert_eq!(node_data.updated_at, 2000);
            assert!(node_data.is_alive);

            let event_queue = node.event_queue.read().await;
            assert_eq!(event_queue.get(&12345).unwrap().len(), 1);
        }

        #[tokio::test]
        async fn test_empty_message() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let msg = BytesMut::new();
            node.notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                .await;

            let map = node.map.read().await;
            assert_eq!(map.len(), 0);
        }

        #[tokio::test]
        async fn test_multiple_code_ids() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg = BytesMut::new();
            msg.put_u128(999);
            msg.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg.put_u128(12345);
            msg.put_u64(1000);
            msg.put_u8(1);
            msg.put_u128(888);
            msg.put_u32(Ipv4Addr::new(192, 168, 1, 2).to_bits());
            msg.put_u128(67890);
            msg.put_u64(2000);
            msg.put_u8(1);

            node.notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                .await;

            let map = node.map.read().await;
            assert_eq!(map.len(), 2);
            assert!(map.contains_key(&12345));
            assert!(map.contains_key(&67890));
        }
    }

    mod broadcast_messages_tests {
        use super::*;

        #[tokio::test]
        async fn test_broadcast_single_message() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut event_queue = node.event_queue.write().await;
            event_queue.entry(12345).or_default().insert(NodePresence {
                id: 999,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 1000,
                is_alive: true,
            });
            drop(event_queue);

            let messages: Vec<_> = node
                .broadcast_messages(1000, |bytes| {
                    let len = bytes.len();
                    (len, bytes)
                })
                .await
                .collect();

            assert_eq!(messages.len(), 1);
            assert_eq!(messages[0].len(), 45);

            let event_queue = node.event_queue.read().await;
            assert_eq!(event_queue.len(), 0);
        }

        #[tokio::test]
        async fn test_broadcast_respects_size_limit() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut event_queue = node.event_queue.write().await;
            for i in 0..10 {
                event_queue.entry(12345).or_default().insert(NodePresence {
                    id: i as u128,
                    addr: Ipv4Addr::new(192, 168, 1, i),
                    updated_at: 1000,
                    is_alive: true,
                });
            }
            drop(event_queue);

            let messages: Vec<_> = node
                .broadcast_messages(100, |bytes| {
                    let len = bytes.len();
                    (len, bytes)
                })
                .await
                .collect();

            assert_eq!(messages.len(), 2);

            let event_queue = node.event_queue.read().await;
            let remaining = event_queue.get(&12345).map(|s| s.len()).unwrap_or(0);
            assert_eq!(remaining, 8);
        }

        #[tokio::test]
        async fn test_broadcast_multiple_code_ids() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut event_queue = node.event_queue.write().await;
            event_queue.entry(12345).or_default().insert(NodePresence {
                id: 999,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 1000,
                is_alive: true,
            });
            event_queue.entry(67890).or_default().insert(NodePresence {
                id: 888,
                addr: Ipv4Addr::new(192, 168, 1, 2),
                updated_at: 2000,
                is_alive: false,
            });
            drop(event_queue);

            let messages: Vec<_> = node
                .broadcast_messages(1000, |bytes| {
                    let len = bytes.len();
                    (len, bytes)
                })
                .await
                .collect();

            assert_eq!(messages.len(), 2);

            let event_queue = node.event_queue.read().await;
            assert_eq!(event_queue.len(), 0);
        }

        #[tokio::test]
        async fn test_broadcast_empty_queue() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let messages: Vec<_> = node
                .broadcast_messages(1000, |bytes| {
                    let len = bytes.len();
                    (len, bytes)
                })
                .await
                .collect();

            assert_eq!(messages.len(), 0);
        }
    }

    mod local_state_tests {
        use super::*;

        #[tokio::test]
        async fn test_empty_map() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let state = node.local_state(false).await;
            assert_eq!(state.len(), 0);
        }

        #[tokio::test]
        async fn test_single_node_serialization() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut map = node.map.write().await;
            map.entry(12345).or_default().insert(NodePresence {
                id: 999,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 1000,
                is_alive: true,
            });
            drop(map);

            let state = node.local_state(false).await;
            assert_eq!(state.len(), 45);

            let mut reader = state.as_ref();
            assert_eq!(reader.get_u128(), 999);
            assert_eq!(
                Ipv4Addr::from(reader.get_u32()),
                Ipv4Addr::new(192, 168, 1, 1)
            );
            assert_eq!(reader.get_u128(), 12345);
            assert_eq!(reader.get_u64(), 1000);
            assert_eq!(reader.get_u8(), 1);
        }

        #[tokio::test]
        async fn test_multiple_nodes_serialization() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut map = node.map.write().await;
            map.entry(12345).or_default().insert(NodePresence {
                id: 999,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 1000,
                is_alive: true,
            });
            map.entry(12345).or_default().insert(NodePresence {
                id: 888,
                addr: Ipv4Addr::new(192, 168, 1, 2),
                updated_at: 2000,
                is_alive: false,
            });
            drop(map);

            let state = node.local_state(false).await;
            assert_eq!(state.len(), 90);
        }

        #[tokio::test]
        async fn test_multiple_code_ids_serialization() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut map = node.map.write().await;
            map.entry(12345).or_default().insert(NodePresence {
                id: 999,
                addr: Ipv4Addr::new(192, 168, 1, 1),
                updated_at: 1000,
                is_alive: true,
            });
            map.entry(67890).or_default().insert(NodePresence {
                id: 888,
                addr: Ipv4Addr::new(192, 168, 1, 2),
                updated_at: 2000,
                is_alive: false,
            });
            drop(map);

            let state = node.local_state(false).await;
            assert_eq!(state.len(), 90);
        }
    }

    mod merge_remote_state_tests {
        use super::*;

        #[tokio::test]
        async fn test_merge_remote_state() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg = BytesMut::new();
            msg.put_u128(999);
            msg.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg.put_u128(12345);
            msg.put_u64(1000);
            msg.put_u8(1);

            node.merge_remote_state(msg.freeze().as_ref(), false).await;

            let map = node.map.read().await;
            assert_eq!(map.len(), 1);
            assert!(map.contains_key(&12345));
        }
    }

    mod integration_tests {
        use super::*;
        use std::sync::Arc;

        #[tokio::test]
        async fn test_node_lifecycle() {
            let node = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg1 = BytesMut::new();
            msg1.put_u128(999);
            msg1.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg1.put_u128(12345);
            msg1.put_u64(1000);
            msg1.put_u8(1);
            node.notify_message(Cow::Borrowed(msg1.freeze().as_ref()))
                .await;

            let mut msg2 = BytesMut::new();
            msg2.put_u128(999);
            msg2.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg2.put_u128(12345);
            msg2.put_u64(2000);
            msg2.put_u8(0);
            node.notify_message(Cow::Borrowed(msg2.freeze().as_ref()))
                .await;

            let messages: Vec<_> = node
                .broadcast_messages(1000, |bytes| {
                    let len = bytes.len();
                    (len, bytes)
                })
                .await
                .collect();

            assert_eq!(messages.len(), 1);

            let mut reader = messages[0].as_ref();
            assert_eq!(reader.get_u128(), 999);
            assert_eq!(
                Ipv4Addr::from(reader.get_u32()),
                Ipv4Addr::new(192, 168, 1, 1)
            );
            assert_eq!(reader.get_u128(), 12345);
            assert_eq!(reader.get_u64(), 2000);
            assert_eq!(reader.get_u8(), 0);
        }

        #[tokio::test]
        async fn test_full_sync_flow() {
            let node1 = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };
            let node2 = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let mut msg = BytesMut::new();
            msg.put_u128(999);
            msg.put_u32(Ipv4Addr::new(192, 168, 1, 1).to_bits());
            msg.put_u128(12345);
            msg.put_u64(1000);
            msg.put_u8(1);
            node1
                .notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                .await;

            let state = node1.local_state(false).await;
            node2.merge_remote_state(state.as_ref(), false).await;

            let map1 = node1.map.read().await;
            let map2 = node2.map.read().await;
            assert_eq!(map1.len(), map2.len());
            assert_eq!(
                map1.get(&12345).unwrap().len(),
                map2.get(&12345).unwrap().len()
            );
        }

        #[tokio::test]
        async fn test_concurrent_notify_messages() {
            let node = Arc::new(WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            });

            let handles: Vec<_> = (0..10)
                .map(|i| {
                    let node_ref = Arc::clone(&node);
                    tokio::spawn(async move {
                        let mut msg = BytesMut::new();
                        msg.put_u128(i as u128);
                        msg.put_u32(Ipv4Addr::new(192, 168, 1, i).to_bits());
                        msg.put_u128(12345);
                        msg.put_u64(1000);
                        msg.put_u8(1);
                        node_ref
                            .notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                            .await;
                    })
                })
                .collect();

            for handle in handles {
                handle.await.unwrap();
            }

            let map = node.map.read().await;
            assert_eq!(map.get(&12345).unwrap().len(), 10);
        }

        #[tokio::test]
        async fn test_message_format_roundtrip() {
            let node1 = WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            };

            let original_id = 999u128;
            let original_addr = Ipv4Addr::new(192, 168, 1, 1);
            let original_code_id = 12345u128;
            let original_updated_at = 1000u64;
            let original_is_alive = true;

            let mut msg = BytesMut::new();
            msg.put_u128(original_id);
            msg.put_u32(original_addr.to_bits());
            msg.put_u128(original_code_id);
            msg.put_u64(original_updated_at);
            msg.put_u8(if original_is_alive { 1 } else { 0 });

            node1
                .notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                .await;

            let state = node1.local_state(false).await;
            let mut reader = state.as_ref();

            assert_eq!(reader.get_u128(), original_id);
            assert_eq!(Ipv4Addr::from(reader.get_u32()), original_addr);
            assert_eq!(reader.get_u128(), original_code_id);
            assert_eq!(reader.get_u64(), original_updated_at);
            assert_eq!(reader.get_u8(), 1);
        }
    }

    // EventDelegate tests
    mod event_delegate_tests {
        use super::*;
        use std::sync::Arc;

        // Test helper functions
        fn create_test_node() -> WarmUpMapNode {
            WarmUpMapNode {
                map: RwLock::new(BTreeMap::new()),
                event_queue: RwLock::new(BTreeMap::new()),
            }
        }

        fn create_node_state(id: NodeId, addr: Ipv4Addr) -> Arc<NodeState<NodeId, Ipv4Addr>> {
            Arc::new(NodeState {
                id,
                addr,
                meta: Default::default(),
                state: Default::default(),
                protocol_version: Default::default(),
                delegate_version: Default::default(),
            })
        }

        async fn add_node_to_map(node: &WarmUpMapNode, code_id: CodeId, presence: NodePresence) {
            let mut map = node.map.write().await;
            map.entry(code_id).or_default().insert(presence);
        }

        async fn get_total_node_count(node: &WarmUpMapNode) -> usize {
            let map = node.map.read().await;
            map.values().map(|set| set.len()).sum()
        }

        async fn node_exists_in_code(
            node: &WarmUpMapNode,
            code_id: CodeId,
            node_id: NodeId,
        ) -> bool {
            let map = node.map.read().await;
            map.get(&code_id)
                .map(|set| set.iter().any(|n| n.id == node_id))
                .unwrap_or(false)
        }

        async fn get_nodes_with_addr(
            node: &WarmUpMapNode,
            code_id: CodeId,
            addr: Ipv4Addr,
        ) -> Vec<NodePresence> {
            let map = node.map.read().await;
            map.get(&code_id)
                .map(|set| {
                    set.iter()
                        .filter(|n| n.addr == addr)
                        .cloned()
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default()
        }

        // Phase 1: notify_join tests
        mod notify_join_tests {
            use super::*;

            #[tokio::test]
            async fn test_basic_join() {
                let node = create_test_node();
                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));

                node.notify_join(node_state).await;

                // Should complete without error
                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_join_removes_same_addr_different_id() {
                let node = create_test_node();
                let code_id = 12345;
                let addr = Ipv4Addr::new(192, 168, 1, 1);

                // Add a node with ID 1 at this address
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 1,
                        addr,
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                // Add another node with different ID/address
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 2,
                        addr: Ipv4Addr::new(192, 168, 1, 2),
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                assert_eq!(get_total_node_count(&node).await, 2);

                // Node with ID 999 joins at the same address
                let node_state = create_node_state(999, addr);
                node.notify_join(node_state).await;

                // Node with ID 1 should be removed (same addr, different ID)
                assert!(!node_exists_in_code(&node, code_id, 1).await);
                // Node with ID 2 should still exist (different addr)
                assert!(node_exists_in_code(&node, code_id, 2).await);
                assert_eq!(get_total_node_count(&node).await, 1);
            }

            #[tokio::test]
            async fn test_join_across_multiple_code_ids() {
                let node = create_test_node();
                let addr = Ipv4Addr::new(192, 168, 1, 1);

                // Add nodes with ID 1 at same address across multiple code_ids
                for code_id in [100, 200, 300] {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: 1,
                            addr,
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                assert_eq!(get_total_node_count(&node).await, 3);

                // Node with ID 999 joins at the same address
                let node_state = create_node_state(999, addr);
                node.notify_join(node_state).await;

                // All nodes with ID 1 should be removed from all code_ids
                for code_id in [100, 200, 300] {
                    assert!(!node_exists_in_code(&node, code_id, 1).await);
                }
                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_join_on_empty_map() {
                let node = create_test_node();
                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));

                node.notify_join(node_state).await;

                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_join_same_node_twice() {
                let node = create_test_node();
                let code_id = 12345;
                let addr = Ipv4Addr::new(192, 168, 1, 1);

                // Add the node
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 1,
                        addr,
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                let node_state = create_node_state(1, addr);

                // Join twice with same ID/address
                node.notify_join(Arc::clone(&node_state)).await;
                node.notify_join(node_state).await;

                // Node should still exist (same ID, so not removed)
                assert!(node_exists_in_code(&node, code_id, 1).await);
                assert_eq!(get_total_node_count(&node).await, 1);
            }

            #[tokio::test]
            async fn test_join_preserves_different_addr_nodes() {
                let node = create_test_node();
                let code_id = 12345;

                // Add multiple nodes with different addresses
                for i in 1..=5 {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: i as u128,
                            addr: Ipv4Addr::new(192, 168, 1, i),
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                assert_eq!(get_total_node_count(&node).await, 5);

                // New node joins at address that doesn't conflict
                let node_state = create_node_state(999, Ipv4Addr::new(192, 168, 1, 100));
                node.notify_join(node_state).await;

                // All 5 nodes should still exist
                assert_eq!(get_total_node_count(&node).await, 5);
            }

            #[tokio::test]
            async fn test_join_removes_only_same_addr_different_id() {
                let node = create_test_node();
                let code_id = 12345;
                let addr = Ipv4Addr::new(192, 168, 1, 1);

                // Add node with ID 1 at target address
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 1,
                        addr,
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                // Add node with ID 2 at same address (should not happen in practice, but testing)
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 2,
                        addr,
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                assert_eq!(get_total_node_count(&node).await, 1); // BTreeSet dedup by addr

                // Node with ID 3 joins
                let node_state = create_node_state(3, addr);
                node.notify_join(node_state).await;

                let nodes_at_addr = get_nodes_with_addr(&node, code_id, addr).await;
                assert_eq!(nodes_at_addr.len(), 0);
            }
        }

        // Phase 1: notify_leave tests
        mod notify_leave_tests {
            use super::*;

            #[tokio::test]
            async fn test_basic_leave() {
                let node = create_test_node();
                let code_id = 12345;

                // Add a node
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 1,
                        addr: Ipv4Addr::new(192, 168, 1, 1),
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                assert!(node_exists_in_code(&node, code_id, 1).await);

                // Node leaves
                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));
                node.notify_leave(node_state).await;

                // Node should be removed
                assert!(!node_exists_in_code(&node, code_id, 1).await);
                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_leave_removes_from_all_code_ids() {
                let node = create_test_node();

                // Add same node ID across multiple code_ids
                for code_id in [100, 200, 300] {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: 1,
                            addr: Ipv4Addr::new(192, 168, 1, 1),
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                assert_eq!(get_total_node_count(&node).await, 3);

                // Node leaves
                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));
                node.notify_leave(node_state).await;

                // Should be removed from all code_ids
                for code_id in [100, 200, 300] {
                    assert!(!node_exists_in_code(&node, code_id, 1).await);
                }
                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_leave_nonexistent_node() {
                let node = create_test_node();

                // Try to remove node that doesn't exist
                let node_state = create_node_state(999, Ipv4Addr::new(192, 168, 1, 1));
                node.notify_leave(node_state).await;

                // Should complete without error
                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_leave_partial_existence() {
                let node = create_test_node();

                // Add node to only some code_ids
                add_node_to_map(
                    &node,
                    100,
                    NodePresence {
                        id: 1,
                        addr: Ipv4Addr::new(192, 168, 1, 1),
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                add_node_to_map(
                    &node,
                    200,
                    NodePresence {
                        id: 2,
                        addr: Ipv4Addr::new(192, 168, 1, 2),
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                assert_eq!(get_total_node_count(&node).await, 2);

                // Node 1 leaves
                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));
                node.notify_leave(node_state).await;

                // Only node 1 should be removed
                assert!(!node_exists_in_code(&node, 100, 1).await);
                assert!(node_exists_in_code(&node, 200, 2).await);
                assert_eq!(get_total_node_count(&node).await, 1);
            }

            #[tokio::test]
            async fn test_leave_on_empty_map() {
                let node = create_test_node();

                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));
                node.notify_leave(node_state).await;

                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_leave_preserves_other_nodes() {
                let node = create_test_node();
                let code_id = 12345;

                // Add multiple nodes
                for i in 1..=5 {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: i as u128,
                            addr: Ipv4Addr::new(192, 168, 1, i),
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                assert_eq!(get_total_node_count(&node).await, 5);

                // Node 3 leaves
                let node_state = create_node_state(3, Ipv4Addr::new(192, 168, 1, 3));
                node.notify_leave(node_state).await;

                // Only node 3 should be removed
                assert!(!node_exists_in_code(&node, code_id, 3).await);
                assert_eq!(get_total_node_count(&node).await, 4);

                // Other nodes should still exist
                for i in [1, 2, 4, 5] {
                    assert!(node_exists_in_code(&node, code_id, i).await);
                }
            }
        }

        // Phase 1: notify_update tests
        mod notify_update_tests {
            use super::*;

            #[tokio::test]
            async fn test_update_is_noop() {
                let node = create_test_node();
                let code_id = 12345;

                // Add a node
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 1,
                        addr: Ipv4Addr::new(192, 168, 1, 1),
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                let count_before = get_total_node_count(&node).await;

                // Call notify_update
                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));
                node.notify_update(node_state).await;

                let count_after = get_total_node_count(&node).await;

                // State should be unchanged
                assert_eq!(count_before, count_after);
                assert!(node_exists_in_code(&node, code_id, 1).await);
            }

            #[tokio::test]
            async fn test_update_on_empty_map() {
                let node = create_test_node();

                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 1, 1));
                node.notify_update(node_state).await;

                // Should complete without error
                assert_eq!(get_total_node_count(&node).await, 0);
            }
        }

        // Phase 2: Concurrency tests
        mod concurrency_tests {
            use super::*;

            #[tokio::test]
            async fn test_concurrent_joins() {
                let node = Arc::new(create_test_node());
                let code_id = 12345;

                // Add some initial nodes
                for i in 1..=10 {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: i as u128,
                            addr: Ipv4Addr::new(192, 168, 1, i),
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                // Concurrent joins
                let handles: Vec<_> = (100..110)
                    .map(|i| {
                        let node_ref = Arc::clone(&node);
                        tokio::spawn(async move {
                            let node_state = create_node_state(i as u128, Ipv4Addr::new(192, 168, 2, i));
                            node_ref.notify_join(node_state).await;
                        })
                    })
                    .collect();

                for handle in handles {
                    handle.await.unwrap();
                }

                // All original nodes should still exist
                assert_eq!(get_total_node_count(&node).await, 10);
            }

            #[tokio::test]
            async fn test_concurrent_leaves() {
                let node = Arc::new(create_test_node());
                let code_id = 12345;

                // Add nodes
                for i in 1..=10 {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: i as u128,
                            addr: Ipv4Addr::new(192, 168, 1, i),
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                // Concurrent leaves
                let handles: Vec<_> = (1..=10)
                    .map(|i| {
                        let node_ref = Arc::clone(&node);
                        tokio::spawn(async move {
                            let node_state = create_node_state(i as u128, Ipv4Addr::new(192, 168, 1, i));
                            node_ref.notify_leave(node_state).await;
                        })
                    })
                    .collect();

                for handle in handles {
                    handle.await.unwrap();
                }

                // All nodes should be removed
                assert_eq!(get_total_node_count(&node).await, 0);
            }

            #[tokio::test]
            async fn test_concurrent_join_and_leave() {
                let node = Arc::new(create_test_node());
                let code_id = 12345;

                // Add initial nodes
                for i in 1..=20 {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: i as u128,
                            addr: Ipv4Addr::new(192, 168, 1, i),
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                let mut handles = vec![];

                // Concurrent joins
                for i in 100..110 {
                    let node_ref = Arc::clone(&node);
                    handles.push(tokio::spawn(async move {
                        let node_state = create_node_state(i as u128, Ipv4Addr::new(192, 168, 2, i));
                        node_ref.notify_join(node_state).await;
                    }));
                }

                // Concurrent leaves
                for i in 1..=10 {
                    let node_ref = Arc::clone(&node);
                    handles.push(tokio::spawn(async move {
                        let node_state = create_node_state(i as u128, Ipv4Addr::new(192, 168, 1, i));
                        node_ref.notify_leave(node_state).await;
                    }));
                }

                for handle in handles {
                    handle.await.unwrap();
                }

                // 20 initial - 10 removed = 10 remaining
                assert_eq!(get_total_node_count(&node).await, 10);
            }

            #[tokio::test]
            async fn test_concurrent_join_and_notify_message() {
                let node = Arc::new(create_test_node());

                let mut handles = vec![];

                // Concurrent joins
                for i in 1..=5 {
                    let node_ref = Arc::clone(&node);
                    handles.push(tokio::spawn(async move {
                        let node_state = create_node_state(i as u128, Ipv4Addr::new(192, 168, 1, i));
                        node_ref.notify_join(node_state).await;
                    }));
                }

                // Concurrent notify_message
                for i in 10..15 {
                    let node_ref = Arc::clone(&node);
                    handles.push(tokio::spawn(async move {
                        let mut msg = BytesMut::new();
                        msg.put_u128(i as u128);
                        msg.put_u32(Ipv4Addr::new(192, 168, 1, i).to_bits());
                        msg.put_u128(12345);
                        msg.put_u64(1000);
                        msg.put_u8(1);
                        node_ref
                            .notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                            .await;
                    }));
                }

                for handle in handles {
                    handle.await.unwrap();
                }

                // Should have 5 nodes from notify_message
                assert!(get_total_node_count(&node).await >= 5);
            }
        }

        // Phase 2: Integration tests
        mod integration_tests {
            use super::*;

            #[tokio::test]
            async fn test_node_full_lifecycle() {
                let node = create_test_node();
                let code_id = 12345;
                let node_id = 999;
                let addr = Ipv4Addr::new(192, 168, 1, 1);

                // Initial state: empty
                assert_eq!(get_total_node_count(&node).await, 0);

                // Node joins
                let node_state = create_node_state(node_id, addr);
                node.notify_join(Arc::clone(&node_state)).await;
                assert_eq!(get_total_node_count(&node).await, 0); // notify_join doesn't add

                // Add via notify_message
                let mut msg = BytesMut::new();
                msg.put_u128(node_id);
                msg.put_u32(addr.to_bits());
                msg.put_u128(code_id);
                msg.put_u64(1000);
                msg.put_u8(1);
                node.notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                    .await;

                assert!(node_exists_in_code(&node, code_id, node_id).await);

                // Node updates (no-op currently)
                node.notify_update(Arc::clone(&node_state)).await;
                assert!(node_exists_in_code(&node, code_id, node_id).await);

                // Node leaves
                node.notify_leave(node_state).await;
                assert!(!node_exists_in_code(&node, code_id, node_id).await);
            }

            #[tokio::test]
            async fn test_node_address_change() {
                let node = create_test_node();
                let code_id = 12345;
                let node_id = 999;
                let old_addr = Ipv4Addr::new(192, 168, 1, 1);
                let new_addr = Ipv4Addr::new(192, 168, 1, 2);

                // Node at old address
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: node_id,
                        addr: old_addr,
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                assert!(node_exists_in_code(&node, code_id, node_id).await);

                // Node joins at new address (simulating IP change)
                let node_state = create_node_state(node_id, new_addr);
                node.notify_join(node_state).await;

                // Old node should still exist (notify_join only removes different IDs at same addr)
                assert!(node_exists_in_code(&node, code_id, node_id).await);
            }

            #[tokio::test]
            async fn test_network_partition_recovery() {
                let node = create_test_node();
                let code_id = 12345;
                let addr = Ipv4Addr::new(192, 168, 1, 1);

                // Old node at address
                add_node_to_map(
                    &node,
                    code_id,
                    NodePresence {
                        id: 1,
                        addr,
                        updated_at: 1000,
                        is_alive: true,
                    },
                )
                .await;

                // After partition, new node joins at same address
                let node_state = create_node_state(999, addr);
                node.notify_join(node_state).await;

                // Old node should be removed
                assert!(!node_exists_in_code(&node, code_id, 1).await);
            }

            #[tokio::test]
            async fn test_event_delegate_with_node_delegate() {
                let node = create_test_node();
                let code_id = 12345;

                // Add nodes via notify_message
                let mut msg = BytesMut::new();
                for i in 1..=3 {
                    msg.put_u128(i as u128);
                    msg.put_u32(Ipv4Addr::new(192, 168, 1, i).to_bits());
                    msg.put_u128(code_id);
                    msg.put_u64(1000);
                    msg.put_u8(1);
                }
                node.notify_message(Cow::Borrowed(msg.freeze().as_ref()))
                    .await;

                assert_eq!(get_total_node_count(&node).await, 3);

                // Node 1 joins at new address
                let node_state = create_node_state(1, Ipv4Addr::new(192, 168, 2, 1));
                node.notify_join(node_state).await;

                // Original nodes should still exist
                assert_eq!(get_total_node_count(&node).await, 3);

                // Node 2 leaves
                let node_state = create_node_state(2, Ipv4Addr::new(192, 168, 1, 2));
                node.notify_leave(node_state).await;

                assert_eq!(get_total_node_count(&node).await, 2);
                assert!(!node_exists_in_code(&node, code_id, 2).await);

                // Check broadcast includes leave event
                let messages: Vec<_> = node
                    .broadcast_messages(1000, |bytes| {
                        let len = bytes.len();
                        (len, bytes)
                    })
                    .await
                    .collect();

                // Should have events from initial adds and update
                assert!(!messages.is_empty());
            }

            #[tokio::test]
            async fn test_stress_100_nodes() {
                let node = create_test_node();
                let code_id = 12345;

                // Add 100 nodes
                for i in 1..=100 {
                    add_node_to_map(
                        &node,
                        code_id,
                        NodePresence {
                            id: i as u128,
                            addr: Ipv4Addr::new(
                                192,
                                168,
                                ((i / 256) % 256) as u8,
                                (i % 256) as u8,
                            ),
                            updated_at: 1000,
                            is_alive: true,
                        },
                    )
                    .await;
                }

                assert_eq!(get_total_node_count(&node).await, 100);

                // Join 50 nodes (some may conflict)
                for i in 1..=50 {
                    let node_state = create_node_state(
                        (i + 1000) as u128,
                        Ipv4Addr::new(192, 168, ((i / 256) % 256) as u8, (i % 256) as u8),
                    );
                    node.notify_join(node_state).await;
                }

                // Should have removed conflicting nodes
                assert!(get_total_node_count(&node).await <= 100);

                // Leave 30 nodes
                for i in 51..=80 {
                    let node_state = create_node_state(
                        i as u128,
                        Ipv4Addr::new(192, 168, ((i / 256) % 256) as u8, (i % 256) as u8),
                    );
                    node.notify_leave(node_state).await;
                }

                // Should have fewer nodes
                let remaining = get_total_node_count(&node).await;
                assert!(remaining <= 70);
            }

            #[tokio::test]
            async fn test_extreme_values() {
                let node = create_test_node();

                // Max values
                let node_state = create_node_state(u128::MAX, Ipv4Addr::BROADCAST);
                node.notify_join(Arc::clone(&node_state)).await;
                node.notify_update(Arc::clone(&node_state)).await;
                node.notify_leave(node_state).await;

                // Should complete without error
                assert_eq!(get_total_node_count(&node).await, 0);
            }
        }
    }
}