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
//! Comprehensive unit tests for node.rs module
//!
//! Tests node lifecycle management including:
//! - NodeImpl trait behavior (init, run, shutdown, health_check)
//! - Node lifecycle states (Starting, Running, Stopping, Stopped, Crashed)
//! - Graceful and forced shutdown
//! - Error handling during startup and shutdown
//! - Resource cleanup verification
//! - Multiple nodes in same process
//! - Edge cases (double start, double stop, start after stop)
//! - RateConfig trait functionality
//! - HealthStatusExt helper methods
//! - HealthReportingConfig
//!
//! # Test Organization
//!
//! Total: 40 tests
//! - 25 tests run without Redis (unit tests)
//! - 15 tests require Redis (integration tests, marked with #[ignore])
//!
//! ## Test Categories:
//!
//! 1. **NodeImpl Trait Tests (3 tests)**
//!    - Initialization success/failure
//!    - Config validation
//!
//! 2. **Node Lifecycle Tests (8 tests)**
//!    - State transitions (Starting → Running → Stopped)
//!    - Crashed state handling
//!    - Run method execution
//!    - Error propagation
//!
//! 3. **Shutdown Tests (3 tests)**
//!    - Graceful shutdown
//!    - Shutdown errors
//!    - Double shutdown (idempotency)
//!
//! 4. **Health Check Tests (5 tests)**
//!    - Default health checks
//!    - Custom health checks
//!    - Unhealthy state
//!    - Multiple health checks
//!    - is_healthy() method
//!
//! 5. **HealthStatusExt Tests (3 tests)**
//!    - healthy() constructor
//!    - unhealthy() constructor
//!    - String conversion
//!
//! 6. **RateConfig Tests (5 tests)**
//!    - rate_hz() method
//!    - period() calculation
//!    - create_interval() usage
//!    - Integration with nodes
//!
//! 7. **HealthReportingConfig Tests (3 tests)**
//!    - Default configuration
//!    - Custom configuration
//!    - Clone behavior
//!
//! 8. **Edge Cases & Error Tests (6 tests)**
//!    - Concurrent operations
//!    - State queries during lifecycle
//!    - Multiple nodes in same process
//!    - Node cloning and shared state
//!    - Context shutdown signals
//!    - Complete lifecycle integration
//!
//! 9. **Performance Tests (3 tests)**
//!    - Rapid node creation
//!    - Rapid health checks
//!    - Rapid state queries
//!
//! 10. **Debug Trait Tests (1 test)**
//!     - Verify Debug implementations
//!
//! # Running Tests
//!
//! ```bash
//! # Run all tests (requires Redis for 15 tests)
//! cargo test --package mecha10-core --test node_unit_tests
//!
//! # Run only unit tests (no Redis required)
//! cargo test --package mecha10-core --test node_unit_tests
//!
//! # Run integration tests (requires Redis)
//! cargo test --package mecha10-core --test node_unit_tests -- --ignored
//!
//! # Run specific test
//! cargo test --package mecha10-core --test node_unit_tests test_node_init_success
//! ```

use mecha10_core::prelude::*;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::{sleep, timeout};

// =============================================================================
// Test Node Implementations
// =============================================================================

/// Simple test node that completes successfully
#[derive(Debug, Clone)]
struct SuccessNode {
    #[allow(dead_code)]
    config: SuccessConfig,
    run_count: Arc<AtomicU32>,
    shutdown_count: Arc<AtomicU32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SuccessConfig {
    value: i32,
}

#[async_trait]
impl NodeImpl for SuccessNode {
    type Config = SuccessConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            config,
            run_count: Arc::new(AtomicU32::new(0)),
            shutdown_count: Arc::new(AtomicU32::new(0)),
        })
    }

    async fn run(&mut self, _ctx: &Context) -> Result<()> {
        self.run_count.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }

    async fn shutdown(&mut self) -> Result<()> {
        self.shutdown_count.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }

    async fn health_check(&self) -> HealthStatus {
        HealthStatus::healthy("SuccessNode is healthy")
    }
}

/// Node that fails during initialization
#[derive(Debug)]
struct FailInitNode;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct FailInitConfig;

#[async_trait]
impl NodeImpl for FailInitNode {
    type Config = FailInitConfig;

