1use std::path::{Path, PathBuf};
50use std::sync::Arc;
51
52pub use dive_trace::mutate::{ControlMode, Mutant};
53pub use dive_trace::{
54 Check, DEADLOCK_UNSUPPORTED, Ending, Failure, InitialErrorStage, InitialInvariantClass, Report,
55 State, Trace, TraceDoc, Validation, ValidationRunError,
56};
57use serde_json::{Value, json};
58
59use crate::ApiError;
60
61pub const TRACE_SCHEMA_VERSION: u32 = crate::REPORT_SCHEMA_VERSION;
63
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct TraceOptions {
67 pub inputs: Option<dive_eval::inputs::RecordedInputs>,
71 pub compat_tlc: bool,
75 pub symmetry_liveness: Option<dive_model::SymmetryLiveness>,
78 pub no_deadlock: bool,
80 pub run: Option<(i64, usize)>,
91 pub library_paths: Vec<PathBuf>,
93 pub module_paths: Vec<PathBuf>,
95}
96
97#[derive(Debug, Clone)]
100pub struct SpecModel {
101 model: dive_model::Model,
102 model_values: Vec<String>,
103 session: dive_trace::Session,
104 recipe: dive_model::Recipe,
105}
106
107pub(crate) fn make_run_config(
108 model: &dive_model::Model,
109 seed: i64,
110 fp_index: usize,
111) -> dive_eval::RunConfig {
112 dive_eval::RunConfig {
113 deadlock: model.settings.check_deadlock,
114 workers: 1,
115 seed,
116 fingerprint: i64::from_ne_bytes(
117 dive_value::fp64::POLYS
118 .get(fp_index)
119 .copied()
120 .unwrap_or(0)
121 .to_ne_bytes(),
122 ),
123 install: std::env::current_exe()
124 .map(|path| path.display().to_string())
125 .unwrap_or_default(),
126 }
127}
128
129impl SpecModel {
130 pub fn load(spec: &Path, cfg: &Path, opts: &TraceOptions) -> Result<Self, ApiError> {
138 Self::load_hosted(spec, cfg, opts, None)
139 }
140
141 pub(crate) fn load_hosted(
142 spec: &Path,
143 cfg: &Path,
144 opts: &TraceOptions,
145 host: Option<Arc<dyn dive_eval::Host>>,
146 ) -> Result<Self, ApiError> {
147 let sema = sema_options(opts);
148 let shown = spec.display().to_string();
149 let analysis = dive_sema::analyze_file(spec, &sema).map_err(|error| ApiError::Io {
150 path: shown.clone(),
151 error,
152 })?;
153 let text = std::fs::read(cfg).map_err(|error| ApiError::Io {
154 path: cfg.display().to_string(),
155 error,
156 })?;
157 let (_, parsed) = dive_config::parse_bytes(&text);
158 Self::bind_hosted(&shown, &analysis, parsed, opts, host)
159 }
160
161 pub fn from_source(
167 file: &str,
168 source: &str,
169 cfg: &str,
170 opts: &TraceOptions,
171 ) -> Result<Self, ApiError> {
172 let analysis = dive_sema::analyze_source(file, source, &sema_options(opts));
173 Self::bind(file, &analysis, dive_config::parse(cfg), opts)
174 }
175
176 fn bind(
177 file: &str,
178 analysis: &dive_sema::Analysis,
179 cfg: dive_config::ConfigParse,
180 opts: &TraceOptions,
181 ) -> Result<Self, ApiError> {
182 Self::bind_hosted(file, analysis, cfg, opts, None)
183 }
184
185 #[allow(
186 clippy::too_many_lines,
187 reason = "one ordered startup transaction retains source, host, replay cursor and config ownership"
188 )]
189 fn bind_hosted(
190 file: &str,
191 analysis: &dive_sema::Analysis,
192 cfg: dive_config::ConfigParse,
193 opts: &TraceOptions,
194 owned_host: Option<Arc<dyn dive_eval::Host>>,
195 ) -> Result<Self, ApiError> {
196 if owned_host.is_some() && opts.inputs.is_some() {
197 return Err(ApiError::Unsupported {
198 feature: "owned simulation external input replay is not implemented".into(),
199 });
200 }
201 if !analysis.accepted() {
202 return Err(ApiError::Rejected {
203 message: format!("{file} has errors; `dive analyze` lists them"),
204 });
205 }
206 let Some(cfg) = cfg.into_config() else {
207 return Err(ApiError::Rejected {
208 message: "the configuration has errors; `dive parse --config` lists them"
209 .to_owned(),
210 });
211 };
212 let ir = dive_ir::lower(analysis).map_err(|e| ApiError::Unsupported {
213 feature: e.to_string(),
214 })?;
215 let ir = Arc::new(ir);
216 dive_eval::validate_ir(&ir).map_err(|error| ApiError::Unsupported {
217 feature: error.to_string(),
218 })?;
219 if let Some(feature) = dive_model::transformed_randomness(&ir, &cfg) {
220 return Err(ApiError::Unsupported {
221 feature: feature.to_owned(),
222 });
223 }
224 let mode = if opts.compat_tlc {
225 dive_stdlib::random::RandomMode::Tlc
226 } else {
227 dive_stdlib::random::RandomMode::Dive
228 };
229 let streams = match opts.run {
230 Some((seed, fp_index)) => {
231 if fp_index >= dive_value::fp64::POLYS.len() {
232 return Err(ApiError::Rejected {
233 message: format!(
234 "fingerprint polynomial index {fp_index} is out of range (0..{})",
235 dive_value::fp64::POLYS.len()
236 ),
237 });
238 }
239 Some(dive_stdlib::random::Streams::new(seed, mode))
240 }
241 None => None,
242 };
243 let replay = opts
244 .inputs
245 .as_ref()
246 .map(|inputs| dive_eval::inputs::InputReplay::new(inputs.clone()).map(Arc::new))
247 .transpose()
248 .map_err(|error| ApiError::Unsupported {
249 feature: error.message,
250 })?;
251 let host = streams.map(|s| {
252 let host = dive_stdlib::host::RunHost::new(s, None);
253 Arc::new(if let Some(replay) = &replay {
254 host.with_inputs(replay.clone())
255 } else {
256 host
257 })
258 });
259 let mut bind_opts = dive_model::BindOptions {
260 no_deadlock: opts.no_deadlock,
261 host: owned_host
262 .or_else(|| host.clone().map(|h| -> Arc<dyn dive_eval::Host> { h }))
263 .or_else(|| {
264 replay
265 .clone()
266 .map(|replay| -> Arc<dyn dive_eval::Host> { replay })
267 }),
268 ..if opts.compat_tlc {
269 dive_model::BindOptions::tlc()
270 } else {
271 dive_model::BindOptions::dive()
272 }
273 };
274 if let Some(inputs) = &opts.inputs {
275 bind_opts.eval.host_access = inputs.grants;
276 }
277 if let Some(policy) = opts.symmetry_liveness {
278 bind_opts.symmetry_liveness = policy;
279 }
280 let model_values = cfg.model_values.clone();
281 let recipe =
282 dive_model::Recipe::new(ir.clone(), cfg.clone(), bind_opts.eval, opts.no_deadlock)
283 .with_symmetry_liveness(bind_opts.symmetry_liveness);
284 let bound = on_big_stack(move || dive_model::bind(ir, &cfg, &bind_opts))?;
285 if let Some(replay) = &replay {
286 replay
287 .finish_binding()
288 .map_err(|error| ApiError::Unsupported {
289 feature: error.message,
290 })?;
291 }
292 let mut run_config = None;
293 if let (Ok(model), Some((seed, fp_index))) = (&bound, opts.run) {
294 model.evaluator.intern_checker_names();
295 let config = make_run_config(model, seed, fp_index);
296 model.evaluator.intern_bfs_config(&config);
297 if let Some(host) = &host {
298 host.set_config(Some(config.clone()));
299 }
300 run_config = Some(config);
301 }
302 match bound {
303 Ok(model) => Ok(Self {
304 model,
305 model_values,
306 recipe: recipe.clone(),
307 session: {
308 let session = dive_trace::Session::new(
309 recipe.clone(),
310 run_config.or_else(|| {
311 host.as_ref()
312 .and_then(|host| dive_eval::Host::config(&**host))
313 }),
314 );
315 if let Some(inputs) = &opts.inputs {
316 session.with_inputs(inputs.clone())
317 } else {
318 session
319 }
320 },
321 }),
322 Err(f) => match &f.error.kind {
323 dive_model::ErrorKind::Unsupported { feature } => Err(ApiError::Unsupported {
324 feature: feature.clone(),
325 }),
326 _ => Err(ApiError::Rejected {
327 message: f.error.to_string(),
328 }),
329 },
330 }
331 }
332
333 #[must_use]
335 pub fn model(&self) -> &dive_model::Model {
336 &self.model
337 }
338
339 pub(crate) fn preparation_model(
341 &self,
342 seed: i64,
343 mode: dive_stdlib::random::RandomMode,
344 control: Arc<dyn dive_eval::HostControl>,
345 ) -> Result<dive_model::Model, String> {
346 let host = Arc::new(dive_stdlib::host::RunHost::new(
347 dive_stdlib::random::Streams::new(seed, mode),
348 None,
349 ));
350 let model = on_big_stack(|| self.recipe.bind_next_fallible(host.clone(), Some(control)))
351 .map_err(|error| error.to_string())?
352 .map_err(|error| error.to_string())?;
353 if let Some(config) = self.model.evaluator.host().and_then(|host| host.config()) {
354 model.evaluator.intern_checker_names();
355 model.evaluator.intern_bfs_config(&config);
356 host.set_config(Some(config));
357 }
358 Ok(model)
359 }
360
361 #[must_use]
363 pub fn model_values(&self) -> &[String] {
364 &self.model_values
365 }
366
367 #[must_use]
370 pub fn validate(&self, doc: &TraceDoc) -> Report {
371 self.read(doc).0
372 }
373
374 pub(crate) fn validate_mode(
377 &self,
378 doc: &TraceDoc,
379 control: Arc<dyn dive_eval::HostControl>,
380 ) -> Result<Report, ValidationRunError> {
381 on_big_stack(|| {
382 self.session
383 .read_controlled(doc, control)
384 .map(|(report, _)| report)
385 })
386 .map_err(|error| ValidationRunError::ThreadFailure(error.to_string()))?
387 }
388
389 pub(crate) fn validate_sample_mode(
393 &self,
394 doc: &TraceDoc,
395 control: Arc<dyn dive_eval::HostControl>,
396 ) -> Result<Report, ValidationRunError> {
397 on_big_stack(|| {
398 if doc.ending == Some(Ending::Behavior) {
399 self.session.read_sampled(doc, Some(control))
400 } else if doc.ending == Some(Ending::Deadlock) {
401 self.session.read_sampled_deadlock(doc, Some(control))
402 } else {
403 self.session.read_controlled(doc, control)
404 }
405 .map(|(report, _)| report)
406 })
407 .map_err(|error| ValidationRunError::ThreadFailure(error.to_string()))?
408 }
409
410 pub fn try_validate_sample(&self, doc: &TraceDoc) -> Result<Report, ValidationRunError> {
428 on_big_stack(|| {
429 if doc.ending == Some(Ending::Deadlock) {
430 self.session.read_sampled_deadlock(doc, None)
431 } else {
432 self.session.read_sampled(doc, None)
433 }
434 .map(|(report, _)| report)
435 })
436 .map_err(|error| ValidationRunError::ThreadFailure(error.to_string()))?
437 }
438
439 #[must_use]
442 pub fn read(&self, doc: &TraceDoc) -> (Report, Option<Trace>) {
443 on_big_stack(|| {
444 let (report, plain) = self.session.read(doc);
445 let trace = plain.and_then(|doc| Trace::decode(&self.model, &doc).ok());
446 (report, trace)
447 })
448 .unwrap_or_else(|e| (thread_failed(&e, doc.states.len()), None))
449 }
450
451 pub fn try_validate(&self, doc: &TraceDoc) -> Result<Report, ValidationRunError> {
466 self.try_read(doc).map(|(report, _)| report)
467 }
468
469 pub fn try_read(&self, doc: &TraceDoc) -> Result<(Report, Option<Trace>), ValidationRunError> {
475 if !matches!(
476 doc.ending,
477 Some(
478 Ending::TemporalStateError { .. }
479 | Ending::TemporalSourceError { .. }
480 | Ending::NextStateError { .. }
481 | Ending::ViewSourceError { .. }
482 | Ending::CandidateStateError { .. }
483 | Ending::PartialNext { .. }
484 | Ending::PartialInit { .. }
485 )
486 ) {
487 return Ok(self.read(doc));
488 }
489 on_big_stack(|| {
490 let (report, plain) = self.session.try_read(doc)?;
491 let trace = plain.and_then(|doc| Trace::decode(&self.model, &doc).ok());
492 Ok((report, trace))
493 })
494 .map_err(|error| ValidationRunError::ThreadFailure(error.to_string()))?
495 }
496
497 pub fn initial_invariant_class(
515 &self,
516 doc: &TraceDoc,
517 control: Option<Arc<dyn dive_eval::HostControl>>,
518 ) -> Result<(Report, Option<dive_trace::InitialInvariantClass>), ValidationRunError> {
519 on_big_stack(|| self.session.initial_invariant_class(doc, control))
520 .map_err(|error| ValidationRunError::ThreadFailure(error.to_string()))?
521 }
522
523 pub fn invariant_error_class(
530 &self,
531 doc: &TraceDoc,
532 control: Option<Arc<dyn dive_eval::HostControl>>,
533 ) -> Result<(Report, Option<dive_trace::InvariantErrorClass>), ValidationRunError> {
534 on_big_stack(|| self.session.invariant_error_class(doc, control))
535 .map_err(|error| ValidationRunError::ThreadFailure(error.to_string()))?
536 }
537
538 pub fn initial_error_stage(
546 &self,
547 control: Option<Arc<dyn dive_eval::HostControl>>,
548 ) -> Result<(Report, Option<dive_trace::InitialErrorStage>), ValidationRunError> {
549 on_big_stack(|| self.session.initial_error_stage(control))
550 .map_err(|error| ValidationRunError::ThreadFailure(error.to_string()))?
551 }
552
553 #[must_use]
555 pub fn validate_trace(&self, trace: &Trace) -> Report {
556 on_big_stack(|| {
557 for state in &trace.states {
559 for value in state.iter().flatten() {
560 if let Err(error) = value.validate_names(&self.model.names) {
561 return thread_failed(
562 &ApiError::Unsupported {
563 feature: error.to_string(),
564 },
565 trace.states.len(),
566 );
567 }
568 }
569 }
570 match trace.to_doc(&self.model) {
571 Ok(doc) => self.session.read(&doc).0,
572 Err(message) => thread_failed(&ApiError::Rejected { message }, trace.states.len()),
573 }
574 })
575 .unwrap_or_else(|e| thread_failed(&e, trace.states.len()))
576 }
577
578 #[must_use]
581 pub fn mutants(&self, trace: &Trace) -> Vec<Mutant> {
582 self.mutants_with_mode(trace, ControlMode::ShortestBfs)
583 }
584
585 #[must_use]
589 pub fn mutants_with_mode(&self, trace: &Trace, mode: ControlMode) -> Vec<Mutant> {
590 on_big_stack(|| dive_trace::mutate::mutants_with_mode(&self.model, trace, mode))
591 .unwrap_or_default()
592 }
593
594 pub fn to_doc(&self, trace: &Trace) -> Result<TraceDoc, ApiError> {
599 trace
600 .to_doc(&self.model)
601 .map_err(|message| ApiError::Rejected { message })
602 }
603}
604
605fn sema_options(opts: &TraceOptions) -> dive_sema::Options {
606 dive_sema::Options {
607 search: dive_sema::SearchPath {
608 library_paths: opts.library_paths.clone(),
609 after_standard: opts.module_paths.clone(),
610 },
611 ..dive_sema::Options::default()
612 }
613}
614
615fn thread_failed(e: &ApiError, length: usize) -> Report {
616 Report {
617 validation: Validation::Unsupported(format!("internal error: {e}")),
618 notes: Vec::new(),
619 length,
620 }
621}
622
623fn on_big_stack<T: Send>(f: impl FnOnce() -> T + Send) -> Result<T, ApiError> {
625 std::thread::scope(|s| {
626 std::thread::Builder::new()
627 .stack_size(dive_eval::RECOMMENDED_STACK)
628 .spawn_scoped(s, f)
629 .ok()
630 .and_then(|h| h.join().ok())
631 })
632 .ok_or_else(|| ApiError::Unsupported {
633 feature: "internal error: the evaluation thread could not run or panicked".to_owned(),
634 })
635}
636
637#[must_use]
640pub fn report_json(report: &Report) -> Value {
641 let mut j = json!({
642 "schema_version": TRACE_SCHEMA_VERSION,
643 "command": "validate-trace",
644 "result": report.validation.kind(),
645 "length": report.length,
646 "notes": report.notes,
647 });
648 match &report.validation {
649 Validation::Invalid(f) => {
650 j["failure"] = json!({"state": f.state, "check": f.check.name(), "detail": f.detail});
651 }
652 Validation::Unsupported(u) => j["unsupported"] = Value::from(u.as_str()),
653 _ => {}
655 }
656 j
657}
658
659#[must_use]
661pub fn render_report(report: &Report) -> String {
662 use std::fmt::Write as _;
663 let mut s = match &report.validation {
664 Validation::Valid => format!("valid: the {}-state trace validates\n", report.length),
665 Validation::Invalid(f) => format!(
666 "invalid: state {} of {} (numbered from 1, as TLC prints traces), check `{}`: {}\n",
667 f.state + 1,
668 report.length,
669 f.check.name(),
670 f.detail
671 ),
672 Validation::Unsupported(u) => format!("unsupported: {u}\n"),
673 other => format!("{}\n", other.kind()),
674 };
675 for n in &report.notes {
676 let _ = writeln!(s, "note: {n}");
677 }
678 s
679}
680
681#[derive(Debug, Clone)]
685pub struct Controls {
686 pub positive: Report,
688 pub dive_format: Option<Validation>,
691 pub mutants: Vec<(String, Validation)>,
693}
694
695impl Controls {
696 #[must_use]
699 pub fn positive_ok(&self) -> bool {
700 match &self.positive.validation {
701 Validation::Valid => true,
702 Validation::Unsupported(u) => u == dive_trace::DEADLOCK_UNSUPPORTED,
703 _ => false,
704 }
705 }
706
707 #[must_use]
709 pub fn failures(&self) -> Vec<String> {
710 let mut out = Vec::new();
711 if !self.positive_ok() {
712 out.push(format!(
713 "positive control: {}",
714 render_report(&self.positive).trim_end()
715 ));
716 }
717 if let Some(v) = &self.dive_format
718 && *v != self.positive.validation
719 {
720 out.push(format!(
721 "the trace in dive's format gives {}, not {}",
722 v.kind(),
723 self.positive.validation.kind()
724 ));
725 }
726 if self.mutants.is_empty() {
727 out.push("no negative controls generated".to_owned());
728 }
729 for (name, v) in &self.mutants {
730 if !matches!(v, Validation::Invalid(_)) {
731 out.push(format!("mutant {name} is not rejected: {}", v.kind()));
732 }
733 }
734 out
735 }
736}
737
738impl SpecModel {
739 #[must_use]
745 pub fn controls(&self, doc: &TraceDoc) -> Controls {
746 self.controls_with_mode(doc, ControlMode::ShortestBfs)
747 }
748
749 #[must_use]
771 pub fn controls_with_mode(&self, doc: &TraceDoc, mode: ControlMode) -> Controls {
772 let (positive, trace) = self.read(doc);
773 let mut mutants = Vec::new();
774 let mut dive_format = None;
775 if let Some(trace) = trace.filter(|_| {
776 matches!(
777 positive.validation,
778 Validation::Valid | Validation::Unsupported(_)
779 )
780 }) {
781 dive_format = Some(match self.to_doc(&trace) {
782 Ok(d) => self.validate(&d).validation,
783 Err(e) => Validation::Unsupported(e.to_string()),
784 });
785 for m in self.mutants_with_mode(&trace, mode) {
786 let direct = self.validate_trace(&m.trace).validation;
787 let via_format = match self.to_doc(&m.trace) {
788 Ok(d) => self.validate(&d).validation,
789 Err(e) => Validation::Unsupported(e.to_string()),
790 };
791 let v = if matches!(direct, Validation::Invalid(_)) {
792 via_format
793 } else {
794 direct
795 };
796 mutants.push((m.name, v));
797 }
798 }
799 Controls {
800 positive,
801 dive_format,
802 mutants,
803 }
804 }
805}