plexor-core 0.1.0-alpha.2

Core library for the rust implementation of the Plexo distributed system architecture, providing the fundamental Plexus, Neuron, Codec, and Axon abstractions.
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
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
// Copyright 2025 Alecks Gates
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use crate::codec::{Codec, CodecName};
use crate::erasure::payload::{PayloadErased, PayloadRawErased};
use crate::erasure::reactant::{ErrorReactantErased, ReactantErased, ReactantRawErased};
use crate::erasure::synapse::{SynapseInternalErased, erase_synapse_internal};
use crate::logging::LogTrace;
use crate::neuron::{Neuron, NeuronError};
use crate::synapse::SynapseInprocess;
use crate::utils::struct_name_of_type;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use parking_lot::RwLock;
use thiserror::Error;
use tokio::sync::Mutex;
use tracing::Instrument;
use uuid::Uuid;

#[derive(Error, Debug)]
pub enum GanglionError {
    #[error("Synapse not found: {neuron_name} (ganglion: {ganglion_name}, id: {ganglion_id})")]
    SynapseNotFound {
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
    },
    #[error(
        "Failed to acquire lock on synapse: {neuron_name} (ganglion: {ganglion_name}, id: {ganglion_id})"
    )]
    SynapseLock {
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
    },
    #[error(
        "Transmission error for neuron {neuron_name} (ganglion: {ganglion_name}, id: {ganglion_id}): {message}"
    )]
    Transmit {
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
        message: String,
    },
    #[error("Encode error for neuron {neuron_name} (ganglion: {ganglion_name}, id: {ganglion_id})")]
    Encode {
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
    },
    #[error("Decode error for neuron {neuron_name} (ganglion: {ganglion_name}, id: {ganglion_id})")]
    Decode {
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
    },
    #[error(
        "Adaptation error for neuron {neuron_name} (ganglion: {ganglion_name}, id: {ganglion_id})"
    )]
    Adapt {
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
    },
    #[error("Queue full for neuron {neuron_name} (ganglion: {ganglion_name}, id: {ganglion_id})")]
    QueueFull {
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
    },
}

impl GanglionError {
    /// Convert a NeuronError to a GanglionError with additional context
    pub fn from_neuron_error(
        neuron_error: NeuronError,
        ganglion_name: String,
        ganglion_id: Uuid,
    ) -> Self {
        match neuron_error {
            NeuronError::Encode { neuron_name, .. } => GanglionError::Encode {
                neuron_name,
                ganglion_name,
                ganglion_id,
            },
            NeuronError::Decode { neuron_name, .. } => GanglionError::Decode {
                neuron_name,
                ganglion_name,
                ganglion_id,
            },
        }
    }

    /// Convert a PlexusError to a GanglionError with additional context
    pub fn from_plexus_error(
        plexus_error: crate::plexus::PlexusError,
        neuron_name: String,
        ganglion_name: String,
        ganglion_id: Uuid,
    ) -> Self {
        match plexus_error {
            // If the PlexusError already contains a GanglionError, return it as-is
            crate::plexus::PlexusError::Ganglion(ganglion_error) => ganglion_error,
            // For all other PlexusError variants, convert to Adapt error
            _ => GanglionError::Adapt {
                neuron_name,
                ganglion_name,
                ganglion_id,
            },
        }
    }
}

pub trait Ganglion {
    fn capable<T, C>(&mut self, neuron: Arc<dyn Neuron<T, C> + Send + Sync>) -> bool
    where
        C: Codec<T> + CodecName + Send + Sync + 'static,
        T: Send + Sync + 'static;

