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
// 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::backpressure::{BackpressureConfig, BackpressureQueue};
use crate::codec::{Codec, CodecName};
use crate::dendrite::{Dendrite, DendriteError};
use crate::erasure::neuron::{NeuronErased, NeuronErasedWrapper};
use crate::erasure::reactant::ReactantErased;
use crate::logging::LogTrace;
use crate::neuron::Neuron;
use crate::payload::{Payload, PayloadRaw};
use crate::reactant::{ErrorReactant, Reactant, ReactantRaw};
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use parking_lot::RwLock;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum SynapseError {
    #[error("Queue for neuron '{neuron_name}' is full")]
    QueueFull { neuron_name: String },
    #[error(transparent)]
    Dendrite(#[from] DendriteError),
    #[error("Type conversion failed for neuron '{neuron_name}'")]
    NeuronTypeConversion { neuron_name: String },
    #[error("Type conversion failed for reactant in neuron '{neuron_name}'")]
    ReactantTypeConversion { neuron_name: String },
    #[error("No dendrite available for processing in neuron '{neuron_name}'")]
    NoDendrite { neuron_name: String },
}

use tracing::Instrument;

pub trait SynapseInternal<T, C>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    fn neuron(&self) -> Arc<dyn Neuron<T, C> + Send + Sync>;
    fn transduce(
        &self,
        payload: Arc<Payload<T, C>>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, SynapseError>> + Send + 'static>>;
    fn transmit(
        &self,
        payload: Arc<Payload<T, C>>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, SynapseError>> + Send + 'static>>;
    fn react(
        &mut self,
        reactants: Vec<Arc<dyn Reactant<T, C> + Send + Sync>>,
        error_reactants: Vec<Arc<dyn ErrorReactant<T, C> + Send + Sync>>,
    ) -> Result<(), SynapseError>;
}

pub trait SynapseExternal<T, C>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    fn neuron(&self) -> Arc<dyn Neuron<T, C> + Send + Sync>;
    fn transduce(
        &self,
        payload: Arc<PayloadRaw<T, C>>,
    ) -> impl Future<Output = Result<(Vec<()>, Vec<()>), SynapseError>> + Send + 'static;
    fn transmit(
        &self,
        payload: Arc<PayloadRaw<T, C>>,
    ) -> impl Future<Output = Result<(Vec<()>, Vec<()>), SynapseError>> + Send + 'static;
    fn react(
        &mut self,
        reactants: Vec<Arc<dyn Reactant<T, C> + Send + Sync>>,
        raw_reactants: Vec<Arc<dyn ReactantRaw<T, C> + Send + Sync>>,
        error_reactants: Vec<Arc<dyn ErrorReactant<T, C> + Send + Sync>>,
    ) -> Result<(), SynapseError>;
}

/// Trait for abstracting raw data transmission.
pub trait RawSender: Send + Sync {
    fn send(
        &self,
        topic: &str,
        data: Vec<u8>,
    ) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
}

/// A wrapper for RawSender that applies backpressure buffering.
pub struct BackpressureSender<S: RawSender> {
    queue: Arc<BackpressureQueue<(String, Vec<u8>)>>,
    _marker: PhantomData<S>,
}

impl<S: RawSender + 'static> BackpressureSender<S> {
    pub fn new(inner: S, config: BackpressureConfig, neuron_name: String) -> Self {
        let inner_arc = Arc::new(inner);
        let inner_clone = inner_arc.clone();

        let queue = BackpressureQueue::<(String, Vec<u8>)>::new(
            neuron_name,
            config,
            move |(topic, data)| {
                let s = inner_clone.clone();
                async move {
                    if let Err(e) = s.send(&topic, data).await {
                        eprintln!("BackpressureSender failed to send: {}", e);
                    }
                }
            },
        );

        Self {
            queue: Arc::new(queue),
            _marker: PhantomData,
        }
    }
}

impl<S: RawSender + 'static> RawSender for BackpressureSender<S> {
    fn send(
        &self,
        topic: &str,
        data: Vec<u8>,
    ) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> {
        let q = self.queue.clone();
        let topic = topic.to_string();
        Box::pin(async move {
            q.push((topic, data)).await.map_err(|e| e.to_string())
        })
    }
}

