asupersync 0.3.5

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! ATP Transport Metrics Integration
//!
//! Exposes QUIC transport metrics to the ATP Transfer Brain for path selection,
//! congestion adaptation, and performance monitoring.

use crate::net::QuicTransportMachine;
use crate::observability::metrics::{Counter, Gauge};
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};

/// ATP transport metrics snapshot for Transfer Brain decision-making.
#[derive(Debug, Clone)]
pub struct AtpTransportMetrics {
    /// Connection identifier for correlation.
    pub connection_id: String,
    /// Path identifier for multi-path scenarios.
    pub path_id: String,
    /// Current smoothed RTT in microseconds.
    pub smoothed_rtt_micros: Option<u64>,
    /// Latest RTT sample in microseconds.
    pub latest_rtt_micros: Option<u64>,
    /// RTT variance in microseconds.
    pub rttvar_micros: Option<u64>,
    /// Current bytes in flight.
    pub bytes_in_flight: u64,
    /// Current congestion window in bytes.
    pub congestion_window_bytes: u64,
    /// Slow-start threshold in bytes.
    pub ssthresh_bytes: u64,
    /// Current PTO count (backoff level).
    pub pto_count: u32,
    /// Whether congestion window is currently limited.
    pub congestion_limited: bool,
    /// Anti-amplification state.
    pub anti_amplification_limited: bool,
    /// Total packets sent on this path.
    pub packets_sent: u64,
    /// Total packets lost on this path.
    pub packets_lost: u64,
    /// Total packets acknowledged on this path.
    pub packets_acked: u64,
    /// Current loss rate (0.0 - 1.0).
    pub loss_rate: f64,
    /// Path stability score (0.0 - 1.0, higher = more stable).
    pub path_stability: f64,
    /// Timestamp of last metric update.
    pub last_updated: Instant,
    /// Optional path doctor assessment.
    pub path_doctor_assessment: Option<PathDoctorAssessment>,
}

/// Path doctor assessment for transport troubleshooting.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathDoctorAssessment {
    /// Overall path health score (0.0 - 1.0).
    pub health_score: f64,
    /// Detected issues with this path.
    pub detected_issues: Vec<PathIssue>,
    /// Recommended actions for path optimization.
    pub recommendations: Vec<PathRecommendation>,
    /// Performance classification.
    pub performance_class: PathPerformanceClass,
}

/// Detected path issues for diagnostics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PathIssue {
    /// High RTT variance indicating unstable path.
    HighRttVariance { variance_micros: u64 },
    /// High packet loss rate.
    HighPacketLoss { loss_rate: f64 },
    /// Persistent congestion detected.
    PersistentCongestion { duration_ms: u64 },
    /// Frequent PTO events indicating poor connectivity.
    FrequentTimeouts { pto_rate: f64 },
    /// Anti-amplification limiting throughput.
    AntiAmplificationLimited,
    /// Suspected middlebox interference.
    MiddleboxInterference,
    /// NAT rebinding detected.
    NatRebinding,
    /// Path MTU issues.
    MtuProblems { detected_mtu: u16 },
}

/// Path optimization recommendations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PathRecommendation {
    /// Switch to different path.
    SwitchPath { suggested_path_id: String },
    /// Reduce sending rate.
    ReduceSendingRate { factor: f64 },
    /// Enable path validation.
    EnablePathValidation,
    /// Perform MTU discovery.
    PerformMtuDiscovery,
    /// Consider relay usage.
    ConsiderRelay,
    /// Enable FEC/repair.
    EnableRepair { fec_rate: f64 },
}

/// Path performance classification for routing decisions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PathPerformanceClass {
    /// Excellent performance, preferred for large transfers.
    Excellent,
    /// Good performance, suitable for most transfers.
    Good,
    /// Fair performance, usable but not optimal.
    Fair,
    /// Poor performance, should be avoided.
    Poor,
    /// Unusable path, should be failed immediately.
    Unusable,
}

impl PathPerformanceClass {
    /// Get numeric score for path ranking (higher = better).
    #[must_use]
    pub const fn score(self) -> u8 {
        match self {
            Self::Excellent => 5,
            Self::Good => 4,
            Self::Fair => 3,
            Self::Poor => 2,
            Self::Unusable => 1,
        }
    }

