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
// 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;
use crate::erasure::reactant::{ErrorReactantErased, ReactantErased};
use crate::ganglion::{Ganglion, GanglionError, GanglionInternal};
use crate::neuron::Neuron;
use crate::utils::struct_name_of_type;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::Mutex;
use uuid::Uuid;

pub struct Thalamus<G>
where
    G: GanglionInternal + Ganglion + Send + Sync + 'static,
{
    id: Uuid,
    peers: Vec<Arc<Mutex<G>>>,
}

impl<G> Thalamus<G>
where
    G: GanglionInternal + Ganglion + Send + Sync + 'static,
{
    pub fn new(peers: Vec<Arc<Mutex<G>>>) -> Self {
        Self {
            id: Uuid::now_v7(),
            peers,
        }
    }
}

impl<G> Ganglion for Thalamus<G>
where
    G: GanglionInternal + Ganglion + Send + Sync + 'static,
{
    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,
    {
        // Thalamus is capable if all peers are capable
        // Actually, we could return true if AT LEAST one peer is capable
        // For simplicity, let's say true if any are capable
        for peer in self.peers.iter() {
            // Using a blocking lock here since capable is synchronous
            // This might be problematic if called from an async context frequently
            // but the trait definition is synchronous.
            if let Some(mut p) = peer.try_lock().ok() {
                if p.capable(neuron.clone()) {
                    return true;
                }
            }
        }
        false
    }

    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,
    {
        let peers = self.peers.clone();
        Box::pin(async move {
            for peer in peers.iter() {
                let mut p = peer.lock().await;
                p.adapt(neuron.clone()).await?;
            }
            Ok(())
        })
    }
}

