asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
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
//! Vector clocks for causal ordering of distributed trace events.
//!
//! A vector clock maps each node in the system to a logical counter. It captures
//! the causal partial order: events are either causally ordered (happens-before)
//! or concurrent. This avoids imposing a false total order on distributed events.
//!
//! # Usage
//!
//! ```rust
//! use asupersync::trace::distributed::vclock::{VectorClock, CausalOrder};
//! use asupersync::remote::NodeId;
//!
//! let mut vc_a = VectorClock::new();
//! let node_a = NodeId::new("node-a");
//! let node_b = NodeId::new("node-b");
//!
//! vc_a.increment(&node_a);
//! vc_a.increment(&node_a);
//!
//! let mut vc_b = VectorClock::new();
//! vc_b.increment(&node_b);
//!
//! // These are concurrent — neither happened before the other.
//! assert_eq!(vc_a.partial_cmp(&vc_b), None);
//!
//! // Merge to get the join (componentwise max).
//! let merged = vc_a.merge(&vc_b);
//! assert!(merged.get(&node_a) == 2);
//! assert!(merged.get(&node_b) == 1);
//! ```

use crate::remote::NodeId;
use crate::time::{TimeSource, TimerDriverHandle, WallClock};
use crate::types::Time;
use parking_lot::Mutex;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

/// Logical clock trait for causally ordering distributed events.
///
/// Uses `PartialOrd` so vector clocks (partial order) are supported.
pub trait LogicalClock: Send + Sync {
    /// The time representation produced by this clock.
    type Time: Clone + PartialOrd + Send + Sync + 'static;

    /// Records a local event and returns the updated time.
    #[must_use]
    fn tick(&self) -> Self::Time;

    /// Updates the clock based on a received time and returns the updated time.
    #[must_use]
    fn receive(&self, sender_time: &Self::Time) -> Self::Time;

    /// Returns the current time without ticking.
    #[must_use]
    fn now(&self) -> Self::Time;
}

/// Logical time for Lamport clocks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LamportTime(u64);

impl LamportTime {
    /// Returns the raw counter value.
    #[must_use]
    pub const fn raw(self) -> u64 {
        self.0
    }

    /// Creates a Lamport time from a raw counter value.
    #[must_use]
    pub const fn from_raw(value: u64) -> Self {
        Self(value)
    }
}

/// Lamport logical clock (single counter).
pub struct LamportClock {
    counter: AtomicU64,
}

impl LamportClock {
    /// Creates a new Lamport clock starting at zero.
    #[must_use]
    pub fn new() -> Self {
        Self {
            counter: AtomicU64::new(0),
        }
    }

    /// Creates a Lamport clock starting at the given value.
    #[must_use]
    pub fn with_start(start: u64) -> Self {
        Self {
            counter: AtomicU64::new(start),
        }
    }

    /// Returns the current Lamport time without incrementing.
    #[must_use]
    pub fn now(&self) -> LamportTime {
        LamportTime(self.counter.load(Ordering::Acquire))
    }

    /// Records a local event and returns the updated time.
    #[must_use]
    pub fn tick(&self) -> LamportTime {
        let mut current = self.counter.load(Ordering::Acquire);
        loop {
            let next = current
                .checked_add(1)
                .expect("Lamport clock overflowed while ticking");
            match self.counter.compare_exchange_weak(
                current,
                next,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return LamportTime(next),
                Err(actual) => current = actual,
            }
        }
    }

    /// Merges a received Lamport time and returns the updated time.
    #[must_use]
    pub fn receive(&self, sender: LamportTime) -> LamportTime {
        let mut current = self.counter.load(Ordering::Acquire);
        loop {
            let next = current
                .max(sender.raw())
                .checked_add(1)
                .expect("Lamport clock overflowed while merging a received time");
            match self.counter.compare_exchange_weak(
                current,
                next,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return LamportTime(next),
                Err(actual) => current = actual,
            }
        }
    }
}

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

impl fmt::Debug for LamportClock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LamportClock")
            .field("counter", &self.counter.load(Ordering::Relaxed))
            .finish()
    }
}

impl LogicalClock for LamportClock {
    type Time = LamportTime;

    fn tick(&self) -> Self::Time {
        Self::tick(self)
    }

    fn receive(&self, sender_time: &Self::Time) -> Self::Time {
        Self::receive(self, *sender_time)
    }

    fn now(&self) -> Self::Time {
        Self::now(self)
    }
}

/// Logical time for hybrid clocks (physical + logical).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HybridTime {
    physical: Time,
    logical: u64,
}

impl HybridTime {
    /// Creates a new hybrid time.
    #[must_use]
    pub const fn new(physical: Time, logical: u64) -> Self {
        Self { physical, logical }
    }

