moonpool-sim 0.6.0

Simulation engine for the moonpool framework
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
//! Antithesis-style assertion macros and result tracking for simulation testing.
//!
//! This module provides 15 assertion macros for testing distributed system
//! properties. Assertions are tracked in shared memory via moonpool-explorer,
//! enabling cross-process tracking across forked exploration timelines.
//!
//! Following the Antithesis principle: **assertions never crash your program**.
//! Always-type assertions log violations at ERROR level and record them via a
//! thread-local flag, allowing the simulation to continue running and discover
//! cascading failures. The simulation runner checks `has_always_violations()`
//! after each iteration to report failures through the normal result pipeline.
//!
//! # Assertion Kinds
//!
//! | Macro | Tracks | Panics | Forks |
//! |-------|--------|--------|-------|
//! | `assert_always!` | yes | no | no |
//! | `assert_always_or_unreachable!` | yes | no | no |
//! | `assert_sometimes!` | yes | no | on first success |
//! | `assert_reachable!` | yes | no | on first reach |
//! | `assert_unreachable!` | yes | no | no |
//! | `assert_always_greater_than!` | yes | no | no |
//! | `assert_always_greater_than_or_equal_to!` | yes | no | no |
//! | `assert_always_less_than!` | yes | no | no |
//! | `assert_always_less_than_or_equal_to!` | yes | no | no |
//! | `assert_sometimes_greater_than!` | yes | no | on watermark improvement |
//! | `assert_sometimes_greater_than_or_equal_to!` | yes | no | on watermark improvement |
//! | `assert_sometimes_less_than!` | yes | no | on watermark improvement |
//! | `assert_sometimes_less_than_or_equal_to!` | yes | no | on watermark improvement |
//! | `assert_sometimes_all!` | yes | no | on frontier advance |
//! | `assert_sometimes_each!` | yes | no | on discovery/quality |

use std::cell::Cell;
use std::collections::HashMap;

// =============================================================================
// Thread-local violation tracking (Antithesis-style: never panic)
// =============================================================================

thread_local! {
    static ALWAYS_VIOLATION_COUNT: Cell<u64> = const { Cell::new(0) };
    /// When set, the next call to [`reset_assertion_results`] is skipped.
    /// Used by multi-seed exploration to prevent `SimWorld::create` from
    /// zeroing assertion state that [`moonpool_explorer::prepare_next_seed`]
    /// already selectively reset.
    static SKIP_NEXT_ASSERTION_RESET: Cell<bool> = const { Cell::new(false) };
}

/// Record that an always-type assertion was violated during this iteration.
///
/// Called by always-type macros instead of panicking. The simulation runner
/// checks `has_always_violations()` after each iteration to report failures.
pub fn record_always_violation() {
    ALWAYS_VIOLATION_COUNT.with(|c| c.set(c.get() + 1));
}

/// Reset the violation counter. Must be called at the start of each iteration.
pub fn reset_always_violations() {
    ALWAYS_VIOLATION_COUNT.with(|c| c.set(0));
}

/// Check whether any always-type assertion was violated during this iteration.
pub fn has_always_violations() -> bool {
    ALWAYS_VIOLATION_COUNT.with(|c| c.get() > 0)
}

/// Statistics for a tracked assertion.
///
/// Records the total number of times an assertion was checked and how many
/// times it succeeded, enabling calculation of success rates for probabilistic
/// properties in distributed systems.
#[derive(Debug, Clone, PartialEq)]
pub struct AssertionStats {
    /// Total number of times this assertion was evaluated
    pub total_checks: usize,
    /// Number of times the assertion condition was true
    pub successes: usize,
}

impl AssertionStats {
    /// Create new assertion statistics starting at zero.
    pub fn new() -> Self {
        Self {
            total_checks: 0,
            successes: 0,
        }
    }

    /// Calculate the success rate as a percentage (0.0 to 100.0).
    ///
    /// Returns 0.0 if no checks have been performed yet.
    pub fn success_rate(&self) -> f64 {
        if self.total_checks == 0 {
            0.0
        } else {
            (self.successes as f64 / self.total_checks as f64) * 100.0
        }
    }

    /// Record a new assertion check with the given result.
    ///
    /// Increments total_checks and successes (if the result was true).
    pub fn record(&mut self, success: bool) {
        self.total_checks += 1;
        if success {
            self.successes += 1;
        }
    }
}

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

// =============================================================================
// Details formatting (log-only, never stored in shared memory)
// =============================================================================

