KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
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
//! Optional structured diagnostics for canonical equilibrium workflows.
//!
//! The nonlinear and phase-control layers emit typed facts, not formatted
//! strings or direct `log` calls.  A caller may retain the immutable report,
//! attach a live sink for a CLI or GUI, or render it afterwards.  Diagnostics
//! are disabled by default so ordinary solves do not allocate event payloads.

use std::fmt;
use std::sync::Arc;

use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::ReactionExtentErrorKind;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::EquilibriumConditions;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_validation::EquilibriumCandidateReport;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::{
    PhaseSet, PhaseTransitionReason,
};

/// Requested amount of diagnostic evidence for one equilibrium transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EquilibriumDiagnosticsMode {
    /// Emit and retain no diagnostic events.
    #[default]
    Disabled,
    /// Retain transaction boundaries and the final decision only.
    Summary,
    /// Include the phase-control lifecycle, TPD evaluations, and transitions.
    PhaseLifecycle,
    /// Include accepted fixed-set candidates and recovery probes as well.
    Detailed,
}

impl EquilibriumDiagnosticsMode {
    pub(crate) fn captures_lifecycle(self) -> bool {
        matches!(self, Self::PhaseLifecycle | Self::Detailed)
    }
}

/// Selects which points of a temperature range emit diagnostic events.
///
/// Point-level diagnostics can be verbose even when each individual trace is
/// bounded. The default records only the two endpoints; callers must opt in
/// explicitly before streaming every point to a live sink.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EquilibriumRangeDiagnosticsPolicy {
    /// Retain and stream a point trace only after that accepted point changed
    /// the active phase set. The range workflow defers its live sink until it
    /// knows whether a transition occurred.
    TransitionsOnly,
    /// Keep diagnostics for the first and last point only.
    #[default]
    Endpoints,
    /// Keep diagnostics for point zero and every `stride`-th point.
    EveryNth { stride: usize },
    /// Keep diagnostics for every solved point.
    EveryPoint,
}

/// Controls bounded structured diagnostic collection.
///
/// `max_events` applies only to the immutable report. A live sink still sees
/// events after the retained report reaches its limit, which lets a caller
/// stream a long temperature range without retaining an unbounded trace.
#[derive(Clone)]
pub struct EquilibriumDiagnosticsOptions {
    mode: EquilibriumDiagnosticsMode,
    max_events: usize,
    range_policy: EquilibriumRangeDiagnosticsPolicy,
    sink: Option<EquilibriumDiagnosticSink>,
    defer_live_sink: bool,
}

impl fmt::Debug for EquilibriumDiagnosticsOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EquilibriumDiagnosticsOptions")
            .field("mode", &self.mode)
            .field("max_events", &self.max_events)
            .field("range_policy", &self.range_policy)
            .field("has_sink", &self.sink.is_some())
            .field("defer_live_sink", &self.defer_live_sink)
            .finish()
    }
}

impl Default for EquilibriumDiagnosticsOptions {
    fn default() -> Self {
        Self {
            mode: EquilibriumDiagnosticsMode::Disabled,
            max_events: 256,
            range_policy: EquilibriumRangeDiagnosticsPolicy::default(),
            sink: None,
            defer_live_sink: false,
        }
    }
}

impl EquilibriumDiagnosticsOptions {
    /// Starts with diagnostics disabled.
    pub fn disabled() -> Self {
        Self::default()
    }

    /// Enables one diagnostic detail level with a bounded in-result trace.
    pub fn enabled(mode: EquilibriumDiagnosticsMode) -> Self {
        Self {
            mode,
            ..Self::default()
        }
    }

    /// Selects the retained diagnostic detail level.
    pub fn with_mode(mut self, mode: EquilibriumDiagnosticsMode) -> Self {
        self.mode = mode;
        self
    }

    /// Limits event retention in the immutable result report.
    pub fn with_max_events(mut self, max_events: usize) -> Self {
        self.max_events = max_events;
        self
    }

