ftui-extras 0.3.1

Feature-gated extras for FrankenTUI (markdown, charts, clipboard, themes).
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
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
#![forbid(unsafe_code)]

//! Async validation with deterministic concurrency and token-based staleness prevention.
//!
//! This module provides infrastructure for async validators that:
//! - Use monotonic tokens to track input versions
//! - Prevent stale results from overriding newer input
//! - Record all validation events in a traceable log
//! - Support deterministic replay under fixed seeds
//!
//! # Design Principles
//!
//! 1. **Monotonic Tokens**: Each input change increments a token. Results include
//!    the token they were computed for.
//! 2. **Staleness Prevention**: Results are only applied if their token matches
//!    the current input token.
//! 3. **Event Tracing**: All validation lifecycle events are recorded for debugging
//!    and determinism verification.
//! 4. **Golden Trace Support**: Traces can be checksummed for regression testing.
//!
//! # Example
//!
//! ```rust,ignore
//! use ftui_extras::validation::async_validation::{
//!     AsyncValidationCoordinator, ValidationEvent, ValidationTrace
//! };
//!
//! let mut coordinator = AsyncValidationCoordinator::new();
//!
//! // Start validation for input
//! let token = coordinator.start_validation("user@example.com");
//!
//! // Simulate async validation completing
//! let result = ValidationResult::Valid;
//! coordinator.complete_validation(token, result);
//!
//! // Check trace for determinism
//! let trace = coordinator.trace();
//! assert!(trace.contains_event(ValidationEvent::Started { token }));
//! ```

use std::collections::VecDeque;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use web_time::{Duration, Instant};

use super::ValidationResult;

// ---------------------------------------------------------------------------
// ValidationToken
// ---------------------------------------------------------------------------

/// A monotonically increasing token representing a validation request version.
///
/// Tokens are used to detect stale validation results. When input changes,
/// a new token is issued. Results computed for older tokens are discarded.
///
/// # Invariants
///
/// - Tokens are strictly monotonic: `token_n < token_{n+1}`
/// - Token 0 is reserved for "no validation"
/// - Tokens never wrap (u64 provides sufficient headroom)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ValidationToken(u64);

impl ValidationToken {
    /// The null token representing no validation.
    pub const NONE: Self = Self(0);

    /// Create a token from a raw value (for testing/deserialization).
    #[must_use]
    pub const fn from_raw(value: u64) -> Self {
        Self(value)
    }

    /// Get the raw token value.
    #[must_use]
    pub const fn raw(self) -> u64 {
        self.0
    }

    /// Check if this is the null token.
    #[must_use]
    pub const fn is_none(self) -> bool {
        self.0 == 0
    }
}

impl Default for ValidationToken {
    fn default() -> Self {
        Self::NONE
    }
}

impl std::fmt::Display for ValidationToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Token({})", self.0)
    }
}

// ---------------------------------------------------------------------------
// ValidationEvent
// ---------------------------------------------------------------------------

/// An event in the validation lifecycle, recorded for tracing and debugging.
///
/// Events form a complete audit trail of validation activity, enabling:
/// - Debugging async validation issues
/// - Verifying deterministic behavior under replay
/// - Golden trace comparison for regression testing
#[derive(Debug, Clone, PartialEq)]
pub enum ValidationEvent {
    /// Validation started for a token.
    Started {
        token: ValidationToken,
        /// Timestamp relative to coordinator creation (for determinism).
        elapsed_ns: u64,
    },

    /// Validation was cancelled (superseded by newer input).
    Cancelled {
        token: ValidationToken,
        /// The newer token that superseded this one.
        superseded_by: ValidationToken,
        elapsed_ns: u64,
    },

    /// Validation completed (may or may not be applied).
    Completed {
        token: ValidationToken,
        /// Whether the result was valid or invalid.
        is_valid: bool,
        /// Duration of the validation computation.
        duration_ns: u64,
        elapsed_ns: u64,
    },

    /// Validation result was applied to the state.
    Applied {
        token: ValidationToken,
        is_valid: bool,
        elapsed_ns: u64,
    },

    /// Validation result was discarded as stale.
    StaleDiscarded {
        token: ValidationToken,
        /// The current token when the result arrived.
        current_token: ValidationToken,
        elapsed_ns: u64,
    },
}

impl ValidationEvent {
    /// Get the token associated with this event.
    #[must_use]
    pub fn token(&self) -> ValidationToken {
        match self {
            Self::Started { token, .. }
            | Self::Cancelled { token, .. }
            | Self::Completed { token, .. }
            | Self::Applied { token, .. }
            | Self::StaleDiscarded { token, .. } => *token,
        }
    }

    /// Get the event type name for logging.
    #[must_use]
    pub fn event_type(&self) -> &'static str {
        match self {
            Self::Started { .. } => "started",
            Self::Cancelled { .. } => "cancelled",
            Self::Completed { .. } => "completed",
            Self::Applied { .. } => "applied",
            Self::StaleDiscarded { .. } => "stale_discarded",
        }
    }
}

