asx-rs 0.2.0

AS2 and AS4 B2B messaging library for Rust — signing, encryption, MDN, and ebMS3/AS4 profile support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
use std::fmt;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

use crate::core::{AsxError, ErrorCode, ErrorContext, Result};

pub mod file_spool;
pub mod http;

pub use file_spool::{
    As2ProviderHealthFileSpoolIncidentChannel, As4ReceiptTaxonomyFileSpoolIncidentChannel,
    FileSpoolForwardSummary, FileSpoolIdempotencyLedgerPolicy, FileSpoolIncidentConfig,
    FileSpoolIncidentEntry, FileSpoolReplayCheckpoint, FileSpoolReplayCheckpointStatus,
};
pub use http::{
    As2ProviderHealthPagingIncidentChannel, As2ProviderHealthWebhookIncidentChannel,
    As4ReceiptTaxonomyPagingIncidentChannel, As4ReceiptTaxonomyWebhookIncidentChannel,
};

#[cfg(test)]
use crate::observability::{As2ProviderHealthIncidentChannel, As4ReceiptTaxonomyIncidentChannel};
#[cfg(test)]
use file_spool::{
    FileSpoolReplayLedgerFile, now_unix_millis, persist_replay_idempotency_ledger,
    replay_idempotency_ledger_path,
};
#[cfg(test)]
use std::time::Instant;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IncidentQueueOverflowPolicy {
    BestEffortDrop,
    FailClosed,
}

