mecha10-core 0.6.2

Mecha10 core runtime and foundational types
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
//! Unit tests for Context module
//!
//! Tests core messaging functionality including:
//! - Subscribe/publish operations
//! - Consumer group behavior
//! - Error conditions
//! - Message serialization/deserialization
//! - Bounded vs unbounded channels
//!
//! These tests require a running Redis instance on localhost:6379
//! Run with: cargo test --package mecha10-core --test context_unit_tests

use mecha10_core::prelude::*;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio::time::timeout;

// Test message types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct TestMessage {
    id: u32,
    data: String,
}

impl Message for TestMessage {}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct SimpleCounter {
    count: u32,
}

impl Message for SimpleCounter {}

/// Helper to setup test environment
async fn setup() -> Result<Context> {
    // Initialize logging for tests
    let _ = tracing_subscriber::fmt()
        .with_env_filter("debug")
        .with_test_writer()
        .try_init();

    // Create context for test node
    Context::new("test_context_unit").await
}

// =============================================================================
// Basic Subscribe/Publish Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_basic_publish_subscribe() -> Result<()> {
    let ctx = setup().await?;

    // Subscribe first
    let mut rx = ctx.subscribe_raw::<TestMessage>("/test/basic_pubsub").await?;

    // Publish a message
    let msg = TestMessage {
        id: 1,
        data: "Hello, World!".to_string(),
    };
    ctx.publish_raw("/test/basic_pubsub", &msg).await?;

    // Receive the message
    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(received)) => {
            assert_eq!(received.id, msg.id);
            assert_eq!(received.data, msg.data);
        }
        Ok(None) => panic!("Channel closed unexpectedly"),
        Err(_) => panic!("Timeout waiting for message"),
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_multiple_messages_in_sequence() -> Result<()> {
    let ctx = setup().await?;

    let mut rx = ctx.subscribe_raw::<TestMessage>("/test/sequence").await?;

    // Publish 5 messages
    for i in 0..5 {
        let msg = TestMessage {
            id: i,
            data: format!("Message {}", i),
        };
        ctx.publish_raw("/test/sequence", &msg).await?;
    }

    // Receive all 5 messages in order
    for i in 0..5 {
        match timeout(Duration::from_secs(2), rx.recv()).await {
            Ok(Some(received)) => {
                assert_eq!(received.id, i);
                assert_eq!(received.data, format!("Message {}", i));
            }
            Ok(None) => panic!("Channel closed at message {}", i),
            Err(_) => panic!("Timeout at message {}", i),
        }
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_publish_before_subscribe() -> Result<()> {
    let ctx = setup().await?;

    // Publish message first
    let msg = TestMessage {
        id: 100,
        data: "Early bird".to_string(),
    };
    ctx.publish_raw("/test/early_pub", &msg).await?;

    // Small delay to ensure Redis processes the message
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Subscribe after publishing
    let mut rx = ctx.subscribe_raw::<TestMessage>("/test/early_pub").await?;

    // Should still receive the message (Redis Streams persistence)
    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(received)) => {
            assert_eq!(received.id, msg.id);
            assert_eq!(received.data, msg.data);
        }
        Ok(None) => panic!("Channel closed unexpectedly"),
        Err(_) => panic!("Timeout waiting for message - Redis may not have persisted it"),
    }

    Ok(())
}