    /// Determine performance class from metrics.
    #[must_use]
    pub fn from_metrics(metrics: &AtpTransportMetrics) -> Self {
        let rtt_score = metrics.smoothed_rtt_micros.map_or(0.0, |rtt| {
            match rtt {
                0..=50_000 => 1.0,        // <= 50ms: excellent
                50_001..=150_000 => 0.8,  // 50-150ms: good
                150_001..=300_000 => 0.6, // 150-300ms: fair
                300_001..=500_000 => 0.4, // 300-500ms: poor
                _ => 0.2,                 // >500ms: unusable
            }
        });

        let loss_score = 1.0 - metrics.loss_rate.min(1.0);

        let congestion_score = if metrics.congestion_limited { 0.6 } else { 1.0 };

        let stability_score = metrics.path_stability;

        let timeout_score = match metrics.pto_count {
            0 => 1.0,
            1 => 0.75,
            2 => 0.5,
            3 => 0.25,
            _ => 0.0,
        };

        let overall_score =
            (rtt_score + loss_score + congestion_score + stability_score + timeout_score) / 5.0;

        let mut class = match overall_score {
            s if s >= 0.9 => Self::Excellent,
            s if s >= 0.7 => Self::Good,
            s if s >= 0.5 => Self::Fair,
            s if s >= 0.3 => Self::Poor,
            _ => Self::Unusable,
        };

        if metrics.pto_count >= 4
            || metrics.loss_rate >= 0.5
            || matches!(metrics.smoothed_rtt_micros, Some(rtt) if rtt > 500_000)
        {
            return Self::Unusable;
        }

        if metrics.pto_count >= 3
            || metrics.loss_rate >= 0.2
            || matches!(metrics.smoothed_rtt_micros, Some(300_001..=500_000))
        {
            if class.score() > Self::Poor.score() {
                class = Self::Poor;
            }
        }

        if metrics.loss_rate >= 0.1 && class.score() > Self::Good.score() {
            class = Self::Good;
        }

        class
    }
}

/// One sampled row from the G3 saturating-load benchmark harness.
///
/// The transport does not read `/proc`, cgroups, or host load directly. The
/// benchmark sampler owns those platform reads and feeds this normalized row to
/// the guard so policy evaluation stays deterministic and artifact-friendly.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SaturatingLoadSample {
    /// Milliseconds since the benchmark began.
    pub elapsed_ms: u64,
    /// Baseline resident set size before the transfer pressure window.
    pub baseline_rss_bytes: u64,
    /// Current resident set size for the sampled process group.
    pub rss_bytes: u64,
    /// One-minute load average sampled by the harness.
    pub loadavg_1m: f64,
    /// CPU pressure in `[0.0, 1.0]`, where `1.0` means fully saturated.
    pub cpu_pressure: f64,
    /// Observed useful transfer rate for correlation with pressure spikes.
    pub goodput_bps: u64,
}

/// Static limits for the G3 bounded-memory and responsiveness guard.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SaturatingLoadGuardConfig {
    /// Maximum RSS growth allowed over the baseline during peak throughput.
    pub rss_growth_ceiling_bytes: u64,
    /// Maximum one-minute load average allowed during the pressure window.
    pub loadavg_cap: f64,
    /// Maximum normalized CPU pressure allowed during the pressure window.
    pub cpu_pressure_cap: f64,
    /// Minimum number of samples required before a green verdict is possible.
    pub min_samples: usize,
}

impl SaturatingLoadGuardConfig {
    /// Build a guard config, clamping invalid host-pressure caps fail closed.
    #[must_use]
    pub fn new(
        rss_growth_ceiling_bytes: u64,
        loadavg_cap: f64,
        cpu_pressure_cap: f64,
        min_samples: usize,
    ) -> Self {
        Self {
            rss_growth_ceiling_bytes: rss_growth_ceiling_bytes.max(1),
            loadavg_cap: finite_positive_cap(loadavg_cap),
            cpu_pressure_cap: finite_unit_cap(cpu_pressure_cap),
            min_samples: min_samples.max(1),
        }
    }
}

/// Fail-closed reason from [`SaturatingLoadGuardReport`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SaturatingLoadGuardViolation {
    /// Not enough sampler rows were present to trust the artifact.
    InsufficientSamples {
        /// Rows observed.
        observed: usize,
        /// Rows required by policy.
        required: usize,
    },
    /// Peak RSS growth exceeded the bounded-memory ceiling.
    RssGrowthExceeded {
        /// Peak resident growth over baseline.
        observed_bytes: u64,
        /// Configured ceiling.
        cap_bytes: u64,
    },
    /// Peak load average exceeded the machine-responsiveness ceiling.
    LoadAverageExceeded {
        /// Peak observed one-minute load average.
        observed: f64,
        /// Configured cap.
        cap: f64,
    },
    /// Peak CPU pressure exceeded the machine-responsiveness ceiling.
    CpuPressureExceeded {
        /// Peak observed normalized CPU pressure.
        observed: f64,
        /// Configured cap.
        cap: f64,
    },
}

