actr-hyper 0.3.0

Hyper — Actor platform infrastructure: sandbox, transport, scheduler, WASM engine, signing, AIS bootstrap, persistence & crypto primitives
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
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;

use actr_hyper::lifecycle::{
    CredentialState, DebounceConfig, DefaultNetworkEventProcessor, NetworkEvent,
    NetworkEventHandle, NetworkEventProcessor, NetworkRecoveryAction, process_network_event_batch,
    run_network_event_reconciler, select_network_recovery_action,
};
use actr_hyper::transport::{NetworkError, NetworkResult};
use actr_hyper::wire::webrtc::{DisconnectReason, SignalingClient, SignalingEvent, SignalingStats};
use actr_protocol::{
    AIdCredential, ActrId, Pong, RegisterRequest, RegisterResponse, RouteCandidatesRequest,
    RouteCandidatesResponse, SignalingEnvelope, UnregisterResponse,
};
use tokio::sync::broadcast;

struct FakeSignalingClient {
    connected: AtomicBool,
    connections: AtomicU64,
    connect_once_calls: AtomicU64,
    disconnections: AtomicU64,
    probe_calls: AtomicU64,
    probe_success: AtomicBool,
    event_tx: broadcast::Sender<SignalingEvent>,
    connect_delay: Duration,
    connect_once_delay: Duration,
}

impl FakeSignalingClient {
    fn new() -> Self {
        Self::new_with_delays(Duration::ZERO, Duration::ZERO)
    }

    fn new_with_delays(connect_delay: Duration, connect_once_delay: Duration) -> Self {
        let (event_tx, _event_rx) = broadcast::channel(64);
        Self {
            connected: AtomicBool::new(false),
            connections: AtomicU64::new(0),
            connect_once_calls: AtomicU64::new(0),
            disconnections: AtomicU64::new(0),
            probe_calls: AtomicU64::new(0),
            probe_success: AtomicBool::new(true),
            event_tx,
            connect_delay,
            connect_once_delay,
        }
    }

    fn stats(&self) -> SignalingStats {
        SignalingStats {
            connections: self.connections.load(Ordering::SeqCst),
            disconnections: self.disconnections.load(Ordering::SeqCst),
            ..SignalingStats::default()
        }
    }

    fn connect_once_calls(&self) -> u64 {
        self.connect_once_calls.load(Ordering::SeqCst)
    }

    fn probe_calls(&self) -> u64 {
        self.probe_calls.load(Ordering::SeqCst)
    }

    fn set_probe_success(&self, success: bool) {
        self.probe_success.store(success, Ordering::SeqCst);
    }

    fn publish_connected(&self) {
        self.connected.store(true, Ordering::SeqCst);
        self.connections.fetch_add(1, Ordering::SeqCst);
        let _ = self.event_tx.send(SignalingEvent::Connected);
    }
}

#[async_trait::async_trait]
impl SignalingClient for FakeSignalingClient {
    async fn connect(&self) -> NetworkResult<()> {
        if !self.connect_delay.is_zero() {
            tokio::time::sleep(self.connect_delay).await;
        }
        self.publish_connected();
        Ok(())
    }

    async fn connect_once(&self) -> NetworkResult<()> {
        self.connect_once_calls.fetch_add(1, Ordering::SeqCst);
        if !self.connect_once_delay.is_zero() {
            tokio::time::sleep(self.connect_once_delay).await;
        }
        self.publish_connected();
        Ok(())
    }

    async fn disconnect(&self) -> NetworkResult<()> {
        self.connected.store(false, Ordering::SeqCst);
        self.disconnections.fetch_add(1, Ordering::SeqCst);
        let _ = self.event_tx.send(SignalingEvent::Disconnected {
            reason: DisconnectReason::Manual,
        });
        Ok(())
    }

    async fn probe_alive(&self, _timeout: Duration) -> NetworkResult<()> {
        self.probe_calls.fetch_add(1, Ordering::SeqCst);
        if !self.is_connected() {
            return Err(NetworkError::ConnectionError(
                "fake signaling is disconnected".to_string(),
            ));
        }
        if self.probe_success.load(Ordering::SeqCst) {
            Ok(())
        } else {
            Err(NetworkError::TimeoutError(
                "fake signaling probe timed out".to_string(),
            ))
        }
    }

    async fn send_register_request(
        &self,
        _request: RegisterRequest,
    ) -> NetworkResult<RegisterResponse> {
        Err(NetworkError::NotImplemented(
            "register request not implemented in fake client".to_string(),
        ))
    }