/// A wrapper for external synapses that adds backpressure management.
pub struct BackpressureExternalSynapse<T, C, S>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Send + Sync + 'static,
    S: SynapseExternal<T, C> + Send + Sync + 'static,
{
    inner: Arc<RwLock<S>>,
    neuron: Arc<dyn Neuron<T, C> + Send + Sync>,
    queue: Arc<BackpressureQueue<Arc<PayloadRaw<T, C>>>>,
    _phantom: PhantomData<(T, C)>,
}

impl<T, C, S> BackpressureExternalSynapse<T, C, S>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Send + Sync + 'static,
    S: SynapseExternal<T, C> + Send + Sync + 'static,
{
    pub fn new(synapse: S, config: BackpressureConfig) -> Self {
        let neuron = synapse.neuron();
        let neuron_name = neuron.name();
        let synapse_arc = Arc::new(RwLock::new(synapse));
        let inner_clone = synapse_arc.clone();

        let queue = BackpressureQueue::new(
            neuron_name,
            config,
            move |payload: Arc<PayloadRaw<T, C>>| {
                let s = inner_clone.clone();
                async move {
                    let future = {
                        let guard = s.read();
                        guard.transmit(payload)
                    };
                    let _ = future.await;
                }
            },
        );

        Self {
            inner: synapse_arc,
            neuron,
            queue: Arc::new(queue),
            _phantom: PhantomData,
        }
    }
}

impl<T, C, S> SynapseExternal<T, C> for BackpressureExternalSynapse<T, C, S>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Send + Sync + 'static,
    S: SynapseExternal<T, C> + Send + Sync + 'static,
{
    fn neuron(&self) -> Arc<dyn Neuron<T, C> + Send + Sync> {
        self.neuron.clone()
    }

    fn transduce(
        &self,
        payload: Arc<PayloadRaw<T, C>>,
    ) -> impl Future<Output = Result<(Vec<()>, Vec<()>), SynapseError>> + Send + 'static {
        self.transmit(payload)
    }

    fn transmit(
        &self,
        payload: Arc<PayloadRaw<T, C>>,
    ) -> impl Future<Output = Result<(Vec<()>, Vec<()>), SynapseError>> + Send + 'static {
        let q = self.queue.clone();
        Box::pin(async move {
            q.push(payload).await?;
            Ok((vec![], vec![]))
        })
    }

    fn react(
        &mut self,
        reactants: Vec<Arc<dyn Reactant<T, C> + Send + Sync>>,
        raw_reactants: Vec<Arc<dyn ReactantRaw<T, C> + Send + Sync>>,
        error_reactants: Vec<Arc<dyn ErrorReactant<T, C> + Send + Sync>>,
    ) -> Result<(), SynapseError> {
        let mut guard = self.inner.write();
        guard.react(reactants, raw_reactants, error_reactants)
    }
}

pub struct SynapseInprocess<T, C>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Sync + Send + 'static,
{
    neuron: Arc<dyn Neuron<T, C> + Send + Sync>,
    dendrite: Option<Dendrite<T, C>>,
    _codec_marker: PhantomData<fn() -> &'static ()>,
}

impl<T, C> SynapseInprocess<T, C>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Sync + Send + 'static,
{
    pub fn new(
        neuron: Arc<dyn Neuron<T, C> + Send + Sync>,
        reactants: Vec<Arc<dyn Reactant<T, C> + Send + Sync>>,
        error_reactants: Vec<Arc<dyn ErrorReactant<T, C> + Send + Sync>>,
    ) -> Self {
        let dendrite = if !reactants.is_empty() || !error_reactants.is_empty() {
            Some(Dendrite::new(neuron.clone(), reactants, error_reactants))
        } else {
            None
        };
        Self {
            neuron,
            dendrite,
            _codec_marker: PhantomData,
        }
    }