/// Machine-readable G3 verdict for benchmark artifacts and pacing feedback.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SaturatingLoadGuardReport {
    /// Number of samples evaluated.
    pub sample_count: usize,
    /// Largest RSS growth over the sample baseline.
    pub peak_rss_growth_bytes: u64,
    /// Average RSS across the sample window.
    pub avg_rss_bytes: u64,
    /// Peak one-minute load average.
    pub peak_loadavg_1m: f64,
    /// Average one-minute load average.
    pub avg_loadavg_1m: f64,
    /// Peak normalized CPU pressure.
    pub peak_cpu_pressure: f64,
    /// Average normalized CPU pressure.
    pub avg_cpu_pressure: f64,
    /// Highest observed useful transfer rate, for correlating peak throughput
    /// with memory/load stability in the artifact.
    pub peak_goodput_bps: u64,
    /// Normalized pressure in `[0.0, 1.0]` suitable for
    /// `QuicConfig::responsiveness_pressure`.
    pub pacer_responsiveness_pressure: f64,
    /// Whether the benchmark artifact satisfies G3.
    pub passed: bool,
    /// Fail-closed reasons. Empty only when `passed` is true.
    pub violations: Vec<SaturatingLoadGuardViolation>,
}

impl SaturatingLoadGuardReport {
    /// Evaluate G3 bounded-memory and host-responsiveness samples.
    #[must_use]
    pub fn evaluate(config: SaturatingLoadGuardConfig, samples: &[SaturatingLoadSample]) -> Self {
        let mut violations = Vec::new();
        if samples.len() < config.min_samples {
            violations.push(SaturatingLoadGuardViolation::InsufficientSamples {
                observed: samples.len(),
                required: config.min_samples,
            });
        }

        let sample_count = samples.len();
        let mut peak_rss_growth_bytes = 0_u64;
        let mut total_rss_bytes = 0_u128;
        let mut peak_loadavg_1m = 0.0_f64;
        let mut total_loadavg_1m = 0.0_f64;
        let mut peak_cpu_pressure = 0.0_f64;
        let mut total_cpu_pressure = 0.0_f64;
        let mut peak_goodput_bps = 0_u64;

        for sample in samples {
            let rss_growth = sample.rss_bytes.saturating_sub(sample.baseline_rss_bytes);
            peak_rss_growth_bytes = peak_rss_growth_bytes.max(rss_growth);
            total_rss_bytes = total_rss_bytes.saturating_add(u128::from(sample.rss_bytes));

            let loadavg = finite_nonnegative(sample.loadavg_1m);
            peak_loadavg_1m = peak_loadavg_1m.max(loadavg);
            total_loadavg_1m += loadavg;

            let cpu_pressure = clamp_unit_or_one(sample.cpu_pressure);
            peak_cpu_pressure = peak_cpu_pressure.max(cpu_pressure);
            total_cpu_pressure += cpu_pressure;
            peak_goodput_bps = peak_goodput_bps.max(sample.goodput_bps);
        }

        let avg_rss_bytes = if sample_count == 0 {
            0
        } else {
            u64::try_from(total_rss_bytes / sample_count as u128).unwrap_or(u64::MAX)
        };
        let avg_loadavg_1m = if sample_count == 0 {
            0.0
        } else {
            total_loadavg_1m / sample_count as f64
        };
        let avg_cpu_pressure = if sample_count == 0 {
            0.0
        } else {
            total_cpu_pressure / sample_count as f64
        };

        if peak_rss_growth_bytes > config.rss_growth_ceiling_bytes {
            violations.push(SaturatingLoadGuardViolation::RssGrowthExceeded {
                observed_bytes: peak_rss_growth_bytes,
                cap_bytes: config.rss_growth_ceiling_bytes,
            });
        }
        if peak_loadavg_1m > config.loadavg_cap {
            violations.push(SaturatingLoadGuardViolation::LoadAverageExceeded {
                observed: peak_loadavg_1m,
                cap: config.loadavg_cap,
            });
        }
        if peak_cpu_pressure > config.cpu_pressure_cap {
            violations.push(SaturatingLoadGuardViolation::CpuPressureExceeded {
                observed: peak_cpu_pressure,
                cap: config.cpu_pressure_cap,
            });
        }

        let rss_pressure = ratio_to_unit(
            peak_rss_growth_bytes as f64,
            config.rss_growth_ceiling_bytes as f64,
        );
        let load_pressure = ratio_to_unit(peak_loadavg_1m, config.loadavg_cap);
        let cpu_pressure = ratio_to_unit(peak_cpu_pressure, config.cpu_pressure_cap);
        let passed = violations.is_empty();
        let raw_pressure = rss_pressure.max(load_pressure).max(cpu_pressure).min(1.0);
        let pacer_responsiveness_pressure = if passed { raw_pressure } else { 1.0 };

        Self {
            sample_count,
            peak_rss_growth_bytes,
            avg_rss_bytes,
            peak_loadavg_1m,
            avg_loadavg_1m,
            peak_cpu_pressure,
            avg_cpu_pressure,
            peak_goodput_bps,
            pacer_responsiveness_pressure,
            passed,
            violations,
        }
    }
}