/// Format key-value details for assertion logging.
///
/// Used by assertion macros to produce human-readable context on failure.
/// Output format: `key1=val1, key2=val2, ...`
pub fn format_details(pairs: &[(&str, &dyn std::fmt::Display)]) -> String {
    pairs
        .iter()
        .map(|(k, v)| format!("{}={}", k, v))
        .collect::<Vec<_>>()
        .join(", ")
}

// =============================================================================
// Thin backing wrappers (for $crate:: macro hygiene)
// =============================================================================

/// Boolean assertion backing wrapper.
///
/// Delegates to `moonpool_explorer::assertion_bool`.
/// Accepts both `&str` and `String` message arguments.
pub fn on_assertion_bool(
    msg: impl AsRef<str>,
    condition: bool,
    kind: moonpool_explorer::AssertKind,
    must_hit: bool,
) {
    moonpool_explorer::assertion_bool(kind, must_hit, condition, msg.as_ref());
}

/// Numeric assertion backing wrapper.
///
/// Delegates to `moonpool_explorer::assertion_numeric`.
/// Accepts both `&str` and `String` message arguments.
pub fn on_assertion_numeric(
    msg: impl AsRef<str>,
    value: i64,
    cmp: moonpool_explorer::AssertCmp,
    threshold: i64,
    kind: moonpool_explorer::AssertKind,
    maximize: bool,
) {
    moonpool_explorer::assertion_numeric(kind, cmp, maximize, value, threshold, msg.as_ref());
}

/// Compound boolean assertion backing wrapper.
///
/// Delegates to `moonpool_explorer::assertion_sometimes_all`.
pub fn on_assertion_sometimes_all(msg: impl AsRef<str>, named_bools: &[(&str, bool)]) {
    moonpool_explorer::assertion_sometimes_all(msg.as_ref(), named_bools);
}

/// Notify the exploration framework of a per-value bucketed assertion.
///
/// This delegates to moonpool-explorer's EachBucket infrastructure for
/// fork-based exploration with identity keys and quality watermarks.
pub fn on_sometimes_each(msg: &str, keys: &[(&str, i64)], quality: &[(&str, i64)]) {
    moonpool_explorer::assertion_sometimes_each(msg, keys, quality);
}

// =============================================================================
// Shared-memory-based result collection
// =============================================================================

/// Get current assertion statistics for all tracked assertions.
///
/// Reads from shared memory assertion slots. Returns a snapshot of assertion
/// results for reporting and validation.
pub fn assertion_results() -> HashMap<String, AssertionStats> {
    let slots = moonpool_explorer::assertion_read_all();
    let mut results = HashMap::new();

    for slot in &slots {
        let total = slot.pass_count.saturating_add(slot.fail_count) as usize;
        if total == 0 {
            continue;
        }
        results.insert(
            slot.msg.clone(),
            AssertionStats {
                total_checks: total,
                successes: slot.pass_count as usize,
            },
        );
    }

    results
}

/// Request that the next call to [`reset_assertion_results`] be skipped.
///
/// Used by multi-seed exploration: [`moonpool_explorer::prepare_next_seed`]
/// does a selective reset (preserving explored map and watermarks), so the
/// full zero in `SimWorld::create` must be suppressed.
pub fn skip_next_assertion_reset() {
    SKIP_NEXT_ASSERTION_RESET.with(|c| c.set(true));
}

/// Reset all assertion statistics.
///
/// Zeros the shared memory assertion table unless a skip was requested via
/// [`skip_next_assertion_reset`]. Should be called before each simulation
/// run to ensure clean state between consecutive simulations.
pub fn reset_assertion_results() {
    let skip = SKIP_NEXT_ASSERTION_RESET.with(|c| {
        let v = c.get();
        c.set(false); // always consume the flag
        v
    });
    if !skip {
        moonpool_explorer::reset_assertions();
    }
}

/// Panic if the report contains assertion violations.
///
/// Uses the pre-collected `assertion_violations` from the report rather than
/// re-reading shared memory (which may already be freed by the time this is
/// called).
///
/// # Panics
///
/// Panics if `report.assertion_violations` is non-empty.
pub fn panic_on_assertion_violations(report: &crate::runner::SimulationReport) {
    if !report.assertion_violations.is_empty() {
        eprintln!("Assertion violations found:");
        for violation in &report.assertion_violations {
            eprintln!("  - {}", violation);
        }
        panic!("Unexpected assertion violations detected!");
    }
}