    /// Returns the physical component.
    #[must_use]
    pub const fn physical(self) -> Time {
        self.physical
    }

    /// Returns the logical component.
    #[must_use]
    pub const fn logical(self) -> u64 {
        self.logical
    }
}

#[derive(Debug)]
struct HybridState {
    last_physical: Time,
    logical: u64,
}

/// Hybrid logical clock (HLC) with a monotonic physical component.
pub struct HybridClock {
    time_source: Arc<dyn TimeSource>,
    state: Mutex<HybridState>,
}

impl HybridClock {
    /// Creates a new hybrid clock using the provided time source.
    #[must_use]
    pub fn new(time_source: Arc<dyn TimeSource>) -> Self {
        let now = time_source.now();
        Self {
            time_source,
            state: Mutex::new(HybridState {
                last_physical: now,
                logical: 0,
            }),
        }
    }

    /// Returns the current hybrid time without ticking.
    #[must_use]
    pub fn now(&self) -> HybridTime {
        let state = self.state.lock();
        let physical = self.physical_now(&state);
        let logical = if physical == state.last_physical {
            state.logical
        } else {
            0
        };
        HybridTime::new(physical, logical)
    }

    /// Records a local event and returns the updated time.
    #[must_use]
    pub fn tick(&self) -> HybridTime {
        let mut state = self.state.lock();
        let physical = self.physical_now(&state);
        if physical == state.last_physical {
            state.logical = state
                .logical
                .checked_add(1)
                .expect("Hybrid clock logical counter overflowed while ticking");
        } else {
            state.last_physical = physical;
            state.logical = 0;
        }
        HybridTime::new(state.last_physical, state.logical)
    }

    /// Merges a received hybrid time and returns the updated time.
    #[must_use]
    pub fn receive(&self, sender: HybridTime) -> HybridTime {
        let mut state = self.state.lock();
        let physical_now = self.physical_now(&state);
        let max_physical = physical_now.max(state.last_physical).max(sender.physical);

        let next_logical = if max_physical == state.last_physical && max_physical == sender.physical
        {
            state
                .logical
                .max(sender.logical)
                .checked_add(1)
                .expect("Hybrid clock logical counter overflowed while merging equal physical time")
        } else if max_physical == state.last_physical {
            state.logical.checked_add(1).expect(
                "Hybrid clock logical counter overflowed while advancing local logical time",
            )
        } else if max_physical == sender.physical {
            sender.logical.checked_add(1).expect(
                "Hybrid clock logical counter overflowed while incorporating a remote physical time",
            )
        } else {
            0
        };

        state.last_physical = max_physical;
        state.logical = next_logical;
        HybridTime::new(state.last_physical, state.logical)
    }

    fn physical_now(&self, state: &HybridState) -> Time {
        let physical = self.time_source.now();
        if physical < state.last_physical {
            state.last_physical
        } else {
            physical
        }
    }
}

impl fmt::Debug for HybridClock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let state = self.state.lock();
        f.debug_struct("HybridClock")
            .field("last_physical", &state.last_physical)
            .field("logical", &state.logical)
            .finish_non_exhaustive()
    }
}

impl LogicalClock for HybridClock {
    type Time = HybridTime;

    fn tick(&self) -> Self::Time {
        Self::tick(self)
    }

    fn receive(&self, sender_time: &Self::Time) -> Self::Time {
        Self::receive(self, *sender_time)
    }

    fn now(&self) -> Self::Time {
        Self::now(self)
    }
}

/// Logical clock wrapper for vector clocks with a local node identity.
pub struct VectorClockHandle {
    /// Local node identity for this vector clock.
    node: NodeId,
    /// Internal vector clock state protected by a mutex.
    clock: Mutex<VectorClock>,
}

impl VectorClockHandle {
    /// Creates a new vector clock handle for the given node.
    #[must_use]
    pub fn new(node: NodeId) -> Self {
        Self {
            node,
            clock: Mutex::new(VectorClock::new()),
        }
    }

    /// Returns the current vector clock snapshot.
    #[must_use]
    pub fn current(&self) -> VectorClock {
        self.clock.lock().clone()
    }
}

impl fmt::Debug for VectorClockHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VectorClockHandle")
            .field("node", &self.node)
            .field("clock", &self.clock.lock())
            .finish()
    }
}

impl LogicalClock for VectorClockHandle {
    type Time = VectorClock;

    fn tick(&self) -> Self::Time {
        let mut clock = self.clock.lock();
        clock.increment(&self.node);
        clock.clone()
    }

    fn receive(&self, sender_time: &Self::Time) -> Self::Time {
        let mut clock = self.clock.lock();
        clock.receive(&self.node, sender_time);
        clock.clone()
    }

    fn now(&self) -> Self::Time {
        self.clock.lock().clone()
    }
}