// =============================================================================
// Consumer Group Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_single_consumer_group_behavior() -> Result<()> {
    let ctx1 = Context::new("test_consumer_1").await?;
    let ctx2 = Context::new("test_consumer_1").await?; // Same node ID = same consumer group

    // Both subscribe to same topic (same consumer group)
    let mut rx1 = ctx1.subscribe_raw::<TestMessage>("/test/consumer_group").await?;
    let mut rx2 = ctx2.subscribe_raw::<TestMessage>("/test/consumer_group").await?;

    // Publish 10 messages
    let publisher = Context::new("test_publisher").await?;
    for i in 0..10 {
        let msg = TestMessage {
            id: i,
            data: format!("Message {}", i),
        };
        publisher.publish_raw("/test/consumer_group", &msg).await?;
    }

    // Collect messages from both receivers
    let mut received1 = Vec::new();
    let mut received2 = Vec::new();

    // Try to receive 10 messages total (distributed between rx1 and rx2)
    for _ in 0..10 {
        tokio::select! {
            msg = rx1.recv() => {
                if let Some(m) = msg {
                    received1.push(m);
                }
            }
            msg = rx2.recv() => {
                if let Some(m) = msg {
                    received2.push(m);
                }
            }
            _ = tokio::time::sleep(Duration::from_millis(100)) => {
                break;
            }
        }
    }

    let total_received = received1.len() + received2.len();
    println!("rx1 received: {}, rx2 received: {}", received1.len(), received2.len());

    // With same consumer group, messages should be distributed
    // Total should be approximately 10 (allowing for Redis timing)
    assert!(
        total_received >= 5,
        "Expected at least 5 messages total, got {}",
        total_received
    );

    // Verify no duplicates (each consumer should get unique messages)
    let mut all_ids: Vec<u32> = received1.iter().map(|m| m.id).collect();
    all_ids.extend(received2.iter().map(|m| m.id));
    all_ids.sort();
    all_ids.dedup();

    // If we got duplicates, the dedup would reduce the length
    assert_eq!(
        all_ids.len(),
        total_received,
        "Detected duplicate messages across consumers"
    );

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_different_consumer_groups() -> Result<()> {
    let ctx1 = Context::new("test_consumer_a").await?;
    let ctx2 = Context::new("test_consumer_b").await?; // Different node ID = different consumer group

    // Both subscribe to same topic (different consumer groups)
    let mut rx1 = ctx1.subscribe_raw::<TestMessage>("/test/different_groups").await?;
    let mut rx2 = ctx2.subscribe_raw::<TestMessage>("/test/different_groups").await?;

    // Publish 5 messages
    let publisher = Context::new("test_group_publisher").await?;
    for i in 0..5 {
        let msg = TestMessage {
            id: i,
            data: format!("Broadcast {}", i),
        };
        publisher.publish_raw("/test/different_groups", &msg).await?;
    }

    // Both consumers should receive all messages (different consumer groups = broadcast)
    let mut received1 = Vec::new();
    let mut received2 = Vec::new();

    // Collect messages with timeout
    let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
    while tokio::time::Instant::now() < deadline && (received1.len() < 5 || received2.len() < 5) {
        tokio::select! {
            msg = rx1.recv() => {
                if let Some(m) = msg {
                    received1.push(m);
                }
            }
            msg = rx2.recv() => {
                if let Some(m) = msg {
                    received2.push(m);
                }
            }
            _ = tokio::time::sleep(Duration::from_millis(50)) => {}
        }
    }

    println!("rx1 received: {}, rx2 received: {}", received1.len(), received2.len());

    // Both should receive messages (not necessarily all due to timing)
    assert!(
        received1.len() >= 3,
        "rx1 should receive at least 3 messages, got {}",
        received1.len()
    );
    assert!(
        received2.len() >= 3,
        "rx2 should receive at least 3 messages, got {}",
        received2.len()
    );

    Ok(())
}

// =============================================================================
// Message Serialization/Deserialization Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_complex_message_serialization() -> Result<()> {
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct ComplexMessage {
        id: u64,
        name: String,
        values: Vec<f64>,
        metadata: std::collections::HashMap<String, String>,
    }
    impl Message for ComplexMessage {}

    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<ComplexMessage>("/test/complex").await?;

    // Create complex message
    let mut metadata = std::collections::HashMap::new();
    metadata.insert("key1".to_string(), "value1".to_string());
    metadata.insert("key2".to_string(), "value2".to_string());

    let msg = ComplexMessage {
        id: 42,
        name: "Complex Test".to_string(),
        values: vec![1.1, 2.2, 3.3, 4.4],
        metadata,
    };

    // Publish and receive
    ctx.publish_raw("/test/complex", &msg).await?;

    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(received)) => {
            assert_eq!(received.id, msg.id);
            assert_eq!(received.name, msg.name);
            assert_eq!(received.values, msg.values);
            assert_eq!(received.metadata, msg.metadata);
        }
        Ok(None) => panic!("Channel closed unexpectedly"),
        Err(_) => panic!("Timeout waiting for message"),
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_empty_message() -> Result<()> {
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct EmptyMessage {}
    impl Message for EmptyMessage {}

    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<EmptyMessage>("/test/empty").await?;

    let msg = EmptyMessage {};
    ctx.publish_raw("/test/empty", &msg).await?;

    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(_received)) => {
            // Successfully received empty message - test passes
        }
        Ok(None) => panic!("Channel closed unexpectedly"),
        Err(_) => panic!("Timeout waiting for message"),
    }

    Ok(())
}

