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
//! Channel Atomicity Verification Framework
//!
//! This oracle verifies that channel operations maintain atomicity guarantees
//! in the presence of cancellation, ensuring that the two-phase reserve/commit
//! protocol prevents data loss and maintains consistent state.
//!
//! # Core Guarantees Verified
//!
//! 1. **Reservation Lifecycle**: Every reservation must be either committed or aborted
//! 2. **No Double Operations**: Cannot commit/abort the same reservation twice
//! 3. **No Use After Operations**: Cannot use reservation after commit/abort
//! 4. **Waker Consistency**: Lost/spurious wakeups detection and prevention
//! 5. **Cancel-Safe Operations**: No data loss when operations are cancelled
//!
//! # Usage
//!
//! ```rust
//! use asupersync::lab::oracle::channel_atomicity::{ChannelAtomicityOracle, ChannelAtomicityConfig};
//!
//! let mut oracle = ChannelAtomicityOracle::new(ChannelAtomicityConfig {
//! track_reservations: true,
//! track_wakers: true,
//! enforcement: EnforcementMode::Panic,
//! structured_logging: true,
//! ..Default::default()
//! });
//!
//! // Hook into channel operations
//! oracle.on_reservation_created(reservation_id, channel_id, Some(trace_id));
//! oracle.on_reservation_committed(reservation_id, data_size);
//! oracle.on_reservation_aborted(reservation_id, reason);
//! ```
use crate::trace::distributed::TraceId;
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{SystemTime, UNIX_EPOCH};
/// Unique identifier for a channel reservation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ReservationId(pub u64);
/// Unique identifier for a channel
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ChannelId(pub u64);
/// Unique identifier for a waker
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WakerId(pub u64);
/// Configuration for the Channel Atomicity Oracle
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct ChannelAtomicityConfig {
/// Whether to track reservation lifecycles
pub track_reservations: bool,
/// Whether to track waker patterns
pub track_wakers: bool,
/// Enforcement mode for violations
pub enforcement: EnforcementMode,
/// Enable structured logging for violations
pub structured_logging: bool,
/// Include stack traces in violation records
pub include_stack_traces: bool,
/// Enable replay command generation for violations
pub enable_replay_commands: bool,
/// Maximum number of violations to track before dropping oldest
pub max_violations_tracked: usize,
/// Maximum age of reservations to track (for cleanup)
pub max_reservation_age_seconds: u64,
/// Maximum number of reservations to track per channel
pub max_reservations_per_channel: usize,
}
impl Default for ChannelAtomicityConfig {
fn default() -> Self {
Self {
track_reservations: true,
track_wakers: true,
enforcement: EnforcementMode::Warn,
structured_logging: false,
include_stack_traces: false,
enable_replay_commands: false,
max_violations_tracked: 1000,
max_reservation_age_seconds: 3600, // 1 hour
max_reservations_per_channel: 10000,
}
}
}
/// Enforcement mode for atomicity violations
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnforcementMode {
/// Only collect violations, no immediate action
Collect,
/// Emit warnings for violations
Warn,
/// Panic on violations (for testing)
Panic,
}
/// Types of channel atomicity violations
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChannelAtomicityViolation {
/// Reservation was created but never committed or aborted
ReservationLeak {
/// ID of the leaked reservation.
reservation_id: ReservationId,
/// ID of the channel where the leak occurred.
channel_id: ChannelId,
/// Timestamp when the reservation was created.
created_at: SystemTime,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
/// Attempt to commit an already committed reservation
DoubleCommit {
/// ID of the reservation that was double-committed.
reservation_id: ReservationId,
/// ID of the channel where the double commit occurred.
channel_id: ChannelId,
/// Timestamp of the first commit.
first_commit_at: SystemTime,
/// Timestamp of the second (invalid) commit.
second_commit_at: SystemTime,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
/// Attempt to abort an already aborted reservation
DoubleAbort {
/// ID of the reservation that was double-aborted.
reservation_id: ReservationId,
/// ID of the channel where the double abort occurred.
channel_id: ChannelId,
/// Timestamp of the first abort.
first_abort_at: SystemTime,
/// Timestamp of the second (invalid) abort.
second_abort_at: SystemTime,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
/// Attempt to use reservation after commit
UseAfterCommit {
/// ID of the reservation used after commit.
reservation_id: ReservationId,
/// ID of the channel where the violation occurred.
channel_id: ChannelId,
/// Timestamp when the reservation was committed.
commit_at: SystemTime,
/// Timestamp of the invalid use attempt.
use_at: SystemTime,
/// Description of the invalid operation attempted.
operation: String,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
/// Attempt to use reservation after abort
UseAfterAbort {
/// ID of the reservation used after abort.
reservation_id: ReservationId,
/// ID of the channel where the violation occurred.
channel_id: ChannelId,
/// Timestamp when the reservation was aborted.
abort_at: SystemTime,
/// Timestamp of the invalid use attempt.
use_at: SystemTime,
/// Description of the invalid operation attempted.
operation: String,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
/// Wakeup lost during channel operation
LostWakeup {
/// ID of the waker that lost its wakeup.
waker_id: WakerId,
/// ID of the channel where the wakeup was lost.
channel_id: ChannelId,
/// Timestamp when the wakeup was expected.
expected_at: SystemTime,
/// Timestamp when the loss was detected.
detected_at: SystemTime,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
/// Spurious wakeup without corresponding channel event
SpuriousWakeup {
/// ID of the waker that had a spurious wakeup.
waker_id: WakerId,
/// ID of the channel where the spurious wakeup occurred.
channel_id: ChannelId,
/// Timestamp of the spurious wakeup.
wakeup_at: SystemTime,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
/// Data loss detected during cancellation
DataLossOnCancel {
/// ID of the channel where data loss occurred.
channel_id: ChannelId,
/// Size of the lost data in bytes.
data_size: usize,
/// Timestamp when cancellation occurred.
cancel_at: SystemTime,
/// Optional trace ID for debugging context.
trace_id: Option<TraceId>,
},
}
impl std::fmt::Display for ChannelAtomicityViolation {
#[allow(clippy::too_many_lines)]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ReservationLeak {
reservation_id,
channel_id,
created_at,
trace_id,
} => {
write!(
f,
"Reservation leak: {reservation_id:?} on channel {channel_id:?} created at {created_at:?}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
Self::DoubleCommit {
reservation_id,
channel_id,
first_commit_at,
second_commit_at,
trace_id,
} => {
write!(
f,
"Double commit: {reservation_id:?} on channel {channel_id:?} first at {first_commit_at:?}, second at {second_commit_at:?}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
Self::DoubleAbort {
reservation_id,
channel_id,
first_abort_at,
second_abort_at,
trace_id,
} => {
write!(
f,
"Double abort: {reservation_id:?} on channel {channel_id:?} first at {first_abort_at:?}, second at {second_abort_at:?}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
Self::UseAfterCommit {
reservation_id,
channel_id,
commit_at,
use_at,
operation,
trace_id,
} => {
write!(
f,
"Use after commit: {reservation_id:?} on channel {channel_id:?} committed at {commit_at:?}, used at {use_at:?} for {operation}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
Self::UseAfterAbort {
reservation_id,
channel_id,
abort_at,
use_at,
operation,
trace_id,
} => {
write!(
f,
"Use after abort: {reservation_id:?} on channel {channel_id:?} aborted at {abort_at:?}, used at {use_at:?} for {operation}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
Self::LostWakeup {
waker_id,
channel_id,
expected_at,
detected_at,
trace_id,
} => {
write!(
f,
"Lost wakeup: {waker_id:?} on channel {channel_id:?} expected at {expected_at:?}, detected at {detected_at:?}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
Self::SpuriousWakeup {
waker_id,
channel_id,
wakeup_at,
trace_id,
} => {
write!(
f,
"Spurious wakeup: {waker_id:?} on channel {channel_id:?} at {wakeup_at:?}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
Self::DataLossOnCancel {
channel_id,
data_size,
cancel_at,
trace_id,
} => {
write!(
f,
"Data loss on cancel: channel {channel_id:?} lost {data_size} bytes at {cancel_at:?}"
)?;
if let Some(trace) = trace_id {
write!(f, " (trace: {trace:?})")?;
}
Ok(())
}
}
}
}
/// Enhanced violation record with diagnostics
/// Record of a channel atomicity violation with metadata.
#[derive(Debug, Clone)]
pub struct ViolationRecord {
/// The specific violation that occurred.
pub violation: ChannelAtomicityViolation,
/// Timestamp when the violation was recorded.
pub timestamp: SystemTime,
/// Optional trace ID for correlation.
pub trace_id: Option<TraceId>,
/// Optional stack trace at violation time.
pub stack_trace: Option<String>,
/// Optional command to replay the violation scenario.
pub replay_command: Option<String>,
}
impl ViolationRecord {
/// Creates a new violation record with metadata from the given violation and config.
#[must_use]
pub fn new(violation: ChannelAtomicityViolation, config: &ChannelAtomicityConfig) -> Self {
let trace_id = match &violation {
ChannelAtomicityViolation::ReservationLeak { trace_id, .. } => *trace_id,
ChannelAtomicityViolation::DoubleCommit { trace_id, .. } => *trace_id,
ChannelAtomicityViolation::DoubleAbort { trace_id, .. } => *trace_id,
ChannelAtomicityViolation::UseAfterCommit { trace_id, .. } => *trace_id,
ChannelAtomicityViolation::UseAfterAbort { trace_id, .. } => *trace_id,
ChannelAtomicityViolation::LostWakeup { trace_id, .. } => *trace_id,
ChannelAtomicityViolation::SpuriousWakeup { trace_id, .. } => *trace_id,
ChannelAtomicityViolation::DataLossOnCancel { trace_id, .. } => *trace_id,
};
let stack_trace = if config.include_stack_traces {
Some(Self::capture_stack_trace())
} else {
None
};
let replay_command = if config.enable_replay_commands {
trace_id.map(|tid| format!("asupersync-replay --trace-id {tid:?}"))
} else {
None
};
Self {
violation,
timestamp: SystemTime::now(),
trace_id,
stack_trace,
replay_command,
}
}
/// Emits a structured JSON log entry for this violation record.
#[allow(unused_variables)]
pub fn emit_structured_log(&self) {
let timestamp_millis = self
.timestamp
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis());
crate::tracing_compat::error!(
violation_type = "channel_atomicity_violation",
timestamp_millis = timestamp_millis,
violation = %self.violation,
trace_id = ?self.trace_id,
replay_command = ?self.replay_command,
stack_trace = ?self.stack_trace,
"channel atomicity violation"
);
}
fn capture_stack_trace() -> String {
// In a real implementation, this would capture the actual stack trace
// For now, we provide a placeholder
"Stack trace capture not implemented in this preview".to_string()
}
}
/// State tracking for a channel reservation
#[derive(Debug, Clone)]
pub struct ReservationState {
/// Unique identifier for this reservation.
pub reservation_id: ReservationId,
/// ID of the channel this reservation belongs to.
pub channel_id: ChannelId,
/// Timestamp when the reservation was created.
pub created_at: SystemTime,
/// Optional trace ID for debugging context.
pub trace_id: Option<TraceId>,
/// Current status of the reservation.
pub status: ReservationStatus,
}
/// Status of a channel reservation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReservationStatus {
/// Reservation is active and can be used.
Active,
/// Reservation has been committed.
Committed {
/// Timestamp when the reservation was committed.
at: SystemTime,
/// Size of data committed with the reservation.
data_size: usize,
},
/// Reservation has been aborted.
Aborted {
/// Timestamp when the reservation was aborted.
at: SystemTime,
/// Reason for the abort.
reason: String,
},
}
/// State tracking for wakers
#[derive(Debug, Clone)]
pub struct WakerState {
/// Unique identifier for this waker.
pub waker_id: WakerId,
/// ID of the channel this waker is associated with.
pub channel_id: ChannelId,
/// Timestamp when the waker was registered.
pub registered_at: SystemTime,
/// Optional timestamp when wakeup is expected.
pub expected_wakeup_at: Option<SystemTime>,
/// Optional timestamp when wakeup actually occurred.
pub actual_wakeup_at: Option<SystemTime>,
/// Optional trace ID for debugging context.
pub trace_id: Option<TraceId>,
}
/// Channel Atomicity Oracle
#[derive(Debug)]
pub struct ChannelAtomicityOracle {
config: ChannelAtomicityConfig,
/// Track active reservations by ID
reservations: HashMap<ReservationId, ReservationState>,
/// Track reservations by channel for cleanup
channel_reservations: HashMap<ChannelId, HashSet<ReservationId>>,
/// Track waker state
wakers: HashMap<WakerId, WakerState>,
/// Track wakers by channel
channel_wakers: HashMap<ChannelId, HashSet<WakerId>>,
/// Violations found (legacy format for compatibility)
violations: Vec<ChannelAtomicityViolation>,
/// Enhanced violation records with diagnostics
violation_records: VecDeque<ViolationRecord>,
/// Statistics
stats: ChannelAtomicityStatistics,
}
/// Statistics tracked by the Channel Atomicity Oracle.
#[derive(Debug, Clone, Default)]
pub struct ChannelAtomicityStatistics {
/// Total number of reservations created.
pub total_reservations_created: u64,
/// Total number of reservations successfully committed.
pub total_reservations_committed: u64,
/// Total number of reservations aborted.
pub total_reservations_aborted: u64,
/// Total number of reservations that leaked (never committed or aborted).
pub total_reservations_leaked: u64,
/// Total number of wakers registered.
pub total_wakers_registered: u64,
/// Total number of expected wakeups.
pub total_wakeups_expected: u64,
/// Total number of actual wakeups that occurred.
pub total_wakeups_actual: u64,
/// Total number of lost wakeups detected.
pub total_lost_wakeups: u64,
/// Total number of spurious wakeups detected.
pub total_spurious_wakeups: u64,
/// Total number of atomicity violations detected.
pub total_violations: u64,
}
impl Default for ChannelAtomicityOracle {
fn default() -> Self {
Self::new(ChannelAtomicityConfig::default())
}
}
impl ChannelAtomicityOracle {
/// Create a new oracle with the given configuration
#[must_use]
pub fn new(config: ChannelAtomicityConfig) -> Self {
Self {
config,
reservations: HashMap::new(),
channel_reservations: HashMap::new(),
wakers: HashMap::new(),
channel_wakers: HashMap::new(),
violations: Vec::new(),
violation_records: VecDeque::new(),
stats: ChannelAtomicityStatistics::default(),
}
}
/// Create oracle with default configuration
#[must_use]
pub fn with_defaults() -> Self {
Self::new(ChannelAtomicityConfig::default())
}
/// Create oracle for runtime use with enhanced enforcement
#[must_use]
pub fn for_runtime() -> Self {
Self::new(ChannelAtomicityConfig {
track_reservations: true,
track_wakers: true,
enforcement: EnforcementMode::Panic,
structured_logging: true,
include_stack_traces: true,
enable_replay_commands: true,
max_violations_tracked: 100,
max_reservation_age_seconds: 300, // 5 minutes
max_reservations_per_channel: 1000,
})
}
/// Record a reservation creation event
pub fn on_reservation_created(
&mut self,
reservation_id: ReservationId,
channel_id: ChannelId,
trace_id: Option<TraceId>,
) {
if !self.config.track_reservations {
return;
}
let state = ReservationState {
reservation_id,
channel_id,
created_at: SystemTime::now(),
trace_id,
status: ReservationStatus::Active,
};
self.reservations.insert(reservation_id, state);
self.channel_reservations
.entry(channel_id)
.or_default()
.insert(reservation_id);
self.stats.total_reservations_created += 1;
self.cleanup_old_reservations();
}
/// Record a reservation commit event
pub fn on_reservation_committed(&mut self, reservation_id: ReservationId, data_size: usize) {
if !self.config.track_reservations {
return;
}
if let Some(state) = self.reservations.get_mut(&reservation_id) {
let commit_time = SystemTime::now();
match &state.status {
ReservationStatus::Active => {
state.status = ReservationStatus::Committed {
at: commit_time,
data_size,
};
self.stats.total_reservations_committed += 1;
}
ReservationStatus::Committed { at, .. } => {
let violation = ChannelAtomicityViolation::DoubleCommit {
reservation_id,
channel_id: state.channel_id,
first_commit_at: *at,
second_commit_at: commit_time,
trace_id: state.trace_id,
};
self.record_violation(violation);
}
ReservationStatus::Aborted { .. } => {
let violation = ChannelAtomicityViolation::UseAfterAbort {
reservation_id,
channel_id: state.channel_id,
abort_at: match state.status {
ReservationStatus::Aborted { at, .. } => at,
_ => unreachable!(),
},
use_at: commit_time,
operation: "commit".to_string(),
trace_id: state.trace_id,
};
self.record_violation(violation);
}
}
}
}
/// Record a reservation abort event
pub fn on_reservation_aborted(&mut self, reservation_id: ReservationId, reason: String) {
if !self.config.track_reservations {
return;
}
if let Some(state) = self.reservations.get_mut(&reservation_id) {
let abort_time = SystemTime::now();
match &state.status {
ReservationStatus::Active => {
state.status = ReservationStatus::Aborted {
at: abort_time,
reason,
};
self.stats.total_reservations_aborted += 1;
}
ReservationStatus::Aborted { at, .. } => {
let violation = ChannelAtomicityViolation::DoubleAbort {
reservation_id,
channel_id: state.channel_id,
first_abort_at: *at,
second_abort_at: abort_time,
trace_id: state.trace_id,
};
self.record_violation(violation);
}
ReservationStatus::Committed { at, .. } => {
let violation = ChannelAtomicityViolation::UseAfterCommit {
reservation_id,
channel_id: state.channel_id,
commit_at: *at,
use_at: abort_time,
operation: "abort".to_string(),
trace_id: state.trace_id,
};
self.record_violation(violation);
}
}
}
}
/// Record a waker registration
pub fn on_waker_registered(
&mut self,
waker_id: WakerId,
channel_id: ChannelId,
trace_id: Option<TraceId>,
) {
if !self.config.track_wakers {
return;
}
let state = WakerState {
waker_id,
channel_id,
registered_at: SystemTime::now(),
expected_wakeup_at: None,
actual_wakeup_at: None,
trace_id,
};
self.wakers.insert(waker_id, state);
self.channel_wakers
.entry(channel_id)
.or_default()
.insert(waker_id);
self.stats.total_wakers_registered += 1;
}
/// Record an expected wakeup
pub fn on_waker_expected(&mut self, waker_id: WakerId, expected_at: SystemTime) {
if !self.config.track_wakers {
return;
}
if let Some(state) = self.wakers.get_mut(&waker_id) {
state.expected_wakeup_at = Some(expected_at);
self.stats.total_wakeups_expected += 1;
}
}
/// Record an actual wakeup
pub fn on_waker_wakeup(&mut self, waker_id: WakerId, actual_at: SystemTime) {
if !self.config.track_wakers {
return;
}
if let Some(state) = self.wakers.get_mut(&waker_id) {
state.actual_wakeup_at = Some(actual_at);
self.stats.total_wakeups_actual += 1;
// Check for lost wakeups (expected but significantly delayed)
if let Some(expected_at) = state.expected_wakeup_at {
if let Ok(delay) = actual_at.duration_since(expected_at) {
if delay.as_millis() > 100 {
// 100ms threshold for "lost" wakeup
let violation = ChannelAtomicityViolation::LostWakeup {
waker_id,
channel_id: state.channel_id,
expected_at,
detected_at: actual_at,
trace_id: state.trace_id,
};
self.record_violation(violation);
self.stats.total_lost_wakeups += 1;
}
}
} else {
// Spurious wakeup (actual without expected)
let violation = ChannelAtomicityViolation::SpuriousWakeup {
waker_id,
channel_id: state.channel_id,
wakeup_at: actual_at,
trace_id: state.trace_id,
};
self.record_violation(violation);
self.stats.total_spurious_wakeups += 1;
}
}
}
/// Record potential data loss during cancellation
pub fn on_cancel_data_loss(
&mut self,
channel_id: ChannelId,
data_size: usize,
trace_id: Option<TraceId>,
) {
let violation = ChannelAtomicityViolation::DataLossOnCancel {
channel_id,
data_size,
cancel_at: SystemTime::now(),
trace_id,
};
self.record_violation(violation);
}
/// Check for violations and return them
pub fn check_for_violations(&mut self) -> Result<Vec<ChannelAtomicityViolation>, String> {
self.check_for_reservation_leaks();
Ok(self.violations.clone())
}
/// Get current statistics
#[must_use]
pub fn statistics(&self) -> ChannelAtomicityStatistics {
self.stats.clone()
}
/// Reset the oracle state
pub fn reset(&mut self) {
self.reservations.clear();
self.channel_reservations.clear();
self.wakers.clear();
self.channel_wakers.clear();
self.violations.clear();
self.violation_records.clear();
self.stats = ChannelAtomicityStatistics::default();
}
/// Get violation records with diagnostics
#[must_use]
pub fn violation_records(&self) -> Vec<ViolationRecord> {
self.violation_records.iter().cloned().collect()
}
/// Record a violation with appropriate enforcement
fn record_violation(&mut self, violation: ChannelAtomicityViolation) {
// Legacy format for backward compatibility
self.violations.push(violation.clone());
// Enhanced format with diagnostics
let record = ViolationRecord::new(violation.clone(), &self.config);
// Emit structured log if enabled
if self.config.structured_logging {
record.emit_structured_log();
}
// Store the record
self.violation_records.push_back(record);
// Limit memory usage
if self.violation_records.len() > self.config.max_violations_tracked {
self.violation_records.pop_front();
}
self.stats.total_violations += 1;
// Apply enforcement mode
match self.config.enforcement {
EnforcementMode::Panic => panic!("Channel atomicity violation detected: {violation}"),
EnforcementMode::Warn => {
crate::tracing_compat::warn!(
violation = %violation,
"channel atomicity violation"
);
}
EnforcementMode::Collect => {} // Just collect, no immediate action
}
}
/// Check for reservation leaks
fn check_for_reservation_leaks(&mut self) {
let now = SystemTime::now();
let mut leaked_reservations = Vec::new();
let mut violations_to_record = Vec::new();
for (reservation_id, state) in &self.reservations {
if matches!(state.status, ReservationStatus::Active) {
if let Ok(age) = now.duration_since(state.created_at) {
// Use >= so that setting `max_reservation_age_seconds = 0`
// enables immediate leak detection (any positive age counts).
if age.as_secs() >= self.config.max_reservation_age_seconds {
leaked_reservations.push(*reservation_id);
let violation = ChannelAtomicityViolation::ReservationLeak {
reservation_id: *reservation_id,
channel_id: state.channel_id,
created_at: state.created_at,
trace_id: state.trace_id,
};
violations_to_record.push(violation);
}
}
}
}
// Record violations
for violation in violations_to_record {
self.record_violation(violation);
self.stats.total_reservations_leaked += 1;
}
// Remove leaked reservations from tracking
for reservation_id in leaked_reservations {
if let Some(state) = self.reservations.remove(&reservation_id) {
if let Some(channel_set) = self.channel_reservations.get_mut(&state.channel_id) {
channel_set.remove(&reservation_id);
}
}
}
}
/// Clean up old reservations to prevent memory leaks
fn cleanup_old_reservations(&mut self) {
// Clean up per-channel reservation tracking
for reservation_set in self.channel_reservations.values_mut() {
if reservation_set.len() > self.config.max_reservations_per_channel {
// Remove oldest reservations (this is a simplified cleanup)
let to_remove: Vec<ReservationId> = reservation_set
.iter()
.take(reservation_set.len() - self.config.max_reservations_per_channel)
.copied()
.collect();
for reservation_id in to_remove {
reservation_set.remove(&reservation_id);
self.reservations.remove(&reservation_id);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn test_reservation_lifecycle_happy_path() {
let mut oracle = ChannelAtomicityOracle::with_defaults();
let reservation_id = ReservationId(1);
let channel_id = ChannelId(1);
// Create reservation
oracle.on_reservation_created(reservation_id, channel_id, None);
// Commit reservation
oracle.on_reservation_committed(reservation_id, 100);
// Should have no violations
let violations = oracle.check_for_violations().unwrap();
assert!(violations.is_empty());
let stats = oracle.statistics();
assert_eq!(stats.total_reservations_created, 1);
assert_eq!(stats.total_reservations_committed, 1);
assert_eq!(stats.total_violations, 0);
}
#[test]
fn test_double_commit_detection() {
let mut oracle = ChannelAtomicityOracle::new(ChannelAtomicityConfig {
enforcement: EnforcementMode::Collect,
..Default::default()
});
let reservation_id = ReservationId(1);
let channel_id = ChannelId(1);
oracle.on_reservation_created(reservation_id, channel_id, None);
oracle.on_reservation_committed(reservation_id, 100);
oracle.on_reservation_committed(reservation_id, 200); // This should be a violation
let violations = oracle.check_for_violations().unwrap();
assert_eq!(violations.len(), 1);
assert!(matches!(
violations[0],
ChannelAtomicityViolation::DoubleCommit { .. }
));
}
#[test]
fn test_use_after_abort_detection() {
let mut oracle = ChannelAtomicityOracle::new(ChannelAtomicityConfig {
enforcement: EnforcementMode::Collect,
..Default::default()
});
let reservation_id = ReservationId(1);
let channel_id = ChannelId(1);
oracle.on_reservation_created(reservation_id, channel_id, None);
oracle.on_reservation_aborted(reservation_id, "cancelled".to_string());
oracle.on_reservation_committed(reservation_id, 100); // This should be a violation
let violations = oracle.check_for_violations().unwrap();
assert_eq!(violations.len(), 1);
assert!(matches!(
violations[0],
ChannelAtomicityViolation::UseAfterAbort { .. }
));
}
#[test]
fn test_reservation_leak_detection() {
let mut oracle = ChannelAtomicityOracle::new(ChannelAtomicityConfig {
enforcement: EnforcementMode::Collect,
max_reservation_age_seconds: 0, // Immediate leak detection
..Default::default()
});
let reservation_id = ReservationId(1);
let channel_id = ChannelId(1);
oracle.on_reservation_created(reservation_id, channel_id, None);
// Let some time pass
std::thread::sleep(Duration::from_millis(10));
let violations = oracle.check_for_violations().unwrap();
assert_eq!(violations.len(), 1);
assert!(matches!(
violations[0],
ChannelAtomicityViolation::ReservationLeak { .. }
));
}
#[test]
fn test_spurious_wakeup_detection() {
let mut oracle = ChannelAtomicityOracle::new(ChannelAtomicityConfig {
enforcement: EnforcementMode::Collect,
..Default::default()
});
let waker_id = WakerId(1);
let channel_id = ChannelId(1);
oracle.on_waker_registered(waker_id, channel_id, None);
oracle.on_waker_wakeup(waker_id, SystemTime::now()); // Wakeup without expectation
let violations = oracle.check_for_violations().unwrap();
assert_eq!(violations.len(), 1);
assert!(matches!(
violations[0],
ChannelAtomicityViolation::SpuriousWakeup { .. }
));
}
#[test]
fn test_lost_wakeup_detection() {
let mut oracle = ChannelAtomicityOracle::new(ChannelAtomicityConfig {
enforcement: EnforcementMode::Collect,
..Default::default()
});
let waker_id = WakerId(1);
let channel_id = ChannelId(1);
let now = SystemTime::now();
oracle.on_waker_registered(waker_id, channel_id, None);
oracle.on_waker_expected(waker_id, now);
// Simulate significant delay
let delayed_wakeup = now + Duration::from_millis(200);
oracle.on_waker_wakeup(waker_id, delayed_wakeup);
let violations = oracle.check_for_violations().unwrap();
assert_eq!(violations.len(), 1);
assert!(matches!(
violations[0],
ChannelAtomicityViolation::LostWakeup { .. }
));
}
#[test]
fn test_data_loss_on_cancel() {
let mut oracle = ChannelAtomicityOracle::new(ChannelAtomicityConfig {
enforcement: EnforcementMode::Collect,
..Default::default()
});
let channel_id = ChannelId(1);
oracle.on_cancel_data_loss(channel_id, 1024, None);
let violations = oracle.check_for_violations().unwrap();
assert_eq!(violations.len(), 1);
assert!(matches!(
violations[0],
ChannelAtomicityViolation::DataLossOnCancel { .. }
));
}
#[test]
fn test_violation_record_creation() {
let config = ChannelAtomicityConfig {
include_stack_traces: true,
enable_replay_commands: true,
structured_logging: false,
..Default::default()
};
let violation = ChannelAtomicityViolation::ReservationLeak {
reservation_id: ReservationId(1),
channel_id: ChannelId(1),
created_at: SystemTime::now(),
trace_id: Some(TraceId::new_for_test(1)),
};
let record = ViolationRecord::new(violation, &config);
assert!(record.trace_id.is_some());
assert!(record.stack_trace.is_some());
assert!(record.replay_command.is_some());
}
#[test]
fn test_oracle_reset() {
let mut oracle = ChannelAtomicityOracle::with_defaults();
// Add some state
oracle.on_reservation_created(ReservationId(1), ChannelId(1), None);
oracle.on_waker_registered(WakerId(1), ChannelId(1), None);
oracle.on_cancel_data_loss(ChannelId(1), 100, None);
// Verify state exists
assert!(!oracle.reservations.is_empty());
assert!(!oracle.wakers.is_empty());
assert!(!oracle.violations.is_empty());
// Reset and verify clean state
oracle.reset();
assert!(oracle.reservations.is_empty());
assert!(oracle.wakers.is_empty());
assert!(oracle.violations.is_empty());
assert_eq!(oracle.statistics().total_reservations_created, 0);
}
}