    /// Controls which points in a temperature range emit diagnostics.
    pub fn with_range_policy(mut self, policy: EquilibriumRangeDiagnosticsPolicy) -> Self {
        self.range_policy = policy;
        self
    }

    /// Receives events as they are produced by the canonical workflow.
    ///
    /// The sink is observational: it must not mutate solver state or depend
    /// on a partially published numerical result.
    pub fn with_sink<F>(mut self, sink: F) -> Self
    where
        F: Fn(EquilibriumDiagnosticEvent) + Send + Sync + 'static,
    {
        self.sink = Some(Arc::new(sink));
        self
    }

    pub fn mode(&self) -> EquilibriumDiagnosticsMode {
        self.mode
    }

    pub fn max_events(&self) -> usize {
        self.max_events
    }

    pub fn range_policy(&self) -> EquilibriumRangeDiagnosticsPolicy {
        self.range_policy
    }

    pub fn has_sink(&self) -> bool {
        self.sink.is_some()
    }

    /// Derives the policy for one zero-based point in a finite range.
    ///
    /// Disabled points suppress the live sink too, rather than merely dropping
    /// report entries after verbose logging has already happened.
    pub(crate) fn for_range_point(&self, index: usize, point_count: usize) -> Self {
        if self.mode == EquilibriumDiagnosticsMode::Disabled {
            return self.clone();
        }
        let selected = match self.range_policy {
            EquilibriumRangeDiagnosticsPolicy::TransitionsOnly => {
                let mut deferred = self.clone();
                deferred.defer_live_sink = true;
                return deferred;
            }
            EquilibriumRangeDiagnosticsPolicy::Endpoints => {
                index == 0 || index.saturating_add(1) == point_count
            }
            EquilibriumRangeDiagnosticsPolicy::EveryNth { stride } => {
                stride > 0 && (index == 0 || index % stride == 0)
            }
            EquilibriumRangeDiagnosticsPolicy::EveryPoint => true,
        };
        if selected {
            self.clone()
        } else {
            Self::disabled()
        }
    }

    /// Streams a workflow-level observation that has no accepted solution to
    /// carry an immutable report yet, such as an `Auto` P,H route fallback.
    pub(crate) fn emit(
        &self,
        minimum: EquilibriumDiagnosticsMode,
        event: EquilibriumDiagnosticEvent,
    ) {
        if self.mode == EquilibriumDiagnosticsMode::Disabled || !mode_includes(self.mode, minimum) {
            return;
        }
        if !self.defer_live_sink {
            if let Some(sink) = &self.sink {
                sink(event);
            }
        }
    }

    /// Replays one retained accepted-point report after a range workflow
    /// confirms that the point satisfies its deferred publication rule.
    pub(crate) fn replay_retained_events(&self, report: &EquilibriumDiagnosticsReport) {
        if self.mode == EquilibriumDiagnosticsMode::Disabled || !self.defer_live_sink {
            return;
        }
        if let Some(sink) = &self.sink {
            for event in report.events() {
                sink(event.clone());
            }
        }
    }
}

/// Live observer for one diagnostic event.
pub type EquilibriumDiagnosticSink = Arc<dyn Fn(EquilibriumDiagnosticEvent) + Send + Sync>;

/// Compact TPD evidence for one declared phase.
#[derive(Debug, Clone, PartialEq)]
pub struct PhaseStabilityDiagnostic {
    /// Dense phase index in canonical phase order.
    pub phase_index: usize,
    /// Whether the phase is active in the accepted solution.
    pub active: bool,
    /// Total mole amount of the phase at the accepted state.
    pub phase_total_moles: f64,
    /// Minimum tangent-plane-distance per mol, when evaluated.
    pub minimum_tpd_j_per_mol: Option<f64>,
    /// Incipient composition (mole fractions) of the TPD minimizer, when run.
    pub incipient_composition: Option<Vec<f64>>,
}