// =============================================================================
// Error Condition Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_subscribe_to_same_topic_twice() -> Result<()> {
    let ctx = setup().await?;

    // Subscribe to same topic twice - should succeed
    let mut rx1 = ctx.subscribe_raw::<TestMessage>("/test/double_sub").await?;
    let mut rx2 = ctx.subscribe_raw::<TestMessage>("/test/double_sub").await?;

    // Publish a message
    let msg = TestMessage {
        id: 999,
        data: "Double sub test".to_string(),
    };
    ctx.publish_raw("/test/double_sub", &msg).await?;

    // Both receivers should get the message (same consumer group behavior)
    let recv1 = timeout(Duration::from_secs(2), rx1.recv()).await;
    let recv2 = timeout(Duration::from_secs(2), rx2.recv()).await;

    // At least one should receive (consumer group distributes)
    assert!(
        recv1.is_ok() || recv2.is_ok(),
        "At least one receiver should get the message"
    );

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_publish_to_nonexistent_topic() -> Result<()> {
    let ctx = setup().await?;

    // Publishing to a topic that has no subscribers should still succeed
    // (Redis Streams persists messages even without consumers)
    let msg = TestMessage {
        id: 404,
        data: "Nobody listening".to_string(),
    };

    let result = ctx.publish_raw("/test/nonexistent", &msg).await;
    assert!(result.is_ok(), "Publishing to nonexistent topic should succeed");

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_context_with_instance() -> Result<()> {
    let ctx = Context::new("camera_node").await?.with_instance("left");

    assert_eq!(ctx.instance(), Some("left"));

    // Verify instance-scoped publishing works
    let msg = TestMessage {
        id: 1,
        data: "Scoped message".to_string(),
    };

    // This should work without errors
    let result = ctx.publish_raw("/test/scoped", &msg).await;
    assert!(result.is_ok());

    Ok(())
}

// =============================================================================
// Channel Behavior Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_receiver_drop_stops_forwarding() -> Result<()> {
    let ctx = setup().await?;

    {
        let mut rx = ctx.subscribe_raw::<TestMessage>("/test/drop").await?;

        // Publish and receive one message
        let msg = TestMessage {
            id: 1,
            data: "First".to_string(),
        };
        ctx.publish_raw("/test/drop", &msg).await?;

        match timeout(Duration::from_secs(2), rx.recv()).await {
            Ok(Some(received)) => {
                assert_eq!(received.id, 1);
            }
            _ => panic!("Should receive first message"),
        }

        // rx is dropped here
    }

    // Publish another message after receiver is dropped
    let msg2 = TestMessage {
        id: 2,
        data: "Second".to_string(),
    };
    ctx.publish_raw("/test/drop", &msg2).await?;

    // Create new receiver - should get the second message (Redis persistence)
    let mut rx2 = ctx.subscribe_raw::<TestMessage>("/test/drop").await?;

    match timeout(Duration::from_secs(2), rx2.recv()).await {
        Ok(Some(received)) => {
            // Should receive the second message (first was acknowledged)
            assert_eq!(received.id, 2);
        }
        _ => {
            // This is acceptable - message may have been auto-acknowledged
            println!("Second receiver didn't get message (expected with auto-ack)");
        }
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_concurrent_publishers() -> Result<()> {
    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<SimpleCounter>("/test/concurrent").await?;

    // Spawn 5 concurrent publishers
    let mut handles = Vec::new();
    for i in 0..5 {
        let ctx_clone = Context::new(&format!("publisher_{}", i)).await?;
        let handle = tokio::spawn(async move {
            for j in 0..10 {
                let msg = SimpleCounter { count: i * 10 + j };
                ctx_clone.publish_raw("/test/concurrent", &msg).await.unwrap();
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        });
        handles.push(handle);
    }

    // Collect messages
    let mut received = Vec::new();
    let deadline = tokio::time::Instant::now() + Duration::from_secs(5);

    while tokio::time::Instant::now() < deadline && received.len() < 50 {
        match timeout(Duration::from_millis(100), rx.recv()).await {
            Ok(Some(msg)) => {
                received.push(msg.count);
            }
            Ok(None) => break,
            Err(_) => break,
        }
    }

    // Wait for publishers to complete
    for handle in handles {
        let _ = handle.await;
    }

    println!("Received {} messages from concurrent publishers", received.len());

    // Should receive most/all of the 50 messages
    assert!(
        received.len() >= 40,
        "Expected at least 40 messages, got {}",
        received.len()
    );

    // Verify no duplicate counts (all should be unique 0-49)
    received.sort();
    received.dedup();
    assert_eq!(received.len(), received.len(), "Should have no duplicates");

    Ok(())
}

// =============================================================================
// Performance and Stress Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_high_throughput_messaging() -> Result<()> {
    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<SimpleCounter>("/test/throughput").await?;

    // Publish 1000 messages as fast as possible
    let start = std::time::Instant::now();
    for i in 0..1000 {
        let msg = SimpleCounter { count: i };
        ctx.publish_raw("/test/throughput", &msg).await?;
    }
    let publish_duration = start.elapsed();

    println!("Published 1000 messages in {:?}", publish_duration);

    // Try to receive all messages
    let mut received = 0;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(10);

    while tokio::time::Instant::now() < deadline && received < 1000 {
        match timeout(Duration::from_millis(10), rx.recv()).await {
            Ok(Some(_)) => {
                received += 1;
            }
            Ok(None) => break,
            Err(_) => {
                if received > 0 {
                    break;
                }
            }
        }
    }

    println!("Received {} out of 1000 messages", received);

    // Should receive most messages (allowing for some loss in high throughput)
    assert!(received >= 900, "Expected at least 900 messages, got {}", received);

    Ok(())
}

// =============================================================================
// Error Condition Tests - Redis Connection Issues
// =============================================================================

#[tokio::test]
async fn test_context_creation_with_invalid_redis() -> Result<()> {
    // Temporarily set invalid Redis URL
    std::env::set_var("MECHA10_REDIS_URL", "redis://localhost:9999");

    // Attempt to create context - should fail with connection error
    let result = Context::new("test_invalid_redis").await;

    // Restore default
    std::env::remove_var("MECHA10_REDIS_URL");

    assert!(result.is_err(), "Should fail to connect to invalid Redis");

    if let Err(e) = result {
        let error_msg = format!("{}", e);
        assert!(
            error_msg.contains("Redis") || error_msg.contains("connect") || error_msg.contains("connection"),
            "Error should mention Redis or connection, got: {}",
            error_msg
        );
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_publish_with_invalid_topic_path() -> Result<()> {
    let ctx = setup().await?;

    // Try various invalid topic paths
    let invalid_topics = vec![
        "",         // Empty
        " ",        // Whitespace
        "/",        // Just root
        "no_slash", // Missing leading slash
    ];

    for topic_path in invalid_topics {
        let msg = TestMessage {
            id: 1,
            data: "test".to_string(),
        };

        // Some paths may work (Redis is permissive), but we're testing the behavior
        let result = ctx.publish_raw(topic_path, &msg).await;

        // Document the behavior - Redis may accept these
        println!("Topic '{}': {:?}", topic_path, result);
    }

    // Test is informational about topic path handling
    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_subscribe_timeout_no_messages() -> Result<()> {
    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<TestMessage>("/test/timeout").await?;

    // Don't publish anything, just wait for timeout
    let result = timeout(Duration::from_millis(500), rx.recv()).await;

    assert!(result.is_err(), "Should timeout when no messages published");

    Ok(())
}

// =============================================================================
// Type Safety Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_type_mismatch_handling() -> Result<()> {
    let ctx = setup().await?;

    // Publish a TestMessage
    let msg = TestMessage {
        id: 42,
        data: "Type test".to_string(),
    };
    ctx.publish_raw("/test/type_mismatch", &msg).await?;

    // Try to receive as SimpleCounter (different type)
    // This will fail at deserialization
    let mut rx = ctx.subscribe_raw::<SimpleCounter>("/test/type_mismatch").await?;

    // The receiver may get an error or no message due to deserialization failure
    match timeout(Duration::from_secs(1), rx.recv()).await {
        Ok(Some(_)) => {
            // If deserialization somehow succeeded, that's surprising but okay
            println!("Surprisingly deserialized different type");
        }
        Ok(None) => {
            // Channel closed - acceptable
            println!("Channel closed on type mismatch");
        }
        Err(_) => {
            // Timeout - also acceptable behavior
            println!("Timeout on type mismatch - message may be stuck");
        }
    }

    // Test passes regardless - we're documenting behavior
    Ok(())
}

// =============================================================================
// Node Instance Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_multiple_instances_same_base_node() -> Result<()> {
    // Create three instances of the same node
    let ctx_left = Context::new("camera").await?.with_instance("left");
    let ctx_right = Context::new("camera").await?.with_instance("right");
    let ctx_center = Context::new("camera").await?.with_instance("center");

    // Subscribe all three to same base topic
    let mut rx_left = ctx_left.subscribe_raw::<TestMessage>("/test/instances").await?;
    let mut rx_right = ctx_right.subscribe_raw::<TestMessage>("/test/instances").await?;
    let mut rx_center = ctx_center.subscribe_raw::<TestMessage>("/test/instances").await?;

    // Publish messages
    let publisher = Context::new("publisher").await?;
    for i in 0..9 {
        let msg = TestMessage {
            id: i,
            data: format!("Message {}", i),
        };
        publisher.publish_raw("/test/instances", &msg).await?;
    }

    // Collect from all three
    let mut left_count = 0;
    let mut right_count = 0;
    let mut center_count = 0;

    let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
    while tokio::time::Instant::now() < deadline && (left_count + right_count + center_count) < 9 {
        tokio::select! {
            msg = rx_left.recv() => {
                if msg.is_some() {
                    left_count += 1;
                }
            }
            msg = rx_right.recv() => {
                if msg.is_some() {
                    right_count += 1;
                }
            }
            msg = rx_center.recv() => {
                if msg.is_some() {
                    center_count += 1;
                }
            }
            _ = tokio::time::sleep(Duration::from_millis(50)) => {}
        }
    }

    println!(
        "Distribution: left={}, right={}, center={}",
        left_count, right_count, center_count
    );

    // Messages should be distributed across the three instances
    let total = left_count + right_count + center_count;
    assert!(total >= 6, "Should receive at least 6 out of 9 messages, got {}", total);

    // At least two instances should get messages (distribution)
    let instances_with_messages = [left_count > 0, right_count > 0, center_count > 0]
        .iter()
        .filter(|&&x| x)
        .count();
    assert!(
        instances_with_messages >= 2,
        "At least 2 instances should receive messages"
    );

    Ok(())
}

// =============================================================================
// Scoped Publishing Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_publish_to_scoped() -> Result<()> {
    let ctx = Context::new("test_scoped_pub").await?.with_instance("instance1");

    // Subscribe to the scoped topic directly
    let scoped_topic = "/test/scoped/instance1";
    let mut rx = ctx.subscribe_raw::<TestMessage>(scoped_topic).await?;

    let msg = TestMessage {
        id: 42,
        data: "Scoped message".to_string(),
    };

    // Publish using raw scoped path
    ctx.publish_raw("/test/scoped/instance1", &msg).await?;

    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(received)) => {
            assert_eq!(received.id, 42);
        }
        _ => panic!("Should receive scoped message"),
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_publish_to_instance_explicit() -> Result<()> {
    let ctx = setup().await?;

    // Subscribe to instance-specific topic
    let instance_topic = "/test/instance_pub/robot_1";
    let mut rx = ctx.subscribe_raw::<TestMessage>(instance_topic).await?;

    let msg = TestMessage {
        id: 99,
        data: "Instance message".to_string(),
    };

    // Publish to specific instance
    ctx.publish_raw("/test/instance_pub/robot_1", &msg).await?;

    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(received)) => {
            assert_eq!(received.id, 99);
        }
        _ => panic!("Should receive instance message"),
    }

    Ok(())
}