/// Logical time values for heterogeneous clock types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LogicalTime {
    /// Lamport clock time.
    Lamport(LamportTime),
    /// Vector clock time.
    Vector(VectorClock),
    /// Hybrid clock time.
    Hybrid(HybridTime),
}

impl LogicalTime {
    /// Returns the logical clock kind for this time value.
    #[must_use]
    pub const fn kind(&self) -> LogicalClockKind {
        match self {
            Self::Lamport(_) => LogicalClockKind::Lamport,
            Self::Vector(_) => LogicalClockKind::Vector,
            Self::Hybrid(_) => LogicalClockKind::Hybrid,
        }
    }

    /// Compares two logical times for causal ordering.
    ///
    /// Returns the causal relationship between `self` and `other`.
    /// For Lamport/Hybrid clocks this is derived from total/partial order;
    /// for vector clocks this uses the vector clock causal order directly.
    ///
    /// Returns `CausalOrder::Concurrent` if the clock types differ.
    #[must_use]
    pub fn causal_order(&self, other: &Self) -> CausalOrder {
        match (self, other) {
            (Self::Vector(a), Self::Vector(b)) => a.causal_order(b),
            _ => match self.partial_cmp(other) {
                Some(std::cmp::Ordering::Less) => CausalOrder::Before,
                Some(std::cmp::Ordering::Greater) => CausalOrder::After,
                Some(std::cmp::Ordering::Equal) => CausalOrder::Equal,
                None => CausalOrder::Concurrent,
            },
        }
    }
}

impl PartialOrd for LogicalTime {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match (self, other) {
            (Self::Lamport(a), Self::Lamport(b)) => a.partial_cmp(b),
            (Self::Vector(a), Self::Vector(b)) => a.partial_cmp(b),
            (Self::Hybrid(a), Self::Hybrid(b)) => a.partial_cmp(b),
            _ => None,
        }
    }
}

/// Kind of logical clock in use.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogicalClockKind {
    /// Lamport clock.
    Lamport,
    /// Vector clock.
    Vector,
    /// Hybrid clock.
    Hybrid,
}

/// Runtime-selected logical clock configuration.
#[derive(Clone, Debug)]
pub enum LogicalClockMode {
    /// Use a Lamport clock.
    Lamport,
    /// Use a vector clock with the provided local node id.
    Vector {
        /// Local node identity for vector clock tracking.
        node: NodeId,
    },
    /// Use a hybrid logical clock.
    Hybrid,
}

/// Opaque handle to a logical clock instance.
#[derive(Clone)]
pub enum LogicalClockHandle {
    /// Lamport clock handle.
    Lamport(Arc<LamportClock>),
    /// Vector clock handle.
    Vector(Arc<VectorClockHandle>),
    /// Hybrid clock handle.
    Hybrid(Arc<HybridClock>),
}

impl LogicalClockHandle {
    /// Returns the kind of clock this handle wraps.
    #[must_use]
    pub const fn kind(&self) -> LogicalClockKind {
        match self {
            Self::Lamport(_) => LogicalClockKind::Lamport,
            Self::Vector(_) => LogicalClockKind::Vector,
            Self::Hybrid(_) => LogicalClockKind::Hybrid,
        }
    }

    /// Records a local event and returns the updated logical time.
    #[must_use]
    pub fn tick(&self) -> LogicalTime {
        match self {
            Self::Lamport(clock) => LogicalTime::Lamport(clock.tick()),
            Self::Vector(clock) => LogicalTime::Vector(clock.tick()),
            Self::Hybrid(clock) => LogicalTime::Hybrid(clock.tick()),
        }
    }

    /// Updates the clock using a received logical time and returns the updated time.
    #[must_use]
    pub fn receive(&self, sender_time: &LogicalTime) -> LogicalTime {
        match (self, sender_time) {
            (Self::Lamport(clock), LogicalTime::Lamport(time)) => {
                LogicalTime::Lamport(clock.receive(*time))
            }
            (Self::Vector(clock), LogicalTime::Vector(time)) => {
                LogicalTime::Vector(clock.receive(time))
            }
            (Self::Hybrid(clock), LogicalTime::Hybrid(time)) => {
                LogicalTime::Hybrid(clock.receive(*time))
            }
            // Mismatched clock kinds: fall back to a local tick.
            _ => self.tick(),
        }
    }

    /// Returns the current logical time without ticking.
    #[must_use]
    pub fn now(&self) -> LogicalTime {
        match self {
            Self::Lamport(clock) => LogicalTime::Lamport(clock.now()),
            Self::Vector(clock) => LogicalTime::Vector(clock.now()),
            Self::Hybrid(clock) => LogicalTime::Hybrid(clock.now()),
        }
    }
}