/// Chronological fact emitted by the canonical phase-control workflow.
#[derive(Debug, Clone, PartialEq)]
pub enum EquilibriumDiagnosticEvent {
    /// A solve transaction began with validated physical conditions.
    SolveStarted {
        /// Thermodynamic conditions of the accepted problem.
        conditions: EquilibriumConditions,
        /// Initial active-phase policy/status set.
        initial_phase_set: PhaseSet,
    },
    /// A bounded outer-loop iteration started for one active phase set.
    OuterIterationStarted {
        /// Zero-based outer-loop iteration number.
        iteration: usize,
        /// Active phase set being solved in this iteration.
        active_phase_set: PhaseSet,
    },
    /// A fixed active-set candidate passed the acceptance gate.
    ActiveSetCandidateAccepted {
        /// Zero-based outer-loop iteration number.
        iteration: usize,
        /// Active phase set whose candidate was accepted.
        active_phase_set: PhaseSet,
        /// Backend-independent acceptance evidence.
        validation: EquilibriumCandidateReport,
        /// Concise human-readable summary of the backend cascade.
        backend_summary: String,
    },
    /// A fixed active-set solve was rejected before it could contribute
    /// stability evidence. The lifecycle may still attempt a boundary
    /// recovery with a smaller active set.
    ActiveSetCandidateRejected {
        iteration: usize,
        active_phase_set: PhaseSet,
        message: String,
    },
    /// Stability (tangent-plane) evidence was evaluated for all phases.
    StabilityEvaluated {
        /// Zero-based outer-loop iteration number.
        iteration: usize,
        /// Hysteresis creation threshold in J/mol.
        dg_create_j_per_mol: f64,
        /// Hysteresis keep threshold in J/mol.
        dg_keep_j_per_mol: f64,
        /// Per-phase stability diagnostics in canonical phase order.
        phases: Vec<PhaseStabilityDiagnostic>,
    },
    /// The outer loop committed a phase transition.
    TransitionAccepted {
        /// Zero-based outer-loop iteration number.
        iteration: usize,
        /// Dense indices of phases activated by this transition.
        activated_phase_indices: Vec<usize>,
        /// Dense indices of phases deactivated by this transition.
        deactivated_phase_indices: Vec<usize>,
        /// Typed reason for accepting the transition.
        reason: PhaseTransitionReason,
        /// Phase set before the transition.
        previous_phase_set: PhaseSet,
        /// Phase set after the transition.
        new_phase_set: PhaseSet,
        /// Optional TPD-derived composition used to seed a new phase.
        incipient_composition: Option<Vec<f64>>,
    },
    /// A proposed activation was rejected by the hysteresis dead zone.
    TransitionHeldByHysteresis {
        /// Zero-based outer-loop iteration number.
        iteration: usize,
        /// Dense index of the phase whose activation was held.
        phase_index: usize,
    },
    /// A boundary-recovery probe with a smaller active set was accepted.
    RecoveryProbeAccepted {
        /// Zero-based outer-loop iteration number.
        iteration: usize,
        /// Dense index of the phase removed by the recovery probe.
        phase_index: usize,
        /// Phase set before the recovery probe.
        previous_phase_set: PhaseSet,
        /// Reduced phase set established by the accepted probe.
        new_phase_set: PhaseSet,
    },
    /// A boundary recovery is trying a smaller active phase set after the
    /// primary fixed-set solve failed.
    RecoveryProbeStarted {
        iteration: usize,
        removed_phase_index: usize,
        attempted_phase_set: PhaseSet,
    },
    /// A boundary recovery probe did not establish a valid physical boundary.
    RecoveryProbeRejected {
        iteration: usize,
        removed_phase_index: usize,
        message: String,
    },
    /// A failed transaction restored the last accepted continuation state.
    ContinuationRestored {
        retained_phase_set: Option<PhaseSet>,
        retained_seed: bool,
    },
    /// The bounded outer loop exhausted its transition budget.
    PhaseControlBudgetExhausted { max_outer_iterations: usize },
    /// A proposed transition revisited a settled active phase set, so the
    /// outer loop stopped rather than oscillating indefinitely.
    PhaseControlCycleDetected {
        iteration: usize,
        repeated_phase_set: PhaseSet,
    },
    /// `Auto` P,H abandoned its coupled formulation after a classified error
    /// and began the independent nested-temperature route.
    PhRouteFallback {
        from_route: PhDiagnosticRoute,
        to_route: PhDiagnosticRoute,
        error_kind: ReactionExtentErrorKind,
        message: String,
    },
    /// A P,H route ended before it could publish an accepted solution.
    PhRouteFailed {
        route: PhDiagnosticRoute,
        error_kind: ReactionExtentErrorKind,
        message: String,
    },
    /// Exact extensive normalization produced the accepted public physical
    /// result after the original physical-coordinate solve failed.
    ExtensiveNormalizationRecoveryAccepted {
        /// Sum of positive physical input component moles used as the scale.
        physical_inventory_scale: f64,
        /// Physical failure kind, absent for proactive small-scale P,H use.
        trigger_kind: Option<ReactionExtentErrorKind>,
        /// Human-readable failure or preconditioning reason.
        trigger_reason: String,
        /// Backend that accepted the normalized equivalent problem.
        discovery_backend: String,
        /// Backend that accepted the optional physical retry.
        physical_retry_backend: Option<String>,
        /// Whether public fields were reconstructed through the audited
        /// physical publication boundary.
        reconstructed_physical_boundary: bool,
    },
    /// The transaction ended without publishing a new accepted solution.
    ///
    /// This event is mainly useful to a live sink because failed transactions
    /// intentionally do not return an immutable solution report.
    SolveFailed {
        message: String,
        continuation_restored: bool,
    },
    /// The transaction ended by publishing an accepted solution.
    SolveAccepted {
        /// Final settled active phase set.
        final_phase_set: PhaseSet,
        /// Total outer-loop iterations used by the solve.
        outer_iterations: usize,
        /// Total accepted phase transitions during the solve.
        transition_count: usize,
    },
}