    async fn send_unregister_request(
        &self,
        _actor_id: ActrId,
        _credential: AIdCredential,
        _reason: Option<String>,
    ) -> NetworkResult<UnregisterResponse> {
        Err(NetworkError::NotImplemented(
            "unregister request not implemented in fake client".to_string(),
        ))
    }

    async fn send_heartbeat(
        &self,
        _actor_id: ActrId,
        _credential: AIdCredential,
        _availability: actr_protocol::ServiceAvailabilityState,
        _power_reserve: f32,
        _mailbox_backlog: f32,
    ) -> NetworkResult<Pong> {
        Err(NetworkError::NotImplemented(
            "heartbeat not implemented in fake client".to_string(),
        ))
    }

    async fn send_route_candidates_request(
        &self,
        _actor_id: ActrId,
        _credential: AIdCredential,
        _request: RouteCandidatesRequest,
    ) -> NetworkResult<RouteCandidatesResponse> {
        Err(NetworkError::NotImplemented(
            "route candidates not implemented in fake client".to_string(),
        ))
    }

    async fn get_signing_key(
        &self,
        _actor_id: ActrId,
        _credential: AIdCredential,
        _key_id: u32,
    ) -> NetworkResult<(u32, Vec<u8>)> {
        Err(NetworkError::NotImplemented(
            "get_signing_key not implemented in fake client".to_string(),
        ))
    }

    async fn send_credential_update_request(
        &self,
        _actor_id: ActrId,
        _credential: AIdCredential,
    ) -> NetworkResult<RegisterResponse> {
        Err(NetworkError::NotImplemented(
            "credential update not implemented in fake client".to_string(),
        ))
    }

    async fn send_envelope(&self, _envelope: SignalingEnvelope) -> NetworkResult<()> {
        Err(NetworkError::NotImplemented(
            "send_envelope not implemented in fake client".to_string(),
        ))
    }

    async fn receive_envelope(&self) -> NetworkResult<Option<SignalingEnvelope>> {
        Err(NetworkError::NotImplemented(
            "receive_envelope not implemented in fake client".to_string(),
        ))
    }

    fn is_connected(&self) -> bool {
        self.connected.load(Ordering::SeqCst)
    }

    fn get_stats(&self) -> SignalingStats {
        self.stats()
    }

    fn subscribe_events(&self) -> broadcast::Receiver<SignalingEvent> {
        self.event_tx.subscribe()
    }

    async fn set_actor_id(&self, _actor_id: ActrId) {}

    async fn set_credential_state(&self, _credential_state: CredentialState) {}

    async fn clear_identity(&self) {}
}

#[tokio::test]
async fn test_network_available_probes_when_already_connected() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    );

    processor
        .process_network_available()
        .await
        .expect("first available should succeed");

    let stats = client.get_stats();
    assert_eq!(
        stats.connections, 1,
        "Available should keep a healthy connected signaling client"
    );
    assert_eq!(
        stats.disconnections, 0,
        "Available should not disconnect when signaling probe succeeds"
    );
    assert_eq!(client.probe_calls(), 1);
    assert_eq!(client.connect_once_calls(), 0);

    processor
        .process_network_available()
        .await
        .expect("second available should be debounced");

    let stats = client.get_stats();
    assert_eq!(stats.connections, 1, "debounced call should not reconnect");
    assert_eq!(
        stats.disconnections, 0,
        "debounced call should not disconnect"
    );
    assert_eq!(client.probe_calls(), 1, "debounced call should not probe");

    tokio::time::sleep(Duration::from_millis(600)).await;

    processor
        .process_network_available()
        .await
        .expect("available after window should succeed");

    let stats = client.get_stats();
    assert_eq!(
        stats.connections, 1,
        "Available after debounce window should keep healthy signaling"
    );
    assert_eq!(stats.disconnections, 0);
    assert_eq!(
        client.probe_calls(),
        2,
        "Available after debounce window should probe again"
    );
}

#[tokio::test]
async fn test_network_available_rebuilds_when_signaling_probe_fails() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");
    client.set_probe_success(false);

    let processor = DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    );

    processor
        .process_network_available()
        .await
        .expect("available should rebuild after failed probe");

    let stats = client.get_stats();
    assert_eq!(client.probe_calls(), 1);
    assert_eq!(
        stats.disconnections, 1,
        "failed probe should disconnect the half-open signaling socket"
    );
    assert_eq!(
        stats.connections, 2,
        "failed probe should reconnect signaling once"
    );
    assert_eq!(client.connect_once_calls(), 1);
    assert!(client.is_connected());
}