impl Hash for ValidationEvent {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash discriminant and key fields for trace checksumming
        std::mem::discriminant(self).hash(state);
        match self {
            Self::Started { token, elapsed_ns } => {
                token.hash(state);
                elapsed_ns.hash(state);
            }
            Self::Cancelled {
                token,
                superseded_by,
                elapsed_ns,
            } => {
                token.hash(state);
                superseded_by.hash(state);
                elapsed_ns.hash(state);
            }
            Self::Completed {
                token,
                is_valid,
                duration_ns,
                elapsed_ns,
            } => {
                token.hash(state);
                is_valid.hash(state);
                duration_ns.hash(state);
                elapsed_ns.hash(state);
            }
            Self::Applied {
                token,
                is_valid,
                elapsed_ns,
            } => {
                token.hash(state);
                is_valid.hash(state);
                elapsed_ns.hash(state);
            }
            Self::StaleDiscarded {
                token,
                current_token,
                elapsed_ns,
            } => {
                token.hash(state);
                current_token.hash(state);
                elapsed_ns.hash(state);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// ValidationTrace
// ---------------------------------------------------------------------------

/// A trace of validation events for debugging and determinism verification.
///
/// Traces can be checksummed to verify that validation behavior is deterministic
/// across runs. This is useful for regression testing async validation logic.
#[derive(Debug, Clone, Default)]
pub struct ValidationTrace {
    events: Vec<ValidationEvent>,
}

impl ValidationTrace {
    /// Create a new empty trace.
    #[must_use]
    pub fn new() -> Self {
        Self { events: Vec::new() }
    }

    /// Add an event to the trace.
    pub fn push(&mut self, event: ValidationEvent) {
        self.events.push(event);
    }

    /// Get all events in the trace.
    #[must_use]
    pub fn events(&self) -> &[ValidationEvent] {
        &self.events
    }

    /// Check if the trace contains a specific event type for a token.
    #[must_use]
    pub fn contains_event_type(&self, token: ValidationToken, event_type: &str) -> bool {
        self.events
            .iter()
            .any(|e| e.token() == token && e.event_type() == event_type)
    }

    /// Get all events for a specific token.
    #[must_use]
    pub fn events_for_token(&self, token: ValidationToken) -> Vec<&ValidationEvent> {
        self.events.iter().filter(|e| e.token() == token).collect()
    }

    /// Compute a checksum of the trace for golden comparison.
    ///
    /// The checksum includes all event data and ordering, making it suitable
    /// for detecting any changes in validation behavior.
    #[must_use]
    pub fn checksum(&self) -> u64 {
        let mut hasher = DefaultHasher::new();
        for event in &self.events {
            event.hash(&mut hasher);
        }
        hasher.finish()
    }

    /// Get the number of events in the trace.
    #[must_use]
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Check if the trace is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Clear all events from the trace.
    pub fn clear(&mut self) {
        self.events.clear();
    }

    /// Verify trace invariants.
    ///
    /// Returns a list of violations if any invariants are broken.
    #[must_use]
    pub fn verify_invariants(&self) -> Vec<String> {
        let mut violations = Vec::new();

        // Invariant 1: Started events should have tokens in monotonic order
        let mut last_started_token = ValidationToken::NONE;
        for event in &self.events {
            if let ValidationEvent::Started { token, .. } = event {
                if *token <= last_started_token {
                    violations.push(format!(
                        "Non-monotonic start token: {} after {}",
                        token, last_started_token
                    ));
                }
                last_started_token = *token;
            }
        }

        // Invariant 2: Applied events should only occur for current token
        // (This is enforced by the coordinator, but we can check post-hoc)

        // Invariant 3: StaleDiscarded should have token < current_token
        for event in &self.events {
            if let ValidationEvent::StaleDiscarded {
                token,
                current_token,
                ..
            } = event
                && token >= current_token
            {
                violations.push(format!(
                    "StaleDiscarded with non-stale token: {} >= {}",
                    token, current_token
                ));
            }
        }

        violations
    }
}

// ---------------------------------------------------------------------------
// ValidationState
// ---------------------------------------------------------------------------

/// The state of an in-flight validation.
#[derive(Debug, Clone)]
pub struct InFlightValidation {
    /// The token for this validation.
    pub token: ValidationToken,
    /// When validation started (for duration tracking).
    pub started_at: Instant,
}

// ---------------------------------------------------------------------------
// AsyncValidationCoordinator
// ---------------------------------------------------------------------------

/// Coordinates async validations with token-based staleness prevention.
///
/// # Thread Safety
///
/// The coordinator is designed for single-threaded use with async validation
/// happening on background threads. The main thread calls `start_validation`
/// and `try_apply_result`, while background threads compute results.
///
/// # Determinism
///
/// For deterministic tracing, use `with_clock` to provide a fixed time source.
pub struct AsyncValidationCoordinator {
    /// The next token to issue.
    next_token: AtomicU64,

    /// The current (most recent) token.
    current_token: ValidationToken,

    /// Currently in-flight validations.
    in_flight: VecDeque<InFlightValidation>,

    /// The event trace.
    trace: ValidationTrace,

    /// When the coordinator was created (for elapsed time calculation).
    created_at: Instant,

    /// Optional fixed clock for deterministic testing (nanoseconds since start).
    fixed_clock: Option<Arc<AtomicU64>>,

    /// The most recently applied result.
    current_result: Option<ValidationResult>,
}

impl std::fmt::Debug for AsyncValidationCoordinator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncValidationCoordinator")
            .field("current_token", &self.current_token)
            .field("in_flight_count", &self.in_flight.len())
            .field("trace_events", &self.trace.len())
            .finish()
    }
}

impl Default for AsyncValidationCoordinator {
    fn default() -> Self {
        Self::new()
    }
}

impl AsyncValidationCoordinator {
    /// Create a new coordinator.
    #[must_use]
    pub fn new() -> Self {
        Self {
            next_token: AtomicU64::new(1),
            current_token: ValidationToken::NONE,
            in_flight: VecDeque::new(),
            trace: ValidationTrace::new(),
            created_at: Instant::now(),
            fixed_clock: None,
            current_result: None,
        }
    }

    /// Create a coordinator with a fixed clock for deterministic testing.
    ///
    /// The clock value represents nanoseconds since coordinator creation.
    #[must_use]
    pub fn with_fixed_clock(clock: Arc<AtomicU64>) -> Self {
        Self {
            next_token: AtomicU64::new(1),
            current_token: ValidationToken::NONE,
            in_flight: VecDeque::new(),
            trace: ValidationTrace::new(),
            created_at: Instant::now(),
            fixed_clock: Some(clock),
            current_result: None,
        }
    }