impl fmt::Debug for LogicalClockHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Lamport(_) => f.write_str("LogicalClockHandle::Lamport"),
            Self::Vector(_) => f.write_str("LogicalClockHandle::Vector"),
            Self::Hybrid(_) => f.write_str("LogicalClockHandle::Hybrid"),
        }
    }
}

impl Default for LogicalClockHandle {
    fn default() -> Self {
        Self::Lamport(Arc::new(LamportClock::new()))
    }
}

impl LogicalClockMode {
    /// Builds a logical clock handle for the given timer driver context.
    #[must_use]
    pub fn build_handle(&self, timer_driver: Option<TimerDriverHandle>) -> LogicalClockHandle {
        match self {
            Self::Lamport => LogicalClockHandle::Lamport(Arc::new(LamportClock::new())),
            Self::Vector { node } => {
                LogicalClockHandle::Vector(Arc::new(VectorClockHandle::new(node.clone())))
            }
            Self::Hybrid => {
                let time_source: Arc<dyn TimeSource> = match timer_driver {
                    Some(driver) => Arc::new(TimerDriverSource::new(driver)),
                    None => Arc::new(WallClock::new()),
                };
                LogicalClockHandle::Hybrid(Arc::new(HybridClock::new(time_source)))
            }
        }
    }
}

#[derive(Clone)]
struct TimerDriverSource {
    timer: TimerDriverHandle,
}

impl TimerDriverSource {
    fn new(timer: TimerDriverHandle) -> Self {
        Self { timer }
    }
}

impl fmt::Debug for TimerDriverSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TimerDriverSource").finish()
    }
}

impl TimeSource for TimerDriverSource {
    fn now(&self) -> Time {
        self.timer.now()
    }
}

/// A vector clock for causal ordering in a distributed system.
///
/// Maps `NodeId → u64` counters. The partial order is:
/// - `a ≤ b` iff `∀ node: a[node] ≤ b[node]`
/// - `a < b` (happens-before) iff `a ≤ b` and `a ≠ b`
/// - `a ∥ b` (concurrent) iff `¬(a ≤ b)` and `¬(b ≤ a)`
#[derive(Clone, PartialEq, Eq)]
pub struct VectorClock {
    /// BTreeMap for deterministic iteration order.
    entries: BTreeMap<NodeId, u64>,
}

impl VectorClock {
    /// Creates an empty vector clock (all components zero).
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: BTreeMap::new(),
        }
    }

    /// Creates a vector clock with a single node initialized to 1.
    #[must_use]
    pub fn for_node(node: &NodeId) -> Self {
        let mut vc = Self::new();
        vc.entries.insert(node.clone(), 1);
        vc
    }

    /// Returns the counter for the given node (0 if absent).
    #[must_use]
    pub fn get(&self, node: &NodeId) -> u64 {
        self.entries.get(node).copied().unwrap_or(0)
    }

    /// Increments the counter for the given node and returns the new value.
    pub fn increment(&mut self, node: &NodeId) -> u64 {
        let entry = self.entries.entry(node.clone()).or_insert(0);
        *entry = entry
            .checked_add(1)
            .expect("Vector clock counter overflowed while incrementing");
        *entry
    }

    /// Sets the counter for a node to a specific value, monotone.
    ///
    /// Used when receiving a message: update local clock to be at least
    /// as large as the sender's value for each node.
    pub fn set(&mut self, node: &NodeId, value: u64) {
        if value == 0 {
            return;
        }
        let entry = self.entries.entry(node.clone()).or_insert(0);
        if value > *entry {
            *entry = value;
        }
    }

    /// Returns the merge (join / componentwise max) of two vector clocks.
    ///
    /// This is the least upper bound in the partial order.
    #[must_use]
    pub fn merge(&self, other: &Self) -> Self {
        let mut result = self.clone();
        for (node, &value) in &other.entries {
            let entry = result.entries.entry(node.clone()).or_insert(0);
            if value > *entry {
                *entry = value;
            }
        }
        result
    }

    /// Merges another vector clock into `self` in place.
    pub fn merge_in(&mut self, other: &Self) {
        for (node, &value) in &other.entries {
            let entry = self.entries.entry(node.clone()).or_insert(0);
            if value > *entry {
                *entry = value;
            }
        }
    }

    /// Increments the local node and merges the remote clock.
    ///
    /// This is the standard "on receive" operation:
    /// 1. Merge the incoming clock
    /// 2. Increment the local counter
    pub fn receive(&mut self, local_node: &NodeId, remote_clock: &Self) {
        self.merge_in(remote_clock);
        self.increment(local_node);
    }

    /// Compares two vector clocks for causal ordering.
    #[must_use]
    pub fn causal_order(&self, other: &Self) -> CausalOrder {
        let mut self_leq_other = true;
        let mut other_leq_self = true;

        // Check all nodes present in either clock.
        let all_nodes: std::collections::BTreeSet<&NodeId> =
            self.entries.keys().chain(other.entries.keys()).collect();

        for node in all_nodes {
            let a = self.get(node);
            let b = other.get(node);
            if a > b {
                self_leq_other = false;
            }
            if b > a {
                other_leq_self = false;
            }
            if !self_leq_other && !other_leq_self {
                return CausalOrder::Concurrent;
            }
        }

        match (self_leq_other, other_leq_self) {
            (true, true) => CausalOrder::Equal,
            (true, false) => CausalOrder::Before,
            (false, true) => CausalOrder::After,
            (false, false) => CausalOrder::Concurrent,
        }
    }

    /// Returns true if `self` happens-before `other`.
    #[must_use]
    pub fn happens_before(&self, other: &Self) -> bool {
        self.causal_order(other) == CausalOrder::Before
    }

    /// Returns true if `self` and `other` are concurrent.
    #[must_use]
    pub fn is_concurrent_with(&self, other: &Self) -> bool {
        self.causal_order(other) == CausalOrder::Concurrent
    }

    /// Returns the number of nodes tracked by this clock.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if all counters are zero (empty clock).
    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns an iterator over (node, counter) pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&NodeId, &u64)> {
        self.entries.iter()
    }
}

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