// =============================================================================
// Topic Discovery Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_discover_topics_basic() -> Result<()> {
    let ctx = setup().await?;

    // Publish to multiple topics to populate Redis
    let topics = vec![
        "/discovery/sensor/camera/front",
        "/discovery/sensor/camera/back",
        "/discovery/sensor/lidar",
    ];

    let msg = TestMessage {
        id: 1,
        data: "Discovery test".to_string(),
    };

    for topic in &topics {
        ctx.publish_raw(topic, &msg).await?;
    }

    // Small delay for Redis to process
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Discover camera topics
    let discovered = ctx.discover_topics("/discovery/sensor/camera/*").await?;

    println!("Discovered topics: {:?}", discovered);

    // Should find at least the camera topics
    assert!(discovered.len() >= 2, "Should discover at least 2 camera topics");

    Ok(())
}

// =============================================================================
// Shutdown and Lifecycle Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_shutdown_flag() -> Result<()> {
    let ctx = setup().await?;

    // Should not be shutdown initially
    assert!(!ctx.is_shutdown().await);

    // Request shutdown
    ctx.shutdown().await;

    // Should be shutdown now
    assert!(ctx.is_shutdown().await);

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_wait_for_shutdown_with_timeout() -> Result<()> {
    let ctx = setup().await?;

    // Spawn task to shutdown after delay
    let ctx_clone = ctx.clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(100)).await;
        ctx_clone.shutdown().await;
    });

    // Wait for shutdown (with safety timeout)
    match timeout(Duration::from_secs(1), ctx.wait_for_shutdown()).await {
        Ok(_) => {
            // Shutdown completed successfully
            assert!(ctx.is_shutdown().await);
        }
        Err(_) => panic!("Shutdown wait timed out"),
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_context_clone_shares_state() -> Result<()> {
    let ctx1 = setup().await?;
    let ctx2 = ctx1.clone();

    // Shutdown via clone
    ctx2.shutdown().await;

    // Original should see the shutdown
    assert!(ctx1.is_shutdown().await);

    Ok(())
}

// =============================================================================
// Large Message Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_large_message_transfer() -> Result<()> {
    let ctx = setup().await?;

    // Create a large message (1MB of data)
    let large_data = "x".repeat(1024 * 1024);
    let msg = TestMessage {
        id: 1,
        data: large_data.clone(),
    };

    let mut rx = ctx.subscribe_raw::<TestMessage>("/test/large_message").await?;

    ctx.publish_raw("/test/large_message", &msg).await?;

    match timeout(Duration::from_secs(5), rx.recv()).await {
        Ok(Some(received)) => {
            assert_eq!(received.id, 1);
            assert_eq!(received.data.len(), large_data.len());
        }
        Ok(None) => panic!("Channel closed unexpectedly"),
        Err(_) => panic!("Timeout waiting for large message"),
    }

    Ok(())
}