#[tokio::test]
async fn test_network_available_connects_without_probe_when_disconnected() {
    let client = Arc::new(FakeSignalingClient::new());

    let processor = DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    );

    processor
        .process_network_available()
        .await
        .expect("available should connect disconnected signaling");

    let stats = client.get_stats();
    assert_eq!(client.probe_calls(), 0);
    assert_eq!(client.connect_once_calls(), 1);
    assert_eq!(stats.connections, 1);
    assert_eq!(stats.disconnections, 0);
    assert!(client.is_connected());
}

#[tokio::test]
async fn test_debounce_does_not_cross_event_types() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    );

    processor
        .process_network_available()
        .await
        .expect("available should succeed");

    processor
        .process_network_lost()
        .await
        .expect("lost should not be debounced by available");

    let stats = client.get_stats();
    assert_eq!(
        stats.connections, 1,
        "Available should keep a healthy connected client"
    );
    assert_eq!(
        stats.disconnections, 1,
        "Lost should disconnect even when Available was processed first"
    );
    assert_eq!(client.probe_calls(), 1);
}

#[tokio::test]
async fn test_direct_available_then_type_changed_probes_each_event_type() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .with_test_writer()
        .try_init()
        .ok();

    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(2000),
        },
    ));

    processor
        .process_network_available()
        .await
        .expect("first available should succeed");

    let stats_after_available = client.get_stats();
    assert_eq!(
        stats_after_available.connections, 1,
        "First Available should keep healthy connected signaling"
    );
    assert_eq!(
        stats_after_available.disconnections, 0,
        "First Available should not disconnect healthy signaling"
    );
    assert!(client.is_connected(), "Should be connected after Available");
    assert_eq!(client.probe_calls(), 1);

    tokio::time::sleep(Duration::from_millis(10)).await;

    processor
        .process_network_type_changed(true, false)
        .await
        .expect("type changed should not return error");

    let stats_after_type_changed = client.get_stats();
    assert_eq!(
        stats_after_type_changed.connections, 1,
        "TypeChanged should keep an already healthy signaling client"
    );
    assert_eq!(
        stats_after_type_changed.disconnections, 0,
        "TypeChanged should not disconnect healthy signaling"
    );
    assert_eq!(
        client.probe_calls(),
        2,
        "Available and TypeChanged should each probe when outside their debounce buckets"
    );
    assert!(
        client.is_connected(),
        "After TypeChanged, signaling should still be connected"
    );
}

#[tokio::test]
async fn test_type_changed_works_without_prior_available() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(2000),
        },
    );

    processor
        .process_network_type_changed(true, false)
        .await
        .expect("type changed should succeed");

    let stats = client.get_stats();
    assert!(client.is_connected());
    assert_eq!(
        stats.connections, 1,
        "TypeChanged should keep healthy connected signaling"
    );
    assert_eq!(
        stats.disconnections, 0,
        "TypeChanged should not disconnect signaling when probe succeeds"
    );
    assert_eq!(client.probe_calls(), 1);
    assert_eq!(client.connect_once_calls(), 0);
}

#[tokio::test]
async fn test_batch_available_type_changed_probes_signaling_once() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    ));

    let action = select_network_recovery_action(&[
        NetworkEvent::Available,
        NetworkEvent::TypeChanged {
            is_wifi: true,
            is_cellular: false,
        },
    ]);
    assert_eq!(action, NetworkRecoveryAction::Restore);

    let results = process_network_event_batch(
        vec![
            NetworkEvent::Available,
            NetworkEvent::TypeChanged {
                is_wifi: true,
                is_cellular: false,
            },
        ],
        processor,
    )
    .await;

    assert_eq!(results.len(), 2, "each merged request should get a result");
    assert!(results.iter().all(|result| result.success));
    assert!(client.is_connected(), "signaling should remain connected");

    let stats = client.get_stats();
    assert_eq!(
        stats.connections, 1,
        "Available + TypeChanged should keep a healthy connected signaling client"
    );
    assert_eq!(
        stats.disconnections, 0,
        "Available + TypeChanged should not disconnect when probe succeeds"
    );
    assert_eq!(
        client.connect_once_calls(),
        0,
        "batched restore should not reconnect when signaling probe succeeds"
    );
    assert_eq!(
        client.probe_calls(),
        1,
        "batched restore should perform one signaling probe"
    );
}