/// Implements the partial order for vector clocks.
///
/// Returns `None` when the clocks are concurrent (incomparable).
impl PartialOrd for VectorClock {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match self.causal_order(other) {
            CausalOrder::Before => Some(std::cmp::Ordering::Less),
            CausalOrder::After => Some(std::cmp::Ordering::Greater),
            CausalOrder::Equal => Some(std::cmp::Ordering::Equal),
            CausalOrder::Concurrent => None,
        }
    }
}

impl fmt::Debug for VectorClock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "VC{{")?;
        for (i, (node, value)) in self.entries.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}:{}", node.as_str(), value)?;
        }
        write!(f, "}}")
    }
}

impl fmt::Display for VectorClock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[")?;
        for (i, (node, value)) in self.entries.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}={}", node.as_str(), value)?;
        }
        write!(f, "]")
    }
}

/// Result of comparing two vector clocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CausalOrder {
    /// `self` happened strictly before `other`.
    Before,
    /// `self` happened strictly after `other`.
    After,
    /// `self` and `other` are exactly equal.
    Equal,
    /// `self` and `other` are concurrent (neither happened before the other).
    Concurrent,
}

/// A trace event annotated with causal metadata.
///
/// Wraps any event with the vector clock at the time the event was recorded,
/// plus the originating node.
#[derive(Clone, Debug)]
pub struct CausalEvent<T> {
    /// The originating node.
    pub origin: NodeId,
    /// The vector clock at event creation time.
    pub clock: VectorClock,
    /// The wrapped event.
    pub event: T,
}

impl<T> CausalEvent<T> {
    /// Creates a new causal event.
    pub fn new(origin: NodeId, clock: VectorClock, event: T) -> Self {
        Self {
            origin,
            clock,
            event,
        }
    }

    /// Returns true if this event causally precedes `other`.
    pub fn happens_before<U>(&self, other: &CausalEvent<U>) -> bool {
        self.clock.happens_before(&other.clock)
    }

    /// Returns true if this event is concurrent with `other`.
    pub fn is_concurrent_with<U>(&self, other: &CausalEvent<U>) -> bool {
        self.clock.is_concurrent_with(&other.clock)
    }
}

/// A causal history tracker for a single node.
///
/// Manages the local vector clock, incrementing on local events and
/// merging on message receive.
#[derive(Clone, Debug)]
pub struct CausalTracker {
    /// The local node.
    node: NodeId,
    /// The current vector clock.
    clock: VectorClock,
}

impl CausalTracker {
    /// Creates a new tracker for the given node.
    #[must_use]
    pub fn new(node: NodeId) -> Self {
        Self {
            node,
            clock: VectorClock::new(),
        }
    }

    /// Records a local event, incrementing the local counter.
    ///
    /// Returns the vector clock at the time of the event.
    pub fn record_local_event(&mut self) -> VectorClock {
        self.clock.increment(&self.node);
        self.clock.clone()
    }

    /// Records a local event, wrapping it with causal metadata.
    pub fn record<T>(&mut self, event: T) -> CausalEvent<T> {
        let clock = self.record_local_event();
        CausalEvent::new(self.node.clone(), clock, event)
    }

    /// Records a message send. Increments the local clock and returns
    /// the clock to attach to the outgoing message.
    pub fn on_send(&mut self) -> VectorClock {
        self.record_local_event()
    }

    /// Records a message receive. Merges the incoming clock and
    /// increments the local counter.
    pub fn on_receive(&mut self, remote_clock: &VectorClock) {
        self.clock.receive(&self.node, remote_clock);
    }