/// Validate all assertion contracts based on their kind.
///
/// Returns two vectors:
/// - **always_violations**: Definite bugs — always-type assertions that failed,
///   or unreachable code that was reached.  Safe to check with any iteration count.
/// - **coverage_violations**: Statistical — sometimes-type assertions that were
///   never satisfied, or reachable code that was never reached.  Only meaningful
///   with enough iterations for statistical coverage.
pub fn validate_assertion_contracts() -> (Vec<String>, Vec<String>) {
    let mut always_violations = Vec::new();
    let mut coverage_violations = Vec::new();
    let slots = moonpool_explorer::assertion_read_all();

    for slot in &slots {
        let total = slot.pass_count.saturating_add(slot.fail_count);
        let kind = moonpool_explorer::AssertKind::from_u8(slot.kind);

        match kind {
            Some(moonpool_explorer::AssertKind::Always) => {
                if slot.fail_count > 0 {
                    always_violations.push(format!(
                        "assert_always!('{}') failed {} times out of {}",
                        slot.msg, slot.fail_count, total
                    ));
                }
                if slot.must_hit != 0 && total == 0 {
                    always_violations
                        .push(format!("assert_always!('{}') was never reached", slot.msg));
                }
            }
            Some(moonpool_explorer::AssertKind::AlwaysOrUnreachable) => {
                if slot.fail_count > 0 {
                    always_violations.push(format!(
                        "assert_always_or_unreachable!('{}') failed {} times out of {}",
                        slot.msg, slot.fail_count, total
                    ));
                }
            }
            Some(moonpool_explorer::AssertKind::Sometimes) => {
                if total > 0 && slot.pass_count == 0 {
                    coverage_violations.push(format!(
                        "assert_sometimes!('{}') has 0% success rate ({} checks)",
                        slot.msg, total
                    ));
                }
            }
            Some(moonpool_explorer::AssertKind::Reachable) => {
                if slot.pass_count == 0 {
                    coverage_violations.push(format!(
                        "assert_reachable!('{}') was never reached",
                        slot.msg
                    ));
                }
            }
            Some(moonpool_explorer::AssertKind::Unreachable) => {
                if slot.pass_count > 0 {
                    always_violations.push(format!(
                        "assert_unreachable!('{}') was reached {} times",
                        slot.msg, slot.pass_count
                    ));
                }
            }
            Some(moonpool_explorer::AssertKind::NumericAlways) => {
                if slot.fail_count > 0 {
                    always_violations.push(format!(
                        "numeric assert_always ('{}') failed {} times out of {}",
                        slot.msg, slot.fail_count, total
                    ));
                }
            }
            Some(moonpool_explorer::AssertKind::NumericSometimes) => {
                if total > 0 && slot.pass_count == 0 {
                    coverage_violations.push(format!(
                        "numeric assert_sometimes ('{}') has 0% success rate ({} checks)",
                        slot.msg, total
                    ));
                }
            }
            Some(moonpool_explorer::AssertKind::BooleanSometimesAll) | None => {
                // BooleanSometimesAll: no simple pass/fail violation contract
                // (the frontier tracking is the guidance mechanism)
            }
        }
    }

    (always_violations, coverage_violations)
}

// =============================================================================
// Assertion Macros
// =============================================================================

/// Assert that a condition is always true.
///
/// Tracks pass/fail in shared memory for cross-process visibility.
/// Does **not** panic — records the violation via `record_always_violation()`
/// and logs at ERROR level with the seed, following the Antithesis principle
/// that assertions never crash the program.
#[macro_export]
macro_rules! assert_always {
    ($condition:expr, $message:expr) => {
        let __msg = $message;
        let cond = $condition;
        $crate::chaos::assertions::on_assertion_bool(
            &__msg,
            cond,
            $crate::chaos::assertions::_re_export::AssertKind::Always,
            true,
        );
        if !cond {
            $crate::chaos::assertions::record_always_violation();
        }
    };
    ($condition:expr, $message:expr, { $($key:expr => $val:expr),+ $(,)? }) => {
        let __msg = $message;
        let cond = $condition;
        $crate::chaos::assertions::on_assertion_bool(
            &__msg,
            cond,
            $crate::chaos::assertions::_re_export::AssertKind::Always,
            true,
        );
        if !cond {
            $crate::chaos::assertions::record_always_violation();
            eprintln!(
                "[ASSERTION FAILED] {} (seed={}) | {}",
                __msg,
                $crate::current_sim_seed(),
                $crate::chaos::assertions::format_details(
                    &[ $(($key, &$val as &dyn std::fmt::Display)),+ ]
                )
            );
        }
    };
}