    /// Create a new SynapseInprocess from type-erased neuron and reactants
    /// Returns None if the types don't match
    pub fn from_erased(
        neuron: Arc<dyn NeuronErased + Send + Sync + 'static>,
        reactants: Vec<Arc<dyn ReactantErased + Send + Sync + 'static>>,
    ) -> Option<Self>
    where
        T: 'static,
        C: 'static,
    {
        use std::any::TypeId;

        // First, check if the neuron's type parameters match what we need
        let neuron_type_id = neuron.payload_type_id();
        let codec_type_id = neuron.codec_type_id();

        if neuron_type_id != TypeId::of::<T>() || codec_type_id != TypeId::of::<C>() {
            return None;
        }

        // Try to convert the neuron to the correct type safely using Any downcast
        let typed_neuron = match neuron.as_any().downcast_ref::<NeuronErasedWrapper<T, C>>() {
            Some(wrapper) => wrapper.get_typed_neuron(),
            None => return None,
        };

        // Convert reactants
        let typed_reactants: Vec<_> = reactants
            .into_iter()
            .filter_map(|erased_reactant| {
                // Check if this reactant's type parameters match
                if erased_reactant.payload_type_id() != TypeId::of::<T>()
                    || erased_reactant.codec_type_id() != TypeId::of::<C>()
                {
                    return None;
                }

                // Try to convert to the correct type using safe Any downcast
                let any_arc = erased_reactant.clone_to_any();
                any_arc
                    .downcast::<Arc<dyn Reactant<T, C> + Send + Sync + 'static>>()
                    .ok()
                    .map(|boxed_arc| (*boxed_arc).clone())
            })
            .collect();

        // Create a new SynapseInprocess with the typed objects
        Some(Self::new(typed_neuron.clone(), typed_reactants, vec![]))
    }
}