/// Coarse P,H route identity used in diagnostics without exposing workflow
/// implementation types to the generic phase-control trace.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhDiagnosticRoute {
    Monolithic,
    NestedTemperature,
}

/// Immutable bounded diagnostic evidence attached to an accepted result.
#[derive(Debug, Clone, PartialEq)]
pub struct EquilibriumDiagnosticsReport {
    mode: EquilibriumDiagnosticsMode,
    events: Vec<EquilibriumDiagnosticEvent>,
    dropped_events: usize,
}

impl EquilibriumDiagnosticsReport {
    pub fn mode(&self) -> EquilibriumDiagnosticsMode {
        self.mode
    }

    pub fn enabled(&self) -> bool {
        self.mode != EquilibriumDiagnosticsMode::Disabled
    }

    pub fn events(&self) -> &[EquilibriumDiagnosticEvent] {
        &self.events
    }

    pub fn dropped_events(&self) -> usize {
        self.dropped_events
    }
}

/// Mutable collector kept inside one phase-control transaction.
#[derive(Debug, Clone)]
pub(crate) struct EquilibriumDiagnosticsCollector {
    options: EquilibriumDiagnosticsOptions,
    events: Vec<EquilibriumDiagnosticEvent>,
    dropped_events: usize,
}

impl EquilibriumDiagnosticsCollector {
    pub(crate) fn new(options: EquilibriumDiagnosticsOptions) -> Self {
        Self {
            options,
            events: Vec::new(),
            dropped_events: 0,
        }
    }

    /// Continues one retained report with a workflow-level decision known only
    /// after the inner phase-control transaction has completed.
    pub(crate) fn from_report(
        options: EquilibriumDiagnosticsOptions,
        report: &EquilibriumDiagnosticsReport,
    ) -> Self {
        Self {
            options,
            events: report.events.clone(),
            dropped_events: report.dropped_events,
        }
    }

