dive-trace 0.1.0

TLA+ counterexample trace format and independent trace validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! Private reconstruction of startup, independent of the caller's evaluator.

use std::sync::atomic::Ordering;
use std::sync::{Arc, PoisonError};

use dive_model::{Model, Recipe};

use crate::validate::{FiniteScope, Run, TraceHost};
use crate::{Report, Source, Trace, TraceDoc, Validation};

/// Immutable validation inputs. Every interpretation gets a freshly bound
/// runtime. The caller's caches, registers, host and atoms are never copied.
///
/// ```
/// use std::sync::Arc;
/// use dive_trace::{Session, TraceDoc, Validation};
/// let source = "---- MODULE M ----\nEXTENDS TLC\nVARIABLE x\n\
///               ASSUME TLCSet(1,42)\nInit == x=0 /\\ TLCGet(1)=42\n\
///               Next == x'=x\n====\n";
/// let analysis = dive_sema::analyze_source("M.tla", source, &Default::default());
/// let ir = Arc::new(dive_ir::lower(&analysis).unwrap());
/// let config = dive_config::parse("INIT Init\nNEXT Next\n").into_config().unwrap();
/// let recipe = dive_model::Recipe::new(ir, config, dive_eval::Options::tlc(), false);
/// let session = Session::new(recipe, None);
/// let doc = TraceDoc::behavior(vec![serde_json::json!({"x":0})]).unwrap();
/// assert_eq!(session.read(&doc).0.validation, Validation::Valid);
/// ```
#[derive(Debug, Clone)]
pub struct Session {
    recipe: Recipe,
    config: Option<dive_eval::RunConfig>,
    inputs: Option<dive_eval::inputs::RecordedInputs>,
}

#[derive(Clone, Copy)]
enum FreshMode {
    Temporal,
    Finite(bool),
    /// A finite word whose last state's successors are regenerated.
    FiniteSuccessors(bool),
    NextPrefix,
    NextTerminal,
    InvariantPrefix,
    InvariantTerminal,
}

impl Session {
    /// Retains source/config inputs and typed run metadata, with no callbacks.
    #[must_use]
    pub fn new(recipe: Recipe, config: Option<dive_eval::RunConfig>) -> Self {
        Self {
            recipe,
            config,
            inputs: None,
        }
    }

    /// Supplies explicit external assumptions for fresh, ordered source replay.
    /// No operating-system input is read. The recipe retains its own category
    /// grants; supplied records must match actual binding operations exactly.
    #[must_use]
    pub fn with_inputs(mut self, inputs: dive_eval::inputs::RecordedInputs) -> Self {
        self.inputs = Some(inputs);
        self
    }

    fn startup_host(
        &self,
        choices: Option<Arc<crate::choices::Search>>,
    ) -> Result<Arc<TraceHost>, String> {
        let inputs = self
            .inputs
            .as_ref()
            .map(|inputs| dive_eval::inputs::InputReplay::new(inputs.clone()).map(Arc::new))
            .transpose()
            .map_err(|error| error.message)?;
        Ok(TraceHost::startup_context(inputs, choices))
    }

    pub(crate) fn bind(&self) -> Result<(Model, Arc<TraceHost>), String> {
        self.bind_in(true)
    }

    fn bind_in(&self, registers: bool) -> Result<(Model, Arc<TraceHost>), String> {
        let host = self.startup_host(None)?;
        host.startup.store(registers, Ordering::Relaxed);
        let model = self
            .recipe
            .bind(host.clone())
            .map_err(|e| e.error.to_string())?;
        host.finish_input_binding(&model)?;
        // Match the API/checker lifecycle: config is unavailable while binding.
        if let Some(mut config) = self.config.clone() {
            config.deadlock = model.settings.check_deadlock;
            model.evaluator.intern_checker_names();
            model.evaluator.intern_bfs_config(&config);
            *host
                .run_config
                .lock()
                .unwrap_or_else(PoisonError::into_inner) = Some(config);
        }
        Ok((model, host))
    }

    /// Reads and validates a document, returning a plain document for transport.
    /// Transport uses text/JSON; private interner atoms cannot escape the runtime.
    #[must_use]
    pub fn read(&self, doc: &TraceDoc) -> (Report, Option<TraceDoc>) {
        if matches!(
            doc.ending,
            Some(
                crate::Ending::TemporalStateError { .. }
                    | crate::Ending::TemporalSourceError { .. }
                    | crate::Ending::NextStateError { .. }
                    | crate::Ending::ViewSourceError { .. }
                    | crate::Ending::CandidateStateError { .. }
                    | crate::Ending::PartialNext { .. }
                    | crate::Ending::PartialInit { .. }
            )
        ) {
            return (
                refusal(
                    "source error endpoints require Session::try_read or read_controlled".into(),
                    doc.logical_length(),
                ),
                None,
            );
        }
        if doc.source == Source::Dive && finite_word(doc) {
            return self
                .read_finite_controlled(doc, None, FiniteScope::Behavior)
                .unwrap_or_else(|error| (refusal(error.to_string(), doc.logical_length()), None));
        }
        let (model, host) = match self.bind() {
            Ok(bound) => bound,
            Err(feature) => return (refusal(feature, doc.logical_length()), None),
        };
        if let Some(feature) = Run::private(&model, host, false).refusal() {
            return (refusal(feature, doc.logical_length()), None);
        }
        if doc.source == Source::Tlc {
            let reading =
                crate::tlc::validate_tlc_private(&model, doc, self.recipe.model_values(), self);
            let plain = reading.trace.and_then(|trace| trace.to_doc(&model).ok());
            (reading.report, plain)
        } else {
            self.plain(doc, true)
        }
    }