impl<T, C> SynapseInternal<T, C> for SynapseInprocess<T, C>
where
    C: Codec<T> + CodecName + Send + Sync + 'static,
    T: Sync + Send + 'static,
{
    fn neuron(&self) -> Arc<dyn Neuron<T, C> + Send + Sync> {
        self.neuron.clone()
    }

    fn transduce(
        &self,
        payload: Arc<Payload<T, C>>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, SynapseError>> + Send + 'static>> {
        let span = payload.span_debug("SynapseInprocess::transduce");
        match &self.dendrite {
            Some(dendrite) => {
                let future = dendrite.transduce(payload);
                Box::pin(
                    async move {
                        tracing::debug!("SynapseInprocess::transduce calling dendrite.transduce");
                        future.await.map_err(SynapseError::from)
                    }
                    .instrument(span),
                )
            }
            None => Box::pin(
                async move {
                    tracing::debug!("SynapseInprocess::transduce no dendrite, returning empty vec");
                    Ok(vec![])
                }
                .instrument(span),
            ),
        }
    }

    fn transmit(
        &self,
        payload: Arc<Payload<T, C>>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<()>, SynapseError>> + Send + 'static>> {
        let span = payload.span_debug("SynapseInprocess::transmit");
        // This is an internal synapse so transmit directly to any reactants we have
        let future = self.transduce(payload);
        Box::pin(
            async move {
                tracing::debug!("SynapseInprocess::transmit called");
                future.await
            }
            .instrument(span),
        )
    }

    fn react(
        &mut self,
        reactants: Vec<Arc<dyn Reactant<T, C> + Send + Sync>>,
        error_reactants: Vec<Arc<dyn ErrorReactant<T, C> + Send + Sync>>,
    ) -> Result<(), SynapseError> {
        if reactants.is_empty() && error_reactants.is_empty() {
            return Ok(());
        }

        match &self.dendrite {
            Some(dendrite) => {
                // Add reactants to existing dendrite
                dendrite.add_reactants(reactants)?;
                dendrite.add_error_reactants(error_reactants)?;
            }
            None => {
                // Create a new dendrite with the stored neuron and reactants
                self.dendrite = Some(Dendrite::new(
                    self.neuron.clone(),
                    reactants,
                    error_reactants,
                ));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::logging::TraceContext;
    use crate::neuron::NeuronImpl;
    use crate::payload::PayloadRaw;
    use crate::test_utils::{
        DebugCodec, DebugStruct, SynapseExternalInprocess, TokioMpscReactant, TokioMpscReactantRaw,
        test_namespace,
    };
    use tokio::sync::mpsc::channel;
    use uuid::Uuid;

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

        let (tx, mut rx) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(10);

        let reactants: Vec<Arc<dyn Reactant<DebugStruct, DebugCodec> + Send + Sync>> = vec![
            Arc::new(TokioMpscReactant { sender: tx.clone() }),
            Arc::new(TokioMpscReactant { sender: tx.clone() }),
        ];
        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync> = Arc::new(neuron_impl);
        let synapse = SynapseInprocess::new(neuron.clone(), reactants, vec![]);

        let debug_struct = Arc::new(DebugStruct {
            foo: 42,
            bar: "test_value".to_owned(),
        });
        let correlation_id = Uuid::now_v7();
        let span_id = Uuid::now_v7().as_u128() as u64;
        let _ = synapse
            .transmit(
                Payload::builder()
                    .value((*debug_struct).clone())
                    .correlation_id(correlation_id)
                    .neuron(neuron.clone())
                    .span_id(span_id)
                    .build()
                    .unwrap(),
            )
            .await;

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

        let p = rx.recv().await.unwrap();
        assert_eq!(p.value, debug_struct);
        assert_eq!(p.correlation_id(), correlation_id);
        assert_eq!(p.span_id(), span_id);
        assert_eq!(rx.len(), 1);
        let p2 = rx.recv().await.unwrap();
        assert_eq!(p2.value, debug_struct);
        assert_eq!(p2.correlation_id(), correlation_id);
        assert_eq!(p2.span_id(), span_id);
        assert_eq!(rx.len(), 0);

        let debug_struct_2 = Arc::new(DebugStruct {
            foo: 49,
            bar: "foo_bar".to_owned(),
        });
        let correlation_id_2 = Uuid::now_v7();
        let span_id_2 = Uuid::now_v7().as_u128() as u64;
        let _ = synapse
            .transmit(
                Payload::builder()
                    .value((*debug_struct_2).clone())
                    .correlation_id(correlation_id_2)
                    .neuron(neuron.clone())
                    .span_id(span_id_2)
                    .build()
                    .unwrap(),
            )
            .await;

        let p3 = rx.recv().await.unwrap();
        assert_eq!(p3.value, debug_struct_2);
        assert_eq!(p3.correlation_id(), correlation_id_2);
        assert_eq!(p3.span_id(), span_id_2);
        assert_eq!(rx.len(), 1);
        let p4 = rx.recv().await.unwrap();
        assert_eq!(p4.value, debug_struct_2);
        assert_eq!(p4.correlation_id(), correlation_id_2);
        assert_eq!(p4.span_id(), span_id_2);
        assert_eq!(rx.len(), 0);
    }

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

        // Create synapse with None reactants
        let synapse = SynapseInprocess::new(neuron.clone(), vec![], vec![]);

        let debug_struct = Arc::new(DebugStruct {
            foo: 42,
            bar: "test_value".to_owned(),
        });
        let correlation_id = Uuid::now_v7();
        let span_id = Uuid::now_v7().as_u128() as u64;

        // This should return empty vector since dendrite is None
        let result = synapse
            .transmit(
                Payload::builder()
                    .value((*debug_struct).clone())
                    .correlation_id(correlation_id)
                    .neuron(neuron.clone())
                    .span_id(span_id)
                    .build()
                    .unwrap(),
            )
            .await;

        assert_eq!(
            result.expect("Should succeed").len(),
            0,
            "Should return empty vector when dendrite is None"
        );
    }

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

        // Create synapse with None reactants and raw_reactants
        let synapse = SynapseExternalInprocess::new(neuron.clone(), vec![], vec![], vec![]);

        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 direct_neuron_encoder: NeuronImpl<DebugStruct, DebugCodec> =
            NeuronImpl::new(ns.clone());
        let encoded = direct_neuron_encoder
            .encode(debug_struct_arc.as_ref())
            .expect("Failed to encode");
        let span_id = Uuid::now_v7().as_u128() as u64;

        // This should return empty vectors since dendrite_decoder is None
        let result = synapse
            .transmit(Arc::new(PayloadRaw {
                value: Arc::new(encoded.clone()),
                neuron: neuron.clone(),
                trace: TraceContext::from_parts(correlation_id, span_id, None),
            }))
            .await
            .expect("Should succeed");

        assert_eq!(
            result.0.len(),
            0,
            "Should return empty vector for reactants when dendrite_decoder is None"
        );
        assert_eq!(
            result.1.len(),
            0,
            "Should return empty vector for raw_reactants when dendrite_decoder is None"
        );
    }

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

        let (tx, mut rx) = channel::<Arc<Payload<DebugStruct, DebugCodec>>>(1);
        let (tx_raw, mut rx_raw) = channel::<Arc<PayloadRaw<DebugStruct, DebugCodec>>>(1);

        let reactants: Vec<Arc<dyn Reactant<DebugStruct, DebugCodec> + Send + Sync>> =
            vec![Arc::new(TokioMpscReactant { sender: tx.clone() })];
        let raw_reactants: Vec<Arc<dyn ReactantRaw<DebugStruct, DebugCodec> + Send + Sync>> =
            vec![Arc::new(TokioMpscReactantRaw {
                sender: tx_raw.clone(),
            })];
        let neuron_impl: NeuronImpl<DebugStruct, DebugCodec> = NeuronImpl::new(ns.clone());
        let neuron: Arc<dyn Neuron<DebugStruct, DebugCodec> + Send + Sync> =
            Arc::new(neuron_impl.clone());
        let synapse =
            SynapseExternalInprocess::new(neuron.clone(), reactants, raw_reactants, vec![]);

        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 direct_neuron_encoder: NeuronImpl<DebugStruct, DebugCodec> =
            NeuronImpl::new(ns.clone());
        let encoded = direct_neuron_encoder
            .encode(debug_struct_arc.as_ref())
            .expect("Failed to encode");

        let span_id = Uuid::now_v7().as_u128() as u64;

        let _ = synapse
            .transmit(Arc::new(PayloadRaw {
                value: Arc::new(encoded.clone()),
                neuron: neuron.clone(),
                trace: TraceContext::from_parts(correlation_id, span_id, None),
            }))
            .await;

        let p = tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv())
            .await
            .expect("Timeout rx1")
            .expect("Closed rx1");
        assert_eq!(p.value, debug_struct_arc);
        assert_eq!(p.correlation_id(), correlation_id);
        assert_eq!(p.span_id(), span_id);

        let p_raw = tokio::time::timeout(std::time::Duration::from_millis(100), rx_raw.recv())
            .await
            .expect("Timeout raw_rx1")
            .expect("Closed raw_rx1");
        assert_eq!(p_raw.value.as_slice(), encoded.as_slice());
        assert_eq!(p_raw.correlation_id(), correlation_id);
        assert_eq!(p_raw.span_id(), span_id);

        let debug_struct_2_value = DebugStruct {
            foo: 49,
            bar: "foo_bar".to_owned(),
        };
        let debug_struct_2_arc = Arc::new(debug_struct_2_value);
        let correlation_id_2 = Uuid::now_v7();
        let encoded_2 = direct_neuron_encoder
            .encode(debug_struct_2_arc.as_ref())
            .expect("Failed to encode");
        let span_id_2 = Uuid::now_v7().as_u128() as u64;
        let _ = synapse
            .transmit(Arc::new(PayloadRaw {
                value: Arc::new(encoded_2.clone()),
                neuron: neuron.clone(),
                trace: TraceContext::from_parts(correlation_id_2, span_id_2, None),
            }))
            .await;

        let p2 = tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv())
            .await
            .expect("Timeout rx2")
            .expect("Closed rx2");
        assert_eq!(p2.value, debug_struct_2_arc);
        assert_eq!(p2.correlation_id(), correlation_id_2);
        assert_eq!(p2.span_id(), span_id_2);

        let p_raw2 = tokio::time::timeout(std::time::Duration::from_millis(100), rx_raw.recv())
            .await
            .expect("Timeout raw_rx2")
            .expect("Closed raw_rx2");
        assert_eq!(p_raw2.value.as_slice(), encoded_2.as_slice());
        assert_eq!(p_raw2.correlation_id(), correlation_id_2);
        assert_eq!(p_raw2.span_id(), span_id_2);
    }
}