    /// Get the current elapsed time in nanoseconds.
    fn elapsed_ns(&self) -> u64 {
        self.fixed_clock.as_ref().map_or_else(
            || self.created_at.elapsed().as_nanos() as u64,
            |clock| clock.load(Ordering::SeqCst),
        )
    }

    /// Start a new validation, returning the token for this request.
    ///
    /// This cancels any in-flight validations with older tokens.
    pub fn start_validation(&mut self) -> ValidationToken {
        let token = ValidationToken(self.next_token.fetch_add(1, Ordering::SeqCst));
        let elapsed = self.elapsed_ns();

        // Cancel all in-flight validations (they're now stale)
        for validation in self.in_flight.drain(..) {
            self.trace.push(ValidationEvent::Cancelled {
                token: validation.token,
                superseded_by: token,
                elapsed_ns: elapsed,
            });
        }

        // Record the new validation
        self.in_flight.push_back(InFlightValidation {
            token,
            started_at: self.fixed_clock.as_ref().map_or_else(Instant::now, |_| {
                // For fixed clock, we just record the current instant
                // Duration will be calculated from elapsed_ns differences
                Instant::now()
            }),
        });

        self.current_token = token;
        self.trace.push(ValidationEvent::Started {
            token,
            elapsed_ns: elapsed,
        });

        token
    }

    /// Get the current token.
    #[must_use]
    pub fn current_token(&self) -> ValidationToken {
        self.current_token
    }

    /// Try to apply a validation result.
    ///
    /// Returns `true` if the result was applied (token matches current).
    /// Returns `false` if the result was discarded as stale.
    pub fn try_apply_result(
        &mut self,
        token: ValidationToken,
        result: ValidationResult,
        duration: Duration,
    ) -> bool {
        let elapsed = self.elapsed_ns();
        let is_valid = result.is_valid();
        let duration_ns = duration.as_nanos() as u64;

        // Record completion
        self.trace.push(ValidationEvent::Completed {
            token,
            is_valid,
            duration_ns,
            elapsed_ns: elapsed,
        });

        // Remove from in-flight
        self.in_flight.retain(|v| v.token != token);

        // Check if stale
        if token < self.current_token {
            self.trace.push(ValidationEvent::StaleDiscarded {
                token,
                current_token: self.current_token,
                elapsed_ns: elapsed,
            });
            return false;
        }

        // Apply the result
        self.current_result = Some(result);
        self.trace.push(ValidationEvent::Applied {
            token,
            is_valid,
            elapsed_ns: elapsed,
        });

        true
    }

    /// Get the current validation result.
    #[must_use]
    pub fn current_result(&self) -> Option<&ValidationResult> {
        self.current_result.as_ref()
    }

    /// Get the event trace.
    #[must_use]
    pub fn trace(&self) -> &ValidationTrace {
        &self.trace
    }

    /// Get a mutable reference to the trace.
    pub fn trace_mut(&mut self) -> &mut ValidationTrace {
        &mut self.trace
    }

    /// Clear the trace (for reuse).
    pub fn clear_trace(&mut self) {
        self.trace.clear();
    }

    /// Get the number of in-flight validations.
    #[must_use]
    pub fn in_flight_count(&self) -> usize {
        self.in_flight.len()
    }

    /// Check if there are any in-flight validations.
    #[must_use]
    pub fn has_in_flight(&self) -> bool {
        !self.in_flight.is_empty()
    }

    /// Verify that the trace satisfies all invariants.
    ///
    /// Returns `Ok(())` if valid, or `Err` with violation descriptions.
    pub fn verify_trace(&self) -> Result<(), Vec<String>> {
        let violations = self.trace.verify_invariants();
        if violations.is_empty() {
            Ok(())
        } else {
            Err(violations)
        }
    }
}

// ---------------------------------------------------------------------------
// AsyncValidator Trait
// ---------------------------------------------------------------------------

/// A validator that can perform async validation.
///
/// Unlike the synchronous `Validator` trait, this trait is designed for
/// validations that may take significant time (network calls, complex checks).
///
/// # Implementation Note
///
/// Implementations should be stateless and side-effect free. The coordinator
/// handles all state management and staleness prevention.
pub trait AsyncValidator<T: ?Sized>: Send + Sync {
    /// Perform validation asynchronously.
    ///
    /// This method will be called on a background thread. It should not
    /// access shared mutable state.
    fn validate(&self, value: &T) -> ValidationResult;

    /// Return the default error message for this validator.
    fn error_message(&self) -> &str;

    /// Return an estimated duration for this validation (for scheduling).
    ///
    /// This is a hint for the coordinator to prioritize fast validators.
    fn estimated_duration(&self) -> Duration {
        Duration::from_millis(100) // Default: 100ms
    }
}

// ---------------------------------------------------------------------------
// Thread-Safe Coordinator Wrapper
// ---------------------------------------------------------------------------

/// A thread-safe wrapper around `AsyncValidationCoordinator`.
///
/// This allows the coordinator to be shared between the main thread
/// (which starts validations) and background threads (which complete them).
pub struct SharedValidationCoordinator {
    inner: Arc<Mutex<AsyncValidationCoordinator>>,
}

impl Clone for SharedValidationCoordinator {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl Default for SharedValidationCoordinator {
    fn default() -> Self {
        Self::new()
    }
}

impl SharedValidationCoordinator {
    fn lock_inner(&self) -> MutexGuard<'_, AsyncValidationCoordinator> {
        match self.inner.lock() {
            Ok(guard) => guard,
            Err(poisoned) => {
                // Best-effort recovery: keep coordinator usable after a panic.
                poisoned.into_inner()
            }
        }
    }