/// Assert that a condition is always true when reached, but the code path
/// need not be reached. Does not panic if never evaluated.
///
/// Does **not** panic on failure — records the violation and logs at ERROR level.
#[macro_export]
macro_rules! assert_always_or_unreachable {
    ($condition:expr, $message:expr) => {
        let __msg = $message;
        let cond = $condition;
        $crate::chaos::assertions::on_assertion_bool(
            &__msg,
            cond,
            $crate::chaos::assertions::_re_export::AssertKind::AlwaysOrUnreachable,
            false,
        );
        if !cond {
            $crate::chaos::assertions::record_always_violation();
        }
    };
    ($condition:expr, $message:expr, { $($key:expr => $val:expr),+ $(,)? }) => {
        let __msg = $message;
        let cond = $condition;
        $crate::chaos::assertions::on_assertion_bool(
            &__msg,
            cond,
            $crate::chaos::assertions::_re_export::AssertKind::AlwaysOrUnreachable,
            false,
        );
        if !cond {
            $crate::chaos::assertions::record_always_violation();
            eprintln!(
                "[ASSERTION FAILED] {} (seed={}) | {}",
                __msg,
                $crate::current_sim_seed(),
                $crate::chaos::assertions::format_details(
                    &[ $(($key, &$val as &dyn std::fmt::Display)),+ ]
                )
            );
        }
    };
}

/// Assert a condition that should sometimes be true, tracking stats and triggering exploration.
///
/// Does not panic. On first success, triggers a fork to explore alternate timelines.
#[macro_export]
macro_rules! assert_sometimes {
    ($condition:expr, $message:expr) => {
        $crate::chaos::assertions::on_assertion_bool(
            &$message,
            $condition,
            $crate::chaos::assertions::_re_export::AssertKind::Sometimes,
            true,
        );
    };
}

/// Assert that a code path is reachable (should be reached at least once).
///
/// Does not panic. On first reach, triggers a fork.
#[macro_export]
macro_rules! assert_reachable {
    ($message:expr) => {
        $crate::chaos::assertions::on_assertion_bool(
            &$message,
            true,
            $crate::chaos::assertions::_re_export::AssertKind::Reachable,
            true,
        );
    };
}

/// Assert that a code path should never be reached.
///
/// Does **not** panic — records the violation and logs at ERROR level.
/// Tracks in shared memory for reporting.
#[macro_export]
macro_rules! assert_unreachable {
    ($message:expr) => {
        let __msg = $message;
        $crate::chaos::assertions::on_assertion_bool(
            &__msg,
            true,
            $crate::chaos::assertions::_re_export::AssertKind::Unreachable,
            false,
        );
        $crate::chaos::assertions::record_always_violation();
    };
    ($message:expr, { $($key:expr => $val:expr),+ $(,)? }) => {
        let __msg = $message;
        $crate::chaos::assertions::on_assertion_bool(
            &__msg,
            true,
            $crate::chaos::assertions::_re_export::AssertKind::Unreachable,
            false,
        );
        $crate::chaos::assertions::record_always_violation();
        eprintln!(
            "[ASSERTION FAILED] {} | {}",
            __msg,
            $crate::chaos::assertions::format_details(
                &[ $(($key, &$val as &dyn std::fmt::Display)),+ ]
            )
        );
    };
}

/// Assert that `val > threshold` always holds.
///
/// Does **not** panic on failure — records the violation and logs at ERROR level.
#[macro_export]
macro_rules! assert_always_greater_than {
    ($val:expr, $thresh:expr, $message:expr) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Gt,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            false,
        );
        if !(__v > __t) {
            $crate::chaos::assertions::record_always_violation();
        }
    };
    ($val:expr, $thresh:expr, $message:expr, { $($key:expr => $dval:expr),+ $(,)? }) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Gt,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            false,
        );
        if !(__v > __t) {
            $crate::chaos::assertions::record_always_violation();
            eprintln!(
                "[ASSERTION FAILED] {} ({}>{} failed, seed={}) | {}",
                __msg, __v, __t,
                $crate::current_sim_seed(),
                $crate::chaos::assertions::format_details(
                    &[ $(($key, &$dval as &dyn std::fmt::Display)),+ ]
                )
            );
        }
    };
}