fn finite_nonnegative(value: f64) -> f64 {
    if value.is_finite() && value >= 0.0 {
        value
    } else {
        f64::INFINITY
    }
}

fn finite_positive_cap(value: f64) -> f64 {
    if value.is_finite() && value > 0.0 {
        value
    } else {
        f64::EPSILON
    }
}

fn finite_unit_cap(value: f64) -> f64 {
    if value.is_finite() {
        value.clamp(f64::EPSILON, 1.0)
    } else {
        f64::EPSILON
    }
}

fn clamp_unit_or_one(value: f64) -> f64 {
    if value.is_finite() {
        value.clamp(0.0, 1.0)
    } else {
        1.0
    }
}

fn ratio_to_unit(numerator: f64, denominator: f64) -> f64 {
    if !numerator.is_finite() {
        return 1.0;
    }
    if !denominator.is_finite() || denominator <= 0.0 {
        return if numerator <= 0.0 { 0.0 } else { 1.0 };
    }
    (numerator / denominator).clamp(0.0, 1.0)
}

/// ATP Transport Metrics Collector
///
/// Collects and exposes QUIC transport metrics for ATP Transfer Brain consumption.
pub struct AtpTransportMetricsCollector {
    /// Connection identifier.
    connection_id: String,
    /// Path identifier.
    path_id: String,
    /// Metrics counters.
    packets_sent: Counter,
    packets_lost: Counter,
    packets_acked: Counter,
    pto_events: Counter,
    /// Metrics gauges.
    bytes_in_flight: Gauge,
    congestion_window: Gauge,
    rtt_gauge: Gauge,
    /// Path stability tracker.
    stability_tracker: PathStabilityTracker,
    /// Anti-amplification limiter.
    anti_amplification: AntiAmplificationLimiter,
}

impl AtpTransportMetricsCollector {
    /// Create a new metrics collector.
    #[must_use]
    pub fn new(connection_id: String, path_id: String) -> Self {
        Self {
            packets_sent: Counter::new(format!("atp_quic_packets_sent_{}", connection_id)),
            packets_lost: Counter::new(format!("atp_quic_packets_lost_{}", connection_id)),
            packets_acked: Counter::new(format!("atp_quic_packets_acked_{}", connection_id)),
            pto_events: Counter::new(format!("atp_quic_pto_events_{}", connection_id)),
            bytes_in_flight: Gauge::new(format!("atp_quic_bytes_in_flight_{}", connection_id)),
            congestion_window: Gauge::new(format!("atp_quic_congestion_window_{}", connection_id)),
            rtt_gauge: Gauge::new(format!("atp_quic_rtt_micros_{}", connection_id)),
            connection_id,
            path_id,
            stability_tracker: PathStabilityTracker::new(),
            anti_amplification: AntiAmplificationLimiter::new(),
        }
    }

    /// Update metrics from transport machine state.
    pub fn update_from_transport(&mut self, transport: &QuicTransportMachine) {
        // Update basic metrics
        let rtt = transport.rtt();
        self.bytes_in_flight
            .set(transport.bytes_in_flight().cast_signed());
        self.congestion_window
            .set(transport.congestion_window_bytes().cast_signed());

        if let Some(smoothed_rtt) = rtt.smoothed_rtt_micros() {
            self.rtt_gauge.set(smoothed_rtt.cast_signed());
            self.stability_tracker.update_rtt(smoothed_rtt);
        }

        // Update stability based on recent metrics
        self.stability_tracker.update();
    }

    /// Record packet send event.
    pub fn on_packet_sent(&mut self, bytes: u64) {
        self.packets_sent.increment();
        self.anti_amplification.on_packet_sent(bytes);
    }