    async fn init(_config: Self::Config) -> Result<Self> {
        Err(Mecha10Error::NodeInit("Initialization failed".to_string()))
    }

    async fn run(&mut self, _ctx: &Context) -> Result<()> {
        Ok(())
    }
}

/// Node that fails during run
#[derive(Debug, Clone)]
struct FailRunNode {
    should_fail: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct FailRunConfig {
    should_fail: bool,
}

#[async_trait]
impl NodeImpl for FailRunNode {
    type Config = FailRunConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            should_fail: config.should_fail,
        })
    }

    async fn run(&mut self, _ctx: &Context) -> Result<()> {
        if self.should_fail {
            Err(Mecha10Error::Runtime("Run failed".to_string()))
        } else {
            Ok(())
        }
    }
}

/// Node that fails during shutdown
#[derive(Debug, Clone)]
struct FailShutdownNode {
    shutdown_error: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct FailShutdownConfig {
    shutdown_error: bool,
}

#[async_trait]
impl NodeImpl for FailShutdownNode {
    type Config = FailShutdownConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            shutdown_error: config.shutdown_error,
        })
    }

    async fn run(&mut self, _ctx: &Context) -> Result<()> {
        Ok(())
    }

    async fn shutdown(&mut self) -> Result<()> {
        if self.shutdown_error {
            Err(Mecha10Error::Shutdown("Shutdown failed".to_string()))
        } else {
            Ok(())
        }
    }
}

/// Node that runs for a specific duration
#[derive(Debug, Clone)]
struct TimedNode {
    duration_ms: u64,
    started: Arc<AtomicBool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TimedConfig {
    duration_ms: u64,
}

#[async_trait]
impl NodeImpl for TimedNode {
    type Config = TimedConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            duration_ms: config.duration_ms,
            started: Arc::new(AtomicBool::new(false)),
        })
    }

    async fn run(&mut self, ctx: &Context) -> Result<()> {
        self.started.store(true, Ordering::SeqCst);
        sleep(Duration::from_millis(self.duration_ms)).await;

        // Check for shutdown signal
        if ctx.is_shutdown().await {
            return Ok(());
        }

        Ok(())
    }
}

/// Node with custom health check
#[derive(Debug, Clone)]
struct HealthyNode {
    healthy: Arc<Mutex<bool>>,
    failure_count: Arc<AtomicU32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct HealthyConfig {
    initially_healthy: bool,
}

#[async_trait]
impl NodeImpl for HealthyNode {
    type Config = HealthyConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            healthy: Arc::new(Mutex::new(config.initially_healthy)),
            failure_count: Arc::new(AtomicU32::new(0)),
        })
    }

    async fn run(&mut self, ctx: &Context) -> Result<()> {
        // Run indefinitely until shutdown
        while !ctx.is_shutdown().await {
            sleep(Duration::from_millis(10)).await;
        }
        Ok(())
    }

    async fn health_check(&self) -> HealthStatus {
        let is_healthy = *self.healthy.lock().await;
        if is_healthy {
            HealthStatus {
                healthy: true,
                last_check: now_micros(),
                failure_count: 0,
                message: Some("Node is healthy".to_string()),
            }
        } else {
            let failures = self.failure_count.fetch_add(1, Ordering::SeqCst) + 1;
            HealthStatus {
                healthy: false,
                last_check: now_micros(),
                failure_count: failures,
                message: Some("Node is unhealthy".to_string()),
            }
        }
    }
}

/// Node with configurable rate
#[derive(Debug, Clone)]
struct RateConfigNode {
    config: RateNodeConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct RateNodeConfig {
    rate_hz: f32,
}

impl RateConfig for RateNodeConfig {
    fn rate_hz(&self) -> f32 {
        self.rate_hz
    }
}

#[async_trait]
impl NodeImpl for RateConfigNode {
    type Config = RateNodeConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self { config })
    }

    async fn run(&mut self, ctx: &Context) -> Result<()> {
        let mut interval = self.config.create_interval();

        for _ in 0..3 {
            interval.tick().await;
            if ctx.is_shutdown().await {
                break;
            }
        }

        Ok(())
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Create a test context
///
/// Sets environment variable to use test Redis URL
async fn create_test_context() -> Context {
    // Set test Redis URL to avoid config file dependency
    std::env::set_var("REDIS_URL", "redis://localhost:6379");

    Context::builder("test_node")
        .with_redis("redis://localhost:6379")
        .build()
        .await
        .expect("Failed to create test context - is Redis running on localhost:6379?")
}

// =============================================================================
// NodeImpl Trait Tests - Initialization
// =============================================================================

#[tokio::test]
async fn test_node_init_success() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await;

    assert!(node.is_ok(), "Node initialization should succeed");
    let node = node.unwrap();

    // Verify initial state
    let state = node.state().await;
    assert_eq!(state, NodeState::Starting);
}