/// Assert that `val >= threshold` always holds.
///
/// Does **not** panic on failure — records the violation and logs at ERROR level.
#[macro_export]
macro_rules! assert_always_greater_than_or_equal_to {
    ($val:expr, $thresh:expr, $message:expr) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Ge,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            false,
        );
        if !(__v >= __t) {
            $crate::chaos::assertions::record_always_violation();
        }
    };
    ($val:expr, $thresh:expr, $message:expr, { $($key:expr => $dval:expr),+ $(,)? }) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Ge,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            false,
        );
        if !(__v >= __t) {
            $crate::chaos::assertions::record_always_violation();
            eprintln!(
                "[ASSERTION FAILED] {} ({}>={} failed, seed={}) | {}",
                __msg, __v, __t,
                $crate::current_sim_seed(),
                $crate::chaos::assertions::format_details(
                    &[ $(($key, &$dval as &dyn std::fmt::Display)),+ ]
                )
            );
        }
    };
}

/// Assert that `val < threshold` always holds.
///
/// Does **not** panic on failure — records the violation and logs at ERROR level.
#[macro_export]
macro_rules! assert_always_less_than {
    ($val:expr, $thresh:expr, $message:expr) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Lt,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            true,
        );
        if !(__v < __t) {
            $crate::chaos::assertions::record_always_violation();
        }
    };
    ($val:expr, $thresh:expr, $message:expr, { $($key:expr => $dval:expr),+ $(,)? }) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Lt,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            true,
        );
        if !(__v < __t) {
            $crate::chaos::assertions::record_always_violation();
            eprintln!(
                "[ASSERTION FAILED] {} ({}<{} failed, seed={}) | {}",
                __msg, __v, __t,
                $crate::current_sim_seed(),
                $crate::chaos::assertions::format_details(
                    &[ $(($key, &$dval as &dyn std::fmt::Display)),+ ]
                )
            );
        }
    };
}

/// Assert that `val <= threshold` always holds.
///
/// Does **not** panic on failure — records the violation and logs at ERROR level.
#[macro_export]
macro_rules! assert_always_less_than_or_equal_to {
    ($val:expr, $thresh:expr, $message:expr) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Le,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            true,
        );
        if !(__v <= __t) {
            $crate::chaos::assertions::record_always_violation();
        }
    };
    ($val:expr, $thresh:expr, $message:expr, { $($key:expr => $dval:expr),+ $(,)? }) => {
        let __msg = $message;
        let __v = $val as i64;
        let __t = $thresh as i64;
        $crate::chaos::assertions::on_assertion_numeric(
            &__msg,
            __v,
            $crate::chaos::assertions::_re_export::AssertCmp::Le,
            __t,
            $crate::chaos::assertions::_re_export::AssertKind::NumericAlways,
            true,
        );
        if !(__v <= __t) {
            $crate::chaos::assertions::record_always_violation();
            eprintln!(
                "[ASSERTION FAILED] {} ({}<={} failed, seed={}) | {}",
                __msg, __v, __t,
                $crate::current_sim_seed(),
                $crate::chaos::assertions::format_details(
                    &[ $(($key, &$dval as &dyn std::fmt::Display)),+ ]
                )
            );
        }
    };
}

/// Assert that `val > threshold` sometimes holds. Forks on watermark improvement.
#[macro_export]
macro_rules! assert_sometimes_greater_than {
    ($val:expr, $thresh:expr, $message:expr) => {
        $crate::chaos::assertions::on_assertion_numeric(
            &$message,
            $val as i64,
            $crate::chaos::assertions::_re_export::AssertCmp::Gt,
            $thresh as i64,
            $crate::chaos::assertions::_re_export::AssertKind::NumericSometimes,
            true,
        );
    };
}

/// Assert that `val >= threshold` sometimes holds. Forks on watermark improvement.
#[macro_export]
macro_rules! assert_sometimes_greater_than_or_equal_to {
    ($val:expr, $thresh:expr, $message:expr) => {
        $crate::chaos::assertions::on_assertion_numeric(
            &$message,
            $val as i64,
            $crate::chaos::assertions::_re_export::AssertCmp::Ge,
            $thresh as i64,
            $crate::chaos::assertions::_re_export::AssertKind::NumericSometimes,
            true,
        );
    };
}

/// Assert that `val < threshold` sometimes holds. Forks on watermark improvement.
#[macro_export]
macro_rules! assert_sometimes_less_than {
    ($val:expr, $thresh:expr, $message:expr) => {
        $crate::chaos::assertions::on_assertion_numeric(
            &$message,
            $val as i64,
            $crate::chaos::assertions::_re_export::AssertCmp::Lt,
            $thresh as i64,
            $crate::chaos::assertions::_re_export::AssertKind::NumericSometimes,
            false,
        );
    };
}