    /// Record inbound peer bytes that credit the anti-amplification budget.
    pub fn on_datagram_received(&mut self, bytes: u64) {
        self.anti_amplification.on_datagram_received(bytes);
    }

    /// Record packet acknowledgment.
    pub fn on_packet_acked(&mut self, bytes: u64) {
        self.packets_acked.increment();
        self.anti_amplification.on_ack_received(bytes);
    }

    /// Record packet loss.
    pub fn on_packet_lost(&mut self, _bytes: u64) {
        self.packets_lost.increment();
        self.stability_tracker.on_packet_lost();
    }

    /// Record PTO event.
    pub fn on_pto_expired(&mut self) {
        self.pto_events.increment();
        self.stability_tracker.on_pto_event();
    }

    /// Check if anti-amplification is limiting sends.
    #[must_use]
    pub fn is_anti_amplification_limited(&self) -> bool {
        self.anti_amplification.is_limited()
    }

    /// Get current transport metrics snapshot.
    #[must_use]
    pub fn current_metrics(&self, transport: &QuicTransportMachine) -> AtpTransportMetrics {
        let rtt = transport.rtt();
        let packets_sent = self.packets_sent.get();
        let packets_lost = self.packets_lost.get();
        let packets_acked = self.packets_acked.get();

        let loss_rate = if packets_sent > 0 {
            packets_lost as f64 / packets_sent as f64
        } else {
            0.0
        };

        let mut metrics = AtpTransportMetrics {
            connection_id: self.connection_id.clone(),
            path_id: self.path_id.clone(),
            smoothed_rtt_micros: rtt.smoothed_rtt_micros(),
            latest_rtt_micros: rtt.latest_rtt_micros(),
            rttvar_micros: rtt.rttvar_micros(),
            bytes_in_flight: transport.bytes_in_flight(),
            congestion_window_bytes: transport.congestion_window_bytes(),
            ssthresh_bytes: transport.ssthresh_bytes(),
            pto_count: transport.pto_count(),
            congestion_limited: !transport.can_send(1200), // Typical packet size
            anti_amplification_limited: self.is_anti_amplification_limited(),
            packets_sent,
            packets_lost,
            packets_acked,
            loss_rate,
            path_stability: self.stability_tracker.stability_score(),
            last_updated: Instant::now(),
            path_doctor_assessment: None,
        };
        metrics.path_doctor_assessment = Some(self.assess_path_health(&metrics));

        metrics
    }

    /// Assess path health and generate doctor report.
    fn assess_path_health(&self, metrics: &AtpTransportMetrics) -> PathDoctorAssessment {
        let mut issues = Vec::new();
        let mut recommendations = Vec::new();
        let mut recommended_rate_reduction = false;

        // Check RTT variance
        if let (Some(rtt), Some(rttvar)) = (metrics.smoothed_rtt_micros, metrics.rttvar_micros) {
            let variance_ratio = rttvar as f64 / rtt as f64;
            if variance_ratio > 0.5 {
                issues.push(PathIssue::HighRttVariance {
                    variance_micros: rttvar,
                });
                recommendations.push(PathRecommendation::EnablePathValidation);
            }
        }

        // Check loss rate
        if metrics.loss_rate > 0.05 {
            issues.push(PathIssue::HighPacketLoss {
                loss_rate: metrics.loss_rate,
            });
            if metrics.loss_rate > 0.1 {
                recommendations.push(PathRecommendation::EnableRepair { fec_rate: 0.2 });
            }
        }

        // Check PTO backoff. A rising transport PTO count is actionable even
        // when the collector has not yet accumulated enough RTT samples.
        let pto_pressure = self.pto_pressure(metrics.pto_count);
        if metrics.pto_count >= 2 || pto_pressure >= 0.25 {
            issues.push(PathIssue::FrequentTimeouts {
                pto_rate: pto_pressure,
            });
            let factor = if metrics.pto_count >= 4 || pto_pressure >= 0.75 {
                0.5
            } else {
                0.7
            };
            recommendations.push(PathRecommendation::ReduceSendingRate { factor });
            recommended_rate_reduction = true;
            recommendations.push(PathRecommendation::EnablePathValidation);
            if metrics.pto_count >= 3 || pto_pressure >= 0.75 {
                recommendations.push(PathRecommendation::ConsiderRelay);
            }
        }

        // Check congestion
        if metrics.congestion_limited && !recommended_rate_reduction {
            recommendations.push(PathRecommendation::ReduceSendingRate { factor: 0.8 });
        }

        // Check anti-amplification
        if metrics.anti_amplification_limited {
            issues.push(PathIssue::AntiAmplificationLimited);
            recommendations.push(PathRecommendation::EnablePathValidation);
        }

        let performance_class = PathPerformanceClass::from_metrics(metrics);
        let health_score = match performance_class {
            PathPerformanceClass::Excellent => 0.95,
            PathPerformanceClass::Good => 0.80,
            PathPerformanceClass::Fair => 0.60,
            PathPerformanceClass::Poor => 0.40,
            PathPerformanceClass::Unusable => 0.20,
        };

        PathDoctorAssessment {
            health_score,
            detected_issues: issues,
            recommendations,
            performance_class,
        }
    }