#[tokio::test]
async fn test_node_init_failure() {
    let config = FailInitConfig;
    let result = Node::<FailInitNode>::from_config(config).await;

    assert!(result.is_err(), "Node initialization should fail");

    if let Err(e) = result {
        assert!(e.to_string().contains("Initialization failed"));
    }
}

#[tokio::test]
async fn test_node_init_with_config_validation() {
    // Test that config is properly passed to init
    let config = SuccessConfig { value: 123 };
    let node = Node::<SuccessNode>::from_config(config).await;

    assert!(node.is_ok());
}

// =============================================================================
// Node Lifecycle Tests - State Transitions
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_state_starting_to_running() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    // Initial state should be Starting
    assert_eq!(node.state().await, NodeState::Starting);

    // Start the node (it completes immediately)
    let ctx = create_test_context().await;
    let result = node.start(ctx).await;

    assert!(result.is_ok());

    // After completion, should be Stopped
    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_state_running_to_stopped_on_success() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;
    let result = node.start(ctx).await;

    assert!(result.is_ok());
    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_state_crashed_on_run_error() {
    let config = FailRunConfig { should_fail: true };
    let node = Node::<FailRunNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;
    let result = node.start(ctx).await;

    assert!(result.is_err(), "Node should fail during run");

    // Should transition to Crashed state
    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_state_stopping_to_stopped() {
    let config = TimedConfig { duration_ms: 100 };
    let node = Node::<TimedNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;

    // Start node in background
    let node_clone = node.clone();
    let ctx_clone = ctx.clone();
    tokio::spawn(async move {
        let _ = node_clone.start(ctx_clone).await;
    });

    // Wait a bit for node to start
    sleep(Duration::from_millis(10)).await;

    // Shutdown the node
    let shutdown_result = node.shutdown().await;
    assert!(shutdown_result.is_ok());

    // Should be in Stopped state
    assert_eq!(node.state().await, NodeState::Stopped);
}

// =============================================================================
// Node Lifecycle Tests - Run Method
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_run_executes() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;
    let result = node.start(ctx).await;

    assert!(result.is_ok());
    // Note: We can't check run_count without exposing internal state
    // This is verified by the node completing successfully
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_run_with_duration() {
    let config = TimedConfig { duration_ms: 50 };
    let node = Node::<TimedNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;

    let start = Instant::now();
    let result = node.start(ctx).await;
    let elapsed = start.elapsed();

    assert!(result.is_ok());
    assert!(elapsed >= Duration::from_millis(50));
    assert!(elapsed < Duration::from_millis(200)); // Reasonable upper bound
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_run_error_propagates() {
    let config = FailRunConfig { should_fail: true };
    let node = Node::<FailRunNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;
    let result = node.start(ctx).await;

    assert!(result.is_err());

    if let Err(e) = result {
        assert!(e.to_string().contains("Run failed"));
    }
}

// =============================================================================
// Node Lifecycle Tests - Shutdown
// =============================================================================

#[tokio::test]
async fn test_node_shutdown_success() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let result = node.shutdown().await;

    assert!(result.is_ok());
    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
async fn test_node_shutdown_error_still_transitions() {
    let config = FailShutdownConfig { shutdown_error: true };
    let node = Node::<FailShutdownNode>::from_config(config).await.unwrap();

    let result = node.shutdown().await;

    // Shutdown should fail but node should still transition to Stopped
    assert!(result.is_err());
    assert_eq!(node.state().await, NodeState::Stopped);

    if let Err(e) = result {
        assert!(e.to_string().contains("Shutdown failed"));
    }
}

#[tokio::test]
async fn test_node_double_shutdown() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    // First shutdown
    let result1 = node.shutdown().await;
    assert!(result1.is_ok());

    // Second shutdown (should be idempotent)
    let result2 = node.shutdown().await;
    assert!(result2.is_ok());

    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_shutdown_called_after_start() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;

    // Start and complete
    let result = node.start(ctx).await;
    assert!(result.is_ok());

    // Shutdown is already called internally
    assert_eq!(node.state().await, NodeState::Stopped);
}

// =============================================================================
// Health Check Tests
// =============================================================================

#[tokio::test]
async fn test_node_health_check_default() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let health = node.health_check().await;

    assert!(health.healthy);
    assert!(health.message.is_some());
}