#[tokio::test]
async fn test_batch_restore_rebuilds_once_when_signaling_probe_fails() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");
    client.set_probe_success(false);

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    ));

    let results = process_network_event_batch(
        vec![
            NetworkEvent::Available,
            NetworkEvent::TypeChanged {
                is_wifi: false,
                is_cellular: true,
            },
        ],
        processor,
    )
    .await;

    assert_eq!(results.len(), 2);
    assert!(results.iter().all(|result| result.success));
    assert!(client.is_connected());

    let stats = client.get_stats();
    assert_eq!(client.probe_calls(), 1);
    assert_eq!(
        stats.disconnections, 1,
        "batched restore should disconnect once after failed probe"
    );
    assert_eq!(
        stats.connections, 2,
        "batched restore should reconnect once after failed probe"
    );
    assert_eq!(client.connect_once_calls(), 1);
}

#[tokio::test]
async fn test_batch_lost_available_type_changed_prefers_restore() {
    let client = Arc::new(FakeSignalingClient::new());

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    ));

    let events = vec![
        NetworkEvent::Lost,
        NetworkEvent::Available,
        NetworkEvent::TypeChanged {
            is_wifi: false,
            is_cellular: true,
        },
    ];
    assert_eq!(
        select_network_recovery_action(&events),
        NetworkRecoveryAction::Restore
    );

    let results = process_network_event_batch(events, processor).await;

    assert_eq!(results.len(), 3, "each merged request should get a result");
    assert!(results.iter().all(|result| result.success));
    assert!(
        client.is_connected(),
        "signaling should be connected after restore"
    );

    let stats = client.get_stats();
    assert_eq!(stats.connections, 1);
    assert_eq!(client.connect_once_calls(), 1);
    assert_eq!(
        client.probe_calls(),
        0,
        "disconnected restore should connect directly without probing"
    );
    assert_eq!(
        stats.disconnections, 0,
        "Lost in the same settle batch as restore should not force an extra disconnect"
    );
}

#[test]
fn test_batch_action_uses_latest_network_state_event() {
    let available_last = vec![
        NetworkEvent::Available,
        NetworkEvent::Lost,
        NetworkEvent::Available,
    ];
    assert_eq!(
        select_network_recovery_action(&available_last),
        NetworkRecoveryAction::Restore,
        "Available after Lost means the settled final state is online"
    );

    let lost_last = vec![
        NetworkEvent::Lost,
        NetworkEvent::Available,
        NetworkEvent::Lost,
    ];
    assert_eq!(
        select_network_recovery_action(&lost_last),
        NetworkRecoveryAction::Offline,
        "Lost after Available means the settled final state is offline"
    );
}

#[tokio::test]
async fn test_batch_cleanup_connections_wins_and_preserves_compat_reconnect() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    ));

    let events = vec![
        NetworkEvent::CleanupConnections,
        NetworkEvent::Available,
        NetworkEvent::TypeChanged {
            is_wifi: true,
            is_cellular: false,
        },
    ];
    assert_eq!(
        select_network_recovery_action(&events),
        NetworkRecoveryAction::CleanupConnectionsCompat
    );

    let results = process_network_event_batch(events, processor).await;

    assert_eq!(results.len(), 3, "each merged request should get a result");
    assert!(results.iter().all(|result| result.success));
    assert!(
        client.is_connected(),
        "cleanup compat should reconnect signaling"
    );

    let stats = client.get_stats();
    assert_eq!(
        stats.connections, 2,
        "cleanup compat should preserve exactly one reconnect after the initial connection"
    );
    assert_eq!(
        stats.disconnections, 1,
        "cleanup compat should preserve exactly one signaling disconnect"
    );
    assert_eq!(
        client.probe_calls(),
        0,
        "cleanup compat should not probe because it deliberately resets signaling"
    );
}

#[tokio::test]
async fn test_cleanup_available_batch_uses_single_attempt_connect_not_retry_backoff() {
    let client = Arc::new(FakeSignalingClient::new_with_delays(
        Duration::from_secs(5),
        Duration::ZERO,
    ));
    client.publish_connected();

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    ));

    let events = vec![NetworkEvent::CleanupConnections, NetworkEvent::Available];
    assert_eq!(
        select_network_recovery_action(&events),
        NetworkRecoveryAction::CleanupConnectionsCompat
    );

    let results = tokio::time::timeout(
        Duration::from_millis(250),
        process_network_event_batch(events, processor),
    )
    .await
    .expect("network recovery must not be blocked by the regular reconnect backoff path");

    assert_eq!(results.len(), 2, "each merged request should get a result");
    assert!(results.iter().all(|result| result.success));
    assert!(client.is_connected(), "signaling should reconnect");
    assert_eq!(
        client.connect_once_calls(),
        1,
        "network recovery should use the explicit single-attempt connect path"
    );

    let stats = client.get_stats();
    assert_eq!(stats.connections, 2);
    assert_eq!(stats.disconnections, 1);
    assert_eq!(client.probe_calls(), 0);
}