    fn pto_pressure(&self, pto_count: u32) -> f64 {
        let event_pressure = self.stability_tracker.pto_rate();
        let backoff_pressure = match pto_count {
            0 => 0.0,
            1 => 0.25,
            2 => 0.5,
            3 => 0.75,
            _ => 1.0,
        };
        event_pressure.max(backoff_pressure)
    }
}

/// Tracks path stability over time.
#[derive(Debug)]
struct PathStabilityTracker {
    rtt_samples: Vec<u64>,
    loss_events: u32,
    pto_events: u32,
    sample_count: u32,
    last_update: Instant,
}

impl PathStabilityTracker {
    fn new() -> Self {
        Self {
            rtt_samples: Vec::with_capacity(100),
            loss_events: 0,
            pto_events: 0,
            sample_count: 0,
            last_update: Instant::now(),
        }
    }

    fn update_rtt(&mut self, rtt_micros: u64) {
        self.rtt_samples.push(rtt_micros);
        if self.rtt_samples.len() > 100 {
            self.rtt_samples.remove(0);
        }
        self.sample_count += 1;
    }

    fn on_packet_lost(&mut self) {
        self.loss_events += 1;
    }

    fn on_pto_event(&mut self) {
        self.pto_events += 1;
    }

    fn update(&mut self) {
        self.last_update = Instant::now();
    }

    fn pto_rate(&self) -> f64 {
        let denominator = self.sample_count.max(self.pto_events).max(1);
        (self.pto_events as f64 / denominator as f64).min(1.0)
    }

    fn stability_score(&self) -> f64 {
        if self.sample_count == 0 {
            return 0.5; // Neutral score with no data
        }

        // Calculate RTT stability (lower variance = higher stability)
        let rtt_stability = if self.rtt_samples.len() >= 2 {
            let mean = self.rtt_samples.iter().sum::<u64>() as f64 / self.rtt_samples.len() as f64;
            let variance = self
                .rtt_samples
                .iter()
                .map(|&x| {
                    let diff = x as f64 - mean;
                    diff * diff
                })
                .sum::<f64>()
                / self.rtt_samples.len() as f64;
            let coefficient_of_variation = variance.sqrt() / mean;
            (1.0 - coefficient_of_variation.min(1.0)).max(0.0)
        } else {
            1.0
        };

        // Calculate loss stability (fewer losses = higher stability)
        let loss_stability = if self.sample_count > 0 {
            let loss_rate = self.loss_events as f64 / self.sample_count as f64;
            (1.0 - loss_rate.min(1.0)).max(0.0)
        } else {
            1.0
        };

        // Calculate timeout stability (fewer PTOs = higher stability)
        let pto_stability = (1.0 - self.pto_rate()).max(0.0);

        // Weighted average
        (rtt_stability * 0.5 + loss_stability * 0.3 + pto_stability * 0.2).clamp(0.0, 1.0)
    }
}

/// Anti-amplification limiter per RFC 9000.
#[derive(Debug)]
struct AntiAmplificationLimiter {
    bytes_sent: u64,
    bytes_received: u64,
    address_validated: bool,
    last_reset: Instant,
}

impl AntiAmplificationLimiter {
    fn new() -> Self {
        Self {
            bytes_sent: 0,
            bytes_received: 0,
            address_validated: false,
            last_reset: Instant::now(),
        }
    }

    fn on_packet_sent(&mut self, bytes: u64) {
        self.bytes_sent = self.bytes_sent.saturating_add(bytes);
        self.maybe_reset();
    }

    fn on_datagram_received(&mut self, bytes: u64) {
        self.bytes_received = self.bytes_received.saturating_add(bytes);
        self.maybe_reset();
    }

    fn on_ack_received(&mut self, _bytes: u64) {
        // Receiving an ACK validates the peer address and lifts the
        // anti-amplification limiter for this path.
        self.address_validated = true;
        self.maybe_reset();
    }