    /// Create a new shared coordinator.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(AsyncValidationCoordinator::new())),
        }
    }

    /// Create a shared coordinator with a fixed clock.
    #[must_use]
    pub fn with_fixed_clock(clock: Arc<AtomicU64>) -> Self {
        Self {
            inner: Arc::new(Mutex::new(AsyncValidationCoordinator::with_fixed_clock(
                clock,
            ))),
        }
    }

    /// Start a new validation.
    pub fn start_validation(&self) -> ValidationToken {
        self.lock_inner().start_validation()
    }

    /// Get the current token.
    #[must_use]
    pub fn current_token(&self) -> ValidationToken {
        self.lock_inner().current_token()
    }

    /// Try to apply a validation result.
    pub fn try_apply_result(
        &self,
        token: ValidationToken,
        result: ValidationResult,
        duration: Duration,
    ) -> bool {
        self.lock_inner().try_apply_result(token, result, duration)
    }

    /// Get the current result.
    #[must_use]
    pub fn current_result(&self) -> Option<ValidationResult> {
        self.lock_inner().current_result().cloned()
    }

    /// Get a copy of the trace.
    #[must_use]
    pub fn trace(&self) -> ValidationTrace {
        self.lock_inner().trace().clone()
    }

    /// Get the trace checksum.
    #[must_use]
    pub fn trace_checksum(&self) -> u64 {
        self.lock_inner().trace().checksum()
    }

    /// Verify trace invariants.
    pub fn verify_trace(&self) -> Result<(), Vec<String>> {
        self.lock_inner().verify_trace()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validation::ValidationError;
    use std::sync::atomic::AtomicU64;
    use std::thread;
    use std::time::Duration;

    // -- ValidationToken tests --

    #[test]
    fn token_none_is_zero() {
        assert_eq!(ValidationToken::NONE.raw(), 0);
        assert!(ValidationToken::NONE.is_none());
    }

    #[test]
    fn token_from_raw() {
        let token = ValidationToken::from_raw(42);
        assert_eq!(token.raw(), 42);
        assert!(!token.is_none());
    }

    #[test]
    fn token_ordering() {
        let t1 = ValidationToken::from_raw(1);
        let t2 = ValidationToken::from_raw(2);
        let t3 = ValidationToken::from_raw(3);

        assert!(t1 < t2);
        assert!(t2 < t3);
        assert!(t1 < t3);
    }

    #[test]
    fn token_display() {
        let token = ValidationToken::from_raw(123);
        assert_eq!(format!("{token}"), "Token(123)");
    }

    // -- unit_token_monotonic: tokens strictly increase per input --

    #[test]
    fn unit_token_monotonic() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        let mut tokens = Vec::new();
        for i in 0..10 {
            clock.store(i * 1000, Ordering::SeqCst);
            tokens.push(coordinator.start_validation());
        }

        // Verify strict monotonicity
        for i in 1..tokens.len() {
            assert!(
                tokens[i] > tokens[i - 1],
                "Token {} ({}) should be greater than token {} ({})",
                i,
                tokens[i],
                i - 1,
                tokens[i - 1]
            );
        }

        // Verify via trace
        let violations = coordinator.trace().verify_invariants();
        assert!(
            violations.is_empty(),
            "Invariant violations: {:?}",
            violations
        );
    }

    // -- unit_stale_result_ignored: older token never applies --

    #[test]
    fn unit_stale_result_ignored() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        // Start validation 1
        clock.store(1000, Ordering::SeqCst);
        let token1 = coordinator.start_validation();

        // Start validation 2 (supersedes 1)
        clock.store(2000, Ordering::SeqCst);
        let token2 = coordinator.start_validation();

        // Validation 1 completes (stale)
        clock.store(3000, Ordering::SeqCst);
        let applied1 = coordinator.try_apply_result(
            token1,
            ValidationResult::Invalid(ValidationError::new("test", "stale")),
            Duration::from_millis(100),
        );

        // Validation 2 completes (current)
        clock.store(4000, Ordering::SeqCst);
        let applied2 = coordinator.try_apply_result(
            token2,
            ValidationResult::Valid,
            Duration::from_millis(50),
        );

        // Verify stale was rejected, current was applied
        assert!(!applied1, "Stale result should not be applied");
        assert!(applied2, "Current result should be applied");

        // Verify current result is from token2
        assert!(coordinator.current_result().unwrap().is_valid());

        // Verify trace contains StaleDiscarded event
        assert!(
            coordinator
                .trace()
                .contains_event_type(token1, "stale_discarded"),
            "Trace should contain stale_discarded for token1"
        );

        // Verify trace invariants
        let violations = coordinator.trace().verify_invariants();
        assert!(
            violations.is_empty(),
            "Invariant violations: {:?}",
            violations
        );
    }

    // -- unit_trace_contains_all_events: no missing transitions --

    #[test]
    fn unit_trace_contains_all_events() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        // Start validation
        clock.store(1000, Ordering::SeqCst);
        let token = coordinator.start_validation();

        // Complete validation
        clock.store(2000, Ordering::SeqCst);
        coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(50));

        // Verify all events are present
        let trace = coordinator.trace();

        assert!(
            trace.contains_event_type(token, "started"),
            "Trace should contain started event"
        );
        assert!(
            trace.contains_event_type(token, "completed"),
            "Trace should contain completed event"
        );
        assert!(
            trace.contains_event_type(token, "applied"),
            "Trace should contain applied event"
        );

        // Verify event count
        let token_events = trace.events_for_token(token);
        assert_eq!(token_events.len(), 3, "Should have 3 events for token");
    }

    #[test]
    fn trace_contains_cancelled_events() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        // Start validation 1
        clock.store(1000, Ordering::SeqCst);
        let token1 = coordinator.start_validation();

        // Start validation 2 (cancels 1)
        clock.store(2000, Ordering::SeqCst);
        let _token2 = coordinator.start_validation();

        // Verify cancelled event
        assert!(
            coordinator.trace().contains_event_type(token1, "cancelled"),
            "Trace should contain cancelled event for token1"
        );
    }

    // -- Coordinator basic tests --

    #[test]
    fn coordinator_initial_state() {
        let coordinator = AsyncValidationCoordinator::new();
        assert_eq!(coordinator.current_token(), ValidationToken::NONE);
        assert!(coordinator.current_result().is_none());
        assert!(!coordinator.has_in_flight());
    }

    #[test]
    fn coordinator_start_updates_current() {
        let mut coordinator = AsyncValidationCoordinator::new();
        let token = coordinator.start_validation();
        assert_eq!(coordinator.current_token(), token);
        assert!(coordinator.has_in_flight());
    }

    #[test]
    fn coordinator_apply_clears_in_flight() {
        let mut coordinator = AsyncValidationCoordinator::new();
        let token = coordinator.start_validation();
        assert_eq!(coordinator.in_flight_count(), 1);

        coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(10));
        assert_eq!(coordinator.in_flight_count(), 0);
    }

    // -- Trace checksum tests --

    #[test]
    fn trace_checksum_deterministic() {
        let clock1 = Arc::new(AtomicU64::new(0));
        let clock2 = Arc::new(AtomicU64::new(0));

        let mut coord1 = AsyncValidationCoordinator::with_fixed_clock(clock1.clone());
        let mut coord2 = AsyncValidationCoordinator::with_fixed_clock(clock2.clone());

        // Perform identical operations
        for i in 0..5 {
            clock1.store(i * 1000, Ordering::SeqCst);
            clock2.store(i * 1000, Ordering::SeqCst);

            let t1 = coord1.start_validation();
            let t2 = coord2.start_validation();

            clock1.store((i * 1000) + 500, Ordering::SeqCst);
            clock2.store((i * 1000) + 500, Ordering::SeqCst);

            coord1.try_apply_result(t1, ValidationResult::Valid, Duration::from_millis(50));
            coord2.try_apply_result(t2, ValidationResult::Valid, Duration::from_millis(50));
        }

        // Checksums should match
        assert_eq!(
            coord1.trace().checksum(),
            coord2.trace().checksum(),
            "Identical operations should produce identical checksums"
        );
    }

    #[test]
    fn trace_checksum_differs_on_different_operations() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coord1 = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        clock.store(0, Ordering::SeqCst);
        let t1 = coord1.start_validation();
        clock.store(500, Ordering::SeqCst);
        coord1.try_apply_result(t1, ValidationResult::Valid, Duration::from_millis(50));

        let checksum1 = coord1.trace().checksum();

        // Different operations
        clock.store(1000, Ordering::SeqCst);
        let t2 = coord1.start_validation();
        clock.store(1500, Ordering::SeqCst);
        coord1.try_apply_result(
            t2,
            ValidationResult::Invalid(ValidationError::new("test", "error")),
            Duration::from_millis(50),
        );

        let checksum2 = coord1.trace().checksum();

        assert_ne!(
            checksum1, checksum2,
            "Different operations should produce different checksums"
        );
    }

    // -- SharedValidationCoordinator tests --

    #[test]
    fn shared_coordinator_thread_safe() {
        let coordinator = SharedValidationCoordinator::new();
        let coord_clone = coordinator.clone();

        // Start validation on main thread
        let token = coordinator.start_validation();

        // Complete on background thread
        let handle = thread::spawn(move || {
            thread::sleep(Duration::from_millis(10));
            coord_clone.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(10))
        });

        let applied = handle.join().unwrap();
        assert!(applied, "Result should be applied from background thread");
        assert!(coordinator.current_result().unwrap().is_valid());
    }

    #[test]
    fn shared_coordinator_concurrent_starts() {
        let coordinator = SharedValidationCoordinator::new();

        // Rapid starts should all get unique tokens
        let tokens: Vec<_> = (0..100).map(|_| coordinator.start_validation()).collect();

        // All tokens should be unique
        let mut unique = tokens.clone();
        unique.sort();
        unique.dedup();
        assert_eq!(unique.len(), tokens.len(), "All tokens should be unique");
    }

    // -- Invariant verification tests --

    #[test]
    fn verify_invariants_passes_for_valid_trace() {
        let mut coordinator = AsyncValidationCoordinator::new();

        for _ in 0..5 {
            let token = coordinator.start_validation();
            coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(10));
        }

        let result = coordinator.verify_trace();
        assert!(result.is_ok(), "Valid trace should pass verification");
    }

    // -- ValidationEvent tests --

    #[test]
    fn event_type_names() {
        let token = ValidationToken::from_raw(1);

        let started = ValidationEvent::Started {
            token,
            elapsed_ns: 0,
        };
        assert_eq!(started.event_type(), "started");

        let cancelled = ValidationEvent::Cancelled {
            token,
            superseded_by: ValidationToken::from_raw(2),
            elapsed_ns: 0,
        };
        assert_eq!(cancelled.event_type(), "cancelled");

        let completed = ValidationEvent::Completed {
            token,
            is_valid: true,
            duration_ns: 0,
            elapsed_ns: 0,
        };
        assert_eq!(completed.event_type(), "completed");

        let applied = ValidationEvent::Applied {
            token,
            is_valid: true,
            elapsed_ns: 0,
        };
        assert_eq!(applied.event_type(), "applied");

        let stale = ValidationEvent::StaleDiscarded {
            token,
            current_token: ValidationToken::from_raw(2),
            elapsed_ns: 0,
        };
        assert_eq!(stale.event_type(), "stale_discarded");
    }

    #[test]
    fn trace_new_is_empty() {
        let trace = ValidationTrace::new();
        assert!(trace.is_empty());
        assert_eq!(trace.len(), 0);
        assert!(trace.events().is_empty());
    }

    #[test]
    fn trace_clear_removes_events() {
        let mut coordinator = AsyncValidationCoordinator::new();
        let token = coordinator.start_validation();
        coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(10));
        assert!(!coordinator.trace().is_empty());
        coordinator.clear_trace();
        assert!(coordinator.trace().is_empty());
    }

    #[test]
    fn trace_events_for_token_filters() {
        let mut coordinator = AsyncValidationCoordinator::new();
        let t1 = coordinator.start_validation();
        coordinator.try_apply_result(t1, ValidationResult::Valid, Duration::from_millis(10));
        let t2 = coordinator.start_validation();
        coordinator.try_apply_result(t2, ValidationResult::Valid, Duration::from_millis(10));

        let events_t1 = coordinator.trace().events_for_token(t1);
        assert!(events_t1.iter().all(|e| e.token() == t1));
        let events_t2 = coordinator.trace().events_for_token(t2);
        assert!(events_t2.iter().all(|e| e.token() == t2));
    }

    #[test]
    fn trace_mut_allows_push() {
        let mut coordinator = AsyncValidationCoordinator::new();
        let before = coordinator.trace().len();
        coordinator.trace_mut().push(ValidationEvent::Started {
            token: ValidationToken::from_raw(999),
            elapsed_ns: 0,
        });
        assert_eq!(coordinator.trace().len(), before + 1);
    }

    #[test]
    fn shared_coordinator_trace_checksum() {
        let coordinator = SharedValidationCoordinator::new();
        let t1 = coordinator.start_validation();
        coordinator.try_apply_result(t1, ValidationResult::Valid, Duration::from_millis(10));
        let checksum = coordinator.trace_checksum();
        // Calling again should be deterministic
        assert_eq!(checksum, coordinator.trace_checksum());
    }

    #[test]
    fn coordinator_current_result_after_invalid() {
        let mut coordinator = AsyncValidationCoordinator::new();
        let token = coordinator.start_validation();
        coordinator.try_apply_result(
            token,
            ValidationResult::Invalid(ValidationError::new("field", "too short")),
            Duration::from_millis(10),
        );
        let result = coordinator.current_result().unwrap();
        assert!(!result.is_valid());
    }

    // =====================================================================
    // Edge-case tests added for bd-e95ux
    // =====================================================================

    // -- ValidationToken edge cases --

    #[test]
    fn token_default_is_none() {
        let token: ValidationToken = Default::default();
        assert!(token.is_none());
        assert_eq!(token, ValidationToken::NONE);
    }

    #[test]
    fn token_display_none() {
        assert_eq!(format!("{}", ValidationToken::NONE), "Token(0)");
    }

    #[test]
    fn token_hash_consistent() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(ValidationToken::from_raw(1));
        set.insert(ValidationToken::from_raw(1));
        assert_eq!(set.len(), 1, "same token should hash to same bucket");
        set.insert(ValidationToken::from_raw(2));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn token_equality() {
        assert_eq!(ValidationToken::from_raw(42), ValidationToken::from_raw(42));
        assert_ne!(ValidationToken::from_raw(1), ValidationToken::from_raw(2));
    }

    #[test]
    fn token_none_is_less_than_any_real() {
        assert!(ValidationToken::NONE < ValidationToken::from_raw(1));
    }

    // -- ValidationEvent edge cases --

    #[test]
    fn event_clone() {
        let event = ValidationEvent::Started {
            token: ValidationToken::from_raw(1),
            elapsed_ns: 100,
        };
        let cloned = event.clone();
        assert_eq!(event, cloned);
    }

    #[test]
    fn event_token_extraction_all_variants() {
        let t = ValidationToken::from_raw(7);
        let events = [
            ValidationEvent::Started {
                token: t,
                elapsed_ns: 0,
            },
            ValidationEvent::Cancelled {
                token: t,
                superseded_by: ValidationToken::from_raw(8),
                elapsed_ns: 0,
            },
            ValidationEvent::Completed {
                token: t,
                is_valid: true,
                duration_ns: 0,
                elapsed_ns: 0,
            },
            ValidationEvent::Applied {
                token: t,
                is_valid: false,
                elapsed_ns: 0,
            },
            ValidationEvent::StaleDiscarded {
                token: t,
                current_token: ValidationToken::from_raw(10),
                elapsed_ns: 0,
            },
        ];
        for event in &events {
            assert_eq!(event.token(), t, "token extraction for {:?}", event);
        }
    }

    #[test]
    fn event_hash_differs_by_variant() {
        use std::hash::{DefaultHasher, Hash, Hasher};
        let t = ValidationToken::from_raw(1);
        let started = ValidationEvent::Started {
            token: t,
            elapsed_ns: 0,
        };
        let applied = ValidationEvent::Applied {
            token: t,
            is_valid: true,
            elapsed_ns: 0,
        };
        let mut h1 = DefaultHasher::new();
        started.hash(&mut h1);
        let mut h2 = DefaultHasher::new();
        applied.hash(&mut h2);
        assert_ne!(
            h1.finish(),
            h2.finish(),
            "different variants should hash differently"
        );
    }

    // -- ValidationTrace edge cases --

    #[test]
    fn trace_verify_invariants_empty_is_clean() {
        let trace = ValidationTrace::new();
        assert!(trace.verify_invariants().is_empty());
    }

    #[test]
    fn trace_verify_invariants_non_monotonic_start() {
        let mut trace = ValidationTrace::new();
        trace.push(ValidationEvent::Started {
            token: ValidationToken::from_raw(5),
            elapsed_ns: 0,
        });
        trace.push(ValidationEvent::Started {
            token: ValidationToken::from_raw(3), // non-monotonic!
            elapsed_ns: 100,
        });
        let violations = trace.verify_invariants();
        assert!(!violations.is_empty(), "should detect non-monotonic tokens");
        assert!(
            violations[0].contains("Non-monotonic"),
            "violation: {}",
            violations[0]
        );
    }

    #[test]
    fn trace_verify_invariants_stale_discarded_non_stale() {
        let mut trace = ValidationTrace::new();
        trace.push(ValidationEvent::StaleDiscarded {
            token: ValidationToken::from_raw(5),
            current_token: ValidationToken::from_raw(3), // token >= current (bad!)
            elapsed_ns: 0,
        });
        let violations = trace.verify_invariants();
        assert!(
            !violations.is_empty(),
            "should detect non-stale StaleDiscarded"
        );
        assert!(violations[0].contains("non-stale"));
    }

    #[test]
    fn trace_checksum_empty_deterministic() {
        let t1 = ValidationTrace::new();
        let t2 = ValidationTrace::new();
        assert_eq!(t1.checksum(), t2.checksum());
    }

    #[test]
    fn trace_checksum_changes_after_push() {
        let mut trace = ValidationTrace::new();
        let empty_checksum = trace.checksum();
        trace.push(ValidationEvent::Started {
            token: ValidationToken::from_raw(1),
            elapsed_ns: 0,
        });
        assert_ne!(trace.checksum(), empty_checksum);
    }

    #[test]
    fn trace_clone_is_independent() {
        let mut trace = ValidationTrace::new();
        trace.push(ValidationEvent::Started {
            token: ValidationToken::from_raw(1),
            elapsed_ns: 0,
        });
        let cloned = trace.clone();
        trace.clear();
        assert!(trace.is_empty());
        assert_eq!(cloned.len(), 1, "clone should be independent");
    }

    #[test]
    fn trace_contains_event_type_returns_false_for_missing() {
        let trace = ValidationTrace::new();
        assert!(!trace.contains_event_type(ValidationToken::from_raw(1), "started"));
    }

    #[test]
    fn trace_events_for_nonexistent_token() {
        let trace = ValidationTrace::new();
        let events = trace.events_for_token(ValidationToken::from_raw(99));
        assert!(events.is_empty());
    }

    // -- AsyncValidationCoordinator edge cases --

    #[test]
    fn coordinator_debug_format() {
        let coordinator = AsyncValidationCoordinator::new();
        let debug = format!("{coordinator:?}");
        assert!(debug.contains("AsyncValidationCoordinator"));
        assert!(debug.contains("current_token"));
    }

    #[test]
    fn coordinator_default_trait() {
        let coordinator: AsyncValidationCoordinator = Default::default();
        assert_eq!(coordinator.current_token(), ValidationToken::NONE);
        assert!(!coordinator.has_in_flight());
    }

    #[test]
    fn coordinator_multiple_rapid_starts_cancel_all_previous() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        clock.store(1000, Ordering::SeqCst);
        let t1 = coordinator.start_validation();
        clock.store(2000, Ordering::SeqCst);
        let t2 = coordinator.start_validation();
        clock.store(3000, Ordering::SeqCst);
        let _t3 = coordinator.start_validation();

        // t1 should be cancelled when t2 started, t2 cancelled when t3 started
        let trace = coordinator.trace();
        assert!(trace.contains_event_type(t1, "cancelled"));
        assert!(trace.contains_event_type(t2, "cancelled"));
    }

    #[test]
    fn coordinator_in_flight_count_after_multiple_starts() {
        let mut coordinator = AsyncValidationCoordinator::new();

        // Each start cancels all previous, so in_flight should always be 1
        coordinator.start_validation();
        assert_eq!(coordinator.in_flight_count(), 1);
        coordinator.start_validation();
        assert_eq!(coordinator.in_flight_count(), 1);
        coordinator.start_validation();
        assert_eq!(coordinator.in_flight_count(), 1);
    }

    #[test]
    fn coordinator_apply_stale_then_current() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        clock.store(1000, Ordering::SeqCst);
        let t1 = coordinator.start_validation();
        clock.store(2000, Ordering::SeqCst);
        let t2 = coordinator.start_validation();

        // Apply stale t1 — should fail
        clock.store(3000, Ordering::SeqCst);
        assert!(!coordinator.try_apply_result(
            t1,
            ValidationResult::Valid,
            Duration::from_millis(100),
        ));

        // Apply current t2 — should succeed
        clock.store(4000, Ordering::SeqCst);
        assert!(coordinator.try_apply_result(
            t2,
            ValidationResult::Valid,
            Duration::from_millis(50),
        ));

        // In-flight should be empty
        assert_eq!(coordinator.in_flight_count(), 0);
    }

    #[test]
    fn coordinator_result_replaced_by_newer() {
        let mut coordinator = AsyncValidationCoordinator::new();

        let t1 = coordinator.start_validation();
        coordinator.try_apply_result(
            t1,
            ValidationResult::Invalid(ValidationError::new("code", "first")),
            Duration::from_millis(10),
        );
        assert!(!coordinator.current_result().unwrap().is_valid());

        let t2 = coordinator.start_validation();
        coordinator.try_apply_result(t2, ValidationResult::Valid, Duration::from_millis(10));
        assert!(coordinator.current_result().unwrap().is_valid());
    }

    #[test]
    fn coordinator_apply_same_token_twice() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        clock.store(1000, Ordering::SeqCst);
        let token = coordinator.start_validation();

        // First apply
        clock.store(2000, Ordering::SeqCst);
        let first =
            coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(50));
        assert!(first);

        // Second apply of same token — should still succeed since token == current_token
        clock.store(3000, Ordering::SeqCst);
        let second = coordinator.try_apply_result(
            token,
            ValidationResult::Invalid(ValidationError::new("code", "err")),
            Duration::from_millis(50),
        );
        assert!(second, "same token applied again should succeed");
    }

    #[test]
    fn coordinator_verify_trace_after_full_lifecycle() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        for i in 0..5 {
            clock.store(i * 2000, Ordering::SeqCst);
            let token = coordinator.start_validation();
            clock.store(i * 2000 + 1000, Ordering::SeqCst);
            coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(50));
        }

        assert!(coordinator.verify_trace().is_ok());
    }

    #[test]
    fn coordinator_elapsed_ns_uses_fixed_clock() {
        let clock = Arc::new(AtomicU64::new(42_000));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        let token = coordinator.start_validation();
        let trace = coordinator.trace();
        let first = &trace.events()[0];
        if let ValidationEvent::Started { elapsed_ns, .. } = first {
            assert_eq!(*elapsed_ns, 42_000);
        } else {
            assert!(
                matches!(first, ValidationEvent::Started { .. }),
                "expected Started event, got: {first:?}"
            );
        }

        // Advance clock
        clock.store(99_000, Ordering::SeqCst);
        coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(10));
        let events = coordinator.trace().events();
        let last = events.last().unwrap();
        if let ValidationEvent::Applied { elapsed_ns, .. } = last {
            assert_eq!(*elapsed_ns, 99_000);
        } else {
            assert!(
                matches!(last, ValidationEvent::Applied { .. }),
                "expected Applied event, got: {last:?}"
            );
        }
    }

    // -- SharedValidationCoordinator edge cases --

    #[test]
    fn shared_coordinator_default_trait() {
        let coord: SharedValidationCoordinator = Default::default();
        assert_eq!(coord.current_token(), ValidationToken::NONE);
    }

    #[test]
    fn shared_coordinator_with_fixed_clock() {
        let clock = Arc::new(AtomicU64::new(5000));
        let coordinator = SharedValidationCoordinator::with_fixed_clock(clock);
        let token = coordinator.start_validation();
        let trace = coordinator.trace();
        let first = &trace.events()[0];
        if let ValidationEvent::Started { elapsed_ns, .. } = first {
            assert_eq!(*elapsed_ns, 5000);
        } else {
            assert!(
                matches!(first, ValidationEvent::Started { .. }),
                "expected Started event, got: {first:?}"
            );
        }
        coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(10));
    }

    #[test]
    fn shared_coordinator_verify_trace() {
        let coordinator = SharedValidationCoordinator::new();
        let t = coordinator.start_validation();
        coordinator.try_apply_result(t, ValidationResult::Valid, Duration::from_millis(10));
        assert!(coordinator.verify_trace().is_ok());
    }

    #[test]
    fn shared_coordinator_multiple_threads_unique_tokens() {
        let coordinator = SharedValidationCoordinator::new();
        let mut handles = vec![];
        for _ in 0..10 {
            let c = coordinator.clone();
            handles.push(thread::spawn(move || c.start_validation()));
        }
        let tokens: Vec<ValidationToken> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        let mut sorted = tokens.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(
            sorted.len(),
            tokens.len(),
            "all tokens from concurrent threads should be unique"
        );
    }

    // -- InFlightValidation --

    #[test]
    fn in_flight_validation_debug() {
        let v = InFlightValidation {
            token: ValidationToken::from_raw(3),
            started_at: Instant::now(),
        };
        let debug = format!("{v:?}");
        assert!(debug.contains("InFlightValidation"));
        assert!(debug.contains("token"));
    }

    #[test]
    fn in_flight_validation_clone() {
        let v = InFlightValidation {
            token: ValidationToken::from_raw(5),
            started_at: Instant::now(),
        };
        let cloned = v.clone();
        assert_eq!(cloned.token, v.token);
    }

    // -- AsyncValidator trait --

    #[test]
    fn async_validator_estimated_duration_default() {
        struct TestValidator;
        impl AsyncValidator<str> for TestValidator {
            fn validate(&self, _value: &str) -> ValidationResult {
                ValidationResult::Valid
            }
            fn error_message(&self) -> &str {
                "test error"
            }
        }
        let v = TestValidator;
        assert_eq!(v.estimated_duration(), Duration::from_millis(100));
        assert_eq!(v.error_message(), "test error");
        assert!(v.validate("anything").is_valid());
    }

    #[test]
    fn async_validator_custom_estimated_duration() {
        struct SlowValidator;
        impl AsyncValidator<str> for SlowValidator {
            fn validate(&self, _value: &str) -> ValidationResult {
                ValidationResult::Valid
            }
            fn error_message(&self) -> &str {
                "slow"
            }
            fn estimated_duration(&self) -> Duration {
                Duration::from_secs(5)
            }
        }
        let v = SlowValidator;
        assert_eq!(v.estimated_duration(), Duration::from_secs(5));
    }

    // -- Coordinator with zero-duration results --

    #[test]
    fn coordinator_zero_duration_result() {
        let mut coordinator = AsyncValidationCoordinator::new();
        let token = coordinator.start_validation();
        let applied = coordinator.try_apply_result(token, ValidationResult::Valid, Duration::ZERO);
        assert!(applied);
    }

    // -- Trace with many events --

    #[test]
    fn trace_many_events() {
        let clock = Arc::new(AtomicU64::new(0));
        let mut coordinator = AsyncValidationCoordinator::with_fixed_clock(clock.clone());

        for i in 0..100 {
            clock.store(i * 100, Ordering::SeqCst);
            let token = coordinator.start_validation();
            clock.store(i * 100 + 50, Ordering::SeqCst);
            coordinator.try_apply_result(token, ValidationResult::Valid, Duration::from_millis(1));
        }

        let trace = coordinator.trace();
        // Each iteration: started + completed + applied = 3
        // (try_apply_result clears in-flight, so next start has nothing to cancel)
        assert_eq!(trace.len(), 100 * 3);
        assert!(coordinator.verify_trace().is_ok());
    }
}