    pub(crate) fn set_options(&mut self, options: EquilibriumDiagnosticsOptions) {
        self.options = options;
        self.events.clear();
        self.dropped_events = 0;
    }

    pub(crate) fn mode(&self) -> EquilibriumDiagnosticsMode {
        self.options.mode
    }

    pub(crate) fn record(
        &mut self,
        minimum: EquilibriumDiagnosticsMode,
        event: EquilibriumDiagnosticEvent,
    ) {
        if self.options.mode == EquilibriumDiagnosticsMode::Disabled
            || !mode_includes(self.options.mode, minimum)
        {
            return;
        }
        self.options.emit(minimum, event.clone());
        if self.events.len() < self.options.max_events {
            self.events.push(event);
        } else {
            self.dropped_events += 1;
        }
    }

    pub(crate) fn finish(&self) -> EquilibriumDiagnosticsReport {
        EquilibriumDiagnosticsReport {
            mode: self.options.mode,
            events: self.events.clone(),
            dropped_events: self.dropped_events,
        }
    }
}

/// Tests whether one diagnostics mode is at least as detailed as another.
///
/// The modes form a strict ladder `Disabled < Summary < PhaseLifecycle <
/// Detailed`. A mode "includes" a required level when its rank is greater than
/// or equal to the required rank, so `PhaseLifecycle` captures summary events
/// and `Detailed` captures everything.
fn mode_includes(mode: EquilibriumDiagnosticsMode, required: EquilibriumDiagnosticsMode) -> bool {
    fn rank(mode: EquilibriumDiagnosticsMode) -> u8 {
        match mode {
            EquilibriumDiagnosticsMode::Disabled => 0,
            EquilibriumDiagnosticsMode::Summary => 1,
            EquilibriumDiagnosticsMode::PhaseLifecycle => 2,
            EquilibriumDiagnosticsMode::Detailed => 3,
        }
    }
    rank(mode) >= rank(required)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::InitialPhaseSet;
    use std::sync::mpsc;

    #[test]
    fn disabled_collector_keeps_no_events() {
        let mut collector =
            EquilibriumDiagnosticsCollector::new(EquilibriumDiagnosticsOptions::disabled());
        collector.record(
            EquilibriumDiagnosticsMode::Summary,
            EquilibriumDiagnosticEvent::SolveAccepted {
                final_phase_set: PhaseSet::from_policy(
                    &InitialPhaseSet::AllCandidatePhases,
                    &[true],
                )
                .unwrap(),
                outer_iterations: 1,
                transition_count: 0,
            },
        );
        assert!(!collector.finish().enabled());
        assert!(collector.finish().events().is_empty());
    }

    #[test]
    fn bounded_report_drops_only_retained_events() {
        let mut collector = EquilibriumDiagnosticsCollector::new(
            EquilibriumDiagnosticsOptions::enabled(EquilibriumDiagnosticsMode::Summary)
                .with_max_events(1),
        );
        let phase_set =
            PhaseSet::from_policy(&InitialPhaseSet::AllCandidatePhases, &[true]).unwrap();
        for _ in 0..2 {
            collector.record(
                EquilibriumDiagnosticsMode::Summary,
                EquilibriumDiagnosticEvent::SolveAccepted {
                    final_phase_set: phase_set.clone(),
                    outer_iterations: 1,
                    transition_count: 0,
                },
            );
        }
        let report = collector.finish();
        assert_eq!(report.events().len(), 1);
        assert_eq!(report.dropped_events(), 1);
    }

    #[test]
    fn workflow_level_recovery_event_extends_an_existing_report() {
        let options = EquilibriumDiagnosticsOptions::enabled(EquilibriumDiagnosticsMode::Summary)
            .with_max_events(2);
        let phase_set =
            PhaseSet::from_policy(&InitialPhaseSet::AllCandidatePhases, &[true]).unwrap();
        let mut initial = EquilibriumDiagnosticsCollector::new(options.clone());
        initial.record(
            EquilibriumDiagnosticsMode::Summary,
            EquilibriumDiagnosticEvent::SolveAccepted {
                final_phase_set: phase_set,
                outer_iterations: 1,
                transition_count: 0,
            },
        );

        let mut extended = EquilibriumDiagnosticsCollector::from_report(options, &initial.finish());
        extended.record(
            EquilibriumDiagnosticsMode::Summary,
            EquilibriumDiagnosticEvent::ExtensiveNormalizationRecoveryAccepted {
                physical_inventory_scale: 1.0e4,
                trigger_kind: Some(ReactionExtentErrorKind::AllBackendsFailed),
                trigger_reason: "all physical backends failed".into(),
                discovery_backend: "Native(LM)".to_string(),
                physical_retry_backend: None,
                reconstructed_physical_boundary: true,
            },
        );
        let report = extended.finish();
        assert_eq!(report.events().len(), 2);
        assert!(matches!(
            report.events().last(),
            Some(
                EquilibriumDiagnosticEvent::ExtensiveNormalizationRecoveryAccepted {
                    reconstructed_physical_boundary: true,
                    ..
                }
            )
        ));
    }

    #[test]
    fn enabled_sink_receives_events_even_when_retention_is_disabled() {
        let (sender, receiver) = mpsc::channel();
        let options = EquilibriumDiagnosticsOptions::enabled(EquilibriumDiagnosticsMode::Summary)
            .with_max_events(0)
            .with_sink(move |event| sender.send(event).unwrap());
        let mut collector = EquilibriumDiagnosticsCollector::new(options);
        let phase_set =
            PhaseSet::from_policy(&InitialPhaseSet::AllCandidatePhases, &[true]).unwrap();
        collector.record(
            EquilibriumDiagnosticsMode::Summary,
            EquilibriumDiagnosticEvent::SolveAccepted {
                final_phase_set: phase_set,
                outer_iterations: 1,
                transition_count: 0,
            },
        );
        assert!(matches!(
            receiver.recv().unwrap(),
            EquilibriumDiagnosticEvent::SolveAccepted { .. }
        ));
        assert!(collector.finish().events().is_empty());
    }

    #[test]
    fn endpoint_range_policy_suppresses_middle_point_diagnostics() {
        let options = EquilibriumDiagnosticsOptions::enabled(EquilibriumDiagnosticsMode::Summary);
        assert_ne!(
            options.for_range_point(0, 5).mode(),
            EquilibriumDiagnosticsMode::Disabled
        );
        assert_eq!(
            options.for_range_point(2, 5).mode(),
            EquilibriumDiagnosticsMode::Disabled
        );
        assert_ne!(
            options.for_range_point(4, 5).mode(),
            EquilibriumDiagnosticsMode::Disabled
        );
    }

    #[test]
    fn transitions_only_policy_defers_then_replays_accepted_point_evidence() {
        let (sender, receiver) = mpsc::channel();
        let options = EquilibriumDiagnosticsOptions::enabled(EquilibriumDiagnosticsMode::Summary)
            .with_range_policy(EquilibriumRangeDiagnosticsPolicy::TransitionsOnly)
            .with_sink(move |event| sender.send(event).unwrap());
        let point_options = options.for_range_point(4, 10);
        let mut collector = EquilibriumDiagnosticsCollector::new(point_options.clone());
        let phase_set =
            PhaseSet::from_policy(&InitialPhaseSet::AllCandidatePhases, &[true]).unwrap();
        collector.record(
            EquilibriumDiagnosticsMode::Summary,
            EquilibriumDiagnosticEvent::SolveAccepted {
                final_phase_set: phase_set,
                outer_iterations: 1,
                transition_count: 1,
            },
        );
        let report = collector.finish();
        assert!(receiver.try_recv().is_err());

        point_options.replay_retained_events(&report);
        assert!(matches!(
            receiver.recv().unwrap(),
            EquilibriumDiagnosticEvent::SolveAccepted {
                transition_count: 1,
                ..
            }
        ));
    }
}