1use std::sync::atomic::Ordering;
4use std::sync::{Arc, PoisonError};
5
6use dive_model::{Model, Recipe};
7
8use crate::validate::{FiniteScope, Run, TraceHost};
9use crate::{Report, Source, Trace, TraceDoc, Validation};
10
11#[derive(Debug, Clone)]
29pub struct Session {
30 recipe: Recipe,
31 config: Option<dive_eval::RunConfig>,
32 inputs: Option<dive_eval::inputs::RecordedInputs>,
33}
34
35#[derive(Clone, Copy)]
36enum FreshMode {
37 Temporal,
38 Finite(bool),
39 FiniteSuccessors(bool),
41 NextPrefix,
42 NextTerminal,
43 InvariantPrefix,
44 InvariantTerminal,
45}
46
47impl Session {
48 #[must_use]
50 pub fn new(recipe: Recipe, config: Option<dive_eval::RunConfig>) -> Self {
51 Self {
52 recipe,
53 config,
54 inputs: None,
55 }
56 }
57
58 #[must_use]
62 pub fn with_inputs(mut self, inputs: dive_eval::inputs::RecordedInputs) -> Self {
63 self.inputs = Some(inputs);
64 self
65 }
66
67 fn startup_host(
68 &self,
69 choices: Option<Arc<crate::choices::Search>>,
70 ) -> Result<Arc<TraceHost>, String> {
71 let inputs = self
72 .inputs
73 .as_ref()
74 .map(|inputs| dive_eval::inputs::InputReplay::new(inputs.clone()).map(Arc::new))
75 .transpose()
76 .map_err(|error| error.message)?;
77 Ok(TraceHost::startup_context(inputs, choices))
78 }
79
80 pub(crate) fn bind(&self) -> Result<(Model, Arc<TraceHost>), String> {
81 self.bind_in(true)
82 }
83
84 fn bind_in(&self, registers: bool) -> Result<(Model, Arc<TraceHost>), String> {
85 let host = self.startup_host(None)?;
86 host.startup.store(registers, Ordering::Relaxed);
87 let model = self
88 .recipe
89 .bind(host.clone())
90 .map_err(|e| e.error.to_string())?;
91 host.finish_input_binding(&model)?;
92 if let Some(mut config) = self.config.clone() {
94 config.deadlock = model.settings.check_deadlock;
95 model.evaluator.intern_checker_names();
96 model.evaluator.intern_bfs_config(&config);
97 *host
98 .run_config
99 .lock()
100 .unwrap_or_else(PoisonError::into_inner) = Some(config);
101 }
102 Ok((model, host))
103 }
104
105 #[must_use]
108 pub fn read(&self, doc: &TraceDoc) -> (Report, Option<TraceDoc>) {
109 if matches!(
110 doc.ending,
111 Some(
112 crate::Ending::TemporalStateError { .. }
113 | crate::Ending::TemporalSourceError { .. }
114 | crate::Ending::NextStateError { .. }
115 | crate::Ending::ViewSourceError { .. }
116 | crate::Ending::CandidateStateError { .. }
117 | crate::Ending::PartialNext { .. }
118 | crate::Ending::PartialInit { .. }
119 )
120 ) {
121 return (
122 refusal(
123 "source error endpoints require Session::try_read or read_controlled".into(),
124 doc.logical_length(),
125 ),
126 None,
127 );
128 }
129 if doc.source == Source::Dive && finite_word(doc) {
130 return self
131 .read_finite_controlled(doc, None, FiniteScope::Behavior)
132 .unwrap_or_else(|error| (refusal(error.to_string(), doc.logical_length()), None));
133 }
134 let (model, host) = match self.bind() {
135 Ok(bound) => bound,
136 Err(feature) => return (refusal(feature, doc.logical_length()), None),
137 };
138 if let Some(feature) = Run::private(&model, host, false).refusal() {
139 return (refusal(feature, doc.logical_length()), None);
140 }
141 if doc.source == Source::Tlc {
142 let reading =
143 crate::tlc::validate_tlc_private(&model, doc, self.recipe.model_values(), self);
144 let plain = reading.trace.and_then(|trace| trace.to_doc(&model).ok());
145 (reading.report, plain)
146 } else {
147 self.plain(doc, true)
148 }
149 }
150
151 fn plain(&self, doc: &TraceDoc, initial: bool) -> (Report, Option<TraceDoc>) {
152 let (model, host) = match self.bind_in(initial) {
153 Ok(bound) => bound,
154 Err(feature) => return (refusal(feature, doc.logical_length()), None),
155 };
156 if let Some(feature) = Run::private(&model, host.clone(), initial).refusal() {
157 return (refusal(feature, doc.logical_length()), None);
158 }
159 let Ok(trace) = Trace::decode(&model, doc) else {
160 let (report, _) = crate::validate_doc(&model, doc, self.recipe.model_values());
161 return (report, None);
162 };
163 let mut run = Run::private(&model, host.clone(), initial);
164 let validation = run.validate(&trace);
165 if initial && run.init_incomplete && !host.register_used.load(Ordering::Relaxed) {
169 drop(run);
170 return self.plain(doc, false);
171 }
172 let report = Report {
173 validation,
174 notes: std::mem::take(&mut run.notes).into_iter().collect(),
175 length: trace.states.len(),
176 };
177 (report, trace.to_doc(&model).ok())
178 }
179
180 pub fn read_controlled(
199 &self,
200 doc: &TraceDoc,
201 control: Arc<dyn dive_eval::HostControl>,
202 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
203 let result = self.read_fallible(doc, Some(&control));
205 drop(control);
206 result
207 }
208
209 pub fn read_sampled(
220 &self,
221 doc: &TraceDoc,
222 control: Option<Arc<dyn dive_eval::HostControl>>,
223 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
224 if let Some(control) = &control {
225 control
226 .check()
227 .map_err(|error| crate::ValidationRunError::Interrupted {
228 error: dive_eval::EvalError::interrupted(error),
229 progress: crate::ValidationProgress {
230 checks_passed: 0,
231 state: None,
232 check: None,
233 },
234 })?;
235 }
236 if doc.source != Source::Dive
237 || doc.ending != Some(crate::Ending::Behavior)
238 || !doc.properties.is_empty()
239 {
240 return Ok((Report {
241 validation: Validation::Invalid(crate::Failure { state: 0,
242 check: crate::Check::Shape,
243 detail: "sample validation requires a native finite behavior with no property or error endpoint claim".into() }),
244 notes: Vec::new(), length: doc.logical_length(),
245 }, None));
246 }
247 let result = self.read_finite_controlled(doc, control.as_ref(), FiniteScope::Sample);
248 drop(control);
249 result
250 }
251
252 pub fn read_sampled_deadlock(
273 &self,
274 doc: &TraceDoc,
275 control: Option<Arc<dyn dive_eval::HostControl>>,
276 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
277 if let Some(control) = &control {
278 control
279 .check()
280 .map_err(|error| crate::ValidationRunError::Interrupted {
281 error: dive_eval::EvalError::interrupted(error),
282 progress: crate::ValidationProgress {
283 checks_passed: 0,
284 state: None,
285 check: None,
286 },
287 })?;
288 }
289 if doc.source != Source::Dive
290 || doc.ending != Some(crate::Ending::Deadlock)
291 || !doc.properties.is_empty()
292 {
293 return Ok((Report {
294 validation: Validation::Invalid(crate::Failure { state: 0,
295 check: crate::Check::Shape,
296 detail: "sampled deadlock validation requires a native finite deadlock with no property claim".into() }),
297 notes: Vec::new(), length: doc.logical_length(),
298 }, None));
299 }
300 let result =
301 self.read_finite_controlled(doc, control.as_ref(), FiniteScope::SampledDeadlock);
302 drop(control);
303 result
304 }
305
306 pub fn try_read(
323 &self,
324 doc: &TraceDoc,
325 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
326 if !matches!(
327 doc.ending,
328 Some(
329 crate::Ending::TemporalStateError { .. }
330 | crate::Ending::TemporalSourceError { .. }
331 | crate::Ending::NextStateError { .. }
332 | crate::Ending::ViewSourceError { .. }
333 | crate::Ending::CandidateStateError { .. }
334 | crate::Ending::PartialNext { .. }
335 | crate::Ending::PartialInit { .. }
336 )
337 ) {
338 return Ok(self.read(doc));
339 }
340 self.read_fallible(doc, None)
341 }
342
343 pub fn initial_error_stage(
352 &self,
353 control: Option<Arc<dyn dive_eval::HostControl>>,
354 ) -> Result<(Report, Option<crate::InitialErrorStage>), crate::ValidationRunError> {
355 use crate::{ValidationProgress, ValidationRunError};
356 let progress = || ValidationProgress {
357 checks_passed: 0,
358 state: None,
359 check: Some(crate::Check::Init),
360 };
361 let poll = || {
362 control.as_ref().map_or(Ok(()), |control| {
363 control
364 .check()
365 .map_err(|error| ValidationRunError::Interrupted {
366 error: dive_eval::EvalError::interrupted(error),
367 progress: progress(),
368 })
369 })
370 };
371 poll()?;
372 let (model, host) =
373 match self.fresh_binding(control.as_ref(), FreshMode::NextTerminal, 0)? {
374 Ok(runtime) => runtime,
375 Err(feature) => return Ok((refusal(feature, 0), None)),
376 };
377 let scope = control
378 .as_ref()
379 .map(|control| model.evaluator.host_control(Some(control.clone())))
380 .transpose()
381 .map_err(ValidationRunError::ControlConflict)?;
382 let (validation, stage) = crate::invariant_error::stage(&model, &host, control.as_deref())
383 .map_err(|error| match error.class() {
384 dive_eval::ErrorClass::Interrupted => ValidationRunError::Interrupted {
385 error,
386 progress: progress(),
387 },
388 dive_eval::ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
389 error,
390 progress: progress(),
391 },
392 _ => ValidationRunError::EvaluationFailure {
393 error,
394 progress: progress(),
395 },
396 })?;
397 poll()?;
398 let report = Report {
399 validation,
400 notes: Vec::new(),
401 length: usize::from(
402 stage.is_some_and(|stage| stage != crate::InitialErrorStage::Generation),
403 ),
404 };
405 drop(scope);
406 drop(control);
407 Ok((report, stage))
408 }
409
410 #[allow(
430 clippy::too_many_lines,
431 reason = "fresh word and receiver runtimes retain distinct ownership"
432 )]
433 pub fn initial_invariant_class(
434 &self,
435 doc: &TraceDoc,
436 control: Option<Arc<dyn dive_eval::HostControl>>,
437 ) -> Result<(Report, Option<crate::InitialInvariantClass>), crate::ValidationRunError> {
438 use crate::{Check, Ending, ValidationProgress, ValidationRunError};
439 let progress = || ValidationProgress {
440 checks_passed: 0,
441 state: Some(0),
442 check: Some(Check::Ending),
443 };
444 let poll = || {
445 control.as_ref().map_or(Ok(()), |control| {
446 control
447 .check()
448 .map_err(|error| ValidationRunError::Interrupted {
449 error: dive_eval::EvalError::interrupted(error),
450 progress: progress(),
451 })
452 })
453 };
454 let finish = |report, class| {
455 poll()?;
456 Ok((report, class))
457 };
458 poll()?;
459 let Some(Ending::InvariantError { name, ec }) = &doc.ending else {
460 return finish(
461 refusal(
462 "initial invariant class requires a named original cause".into(),
463 doc.logical_length(),
464 ),
465 None,
466 );
467 };
468 if doc.source != Source::Dive || doc.states.len() != 1 || !doc.properties.is_empty() {
469 return finish(refusal("initial receiver class requires one native initial state without temporal claims".into(), doc.logical_length()), None);
470 }
471 let (model, host) = match self.fresh_binding(control.as_ref(), FreshMode::NextPrefix, 0)? {
472 Ok(runtime) => runtime,
473 Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
474 };
475 let trace = match Trace::decode(&model, doc) {
476 Ok(trace) => trace,
477 Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
478 };
479 let mut report =
480 crate::validate::validate_private_controlled(&model, host, &trace, control.clone())?;
481 if !report.validation.is_valid() {
482 return finish(report, None);
483 }
484 drop(trace);
487 drop(model);
488 let (model, host) =
489 match self.fresh_binding(control.as_ref(), FreshMode::NextTerminal, 0)? {
490 Ok(runtime) => runtime,
491 Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
492 };
493 let trace = match Trace::decode(&model, doc) {
494 Ok(trace) => trace,
495 Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
496 };
497 let control_scope = control
498 .as_ref()
499 .map(|control| model.evaluator.host_control(Some(control.clone())))
500 .transpose()
501 .map_err(ValidationRunError::ControlConflict)?;
502 let replay = crate::invariant_error::replay(
503 &model,
504 &trace.states[0],
505 name,
506 ec,
507 &host,
508 control.as_deref(),
509 );
510 let class = match replay {
511 Ok((validation, class)) => {
512 report.validation = validation;
513 class
514 }
515 Err(error) => {
516 return Err(match error.class() {
517 dive_eval::ErrorClass::Interrupted => ValidationRunError::Interrupted {
518 error,
519 progress: progress(),
520 },
521 dive_eval::ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
522 error,
523 progress: progress(),
524 },
525 _ => ValidationRunError::EvaluationFailure {
526 error,
527 progress: progress(),
528 },
529 });
530 }
531 };
532 let result = finish(report, class);
533 drop(control_scope);
534 drop(control);
535 result
536 }
537
538 #[allow(
547 clippy::too_many_lines,
548 reason = "fresh word and receiver runtimes retain distinct ownership"
549 )]
550 pub fn invariant_error_class(
551 &self,
552 doc: &TraceDoc,
553 control: Option<Arc<dyn dive_eval::HostControl>>,
554 ) -> Result<(Report, Option<crate::InvariantErrorClass>), crate::ValidationRunError> {
555 use crate::{Check, Ending, ValidationProgress, ValidationRunError};
556 let progress = || ValidationProgress {
557 checks_passed: 0,
558 state: Some(0),
559 check: Some(Check::Ending),
560 };
561 let poll = || {
562 control.as_ref().map_or(Ok(()), |control| {
563 control
564 .check()
565 .map_err(|error| ValidationRunError::Interrupted {
566 error: dive_eval::EvalError::interrupted(error),
567 progress: progress(),
568 })
569 })
570 };
571 let finish = |report, class| {
572 poll()?;
573 Ok((report, class))
574 };
575 poll()?;
576 let Some(Ending::InvariantError { .. }) = &doc.ending else {
577 return finish(
578 refusal(
579 "successor invariant class requires a named original cause".into(),
580 doc.logical_length(),
581 ),
582 None,
583 );
584 };
585 if doc.source != Source::Dive || doc.states.len() < 2 || !doc.properties.is_empty() {
586 return finish(refusal("successor invariant class requires a finite native successor word without temporal claims".into(), doc.logical_length()), None);
587 }
588 let (model, host) =
589 match self.fresh_binding(control.as_ref(), FreshMode::InvariantPrefix, 0)? {
590 Ok(runtime) => runtime,
591 Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
592 };
593 let trace = match Trace::decode(&model, doc) {
594 Ok(trace) => trace,
595 Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
596 };
597 let mut report =
598 crate::validate::validate_private_controlled(&model, host, &trace, control.clone())?;
599 if !report.validation.is_valid() {
600 return finish(report, None);
601 }
602 drop(trace);
605 drop(model);
606 let (model, host) =
607 match self.fresh_binding(control.as_ref(), FreshMode::InvariantTerminal, 0)? {
608 Ok(runtime) => runtime,
609 Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
610 };
611 let trace = match Trace::decode(&model, doc) {
612 Ok(trace) => trace,
613 Err(error) => return finish(shape_refusal(error, doc.logical_length()), None),
614 };
615 let control_scope = control
616 .as_ref()
617 .map(|control| model.evaluator.host_control(Some(control.clone())))
618 .transpose()
619 .map_err(ValidationRunError::ControlConflict)?;
620 let replay = crate::ordered_prefix::invariant(&model, &trace, &host, control.as_deref());
621 let class = match replay {
622 Ok((validation, class)) => {
623 if let Some(reason) = Run::private(&model, host.clone(), false).refusal() {
624 report.validation = Validation::Unsupported(reason);
625 None
626 } else {
627 report.validation = validation;
628 class
629 }
630 }
631 Err(error) => {
632 return Err(match error.class() {
633 dive_eval::ErrorClass::Interrupted => ValidationRunError::Interrupted {
634 error,
635 progress: progress(),
636 },
637 dive_eval::ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
638 error,
639 progress: progress(),
640 },
641 _ => ValidationRunError::EvaluationFailure {
642 error,
643 progress: progress(),
644 },
645 });
646 }
647 };
648 let result = finish(report, class);
649 drop(control_scope);
650 drop(control);
651 result
652 }
653
654 #[allow(
655 clippy::too_many_lines,
656 reason = "one source-admission boundary retains typed controls and endpoint dispatch order"
657 )]
658 fn read_fallible(
659 &self,
660 doc: &TraceDoc,
661 control: Option<&Arc<dyn dive_eval::HostControl>>,
662 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
663 use crate::{ValidationProgress, ValidationRunError};
664 let progress = || ValidationProgress {
665 checks_passed: 0,
666 state: None,
667 check: None,
668 };
669 let poll = || {
670 if let Some(control) = control {
671 control
672 .check()
673 .map_err(|error| ValidationRunError::Interrupted {
674 error: dive_eval::EvalError::interrupted(error),
675 progress: progress(),
676 })?;
677 }
678 Ok(())
679 };
680 let finish = |report, document| {
681 poll()?;
682 Ok((report, document))
683 };
684 poll()?;
685 if doc.source != Source::Dive {
686 return finish(
687 refusal(
688 "controlled private TLC document interpretation".into(),
689 doc.logical_length(),
690 ),
691 None,
692 );
693 }
694 if finite_word(doc) {
695 return self.read_finite_controlled(doc, control, FiniteScope::Behavior);
696 }
697 if !matches!(
698 doc.ending,
699 Some(
700 crate::Ending::TemporalStateError { .. }
701 | crate::Ending::TemporalSourceError { .. }
702 | crate::Ending::NextStateError { .. }
703 | crate::Ending::ViewSourceError { .. }
704 | crate::Ending::CandidateStateError { .. }
705 | crate::Ending::PartialNext { .. }
706 | crate::Ending::PartialInit { .. }
707 )
708 ) {
709 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);
710 }
711 let next_error = matches!(
712 doc.ending,
713 Some(
714 crate::Ending::NextStateError { .. }
715 | crate::Ending::TemporalSourceError { .. }
716 | crate::Ending::ViewSourceError { .. }
717 | crate::Ending::CandidateStateError { .. }
718 | crate::Ending::PartialNext { .. }
719 | crate::Ending::PartialInit { .. }
720 )
721 );
722 if next_error && !doc.properties.is_empty() {
723 return finish(
724 Report {
725 validation: Validation::Invalid(crate::Failure {
726 state: 0,
727 check: crate::Check::Shape,
728 detail: "finite Next error endpoint cannot claim temporal properties"
729 .into(),
730 }),
731 notes: Vec::new(),
732 length: doc.logical_length(),
733 },
734 None,
735 );
736 }
737 let mode = if matches!(doc.ending, Some(crate::Ending::PartialInit { .. })) {
738 FreshMode::NextTerminal
739 } else if next_error {
740 FreshMode::NextPrefix
741 } else {
742 FreshMode::Temporal
743 };
744 let (model, host) = match self.fresh_binding(control, mode, 0)? {
745 Ok(runtime) => runtime,
746 Err(feature) => return finish(refusal(feature, doc.logical_length()), None),
747 };
748 if matches!(doc.ending, Some(crate::Ending::PartialInit { .. })) {
749 return Self::read_initial_partial_endpoint(doc, &model, host, control);
750 }
751 if matches!(doc.ending, Some(crate::Ending::PartialNext { .. })) {
752 return self.read_partial_endpoint(doc, model, host, control);
753 }
754 let trace = match Trace::decode(&model, doc) {
755 Ok(trace) => trace,
756 Err(error) => {
757 return finish(shape_refusal(error, doc.states.len()), None);
758 }
759 };
760 if next_error {
761 return self.read_next_endpoint(doc, model, host, trace, control);
762 }
763 let report =
764 crate::validate::validate_private_controlled(&model, host, &trace, control.cloned())?;
765 finish(report, trace.to_doc(&model).ok())
766 }
767
768 fn read_finite_controlled(
769 &self,
770 doc: &TraceDoc,
771 control: Option<&Arc<dyn dive_eval::HostControl>>,
772 scope: FiniteScope,
773 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
774 if !self.recipe.has_randomness() {
775 return self.read_finite_attempt(doc, control, scope, None);
776 }
777 let choices = Arc::new(crate::choices::Search::default());
778 for _ in 0..crate::choices::MAX_ATTEMPTS {
779 if let Some(control) = control {
780 control
781 .check()
782 .map_err(|error| crate::ValidationRunError::Interrupted {
783 error: dive_eval::EvalError::interrupted(error),
784 progress: crate::ValidationProgress {
785 checks_passed: 0,
786 state: None,
787 check: None,
788 },
789 })?;
790 }
791 let result = self.read_finite_attempt(doc, control, scope, Some(&choices))?;
795 if !matches!(result.0.validation, Validation::Invalid(_))
796 || choices.refusal().is_some()
797 || !choices.advance()
798 {
799 return Ok(result);
800 }
801 }
802 Err(crate::ValidationRunError::ResourceLimit {
803 error: dive_eval::EvalError::resource_limit(
804 "independent finite random choice attempts",
805 ),
806 progress: crate::ValidationProgress {
807 checks_passed: 0,
808 state: None,
809 check: None,
810 },
811 })
812 }
813
814 fn read_finite_attempt(
815 &self,
816 doc: &TraceDoc,
817 control: Option<&Arc<dyn dive_eval::HostControl>>,
818 scope: FiniteScope,
819 choices: Option<&Arc<crate::choices::Search>>,
820 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
821 for initial in [true, false] {
822 if let Some(choices) = choices {
823 choices.rewind();
824 }
825 let (model, host) = match self.fresh_binding_choices(
826 control,
827 if scope == FiniteScope::SampledDeadlock {
828 FreshMode::FiniteSuccessors(initial)
829 } else {
830 FreshMode::Finite(initial)
831 },
832 0,
833 choices.cloned(),
834 )? {
835 Ok(runtime) => runtime,
836 Err(feature) => return Ok((refusal(feature, doc.logical_length()), None)),
837 };
838 if scope == FiniteScope::Sample
839 && (!model.implied_temporals.is_empty()
840 || model.view.is_some()
841 || model.symmetry.is_some()
842 || model.alias.is_some()
843 || !matches!(&model.postconditions, Ok(postconditions) if postconditions.is_empty()))
844 {
845 return Ok((refusal("finite sample validation does not discharge temporal PROPERTY, VIEW, symmetry, ALIAS or POSTCONDITION obligations".into(), doc.logical_length()), None));
846 }
847 let trace = match Trace::decode(&model, doc) {
848 Ok(trace) => trace,
849 Err(error) => {
850 return Ok((
851 Report {
852 validation: Validation::Invalid(crate::Failure {
853 state: error.state.unwrap_or(0),
854 check: crate::Check::Shape,
855 detail: error.detail,
856 }),
857 notes: Vec::new(),
858 length: doc.logical_length(),
859 },
860 None,
861 ));
862 }
863 };
864 let (report, retry) = crate::validate::validate_finite_private_controlled(
865 &model,
866 &host,
867 &trace,
868 initial,
869 control.cloned(),
870 scope,
871 )?;
872 if !retry {
873 return Ok((report, trace.to_doc(&model).ok()));
874 }
875 }
876 Ok((
877 refusal(
878 "finite initial replay is unproved".into(),
879 doc.logical_length(),
880 ),
881 None,
882 ))
883 }
884
885 fn read_next_endpoint(
886 &self,
887 doc: &TraceDoc,
888 model: Model,
889 host: Arc<TraceHost>,
890 trace: Trace,
891 control: Option<&Arc<dyn dive_eval::HostControl>>,
892 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
893 use crate::{ValidationProgress, ValidationRunError};
894 let (prefix, checks_passed) = crate::validate::validate_next_prefix_controlled(
895 &model,
896 host,
897 &trace,
898 control.cloned(),
899 )?;
900 let finish_next = |report, document| {
901 if let Some(control) = control {
902 control
903 .check()
904 .map_err(|error| ValidationRunError::Interrupted {
905 error: dive_eval::EvalError::interrupted(error),
906 progress: ValidationProgress {
907 checks_passed,
908 state: doc.states.len().checked_sub(1),
909 check: Some(crate::Check::Ending),
910 },
911 })?;
912 }
913 Ok((report, document))
914 };
915 if prefix.validation != Validation::Valid {
916 return finish_next(prefix, trace.to_doc(&model).ok());
917 }
918 drop(trace);
921 drop(model);
922 let (model, host) =
923 match self.fresh_binding(control, FreshMode::NextTerminal, checks_passed)? {
924 Ok(runtime) => runtime,
925 Err(feature) => return finish_next(refusal(feature, doc.logical_length()), None),
926 };
927 let trace = match Trace::decode(&model, doc) {
928 Ok(trace) => trace,
929 Err(error) => return finish_next(shape_refusal(error, doc.states.len()), None),
930 };
931 let Some(state) = trace.states.last() else {
932 return finish_next(refusal("Next endpoint has no state".into(), 0), None);
933 };
934 let mut report = crate::validate::replay_next_controlled(
935 &model,
936 host,
937 &trace,
938 state,
939 checks_passed,
940 control.cloned(),
941 )?;
942 report.notes.extend(prefix.notes);
943 let plain = trace.to_doc(&model).ok();
944 finish_next(report, plain)
945 }
946
947 fn read_partial_endpoint(
948 &self,
949 doc: &TraceDoc,
950 model: Model,
951 host: Arc<TraceHost>,
952 control: Option<&Arc<dyn dive_eval::HostControl>>,
953 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
954 let invalid = |detail: &str| {
955 (
956 Report {
957 validation: Validation::Invalid(crate::Failure {
958 state: doc.states.len(),
959 check: crate::Check::Shape,
960 detail: detail.into(),
961 }),
962 notes: Vec::new(),
963 length: doc.logical_length(),
964 },
965 None,
966 )
967 };
968 if matches!(&doc.ending,Some(crate::Ending::PartialNext {endpoint}) if endpoint.initial()) {
969 return Ok(invalid("partial Next descriptor has an Init phase"));
970 }
971 if doc.states.is_empty() {
972 return Ok(invalid("partial Next needs a complete source prefix"));
973 }
974 if doc
975 .length
976 .is_some_and(|length| length != doc.logical_length())
977 {
978 return Ok(invalid(
979 "logical word length must include the partial terminal candidate",
980 ));
981 }
982 let mut prefix = doc.clone();
986 prefix.length = Some(prefix.states.len());
987 let trace = match Trace::decode(&model, &prefix) {
988 Ok(trace) => trace,
989 Err(error) => return Ok(invalid(&error.detail)),
990 };
991 let (mut report, passed) = crate::validate::validate_next_prefix_controlled(
992 &model,
993 host,
994 &trace,
995 control.cloned(),
996 )?;
997 report.length = doc.logical_length();
998 if report.validation != Validation::Valid {
999 return Ok((report, None));
1000 }
1001 drop(trace);
1002 drop(model);
1003 let (model, host) = match self.fresh_binding(control, FreshMode::NextTerminal, passed)? {
1004 Ok(runtime) => runtime,
1005 Err(feature) => return Ok((refusal(feature, doc.logical_length()), None)),
1006 };
1007 let trace = match Trace::decode(&model, &prefix) {
1008 Ok(trace) => trace,
1009 Err(error) => return Ok(invalid(&error.detail)),
1010 };
1011 let Some(crate::Ending::PartialNext { endpoint }) = &doc.ending else {
1012 return Ok(invalid("missing partial terminal descriptor"));
1013 };
1014 let report = crate::validate::replay_partial_controlled(
1015 &model,
1016 host,
1017 &trace,
1018 endpoint,
1019 passed,
1020 control.cloned(),
1021 )?;
1022 Ok((report, Some(doc.clone())))
1023 }
1024
1025 fn read_initial_partial_endpoint(
1026 doc: &TraceDoc,
1027 model: &Model,
1028 host: Arc<TraceHost>,
1029 control: Option<&Arc<dyn dive_eval::HostControl>>,
1030 ) -> Result<(Report, Option<TraceDoc>), crate::ValidationRunError> {
1031 let invalid = |detail: &str| {
1032 (
1033 Report {
1034 validation: Validation::Invalid(crate::Failure {
1035 state: 0,
1036 check: crate::Check::Shape,
1037 detail: detail.into(),
1038 }),
1039 notes: Vec::new(),
1040 length: doc.logical_length(),
1041 },
1042 None,
1043 )
1044 };
1045 if !doc.states.is_empty()
1046 || !doc.labels.is_empty()
1047 || doc.length.is_some_and(|length| length != 1)
1048 {
1049 return Ok(invalid(
1050 "partial Init has no complete prefix and logical length one",
1051 ));
1052 }
1053 let variables = crate::variables(model);
1054 let header: std::collections::BTreeSet<_> = doc.variables.iter().collect();
1055 if header.len() != variables.len()
1056 || doc.variables.len() != variables.len()
1057 || variables.iter().any(|name| !header.contains(name))
1058 {
1059 return Ok(invalid(
1060 "partial Init variable header differs from the model",
1061 ));
1062 }
1063 let Some(crate::Ending::PartialInit { endpoint }) = &doc.ending else {
1064 return Ok(invalid("missing Init partial descriptor"));
1065 };
1066 if !endpoint.initial() {
1067 return Ok(invalid("partial Init descriptor has a Next phase"));
1068 }
1069 let report = crate::validate::replay_initial_partial_controlled(
1070 model,
1071 host,
1072 endpoint,
1073 control.cloned(),
1074 )?;
1075 Ok((report, Some(doc.clone())))
1076 }
1077
1078 fn fresh_binding(
1079 &self,
1080 control: Option<&Arc<dyn dive_eval::HostControl>>,
1081 mode: FreshMode,
1082 checks_passed: u64,
1083 ) -> Result<Result<(Model, Arc<TraceHost>), String>, crate::ValidationRunError> {
1084 self.fresh_binding_choices(control, mode, checks_passed, None)
1085 }
1086
1087 fn fresh_binding_choices(
1088 &self,
1089 control: Option<&Arc<dyn dive_eval::HostControl>>,
1090 mode: FreshMode,
1091 checks_passed: u64,
1092 choices: Option<Arc<crate::choices::Search>>,
1093 ) -> Result<Result<(Model, Arc<TraceHost>), String>, crate::ValidationRunError> {
1094 use crate::{ValidationProgress, ValidationRunError};
1095 let progress = || ValidationProgress {
1096 checks_passed,
1097 state: None,
1098 check: None,
1099 };
1100 let poll = || {
1101 if let Some(control) = control {
1102 control
1103 .check()
1104 .map_err(|error| ValidationRunError::Interrupted {
1105 error: dive_eval::EvalError::interrupted(error),
1106 progress: progress(),
1107 })?;
1108 }
1109 Ok(())
1110 };
1111 poll()?;
1112 let source_actions = (choices.is_some() && matches!(mode, FreshMode::Finite(_)))
1113 || matches!(mode, FreshMode::FiniteSuccessors(_));
1114 let host = match self.startup_host(choices) {
1115 Ok(host) => host,
1116 Err(error) => return Ok(Err(error)),
1117 };
1118 host.startup.store(
1119 matches!(
1120 mode,
1121 FreshMode::Temporal | FreshMode::Finite(true) | FreshMode::FiniteSuccessors(true)
1122 ),
1123 Ordering::Relaxed,
1124 );
1125 host.next_error.store(
1130 matches!(mode, FreshMode::NextPrefix | FreshMode::NextTerminal),
1131 Ordering::Relaxed,
1132 );
1133 let binding = if source_actions
1134 || matches!(mode, FreshMode::NextTerminal | FreshMode::InvariantTerminal)
1135 {
1136 self.recipe
1137 .bind_next_fallible(host.clone(), control.cloned())
1138 } else {
1139 self.recipe.bind_fallible(host.clone(), control.cloned())
1140 };
1141 let model = match binding {
1142 Ok(model) => model,
1143 Err(dive_model::ControlledBindError::Interrupted { error, .. }) => {
1144 return Err(ValidationRunError::Interrupted {
1145 error,
1146 progress: progress(),
1147 });
1148 }
1149 Err(dive_model::ControlledBindError::ControlConflict { error, .. }) => {
1150 return Err(ValidationRunError::ControlConflict(error));
1151 }
1152 Err(dive_model::ControlledBindError::EvaluationFailure { error, .. }) => {
1153 return Err(if error.class() == dive_eval::ErrorClass::ResourceLimit {
1154 ValidationRunError::ResourceLimit {
1155 error,
1156 progress: progress(),
1157 }
1158 } else {
1159 ValidationRunError::EvaluationFailure {
1160 error,
1161 progress: progress(),
1162 }
1163 });
1164 }
1165 Err(dive_model::ControlledBindError::Binding(failure)) => {
1166 if failure.error.kind == dive_model::ErrorKind::Bug {
1167 return Err(ValidationRunError::BindingFailure {
1168 error: failure.error,
1169 progress: progress(),
1170 });
1171 }
1172 return Ok(Err(failure.error.to_string()));
1173 }
1174 };
1175 if let Err(error) = host.finish_input_binding(&model) {
1176 return Ok(Err(error));
1177 }
1178 poll()?;
1179 if let Some(mut config) = self.config.clone() {
1180 config.deadlock = model.settings.check_deadlock;
1181 model.evaluator.intern_checker_names();
1182 model.evaluator.intern_bfs_config(&config);
1183 *host
1184 .run_config
1185 .lock()
1186 .unwrap_or_else(PoisonError::into_inner) = Some(config);
1187 }
1188 poll()?;
1189 Ok(Ok((model, host)))
1190 }
1191
1192 pub(crate) fn interpretation(&self, doc: &TraceDoc) -> (Report, Option<TraceDoc>) {
1193 self.plain(doc, true)
1194 }
1195}
1196
1197fn finite_word(doc: &TraceDoc) -> bool {
1198 doc.properties.is_empty()
1199 && matches!(
1200 doc.ending,
1201 None | Some(
1202 crate::Ending::Behavior
1203 | crate::Ending::Invariant(_)
1204 | crate::Ending::Property(_)
1205 | crate::Ending::Deadlock
1206 )
1207 )
1208}
1209
1210fn refusal(feature: String, length: usize) -> Report {
1211 Report {
1212 validation: Validation::Unsupported(feature),
1213 notes: Vec::new(),
1214 length,
1215 }
1216}
1217
1218fn shape_refusal(error: crate::ShapeError, length: usize) -> Report {
1219 Report {
1220 validation: Validation::Invalid(crate::Failure {
1221 state: error.state.unwrap_or(0),
1222 check: crate::Check::Shape,
1223 detail: error.detail,
1224 }),
1225 notes: Vec::new(),
1226 length,
1227 }
1228}