#[tokio::test]
async fn test_node_health_check_custom() {
    let config = HealthyConfig {
        initially_healthy: true,
    };
    let node = Node::<HealthyNode>::from_config(config).await.unwrap();

    let health = node.health_check().await;

    assert!(health.healthy);
    assert_eq!(health.failure_count, 0);
}

#[tokio::test]
async fn test_node_health_check_unhealthy() {
    let config = HealthyConfig {
        initially_healthy: false,
    };
    let node = Node::<HealthyNode>::from_config(config).await.unwrap();

    let health = node.health_check().await;

    assert!(!health.healthy);
    assert!(health.failure_count > 0);
}

#[tokio::test]
async fn test_node_health_check_multiple_calls() {
    let config = HealthyConfig {
        initially_healthy: false,
    };
    let node = Node::<HealthyNode>::from_config(config).await.unwrap();

    // First check
    let health1 = node.health_check().await;
    assert!(!health1.healthy);
    let failures1 = health1.failure_count;

    // Second check should increment failure count
    let health2 = node.health_check().await;
    assert!(!health2.healthy);
    assert!(health2.failure_count > failures1);
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_is_healthy() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    // Initially in Starting state, should be healthy
    assert!(node.is_healthy().await);

    // After running, in Stopped state, should not be healthy
    let ctx = create_test_context().await;
    let _ = node.start(ctx).await;

    assert!(!node.is_healthy().await);
}

// =============================================================================
// HealthStatusExt Tests
// =============================================================================

#[test]
fn test_health_status_ext_healthy() {
    let status = HealthStatus::healthy("All systems operational");

    assert!(status.healthy);
    assert_eq!(status.failure_count, 0);
    assert_eq!(status.message, Some("All systems operational".to_string()));
    assert!(status.last_check > 0);
}

#[test]
fn test_health_status_ext_unhealthy() {
    let status = HealthStatus::unhealthy("Connection failed");

    assert!(!status.healthy);
    assert_eq!(status.failure_count, 1);
    assert_eq!(status.message, Some("Connection failed".to_string()));
    assert!(status.last_check > 0);
}

#[test]
fn test_health_status_ext_with_string() {
    let status = HealthStatus::healthy("OK".to_string());
    assert!(status.healthy);
    assert_eq!(status.message, Some("OK".to_string()));
}

// =============================================================================
// RateConfig Tests
// =============================================================================

#[test]
fn test_rate_config_rate_hz() {
    let config = RateNodeConfig { rate_hz: 30.0 };
    assert_eq!(config.rate_hz(), 30.0);
}

#[test]
fn test_rate_config_period() {
    let config = RateNodeConfig { rate_hz: 10.0 };
    let period = config.period();

    // Use approximate comparison for floating point
    let expected = Duration::from_millis(100);
    let diff = if period > expected {
        period - expected
    } else {
        expected - period
    };

    assert!(
        diff < Duration::from_micros(1),
        "Period should be approximately 100ms, got {:?}",
        period
    );
}

#[test]
fn test_rate_config_period_high_frequency() {
    let config = RateNodeConfig { rate_hz: 100.0 };
    let period = config.period();

    assert_eq!(period, Duration::from_millis(10));
}