    fn adapt<T, C>(
        &mut self,
        neuron: Arc<dyn Neuron<T, C> + Send + Sync>,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>>
    where
        C: Codec<T> + CodecName + Send + Sync + 'static,
        T: Send + Sync + 'static;
}

/// Internal interface for Ganglion that handles type-erased payloads and reactants.
pub trait GanglionInternal {
    fn transmit(
        &mut self,
        payload: Arc<dyn PayloadErased + Send + Sync + 'static>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, GanglionError>> + Send + 'static>>;

    fn react(
        &mut self,
        neuron_name: String,
        reactants: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>>,
        error_reactants: Vec<Arc<dyn ErrorReactantErased + Send + Sync>>,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>>;

    /// React to multiple neurons at once.
    fn react_many(
        &mut self,
        reactions: HashMap<
            String,
            (
                Vec<Arc<dyn ReactantErased + Send + Sync + 'static>>,
                Vec<Arc<dyn ErrorReactantErased + Send + Sync>>,
            ),
        >,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>> {
        let mut futures = Vec::new();
        for (name, (rs, ers)) in reactions {
            futures.push(self.react(name, rs, ers));
        }
        Box::pin(async move {
            for f in futures {
                f.await?;
            }
            Ok(())
        })
    }

    fn unique_id(&self) -> Uuid;
}

/// External interface for Ganglion that handles network-level type-erased data.
pub trait GanglionExternal {
    fn transmit(
        &mut self,
        payload: Arc<dyn PayloadErased + Send + Sync + 'static>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, GanglionError>> + Send + 'static>>;

    #[allow(clippy::type_complexity)]
    fn transmit_encoded(
        &mut self,
        payload: Arc<dyn PayloadRawErased + Send + Sync + 'static>,
    ) -> Pin<Box<dyn Future<Output = Result<(Vec<()>, Vec<()>), GanglionError>> + Send + 'static>>;

    fn react(
        &mut self,
        neuron_name: String,
        reactants: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>>,
        raw_reactants: Vec<Arc<dyn ReactantRawErased + Send + Sync + 'static>>,
        error_reactants: Vec<Arc<dyn ErrorReactantErased + Send + Sync>>,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>>;

    /// React to multiple neurons at once.
    fn react_many(
        &mut self,
        reactions: HashMap<
            String,
            (
                Vec<Arc<dyn ReactantErased + Send + Sync + 'static>>,
                Vec<Arc<dyn ReactantRawErased + Send + Sync + 'static>>,
                Vec<Arc<dyn ErrorReactantErased + Send + Sync>>,
            ),
        >,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>> {
        let mut futures = Vec::new();
        for (name, (rs, rrs, ers)) in reactions {
            futures.push(self.react(name, rs, rrs, ers));
        }
        Box::pin(async move {
            for f in futures {
                f.await?;
            }
            Ok(())
        })
    }

    fn unique_id(&self) -> Uuid;
}

/// Helper function to adapt a single neuron to multiple ganglia at once.
/// Note: All ganglia in the slice must be of the same type G.
/// For heterogeneous ganglia, use the `adapt_all!` macro instead.
pub async fn adapt_all<T, C, G>(
    ganglia: &[Arc<Mutex<G>>],
    neuron: Arc<dyn Neuron<T, C> + Send + Sync>,
) -> Result<(), GanglionError>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Send + Sync + 'static,
    G: Ganglion + ?Sized,
{
    for ganglion_mutex in ganglia {
        let mut ganglion = ganglion_mutex.lock().await;
        ganglion.adapt(neuron.clone()).await?;
    }
    Ok(())
}

/// Macro to adapt a single neuron to multiple heterogeneous ganglia at once.
///
/// # Examples
///
/// ```rust
/// # use std::sync::Arc;
/// # use tokio::sync::Mutex;
/// # use plexor_core::adapt_all;
/// # use plexor_core::neuron::{Neuron, NeuronImpl};
/// # use plexor_core::ganglion::{Ganglion, GanglionInprocess};
/// # use plexor_core::namespace::NamespaceImpl;
/// # use plexor_core::codec::{Codec, CodecError, CodecName};
/// #
/// # #[derive(Debug)]
/// # struct Dummy;
/// # impl CodecName for Dummy { fn name() -> &'static str { "dummy" } }
/// # impl Codec<Dummy> for Dummy {
/// #     fn encode(_: &Dummy) -> Result<Vec<u8>, CodecError> { Ok(vec![]) }
/// #     fn decode(_: &[u8]) -> Result<Dummy, CodecError> { Ok(Dummy) }
/// # }
/// #
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let ns = Arc::new(NamespaceImpl { delimiter: ".", parts: vec!["test"] });
/// let neuron = Arc::new(NeuronImpl::<Dummy, Dummy>::new(ns));
/// let g1 = Arc::new(Mutex::new(GanglionInprocess::new()));
/// let g2 = Arc::new(Mutex::new(GanglionInprocess::new()));
///
/// adapt_all!(neuron, g1, g2).await.unwrap();
/// # });
/// ```
#[macro_export]
macro_rules! adapt_all {
    ($neuron:expr, $($ganglion:expr),+ $(,)?) => {
        async {
            $(
                $ganglion.lock().await.adapt($neuron.clone()).await?;
            )+
            Result::<(), $crate::ganglion::GanglionError>::Ok(())
        }
    };
}

/// Macro to adapt multiple neurons to multiple heterogeneous ganglia at once.
///
/// This locks each ganglion once and adapts all provided neurons to it.
///
/// # Examples
///
/// ```rust
/// # use std::sync::Arc;
/// # use tokio::sync::Mutex;
/// # use plexor_core::adapt_many;
/// # use plexor_core::neuron::{Neuron, NeuronImpl};
/// # use plexor_core::ganglion::{Ganglion, GanglionInprocess};
/// # use plexor_core::namespace::NamespaceImpl;
/// # use plexor_core::codec::{Codec, CodecError, CodecName};
/// #
/// # #[derive(Debug, Clone)]
/// # struct Dummy;
/// # impl CodecName for Dummy { fn name() -> &'static str { "dummy" } }
/// # impl Codec<Dummy> for Dummy {
/// #     fn encode(_: &Dummy) -> Result<Vec<u8>, CodecError> { Ok(vec![]) }
/// #     fn decode(_: &[u8]) -> Result<Dummy, CodecError> { Ok(Dummy) }
/// # }
/// #
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let ns = Arc::new(NamespaceImpl { delimiter: ".", parts: vec!["test"] });
/// let n1 = Arc::new(NeuronImpl::<Dummy, Dummy>::new(ns.clone()));
/// let n2 = Arc::new(NeuronImpl::<Dummy, Dummy>::new(ns));
/// let g1 = Arc::new(Mutex::new(GanglionInprocess::new()));
/// let g2 = Arc::new(Mutex::new(GanglionInprocess::new()));
///
/// let res: Result<(), plexor_core::ganglion::GanglionError> = adapt_many!([n1, n2], g1, g2).await;
/// res.unwrap();
/// # });
/// ```
#[macro_export]
macro_rules! adapt_many {
    // Base case: simple expansion for a single ganglion
    ([$($neuron:expr),+ $(,)?], $ganglion:expr $(,)?) => {
        async {
            let mut g = $ganglion.lock().await;
            $(
                g.adapt($neuron.clone()).await?;
            )+
            Result::<(), $crate::ganglion::GanglionError>::Ok(())
        }
    };

    // Recursive step: handle head ganglion, then recurse for tail
    ([$($neuron:expr),+ $(,)?], $head_ganglion:expr, $($tail_ganglion:expr),+ $(,)?) => {
        async {
            {
                let mut g = $head_ganglion.lock().await;
                $(
                    g.adapt($neuron.clone()).await?;
                )+
            }
            $crate::adapt_many!([$($neuron),+], $($tail_ganglion),+).await
        }
    };
}

pub struct GanglionInprocess {
    id: Uuid,
    synapses_by_name:
        HashMap<String, Arc<RwLock<dyn SynapseInternalErased + Send + Sync + 'static>>>,
    /// Neurons that this ganglion will handle (if empty, handles all)
    relevant_neurons: HashSet<String>,
    /// Neurons that this ganglion will ignore
    ignored_neurons: HashSet<String>,
}

impl GanglionInprocess {
    pub fn new() -> Self {
        Self {
            id: Uuid::now_v7(),
            synapses_by_name: HashMap::new(),
            relevant_neurons: HashSet::new(),
            ignored_neurons: HashSet::new(),
        }
    }

    /// Helper to create an Arc<Mutex<GanglionInprocess>>
    pub fn new_shared() -> Arc<Mutex<Self>> {
        Arc::new(Mutex::new(Self::new()))
    }

    pub fn new_with_filters(
        relevant_neurons: HashSet<String>,
        ignored_neurons: HashSet<String>,
    ) -> Self {
        Self {
            id: Uuid::now_v7(),
            synapses_by_name: HashMap::new(),
            relevant_neurons,
            ignored_neurons,
        }
    }

    fn get_synapse_by_name(
        &self,
        name: &str,
    ) -> Option<Arc<RwLock<dyn SynapseInternalErased + Send + Sync + 'static>>> {
        self.synapses_by_name.get(name).cloned()
    }
}

impl Default for GanglionInprocess {
    fn default() -> Self {
        Self::new()
    }
}

impl Ganglion for GanglionInprocess {
    fn capable<T, C>(&mut self, neuron: Arc<dyn Neuron<T, C> + Send + Sync>) -> bool
    where
        C: Codec<T> + CodecName + Send + Sync + 'static,
        T: Send + Sync + 'static,
    {
        let neuron_name = neuron.name();

        if !self.relevant_neurons.is_empty() && !self.relevant_neurons.contains(&neuron_name) {
            return false;
        }

        if !self.ignored_neurons.is_empty() && self.ignored_neurons.contains(&neuron_name) {
            return false;
        }

        true
    }

    fn adapt<T, C>(
        &mut self,
        neuron: Arc<dyn Neuron<T, C> + Send + Sync>,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>>
    where
        C: Codec<T> + CodecName + Send + Sync + 'static,
        T: Send + Sync + 'static,
    {
        // Call capable and return early if false
        if !self.capable(neuron.clone()) {
            return Box::pin(async move {
                Ok(()) // Not an error, just not capable
            });
        }

        let neuron_name = neuron.name();

        // Check if the synapse already exists
        if self.synapses_by_name.contains_key(&neuron_name) {
            return Box::pin(async move {
                Ok(()) // Not an error, synapse already exists
            });
        }

        // Create the synapse
        let synapse = SynapseInprocess::<T, C>::new(neuron.clone(), vec![], vec![]);
        let erased_synapse = erase_synapse_internal(synapse);

        // Insert the synapse
        self.synapses_by_name
            .insert(neuron_name.clone(), erased_synapse);

        Box::pin(async move { Ok(()) })
    }
}

impl GanglionInternal for GanglionInprocess {
    fn transmit(
        &mut self,
        payload: Arc<dyn PayloadErased + Send + Sync + 'static>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, GanglionError>> + Send + 'static>> {
        let neuron_name = payload.get_neuron_name();
        tracing::debug!("GanglionInprocess::transmit called for neuron: {neuron_name}");

        if let Some(synapse_lock) = self.get_synapse_by_name(&neuron_name) {
            tracing::debug!("GanglionInprocess::transmit found synapse, acquiring read lock");
            let synapse_guard = synapse_lock.read();
            tracing::debug!(
                "GanglionInprocess::transmit acquired read lock, calling transmit_erased"
            );
            let future = synapse_guard.transmit_erased(payload.clone());
            let ganglion_id = self.id;
            let ganglion_name = struct_name_of_type::<Self>().to_string();
            Box::pin(
                async move {
                    tracing::debug!(
                        "GanglionInprocess::transmit awaiting transmit_erased future"
                    );
                    let result = future.await;
                    tracing::debug!("GanglionInprocess::transmit transmit_erased completed");
                    result.map_err(|e| match e {
                        crate::synapse::SynapseError::QueueFull { neuron_name: _ } => {
                            GanglionError::QueueFull {
                                neuron_name: neuron_name.clone(),
                                ganglion_name: ganglion_name.clone(),
                                ganglion_id,
                            }
                        }
                        _ => GanglionError::Transmit {
                            neuron_name: neuron_name.clone(),
                            ganglion_name: ganglion_name.clone(),
                            ganglion_id,
                            message: e.to_string(),
                        },
                    })
                }
                .instrument(payload.span_debug("GanglionInprocess::transmit")),
            )
        } else {
            tracing::debug!("GanglionInprocess::transmit synapse not found");
            let ganglion_id = self.id;
            let ganglion_name = struct_name_of_type::<GanglionInprocess>().to_string();
            Box::pin(async move {
                Err(GanglionError::SynapseNotFound {
                    neuron_name,
                    ganglion_name,
                    ganglion_id,
                })
            })
        }
    }

    fn react(
        &mut self,
        neuron_name: String,
        reactants: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>>,
        error_reactants: Vec<Arc<dyn ErrorReactantErased + Send + Sync>>,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>> {
        // Get the synapse by name
        let synapse_lock_opt = self.get_synapse_by_name(&neuron_name);

        // Check if the synapse exists
        if synapse_lock_opt.is_none() {
            let ganglion_id = self.id;
            let ganglion_name = struct_name_of_type::<GanglionInprocess>().to_string();
            return Box::pin(async move {
                Err(GanglionError::SynapseNotFound {
                    neuron_name,
                    ganglion_name,
                    ganglion_id,
                })
            });
        }

        // Get a write lock on the synapse
        let synapse_lock = synapse_lock_opt.unwrap();
        let mut synapse_guard = synapse_lock.write();

        // Call react_erased on the synapse with the reactants
        synapse_guard.react_erased(reactants, error_reactants);

        // The write lock is automatically released when synapse_guard goes out of scope

        Box::pin(async move { Ok(()) })
    }

    fn react_many(
        &mut self,
        reactions: HashMap<
            String,
            (
                Vec<Arc<dyn ReactantErased + Send + Sync + 'static>>,
                Vec<Arc<dyn ErrorReactantErased + Send + Sync>>,
            ),
        >,
    ) -> Pin<Box<dyn Future<Output = Result<(), GanglionError>> + Send + 'static>> {
        for (neuron_name, (reactants, error_reactants)) in reactions {
            if let Some(synapse_lock) = self.get_synapse_by_name(&neuron_name) {
                let mut synapse_guard = synapse_lock.write();
                synapse_guard.react_erased(reactants, error_reactants);
            } else {
                let ganglion_id = self.id;
                let ganglion_name = struct_name_of_type::<GanglionInprocess>().to_string();
                return Box::pin(async move {
                    Err(GanglionError::SynapseNotFound {
                        neuron_name,
                        ganglion_name,
                        ganglion_id,
                    })
                });
            }
        }
        Box::pin(async move { Ok(()) })
    }

    fn unique_id(&self) -> Uuid {
        self.id
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::erasure::payload::{erase_payload, erase_payload_raw};
    use crate::erasure::reactant::{
        ReactantErased, ReactantRawErased, erase_reactant, erase_reactant_raw,
    };
    use crate::namespace::NamespaceImpl;
    use crate::neuron::{Neuron, NeuronImpl};
    use crate::payload::{Payload, PayloadRaw};
    use crate::test_utils::{
        DebugCodec, DebugStruct, GanglionExternalInprocess, PingCodec, PingMsg, PingNeuron,
        TokioMpscReactant, TokioMpscReactantGeneric, TokioMpscReactantRaw, test_namespace,
    };
    use std::collections::HashSet;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::sync::mpsc::channel;
    use tokio::task;
    use tokio::time::sleep;
    use uuid::Uuid;

    #[test]
    fn test_ganglion_error_with_ganglion_name() {
        let ganglion_id = Uuid::now_v7();
        let ganglion_name = struct_name_of_type::<GanglionInprocess>().to_string();

        // Test SynapseNotFound error
        let synapse_not_found = GanglionError::SynapseNotFound {
            neuron_name: "test_neuron".to_string(),
            ganglion_name: ganglion_name.clone(),
            ganglion_id,
        };
        assert!(synapse_not_found.to_string().contains("test_neuron"));
        assert!(synapse_not_found.to_string().contains("GanglionInprocess"));

        // Test SynapseLockError error
        let synapse_lock_error = GanglionError::SynapseLock {
            neuron_name: "test_neuron".to_string(),
            ganglion_name: ganglion_name.clone(),
            ganglion_id,
        };
        assert!(synapse_lock_error.to_string().contains("test_neuron"));
        assert!(synapse_lock_error.to_string().contains("GanglionInprocess"));

        // Test new Transmit error
        let transmit_error = GanglionError::Transmit {
            neuron_name: "test_neuron".to_string(),
            ganglion_name: ganglion_name.clone(),
            ganglion_id,
            message: "test failure".to_string(),
        };
        assert!(transmit_error.to_string().contains("test_neuron"));
        assert!(transmit_error.to_string().contains("GanglionInprocess"));
        assert!(transmit_error.to_string().contains("test failure"));
    }
    // test_ganglion_inprocess_neuron_by_name has been removed as part of removing get_neuron_by_name and neurons_by_name

    #[tokio::test]
    async fn test_ganglion_inprocess_get_synapse_by_name() {
        let ns = test_namespace();
        let neuron_impl_instance: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron_name_str = neuron_impl_instance.name();

        let neuron: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync + 'static> =
            Arc::new(neuron_impl_instance);

        let mut ganglion = GanglionInprocess::new();

        // Use adapt instead of add_neuron and populate_synapse
        ganglion
            .adapt(neuron.clone())
            .await
            .expect("Failed to adapt neuron for test");

        let result_by_name1 = ganglion.get_synapse_by_name(&neuron_name_str);
        assert!(result_by_name1.is_some());
        let synapse_by_name1 = result_by_name1.unwrap();

        let result_by_name2 = ganglion.get_synapse_by_name(&neuron_name_str);
        assert!(result_by_name2.is_some());
        let synapse_by_name2 = result_by_name2.unwrap();

        assert!(
            Arc::ptr_eq(&synapse_by_name1, &synapse_by_name2),
            "Repeated calls to get_synapse_by_name should yield the same Arc instance."
        );

        let non_existent_result = ganglion.get_synapse_by_name("non_existent_neuron");
        assert!(non_existent_result.is_none());
    }

    #[tokio::test]
    async fn test_ganglion_inprocess_transmit_via_adapt() {
        let ns = test_namespace();

        let (tx1, mut rx1) = channel::<Arc<Payload<PingMsg, PingCodec>>>(10);
        let (tx2, mut rx2) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(10);

        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());

        let neuron_arc = neuron_impl.clone_to_arc();

        let mut ganglion: GanglionInprocess = GanglionInprocess::new();

        // Use adapt instead of add_neuron and populate_synapse
        ganglion
            .adapt(neuron_arc.clone())
            .await
            .expect("Failed to adapt neuron");

        let ping_neuron = Arc::new(PingNeuron::new(test_namespace()));
        ganglion
            .adapt(ping_neuron.clone())
            .await
            .expect("Failed to adapt ping neuron");

        let reactants1: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>> =
            vec![erase_reactant::<PingMsg, PingCodec, _>(Box::new(
                TokioMpscReactantGeneric::new(tx1.clone()),
            ))];
        let reactants2: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>> =
            vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
                TokioMpscReactantGeneric::new(tx2.clone()),
            ))];

        ganglion
            .react(ping_neuron.name(), reactants1, vec![])
            .await
            .expect("Failed to react ping");
        ganglion
            .react(neuron_arc.name(), reactants2, vec![])
            .await
            .expect("Failed to react debug");

        let correlation_uuid1 = Uuid::now_v7();
        let payload1 = Payload::builder()
            .value(PingMsg { seq: 1 })
            .correlation_id(correlation_uuid1)
            .neuron(ping_neuron)
            .build()
            .unwrap();

        let erased_payload1 = erase_payload(payload1);
        ganglion
            .transmit(erased_payload1)
            .await
            .expect("Failed to transmit payload1");

        assert_eq!(
            rx1.len(),
            1,
            "Reactant 1 should have received the first message (ping)"
        );
        let received_p1_ch1 = rx1.recv().await.unwrap();
        assert_eq!(
            received_p1_ch1.value.seq, 1,
            "Payload value mismatch for reactant 1"
        );
        assert_eq!(
            received_p1_ch1.correlation_id(), correlation_uuid1,
            "Correlation ID mismatch for reactant 1"
        );

        let debug_struct_arc_2 = Arc::new(DebugStruct {
            foo: 456,
            bar: "ganglion_test_payload_2".to_string(),
        });
        let correlation_uuid2 = Uuid::now_v7();
        let payload2 = Payload::builder()
            .value((*debug_struct_arc_2).clone())
            .correlation_id(correlation_uuid2)
            .neuron(neuron_arc.clone())
            .build()
            .unwrap();

        let erased_payload2 = erase_payload(payload2);
        ganglion
            .transmit(erased_payload2)
            .await
            .expect("Failed to transmit payload2");

        assert_eq!(
            rx2.len(),
            1,
            "Reactant 2 should have received the second message (debug)"
        );
        let received_p2_ch1 = rx2.recv().await.unwrap();
        assert_eq!(
            received_p2_ch1.value, debug_struct_arc_2,
            "Second payload value mismatch for reactant 2"
        );
        assert_eq!(
            received_p2_ch1.correlation_id(), correlation_uuid2,
            "Second correlation ID mismatch for reactant 2"
        );

        // Ensure channels are empty now, indicating no unexpected messages
        assert_eq!(
            rx1.len(),
            0,
            "Reactant 1 channel should be empty after all expected messages"
        );
        assert_eq!(
            rx2.len(),
            0,
            "Reactant 2 channel should be empty after all expected messages"
        );
    }

    #[tokio::test]
    async fn test_ganglion_inprocess_across_threads() {
        // Create a struct to hold the shared state
        struct SharedState {
            // Channels to receive payloads from reactants
            tx1: tokio::sync::mpsc::Sender<Arc<Payload<DebugStruct, DebugCodec>>>,
            tx2: tokio::sync::mpsc::Sender<Arc<Payload<DebugStruct, DebugCodec>>>,
            // Counter for received payloads
            received_count: std::sync::atomic::AtomicUsize,
        }

        // Create channels with large buffer to avoid blocking
        let (tx1, mut rx1) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(100);
        let (tx2, mut rx2) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(100);

        // Create shared state
        let shared_state = Arc::new(SharedState {
            tx1,
            tx2,
            received_count: std::sync::atomic::AtomicUsize::new(0),
        });

        // Number of threads and payloads per thread
        let num_threads = 10;
        let payloads_per_thread = 10;
        let total_payloads = num_threads * payloads_per_thread;

        // Create a vector to store all task handles
        let mut handles = Vec::new();

        // Spawn a task to receive payloads and count them
        let receiver_state = shared_state.clone();
        let receiver_handle = task::spawn(async move {
            let mut received_payloads = Vec::new();

            // Collect payloads from both channels
            for _ in 0..total_payloads * 2 {
                tokio::select! {
                    Some(payload) = rx1.recv() => {
                        received_payloads.push(payload);
                        receiver_state.received_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                    Some(payload) = rx2.recv() => {
                        received_payloads.push(payload);
                        receiver_state.received_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                }
            }

            received_payloads
        });

        // Create shared namespace, neuron, and ganglion outside the tasks
        let ns = test_namespace();
        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns);
        let neuron = neuron_impl.clone_to_arc();

        let reactants: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>> = vec![
            erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactant {
                sender: shared_state.tx1.clone(),
            })),
            erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactant {
                sender: shared_state.tx2.clone(),
            })),
        ];

        let mut shared_ganglion = GanglionInprocess::new();
        // Use adapt instead of add_neuron and populate_synapse
        shared_ganglion
            .adapt(neuron.clone())
            .await
            .expect("Failed to adapt neuron");
        shared_ganglion
            .react(neuron.name(), reactants, vec![])
            .await
            .expect("Failed to react");

        let shared_ganglion = Arc::new(tokio::sync::Mutex::new(shared_ganglion));

        // Spawn multiple tasks that will transmit payloads using the shared ganglion
        for thread_id in 0..num_threads {
            let ganglion = shared_ganglion.clone();
            let neuron_clone = neuron.clone();

            // Spawn a new task
            let handle = task::spawn(async move {
                // Transmit payloads through this task's ganglion
                for i in 0..payloads_per_thread {
                    // Create a unique payload for this thread and iteration
                    let payload_id = thread_id * payloads_per_thread + i;
                    let debug_struct = Arc::new(DebugStruct {
                        foo: payload_id as i32,
                        bar: format!("thread_{thread_id}_payload_{i}"),
                    });

                    let correlation_uuid = Uuid::now_v7();
                    let payload = Payload::builder()
                        .value((*debug_struct).clone())
                        .correlation_id(correlation_uuid)
                        .neuron(neuron_clone.clone())
                        .build()
                        .unwrap();

                    // Add a small delay to increase the chance of thread interleaving
                    sleep(Duration::from_millis(1)).await;

                    // Transmit the payload through the shared ganglion
                    let mut ganglion_guard = ganglion.lock().await;
                    let erased_payload = erase_payload(payload);
                    let _ = ganglion_guard.transmit(erased_payload).await;
                }
            });

            handles.push(handle);
        }

        // Wait for all transmitter tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }

        // Wait for the receiver task to complete and get the received payloads
        let received_payloads = receiver_handle.await.unwrap();

        // Verify that we received the expected number of payloads
        assert_eq!(
            shared_state
                .received_count
                .load(std::sync::atomic::Ordering::SeqCst),
            total_payloads * 2,
            "Should have received all payloads on both reactants"
        );

        // Verify that we received payloads from all threads
        let mut foo_values = received_payloads
            .iter()
            .map(|p| p.value.foo)
            .collect::<Vec<_>>();
        foo_values.sort();
        foo_values.dedup();

        assert_eq!(
            foo_values.len(),
            total_payloads,
            "Should have received payloads with all expected foo values"
        );

        // Check that the foo values match the expected range
        for i in 0..total_payloads {
            assert!(
                foo_values.contains(&(i as i32)),
                "Should have received a payload with foo={i}"
            );
        }

        // Verify that all correlation_ids are preserved
        let mut correlation_ids = received_payloads
            .iter()
            .map(|p| p.correlation_id())
            .collect::<Vec<_>>();

        // Each correlation_id should appear exactly twice (once from each reactant)
        // So we should have total_payloads unique correlation_ids
        correlation_ids.sort();

        // Count occurrences of each correlation_id
        let mut correlation_id_counts = std::collections::HashMap::new();
        for id in &correlation_ids {
            *correlation_id_counts.entry(*id).or_insert(0) += 1;
        }

        // Verify we have the expected number of unique correlation_ids
        assert_eq!(
            correlation_id_counts.len(),
            total_payloads,
            "Should have received payloads with all expected correlation_ids"
        );

        // Verify each correlation_id appears exactly twice (once from each reactant)
        for (id, count) in correlation_id_counts {
            assert_eq!(
                count, 2,
                "Correlation ID {id} should appear exactly twice (once from each reactant)"
            );
        }
    }

    #[tokio::test]
    async fn test_ganglion_external_unique_id() {
        use crate::test_utils::GanglionExternalInprocess;
        let ganglion1 = GanglionExternalInprocess::new();
        let ganglion2 = GanglionExternalInprocess::new();

        // Each ganglion should have a unique ID
        assert_ne!(ganglion1.unique_id(), ganglion2.unique_id());

        // The same ganglion should return the same ID consistently
        assert_eq!(ganglion1.unique_id(), ganglion1.unique_id());
    }

    #[tokio::test]
    async fn test_ganglion_inprocess_capable_with_relevant_neurons() {
        // Create neurons
        let neuron1 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "1"],
            },
        )));
        let neuron2 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "2"],
            },
        )));
        // Create ganglion with only neuron1 in relevant_neurons
        let mut relevant_neurons = HashSet::new();
        relevant_neurons.insert("dev.plexo.1.DebugStruct.debug".to_string());
        let mut ganglion = GanglionInprocess::new_with_filters(relevant_neurons, HashSet::new());

        // Test that neuron1 is capable
        assert!(ganglion.capable(neuron1.clone()));

        // Test that neuron2 is not capable
        assert!(!ganglion.capable(neuron2.clone()));
    }

    #[tokio::test]
    async fn test_ganglion_inprocess_capable_with_ignored_neurons() {
        // Create neurons
        let neuron1 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "1"],
            },
        )));
        let neuron2 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "2"],
            },
        )));

        // Create ganglion with neuron1 in ignored_neurons
        let mut ignored_neurons = HashSet::new();
        ignored_neurons.insert("dev.plexo.1.DebugStruct.debug".to_string());
        let mut ganglion = GanglionInprocess::new_with_filters(HashSet::new(), ignored_neurons);

        // Test that neuron1 is not capable (ignored)
        assert!(!ganglion.capable(neuron1.clone()));

        // Test that neuron2 is capable (not ignored)
        assert!(ganglion.capable(neuron2.clone()));
    }

    #[tokio::test]
    async fn test_ganglion_external_inprocess_capable_with_relevant_neurons() {
        // Create neurons
        let neuron1 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "1"],
            },
        )));
        let neuron2 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "2"],
            },
        )));

        // Create ganglion with only neuron1 in relevant_neurons
        let mut relevant_neurons = HashSet::new();
        relevant_neurons.insert("dev.plexo.1.DebugStruct.debug".to_string());
        let mut ganglion =
            GanglionExternalInprocess::new_with_filters(relevant_neurons, HashSet::new());

        // Test that neuron1 is capable
        assert!(ganglion.capable(neuron1.clone()));

        // Test that neuron2 is not capable
        assert!(!ganglion.capable(neuron2.clone()));
    }

    #[tokio::test]
    async fn test_ganglion_external_inprocess_capable_with_ignored_neurons() {
        // Create neurons
        let neuron1 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "1"],
            },
        )));
        let neuron2 = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo", "2"],
            },
        )));

        // Create ganglion with neuron1 in ignored_neurons
        let mut ignored_neurons = HashSet::new();
        ignored_neurons.insert("dev.plexo.1.DebugStruct.debug".to_string());
        let mut ganglion =
            GanglionExternalInprocess::new_with_filters(HashSet::new(), ignored_neurons);

        // Test that neuron1 is not capable (ignored)
        assert!(!ganglion.capable(neuron1.clone()));

        // Test that neuron2 is capable (not ignored)
        assert!(ganglion.capable(neuron2.clone()));
    }

    #[tokio::test]
    async fn test_ganglion_inprocess_capable_default_behavior() {
        // Create neuron
        let neuron = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(Arc::new(
            NamespaceImpl {
                delimiter: ".",
                parts: vec!["dev", "plexo"],
            },
        )));

        // Create ganglion with default constructor (no filters)
        let mut ganglion = GanglionInprocess::new();

        // Test that neuron is capable (default behavior should accept all)
        assert!(ganglion.capable(neuron.clone()));
    }

    #[tokio::test]
    async fn test_ganglion_external_inprocess_capable_default_behavior() {
        // Create neuron
        let neuron = Arc::new(NeuronImpl::<DebugStruct, DebugCodec>::new(test_namespace()));

        // Create ganglion with default constructor (no filters)
        let mut ganglion = GanglionExternalInprocess::new();

        // Test that neuron is capable (default behavior should accept all)
        assert!(ganglion.capable(neuron.clone()));
    }

    #[tokio::test]
    async fn test_ganglion_external_transmit_encoded() {
        let ns = test_namespace();
        let mut ganglion = GanglionExternalInprocess::new();
        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync + 'static> =
            Arc::new(neuron_impl.clone());

        // Adapt the neuron to the ganglion first
        ganglion
            .adapt(neuron.clone())
            .await
            .expect("Failed to adapt neuron");

        let debug_struct_value = DebugStruct {
            foo: 42,
            bar: "test_value".to_owned(),
        };
        let debug_struct_arc = Arc::new(debug_struct_value);
        let correlation_id = Uuid::now_v7();
        let encoded = neuron_impl
            .encode(debug_struct_arc.as_ref())
            .expect("Encoding should succeed in test");

        let payload_raw =
            PayloadRaw::with_correlation(encoded, neuron.clone(), Some(correlation_id));

        let erased_payload = erase_payload_raw(payload_raw);
        let result = ganglion
            .transmit_encoded(erased_payload)
            .await
            .expect("Failed to transmit encoded payload");

        // For the test implementation, we expect empty vectors since no reactants were added
        assert_eq!(result.0.len(), 0);
        assert_eq!(result.1.len(), 0);
    }

    #[tokio::test]
    async fn test_ganglion_external_adapt() {
        let mut ganglion = GanglionExternalInprocess::new();
        let ns = test_namespace();
        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns);
        let neuron: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync + 'static> =
            Arc::new(neuron_impl);

        // This should complete without error
        ganglion
            .adapt(neuron)
            .await
            .expect("Failed to adapt neuron");
    }

    #[tokio::test]
    async fn test_ganglion_external_inprocess_transmit_via_adapt() {
        let ns = test_namespace();

        let (tx1, mut rx1) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(2);
        let (tx2, mut rx2) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(2);
        let (raw_tx1, mut raw_rx1) = channel::<Arc<PayloadRaw<DebugStruct, DebugCodec>>>(2);
        let (raw_tx2, mut raw_rx2) = channel::<Arc<PayloadRaw<DebugStruct, DebugCodec>>>(2);

        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron_arc = neuron_impl.clone_to_arc();

        let reactants: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>> = vec![
            erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactant {
                sender: tx1.clone(),
            })),
            erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactant {
                sender: tx2.clone(),
            })),
        ];

        let raw_reactants: Vec<Arc<dyn ReactantRawErased + Send + Sync + 'static>> = vec![
            erase_reactant_raw::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactantRaw {
                sender: raw_tx1.clone(),
            })),
            erase_reactant_raw::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactantRaw {
                sender: raw_tx2.clone(),
            })),
        ];

        let mut ganglion: GanglionExternalInprocess = GanglionExternalInprocess::new();

        ganglion
            .adapt(neuron_arc.clone())
            .await
            .expect("Failed to adapt neuron");
        ganglion
            .react(neuron_arc.name(), reactants, raw_reactants, vec![])
            .await
            .expect("Failed to react");

        let debug_struct_arc = Arc::new(DebugStruct {
            foo: 123,
            bar: "ganglion_external_test_payload_1".to_string(),
        });
        let correlation_uuid1 = Uuid::now_v7();
        let encoded = neuron_impl
            .encode(debug_struct_arc.as_ref())
            .expect("Encoding should succeed in test");
        let payload_raw1 = PayloadRaw::with_correlation(
            encoded,
            neuron_arc.clone(),
            Some(correlation_uuid1),
        );

        let erased_payload1 = erase_payload_raw(payload_raw1);
        ganglion
            .transmit_encoded(erased_payload1)
            .await
            .expect("Failed to transmit encoded payload1");

        // Check that raw reactants received the payload
        let received_raw_p1_ch1 =
            tokio::time::timeout(std::time::Duration::from_millis(100), raw_rx1.recv())
                .await
                .expect("Timeout raw_rx1")
                .expect("Closed raw_rx1");
        assert_eq!(
            received_raw_p1_ch1.correlation_id(), correlation_uuid1,
            "Raw correlation ID mismatch for reactant 1"
        );

        let received_raw_p1_ch2 =
            tokio::time::timeout(std::time::Duration::from_millis(100), raw_rx2.recv())
                .await
                .expect("Timeout raw_rx2")
                .expect("Closed raw_rx2");
        assert_eq!(
            received_raw_p1_ch2.correlation_id(), correlation_uuid1,
            "Raw correlation ID mismatch for reactant 2"
        );

        // Check that regular reactants also received the decoded payload
        let received_p1_ch1 =
            tokio::time::timeout(std::time::Duration::from_millis(100), rx1.recv())
                .await
                .expect("Timeout rx1")
                .expect("Closed rx1");
        assert_eq!(
            received_p1_ch1.value, debug_struct_arc,
            "Payload value mismatch for reactant 1"
        );
        assert_eq!(
            received_p1_ch1.correlation_id(), correlation_uuid1,
            "Correlation ID mismatch for reactant 1"
        );

        let received_p1_ch2 =
            tokio::time::timeout(std::time::Duration::from_millis(100), rx2.recv())
                .await
                .expect("Timeout rx2")
                .expect("Closed rx2");
        assert_eq!(
            received_p1_ch2.value, debug_struct_arc,
            "Payload value mismatch for reactant 2"
        );
        assert_eq!(
            received_p1_ch2.correlation_id(), correlation_uuid1,
            "Correlation ID mismatch for reactant 2"
        );

        // Send a second payload
        let debug_struct_arc_2 = Arc::new(DebugStruct {
            foo: 456,
            bar: "ganglion_external_test_payload_2".to_string(),
        });
        let correlation_uuid2 = Uuid::now_v7();
        let encoded2 = neuron_impl
            .encode(debug_struct_arc_2.as_ref())
            .expect("Encoding should succeed in test");
        let payload_raw2 = PayloadRaw::with_correlation(
            encoded2,
            neuron_arc.clone(),
            Some(correlation_uuid2),
        );

        let erased_payload2 = erase_payload_raw(payload_raw2);
        ganglion
            .transmit_encoded(erased_payload2)
            .await
            .expect("Failed to transmit encoded payload2");

        // Check raw reactants received the second payload
        let received_raw_p2_ch1 =
            tokio::time::timeout(std::time::Duration::from_millis(100), raw_rx1.recv())
                .await
                .expect("Timeout raw_rx1_2")
                .expect("Closed raw_rx1_2");
        assert_eq!(
            received_raw_p2_ch1.correlation_id(), correlation_uuid2,
            "Second raw correlation ID mismatch for reactant 1"
        );

        let received_raw_p2_ch2 =
            tokio::time::timeout(std::time::Duration::from_millis(100), raw_rx2.recv())
                .await
                .expect("Timeout raw_rx2_2")
                .expect("Closed raw_rx2_2");
        assert_eq!(
            received_raw_p2_ch2.correlation_id(), correlation_uuid2,
            "Second raw correlation ID mismatch for reactant 2"
        );

        // Check regular reactants received the second decoded payload
        let received_p2_ch1 =
            tokio::time::timeout(std::time::Duration::from_millis(100), rx1.recv())
                .await
                .expect("Timeout rx1_2")
                .expect("Closed rx1_2");
        assert_eq!(
            received_p2_ch1.value, debug_struct_arc_2,
            "Second payload value mismatch for reactant 1"
        );
        assert_eq!(
            received_p2_ch1.correlation_id(), correlation_uuid2,
            "Second correlation ID mismatch for reactant 1"
        );

        let received_p2_ch2 =
            tokio::time::timeout(std::time::Duration::from_millis(100), rx2.recv())
                .await
                .expect("Timeout rx2_2")
                .expect("Closed rx2_2");
        assert_eq!(
            received_p2_ch2.value, debug_struct_arc_2,
            "Second payload value mismatch for reactant 2"
        );
        assert_eq!(
            received_p2_ch2.correlation_id(), correlation_uuid2,
            "Second correlation ID mismatch for reactant 2"
        );

        // Ensure channels are empty now, indicating no unexpected messages
        assert_eq!(
            rx1.len(),
            0,
            "Reactant 1 channel should be empty after all expected messages"
        );
        assert_eq!(
            rx2.len(),
            0,
            "Reactant 2 channel should be empty after all expected messages"
        );
        assert_eq!(
            raw_rx1.len(),
            0,
            "Raw reactant 1 channel should be empty after all expected messages"
        );
        assert_eq!(
            raw_rx2.len(),
            0,
            "Raw reactant 2 channel should be empty after all expected messages"
        );
    }

    #[tokio::test]
    async fn test_ganglion_inprocess_adapt_erased() {
        let ns = test_namespace();

        // Create a neuron
        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync + 'static> =
            Arc::new(neuron_impl);

        // Create a ganglion
        let mut ganglion = GanglionInprocess::new();

        // Use the regular adapt method instead of adapt_erased
        ganglion
            .adapt(neuron.clone())
            .await
            .expect("Failed to adapt neuron");

        // Verify that a synapse was created and stored
        let neuron_name = neuron.name();
        let synapse = ganglion.get_synapse_by_name(&neuron_name);
        assert!(synapse.is_some());
    }

    #[tokio::test]
    async fn test_ganglion_external_inprocess_across_threads() {
        use crate::ganglion::GanglionExternal;
        use crate::neuron::NeuronImpl;
        use crate::payload::PayloadRaw;
        use crate::test_utils::{
            DebugCodec, DebugStruct, GanglionExternalInprocess, TokioMpscReactant,
            TokioMpscReactantRaw, test_namespace,
        };
        use std::sync::Arc;
        use tokio::sync::mpsc::channel;
        use tokio::task;
        use tokio::time::{Duration, sleep};
        use uuid::Uuid;

        // Create a struct to hold the shared state
        struct SharedState {
            // Channels to receive payloads from reactants
            tx1: tokio::sync::mpsc::Sender<Arc<Payload<DebugStruct, DebugCodec>>>,
            tx2: tokio::sync::mpsc::Sender<Arc<Payload<DebugStruct, DebugCodec>>>,
            raw_tx1: tokio::sync::mpsc::Sender<Arc<PayloadRaw<DebugStruct, DebugCodec>>>,
            raw_tx2: tokio::sync::mpsc::Sender<Arc<PayloadRaw<DebugStruct, DebugCodec>>>,
            // Counter for received payloads
            received_count: std::sync::atomic::AtomicUsize,
            raw_received_count: std::sync::atomic::AtomicUsize,
        }

        // Create channels with large buffer to avoid blocking
        let (tx1, mut rx1) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(100);
        let (tx2, mut rx2) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(100);
        let (raw_tx1, mut raw_rx1) = channel::<Arc<PayloadRaw<DebugStruct, DebugCodec>>>(100);
        let (raw_tx2, mut raw_rx2) = channel::<Arc<PayloadRaw<DebugStruct, DebugCodec>>>(100);

        // Create shared state
        let shared_state = Arc::new(SharedState {
            tx1,
            tx2,
            raw_tx1,
            raw_tx2,
            received_count: std::sync::atomic::AtomicUsize::new(0),
            raw_received_count: std::sync::atomic::AtomicUsize::new(0),
        });

        // Number of threads and payloads per thread
        let num_threads = 10;
        let payloads_per_thread = 10;
        let total_payloads = num_threads * payloads_per_thread;

        // Create a vector to store all task handles
        let mut handles = Vec::new();

        // Spawn a task to receive payloads and count them
        let receiver_state = shared_state.clone();
        let receiver_handle = task::spawn(async move {
            let mut received_payloads = Vec::new();
            let mut received_raw_payloads = Vec::new();

            // Collect payloads from all channels
            for _ in 0..total_payloads * 4 {
                // 2 regular + 2 raw channels
                tokio::select! {
                    Some(payload) = rx1.recv() => {
                        received_payloads.push(payload);
                        receiver_state.received_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                    Some(payload) = rx2.recv() => {
                        received_payloads.push(payload);
                        receiver_state.received_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                    Some(payload) = raw_rx1.recv() => {
                        received_raw_payloads.push(payload);
                        receiver_state.raw_received_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                    Some(payload) = raw_rx2.recv() => {
                        received_raw_payloads.push(payload);
                        receiver_state.raw_received_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                }
            }

            (received_payloads, received_raw_payloads)
        });

        // Create shared namespace, neuron, and ganglion outside the tasks
        let ns = test_namespace();
        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns);
        let neuron = neuron_impl.clone_to_arc();

        // Create a single shared ganglion with reactants
        let reactants: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>> = vec![
            erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactant {
                sender: shared_state.tx1.clone(),
            })),
            erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactant {
                sender: shared_state.tx2.clone(),
            })),
        ];

        let raw_reactants: Vec<Arc<dyn ReactantRawErased + Send + Sync + 'static>> = vec![
            erase_reactant_raw::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactantRaw {
                sender: shared_state.raw_tx1.clone(),
            })),
            erase_reactant_raw::<DebugStruct, DebugCodec, _>(Box::new(TokioMpscReactantRaw {
                sender: shared_state.raw_tx2.clone(),
            })),
        ];

        let mut shared_ganglion = GanglionExternalInprocess::new();
        shared_ganglion
            .adapt(neuron.clone())
            .await
            .expect("Failed to adapt neuron");
        shared_ganglion
            .react(neuron.name(), reactants, raw_reactants, vec![])
            .await
            .expect("Failed to react");

        let shared_ganglion = Arc::new(tokio::sync::Mutex::new(shared_ganglion));

        // Spawn multiple tasks that will transmit payloads using the shared ganglion
        for thread_id in 0..num_threads {
            let ganglion = shared_ganglion.clone();
            let neuron_clone = neuron.clone();
            let neuron_impl_clone = neuron_impl.clone();

            // Spawn a new task
            let handle = task::spawn(async move {
                // Transmit payloads through this task's ganglion
                for i in 0..payloads_per_thread {
                    // Create a unique payload for this thread and iteration
                    let payload_id = thread_id * payloads_per_thread + i;
                    let debug_struct = Arc::new(DebugStruct {
                        foo: payload_id as i32,
                        bar: format!("external_thread_{thread_id}_payload_{i}"),
                    });

                    let correlation_uuid = Uuid::now_v7();
                    let encoded = neuron_impl_clone
                        .encode(debug_struct.as_ref())
                        .expect("Encoding should succeed in test");
                    let payload_raw = PayloadRaw::with_correlation(
                        encoded,
                        neuron_clone.clone(),
                        Some(correlation_uuid),
                    );

                    // Add a small delay to increase the chance of thread interleaving
                    sleep(Duration::from_millis(1)).await;

                    // Transmit the payload through the shared ganglion
                    let mut ganglion_guard = ganglion.lock().await;
                    let erased_payload = erase_payload_raw(payload_raw);
                    ganglion_guard
                        .transmit_encoded(erased_payload)
                        .await
                        .expect("Failed to transmit encoded payload");
                }
            });

            handles.push(handle);
        }

        // Wait for all transmitter tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }

        // Wait for the receiver task to complete and get the received payloads
        let (received_payloads, received_raw_payloads) = receiver_handle.await.unwrap();

        // Verify that we received the expected number of payloads
        assert_eq!(
            shared_state
                .received_count
                .load(std::sync::atomic::Ordering::SeqCst),
            total_payloads * 2,
            "Should have received all decoded payloads on both regular reactants"
        );

        assert_eq!(
            shared_state
                .raw_received_count
                .load(std::sync::atomic::Ordering::SeqCst),
            total_payloads * 2,
            "Should have received all raw payloads on both raw reactants"
        );

        // Verify that we received payloads from all threads (regular reactants)
        let mut foo_values = received_payloads
            .iter()
            .map(|p| p.value.foo)
            .collect::<Vec<_>>();
        foo_values.sort();
        foo_values.dedup();

        assert_eq!(
            foo_values.len(),
            total_payloads,
            "Should have received payloads with all expected foo values"
        );

        // Check that the foo values match the expected range
        for i in 0..total_payloads {
            assert!(
                foo_values.contains(&(i as i32)),
                "Should have received a payload with foo={i}"
            );
        }

        // Verify that all correlation_ids are preserved (regular reactants)
        let mut correlation_ids = received_payloads
            .iter()
            .map(|p| p.correlation_id())
            .collect::<Vec<_>>();

        // Each correlation_id should appear exactly twice (once from each reactant)
        // So we should have total_payloads unique correlation_ids
        correlation_ids.sort();

        // Count occurrences of each correlation_id
        let mut correlation_id_counts = std::collections::HashMap::new();
        for id in &correlation_ids {
            *correlation_id_counts.entry(*id).or_insert(0) += 1;
        }

        // Verify we have the expected number of unique correlation_ids (regular reactants)
        assert_eq!(
            correlation_id_counts.len(),
            total_payloads,
            "Should have received payloads with all expected correlation_ids"
        );

        // Verify each correlation_id appears exactly twice (once from each reactant)
        for (id, count) in correlation_id_counts {
            assert_eq!(
                count, 2,
                "Correlation ID {id} should appear exactly twice (once from each regular reactant)"
            );
        }

        // Verify that all correlation_ids are preserved (raw reactants)
        let mut raw_correlation_ids = received_raw_payloads
            .iter()
            .map(|p| p.correlation_id())
            .collect::<Vec<_>>();

        raw_correlation_ids.sort();

        // Count occurrences of each correlation_id for raw reactants
        let mut raw_correlation_id_counts = std::collections::HashMap::new();
        for id in &raw_correlation_ids {
            *raw_correlation_id_counts.entry(*id).or_insert(0) += 1;
        }

        // Verify we have the expected number of unique correlation_ids for raw reactants
        assert_eq!(
            raw_correlation_id_counts.len(),
            total_payloads,
            "Should have received raw payloads with all expected correlation_ids"
        );

        // Verify each correlation_id appears exactly twice for raw reactants (once from each raw reactant)
        for (id, count) in raw_correlation_id_counts {
            assert_eq!(
                count, 2,
                "Correlation ID {id} should appear exactly twice (once from each raw reactant)"
            );
        }
    }
}