#[tokio::test]
async fn test_network_event_handle_settle_window_merges_events_once() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    ));

    let (event_tx, event_rx) = tokio::sync::mpsc::channel(10);
    let (result_tx, result_rx) = tokio::sync::mpsc::channel(10);
    let handle = NetworkEventHandle::new(event_tx, result_rx);
    let shutdown = tokio_util::sync::CancellationToken::new();
    let processor: Arc<dyn NetworkEventProcessor> = processor;
    let reconciler_shutdown = shutdown.clone();

    let reconciler = tokio::spawn(async move {
        run_network_event_reconciler(event_rx, result_tx, processor, reconciler_shutdown).await;
    });

    let lost = {
        let handle = handle.clone();
        tokio::spawn(async move { handle.handle_network_lost().await })
    };
    tokio::time::sleep(Duration::from_millis(20)).await;
    let available = {
        let handle = handle.clone();
        tokio::spawn(async move { handle.handle_network_available().await })
    };
    tokio::time::sleep(Duration::from_millis(20)).await;
    let type_changed =
        tokio::spawn(async move { handle.handle_network_type_changed(true, false).await });

    let lost_result = lost.await.expect("lost task should not panic").unwrap();
    let available_result = available
        .await
        .expect("available task should not panic")
        .unwrap();
    let type_changed_result = type_changed
        .await
        .expect("type changed task should not panic")
        .unwrap();

    assert!(lost_result.success);
    assert!(available_result.success);
    assert!(type_changed_result.success);
    assert!(client.is_connected());

    let stats = client.get_stats();
    assert_eq!(
        stats.connections, 1,
        "Lost + Available + TypeChanged in one settle window should keep healthy signaling"
    );
    assert_eq!(
        stats.disconnections, 0,
        "Batched restore should not disconnect when signaling probe succeeds"
    );
    assert_eq!(client.probe_calls(), 1, "Batched restore should probe once");

    shutdown.cancel();
    reconciler.await.expect("reconciler task should not panic");
}

#[tokio::test]
async fn test_repeated_foreground_restore_batches_probe_once_per_cycle() {
    let client = Arc::new(FakeSignalingClient::new());
    client.connect().await.expect("initial connect");

    let processor = Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
        client.clone(),
        None,
        DebounceConfig {
            window: Duration::from_millis(500),
        },
    ));

    let (event_tx, event_rx) = tokio::sync::mpsc::channel(10);
    let (result_tx, result_rx) = tokio::sync::mpsc::channel(10);
    let handle = NetworkEventHandle::new(event_tx, result_rx);
    let shutdown = tokio_util::sync::CancellationToken::new();
    let processor: Arc<dyn NetworkEventProcessor> = processor;
    let reconciler_shutdown = shutdown.clone();

    let reconciler = tokio::spawn(async move {
        run_network_event_reconciler(event_rx, result_tx, processor, reconciler_shutdown).await;
    });

    const CYCLES: u64 = 5;

    for cycle in 1..=CYCLES {
        let available = {
            let handle = handle.clone();
            tokio::spawn(async move { handle.handle_network_available().await })
        };

        tokio::time::sleep(Duration::from_millis(20)).await;

        let type_changed = {
            let handle = handle.clone();
            tokio::spawn(async move {
                handle
                    .handle_network_type_changed(cycle % 2 == 0, cycle % 2 != 0)
                    .await
            })
        };

        let available_result = available
            .await
            .expect("available task should not panic")
            .unwrap();
        let type_changed_result = type_changed
            .await
            .expect("type changed task should not panic")
            .unwrap();

        assert!(
            available_result.success,
            "foreground Available should succeed in cycle {}",
            cycle
        );
        assert!(
            type_changed_result.success,
            "foreground TypeChanged should succeed in cycle {}",
            cycle
        );
        assert!(
            client.is_connected(),
            "signaling should remain connected after foreground cycle {}",
            cycle
        );

        let stats = client.get_stats();
        assert_eq!(
            stats.connections, 1,
            "foreground cycle {} should keep the original healthy signaling connection",
            cycle
        );
        assert_eq!(
            stats.disconnections, 0,
            "foreground cycle {} should not disconnect healthy signaling",
            cycle
        );
        assert_eq!(
            client.connect_once_calls(),
            0,
            "foreground cycle {} should not reconnect healthy signaling",
            cycle
        );
        assert_eq!(
            client.probe_calls(),
            cycle,
            "foreground cycle {} should probe once for the settled restore batch",
            cycle
        );
    }

    shutdown.cancel();
    reconciler.await.expect("reconciler task should not panic");
}