#[tokio::test]
async fn test_rate_config_create_interval() {
    let config = RateNodeConfig { rate_hz: 10.0 };
    let mut interval = config.create_interval();

    let start = Instant::now();
    interval.tick().await; // First tick is immediate
    interval.tick().await; // Second tick waits
    let elapsed = start.elapsed();

    // Should be approximately 100ms (10 Hz)
    assert!(elapsed >= Duration::from_millis(90));
    assert!(elapsed < Duration::from_millis(150));
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_rate_config_in_node() {
    let config = RateNodeConfig { rate_hz: 100.0 };
    let node = Node::<RateConfigNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;

    let start = Instant::now();
    let result = node.start(ctx).await;
    let elapsed = start.elapsed();

    assert!(result.is_ok());

    // Should complete 3 ticks at 100 Hz (30ms + overhead)
    assert!(elapsed >= Duration::from_millis(20));
    assert!(elapsed < Duration::from_millis(100));
}

// =============================================================================
// HealthReportingConfig Tests
// =============================================================================

#[test]
fn test_health_reporting_config_default() {
    let config = HealthReportingConfig::default();

    // Default is Normal priority with 5s interval
    assert_eq!(config.priority.interval(), Duration::from_secs(5));
    assert!(config.enabled);
}

#[test]
fn test_health_reporting_config_priority_levels() {
    // Critical priority - 1s interval
    let critical = HealthReportingConfig::critical();
    assert_eq!(critical.priority.interval(), Duration::from_secs(1));
    assert!(critical.enabled);

    // Normal priority - 5s interval
    let normal = HealthReportingConfig::normal();
    assert_eq!(normal.priority.interval(), Duration::from_secs(5));
    assert!(normal.enabled);

    // Background priority - 30s interval
    let background = HealthReportingConfig::background();
    assert_eq!(background.priority.interval(), Duration::from_secs(30));
    assert!(background.enabled);
}

#[test]
fn test_health_reporting_config_clone() {
    let config1 = HealthReportingConfig::critical();
    let config2 = config1.clone();

    assert_eq!(config1.priority.interval(), config2.priority.interval());
    assert_eq!(config1.enabled, config2.enabled);
}

// =============================================================================
// Edge Cases and Error Conditions
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_concurrent_operations() {
    let config = TimedConfig { duration_ms: 100 };
    let node = Node::<TimedNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;

    // Start node
    let node_clone = node.clone();
    let ctx_clone = ctx.clone();
    let handle = tokio::spawn(async move { node_clone.start(ctx_clone).await });

    // Wait a bit
    sleep(Duration::from_millis(10)).await;

    // Check health while running (just verify it doesn't panic)
    let _health = node.health_check().await;

    // Wait for completion
    let _ = handle.await;
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_state_query_during_lifecycle() {
    let config = TimedConfig { duration_ms: 50 };
    let node = Node::<TimedNode>::from_config(config).await.unwrap();

    // Check initial state
    assert_eq!(node.state().await, NodeState::Starting);

    let ctx = create_test_context().await;

    // Start node in background
    let node_clone = node.clone();
    let ctx_clone = ctx.clone();
    tokio::spawn(async move {
        let _ = node_clone.start(ctx_clone).await;
    });

    // Wait for it to start
    sleep(Duration::from_millis(10)).await;

    // Query state multiple times
    for _ in 0..5 {
        let _ = node.state().await;
        sleep(Duration::from_millis(5)).await;
    }

    // Wait for completion
    sleep(Duration::from_millis(100)).await;

    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
#[ignore] // Requires Redis
async fn test_multiple_nodes_same_process() {
    let config1 = SuccessConfig { value: 1 };
    let config2 = SuccessConfig { value: 2 };
    let config3 = SuccessConfig { value: 3 };

    let node1 = Node::<SuccessNode>::from_config(config1).await.unwrap();
    let node2 = Node::<SuccessNode>::from_config(config2).await.unwrap();
    let node3 = Node::<SuccessNode>::from_config(config3).await.unwrap();

    let ctx1 = create_test_context().await;
    let ctx2 = create_test_context().await;
    let ctx3 = create_test_context().await;

    // Start all nodes
    let handle1 = tokio::spawn({
        let node = node1.clone();
        async move { node.start(ctx1).await }
    });

    let handle2 = tokio::spawn({
        let node = node2.clone();
        async move { node.start(ctx2).await }
    });

    let handle3 = tokio::spawn({
        let node = node3.clone();
        async move { node.start(ctx3).await }
    });

    // Wait for all to complete
    let results = tokio::join!(handle1, handle2, handle3);

    assert!(results.0.unwrap().is_ok());
    assert!(results.1.unwrap().is_ok());
    assert!(results.2.unwrap().is_ok());

    // All should be stopped
    assert_eq!(node1.state().await, NodeState::Stopped);
    assert_eq!(node2.state().await, NodeState::Stopped);
    assert_eq!(node3.state().await, NodeState::Stopped);
}

#[tokio::test]
async fn test_node_clone_shares_state() {
    let config = SuccessConfig { value: 42 };
    let node1 = Node::<SuccessNode>::from_config(config).await.unwrap();
    let node2 = node1.clone();

    // Both should have same initial state
    assert_eq!(node1.state().await, node2.state().await);

    // Shutdown via node1
    let _ = node1.shutdown().await;

    // node2 should also reflect the state change
    assert_eq!(node2.state().await, NodeState::Stopped);
}

// =============================================================================
// Context Integration Tests (without Redis)
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis
async fn test_node_respects_context_shutdown() {
    let config = TimedConfig { duration_ms: 1000 };
    let node = Node::<TimedNode>::from_config(config).await.unwrap();

    let ctx = create_test_context().await;

    // Start node in background
    let node_clone = node.clone();
    let ctx_clone = ctx.clone();
    let handle = tokio::spawn(async move { node_clone.start(ctx_clone).await });

    // Wait a bit
    sleep(Duration::from_millis(50)).await;

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

    // Node should complete quickly (not wait full 1000ms)
    let result = timeout(Duration::from_millis(200), handle).await;

    assert!(result.is_ok(), "Node should respond to shutdown signal");
}

// =============================================================================
// Node Type Tests - Verify Debug trait
// =============================================================================

#[test]
fn test_node_types_are_debug() {
    let config = SuccessConfig { value: 42 };
    let debug_str = format!("{:?}", config);
    assert!(debug_str.contains("SuccessConfig"));
}

// =============================================================================
// Comprehensive Lifecycle Test
// =============================================================================

#[tokio::test]
#[ignore] // Requires Redis
async fn test_complete_node_lifecycle() {
    let config = HealthyConfig {
        initially_healthy: true,
    };

    // 1. Initialize
    let node = Node::<HealthyNode>::from_config(config).await;
    assert!(node.is_ok(), "Initialization should succeed");
    let node = node.unwrap();

    // 2. Check initial state
    assert_eq!(node.state().await, NodeState::Starting);
    assert!(node.is_healthy().await);

    // 3. Check health before running
    let health = node.health_check().await;
    assert!(health.healthy);

    // 4. Start node in background
    let ctx = create_test_context().await;
    let node_clone = node.clone();
    let ctx_clone = ctx.clone();
    let handle = tokio::spawn(async move { node_clone.start(ctx_clone).await });

    // 5. Wait for it to be running
    sleep(Duration::from_millis(20)).await;

    // 6. Verify it's running
    let state = node.state().await;
    assert!(
        state == NodeState::Running || state == NodeState::Starting,
        "Node should be running or starting"
    );

    // 7. Check health while running
    let health = node.health_check().await;
    assert!(health.healthy);

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

    // 9. Wait for completion
    let result = timeout(Duration::from_secs(1), handle).await;
    assert!(result.is_ok(), "Node should shut down gracefully");

    // 10. Verify final state
    assert_eq!(node.state().await, NodeState::Stopped);
    assert!(!node.is_healthy().await);
}

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

#[tokio::test]
async fn test_rapid_node_creation() {
    let mut nodes = Vec::new();

    for i in 0..10 {
        let config = SuccessConfig { value: i };
        let node = Node::<SuccessNode>::from_config(config).await;
        assert!(node.is_ok());
        nodes.push(node.unwrap());
    }

    assert_eq!(nodes.len(), 10);
}

#[tokio::test]
async fn test_rapid_health_checks() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    // Perform 100 rapid health checks
    for _ in 0..100 {
        let health = node.health_check().await;
        assert!(health.healthy);
    }
}

#[tokio::test]
async fn test_rapid_state_queries() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    // Perform 100 rapid state queries
    for _ in 0..100 {
        let state = node.state().await;
        assert_eq!(state, NodeState::Starting);
    }
}