impl IncidentQueueOverflowPolicy {
    fn as_str(self) -> &'static str {
        match self {
            Self::BestEffortDrop => "best_effort_drop",
            Self::FailClosed => "fail_closed",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Configuration for incident channel delivery queuing and backpressure.
///
/// # Backpressure Chain Warning
///
/// ASX has **two independent backpressure points** that interact when `FailClosed` is chosen:
///
/// 1. **`EventBus` backpressure** — the inner event bus has its own channel capacity. When
///    the event bus queue is full, `emit_event` blocks or drops (depending on `EventBus`
///    configuration).
///
/// 2. **Incident channel backpressure** — when the incident queue reaches
///    `queue_capacity`, the emission path waits up to `enqueue_backpressure_wait_millis`
///    before yielding a `FailClosed` error that propagates back through the receive path.
///
/// Under a large burst (replay attack, cascading gateway failures) these two points can
/// form a **deadlock chain**:
///
/// - The receive path fills the `EventBus`.
/// - The `EventBus` worker fills the incident queue.
/// - The incident queue blocks with `FailClosed`, which propagates back to the receive
///   path *as a protocol error*, rejecting otherwise-valid inbound messages.
///
/// ## Recommended mitigations
///
/// - **High-traffic environments**: use `IncidentDeliveryPolicyBundle::BestEffortRealtime`
///   (`BestEffortDrop` overflow policy, 0ms wait) so incident queue pressure never blocks
///   the receive path. Use [`RegulatedHighThroughput`] or custom sizing for regulated
///   environments that need lossless incident delivery.
///
/// - **Rate-limit at the transport layer**: reject or throttle inbound connections
///   upstream (e.g. via nginx `limit_req`) before the burst reaches the incident queue.
///
/// - **Increase `queue_capacity`**: use [`recommend_incident_delivery_config`] with your
///   actual workload `peak_incidents_per_sec` and `sustained_burst_secs` to derive a
///   properly sized queue rather than relying on the 64-slot default.
///
/// - **Separate receive and incident workers**: if operating at very high message
///   rates, run the incident delivery channel on a dedicated Tokio worker pool so that
///   incident queue pressure never affects the protocol receive path.
///
/// [`RegulatedHighThroughput`]: IncidentDeliveryPolicyBundle::RegulatedHighThroughput
pub struct IncidentDeliveryConfig {
    pub queue_capacity: usize,
    pub request_timeout_secs: u64,
    pub enqueue_backpressure_wait_millis: u64,
    pub queue_overflow: IncidentQueueOverflowPolicy,
}

impl Default for IncidentDeliveryConfig {
    fn default() -> Self {
        Self {
            queue_capacity: 64,
            request_timeout_secs: 5,
            enqueue_backpressure_wait_millis: 25,
            queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IncidentDeliveryPolicyBundle {
    RegulatedLowLatency,
    RegulatedHighThroughput,
    BestEffortRealtime,
}

impl IncidentDeliveryPolicyBundle {
    pub fn into_config(self) -> IncidentDeliveryConfig {
        match self {
            Self::RegulatedLowLatency => IncidentDeliveryConfig {
                queue_capacity: 64,
                request_timeout_secs: 5,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
            Self::RegulatedHighThroughput => IncidentDeliveryConfig {
                queue_capacity: 256,
                request_timeout_secs: 5,
                enqueue_backpressure_wait_millis: 100,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
            Self::BestEffortRealtime => IncidentDeliveryConfig {
                queue_capacity: 256,
                request_timeout_secs: 3,
                enqueue_backpressure_wait_millis: 0,
                queue_overflow: IncidentQueueOverflowPolicy::BestEffortDrop,
            },
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IncidentDeliverySizingInput {
    pub peak_incidents_per_sec: usize,
    pub sustained_burst_secs: u64,
    pub delivery_p99_millis: u64,
    pub regulated: bool,
}

#[inline]
fn ceil_div_u64(value: u64, divisor: u64) -> u64 {
    value.saturating_add(divisor.saturating_sub(1)) / divisor
}

#[inline]
fn next_power_of_two_capped(value: usize, cap: usize) -> usize {
    if value <= 1 {
        return 1;
    }

    match value.checked_next_power_of_two() {
        Some(pow2) => pow2.min(cap),
        None => cap,
    }
}

/// Derive a deterministic incident-delivery configuration from workload signals.
///
/// This provides a fail-closed baseline for high-cardinality deployments where
/// queue sizing and timeouts must be explicit and reproducible in reviews.
pub fn recommend_incident_delivery_config(
    input: IncidentDeliverySizingInput,
) -> Result<IncidentDeliveryConfig> {
    if input.peak_incidents_per_sec == 0 {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "incident sizing peak_incidents_per_sec must be greater than zero",
            ErrorContext::new("incident_delivery_sizing"),
        ));
    }

    if input.sustained_burst_secs == 0 {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "incident sizing sustained_burst_secs must be greater than zero",
            ErrorContext::new("incident_delivery_sizing"),
        ));
    }

    if input.delivery_p99_millis == 0 {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "incident sizing delivery_p99_millis must be greater than zero",
            ErrorContext::new("incident_delivery_sizing"),
        ));
    }

    let burst_secs = input.sustained_burst_secs.clamp(1, 30) as usize;
    let projected_backlog = input.peak_incidents_per_sec.saturating_mul(burst_secs);

    let (min_capacity, max_capacity, overflow_policy) = if input.regulated {
        (
            128usize,
            16_384usize,
            IncidentQueueOverflowPolicy::FailClosed,
        )
    } else {
        (
            64usize,
            16_384usize,
            IncidentQueueOverflowPolicy::BestEffortDrop,
        )
    };

    let queue_capacity =
        next_power_of_two_capped(projected_backlog.max(min_capacity), max_capacity)
            .max(min_capacity);

    let request_timeout_secs =
        ceil_div_u64(input.delivery_p99_millis.saturating_mul(4), 1_000).clamp(2, 30);

    let enqueue_backpressure_wait_millis = if input.regulated {
        input.delivery_p99_millis.saturating_mul(2).clamp(25, 750)
    } else {
        0
    };

    Ok(IncidentDeliveryConfig {
        queue_capacity,
        request_timeout_secs,
        enqueue_backpressure_wait_millis,
        queue_overflow: overflow_policy,
    })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IncidentDeliveryMetricsSnapshot {
    pub queue_capacity: usize,
    pub queued_depth: usize,
    pub accepted_total: u64,
    pub dropped_total: u64,
    pub capacity_exhausted_total: u64,
    pub worker_stopped_total: u64,
}

#[derive(Debug)]
struct IncidentDeliveryMetrics {
    queue_capacity: usize,
    queued_depth: AtomicUsize,
    accepted_total: AtomicU64,
    dropped_total: AtomicU64,
    capacity_exhausted_total: AtomicU64,
    worker_stopped_total: AtomicU64,
}

impl IncidentDeliveryMetrics {
    fn new(queue_capacity: usize) -> Self {
        Self {
            queue_capacity,
            queued_depth: AtomicUsize::new(0),
            accepted_total: AtomicU64::new(0),
            dropped_total: AtomicU64::new(0),
            capacity_exhausted_total: AtomicU64::new(0),
            worker_stopped_total: AtomicU64::new(0),
        }
    }

    fn record_enqueue_accepted(&self) {
        self.accepted_total.fetch_add(1, Ordering::Relaxed);
        self.queued_depth.fetch_add(1, Ordering::Relaxed);
    }

    fn record_enqueue_dropped(&self) {
        self.dropped_total.fetch_add(1, Ordering::Relaxed);
    }

    fn record_capacity_exhausted(&self) {
        self.capacity_exhausted_total
            .fetch_add(1, Ordering::Relaxed);
    }

    fn record_worker_stopped(&self) {
        self.worker_stopped_total.fetch_add(1, Ordering::Relaxed);
    }

    fn record_dequeue(&self) {
        let _ = self
            .queued_depth
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                Some(current.saturating_sub(1))
            });
    }

    fn snapshot(&self) -> IncidentDeliveryMetricsSnapshot {
        IncidentDeliveryMetricsSnapshot {
            queue_capacity: self.queue_capacity,
            queued_depth: self.queued_depth.load(Ordering::Relaxed),
            accepted_total: self.accepted_total.load(Ordering::Relaxed),
            dropped_total: self.dropped_total.load(Ordering::Relaxed),
            capacity_exhausted_total: self.capacity_exhausted_total.load(Ordering::Relaxed),
            worker_stopped_total: self.worker_stopped_total.load(Ordering::Relaxed),
        }
    }
}

impl fmt::Display for IncidentDeliveryConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "queue_capacity={}, request_timeout_secs={}, enqueue_backpressure_wait_millis={}, queue_overflow={}",
            self.queue_capacity,
            self.request_timeout_secs,
            self.enqueue_backpressure_wait_millis,
            self.queue_overflow.as_str()
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::path::PathBuf;
    use std::sync::Mutex;
    use std::thread;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    use crate::observability::{
        As2ProviderHealthAlertCategory, As2ProviderHealthAlertIncident,
        As2ProviderHealthAlertSeverity, As4ReceiptTaxonomyAlertCategory,
        As4ReceiptTaxonomyAlertIncident, As4ReceiptTaxonomyAlertSeverity,
    };

    fn read_http_request(mut stream: TcpStream) -> String {
        let mut header = Vec::new();
        let mut byte = [0u8; 1];

        loop {
            stream.read_exact(&mut byte).expect("read request byte");
            header.push(byte[0]);
            if header.ends_with(b"\r\n\r\n") {
                break;
            }
        }

        let header_text = String::from_utf8(header.clone()).expect("valid utf8 headers");
        let content_length = header_text
            .lines()
            .find_map(|line| {
                let lower = line.to_ascii_lowercase();
                lower
                    .strip_prefix("content-length: ")
                    .and_then(|value| value.trim().parse::<usize>().ok())
            })
            .unwrap_or(0);

        let mut body = vec![0u8; content_length];
        if content_length > 0 {
            stream.read_exact(&mut body).expect("read request body");
        }

        stream
            .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
            .expect("write response");

        header.extend_from_slice(&body);
        String::from_utf8(header).expect("valid utf8 request")
    }

    fn unique_spool_path(prefix: &str) -> PathBuf {
        let now_nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        std::env::temp_dir().join(format!("asx-{prefix}-{now_nanos}.jsonl"))
    }

    fn unique_checkpoint_path(prefix: &str) -> PathBuf {
        let now_nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        std::env::temp_dir().join(format!("asx-{prefix}-{now_nanos}.checkpoint.json"))
    }

    #[derive(Debug)]
    struct RecordingAs2Channel {
        sent: Mutex<Vec<String>>,
        fail_after: Option<usize>,
    }

    impl RecordingAs2Channel {
        fn new(fail_after: Option<usize>) -> Self {
            Self {
                sent: Mutex::new(Vec::new()),
                fail_after,
            }
        }
    }

    impl As2ProviderHealthIncidentChannel for RecordingAs2Channel {
        fn send_incident(&self, incident: &As2ProviderHealthAlertIncident) -> Result<()> {
            let mut sent = self.sent.lock().expect("lock recording channel");
            if let Some(limit) = self.fail_after
                && sent.len() >= limit
            {
                return Err(AsxError::new(
                    ErrorCode::ReliabilityFailure,
                    "simulated as2 forward failure",
                    ErrorContext::new("recording_as2_channel"),
                ));
            }
            sent.push(incident.dedup_key.clone());
            Ok(())
        }
    }

    #[derive(Debug)]
    struct RecordingAs4Channel {
        sent: Mutex<Vec<String>>,
        fail_after: Option<usize>,
    }

    impl RecordingAs4Channel {
        fn new(fail_after: Option<usize>) -> Self {
            Self {
                sent: Mutex::new(Vec::new()),
                fail_after,
            }
        }
    }

    impl As4ReceiptTaxonomyIncidentChannel for RecordingAs4Channel {
        fn send_incident(&self, incident: &As4ReceiptTaxonomyAlertIncident) -> Result<()> {
            let mut sent = self.sent.lock().expect("lock recording channel");
            if let Some(limit) = self.fail_after
                && sent.len() >= limit
            {
                return Err(AsxError::new(
                    ErrorCode::ReliabilityFailure,
                    "simulated as4 forward failure",
                    ErrorContext::new("recording_as4_channel"),
                ));
            }
            sent.push(incident.dedup_key.clone());
            Ok(())
        }
    }

    fn as2_incident(dedup_key: &str) -> As2ProviderHealthAlertIncident {
        As2ProviderHealthAlertIncident {
            dedup_key: dedup_key.to_string(),
            signal: "as2",
            severity: As2ProviderHealthAlertSeverity::Critical,
            category: As2ProviderHealthAlertCategory::TransitionToFailingRate,
            observed_rate_ppm: 600_000,
            sample_size: 20,
            runbook_hint: "Investigate provider health.",
        }
    }

    #[test]
    fn policy_bundle_regulated_low_latency_maps_to_fail_closed_defaults() {
        let config = IncidentDeliveryPolicyBundle::RegulatedLowLatency.into_config();
        assert_eq!(config.queue_capacity, 64);
        assert_eq!(config.request_timeout_secs, 5);
        assert_eq!(config.enqueue_backpressure_wait_millis, 25);
        assert_eq!(
            config.queue_overflow,
            IncidentQueueOverflowPolicy::FailClosed
        );
    }

    #[test]
    fn policy_bundle_best_effort_realtime_maps_to_drop_policy() {
        let config = IncidentDeliveryPolicyBundle::BestEffortRealtime.into_config();
        assert_eq!(config.queue_capacity, 256);
        assert_eq!(config.request_timeout_secs, 3);
        assert_eq!(config.enqueue_backpressure_wait_millis, 0);
        assert_eq!(
            config.queue_overflow,
            IncidentQueueOverflowPolicy::BestEffortDrop
        );
    }

    #[test]
    fn recommend_incident_delivery_config_regulated_maps_to_fail_closed_profile() {
        let config = recommend_incident_delivery_config(IncidentDeliverySizingInput {
            peak_incidents_per_sec: 300,
            sustained_burst_secs: 4,
            delivery_p99_millis: 180,
            regulated: true,
        })
        .expect("regulated sizing recommendation must succeed");

        assert_eq!(config.queue_capacity, 2048);
        assert_eq!(config.request_timeout_secs, 2);
        assert_eq!(config.enqueue_backpressure_wait_millis, 360);
        assert_eq!(
            config.queue_overflow,
            IncidentQueueOverflowPolicy::FailClosed
        );
    }

    #[test]
    fn recommend_incident_delivery_config_best_effort_maps_to_drop_profile() {
        let config = recommend_incident_delivery_config(IncidentDeliverySizingInput {
            peak_incidents_per_sec: 40,
            sustained_burst_secs: 2,
            delivery_p99_millis: 900,
            regulated: false,
        })
        .expect("best-effort sizing recommendation must succeed");

        assert_eq!(config.queue_capacity, 128);
        assert_eq!(config.request_timeout_secs, 4);
        assert_eq!(config.enqueue_backpressure_wait_millis, 0);
        assert_eq!(
            config.queue_overflow,
            IncidentQueueOverflowPolicy::BestEffortDrop
        );
    }

    #[test]
    fn recommend_incident_delivery_config_rejects_zero_inputs() {
        let err = recommend_incident_delivery_config(IncidentDeliverySizingInput {
            peak_incidents_per_sec: 0,
            sustained_burst_secs: 1,
            delivery_p99_millis: 100,
            regulated: true,
        })
        .expect_err("zero peak incidents must fail fast");
        assert_eq!(err.code, ErrorCode::InvalidInput);

        let err = recommend_incident_delivery_config(IncidentDeliverySizingInput {
            peak_incidents_per_sec: 10,
            sustained_burst_secs: 0,
            delivery_p99_millis: 100,
            regulated: true,
        })
        .expect_err("zero burst window must fail fast");
        assert_eq!(err.code, ErrorCode::InvalidInput);

        let err = recommend_incident_delivery_config(IncidentDeliverySizingInput {
            peak_incidents_per_sec: 10,
            sustained_burst_secs: 1,
            delivery_p99_millis: 0,
            regulated: true,
        })
        .expect_err("zero delivery p99 must fail fast");
        assert_eq!(err.code, ErrorCode::InvalidInput);
    }

    #[test]
    fn as2_webhook_channel_posts_json_payload() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let addr = listener.local_addr().expect("local addr");
        let server = thread::spawn(move || {
            let (stream, _) = listener.accept().expect("accept request");
            read_http_request(stream)
        });

        let channel = As2ProviderHealthWebhookIncidentChannel::with_raw_config(
            format!("http://{addr}"),
            IncidentDeliveryConfig {
                queue_capacity: 8,
                request_timeout_secs: 2,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect("construct webhook channel");

        let incident = As2ProviderHealthAlertIncident {
            dedup_key: "as2:provider-health:critical:transition_to_failing_rate".to_string(),
            signal: "as2",
            severity: As2ProviderHealthAlertSeverity::Critical,
            category: As2ProviderHealthAlertCategory::TransitionToFailingRate,
            observed_rate_ppm: 600_000,
            sample_size: 20,
            runbook_hint: "Investigate provider health.",
        };

        channel.send_incident(&incident).expect("enqueue incident");
        let request = server.join().expect("server thread");
        assert!(request.contains("POST / HTTP/1.1"));
        assert!(request.contains("\"adapter\":\"as2_provider_health_webhook\""));
        assert!(request.contains("\"protocol\":\"as2\""));
        assert!(
            request.contains(
                "\"dedup_key\":\"as2:provider-health:critical:transition_to_failing_rate\""
            )
        );
    }

    #[test]
    fn as4_webhook_channel_posts_json_payload() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let addr = listener.local_addr().expect("local addr");
        let server = thread::spawn(move || {
            let (stream, _) = listener.accept().expect("accept request");
            read_http_request(stream)
        });

        let channel = As4ReceiptTaxonomyWebhookIncidentChannel::with_raw_config(
            format!("http://{addr}"),
            IncidentDeliveryConfig {
                queue_capacity: 8,
                request_timeout_secs: 2,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect("construct webhook channel");

        let incident = As4ReceiptTaxonomyAlertIncident {
            dedup_key: "as4:receipt-taxonomy:critical:security_verification_failed".to_string(),
            signal: "as4",
            severity: As4ReceiptTaxonomyAlertSeverity::Critical,
            category: As4ReceiptTaxonomyAlertCategory::SecurityVerificationFailed,
            observed_rate_ppm: 75_000,
            sample_size: 100,
            runbook_hint: "Check WS-Security signature verification.",
        };

        channel.send_incident(&incident).expect("enqueue incident");
        let request = server.join().expect("server thread");
        assert!(request.contains("POST / HTTP/1.1"));
        assert!(request.contains("\"adapter\":\"as4_receipt_taxonomy_webhook\""));
        assert!(request.contains("\"protocol\":\"as4\""));
        assert!(request.contains(
            "\"dedup_key\":\"as4:receipt-taxonomy:critical:security_verification_failed\""
        ));
    }

    #[test]
    fn as2_paging_channel_posts_json_payload() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let addr = listener.local_addr().expect("local addr");
        let server = thread::spawn(move || {
            let (stream, _) = listener.accept().expect("accept request");
            read_http_request(stream)
        });

        let channel = As2ProviderHealthPagingIncidentChannel::with_raw_config(
            format!("http://{addr}"),
            "routing-key-123",
            "asx-test-service",
            IncidentDeliveryConfig {
                queue_capacity: 8,
                request_timeout_secs: 2,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect("construct paging channel");

        let incident = As2ProviderHealthAlertIncident {
            dedup_key: "as2:provider-health:critical:transition_to_failing_rate".to_string(),
            signal: "as2",
            severity: As2ProviderHealthAlertSeverity::Critical,
            category: As2ProviderHealthAlertCategory::TransitionToFailingRate,
            observed_rate_ppm: 600_000,
            sample_size: 20,
            runbook_hint: "Investigate provider health.",
        };

        channel.send_incident(&incident).expect("enqueue incident");
        let request = server.join().expect("server thread");
        assert!(request.contains("POST / HTTP/1.1"));
        assert!(request.contains("\"routing_key\":\"routing-key-123\""));
        assert!(request.contains("\"source\":\"asx-test-service\""));
        assert!(request.contains(
            "\"summary\":\"AS2 provider-health incident: critical transition_to_failing_rate\""
        ));
    }

    #[test]
    fn as4_paging_channel_posts_json_payload() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let addr = listener.local_addr().expect("local addr");
        let server = thread::spawn(move || {
            let (stream, _) = listener.accept().expect("accept request");
            read_http_request(stream)
        });

        let channel = As4ReceiptTaxonomyPagingIncidentChannel::with_raw_config(
            format!("http://{addr}"),
            "routing-key-456",
            "asx-test-service",
            IncidentDeliveryConfig {
                queue_capacity: 8,
                request_timeout_secs: 2,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect("construct paging channel");

        let incident = As4ReceiptTaxonomyAlertIncident {
            dedup_key: "as4:receipt-taxonomy:critical:security_verification_failed".to_string(),
            signal: "as4",
            severity: As4ReceiptTaxonomyAlertSeverity::Critical,
            category: As4ReceiptTaxonomyAlertCategory::SecurityVerificationFailed,
            observed_rate_ppm: 75_000,
            sample_size: 100,
            runbook_hint: "Check WS-Security signature verification.",
        };

        channel.send_incident(&incident).expect("enqueue incident");
        let request = server.join().expect("server thread");
        assert!(request.contains("POST / HTTP/1.1"));
        assert!(request.contains("\"routing_key\":\"routing-key-456\""));
        assert!(request.contains("\"source\":\"asx-test-service\""));
        assert!(request.contains(
            "\"summary\":\"AS4 receipt-taxonomy incident: critical security_verification_failed\""
        ));
    }

    #[test]
    fn webhook_channel_rejects_zero_queue_capacity() {
        let err = As2ProviderHealthWebhookIncidentChannel::with_raw_config(
            "http://127.0.0.1:9",
            IncidentDeliveryConfig {
                queue_capacity: 0,
                request_timeout_secs: 1,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect_err("zero queue capacity must fail fast");
        assert_eq!(err.code, ErrorCode::InvalidInput);
    }

    #[test]
    fn webhook_channel_rejects_zero_request_timeout_secs() {
        let err = As2ProviderHealthWebhookIncidentChannel::with_raw_config(
            "http://127.0.0.1:9",
            IncidentDeliveryConfig {
                queue_capacity: 1,
                request_timeout_secs: 0,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect_err("zero request timeout must fail fast");
        assert_eq!(err.code, ErrorCode::InvalidInput);
    }

    #[test]
    fn webhook_channel_shutdown_and_drain_is_deterministic() {
        let mut channel = As2ProviderHealthWebhookIncidentChannel::with_raw_config(
            "http://127.0.0.1:9",
            IncidentDeliveryConfig {
                queue_capacity: 4,
                request_timeout_secs: 1,
                enqueue_backpressure_wait_millis: 25,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect("construct webhook channel");

        channel
            .shutdown_and_drain(Duration::from_millis(500))
            .expect("shutdown and drain");

        let incident = As2ProviderHealthAlertIncident {
            dedup_key: "as2:provider-health:critical:transition_to_failing_rate".to_string(),
            signal: "as2",
            severity: As2ProviderHealthAlertSeverity::Critical,
            category: As2ProviderHealthAlertCategory::TransitionToFailingRate,
            observed_rate_ppm: 600_000,
            sample_size: 20,
            runbook_hint: "Investigate provider health.",
        };

        let err = channel
            .send_incident(&incident)
            .expect_err("sending after shutdown must fail");
        assert_eq!(err.code, ErrorCode::TransportFailure);
    }

    #[test]
    fn fail_closed_reports_capacity_when_queue_stays_full_without_wait_budget() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let addr = listener.local_addr().expect("local addr");
        let server = thread::spawn(move || {
            let (mut stream, _) = listener.accept().expect("accept request");
            thread::sleep(Duration::from_millis(300));
            let _ = stream
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
        });

        let channel = As2ProviderHealthWebhookIncidentChannel::with_raw_config(
            format!("http://{addr}"),
            IncidentDeliveryConfig {
                queue_capacity: 1,
                request_timeout_secs: 1,
                enqueue_backpressure_wait_millis: 0,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect("construct webhook channel");

        channel
            .send_incident(&as2_incident("as2:test:burst:1"))
            .expect("enqueue first incident");

        thread::sleep(Duration::from_millis(20));

        let fill_deadline = Instant::now() + Duration::from_millis(200);
        loop {
            let second_result = channel.send_incident(&as2_incident("as2:test:burst:2"));
            if second_result.is_ok() {
                break;
            }
            if Instant::now() >= fill_deadline {
                panic!("failed to enqueue second incident before deadline");
            }
            thread::sleep(Duration::from_millis(1));
        }

        let err = channel
            .send_incident(&as2_incident("as2:test:burst:3"))
            .expect_err("third incident must fail closed when queue remains saturated");
        assert_eq!(err.code, ErrorCode::CapacityExhausted);

        let metrics = channel.metrics_snapshot();
        assert_eq!(metrics.queue_capacity, 1);
        assert_eq!(metrics.accepted_total, 2);
        assert_eq!(metrics.capacity_exhausted_total, 1);
        assert_eq!(metrics.dropped_total, 0);

        let _ = server.join();
    }

    #[test]
    fn best_effort_drop_updates_exact_metrics_snapshot() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let addr = listener.local_addr().expect("local addr");
        let server = thread::spawn(move || {
            let (first, _) = listener.accept().expect("accept first request");
            thread::sleep(Duration::from_millis(150));
            let _ = read_http_request(first);
            let (second, _) = listener.accept().expect("accept second request");
            let _ = read_http_request(second);
        });

        let channel = As2ProviderHealthWebhookIncidentChannel::with_raw_config(
            format!("http://{addr}"),
            IncidentDeliveryConfig {
                queue_capacity: 1,
                request_timeout_secs: 1,
                enqueue_backpressure_wait_millis: 0,
                queue_overflow: IncidentQueueOverflowPolicy::BestEffortDrop,
            },
        )
        .expect("construct webhook channel");

        channel
            .send_incident(&as2_incident("as2:test:drop:1"))
            .expect("enqueue first incident");

        thread::sleep(Duration::from_millis(20));

        let fill_deadline = Instant::now() + Duration::from_millis(200);
        loop {
            let second_result = channel.send_incident(&as2_incident("as2:test:drop:2"));
            if second_result.is_ok() {
                break;
            }
            if Instant::now() >= fill_deadline {
                panic!("failed to enqueue second incident before deadline");
            }
            thread::sleep(Duration::from_millis(1));
        }

        channel
            .send_incident(&as2_incident("as2:test:drop:3"))
            .expect("third incident should be dropped by policy, not error");

        let metrics = channel.metrics_snapshot();
        assert_eq!(metrics.queue_capacity, 1);
        assert_eq!(metrics.accepted_total, 2);
        assert_eq!(metrics.dropped_total, 1);
        assert_eq!(metrics.capacity_exhausted_total, 0);

        let _ = server.join();
    }

    #[test]
    fn fail_closed_wait_budget_absorbs_transient_queue_saturation() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
        let addr = listener.local_addr().expect("local addr");
        let server = thread::spawn(move || {
            let (first, _) = listener.accept().expect("accept first request");
            thread::sleep(Duration::from_millis(120));
            let _ = read_http_request(first);
            let (second, _) = listener.accept().expect("accept second request");
            let _ = read_http_request(second);
        });

        let channel = As2ProviderHealthWebhookIncidentChannel::with_raw_config(
            format!("http://{addr}"),
            IncidentDeliveryConfig {
                queue_capacity: 1,
                request_timeout_secs: 1,
                enqueue_backpressure_wait_millis: 300,
                queue_overflow: IncidentQueueOverflowPolicy::FailClosed,
            },
        )
        .expect("construct webhook channel");

        channel
            .send_incident(&as2_incident("as2:test:recovery:1"))
            .expect("enqueue first incident");
        thread::sleep(Duration::from_millis(20));

        let fill_deadline = Instant::now() + Duration::from_millis(200);
        loop {
            let second_result = channel.send_incident(&as2_incident("as2:test:recovery:2"));
            if second_result.is_ok() {
                break;
            }
            if Instant::now() >= fill_deadline {
                panic!("failed to enqueue second incident before deadline");
            }
            thread::sleep(Duration::from_millis(1));
        }

        channel
            .send_incident(&as2_incident("as2:test:recovery:3"))
            .expect("third incident should enqueue after transient saturation clears");

        let _ = server.join();
    }

    #[test]
    fn as2_file_spool_channel_appends_incident_jsonl() {
        let path = unique_spool_path("as2-incident-spool");
        let channel =
            As2ProviderHealthFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as2 file spool channel");

        let incident = As2ProviderHealthAlertIncident {
            dedup_key: "as2:provider-health:critical:transition_to_failing_rate".to_string(),
            signal: "as2",
            severity: As2ProviderHealthAlertSeverity::Critical,
            category: As2ProviderHealthAlertCategory::TransitionToFailingRate,
            observed_rate_ppm: 600_000,
            sample_size: 20,
            runbook_hint: "Investigate provider health.",
        };

        channel.send_incident(&incident).expect("spool incident");

        let contents = fs::read_to_string(&path).expect("read spool file");
        assert!(contents.contains("\"adapter\":\"as2_provider_health_file_spool\""));
        assert!(contents.contains("\"protocol\":\"as2\""));
        assert!(
            contents.contains(
                "\"dedup_key\":\"as2:provider-health:critical:transition_to_failing_rate\""
            )
        );

        let _ = fs::remove_file(&path);
    }

    #[test]
    fn as4_file_spool_channel_appends_incident_jsonl() {
        let path = unique_spool_path("as4-incident-spool");
        let channel =
            As4ReceiptTaxonomyFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as4 file spool channel");

        let incident = As4ReceiptTaxonomyAlertIncident {
            dedup_key: "as4:receipt-taxonomy:critical:security_verification_failed".to_string(),
            signal: "as4",
            severity: As4ReceiptTaxonomyAlertSeverity::Critical,
            category: As4ReceiptTaxonomyAlertCategory::SecurityVerificationFailed,
            observed_rate_ppm: 75_000,
            sample_size: 100,
            runbook_hint: "Check WS-Security signature verification.",
        };

        channel.send_incident(&incident).expect("spool incident");

        let contents = fs::read_to_string(&path).expect("read spool file");
        assert!(contents.contains("\"adapter\":\"as4_receipt_taxonomy_file_spool\""));
        assert!(contents.contains("\"protocol\":\"as4\""));
        assert!(contents.contains(
            "\"dedup_key\":\"as4:receipt-taxonomy:critical:security_verification_failed\""
        ));

        let _ = fs::remove_file(&path);
    }

    #[test]
    fn as2_file_spool_channel_replay_and_drain_are_deterministic() {
        let path = unique_spool_path("as2-incident-spool-replay");
        let channel =
            As2ProviderHealthFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as2 file spool channel");

        let incident = As2ProviderHealthAlertIncident {
            dedup_key: "as2:provider-health:critical:transition_to_failing_rate".to_string(),
            signal: "as2",
            severity: As2ProviderHealthAlertSeverity::Critical,
            category: As2ProviderHealthAlertCategory::TransitionToFailingRate,
            observed_rate_ppm: 600_000,
            sample_size: 20,
            runbook_hint: "Investigate provider health.",
        };

        channel.send_incident(&incident).expect("spool incident");

        let replayed = channel
            .replay_spooled_incidents()
            .expect("replay spooled incidents");
        assert_eq!(replayed.len(), 1);
        assert_eq!(replayed[0].protocol, "as2");
        assert_eq!(
            replayed[0].dedup_key,
            "as2:provider-health:critical:transition_to_failing_rate"
        );

        let contents_after_replay =
            fs::read_to_string(&path).expect("read spool file after replay");
        assert!(!contents_after_replay.trim().is_empty());

        let drained = channel
            .drain_spooled_incidents()
            .expect("drain spooled incidents");
        assert_eq!(drained.len(), 1);
        assert_eq!(drained[0].protocol, "as2");

        let contents_after_drain = fs::read_to_string(&path).expect("read spool file after drain");
        assert!(contents_after_drain.trim().is_empty());

        let _ = fs::remove_file(&path);
    }

    #[test]
    fn as4_file_spool_channel_drain_returns_entries_and_truncates_file() {
        let path = unique_spool_path("as4-incident-spool-drain");
        let channel =
            As4ReceiptTaxonomyFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as4 file spool channel");

        let incident = As4ReceiptTaxonomyAlertIncident {
            dedup_key: "as4:receipt-taxonomy:critical:security_verification_failed".to_string(),
            signal: "as4",
            severity: As4ReceiptTaxonomyAlertSeverity::Critical,
            category: As4ReceiptTaxonomyAlertCategory::SecurityVerificationFailed,
            observed_rate_ppm: 75_000,
            sample_size: 100,
            runbook_hint: "Check WS-Security signature verification.",
        };

        channel.send_incident(&incident).expect("spool incident");

        let drained = channel
            .drain_spooled_incidents()
            .expect("drain spooled incidents");
        assert_eq!(drained.len(), 1);
        assert_eq!(drained[0].protocol, "as4");
        assert_eq!(
            drained[0].dedup_key,
            "as4:receipt-taxonomy:critical:security_verification_failed"
        );

        let contents_after_drain = fs::read_to_string(&path).expect("read spool file after drain");
        assert!(contents_after_drain.trim().is_empty());

        let _ = fs::remove_file(&path);
    }

    #[test]
    fn as2_file_spool_drain_forward_writes_committed_checkpoint() {
        let path = unique_spool_path("as2-incident-forward");
        let checkpoint_path = unique_checkpoint_path("as2-incident-forward");
        let ledger_path = replay_idempotency_ledger_path(&checkpoint_path);
        let channel =
            As2ProviderHealthFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as2 file spool channel");

        channel
            .send_incident(&as2_incident("as2:forward:test:1"))
            .expect("spool first incident");
        channel
            .send_incident(&as2_incident("as2:forward:test:2"))
            .expect("spool second incident");

        let downstream = RecordingAs2Channel::new(None);
        let summary = channel
            .drain_and_forward_with_checkpoint(&downstream, checkpoint_path.clone())
            .expect("drain and forward with checkpoint");

        assert_eq!(summary.checkpoint.status, "committed");
        assert_eq!(summary.checkpoint.forwarded_entries, 2);
        assert_eq!(summary.checkpoint.skipped_duplicate_entries, 0);
        assert_eq!(summary.checkpoint.requeued_entries, 0);

        let remaining = channel
            .replay_spooled_incidents()
            .expect("replay remaining incidents");
        assert!(remaining.is_empty());

        let checkpoint_contents =
            fs::read_to_string(&checkpoint_path).expect("read checkpoint file");
        let checkpoint: FileSpoolReplayCheckpoint =
            serde_json::from_str(&checkpoint_contents).expect("parse checkpoint json");
        assert_eq!(checkpoint.status, "committed");
        assert_eq!(checkpoint.forwarded_entries, 2);
        assert_eq!(checkpoint.skipped_duplicate_entries, 0);

        let sent = downstream.sent.lock().expect("lock sent list");
        assert_eq!(sent.len(), 2);

        let _ = fs::remove_file(&path);
        let _ = fs::remove_file(&checkpoint_path);
        let _ = fs::remove_file(&ledger_path);
    }

    #[test]
    fn as4_file_spool_drain_forward_failure_requeues_and_checkpoints_failed() {
        let path = unique_spool_path("as4-incident-forward-failure");
        let checkpoint_path = unique_checkpoint_path("as4-incident-forward-failure");
        let ledger_path = replay_idempotency_ledger_path(&checkpoint_path);
        let channel =
            As4ReceiptTaxonomyFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as4 file spool channel");

        let first = As4ReceiptTaxonomyAlertIncident {
            dedup_key: "as4:forward:test:1".to_string(),
            signal: "as4",
            severity: As4ReceiptTaxonomyAlertSeverity::Critical,
            category: As4ReceiptTaxonomyAlertCategory::SecurityVerificationFailed,
            observed_rate_ppm: 75_000,
            sample_size: 100,
            runbook_hint: "Check WS-Security signature verification.",
        };
        let second = As4ReceiptTaxonomyAlertIncident {
            dedup_key: "as4:forward:test:2".to_string(),
            signal: "as4",
            severity: As4ReceiptTaxonomyAlertSeverity::Warning,
            category: As4ReceiptTaxonomyAlertCategory::SemanticInteropFailure,
            observed_rate_ppm: 25_000,
            sample_size: 100,
            runbook_hint: "Review interoperability profile mapping and payload semantics.",
        };

        channel.send_incident(&first).expect("spool first incident");
        channel
            .send_incident(&second)
            .expect("spool second incident");

        let downstream = RecordingAs4Channel::new(Some(1));
        let err = channel
            .drain_and_forward_with_checkpoint(&downstream, checkpoint_path.clone())
            .expect_err("forward must fail on second incident");
        assert_eq!(err.code, ErrorCode::ReliabilityFailure);

        let remaining = channel
            .replay_spooled_incidents()
            .expect("replay remaining incidents");
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].dedup_key, "as4:forward:test:2");

        let checkpoint_contents =
            fs::read_to_string(&checkpoint_path).expect("read checkpoint file");
        let checkpoint: FileSpoolReplayCheckpoint =
            serde_json::from_str(&checkpoint_contents).expect("parse checkpoint json");
        assert_eq!(checkpoint.status, "failed");
        assert_eq!(checkpoint.forwarded_entries, 1);
        assert_eq!(checkpoint.skipped_duplicate_entries, 0);
        assert_eq!(checkpoint.requeued_entries, 1);

        let sent = downstream.sent.lock().expect("lock sent list");
        assert_eq!(sent.len(), 1);

        let _ = fs::remove_file(&path);
        let _ = fs::remove_file(&checkpoint_path);
        let _ = fs::remove_file(&ledger_path);
    }

    #[test]
    fn as4_file_spool_forward_failure_requeues_remaining_tail_entries() {
        let path = unique_spool_path("as4-incident-forward-tail-requeue");
        let checkpoint_path = unique_checkpoint_path("as4-incident-forward-tail-requeue");
        let ledger_path = replay_idempotency_ledger_path(&checkpoint_path);
        let channel =
            As4ReceiptTaxonomyFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as4 file spool channel");

        for key in [
            "as4:forward:tail:1",
            "as4:forward:tail:2",
            "as4:forward:tail:3",
        ] {
            let incident = As4ReceiptTaxonomyAlertIncident {
                dedup_key: key.to_string(),
                signal: "as4",
                severity: As4ReceiptTaxonomyAlertSeverity::Critical,
                category: As4ReceiptTaxonomyAlertCategory::SecurityVerificationFailed,
                observed_rate_ppm: 75_000,
                sample_size: 100,
                runbook_hint: "Check WS-Security signature verification.",
            };
            channel.send_incident(&incident).expect("spool incident");
        }

        let downstream = RecordingAs4Channel::new(Some(1));
        let err = channel
            .drain_and_forward_with_checkpoint(&downstream, checkpoint_path.clone())
            .expect_err("forward must fail on second incident");
        assert_eq!(err.code, ErrorCode::ReliabilityFailure);

        let remaining = channel
            .replay_spooled_incidents()
            .expect("replay remaining incidents");
        assert_eq!(remaining.len(), 2);
        assert_eq!(remaining[0].dedup_key, "as4:forward:tail:2");
        assert_eq!(remaining[1].dedup_key, "as4:forward:tail:3");

        let _ = fs::remove_file(&path);
        let _ = fs::remove_file(&checkpoint_path);
        let _ = fs::remove_file(&ledger_path);
    }

    #[test]
    fn as2_file_spool_forward_skips_already_forwarded_dedup_keys_across_runs() {
        let path = unique_spool_path("as2-incident-forward-idempotent");
        let checkpoint_path = unique_checkpoint_path("as2-incident-forward-idempotent");
        let ledger_path = replay_idempotency_ledger_path(&checkpoint_path);
        let channel =
            As2ProviderHealthFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as2 file spool channel");

        channel
            .send_incident(&as2_incident("as2:forward:idempotent:1"))
            .expect("spool first incident");
        let downstream_first = RecordingAs2Channel::new(None);
        let first_summary = channel
            .drain_and_forward_with_checkpoint(&downstream_first, checkpoint_path.clone())
            .expect("forward first run");
        assert_eq!(first_summary.checkpoint.forwarded_entries, 1);
        assert_eq!(first_summary.checkpoint.skipped_duplicate_entries, 0);

        channel
            .send_incident(&as2_incident("as2:forward:idempotent:1"))
            .expect("spool duplicate incident");
        let downstream_second = RecordingAs2Channel::new(None);
        let second_summary = channel
            .drain_and_forward_with_checkpoint(&downstream_second, checkpoint_path.clone())
            .expect("forward second run");
        assert_eq!(second_summary.checkpoint.forwarded_entries, 0);
        assert_eq!(second_summary.checkpoint.skipped_duplicate_entries, 1);
        assert_eq!(second_summary.checkpoint.requeued_entries, 0);

        let sent_first = downstream_first.sent.lock().expect("lock first sent list");
        assert_eq!(sent_first.len(), 1);
        let sent_second = downstream_second
            .sent
            .lock()
            .expect("lock second sent list");
        assert_eq!(sent_second.len(), 0);

        let _ = fs::remove_file(&path);
        let _ = fs::remove_file(&checkpoint_path);
        let _ = fs::remove_file(&ledger_path);
    }

    #[test]
    fn as2_file_spool_ledger_compacts_to_max_entries() {
        let path = unique_spool_path("as2-ledger-max-entries");
        let checkpoint_path = unique_checkpoint_path("as2-ledger-max-entries");
        let ledger_path = replay_idempotency_ledger_path(&checkpoint_path);
        let channel =
            As2ProviderHealthFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy {
                    max_entries: 2,
                    retention_secs: 86_400,
                },
            })
            .expect("construct as2 file spool channel");

        for key in ["as2:ledger:max:1", "as2:ledger:max:2", "as2:ledger:max:3"] {
            channel
                .send_incident(&as2_incident(key))
                .expect("spool incident");
        }

        let downstream = RecordingAs2Channel::new(None);
        let summary = channel
            .drain_and_forward_with_checkpoint(&downstream, checkpoint_path.clone())
            .expect("forward incidents");
        assert_eq!(summary.checkpoint.forwarded_entries, 3);

        let ledger_contents = fs::read_to_string(&ledger_path).expect("read ledger file");
        let ledger: FileSpoolReplayLedgerFile =
            serde_json::from_str(&ledger_contents).expect("parse ledger json");
        assert_eq!(ledger.entries.len(), 2);

        let mut keys: Vec<String> = ledger.entries.into_iter().map(|e| e.dedup_key).collect();
        keys.sort();
        assert_eq!(
            keys,
            vec![
                "as2:ledger:max:2".to_string(),
                "as2:ledger:max:3".to_string()
            ]
        );

        let _ = fs::remove_file(&path);
        let _ = fs::remove_file(&checkpoint_path);
        let _ = fs::remove_file(&ledger_path);
    }

    #[test]
    fn as2_file_spool_ledger_retention_evicts_stale_dedup_keys() {
        let path = unique_spool_path("as2-ledger-retention");
        let checkpoint_path = unique_checkpoint_path("as2-ledger-retention");
        let ledger_path = replay_idempotency_ledger_path(&checkpoint_path);
        let channel =
            As2ProviderHealthFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy {
                    max_entries: 100,
                    retention_secs: 1,
                },
            })
            .expect("construct as2 file spool channel");

        let stale_millis = now_unix_millis().saturating_sub(60_000);
        let stale_ledger =
            std::collections::HashMap::from([("as2:ledger:retention:1".to_string(), stale_millis)]);
        persist_replay_idempotency_ledger(&ledger_path, &stale_ledger)
            .expect("seed stale ledger entry");

        channel
            .send_incident(&as2_incident("as2:ledger:retention:1"))
            .expect("spool duplicate of stale key");

        let downstream = RecordingAs2Channel::new(None);
        let summary = channel
            .drain_and_forward_with_checkpoint(&downstream, checkpoint_path.clone())
            .expect("forward incident after retention compaction");
        assert_eq!(summary.checkpoint.forwarded_entries, 1);
        assert_eq!(summary.checkpoint.skipped_duplicate_entries, 0);

        let sent = downstream.sent.lock().expect("lock sent list");
        assert_eq!(sent.len(), 1);

        let _ = fs::remove_file(&path);
        let _ = fs::remove_file(&checkpoint_path);
        let _ = fs::remove_file(&ledger_path);
    }

    #[test]
    fn as2_file_spool_rejects_legacy_newline_ledger_format() {
        let path = unique_spool_path("as2-ledger-legacy-format");
        let checkpoint_path = unique_checkpoint_path("as2-ledger-legacy-format");
        let ledger_path = replay_idempotency_ledger_path(&checkpoint_path);
        let channel =
            As2ProviderHealthFileSpoolIncidentChannel::with_config(FileSpoolIncidentConfig {
                path: path.clone(),
                fsync_each_write: true,
                idempotency_ledger_policy: FileSpoolIdempotencyLedgerPolicy::default(),
            })
            .expect("construct as2 file spool channel");

        fs::write(&ledger_path, "as2:legacy:key-1\nas2:legacy:key-2\n")
            .expect("write legacy newline ledger");

        channel
            .send_incident(&as2_incident("as2:legacy:key-1"))
            .expect("spool incident");

        let downstream = RecordingAs2Channel::new(None);
        let err = channel
            .drain_and_forward_with_checkpoint(&downstream, checkpoint_path.clone())
            .expect_err("legacy newline ledger should fail to load");
        assert_eq!(err.code, ErrorCode::ReliabilityFailure);

        let _ = fs::remove_file(&path);
        let _ = fs::remove_file(&checkpoint_path);
        let _ = fs::remove_file(&ledger_path);
    }
}