    fn plain(&self, doc: &TraceDoc, initial: bool) -> (Report, Option<TraceDoc>) {
        let (model, host) = match self.bind_in(initial) {
            Ok(bound) => bound,
            Err(feature) => return (refusal(feature, doc.logical_length()), None),
        };
        if let Some(feature) = Run::private(&model, host.clone(), initial).refusal() {
            return (refusal(feature, doc.logical_length()), None);
        }
        let Ok(trace) = Trace::decode(&model, doc) else {
            let (report, _) = crate::validate_doc(&model, doc, self.recipe.model_values());
            return (report, None);
        };
        let mut run = Run::private(&model, host.clone(), initial);
        let validation = run.validate(&trace);
        // Pure membership may use the conservative predicate path. It gets a
        // new runtime with registers refused even during binding and ASSUMEs;
        // any register use in this attempt disallows that fallback.
        if initial && run.init_incomplete && !host.register_used.load(Ordering::Relaxed) {
            drop(run);
            return self.plain(doc, false);
        }
        let report = Report {
            validation,
            notes: std::mem::take(&mut run.notes).into_iter().collect(),
            length: trace.states.len(),
        };
        (report, trace.to_doc(&model).ok())
    }

    /// Reads a native trace on a fresh privately bound runtime with typed control.
    /// Endpoint descriptors are independently compiled and replayed; no producer
    /// validation flag is authority. This new controlled fresh-session path
    /// supports native source error endpoints and finite behavior, invariant,
    /// action-property and deadlock words. TLC JSON interpretation retains its
    /// existing entrypoints.
    ///
    /// ```no_run
    /// # fn check(session: &dive_trace::Session, document: &dive_trace::TraceDoc,
    /// # control: std::sync::Arc<dyn dive_eval::HostControl>)
    /// # -> Result<(), dive_trace::ValidationRunError> {
    /// let (report, _) = session.read_controlled(document, control)?;
    /// # let _ = report; Ok(()) }
    /// ```
    ///
    /// # Errors
    /// Typed binding or validation interruption with progress, or conflicting
    /// evaluator control ownership. Other refusals remain validation reports.
    pub fn read_controlled(
        &self,
        doc: &TraceDoc,
        control: Arc<dyn dive_eval::HostControl>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        // Retain the owned control until private model/trace owners and the final poll finish.
        let result = self.read_fallible(doc, Some(&control));
        drop(control);
        result
    }

    /// Independently checks a native finite sample on a freshly reconstructed
    /// runtime. The document must retain its ordinary `behavior` ending; this
    /// separate operation also checks every sampled constraint, invariant and
    /// implied finite property. It proves neither exhaustive safety nor liveness.
    /// Fairness-only specifications are allowed; configured temporal properties
    /// remain unsupported. No producer metadata selects this operation.
    ///
    /// # Errors
    /// The same typed resource, interruption and control failures as
    /// [`Self::read_controlled`].
    pub fn read_sampled(
        &self,
        doc: &TraceDoc,
        control: Option<Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        if let Some(control) = &control {
            control
                .check()
                .map_err(|error| crate::ValidationRunError::Interrupted {
                    error: dive_eval::EvalError::interrupted(error),
                    progress: crate::ValidationProgress {
                        checks_passed: 0,
                        state: None,
                        check: None,
                    },
                })?;
        }
        if doc.source != Source::Dive
            || doc.ending != Some(crate::Ending::Behavior)
            || !doc.properties.is_empty()
        {
            return Ok((Report {
                validation: Validation::Invalid(crate::Failure { state: 0,
                    check: crate::Check::Shape,
                    detail: "sample validation requires a native finite behavior with no property or error endpoint claim".into() }),
                notes: Vec::new(), length: doc.logical_length(),
            }, None));
        }
        let result = self.read_finite_controlled(doc, control.as_ref(), FiniteScope::Sample);
        drop(control);
        result
    }