impl<G> GanglionInternal for Thalamus<G>
where
    G: GanglionInternal + Ganglion + Send + Sync + 'static,
{
    fn transmit(
        &mut self,
        payload: Arc<dyn PayloadErased + Send + Sync + 'static>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, GanglionError>> + Send + 'static>> {
        let peers = self.peers.clone();
        let neuron_name = payload.get_neuron_name();
        Box::pin(async move {
            // Round-robin or broadcast?
            // Thalamus usually load balances (round-robin)
            if peers.is_empty() {
                return Err(GanglionError::SynapseNotFound {
                    neuron_name,
                    ganglion_name: struct_name_of_type::<Self>().to_string(),
                    ganglion_id: Uuid::nil(),
                });
            }

            // Simple load balancing: find first that succeeds?
            // Or round-robin index?
            // For now, let's broadcast to all and collect results
            let mut all_results = Vec::new();
            let mut last_err = None;
            let mut at_least_one_ok = false;

            for peer in peers.iter() {
                let future = {
                    let mut p = peer.lock().await;
                    p.transmit(payload.clone())
                };
                match future.await {
                    Ok(mut results) => {
                        all_results.append(&mut results);
                        at_least_one_ok = true;
                    }
                    Err(e) => {
                        last_err = Some(e);
                    }
                }
            }

            if at_least_one_ok {
                Ok(all_results)
            } else {
                Err(last_err.unwrap_or(GanglionError::SynapseNotFound {
                    neuron_name,
                    ganglion_name: struct_name_of_type::<Self>().to_string(),
                    ganglion_id: Uuid::nil(),
                }))
            }
        })
    }

    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>> {
        let peers = self.peers.clone();
        Box::pin(async move {
            if peers.is_empty() {
                return Err(GanglionError::SynapseNotFound {
                    neuron_name,
                    ganglion_name: struct_name_of_type::<Self>().to_string(),
                    ganglion_id: Uuid::nil(),
                });
            }

            let mut at_least_one_ok = false;
            let mut last_err: Option<GanglionError> = None;
            for peer in peers.iter() {
                let future = {
                    let mut p = peer.lock().await;
                    p.react(neuron_name.clone(), reactants.clone(), error_reactants.clone())
                };
                match future.await {
                    Ok(()) => at_least_one_ok = true,
                    Err(e) => last_err = Some(e),
                }
            }
            if at_least_one_ok {
                Ok(())
            } else {
                Err(last_err.unwrap_or(GanglionError::SynapseNotFound {
                    neuron_name,
                    ganglion_name: struct_name_of_type::<Self>().to_string(),
                    ganglion_id: Uuid::nil(),
                }))
            }
        })
    }

    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 peers = self.peers.clone();
        Box::pin(async move {
            if peers.is_empty() {
                return Err(GanglionError::SynapseNotFound {
                    neuron_name: "batch".to_string(),
                    ganglion_name: struct_name_of_type::<Self>().to_string(),
                    ganglion_id: Uuid::nil(),
                });
            }

            let mut at_least_one_ok = false;
            let mut last_err: Option<GanglionError> = None;
            for peer in peers.iter() {
                let future = {
                    let mut p = peer.lock().await;
                    p.react_many(reactions.clone())
                };
                match future.await {
                    Ok(()) => at_least_one_ok = true,
                    Err(e) => last_err = Some(e),
                }
            }
            if at_least_one_ok {
                Ok(())
            } else {
                Err(last_err.unwrap_or(GanglionError::SynapseNotFound {
                    neuron_name: "batch".to_string(),
                    ganglion_name: struct_name_of_type::<Self>().to_string(),
                    ganglion_id: Uuid::nil(),
                }))
            }
        })
    }

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::erasure::payload::erase_payload;
    use crate::erasure::reactant::erase_reactant;
    use crate::ganglion::GanglionInprocess;
    use crate::logging::TraceContext;
    use crate::neuron::NeuronImpl;
    use crate::payload::Payload;
    use crate::reactant::Reactant;
    use crate::test_utils::{
        DebugCodec, DebugStruct, ResponseCodec, ResponseStruct, TokioMpscReactant, test_namespace,
    };
    use std::sync::Arc;
    use tokio::sync::Mutex;
    use tokio::sync::mpsc::channel;
    use uuid::Uuid;

    #[tokio::test]
    async fn test_thalamus_broadcast_basic() {
        let ns = test_namespace();
        let neuron: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron_name = neuron.name();
        let neuron_arc: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync> = Arc::new(neuron);

        let g1 = Arc::new(Mutex::new(GanglionInprocess::new()));
        let g2 = Arc::new(Mutex::new(GanglionInprocess::new()));

        let mut thalamus = Thalamus::new(vec![g1.clone(), g2.clone()]);
        // Adapt neuron across peers
        thalamus
            .adapt::<DebugStruct, DebugCodec>(neuron_arc.clone())
            .await
            .unwrap();

        let (tx, mut rx) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(10);
        let reactants = vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
            TokioMpscReactant::new(tx),
        ))];

        // Attach reactants across all peers via thalamus
        thalamus
            .react(neuron_name.clone(), reactants, vec![])
            .await
            .unwrap();

        // Create payloads and send twice; expect four receives (broadcast to both peers per transmit)
        let correlation_id = Uuid::now_v7();
        let span_id = correlation_id.as_u128() as u64;
        let payload1 = Arc::new(Payload::from_parts(
            Arc::new(DebugStruct {
                foo: 1,
                bar: "a".to_string(),
            }),
            neuron_arc.clone(),
            TraceContext::from_parts(correlation_id, span_id, None),
        ));
        let payload2 = Payload::new(
            DebugStruct {
                foo: 2,
                bar: "b".to_string(),
            },
            neuron_arc.clone(),
        );

        thalamus.transmit(erase_payload(payload1)).await.unwrap();
        thalamus.transmit(erase_payload(payload2)).await.unwrap();

        // Should receive exactly four messages (2 transmits * 2 peers)
        let _m1 = rx.recv().await.expect("expected first message");
        let _m2 = rx.recv().await.expect("expected second message");
        let _m3 = rx.recv().await.expect("expected third message");
        let _m4 = rx.recv().await.expect("expected fourth message");
    }

    #[tokio::test]
    async fn test_thalamus_broadcast_work_distribution() {
        let ns = test_namespace();
        let neuron: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron_name = neuron.name();
        let neuron_arc: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync> = Arc::new(neuron);

        let g1 = Arc::new(Mutex::new(GanglionInprocess::new()));
        let g2 = Arc::new(Mutex::new(GanglionInprocess::new()));
        let g3 = Arc::new(Mutex::new(GanglionInprocess::new()));

        let mut thalamus = Thalamus::new(vec![g1.clone(), g2.clone(), g3.clone()]);
        // Adapt neuron across peers
        thalamus
            .adapt::<DebugStruct, DebugCodec>(neuron_arc.clone())
            .await
            .unwrap();

        // Create separate channels for each ganglion to track work distribution
        let (tx1, rx1) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(10);
        let (tx2, rx2) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(10);
        let (tx3, rx3) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(10);

        // Attach reactants to each peer individually to track which peer handles what
        {
            let mut g1_guard = g1.lock().await;
            let reactants1 = vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
                TokioMpscReactant::new(tx1),
            ))];
            g1_guard
                .react(neuron_name.clone(), reactants1, vec![])
                .await
                .unwrap();
        }
        {
            let mut g2_guard = g2.lock().await;
            let reactants2 = vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
                TokioMpscReactant::new(tx2),
            ))];
            g2_guard
                .react(neuron_name.clone(), reactants2, vec![])
                .await
                .unwrap();
        }
        {
            let mut g3_guard = g3.lock().await;
            let reactants3 = vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
                TokioMpscReactant::new(tx3),
            ))];
            g3_guard
                .react(neuron_name.clone(), reactants3, vec![])
                .await
                .unwrap();
        }

        // Send 2 messages through thalamus (expect each peer to get both)
        for i in 0..2 {
            let test_data = DebugStruct {
                foo: i,
                bar: format!("msg{i}"),
            };

            thalamus
                .transmit(erase_payload(Payload::new(test_data, neuron_arc.clone())))
                .await
                .expect("Failed to transmit");
        }

        // Give some time for async processing
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

        // Each ganglion should get exactly 2 messages
        assert_eq!(rx1.len(), 2, "Ganglion 1 should receive 2 messages");
        assert_eq!(rx2.len(), 2, "Ganglion 2 should receive 2 messages");
        assert_eq!(rx3.len(), 2, "Ganglion 3 should receive 2 messages");
    }

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

        // Create request neuron for sending work
        let request_neuron: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let request_neuron_name = request_neuron.name();
        let request_neuron_arc: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync> =
            Arc::new(request_neuron);

        let g1 = Arc::new(Mutex::new(GanglionInprocess::new()));
        let g2 = Arc::new(Mutex::new(GanglionInprocess::new()));
        let g3 = Arc::new(Mutex::new(GanglionInprocess::new()));

        let mut thalamus = Thalamus::new(vec![g1.clone(), g2.clone(), g3.clone()]);

        // Create response neuron for receiving responses using ResponseStruct/ResponseCodec
        let response_neuron: NeuronImpl<ResponseStruct, ResponseCodec> =
            NeuronImpl::new(ns.clone());
        let response_neuron_name = response_neuron.name();
        let response_neuron_arc: Arc<dyn Neuron<ResponseStruct, ResponseCodec> + Send + Sync> =
            Arc::new(response_neuron);

        // Adapt both request and response neurons across all peers
        thalamus
            .adapt::<DebugStruct, DebugCodec>(request_neuron_arc.clone())
            .await
            .unwrap();
        thalamus
            .adapt::<ResponseStruct, ResponseCodec>(response_neuron_arc.clone())
            .await
            .unwrap();

        // Channel to receive response payloads from thalamus
        let (response_tx, mut response_rx) =
            channel::<Arc<Payload<ResponseStruct, ResponseCodec>>>(20);

        // Create a custom reactant to capture responses using ResponseStruct
        #[derive(Clone)]
        struct ResponseCaptureReactant {
            sender: tokio::sync::mpsc::Sender<Arc<Payload<ResponseStruct, ResponseCodec>>>,
        }

        impl ResponseCaptureReactant {
            fn new(
                sender: tokio::sync::mpsc::Sender<Arc<Payload<ResponseStruct, ResponseCodec>>>,
            ) -> Self {
                Self { sender }
            }
        }

        impl Reactant<ResponseStruct, ResponseCodec> for ResponseCaptureReactant {
            fn react(
                &self,
                payload: Arc<Payload<ResponseStruct, ResponseCodec>>,
            ) -> Pin<
                Box<
                    dyn Future<Output = Result<(), crate::reactant::ReactantError>>
                        + Send
                        + 'static,
                >,
            > {
                let sender = self.sender.clone();
                let payload_clone = payload.clone();

                Box::pin(async move {
                    // No filtering needed - all ResponseStruct payloads are responses by definition
                    let _ = sender.try_send(payload_clone);
                    Ok(())
                })
            }

            fn erase(self: Box<Self>) -> Arc<dyn ReactantErased + Send + Sync + 'static> {
                erase_reactant(self)
            }
        }

        let response_capture_reactant = ResponseCaptureReactant::new(response_tx.clone());

        // Create a custom reactant that queues responses instead of transmitting directly
        #[derive(Clone)]
        struct ResponseGeneratingReactant {
            ganglion_id: u32,
            response_neuron: Arc<dyn Neuron<ResponseStruct, ResponseCodec> + Send + Sync>,
            queue_sender: tokio::sync::mpsc::Sender<Arc<Payload<ResponseStruct, ResponseCodec>>>,
        }

        impl ResponseGeneratingReactant {
            fn new(
                ganglion_id: u32,
                response_neuron: Arc<dyn Neuron<ResponseStruct, ResponseCodec> + Send + Sync>,
                queue_sender: tokio::sync::mpsc::Sender<
                    Arc<Payload<ResponseStruct, ResponseCodec>>,
                >,
            ) -> Self {
                Self {
                    ganglion_id,
                    response_neuron,
                    queue_sender,
                }
            }
        }

        impl Reactant<DebugStruct, DebugCodec> for ResponseGeneratingReactant {
            fn react(
                &self,
                payload: Arc<Payload<DebugStruct, DebugCodec>>,
            ) -> Pin<
                Box<
                    dyn Future<Output = Result<(), crate::reactant::ReactantError>>
                        + Send
                        + 'static,
                >,
            > {
                let ganglion_id = self.ganglion_id;
                let response_neuron = self.response_neuron.clone();
                let queue_sender = self.queue_sender.clone();
                let original_value = payload.value.clone();

                Box::pin(async move {
                    // Process all DebugStruct payloads as requests (no filtering needed)
                    // Create ResponseStruct payload indicating which ganglion processed this request
                    let response_payload = Payload::new(
                        ResponseStruct {
                            ganglion_id,
                            response_message: format!(
                                "response_from_ganglion_{}_for_{}",
                                ganglion_id, original_value.bar
                            ),
                        },
                        response_neuron,
                    );

                    // Add response payload to queue instead of transmitting directly
                    let _ = queue_sender.try_send(response_payload);
                    Ok(())
                })
            }

            fn erase(self: Box<Self>) -> Arc<dyn ReactantErased + Send + Sync + 'static> {
                erase_reactant(self)
            }
        }

        // Create queues for each ganglion's transmission loop
        let (queue1_tx, mut queue1_rx) = channel::<Arc<Payload<ResponseStruct, ResponseCodec>>>(10);
        let (queue2_tx, mut queue2_rx) = channel::<Arc<Payload<ResponseStruct, ResponseCodec>>>(10);
        let (queue3_tx, mut queue3_rx) = channel::<Arc<Payload<ResponseStruct, ResponseCodec>>>(10);

        let thalamus_arc = Arc::new(Mutex::new(thalamus));

        // Add the response capture reactant to the thalamus for the response neuron
        {
            let mut thalamus_guard = thalamus_arc.lock().await;
            let response_reactants = vec![erase_reactant::<ResponseStruct, ResponseCodec, _>(
                Box::new(response_capture_reactant),
            )];
            let future =
                thalamus_guard.react(response_neuron_name.clone(), response_reactants, vec![]);
            drop(thalamus_guard);
            future.await.unwrap();
        }

        // Start transmission loops for each ganglion
        let g1_clone = g1.clone();
        tokio::spawn(async move {
            while let Some(payload) = queue1_rx.recv().await {
                let future = {
                    let mut ganglion_guard = g1_clone.lock().await;
                    ganglion_guard.transmit(erase_payload(payload))
                };
                let _ = future.await;
            }
        });

        let g2_clone = g2.clone();
        tokio::spawn(async move {
            while let Some(payload) = queue2_rx.recv().await {
                let future = {
                    let mut ganglion_guard = g2_clone.lock().await;
                    ganglion_guard.transmit(erase_payload(payload))
                };
                let _ = future.await;
            }
        });

        let g3_clone = g3.clone();
        tokio::spawn(async move {
            while let Some(payload) = queue3_rx.recv().await {
                let future = {
                    let mut ganglion_guard = g3_clone.lock().await;
                    ganglion_guard.transmit(erase_payload(payload))
                };
                let _ = future.await;
            }
        });

        // Attach response-generating reactants to each child ganglion
        // Each reactant sends to its corresponding queue
        {
            let mut g1_guard = g1.lock().await;
            let reactants1 = vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
                ResponseGeneratingReactant::new(1, response_neuron_arc.clone(), queue1_tx),
            ))];
            let future = g1_guard.react(request_neuron_name.clone(), reactants1, vec![]);
            drop(g1_guard);
            future.await.unwrap();
        }
        {
            let mut g2_guard = g2.lock().await;
            let reactants2 = vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
                ResponseGeneratingReactant::new(2, response_neuron_arc.clone(), queue2_tx),
            ))];
            let future = g2_guard.react(request_neuron_name.clone(), reactants2, vec![]);
            drop(g2_guard);
            future.await.unwrap();
        }
        {
            let mut g3_guard = g3.lock().await;
            let reactants3 = vec![erase_reactant::<DebugStruct, DebugCodec, _>(Box::new(
                ResponseGeneratingReactant::new(3, response_neuron_arc.clone(), queue3_tx),
            ))];
            let future = g3_guard.react(request_neuron_name.clone(), reactants3, vec![]);
            drop(g3_guard);
            future.await.unwrap();
        }

        // Send 2 request messages through thalamus (each broadcast to 3 peers = 6 responses total)
        {
            for i in 0..2 {
                let payload = Payload::new(
                    DebugStruct {
                        foo: i,
                        bar: format!("request_{i}"),
                    },
                    request_neuron_arc.clone(),
                );

                let future = {
                    let mut thalamus_guard = thalamus_arc.lock().await;
                    thalamus_guard.transmit(erase_payload(payload))
                };
                future.await.unwrap();
            }
        }

        // Count response messages received by ganglion ID
        let mut count_g1 = 0;
        let mut count_g2 = 0;
        let mut count_g3 = 0;

        // Give some time for async processing and responses
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        // Collect all response messages using proper async coordination like plexus tests
        let mut total_received = 0;
        while total_received < 6 && !response_rx.is_empty() {
            if let Ok(payload) = response_rx.try_recv() {
                match payload.value.ganglion_id {
                    1 => count_g1 += 1,
                    2 => count_g2 += 1,
                    3 => count_g3 += 1,
                    _ => panic!(
                        "Unexpected ganglion ID in response: {}",
                        payload.value.ganglion_id
                    ),
                }
                total_received += 1;
            } else {
                break;
            }
        }

        // Since it's broadcast now, each ganglion should have processed both requests
        assert_eq!(count_g1, 2, "Should receive 2 responses from ganglion 1");
        assert_eq!(count_g2, 2, "Should receive 2 responses from ganglion 2");
        assert_eq!(count_g3, 2, "Should receive 2 responses from ganglion 3");
        assert_eq!(
            count_g1 + count_g2 + count_g3,
            6,
            "Total responses should be 6"
        );
    }
}