    /// Returns the current vector clock (snapshot).
    #[must_use]
    pub fn current_clock(&self) -> &VectorClock {
        &self.clock
    }

    /// Returns the local node ID.
    #[must_use]
    pub fn node(&self) -> &NodeId {
        &self.node
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::time::VirtualClock;
    use serde_json::{Value, json};
    use std::sync::Arc;

    fn node(name: &str) -> NodeId {
        NodeId::new(name)
    }

    fn scrub_vclock_output(value: Value) -> Value {
        fn scrub_node_names(text: &str) -> String {
            text.replace("alpha-node", "[NODE_A]")
                .replace("beta-node", "[NODE_B]")
        }

        let mut scrubbed = value;

        if let Some(display) = scrubbed.pointer_mut("/display") {
            if let Some(text) = display.as_str() {
                *display = Value::String(scrub_node_names(text));
            }
        }

        if let Some(debug) = scrubbed.pointer_mut("/debug") {
            if let Some(text) = debug.as_str() {
                *debug = Value::String(scrub_node_names(text));
            }
        }

        scrubbed
    }

    #[test]
    fn empty_clocks_are_equal() {
        let a = VectorClock::new();
        let b = VectorClock::new();
        assert_eq!(a.causal_order(&b), CausalOrder::Equal);
        assert_eq!(a.partial_cmp(&b), Some(std::cmp::Ordering::Equal));
    }

    #[test]
    fn increment_creates_happens_before() {
        let n = node("A");
        let mut a = VectorClock::new();
        let b = a.clone();
        a.increment(&n);
        assert_eq!(b.causal_order(&a), CausalOrder::Before);
        assert!(b.happens_before(&a));
    }

    #[test]
    fn concurrent_detection() {
        let na = node("A");
        let nb = node("B");
        let mut a = VectorClock::new();
        let mut b = VectorClock::new();
        a.increment(&na);
        b.increment(&nb);
        assert_eq!(a.causal_order(&b), CausalOrder::Concurrent);
        assert!(a.is_concurrent_with(&b));
        assert_eq!(a.partial_cmp(&b), None);
    }

    #[test]
    fn lamport_tick_and_receive() {
        let clock = LamportClock::new();
        let t1 = clock.tick();
        let t2 = clock.tick();
        assert!(t2 > t1);

        let remote = LamportTime::from_raw(10);
        let merged = clock.receive(remote);
        assert!(merged.raw() > remote.raw());
    }

    #[test]
    #[should_panic(expected = "Lamport clock overflowed while ticking")]
    fn lamport_tick_panics_on_overflow() {
        let clock = LamportClock::with_start(u64::MAX);
        let _ = clock.tick();
    }

    #[test]
    #[should_panic(expected = "Lamport clock overflowed while merging a received time")]
    fn lamport_receive_panics_on_overflow() {
        let clock = LamportClock::with_start(u64::MAX - 1);
        let _ = clock.receive(LamportTime::from_raw(u64::MAX));
    }

    #[test]
    fn hybrid_clock_deterministic_with_virtual_time() {
        let virtual_clock = Arc::new(VirtualClock::new());
        let hlc = HybridClock::new(virtual_clock.clone());

        let t1 = hlc.tick();
        let t2 = hlc.tick();
        assert!(t2 >= t1);

        virtual_clock.advance(1_000);
        let t3 = hlc.tick();
        assert!(t3.physical() >= t2.physical());
    }

    #[test]
    fn hybrid_now_resets_logical_when_physical_advances() {
        let virtual_clock = Arc::new(VirtualClock::new());
        let hlc = HybridClock::new(virtual_clock.clone());

        let t1 = hlc.tick();
        assert_eq!(t1.logical(), 1);

        virtual_clock.advance(1_000);
        let observed = hlc.now();
        assert!(observed.physical() > t1.physical());
        assert_eq!(observed.logical(), 0);

        let t2 = hlc.tick();
        assert!(t2 >= observed);
    }

    #[test]
    #[should_panic(expected = "Hybrid clock logical counter overflowed while ticking")]
    fn hybrid_tick_panics_on_logical_overflow() {
        let time_source: Arc<dyn TimeSource> = Arc::new(VirtualClock::new());
        let hlc = HybridClock {
            time_source,
            state: Mutex::new(HybridState {
                last_physical: Time::ZERO,
                logical: u64::MAX,
            }),
        };

        let _ = hlc.tick();
    }

    #[test]
    #[should_panic(
        expected = "Hybrid clock logical counter overflowed while merging equal physical time"
    )]
    fn hybrid_receive_panics_on_equal_physical_logical_overflow() {
        let time_source: Arc<dyn TimeSource> = Arc::new(VirtualClock::new());
        let hlc = HybridClock {
            time_source,
            state: Mutex::new(HybridState {
                last_physical: Time::ZERO,
                logical: u64::MAX,
            }),
        };

        let _ = hlc.receive(HybridTime::new(Time::ZERO, u64::MAX));
    }

    #[test]
    fn merge_is_least_upper_bound() {
        let na = node("A");
        let nb = node("B");
        let mut a = VectorClock::new();
        a.increment(&na);
        a.increment(&na);
        let mut b = VectorClock::new();
        b.increment(&nb);
        b.increment(&nb);
        b.increment(&nb);

        let merged = a.merge(&b);
        assert_eq!(merged.get(&na), 2);
        assert_eq!(merged.get(&nb), 3);
        // Both original clocks happen-before the merge
        assert!(a.happens_before(&merged));
        assert!(b.happens_before(&merged));
    }

    #[test]
    fn merge_is_commutative() {
        let na = node("A");
        let nb = node("B");
        let mut a = VectorClock::new();
        a.increment(&na);
        let mut b = VectorClock::new();
        b.increment(&nb);

        assert_eq!(a.merge(&b), b.merge(&a));
    }

    #[test]
    fn merge_is_associative() {
        let na = node("A");
        let nb = node("B");
        let nc = node("C");
        let mut a = VectorClock::new();
        a.increment(&na);
        let mut b = VectorClock::new();
        b.increment(&nb);
        let mut c = VectorClock::new();
        c.increment(&nc);

        let ab_c = a.merge(&b).merge(&c);
        let a_bc = a.merge(&b.merge(&c));
        assert_eq!(ab_c, a_bc);
    }

    #[test]
    fn merge_is_idempotent() {
        let na = node("A");
        let mut a = VectorClock::new();
        a.increment(&na);
        assert_eq!(a.merge(&a), a);
    }

    #[test]
    fn receive_merges_and_increments() {
        let na = node("A");
        let nb = node("B");
        let mut a = VectorClock::new();
        a.increment(&na); // A: {A:1}

        let mut b = VectorClock::new();
        b.increment(&nb); // B: {B:1}
        b.increment(&nb); // B: {B:2}

        // A receives a message with B's clock
        a.receive(&na, &b); // merge → {A:1, B:2}, then increment → {A:2, B:2}
        assert_eq!(a.get(&na), 2);
        assert_eq!(a.get(&nb), 2);
    }

    #[test]
    fn vector_clock_output_snapshot_scrubbed() {
        let na = node("alpha-node");
        let nb = node("beta-node");
        let mut a = VectorClock::new();
        a.increment(&na);
        a.increment(&na);

        let mut b = VectorClock::new();
        b.increment(&nb);

        let merged = a.merge(&b);
        insta::assert_json_snapshot!(
            "vector_clock_output_scrubbed",
            scrub_vclock_output(json!({
                "display": merged.to_string(),
                "debug": format!("{merged:?}"),
                "order_vs_a": format!("{:?}", merged.causal_order(&a)),
            }))
        );
    }

    #[test]
    fn for_node_initializes_to_one() {
        let n = node("X");
        let vc = VectorClock::for_node(&n);
        assert_eq!(vc.get(&n), 1);
        assert_eq!(vc.node_count(), 1);
    }

    #[test]
    fn set_is_monotone() {
        let n = node("A");
        let mut vc = VectorClock::new();
        vc.set(&n, 3);
        assert_eq!(vc.get(&n), 3);

        // Lower value should not regress the clock.
        vc.set(&n, 1);
        assert_eq!(vc.get(&n), 3);

        // Higher value should advance.
        vc.set(&n, 7);
        assert_eq!(vc.get(&n), 7);
    }

    #[test]
    #[should_panic(expected = "Vector clock counter overflowed while incrementing")]
    fn vector_clock_increment_panics_on_overflow() {
        let n = node("A");
        let mut vc = VectorClock::new();
        vc.entries.insert(n.clone(), u64::MAX);
        let _ = vc.increment(&n);
    }

    #[test]
    #[should_panic(expected = "Vector clock counter overflowed while incrementing")]
    fn vector_clock_receive_panics_on_local_overflow() {
        let local = node("A");
        let remote = node("B");
        let mut vc = VectorClock::new();
        vc.entries.insert(local.clone(), u64::MAX);

        let mut remote_clock = VectorClock::new();
        remote_clock.set(&remote, 1);

        vc.receive(&local, &remote_clock);
    }

    #[test]
    fn causal_tracker_send_receive_protocol() {
        let na = node("A");
        let nb = node("B");
        let mut tracker_a = CausalTracker::new(na.clone());
        let mut tracker_b = CausalTracker::new(nb.clone());

        // A does local work
        tracker_a.record_local_event(); // A: {A:1}

        // A sends message to B
        let msg_clock = tracker_a.on_send(); // A: {A:2}
        assert_eq!(msg_clock.get(&na), 2);

        // B receives message from A
        tracker_b.on_receive(&msg_clock); // B: merge({}, {A:2}) → {A:2}, incr → {A:2, B:1}
        assert_eq!(tracker_b.current_clock().get(&na), 2);
        assert_eq!(tracker_b.current_clock().get(&nb), 1);

        // B does more work
        tracker_b.record_local_event(); // B: {A:2, B:2}

        // B's events happen after A's send
        assert!(msg_clock.happens_before(tracker_b.current_clock()));
    }

    #[test]
    fn causal_event_ordering() {
        let na = node("A");
        let nb = node("B");
        let mut tracker_a = CausalTracker::new(na);
        let mut tracker_b = CausalTracker::new(nb);

        let e1 = tracker_a.record("event-1");
        let e2 = tracker_b.record("event-2");

        // Independent events are concurrent
        assert!(e1.is_concurrent_with(&e2));
        assert!(!e1.happens_before(&e2));
    }

    #[test]
    fn display_formatting() {
        let na = node("A");
        let nb = node("B");
        let mut vc = VectorClock::new();
        vc.increment(&na);
        vc.increment(&nb);
        vc.increment(&nb);
        let display = format!("{vc}");
        assert!(display.contains("A=1"));
        assert!(display.contains("B=2"));
    }

    #[test]
    fn partial_order_after() {
        let na = node("A");
        let mut a = VectorClock::new();
        a.increment(&na);
        let b = VectorClock::new();
        assert_eq!(a.causal_order(&b), CausalOrder::After);
        assert_eq!(a.partial_cmp(&b), Some(std::cmp::Ordering::Greater));
    }

    #[test]
    fn three_node_diamond() {
        // Classic diamond:
        //   A sends to B and C independently
        //   B and C are concurrent
        //   D receives from both B and C
        let na = node("A");
        let nb = node("B");
        let nc = node("C");
        let nd = node("D");

        let mut ta = CausalTracker::new(na);
        let mut tb = CausalTracker::new(nb);
        let mut tc = CausalTracker::new(nc);
        let mut td = CausalTracker::new(nd);

        // A sends to B and C
        let msg_to_b = ta.on_send();
        let msg_to_c = ta.on_send();

        tb.on_receive(&msg_to_b);
        tc.on_receive(&msg_to_c);

        // B and C do independent work
        let b_clock = tb.on_send();
        let c_clock = tc.on_send();

        // B and C are concurrent
        assert!(b_clock.is_concurrent_with(&c_clock));

        // D receives from B then C
        td.on_receive(&b_clock);
        td.on_receive(&c_clock);

        // D happens after both B and C
        assert!(b_clock.happens_before(td.current_clock()));
        assert!(c_clock.happens_before(td.current_clock()));
    }

    // =========================================================================
    // Wave 55 – pure data-type trait coverage
    // =========================================================================

    #[test]
    fn hybrid_time_debug_clone_copy_hash_ord() {
        use std::collections::HashSet;
        let ht = HybridTime::new(Time::from_nanos(1_000), 3);
        let dbg = format!("{ht:?}");
        assert!(dbg.contains("HybridTime"), "{dbg}");
        let copied = ht;
        let cloned = ht;
        assert_eq!(copied, cloned);

        let earlier = HybridTime::new(Time::ZERO, 0);
        assert!(earlier < ht);

        let mut set = HashSet::new();
        set.insert(ht);
        set.insert(earlier);
        assert_eq!(set.len(), 2);
        assert!(set.contains(&ht));
    }

    #[test]
    fn logical_clock_kind_debug_clone_copy_eq() {
        let k = LogicalClockKind::Lamport;
        let dbg = format!("{k:?}");
        assert!(dbg.contains("Lamport"), "{dbg}");
        let copied = k;
        let cloned = k;
        assert_eq!(copied, cloned);
        assert_ne!(k, LogicalClockKind::Vector);
        assert_ne!(k, LogicalClockKind::Hybrid);
    }

    #[test]
    fn logical_time_debug_clone_eq() {
        let lt = LogicalTime::Lamport(LamportTime::from_raw(5));
        let dbg = format!("{lt:?}");
        assert!(dbg.contains("Lamport"), "{dbg}");
        let cloned = lt.clone();
        assert_eq!(lt, cloned);
    }

    #[test]
    fn logical_clock_mode_debug_clone() {
        let mode = LogicalClockMode::Lamport;
        let dbg = format!("{mode:?}");
        assert!(dbg.contains("Lamport"), "{dbg}");
        let cloned = mode;
        let dbg2 = format!("{cloned:?}");
        assert_eq!(dbg, dbg2);
    }
}