// =============================================================================
// UTF-8 and Special Characters Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_unicode_message_data() -> Result<()> {
    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<TestMessage>("/test/unicode").await?;

    let msg = TestMessage {
        id: 1,
        data: "Hello 世界 🌍 Здравствуй мир".to_string(),
    };

    ctx.publish_raw("/test/unicode", &msg).await?;

    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(received)) => {
            assert_eq!(received.data, msg.data);
        }
        _ => panic!("Should receive unicode message"),
    }

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_special_characters_in_topic() -> Result<()> {
    let ctx = setup().await?;

    // Topic with underscores, dots, and dashes
    let topic = "/test/special_chars/topic-1.0";
    let mut rx = ctx.subscribe_raw::<TestMessage>(topic).await?;

    let msg = TestMessage {
        id: 1,
        data: "Special topic".to_string(),
    };

    ctx.publish_raw(topic, &msg).await?;

    match timeout(Duration::from_secs(2), rx.recv()).await {
        Ok(Some(_)) => {
            // Successfully sent and received with special chars
        }
        _ => panic!("Should handle special characters in topic"),
    }

    Ok(())
}

// =============================================================================
// Edge Case Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_rapid_subscribe_unsubscribe() -> Result<()> {
    let ctx = setup().await?;

    // Rapidly create and drop subscribers
    for i in 0..10 {
        let topic = format!("/test/rapid_sub/{}", i);
        let rx = ctx.subscribe_raw::<TestMessage>(&topic).await?;
        drop(rx); // Immediately drop
    }

    // Should not crash or leak resources
    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_subscribe_to_same_topic_different_types() -> Result<()> {
    let ctx = setup().await?;

    // Subscribe with two different types to same topic
    let mut rx1 = ctx.subscribe_raw::<TestMessage>("/test/multi_type").await?;
    let mut rx2 = ctx.subscribe_raw::<SimpleCounter>("/test/multi_type").await?;

    // Publish TestMessage
    let msg = TestMessage {
        id: 1,
        data: "test".to_string(),
    };
    ctx.publish_raw("/test/multi_type", &msg).await?;

    // First subscriber should get it
    match timeout(Duration::from_millis(500), rx1.recv()).await {
        Ok(Some(_)) => {
            // Got the message as TestMessage
        }
        _ => panic!("First subscriber should receive"),
    }

    // Second subscriber will fail deserialization or timeout
    // This is expected behavior
    match timeout(Duration::from_millis(200), rx2.recv()).await {
        Ok(Some(_)) => {
            // Unexpectedly deserialized (shouldn't happen)
            println!("Warning: Type mismatch deserialized successfully");
        }
        Ok(None) => {
            // Channel closed
        }
        Err(_) => {
            // Timeout - expected for type mismatch
        }
    }

    Ok(())
}