    fn is_limited(&self) -> bool {
        if self.address_validated {
            return false;
        }

        // RFC 9000: server MUST NOT send more than 3x received bytes
        self.bytes_sent > self.bytes_received.saturating_mul(3)
    }

    fn maybe_reset(&mut self) {
        // Reset counters periodically to avoid overflow
        if self.last_reset.elapsed() > Duration::from_secs(60) {
            self.bytes_sent = 0;
            self.bytes_received = 0;
            self.last_reset = Instant::now();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::net::quic_native::QuicTransportMachine;

    #[test]
    fn path_performance_classification() {
        let mut metrics = AtpTransportMetrics {
            connection_id: "test".to_string(),
            path_id: "path1".to_string(),
            smoothed_rtt_micros: Some(30_000), // 30ms
            latest_rtt_micros: Some(32_000),
            rttvar_micros: Some(5_000),
            bytes_in_flight: 1200,
            congestion_window_bytes: 12_000,
            ssthresh_bytes: 24_000,
            pto_count: 0,
            congestion_limited: false,
            anti_amplification_limited: false,
            packets_sent: 100,
            packets_lost: 1,
            packets_acked: 99,
            loss_rate: 0.01,
            path_stability: 0.95,
            last_updated: Instant::now(),
            path_doctor_assessment: None,
        };

        // Should be excellent with low RTT, low loss, no congestion, high stability
        assert_eq!(
            PathPerformanceClass::from_metrics(&metrics),
            PathPerformanceClass::Excellent
        );

        // Higher loss should degrade performance
        metrics.loss_rate = 0.1;
        assert_eq!(
            PathPerformanceClass::from_metrics(&metrics),
            PathPerformanceClass::Good
        );

        // High RTT should further degrade
        metrics.smoothed_rtt_micros = Some(400_000); // 400ms
        assert_eq!(
            PathPerformanceClass::from_metrics(&metrics),
            PathPerformanceClass::Poor
        );
    }

    #[test]
    fn saturating_load_guard_accepts_flat_rss_and_responsive_host() {
        let config = SaturatingLoadGuardConfig::new(8 * 1024 * 1024, 8.0, 0.85, 3);
        let baseline = 128 * 1024 * 1024;
        let samples = [
            SaturatingLoadSample {
                elapsed_ms: 0,
                baseline_rss_bytes: baseline,
                rss_bytes: baseline + 1024 * 1024,
                loadavg_1m: 2.0,
                cpu_pressure: 0.20,
                goodput_bps: 700 * 1024 * 1024,
            },
            SaturatingLoadSample {
                elapsed_ms: 200,
                baseline_rss_bytes: baseline,
                rss_bytes: baseline + 2 * 1024 * 1024,
                loadavg_1m: 3.5,
                cpu_pressure: 0.40,
                goodput_bps: 930 * 1024 * 1024,
            },
            SaturatingLoadSample {
                elapsed_ms: 400,
                baseline_rss_bytes: baseline,
                rss_bytes: baseline + 2 * 1024 * 1024,
                loadavg_1m: 4.0,
                cpu_pressure: 0.50,
                goodput_bps: 920 * 1024 * 1024,
            },
        ];

        let report = SaturatingLoadGuardReport::evaluate(config, &samples);

        assert!(report.passed, "{report:?}");
        assert!(report.violations.is_empty());
        assert_eq!(report.sample_count, 3);
        assert_eq!(report.peak_rss_growth_bytes, 2 * 1024 * 1024);
        assert_eq!(report.peak_goodput_bps, 930 * 1024 * 1024);
        assert!(
            report.pacer_responsiveness_pressure > 0.0
                && report.pacer_responsiveness_pressure < 1.0
        );
    }

    #[test]
    fn saturating_load_guard_fails_closed_on_rss_load_and_cpu_pressure() {
        let config = SaturatingLoadGuardConfig::new(4 * 1024 * 1024, 4.0, 0.70, 2);
        let baseline = 64 * 1024 * 1024;
        let samples = [
            SaturatingLoadSample {
                elapsed_ms: 0,
                baseline_rss_bytes: baseline,
                rss_bytes: baseline + 1024 * 1024,
                loadavg_1m: 3.0,
                cpu_pressure: 0.30,
                goodput_bps: 100,
            },
            SaturatingLoadSample {
                elapsed_ms: 200,
                baseline_rss_bytes: baseline,
                rss_bytes: baseline + 12 * 1024 * 1024,
                loadavg_1m: 5.5,
                cpu_pressure: 0.95,
                goodput_bps: 200,
            },
        ];

        let report = SaturatingLoadGuardReport::evaluate(config, &samples);

        assert!(!report.passed);
        assert_eq!(report.pacer_responsiveness_pressure, 1.0);
        assert!(report.violations.iter().any(|violation| matches!(
            violation,
            SaturatingLoadGuardViolation::RssGrowthExceeded {
                observed_bytes,
                cap_bytes
            } if *observed_bytes == 12 * 1024 * 1024 && *cap_bytes == 4 * 1024 * 1024
        )));
        assert!(report.violations.iter().any(|violation| matches!(
            violation,
            SaturatingLoadGuardViolation::LoadAverageExceeded { observed, cap }
                if (*observed - 5.5).abs() < f64::EPSILON && (*cap - 4.0).abs() < f64::EPSILON
        )));
        assert!(report.violations.iter().any(|violation| matches!(
            violation,
            SaturatingLoadGuardViolation::CpuPressureExceeded { observed, cap }
                if (*observed - 0.95).abs() < f64::EPSILON && (*cap - 0.70).abs() < f64::EPSILON
        )));
    }

    #[test]
    fn saturating_load_guard_requires_enough_samples() {
        let config = SaturatingLoadGuardConfig::new(1024, 1.0, 0.5, 3);
        let sample = SaturatingLoadSample {
            elapsed_ms: 0,
            baseline_rss_bytes: 4096,
            rss_bytes: 4096,
            loadavg_1m: 0.1,
            cpu_pressure: 0.1,
            goodput_bps: 1,
        };

        let report = SaturatingLoadGuardReport::evaluate(config, &[sample]);

        assert!(!report.passed);
        assert_eq!(report.pacer_responsiveness_pressure, 1.0);
        assert_eq!(
            report.violations,
            vec![SaturatingLoadGuardViolation::InsufficientSamples {
                observed: 1,
                required: 3
            }]
        );
    }

    #[test]
    fn anti_amplification_limits() {
        let mut limiter = AntiAmplificationLimiter::new();

        // No peer bytes received yet, so sending any bytes exceeds the budget.
        limiter.on_packet_sent(1000);
        assert!(limiter.is_limited());

        // Receive 400 bytes from the peer: the server may send up to 1200 bytes.
        limiter.on_datagram_received(400);
        assert!(!limiter.is_limited());

        // Sending beyond the 3x received budget is limited.
        limiter.on_packet_sent(201);
        assert!(limiter.is_limited());

        // Receiving an ACK validates the address and lifts the limiter.
        limiter.on_ack_received(0);
        assert!(!limiter.is_limited());
    }

    #[test]
    fn path_stability_tracking() {
        let mut tracker = PathStabilityTracker::new();

        // Add consistent RTT samples
        for _ in 0..10 {
            tracker.update_rtt(50_000); // Consistent 50ms
        }

        let stable_score = tracker.stability_score();
        assert!(
            stable_score > 0.9,
            "Consistent RTT should give high stability"
        );

        // Add variable RTT samples
        for rtt in [25_000, 75_000, 40_000, 90_000, 30_000] {
            tracker.update_rtt(rtt);
        }

        let variable_score = tracker.stability_score();
        assert!(
            variable_score < stable_score,
            "Variable RTT should reduce stability"
        );

        // Add loss events
        tracker.on_packet_lost();
        tracker.on_packet_lost();

        let loss_score = tracker.stability_score();
        assert!(
            loss_score < variable_score,
            "Packet loss should further reduce stability"
        );
    }

    #[test]
    fn metrics_collector_integration() {
        let mut collector =
            AtpTransportMetricsCollector::new("conn123".to_string(), "path456".to_string());

        let mut transport = QuicTransportMachine::new();

        // Send some packets
        collector.on_packet_sent(1200);
        collector.on_packet_sent(1200);

        // Ack one packet
        collector.on_packet_acked(1200);

        // Lose one packet
        collector.on_packet_lost(1200);

        // Record PTO backoff in both the transport machine and collector.
        transport.on_pto_expired();
        transport.on_pto_expired();
        collector.on_pto_expired();
        collector.on_pto_expired();

        let metrics = collector.current_metrics(&transport);

        assert_eq!(metrics.packets_sent, 2);
        assert_eq!(metrics.packets_acked, 1);
        assert_eq!(metrics.packets_lost, 1);
        assert_eq!(metrics.pto_count, 2);
        assert_eq!(metrics.loss_rate, 0.5);
        assert_eq!(metrics.connection_id, "conn123");
        assert_eq!(metrics.path_id, "path456");
    }
}