    /// Independently checks a native finite deadlock found by simulation on a
    /// freshly reconstructed runtime. Simulation keeps only the successors that
    /// satisfy every `CONSTRAINT` and `ACTION_CONSTRAINT`, as TLC's simulator
    /// does, so its deadlock is a last state none of whose successors is in
    /// the model. This operation regenerates every successor of the last state
    /// and rejects the word if any of them satisfies all the constraints; the
    /// rest of the word is checked as by [`Self::read_controlled`]. Exhaustive
    /// checking callers keep [`Self::read_controlled`], whose deadlock has no
    /// successor at all. No producer metadata selects this operation.
    ///
    /// ```no_run
    /// # fn check(session: &dive_trace::Session, document: &dive_trace::TraceDoc)
    /// # -> Result<(), dive_trace::ValidationRunError> {
    /// let (report, _) = session.read_sampled_deadlock(document, None)?;
    /// # let _ = report; Ok(()) }
    /// ```
    ///
    /// # Errors
    /// The same typed resource, interruption and control failures as
    /// [`Self::read_controlled`].
    pub fn read_sampled_deadlock(
        &self,
        doc: &TraceDoc,
        control: Option<Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        if let Some(control) = &control {
            control
                .check()
                .map_err(|error| crate::ValidationRunError::Interrupted {
                    error: dive_eval::EvalError::interrupted(error),
                    progress: crate::ValidationProgress {
                        checks_passed: 0,
                        state: None,
                        check: None,
                    },
                })?;
        }
        if doc.source != Source::Dive
            || doc.ending != Some(crate::Ending::Deadlock)
            || !doc.properties.is_empty()
        {
            return Ok((Report {
                validation: Validation::Invalid(crate::Failure { state: 0,
                    check: crate::Check::Shape,
                    detail: "sampled deadlock validation requires a native finite deadlock with no property claim".into() }),
                notes: Vec::new(), length: doc.logical_length(),
            }, None));
        }
        let result =
            self.read_finite_controlled(doc, control.as_ref(), FiniteScope::SampledDeadlock);
        drop(control);
        result
    }

    /// Validates a document with resource exceptions outside the report.
    /// No budget or artificial control is installed by this uncontrolled path.
    /// Documents without temporal error endpoints use the plain reader; those
    /// endpoints use fresh private binding, ordered reconstruction and finite
    /// replay.
    ///
    /// ```no_run
    /// # fn read(session: &dive_trace::Session, doc: &dive_trace::TraceDoc)
    /// # -> Result<(), dive_trace::ValidationRunError> {
    /// let (report, _) = session.try_read(doc)?;
    /// # let _ = report; Ok(()) }
    /// ```
    ///
    /// # Errors
    /// Allocation/resource failure or a typed evaluation-control interruption;
    /// neither is a completed validation verdict.
    pub fn try_read(
        &self,
        doc: &TraceDoc,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        if !matches!(
            doc.ending,
            Some(
                crate::Ending::TemporalStateError { .. }
                    | crate::Ending::TemporalSourceError { .. }
                    | crate::Ending::NextStateError { .. }
                    | crate::Ending::ViewSourceError { .. }
                    | crate::Ending::CandidateStateError { .. }
                    | crate::Ending::PartialNext { .. }
                    | crate::Ending::PartialInit { .. }
            )
        ) {
            return Ok(self.read(doc));
        }
        self.read_fallible(doc, None)
    }