// =============================================================================
// Context Node ID Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_node_id_retrieval() -> Result<()> {
    let ctx = Context::new("test_node_id_retrieval").await?;
    assert_eq!(ctx.node_id(), "test_node_id_retrieval");

    Ok(())
}

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_node_id_with_instance() -> Result<()> {
    let ctx = Context::new("test_node").await?.with_instance("instance_1");

    assert_eq!(ctx.node_id(), "test_node/instance_1");
    assert_eq!(ctx.instance(), Some("instance_1"));

    Ok(())
}

// =============================================================================
// Message Ordering Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_message_ordering_preserved() -> Result<()> {
    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<SimpleCounter>("/test/ordering").await?;

    // Send messages in specific order
    for i in 0..20 {
        let msg = SimpleCounter { count: i };
        ctx.publish_raw("/test/ordering", &msg).await?;
    }

    // Receive and verify order
    let mut prev_count = None;
    let mut received = 0;

    let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
    while tokio::time::Instant::now() < deadline && received < 20 {
        match timeout(Duration::from_millis(100), rx.recv()).await {
            Ok(Some(msg)) => {
                // Verify increasing order
                if let Some(prev) = prev_count {
                    assert!(
                        msg.count > prev,
                        "Messages should be in order: got {} after {}",
                        msg.count,
                        prev
                    );
                }
                prev_count = Some(msg.count);
                received += 1;
            }
            Ok(None) => break,
            Err(_) => break,
        }
    }

    assert!(received >= 15, "Should receive most messages in order");

    Ok(())
}

// =============================================================================
// Receiver Try Recv Tests
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis to be running
async fn test_receiver_try_recv_integration() -> Result<()> {
    let ctx = setup().await?;
    let mut rx = ctx.subscribe_raw::<TestMessage>("/test/try_recv").await?;

    // Initially empty
    assert!(rx.try_recv().is_err());

    // Publish message
    let msg = TestMessage {
        id: 42,
        data: "Try recv test".to_string(),
    };
    ctx.publish_raw("/test/try_recv", &msg).await?;

    // Wait for message to arrive
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Should be able to try_recv
    let received = rx.try_recv();
    assert!(received.is_ok(), "Should have message available");

    Ok(())
}