Skip to main content

dive_api/
temporal.rs

1//! Bounded final temporal checking for Rust callers.
2//!
3//! This API checks the supported pure temporal subset and independently validates
4//! every periodic counterexample before returning it as a violation. It binds a
5//! fresh model for each run and for validation. It selects a deterministic short
6//! lasso, including with TLC value semantics. Eligible ordinary [`crate::check_file`]
7//! requests use final checking in the TLC profile and deterministic completed-level
8//! checks in the dive profile. Explicit final/short selection remains unchanged;
9//! neither schedule reproduces TLC's periodic timing or exact lasso selection.
10
11use std::sync::Arc;
12use std::time::{Duration, Instant};
13
14use dive_config::ModelConfig;
15use dive_ir::Ir;
16use dive_liveness::analyze::periodic::{Checks, PrefixCandidate};
17use dive_liveness::analyze::{AnalysisError, Candidate, GraphLabelPolicy, Limits};
18use dive_liveness::product::AcceptancePolicy;
19use dive_model::{BindOptions, Model};
20use dive_runtime::{CheckOptions, CheckResult, capture};
21use dive_trace::{
22    Ending, Report as ValidationReport, Trace, TraceDoc, Validation, ValidationProgress,
23    ValidationRunError,
24};
25
26mod native;
27#[cfg(test)]
28pub(crate) use native::core_analysis;
29pub use native::{ValidatedNativeCounterexample, ValidatedNativePrefix};
30pub(crate) use native::{
31    core_capture_stop, core_native_report, core_source_row_failure, core_startup_stop,
32};
33
34/// The outcome of a bounded temporal run on Core, distinguishing real prefixes.
35#[derive(Clone, Debug)]
36#[non_exhaustive]
37pub enum Outcome {
38    /// All properties hold after complete native capture, without retained rows.
39    NativeHolds(Box<capture::CompleteEvidence>),
40    /// Independently validated native word with complete producer facts.
41    NativeViolation(Box<ValidatedNativeCounterexample>),
42    /// Independently validated native word with unfinished-prefix facts.
43    NativePrefixViolation(Box<ValidatedNativePrefix>),
44    /// The ordinary safety result when no properties are configured, when
45    /// configured properties bind entirely to safety roles, or a safety stop
46    /// before temporal checking completes. This preserves its verdict,
47    /// statistics, output and counterexample; unsupported features and
48    /// resource limits are never success.
49    Safety(Box<CheckResult>),
50}
51
52/// Configured analysis owners, independent of whether execution reached them.
53/// Existing APIs retain their exact caller-supplied logical cell ceilings.
54#[derive(Clone, Copy, Debug)]
55pub struct Configuration {
56    /// Existing formula, capture, product and attribution/word bounds.
57    pub limits: Limits,
58    /// Acceptance-buffer admission, independent of graph-label admission.
59    pub acceptance: AcceptancePolicy,
60    /// Admission for graph labels only; attribution and word bounds stay finite.
61    pub graph_labels: GraphLabelPolicy,
62}
63
64pub(crate) fn file_configuration() -> Configuration {
65    let mut limits = Limits::default();
66    // File requests use machine-index capacity; explicit Rust ceilings stay exact.
67    limits.product.vertices = usize::MAX;
68    Configuration {
69        limits,
70        acceptance: AcceptancePolicy::compact_default(),
71        graph_labels: GraphLabelPolicy::NoCellLimit,
72    }
73}
74
75/// Ordinary core file requests use actual run budgets and checked machine layouts.
76/// Planning limits and explicit library/reference limits retain their exact scope.
77pub(crate) fn core_file_configuration() -> Configuration {
78    let mut configuration = file_configuration();
79    let limits = &mut configuration.limits;
80    limits.capture = capture::Limits {
81        states: usize::MAX,
82        edges: usize::MAX,
83        generated: u64::MAX,
84        // The explorer retains fixed eight-source waves. Its per-emission
85        // allocation and actual budget checks bound provisional growth.
86        successors_per_unit: u64::MAX,
87    };
88    limits.product.vertices = usize::MAX;
89    limits.product.edges = usize::MAX;
90    limits.product.acceptance_cells = usize::MAX;
91    limits.product.steps = usize::MAX;
92    limits.atom_cells = usize::MAX;
93    configuration.acceptance = AcceptancePolicy::Buffers {
94        bytes: usize::MAX,
95        work: usize::MAX,
96    };
97    configuration
98}
99
100/// A temporal result with total binding, exploration and validation time.
101#[derive(Clone, Debug)]
102pub struct Report {
103    symmetry_liveness: Option<dive_model::SymmetryLivenessResolution>,
104    outcome: Outcome,
105    options: CheckOptions,
106    elapsed: Duration,
107    periodic: Option<Checks>,
108    memory_samples: Option<dive_runtime::budget::MemorySamples>,
109    configuration: Option<Configuration>,
110}
111impl Report {
112    /// Original declared symmetry and effective whole-run policy after binding.
113    /// `None` means no successfully bound model is available; this is not proof.
114    #[must_use]
115    pub fn symmetry_liveness(&self) -> Option<&dive_model::SymmetryLivenessResolution> {
116        self.symmetry_liveness.as_ref()
117    }
118
119    /// Actual configured owner limits and policies. Their presence establishes
120    /// neither execution nor completion; safety dispatch can leave them unused.
121    #[must_use]
122    pub const fn configuration(&self) -> Option<Configuration> {
123        self.configuration
124    }
125    /// Actual observations when this temporal call returned. Nested already-armed
126    /// calls return a snapshot; the enclosing file report includes its owner's
127    /// later terminal observation.
128    #[must_use]
129    pub const fn memory_samples(&self) -> Option<dive_runtime::budget::MemorySamples> {
130        self.memory_samples
131    }
132
133    /// The temporal outcome or the complete safety stop.
134    #[must_use]
135    pub fn outcome(&self) -> &Outcome {
136        &self.outcome
137    }
138    /// Run settings, including the seed and profile, even on a safety stop.
139    #[must_use]
140    pub fn options(&self) -> &CheckOptions {
141        &self.options
142    }
143    /// Actual deterministic checks, absent for the final-only schedule.
144    #[must_use]
145    pub const fn periodic(&self) -> Option<Checks> {
146        self.periodic
147    }
148    /// Actual schedule used, independent of the value-semantics profile.
149    #[must_use]
150    pub const fn lncheck(&self) -> &'static str {
151        if self.periodic.is_some() {
152            "deterministic"
153        } else {
154            "final"
155        }
156    }
157    /// Total wall-clock time, including independent validation.
158    #[must_use]
159    pub fn elapsed(&self) -> Duration {
160        self.elapsed
161    }
162}
163
164/// Applies the outer owner's terminal observation after independent replay.
165pub(crate) fn finish_report(
166    report: &mut Report,
167    finished: Result<
168        Option<dive_runtime::budget::Exhausted>,
169        dive_runtime::budget::MeasurementError,
170    >,
171    elapsed: Duration,
172) -> Option<Failure> {
173    report.elapsed = elapsed;
174    let error = match finished {
175        Ok(Some(exhausted)) => Error::Analysis(AnalysisError::Stopped(Box::new(
176            exhausted.during(dive_runtime::budget::Phase::Finalization),
177        ))),
178        Err(error) => Error::Analysis(AnalysisError::BudgetMeasurement(error)),
179        Ok(None) => return None,
180    };
181    match &mut report.outcome {
182        Outcome::NativeHolds(capture) => {
183            let mut failure = Failure::before(
184                error,
185                Stage::Analysis(dive_liveness::analyze::Stage::Finalization),
186            );
187            failure.exploration = Some(Box::new(native::facts(
188                capture.safety_result(),
189                capture.stats(),
190            )));
191            failure.elapsed = report.elapsed;
192            failure.periodic = report.periodic.map(Box::new);
193            failure.configuration = report.configuration.map(Box::new);
194            failure.symmetry_liveness = report.symmetry_liveness.clone().map(Box::new);
195            Some(failure)
196        }
197        Outcome::Safety(result) => {
198            dive_runtime::budget::finish_result(
199                result,
200                finished,
201                dive_runtime::budget::Phase::Finalization,
202            );
203            None
204        }
205        // These witnesses already passed fresh independent validation.
206        Outcome::NativeViolation(_) | Outcome::NativePrefixViolation(_) => None,
207    }
208}
209
210/// An explicit refusal, evaluation error, resource bound or internal inconsistency. No error
211/// variant is evidence of a successful model check.
212#[derive(Clone, Debug)]
213#[non_exhaustive]
214pub enum Error {
215    /// Binding failed, preserving diagnostics and startup output.
216    Binding(Box<dive_model::Failure>),
217    /// A graph-independent native candidate failed independent validation.
218    NativeValidation {
219        /// The unvalidated selected word, without retained graph storage.
220        word: Box<dive_liveness::analyze::periodic::external::NativeWord>,
221        /// Actual independent validation result, which is not valid.
222        report: ValidationReport,
223    },
224    /// Planning, product construction, atom evaluation or an explicit bound.
225    Analysis(AnalysisError),
226    /// The independent validator cannot decide the candidate, or refutes it.
227    /// Invalid candidates indicate an internal error and are never violations.
228    Validation {
229        /// The candidate whose claim could not be certified.
230        candidate: Box<Candidate>,
231        /// Independent validation details.
232        report: ValidationReport,
233    },
234    /// Independent validation refused or refuted an incomplete-prefix word.
235    PrefixValidation {
236        /// Actual prefix candidate, never a completed graph.
237        candidate: Box<PrefixCandidate>,
238        /// Actual independent validator report.
239        report: ValidationReport,
240    },
241    /// Independent finite-error endpoint validation, distinct from a lasso.
242    EndpointValidation {
243        /// Actual independently computed valid/invalid/unsupported result.
244        report: ValidationReport,
245    },
246    /// Validation exhausted an actual resource without producing a verdict.
247    ValidationResource(dive_eval::EvalError),
248    /// A value could not be represented in the tagged trace document.
249    Document(String),
250    /// The evaluation thread failed to start or panicked.
251    Thread(String),
252}
253impl Error {
254    /// Stable diagnostic code. An invalid independent result has a separate
255    /// internal-error code from an unsupported validation result.
256    #[must_use]
257    pub fn code(&self) -> &'static str {
258        match self {
259            Self::Binding(_) => "DIVE-A0030",
260            Self::Analysis(e) => e.code(),
261            Self::NativeValidation { report, .. }
262            | Self::Validation { report, .. }
263            | Self::PrefixValidation { report, .. }
264            | Self::EndpointValidation { report }
265                if matches!(report.validation, Validation::Invalid(_)) =>
266            {
267                "DIVE-A0031"
268            }
269            Self::NativeValidation { .. }
270            | Self::Validation { .. }
271            | Self::PrefixValidation { .. }
272            | Self::EndpointValidation { .. } => "DIVE-A0032",
273            Self::ValidationResource(_) => "DIVE-L0034",
274            Self::Document(_) => "DIVE-A0033",
275            Self::Thread(_) => "DIVE-A0034",
276        }
277    }
278}
279impl std::fmt::Display for Error {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        match self {
282            Self::Binding(e) => e.fmt(f),
283            Self::Analysis(e) => e.fmt(f),
284            Self::NativeValidation { report, .. }
285            | Self::Validation { report, .. }
286            | Self::PrefixValidation { report, .. }
287            | Self::EndpointValidation { report } => write!(
288                f,
289                "{}: temporal candidate did not pass independent validation: {:?}",
290                self.code(),
291                report.validation
292            ),
293            Self::ValidationResource(error) => error.fmt(f),
294            Self::Document(e) => write!(f, "{}: temporal trace document: {e}", self.code()),
295            Self::Thread(e) => write!(f, "{}: temporal evaluation thread: {e}", self.code()),
296        }
297    }
298}
299impl std::error::Error for Error {}
300
301/// Stage reached by a temporal run that produced no verdict.
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
303#[non_exhaustive]
304pub enum Stage {
305    /// Budget admission before model binding or capture starts.
306    Startup,
307    /// Initial model binding; no capture started.
308    Binding,
309    /// A known stage of final temporal analysis.
310    Analysis(dive_liveness::analyze::Stage),
311    /// Independent validation, including binding a fresh validation model.
312    Validation,
313    /// Conversion to the tagged trace document.
314    Document,
315    /// A thread failure prevented recovery of execution evidence.
316    Unknown,
317}
318impl Stage {
319    /// Stable execution-stage name for structured reports.
320    #[must_use]
321    pub const fn name(self) -> &'static str {
322        match self {
323            Self::Startup => "check-startup",
324            Self::Binding => "binding",
325            Self::Analysis(stage) => stage.name(),
326            Self::Validation => "validation",
327            Self::Document => "document",
328            Self::Unknown => "unknown",
329        }
330    }
331}
332
333/// A temporal failure with retained execution facts, never a verdict, as
334/// [`crate::CheckReport::temporal_failure`] returns it.
335#[derive(Clone, Debug)]
336pub struct Failure {
337    symmetry_liveness: Option<Box<dive_model::SymmetryLivenessResolution>>,
338    error: Box<Error>,
339    stage: Stage,
340    exploration: Option<Box<dive_liveness::analyze::ExplorationEvidence>>,
341    elapsed: Duration,
342    action_evaluation: Option<Box<dive_liveness::analyze::ActionEvaluation>>,
343    state_evaluation: Option<Box<dive_liveness::analyze::StateEvaluation>>,
344    row_validation: Option<Box<RowValidation>>,
345    validation_progress: Option<Box<ValidationProgress>>,
346    incomplete: bool,
347    periodic: Option<Box<Checks>>,
348    configuration: Option<Box<Configuration>>,
349    binding_output: Vec<dive_model::Message>,
350}
351
352#[derive(Clone, Debug)]
353struct RowValidation {
354    document: TraceDoc,
355    report: ValidationReport,
356}
357
358impl Failure {
359    pub(crate) fn capture_row_error(
360        &self,
361    ) -> Option<(&dive_eval::EvalError, &TraceDoc, &ValidationReport)> {
362        let state = self.row_candidate()?;
363        let validation = self.row_validation.as_deref()?;
364        (validation.report.validation == Validation::Valid).then_some((
365            state.core_cause()?,
366            &validation.document,
367            &validation.report,
368        ))
369    }
370
371    fn row_candidate(&self) -> Option<&dive_liveness::analyze::StateEvaluation> {
372        let state = self.state_evaluation()?;
373        let cause = state.core_cause()?;
374        let result = match state.site() {
375            dive_liveness::analyze::StateEvaluationSite::CaptureRow
376                if cause.is_eval_exception()
377                    && matches!(
378                        cause.ec(),
379                        dive_eval::Ec::DivisionByZero | dive_eval::Ec::ModuleEvaluating
380                    ) =>
381            {
382                state.capture_row()?.result()
383            }
384            dive_liveness::analyze::StateEvaluationSite::CaptureSourceRow
385                if cause.exception_kind() == Some(dive_eval::ExceptionKind::ToolRuntime)
386                    && cause.ec() == dive_eval::Ec::General =>
387            {
388                state.capture_source_row()?.result()
389            }
390            _ => return None,
391        };
392        (cause.class() == dive_eval::ErrorClass::Eval
393            && cause.origin().is_some()
394            && result.stats.is_some()
395            && result
396                .counterexample
397                .as_ref()
398                .is_some_and(|path| !path.states.is_empty()))
399        .then_some(state)
400    }
401    /// Original declared symmetry and effective whole-run policy after binding.
402    /// `None` means no successfully bound model is available; this is not proof.
403    #[must_use]
404    pub fn symmetry_liveness(&self) -> Option<&dive_model::SymmetryLivenessResolution> {
405        self.symmetry_liveness.as_deref()
406    }
407
408    /// Actual configured owner limits when admitted by the enclosing API.
409    /// Internal failures without a configuration retain `None`, never guessed
410    /// default settings. This does not certify that any bound was exercised.
411    #[must_use]
412    pub fn configuration(&self) -> Option<Configuration> {
413        self.configuration.as_deref().copied()
414    }
415    pub(crate) fn before(error: Error, stage: Stage) -> Self {
416        Self {
417            error: Box::new(error),
418            stage,
419            exploration: None,
420            elapsed: Duration::ZERO,
421            action_evaluation: None,
422            state_evaluation: None,
423            row_validation: None,
424            validation_progress: None,
425            incomplete: false,
426            periodic: None,
427            configuration: None,
428            binding_output: Vec::new(),
429            symmetry_liveness: None,
430        }
431    }
432    /// The actual typed active action-label error, when one occurred.
433    /// This does not claim TLC's error ordering across multiple properties.
434    #[must_use]
435    pub fn action_evaluation(&self) -> Option<&dive_liveness::analyze::ActionEvaluation> {
436        self.action_evaluation.as_deref()
437    }
438    /// Original state-atom cause and postcapture/periodic/attribution site.
439    /// This is not certified TLC demand or a new evaluation-error verdict.
440    ///
441    /// ```
442    /// # fn example(failure: &dive_api::temporal::Failure) {
443    /// if let Some(state) = failure.state_evaluation() {
444    ///     let _actual_site = state.site();
445    ///     let _original_cause = state.core_cause();
446    /// }
447    /// # }
448    /// ```
449    #[must_use]
450    pub fn state_evaluation(&self) -> Option<&dive_liveness::analyze::StateEvaluation> {
451        self.state_evaluation.as_deref()
452    }
453    /// Output retained from the binding invocation which failed.
454    ///
455    /// For validation rebinding this is replay evidence, not additional output
456    /// from the original execution. Report writers retain the capture's output.
457    #[must_use]
458    pub fn binding_output(&self) -> &[dive_model::Message] {
459        match self.error() {
460            Error::Binding(failure) => &failure.output,
461            Error::Analysis(AnalysisError::StartupTautology { output }) => output,
462            _ => &self.binding_output,
463        }
464    }
465
466    /// Actual progress from an interrupted independent validation invocation.
467    #[must_use]
468    pub fn validation_progress(&self) -> Option<&ValidationProgress> {
469        self.validation_progress.as_deref()
470    }
471    /// Original diagnostic, preserving its code and classification.
472    #[must_use]
473    pub fn error(&self) -> &Error {
474        &self.error
475    }
476    /// Stage reached before the failure.
477    #[must_use]
478    pub const fn stage(&self) -> Stage {
479        self.stage
480    }
481    /// Actual capture facts, when available. Consult [`Self::capture_completed`]
482    /// to distinguish a committed prefix from complete exploration.
483    #[must_use]
484    pub fn exploration(&self) -> Option<&dive_liveness::analyze::ExplorationEvidence> {
485        self.exploration.as_deref()
486    }
487    /// Total time including binding, exploration and any validation work.
488    #[must_use]
489    pub const fn elapsed(&self) -> Duration {
490        self.elapsed
491    }
492    /// Whether capture completed. Unknown thread failures yield `None`, not
493    /// a claim that no work ran.
494    #[must_use]
495    pub fn capture_completed(&self) -> Option<bool> {
496        if self.incomplete {
497            Some(false)
498        } else if self.exploration.is_some() {
499            Some(true)
500        } else if matches!(
501            self.stage,
502            Stage::Startup
503                | Stage::Binding
504                | Stage::Analysis(dive_liveness::analyze::Stage::Planning)
505        ) {
506            Some(false)
507        } else {
508            None
509        }
510    }
511    /// Actual deterministic scheduling work before this failure, if selected.
512    #[must_use]
513    pub fn periodic(&self) -> Option<Checks> {
514        self.periodic.as_deref().copied()
515    }
516    /// Actual execution width where known. Pre-search refusals prove zero;
517    /// unobserved thread failures do not.
518    #[must_use]
519    pub fn workers(&self, requested: usize) -> Option<dive_runtime::Workers> {
520        if let Some(evidence) = &self.exploration {
521            Some(evidence.workers.clone())
522        } else if self.capture_completed() == Some(false) {
523            Some(dive_runtime::Workers {
524                requested,
525                used: 0,
526                sequential: false,
527                reason: Some("no search ran".into()),
528            })
529        } else {
530            None
531        }
532    }
533}
534impl std::fmt::Display for Failure {
535    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
536        self.error.fmt(f)
537    }
538}
539impl std::error::Error for Failure {
540    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
541        Some(&*self.error)
542    }
543}
544
545#[cfg(test)]
546fn bind(ir: &Arc<Ir>, config: &ModelConfig, options: &CheckOptions) -> Result<Model, Error> {
547    if options.seen_disk.is_some() {
548        return Err(Error::Analysis(AnalysisError::Unsupported(
549            "disk seen-state retention with temporal capture is not implemented",
550        )));
551    }
552    let mode = if options.profile == dive_eval::Profile::Tlc {
553        dive_stdlib::random::RandomMode::Tlc
554    } else {
555        dive_stdlib::random::RandomMode::Dive
556    };
557    let host = Arc::new(dive_stdlib::host::RunHost::new(
558        dive_stdlib::random::Streams::new(options.seed, mode),
559        None,
560    ));
561    dive_model::bind(
562        ir.clone(),
563        config,
564        &BindOptions {
565            eval: options.eval,
566            symmetry_liveness: options.symmetry_liveness,
567            no_deadlock: options.no_deadlock,
568            host: Some(host),
569        },
570    )
571    .map_err(Error::Binding)
572}
573
574fn controlled_binding_failure(
575    failure: dive_model::ControlledBindError,
576    control: &dive_runtime::budget::EvaluationControl,
577) -> Failure {
578    let output = failure.output().to_vec();
579    let error = match failure {
580        dive_model::ControlledBindError::Binding(failure) => Error::Binding(failure),
581        dive_model::ControlledBindError::Interrupted { error, .. } => {
582            Error::Analysis(match control.verdict(&error) {
583                Some(dive_runtime::Verdict::Stopped(stopped)) => AnalysisError::Stopped(stopped),
584                Some(dive_runtime::Verdict::BudgetMeasurement { error }) => {
585                    AnalysisError::BudgetMeasurement(error)
586                }
587                _ => AnalysisError::Inconsistent(
588                    "binding interruption lacks matching active resource authority",
589                ),
590            })
591        }
592        dive_model::ControlledBindError::EvaluationFailure { error, .. } => match error.class() {
593            dive_eval::ErrorClass::ResourceLimit => Error::ValidationResource(error),
594            _ => Error::Thread(format!("intrinsic binding evaluator failure: {error}")),
595        },
596        dive_model::ControlledBindError::ControlConflict { .. } => Error::Analysis(
597            AnalysisError::Inconsistent("binding control ownership conflict"),
598        ),
599    };
600    let mut failure = Failure::before(error, Stage::Binding);
601    failure.binding_output = output;
602    failure
603}
604
605fn bind_controlled(
606    ir: &Arc<Ir>,
607    config: &ModelConfig,
608    options: &CheckOptions,
609    control: &Arc<dive_runtime::budget::EvaluationControl>,
610) -> Result<Model, Failure> {
611    if options.seen_disk.is_some() {
612        return Err(Failure::before(
613            Error::Analysis(AnalysisError::Unsupported(
614                "disk seen-state retention with temporal capture is not implemented",
615            )),
616            Stage::Binding,
617        ));
618    }
619    let mode = if options.profile == dive_eval::Profile::Tlc {
620        dive_stdlib::random::RandomMode::Tlc
621    } else {
622        dive_stdlib::random::RandomMode::Dive
623    };
624    let host = Arc::new(dive_stdlib::host::RunHost::new(
625        dive_stdlib::random::Streams::new(options.seed, mode),
626        None,
627    ));
628    dive_model::bind_controlled(
629        ir.clone(),
630        config,
631        &BindOptions {
632            eval: options.eval,
633            symmetry_liveness: options.symmetry_liveness,
634            no_deadlock: options.no_deadlock,
635            host: Some(host),
636        },
637        control.clone(),
638    )
639    .map_err(|failure| controlled_binding_failure(failure, control))
640}
641
642fn validation_binding_failure(mut failure: Failure) -> Failure {
643    failure.stage = Stage::Validation;
644    if matches!(
645        failure.error(),
646        Error::Analysis(AnalysisError::Stopped(_) | AnalysisError::BudgetMeasurement(_))
647    ) {
648        failure.validation_progress = Some(Box::new(ValidationProgress {
649            checks_passed: 0,
650            state: None,
651            check: None,
652        }));
653    }
654    failure
655}
656
657fn validation_control(
658    options: &CheckOptions,
659) -> Result<Arc<dive_runtime::budget::EvaluationControl>, Error> {
660    dive_runtime::budget::EvaluationControl::new(
661        &options.budget,
662        dive_runtime::budget::Phase::Validation,
663    )
664    .map_err(|_| Error::Analysis(AnalysisError::Inconsistent("validation control identity")))
665}
666
667fn validation_checkpoint(
668    control: &dive_runtime::budget::EvaluationControl,
669) -> Result<(), ValidationRunError> {
670    dive_eval::HostControl::check(control).map_err(|interrupted| ValidationRunError::Interrupted {
671        error: dive_eval::EvalError::interrupted(interrupted),
672        progress: ValidationProgress {
673            checks_passed: 0,
674            state: None,
675            check: None,
676        },
677    })
678}
679
680fn validation_run_error(
681    control: &dive_runtime::budget::EvaluationControl,
682    error: ValidationRunError,
683) -> (Error, Option<ValidationProgress>) {
684    let (error, progress) = match error {
685        ValidationRunError::Interrupted { error, progress } => (error, progress),
686        ValidationRunError::ResourceLimit { error, progress } => {
687            return (Error::ValidationResource(error), Some(progress));
688        }
689        ValidationRunError::EvaluationFailure { error, progress } => {
690            return (
691                Error::Thread(format!("independent validation evaluator failed: {error}")),
692                Some(progress),
693            );
694        }
695        ValidationRunError::BindingFailure { error, progress } => {
696            return (
697                Error::Thread(format!("independent validation binding failed: {error}")),
698                Some(progress),
699            );
700        }
701        ValidationRunError::ThreadFailure(message) => return (Error::Thread(message), None),
702        ValidationRunError::ControlConflict(_) => {
703            return (
704                Error::Analysis(AnalysisError::Inconsistent(
705                    "validation control ownership conflict",
706                )),
707                None,
708            );
709        }
710        other => return (Error::Thread(other.to_string()), None),
711    };
712    let error = match control.verdict(&error) {
713        Some(dive_runtime::Verdict::Stopped(stopped)) => AnalysisError::Stopped(stopped),
714        Some(dive_runtime::Verdict::BudgetMeasurement { error }) => {
715            AnalysisError::BudgetMeasurement(error)
716        }
717        _ => {
718            AnalysisError::Inconsistent("validation interruption lacks matching resource authority")
719        }
720    };
721    (Error::Analysis(error), Some(progress))
722}
723
724// The API creates native documents itself. Keep this deliberately separate
725// from TLC's ambiguous document/session reader, which is not controlled yet.
726fn validate_native_document(
727    model: &Model,
728    document: &TraceDoc,
729    control: &Arc<dive_runtime::budget::EvaluationControl>,
730) -> Result<ValidationReport, ValidationRunError> {
731    validation_checkpoint(control)?;
732    let trace = match Trace::decode(model, document) {
733        Ok(trace) => trace,
734        Err(error) => {
735            return Ok(ValidationReport {
736                validation: if model.has_runtime_names() {
737                    Validation::Unsupported(dive_trace::RUNTIME_NAMES_UNSUPPORTED.into())
738                } else {
739                    Validation::Invalid(dive_trace::Failure {
740                        state: error.state.unwrap_or(0),
741                        check: dive_trace::Check::Shape,
742                        detail: error.detail,
743                    })
744                },
745                notes: Vec::new(),
746                length: document.states.len(),
747            });
748        }
749    };
750    dive_trace::validate_controlled(model, &trace, control.clone())
751}
752
753fn row_ending(
754    model: &Model,
755    state: &dive_liveness::analyze::StateEvaluation,
756    cause: &dive_eval::EvalError,
757) -> Result<Ending, (Error, Option<ValidationProgress>)> {
758    Ok(
759        if state.site() == dive_liveness::analyze::StateEvaluationSite::CaptureSourceRow {
760            let endpoint = dive_trace::TemporalSourceEndpoint::from_error(model, cause)
761                .ok_or_else(|| {
762                    (
763                        Error::Document("source-row endpoint lost its source context".into()),
764                        None,
765                    )
766                })?;
767            Ending::TemporalSourceError {
768                ec: cause.ec().name().into(),
769                endpoint,
770            }
771        } else {
772            let endpoint =
773                dive_trace::TemporalStateEndpoint::from_error(model, cause).ok_or_else(|| {
774                    (
775                        Error::Document("row endpoint has no original source context".into()),
776                        None,
777                    )
778                })?;
779            Ending::TemporalStateError {
780                ec: cause.ec().name().into(),
781                endpoint,
782            }
783        },
784    )
785}
786
787fn validate_row(
788    ir: &Arc<Ir>,
789    config: &ModelConfig,
790    options: &CheckOptions,
791    state: &dive_liveness::analyze::StateEvaluation,
792) -> Result<RowValidation, (Error, Option<ValidationProgress>)> {
793    let result = state
794        .capture_row()
795        .map(dive_liveness::analyze::CaptureRowEvidence::result)
796        .or_else(|| {
797            state
798                .capture_source_row()
799                .map(dive_liveness::analyze::SourceRowEvidence::result)
800        })
801        .ok_or_else(|| {
802            (
803                Error::Analysis(AnalysisError::Inconsistent("missing row certificate")),
804                None,
805            )
806        })?;
807    let path = result.counterexample.as_ref().ok_or_else(|| {
808        (
809            Error::Analysis(AnalysisError::Inconsistent("missing row source path")),
810            None,
811        )
812    })?;
813    let control = validation_control(options).map_err(|error| (error, None))?;
814    let recipe = dive_model::Recipe::new(
815        ir.clone(),
816        config.clone(),
817        options.eval,
818        options.no_deadlock,
819    )
820    .with_symmetry_liveness(options.symmetry_liveness);
821    let mode = if options.profile == dive_eval::Profile::Tlc {
822        dive_stdlib::random::RandomMode::Tlc
823    } else {
824        dive_stdlib::random::RandomMode::Dive
825    };
826    let host = Arc::new(dive_stdlib::host::RunHost::new(
827        dive_stdlib::random::Streams::new(options.seed, mode),
828        None,
829    ));
830    // Encoding still uses a genuine fresh model, but no earlier binding or
831    // Behavior validation may erase an intrinsic error before the fallible path.
832    let model = recipe
833        .bind_fallible(host, Some(control.clone()))
834        .map_err(|failure| (*controlled_binding_failure(failure, &control).error, None))?;
835    let mut states = Vec::new();
836    for state in &path.states {
837        if state.text.is_some() {
838            return Err((
839                Error::Document("incomplete row-error source state".into()),
840                None,
841            ));
842        }
843        states.push(Arc::from(
844            state.values.iter().cloned().map(Some).collect::<Vec<_>>(),
845        ));
846    }
847    let trace = Trace {
848        length: Some(states.len()),
849        labels: vec![None; states.len()],
850        states,
851        ending: Ending::Behavior,
852        properties: Vec::new(),
853    };
854    let cause = state.core_cause().ok_or_else(|| {
855        (
856            Error::Document("row endpoint lost its original core cause".into()),
857            None,
858        )
859    })?;
860    let ending = row_ending(&model, state, cause)?;
861    let document = trace
862        .to_doc(&model)
863        .map_err(|error| (Error::Document(error), None))?
864        .with_ending(ending);
865    let session = dive_trace::Session::new(recipe, None);
866    let (report, _) = session
867        .read_controlled(&document, control.clone())
868        .map_err(|error| validation_run_error(&control, error))?;
869    if report.validation != Validation::Valid {
870        return Err((Error::EndpointValidation { report }, None));
871    }
872    Ok(RowValidation { document, report })
873}
874
875fn finish_row_failure(
876    ir: &Arc<Ir>,
877    config: &ModelConfig,
878    options: &CheckOptions,
879    mut failure: Failure,
880) -> Failure {
881    let Some(state) = failure.row_candidate() else {
882        return failure;
883    };
884    let validation = validate_row(ir, config, options, state);
885    match validation {
886        Ok(validation) => failure.row_validation = Some(Box::new(validation)),
887        Err((error, progress)) => {
888            failure.error = Box::new(error);
889            failure.stage = Stage::Validation;
890            failure.validation_progress = progress.map(Box::new);
891        }
892    }
893    failure
894}
895
896#[cfg(test)]
897#[allow(
898    clippy::expect_used,
899    clippy::panic,
900    reason = "actual candidate control evidence"
901)]
902mod validation_controls {
903    use super::*;
904
905    fn input() -> (Arc<Ir>, ModelConfig) {
906        let source = "---- MODULE ValidationBudget ----\nEXTENDS Naturals\nVARIABLE x\nInit == x=0\nNext == x'=IF x<2 THEN x+1 ELSE x\nP == <>(x=3)\n====\n";
907        let analysis = dive_sema::analyze_source(
908            "ValidationBudget.tla",
909            source,
910            &dive_sema::Options::default(),
911        );
912        assert!(analysis.accepted());
913        (
914            Arc::new(dive_ir::lower(&analysis).expect("IR")),
915            dive_config::parse("INIT Init\nNEXT Next\nPROPERTY P\n")
916                .into_config()
917                .expect("configuration"),
918        )
919    }
920
921    #[test]
922    fn decoded_native_shape_errors_keep_the_independent_validation_class() {
923        let (ir, config) = input();
924        let options = CheckOptions::tlc(0, 0);
925        let model = bind(&ir, &config, &options).expect("model");
926        let document = TraceDoc::behavior(vec![serde_json::json!({"wrong":0})]).expect("document");
927        let legacy = dive_trace::validate_doc(&model, &document, &config.model_values).0;
928        let control = validation_control(&options).expect("control");
929        let controlled =
930            validate_native_document(&model, &document, &control).expect("shape report");
931        assert_eq!(controlled, legacy);
932        assert!(
933            matches!(controlled.validation,Validation::Invalid(ref e) if e.check==dive_trace::Check::Shape)
934        );
935    }
936
937    #[test]
938    fn an_unarmed_validation_identity_is_not_resource_authority() {
939        let mut options = CheckOptions::tlc(0, 0);
940        options.budget = dive_runtime::budget::Budget::new(Some(Duration::from_secs(3600)), None);
941        let control = validation_control(&options).expect("unarmed control");
942        assert!(dive_eval::HostControl::check(control.as_ref()).is_ok());
943        // Unarmed contexts carry the public no-owner identity zero. A matching
944        // payload still cannot prove that any run resource was exhausted.
945        let (error, _) = validation_run_error(
946            &control,
947            ValidationRunError::Interrupted {
948                error: dive_eval::EvalError::interrupted(dive_eval::Interrupted::new(0)),
949                progress: ValidationProgress {
950                    checks_passed: 0,
951                    state: None,
952                    check: None,
953                },
954            },
955        );
956        assert!(matches!(
957            error,
958            Error::Analysis(AnalysisError::Inconsistent(_))
959        ));
960    }
961
962    #[test]
963    fn foreign_interruption_cannot_borrow_an_exhausted_validation_budget() {
964        let watchdog = dive_runtime::budget::Budget::new(Some(Duration::ZERO), None)
965            .start()
966            .expect("thread")
967            .expect("watchdog");
968        let mut options = CheckOptions::tlc(0, 0);
969        options.budget = watchdog.budget().clone();
970        let control = validation_control(&options).expect("control");
971        let (error, _) = validation_run_error(
972            &control,
973            ValidationRunError::Interrupted {
974                error: dive_eval::EvalError::interrupted(dive_eval::Interrupted::new(0)),
975                progress: ValidationProgress {
976                    checks_passed: 0,
977                    state: None,
978                    check: None,
979                },
980            },
981        );
982        assert!(matches!(
983            error,
984            Error::Analysis(AnalysisError::Inconsistent(_))
985        ));
986    }
987}
988
989/// The safety stop or typed failure of a periodic analysis that failed.
990fn finish_periodic_failure(
991    ir: &Arc<Ir>,
992    config: &ModelConfig,
993    options: &CheckOptions,
994    failure: dive_liveness::analyze::periodic::PeriodicFailure,
995) -> Result<(Outcome, Checks), Failure> {
996    let mut detailed = *failure.failure;
997    let state_evaluation = detailed.take_state_evaluation();
998    let (detail, action_evaluation) = detailed.into_parts();
999    if let AnalysisError::Exploration(result) = detail.error {
1000        return Ok((Outcome::Safety(result), failure.checks));
1001    }
1002    Err(finish_row_failure(
1003        ir,
1004        config,
1005        options,
1006        Failure {
1007            error: Box::new(Error::Analysis(detail.error)),
1008            stage: Stage::Analysis(detail.stage),
1009            exploration: detail.exploration.or(failure.prefix),
1010            elapsed: Duration::ZERO,
1011            action_evaluation,
1012            state_evaluation,
1013            row_validation: None,
1014            validation_progress: None,
1015            incomplete: failure.capture_completed == Some(false),
1016            periodic: Some(Box::new(failure.checks)),
1017            configuration: None,
1018            binding_output: Vec::new(),
1019            symmetry_liveness: None,
1020        },
1021    ))
1022}
1023
1024/// The report of a temporal check whose graph Core produced: the analysis
1025/// result goes
1026/// through this module's validation and report path, with
1027/// the file configuration. `periodic` says whether the default profile's
1028/// completed-level schedule ran.
1029pub(crate) fn core_report(
1030    ir: &Arc<Ir>,
1031    config: &ModelConfig,
1032    options: &CheckOptions,
1033    failure: dive_liveness::analyze::periodic::PeriodicFailure,
1034    periodic: bool,
1035    symmetry_liveness: dive_model::SymmetryLivenessResolution,
1036    started: Instant,
1037) -> Result<Report, Failure> {
1038    match finish_periodic_failure(ir, config, options, failure) {
1039        Ok((outcome, checks)) => Ok(Report {
1040            outcome,
1041            symmetry_liveness: Some(symmetry_liveness),
1042            options: options.clone(),
1043            elapsed: started.elapsed(),
1044            periodic: periodic.then_some(checks),
1045            configuration: Some(file_configuration()),
1046            memory_samples: options.budget.memory_samples(),
1047        }),
1048        Err(mut failure) => {
1049            failure.elapsed = started.elapsed();
1050            failure.configuration = Some(Box::new(file_configuration()));
1051            failure.symmetry_liveness = Some(Box::new(symmetry_liveness));
1052            if !periodic {
1053                failure.periodic = None;
1054            }
1055            Err(failure)
1056        }
1057    }
1058}
1059
1060#[cfg(test)]
1061#[allow(
1062    clippy::expect_used,
1063    clippy::panic,
1064    reason = "test setup and assertions"
1065)]
1066mod evidence_controls {
1067    use super::*;
1068
1069    /// Core's temporal report for `P == property`, under `--compat=tlc`.
1070    fn sampled_report(property: &str) -> Report {
1071        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1072        let directory = std::env::temp_dir().join(format!(
1073            "dive-temporal-boundaries-{}-{}",
1074            std::process::id(),
1075            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1076        ));
1077        std::fs::create_dir_all(&directory).expect("directory");
1078        let file = directory.join("Boundaries.tla");
1079        std::fs::write(
1080            &file,
1081            format!(
1082                "---- MODULE Boundaries ----\nVARIABLE x\nInit == x = FALSE\nNext == x' = ~x\nP == {property}\n====\n"
1083            ),
1084        )
1085        .expect("module");
1086        std::fs::write(
1087            file.with_extension("cfg"),
1088            "INIT Init\nNEXT Next\nPROPERTY P\n",
1089        )
1090        .expect("configuration");
1091        let report = crate::check_file(&crate::CheckRequest {
1092            file,
1093            compat_tlc: true,
1094            seed: Some(0),
1095            workers: Some(1),
1096            ..crate::CheckRequest::default()
1097        })
1098        .expect("report");
1099        let _ = std::fs::remove_dir_all(&directory);
1100        report
1101            .temporal_result()
1102            .expect("real temporal result")
1103            .clone()
1104    }
1105
1106    #[test]
1107    fn a_terminal_measurement_failure_never_publishes_holds() {
1108        let mut report = sampled_report("[]<>(x \\/ ~x)");
1109        assert!(matches!(report.outcome(), Outcome::NativeHolds(_)));
1110        let failure = finish_report(
1111            &mut report,
1112            Err(dive_runtime::budget::MeasurementError::unavailable(
1113                dive_runtime::budget::SamplePoint::Final,
1114            )),
1115            Duration::from_millis(2),
1116        )
1117        .expect("holding cannot escape");
1118        assert_eq!(
1119            failure.error().code(),
1120            dive_runtime::budget::MEASUREMENT_FAILURE_CODE
1121        );
1122        assert_eq!(failure.capture_completed(), Some(true));
1123        assert_eq!(failure.stage().name(), "finalization");
1124        assert_eq!(failure.elapsed(), Duration::from_millis(2));
1125        let evidence = failure.exploration().expect("actual complete capture");
1126        assert_eq!(
1127            (
1128                evidence.stats.distinct,
1129                evidence.stats.generated,
1130                evidence.stats.depth
1131            ),
1132            (2, 3, 2)
1133        );
1134    }
1135
1136    #[test]
1137    fn terminal_memory_excess_has_completed_capture_at_finalization() {
1138        let mut report = sampled_report(r"[]<>(x \/ ~x)");
1139        let stop = dive_runtime::budget::Exhausted {
1140            resource: dive_runtime::budget::Resource::Memory,
1141            limit: 100,
1142            observed: 101,
1143            elapsed_ms: 2,
1144        };
1145        let failure = finish_report(&mut report, Ok(Some(stop)), Duration::from_millis(2))
1146            .expect("no holding verdict");
1147        assert_eq!(failure.stage().name(), "finalization");
1148        assert_eq!(failure.capture_completed(), Some(true));
1149        let Error::Analysis(AnalysisError::Stopped(stopped)) = failure.error() else {
1150            panic!("actual resource stop");
1151        };
1152        assert_eq!(stopped.phase, dive_runtime::budget::Phase::Finalization);
1153        let evidence = failure.exploration().expect("actual completed capture");
1154        assert_eq!(
1155            (
1156                evidence.stats.distinct,
1157                evidence.stats.generated,
1158                evidence.stats.depth
1159            ),
1160            (2, 3, 2)
1161        );
1162    }
1163
1164    #[test]
1165    fn a_terminal_failure_keeps_an_already_validated_witness() {
1166        let mut report = sampled_report("<>[]x");
1167        let Outcome::NativeViolation(before) = report.outcome() else {
1168            panic!("real validated witness");
1169        };
1170        let document = before.document().to_json();
1171        assert!(
1172            finish_report(
1173                &mut report,
1174                Err(dive_runtime::budget::MeasurementError::unavailable(
1175                    dive_runtime::budget::SamplePoint::Final
1176                )),
1177                Duration::from_millis(2),
1178            )
1179            .is_none()
1180        );
1181        let Outcome::NativeViolation(after) = report.outcome() else {
1182            panic!("witness retained");
1183        };
1184        assert_eq!(after.document().to_json(), document);
1185        assert_eq!(after.validation().validation, Validation::Valid);
1186    }
1187
1188    #[test]
1189    fn lost_thread_evidence_is_unknown_not_zero() {
1190        for stage in [
1191            Stage::Unknown,
1192            Stage::Analysis(dive_liveness::analyze::Stage::Unknown),
1193        ] {
1194            let failure = Failure::before(Error::Thread("test thread failure".into()), stage);
1195            assert_eq!(failure.stage().name(), "unknown");
1196            assert_eq!(failure.capture_completed(), None);
1197            assert!(failure.workers(8).is_none());
1198            assert!(failure.exploration().is_none());
1199        }
1200    }
1201}
1202
1203#[cfg(test)]
1204pub(crate) mod binding_controls;