    /// Reconstructs the first actual Init operation before selecting an error
    /// transport. Reported site/codes cannot disguise an emitted receiver error
    /// as a generation error to evade its required diagnostic witness.
    /// The no-word stages require matching actual diagnostic receiver catches.
    ///
    /// # Errors
    /// Typed interruption, resource/internal failure or control conflict;
    /// neither a stage nor an exception certificate exists in these cases.
    pub fn initial_error_stage(
        &self,
        control: Option<Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<crate::InitialErrorStage>), crate::ValidationRunError> {
        use crate::{ValidationProgress, ValidationRunError};
        let progress = || ValidationProgress {
            checks_passed: 0,
            state: None,
            check: Some(crate::Check::Init),
        };
        let poll = || {
            control.as_ref().map_or(Ok(()), |control| {
                control
                    .check()
                    .map_err(|error| ValidationRunError::Interrupted {
                        error: dive_eval::EvalError::interrupted(error),
                        progress: progress(),
                    })
            })
        };
        poll()?;
        let (model, host) =
            match self.fresh_binding(control.as_ref(), FreshMode::NextTerminal, 0)? {
                Ok(runtime) => runtime,
                Err(feature) => return Ok((refusal(feature, 0), None)),
            };
        let scope = control
            .as_ref()
            .map(|control| model.evaluator.host_control(Some(control.clone())))
            .transpose()
            .map_err(ValidationRunError::ControlConflict)?;
        let (validation, stage) = crate::invariant_error::stage(&model, &host, control.as_deref())
            .map_err(|error| match error.class() {
                dive_eval::ErrorClass::Interrupted => ValidationRunError::Interrupted {
                    error,
                    progress: progress(),
                },
                dive_eval::ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
                    error,
                    progress: progress(),
                },
                _ => ValidationRunError::EvaluationFailure {
                    error,
                    progress: progress(),
                },
            })?;
        poll()?;
        let report = Report {
            validation,
            notes: Vec::new(),
            length: usize::from(
                stage.is_some_and(|stage| stage != crate::InitialErrorStage::Generation),
            ),
        };
        drop(scope);
        drop(control);
        Ok((report, stage))
    }

    /// Validates a named invariant-error word, then independently reconstructs
    /// its bounded first-Init receiver exception and diagnostic wrapper.
    /// Ordinary word validity alone never grants the optional class evidence.
    /// The document retains version 2 and names its original underlying cause.
    ///
    /// ```no_run
    /// # fn replay(session: &dive_trace::Session, word: &dive_trace::TraceDoc)
    /// # -> Result<(), dive_trace::ValidationRunError> {
    /// let (report, class) = session.initial_invariant_class(word, None)?;
    /// if let Some(class) = class {
    ///     assert!(report.validation.is_valid());
    ///     assert_eq!(class.deciding_code(), 2147);
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    /// Original typed interruption, resource/internal failure or conflicting
    /// control ownership; none can produce a class certificate.
    #[allow(
        clippy::too_many_lines,
        reason = "fresh word and receiver runtimes retain distinct ownership"
    )]
    pub fn initial_invariant_class(
        &self,
        doc: &TraceDoc,
        control: Option<Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<crate::InitialInvariantClass>), crate::ValidationRunError> {
        use crate::{Check, Ending, ValidationProgress, ValidationRunError};
        let progress = || ValidationProgress {
            checks_passed: 0,
            state: Some(0),
            check: Some(Check::Ending),
        };
        let poll = || {
            control.as_ref().map_or(Ok(()), |control| {
                control
                    .check()
                    .map_err(|error| ValidationRunError::Interrupted {
                        error: dive_eval::EvalError::interrupted(error),
                        progress: progress(),
                    })
            })
        };
        let finish = |report, class| {
            poll()?;
            Ok((report, class))
        };
        poll()?;
        let Some(Ending::InvariantError { name, ec }) = &doc.ending else {
            return finish(
                refusal(
                    "initial invariant class requires a named original cause".into(),
                    doc.logical_length(),
                ),
                None,
            );
        };
        if doc.source != Source::Dive || doc.states.len() != 1 || !doc.properties.is_empty() {
            return finish(refusal("initial receiver class requires one native initial state without temporal claims".into(), doc.logical_length()), None);
        }
        let (model, host) = match self.fresh_binding(control.as_ref(), FreshMode::NextPrefix, 0)? {
            Ok(runtime) => runtime,
            Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
        };
        let trace = match Trace::decode(&model, doc) {
            Ok(trace) => trace,
            Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
        };
        let mut report =
            crate::validate::validate_private_controlled(&model, host, &trace, control.clone())?;
        if !report.validation.is_valid() {
            return finish(report, None);
        }
        // Predicate validation must not supply cached receivers or normalization
        // history to the separate ordinary/diagnostic Init reconstruction.
        drop(trace);
        drop(model);
        let (model, host) =
            match self.fresh_binding(control.as_ref(), FreshMode::NextTerminal, 0)? {
                Ok(runtime) => runtime,
                Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
            };
        let trace = match Trace::decode(&model, doc) {
            Ok(trace) => trace,
            Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
        };
        let control_scope = control
            .as_ref()
            .map(|control| model.evaluator.host_control(Some(control.clone())))
            .transpose()
            .map_err(ValidationRunError::ControlConflict)?;
        let replay = crate::invariant_error::replay(
            &model,
            &trace.states[0],
            name,
            ec,
            &host,
            control.as_deref(),
        );
        let class = match replay {
            Ok((validation, class)) => {
                report.validation = validation;
                class
            }
            Err(error) => {
                return Err(match error.class() {
                    dive_eval::ErrorClass::Interrupted => ValidationRunError::Interrupted {
                        error,
                        progress: progress(),
                    },
                    dive_eval::ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
                        error,
                        progress: progress(),
                    },
                    _ => ValidationRunError::EvaluationFailure {
                        error,
                        progress: progress(),
                    },
                });
            }
        };
        let result = finish(report, class);
        drop(control_scope);
        drop(control);
        result
    }

    /// Validates a named successor-invariant word and independently executes
    /// one exhausted Init, each earlier admitted source and actual diagnostic
    /// replay with bounded private key history.
    /// No serialized metadata or ordinary word validity supplies this evidence.
    ///
    /// # Errors
    /// Actual interruption, resource/internal failure or control conflict;
    /// no completed class certificate is returned for these failures.
    #[allow(
        clippy::too_many_lines,
        reason = "fresh word and receiver runtimes retain distinct ownership"
    )]
    pub fn invariant_error_class(
        &self,
        doc: &TraceDoc,
        control: Option<Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<crate::InvariantErrorClass>), crate::ValidationRunError> {
        use crate::{Check, Ending, ValidationProgress, ValidationRunError};
        let progress = || ValidationProgress {
            checks_passed: 0,
            state: Some(0),
            check: Some(Check::Ending),
        };
        let poll = || {
            control.as_ref().map_or(Ok(()), |control| {
                control
                    .check()
                    .map_err(|error| ValidationRunError::Interrupted {
                        error: dive_eval::EvalError::interrupted(error),
                        progress: progress(),
                    })
            })
        };
        let finish = |report, class| {
            poll()?;
            Ok((report, class))
        };
        poll()?;
        let Some(Ending::InvariantError { .. }) = &doc.ending else {
            return finish(
                refusal(
                    "successor invariant class requires a named original cause".into(),
                    doc.logical_length(),
                ),
                None,
            );
        };
        if doc.source != Source::Dive || doc.states.len() < 2 || !doc.properties.is_empty() {
            return finish(refusal("successor invariant class requires a finite native successor word without temporal claims".into(), doc.logical_length()), None);
        }
        let (model, host) =
            match self.fresh_binding(control.as_ref(), FreshMode::InvariantPrefix, 0)? {
                Ok(runtime) => runtime,
                Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
            };
        let trace = match Trace::decode(&model, doc) {
            Ok(trace) => trace,
            Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
        };
        let mut report =
            crate::validate::validate_private_controlled(&model, host, &trace, control.clone())?;
        if !report.validation.is_valid() {
            return finish(report, None);
        }
        // Predicate validation must not supply cached receivers or normalization
        // history to the separate ordinary/diagnostic Init reconstruction.
        drop(trace);
        drop(model);
        let (model, host) =
            match self.fresh_binding(control.as_ref(), FreshMode::InvariantTerminal, 0)? {
                Ok(runtime) => runtime,
                Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
            };
        let trace = match Trace::decode(&model, doc) {
            Ok(trace) => trace,
            Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
        };
        let control_scope = control
            .as_ref()
            .map(|control| model.evaluator.host_control(Some(control.clone())))
            .transpose()
            .map_err(ValidationRunError::ControlConflict)?;
        let replay = crate::ordered_prefix::invariant(&model, &trace, &host, control.as_deref());
        let class = match replay {
            Ok((validation, class)) => {
                if let Some(reason) = Run::private(&model, host.clone(), false).refusal() {
                    report.validation = Validation::Unsupported(reason);
                    None
                } else {
                    report.validation = validation;
                    class
                }
            }
            Err(error) => {
                return Err(match error.class() {
                    dive_eval::ErrorClass::Interrupted => ValidationRunError::Interrupted {
                        error,
                        progress: progress(),
                    },
                    dive_eval::ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
                        error,
                        progress: progress(),
                    },
                    _ => ValidationRunError::EvaluationFailure {
                        error,
                        progress: progress(),
                    },
                });
            }
        };
        let result = finish(report, class);
        drop(control_scope);
        drop(control);
        result
    }

    #[allow(
        clippy::too_many_lines,
        reason = "one source-admission boundary retains typed controls and endpoint dispatch order"
    )]
    fn read_fallible(
        &self,
        doc: &TraceDoc,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        use crate::{ValidationProgress, ValidationRunError};
        let progress = || ValidationProgress {
            checks_passed: 0,
            state: None,
            check: None,
        };
        let poll = || {
            if let Some(control) = control {
                control
                    .check()
                    .map_err(|error| ValidationRunError::Interrupted {
                        error: dive_eval::EvalError::interrupted(error),
                        progress: progress(),
                    })?;
            }
            Ok(())
        };
        let finish = |report, document| {
            poll()?;
            Ok((report, document))
        };
        poll()?;
        if doc.source != Source::Dive {
            return finish(
                refusal(
                    "controlled private TLC document interpretation".into(),
                    doc.logical_length(),
                ),
                None,
            );
        }
        if finite_word(doc) {
            return self.read_finite_controlled(doc, control, FiniteScope::Behavior);
        }
        if !matches!(
            doc.ending,
            Some(
                crate::Ending::TemporalStateError { .. }
                    | crate::Ending::TemporalSourceError { .. }
                    | crate::Ending::NextStateError { .. }
                    | crate::Ending::ViewSourceError { .. }
                    | crate::Ending::CandidateStateError { .. }
                    | crate::Ending::PartialNext { .. }
                    | crate::Ending::PartialInit { .. }
            )
        ) {
            return finish(refusal("controlled fresh-session validation currently requires a native source error endpoint; use existing validation entrypoints for other documents".into(),doc.states.len()),None);
        }
        let next_error = matches!(
            doc.ending,
            Some(
                crate::Ending::NextStateError { .. }
                    | crate::Ending::TemporalSourceError { .. }
                    | crate::Ending::ViewSourceError { .. }
                    | crate::Ending::CandidateStateError { .. }
                    | crate::Ending::PartialNext { .. }
                    | crate::Ending::PartialInit { .. }
            )
        );
        if next_error && !doc.properties.is_empty() {
            return finish(
                Report {
                    validation: Validation::Invalid(crate::Failure {
                        state: 0,
                        check: crate::Check::Shape,
                        detail: "finite Next error endpoint cannot claim temporal properties"
                            .into(),
                    }),
                    notes: Vec::new(),
                    length: doc.logical_length(),
                },
                None,
            );
        }
        let mode = if matches!(doc.ending, Some(crate::Ending::PartialInit { .. })) {
            FreshMode::NextTerminal
        } else if next_error {
            FreshMode::NextPrefix
        } else {
            FreshMode::Temporal
        };
        let (model, host) = match self.fresh_binding(control, mode, 0)? {
            Ok(runtime) => runtime,
            Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
        };
        if matches!(doc.ending, Some(crate::Ending::PartialInit { .. })) {
            return Self::read_initial_partial_endpoint(doc, &model, host, control);
        }
        if matches!(doc.ending, Some(crate::Ending::PartialNext { .. })) {
            return self.read_partial_endpoint(doc, model, host, control);
        }
        let trace = match Trace::decode(&model, doc) {
            Ok(trace) => trace,
            Err(error) => {
                return finish(shape_refusal(error, doc.states.len()), None);
            }
        };
        if next_error {
            return self.read_next_endpoint(doc, model, host, trace, control);
        }
        let report =
            crate::validate::validate_private_controlled(&model, host, &trace, control.cloned())?;
        finish(report, trace.to_doc(&model).ok())
    }

    fn read_finite_controlled(
        &self,
        doc: &TraceDoc,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
        scope: FiniteScope,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        if !self.recipe.has_randomness() {
            return self.read_finite_attempt(doc, control, scope, None);
        }
        let choices = Arc::new(crate::choices::Search::default());
        for _ in 0..crate::choices::MAX_ATTEMPTS {
            if let Some(control) = control {
                control
                    .check()
                    .map_err(|error| crate::ValidationRunError::Interrupted {
                        error: dive_eval::EvalError::interrupted(error),
                        progress: crate::ValidationProgress {
                            checks_passed: 0,
                            state: None,
                            check: None,
                        },
                    })?;
            }
            // The previous attempt, including every value and name it created,
            // is dropped before another source binding begins. A new host cache
            // domain alone would not isolate mutable normalization histories.
            let result = self.read_finite_attempt(doc, control, scope, Some(&choices))?;
            if !matches!(result.0.validation, Validation::Invalid(_))
                || choices.refusal().is_some()
                || !choices.advance()
            {
                return Ok(result);
            }
        }
        Err(crate::ValidationRunError::ResourceLimit {
            error: dive_eval::EvalError::resource_limit(
                "independent finite random choice attempts",
            ),
            progress: crate::ValidationProgress {
                checks_passed: 0,
                state: None,
                check: None,
            },
        })
    }

    fn read_finite_attempt(
        &self,
        doc: &TraceDoc,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
        scope: FiniteScope,
        choices: Option<&Arc<crate::choices::Search>>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        for initial in [true, false] {
            if let Some(choices) = choices {
                choices.rewind();
            }
            let (model, host) = match self.fresh_binding_choices(
                control,
                if scope == FiniteScope::SampledDeadlock {
                    FreshMode::FiniteSuccessors(initial)
                } else {
                    FreshMode::Finite(initial)
                },
                0,
                choices.cloned(),
            )? {
                Ok(runtime) => runtime,
                Err(feature) => return Ok((refusal(feature, doc.logical_length()), None)),
            };
            if scope == FiniteScope::Sample
                && (!model.implied_temporals.is_empty()
                    || model.view.is_some()
                    || model.symmetry.is_some()
                    || model.alias.is_some()
                    || !matches!(&model.postconditions, Ok(postconditions) if postconditions.is_empty()))
            {
                return Ok((refusal("finite sample validation does not discharge temporal PROPERTY, VIEW, symmetry, ALIAS or POSTCONDITION obligations".into(), doc.logical_length()), None));
            }
            let trace = match Trace::decode(&model, doc) {
                Ok(trace) => trace,
                Err(error) => {
                    return Ok((
                        Report {
                            validation: Validation::Invalid(crate::Failure {
                                state: error.state.unwrap_or(0),
                                check: crate::Check::Shape,
                                detail: error.detail,
                            }),
                            notes: Vec::new(),
                            length: doc.logical_length(),
                        },
                        None,
                    ));
                }
            };
            let (report, retry) = crate::validate::validate_finite_private_controlled(
                &model,
                &host,
                &trace,
                initial,
                control.cloned(),
                scope,
            )?;
            if !retry {
                return Ok((report, trace.to_doc(&model).ok()));
            }
        }
        Ok((
            refusal(
                "finite initial replay is unproved".into(),
                doc.logical_length(),
            ),
            None,
        ))
    }

    fn read_next_endpoint(
        &self,
        doc: &TraceDoc,
        model: Model,
        host: Arc<TraceHost>,
        trace: Trace,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        use crate::{ValidationProgress, ValidationRunError};
        let (prefix, checks_passed) = crate::validate::validate_next_prefix_controlled(
            &model,
            host,
            &trace,
            control.cloned(),
        )?;
        let finish_next = |report, document| {
            if let Some(control) = control {
                control
                    .check()
                    .map_err(|error| ValidationRunError::Interrupted {
                        error: dive_eval::EvalError::interrupted(error),
                        progress: ValidationProgress {
                            checks_passed,
                            state: doc.states.len().checked_sub(1),
                            check: Some(crate::Check::Ending),
                        },
                    })?;
            }
            Ok((report, document))
        };
        if prefix.validation != Validation::Valid {
            return finish_next(prefix, trace.to_doc(&model).ok());
        }
        // Prefix predicates must not warm the terminal generator's lazy
        // values or normalization state. No private atom is transferred.
        drop(trace);
        drop(model);
        let (model, host) =
            match self.fresh_binding(control, FreshMode::NextTerminal, checks_passed)? {
                Ok(runtime) => runtime,
                Err(feature) => return finish_next(refusal(feature, doc.logical_length()), None),
            };
        let trace = match Trace::decode(&model, doc) {
            Ok(trace) => trace,
            Err(error) => return finish_next(shape_refusal(error, doc.states.len()), None),
        };
        let Some(state) = trace.states.last() else {
            return finish_next(refusal("Next endpoint has no state".into(), 0), None);
        };
        let mut report = crate::validate::replay_next_controlled(
            &model,
            host,
            &trace,
            state,
            checks_passed,
            control.cloned(),
        )?;
        report.notes.extend(prefix.notes);
        let plain = trace.to_doc(&model).ok();
        finish_next(report, plain)
    }

    fn read_partial_endpoint(
        &self,
        doc: &TraceDoc,
        model: Model,
        host: Arc<TraceHost>,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        let invalid = |detail: &str| {
            (
                Report {
                    validation: Validation::Invalid(crate::Failure {
                        state: doc.states.len(),
                        check: crate::Check::Shape,
                        detail: detail.into(),
                    }),
                    notes: Vec::new(),
                    length: doc.logical_length(),
                },
                None,
            )
        };
        if matches!(&doc.ending,Some(crate::Ending::PartialNext {endpoint}) if endpoint.initial()) {
            return Ok(invalid("partial Next descriptor has an Init phase"));
        }
        if doc.states.is_empty() {
            return Ok(invalid("partial Next needs a complete source prefix"));
        }
        if doc
            .length
            .is_some_and(|length| length != doc.logical_length())
        {
            return Ok(invalid(
                "logical word length must include the partial terminal candidate",
            ));
        }
        // Retain the error-witness goal: ordinary Behavior deliberately omits
        // configured safety obligations, while every complete prefix row here
        // must pass them before a terminal event can be certified.
        let mut prefix = doc.clone();
        prefix.length = Some(prefix.states.len());
        let trace = match Trace::decode(&model, &prefix) {
            Ok(trace) => trace,
            Err(error) => return Ok(invalid(&error.detail)),
        };
        let (mut report, passed) = crate::validate::validate_next_prefix_controlled(
            &model,
            host,
            &trace,
            control.cloned(),
        )?;
        report.length = doc.logical_length();
        if report.validation != Validation::Valid {
            return Ok((report, None));
        }
        drop(trace);
        drop(model);
        let (model, host) = match self.fresh_binding(control, FreshMode::NextTerminal, passed)? {
            Ok(runtime) => runtime,
            Err(feature) => return Ok((refusal(feature, doc.logical_length()), None)),
        };
        let trace = match Trace::decode(&model, &prefix) {
            Ok(trace) => trace,
            Err(error) => return Ok(invalid(&error.detail)),
        };
        let Some(crate::Ending::PartialNext { endpoint }) = &doc.ending else {
            return Ok(invalid("missing partial terminal descriptor"));
        };
        let report = crate::validate::replay_partial_controlled(
            &model,
            host,
            &trace,
            endpoint,
            passed,
            control.cloned(),
        )?;
        Ok((report, Some(doc.clone())))
    }

    fn read_initial_partial_endpoint(
        doc: &TraceDoc,
        model: &Model,
        host: Arc<TraceHost>,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
    ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
        let invalid = |detail: &str| {
            (
                Report {
                    validation: Validation::Invalid(crate::Failure {
                        state: 0,
                        check: crate::Check::Shape,
                        detail: detail.into(),
                    }),
                    notes: Vec::new(),
                    length: doc.logical_length(),
                },
                None,
            )
        };
        if !doc.states.is_empty()
            || !doc.labels.is_empty()
            || doc.length.is_some_and(|length| length != 1)
        {
            return Ok(invalid(
                "partial Init has no complete prefix and logical length one",
            ));
        }
        let variables = crate::variables(model);
        let header: std::collections::BTreeSet<_> = doc.variables.iter().collect();
        if header.len() != variables.len()
            || doc.variables.len() != variables.len()
            || variables.iter().any(|name| !header.contains(name))
        {
            return Ok(invalid(
                "partial Init variable header differs from the model",
            ));
        }
        let Some(crate::Ending::PartialInit { endpoint }) = &doc.ending else {
            return Ok(invalid("missing Init partial descriptor"));
        };
        if !endpoint.initial() {
            return Ok(invalid("partial Init descriptor has a Next phase"));
        }
        let report = crate::validate::replay_initial_partial_controlled(
            model,
            host,
            endpoint,
            control.cloned(),
        )?;
        Ok((report, Some(doc.clone())))
    }

    fn fresh_binding(
        &self,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
        mode: FreshMode,
        checks_passed: u64,
    ) -> Result<Result<(Model, Arc<TraceHost>), String>, crate::ValidationRunError> {
        self.fresh_binding_choices(control, mode, checks_passed, None)
    }

    fn fresh_binding_choices(
        &self,
        control: Option<&Arc<dyn dive_eval::HostControl>>,
        mode: FreshMode,
        checks_passed: u64,
        choices: Option<Arc<crate::choices::Search>>,
    ) -> Result<Result<(Model, Arc<TraceHost>), String>, crate::ValidationRunError> {
        use crate::{ValidationProgress, ValidationRunError};
        let progress = || ValidationProgress {
            checks_passed,
            state: None,
            check: None,
        };
        let poll = || {
            if let Some(control) = control {
                control
                    .check()
                    .map_err(|error| ValidationRunError::Interrupted {
                        error: dive_eval::EvalError::interrupted(error),
                        progress: progress(),
                    })?;
            }
            Ok(())
        };
        poll()?;
        let source_actions = (choices.is_some() && matches!(mode, FreshMode::Finite(_)))
            || matches!(mode, FreshMode::FiniteSuccessors(_));
        let host = match self.startup_host(choices) {
            Ok(host) => host,
            Err(error) => return Ok(Err(error)),
        };
        host.startup.store(
            matches!(
                mode,
                FreshMode::Temporal | FreshMode::Finite(true) | FreshMode::FiniteSuccessors(true)
            ),
            Ordering::Relaxed,
        );
        // Invariant certification executes deterministic Print value semantics
        // with the existing suppressed sink throughout its actual lifecycle.
        // Other error endpoints keep their earlier effect refusal; random,
        // registers and I/O retain their independent host guards.
        host.next_error.store(
            matches!(mode, FreshMode::NextPrefix | FreshMode::NextTerminal),
            Ordering::Relaxed,
        );
        let binding = if source_actions
            || matches!(mode, FreshMode::NextTerminal | FreshMode::InvariantTerminal)
        {
            self.recipe
                .bind_next_fallible(host.clone(), control.cloned())
        } else {
            self.recipe.bind_fallible(host.clone(), control.cloned())
        };
        let model = match binding {
            Ok(model) => model,
            Err(dive_model::ControlledBindError::Interrupted { error, .. }) => {
                return Err(ValidationRunError::Interrupted {
                    error,
                    progress: progress(),
                });
            }
            Err(dive_model::ControlledBindError::ControlConflict { error, .. }) => {
                return Err(ValidationRunError::ControlConflict(error));
            }
            Err(dive_model::ControlledBindError::EvaluationFailure { error, .. }) => {
                return Err(if error.class() == dive_eval::ErrorClass::ResourceLimit {
                    ValidationRunError::ResourceLimit {
                        error,
                        progress: progress(),
                    }
                } else {
                    ValidationRunError::EvaluationFailure {
                        error,
                        progress: progress(),
                    }
                });
            }
            Err(dive_model::ControlledBindError::Binding(failure)) => {
                if failure.error.kind == dive_model::ErrorKind::Bug {
                    return Err(ValidationRunError::BindingFailure {
                        error: failure.error,
                        progress: progress(),
                    });
                }
                return Ok(Err(failure.error.to_string()));
            }
        };
        if let Err(error) = host.finish_input_binding(&model) {
            return Ok(Err(error));
        }
        poll()?;
        if let Some(mut config) = self.config.clone() {
            config.deadlock = model.settings.check_deadlock;
            model.evaluator.intern_checker_names();
            model.evaluator.intern_bfs_config(&config);
            *host
                .run_config
                .lock()
                .unwrap_or_else(PoisonError::into_inner) = Some(config);
        }
        poll()?;
        Ok(Ok((model, host)))
    }

    pub(crate) fn interpretation(&self, doc: &TraceDoc) -> (Report, Option<TraceDoc>) {
        self.plain(doc, true)
    }
}

fn finite_word(doc: &TraceDoc) -> bool {
    doc.properties.is_empty()
        && matches!(
            doc.ending,
            None | Some(
                crate::Ending::Behavior
                    | crate::Ending::Invariant(_)
                    | crate::Ending::Property(_)
                    | crate::Ending::Deadlock
            )
        )
}

fn refusal(feature: String, length: usize) -> Report {
    Report {
        validation: Validation::Unsupported(feature),
        notes: Vec::new(),
        length,
    }
}

fn shape_refusal(error: crate::ShapeError, length: usize) -> Report {
    Report {
        validation: Validation::Invalid(crate::Failure {
            state: error.state.unwrap_or(0),
            check: crate::Check::Shape,
            detail: error.detail,
        }),
        notes: Vec::new(),
        length,
    }
}