/// Assert that `val <= threshold` sometimes holds. Forks on watermark improvement.
#[macro_export]
macro_rules! assert_sometimes_less_than_or_equal_to {
    ($val:expr, $thresh:expr, $message:expr) => {
        $crate::chaos::assertions::on_assertion_numeric(
            &$message,
            $val as i64,
            $crate::chaos::assertions::_re_export::AssertCmp::Le,
            $thresh as i64,
            $crate::chaos::assertions::_re_export::AssertKind::NumericSometimes,
            false,
        );
    };
}

/// Compound boolean assertion: all named bools should sometimes be true simultaneously.
///
/// Tracks a frontier (max number of simultaneously true bools). Forks when
/// the frontier advances.
///
/// # Usage
///
/// ```ignore
/// assert_sometimes_all!("all_nodes_healthy", [
///     ("node_a", node_a_healthy),
///     ("node_b", node_b_healthy),
///     ("node_c", node_c_healthy),
/// ]);
/// ```
#[macro_export]
macro_rules! assert_sometimes_all {
    ($msg:expr, [ $(($name:expr, $val:expr)),+ $(,)? ]) => {
        $crate::chaos::assertions::on_assertion_sometimes_all($msg, &[ $(($name, $val)),+ ])
    };
}

/// Per-value bucketed sometimes assertion with optional quality watermarks.
///
/// Each unique combination of identity keys gets its own bucket. On first
/// discovery of a new bucket, a fork is triggered for exploration. If quality
/// keys are provided, re-forks when quality improves.
///
/// # Usage
///
/// ```ignore
/// // Identity keys only
/// assert_sometimes_each!("gate", [("lock", lock_id), ("depth", depth)]);
///
/// // With quality watermarks
/// assert_sometimes_each!("descended", [("to_floor", floor)], [("health", hp)]);
/// ```
#[macro_export]
macro_rules! assert_sometimes_each {
    ($msg:expr, [ $(($name:expr, $val:expr)),+ $(,)? ]) => {
        $crate::chaos::assertions::on_sometimes_each($msg, &[ $(($name, $val as i64)),+ ], &[])
    };
    ($msg:expr, [ $(($name:expr, $val:expr)),+ $(,)? ], [ $(($qname:expr, $qval:expr)),+ $(,)? ]) => {
        $crate::chaos::assertions::on_sometimes_each(
            $msg,
            &[ $(($name, $val as i64)),+ ],
            &[ $(($qname, $qval as i64)),+ ],
        )
    };
}

/// Re-exports for macro hygiene (`$crate::chaos::assertions::_re_export::*`).
pub mod _re_export {
    pub use moonpool_explorer::{AssertCmp, AssertKind};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_assertion_stats_new() {
        let stats = AssertionStats::new();
        assert_eq!(stats.total_checks, 0);
        assert_eq!(stats.successes, 0);
        assert_eq!(stats.success_rate(), 0.0);
    }

    #[test]
    fn test_assertion_stats_record() {
        let mut stats = AssertionStats::new();

        stats.record(true);
        assert_eq!(stats.total_checks, 1);
        assert_eq!(stats.successes, 1);
        assert_eq!(stats.success_rate(), 100.0);

        stats.record(false);
        assert_eq!(stats.total_checks, 2);
        assert_eq!(stats.successes, 1);
        assert_eq!(stats.success_rate(), 50.0);

        stats.record(true);
        assert_eq!(stats.total_checks, 3);
        assert_eq!(stats.successes, 2);
        let expected = 200.0 / 3.0;
        assert!((stats.success_rate() - expected).abs() < 1e-10);
    }

    #[test]
    fn test_assertion_stats_success_rate_edge_cases() {
        let mut stats = AssertionStats::new();
        assert_eq!(stats.success_rate(), 0.0);

        stats.record(false);
        assert_eq!(stats.success_rate(), 0.0);

        stats.record(true);
        assert_eq!(stats.success_rate(), 50.0);
    }

    #[test]
    fn test_assertion_results_empty() {
        // When no assertions have been tracked, results should be empty
        // (assertion table not initialized = empty)
        let results = assertion_results();
        // May or may not be empty depending on prior test state,
        // but should not panic
        let _ = results;
    }

    #[test]
    fn test_validate_contracts_empty() {
        // Should produce no violations when no assertions tracked
        let violations = validate_assertion_contracts();
        // May or may not be empty, but should not panic
        let _ = violations;
    }
}