1use crate::dfid_admission::{Options, Outcome};
17use crate::trace::{Ending, SpecModel, TraceDoc, TraceOptions, Validation};
18use serde_json::{Value, json};
19use std::path::PathBuf;
20
21pub const DFID_SCHEMA_VERSION: u32 = crate::REPORT_SCHEMA_VERSION;
23
24#[derive(Clone, Debug, Default)]
26pub struct DfidRequest {
27 pub file: PathBuf,
29 pub config: Option<PathBuf>,
31 pub compat_tlc: bool,
33 pub max_level: u32,
35 pub seed: Option<i64>,
37 pub fp: usize,
39 pub worker_seeds: Option<Vec<i64>>,
41 pub workers: Option<usize>,
43 pub exact: bool,
45 pub no_deadlock: bool,
47 pub time_limit: crate::BudgetSetting<std::time::Duration>,
49 pub max_memory: crate::BudgetSetting<u64>,
51 pub library_paths: Vec<PathBuf>,
53 pub module_paths: Vec<PathBuf>,
55}
56
57#[derive(Clone, Debug)]
59pub struct DfidReport {
60 document: Value,
61 exit: u8,
62}
63
64impl DfidReport {
65 #[must_use]
67 pub fn to_json(&self) -> Value {
68 self.document.clone()
69 }
70 #[must_use]
72 pub const fn exit_status(&self) -> u8 {
73 self.exit
74 }
75 #[must_use]
78 pub fn render_human(&self) -> String {
79 let mut text = format!(
80 "DFID: {}; model proved: {}; generated {}, distinct {}; seed {}\n",
81 self.document["result"],
82 self.document["model_proved"],
83 self.document["statistics"]["generated"],
84 self.document["statistics"]["distinct"],
85 self.document["options"]["seed"]
86 );
87 if let (Some(result), Some(message)) = (
88 self.document["result"].as_str(),
89 self.document["message"].as_str(),
90 ) {
91 text.push_str(result);
92 text.push_str(": ");
93 text.push_str(message);
94 text.push('\n');
95 }
96 text
97 }
98}
99
100#[allow(
108 clippy::too_many_lines,
109 reason = "keep report provenance and certification in one path"
110)]
111pub fn dfid_file(req: &DfidRequest) -> Result<DfidReport, crate::ApiError> {
112 let seed = req.seed.unwrap_or_else(dive_stdlib::random::fresh_seed);
113 let config = req
114 .config
115 .clone()
116 .unwrap_or_else(|| req.file.with_extension("cfg"));
117 let profile = if req.compat_tlc {
118 if req.worker_seeds.is_some() || matches!(req.time_limit, crate::BudgetSetting::Explicit(_))
119 {
120 "tlc+overrides"
121 } else {
122 "tlc"
123 }
124 } else {
125 "dive"
126 };
127 let mut document = json!({
128 "schema_version": DFID_SCHEMA_VERSION, "command": "dfid", "profile": profile,
129 "engine_requested": "core", "engine": "none", "engine_fallback": null,
130 "file": req.file.display().to_string(), "config": config.display().to_string(),
131 "exhaustive": false, "model_proved": false, "violation_validated": false,
132 "result": "internal-error", "termination": "unavailable", "tlc_code": null,
133 "options": {"seed": seed, "seed_given": req.seed.is_some(), "fp": req.fp,
134 "max_level": req.max_level, "workers_requested": req.workers.unwrap_or(1), "workers_used": 0,
135 "worker_seeds": [], "worker_seed_override": req.worker_seeds,
136 "cli_seed_controls_workers": !req.compat_tlc, "store": if req.exact { "exact" } else { "fingerprint+exact-collision-guard" },
137 "execution_stage": "model-loading", "execution_scope": "native-dfid",
138 "witness_policy": "actual-concrete-path"},
139 "statistics": {"scope": "unavailable", "generated": null, "distinct": null, "level": null, "initial_candidates": null},
140 "counterexample": null, "startup_output": null,
141 });
142 if req.workers == Some(0) {
144 let exit = if req.compat_tlc { 1 } else { 2 };
145 document["result"] = json!("parameter-error");
146 document["observed_result"] = json!("parameter-error");
147 document["observed_tlc_code"] = json!(1102);
148 document["tlc_code"] = json!(if req.compat_tlc { Some(1102) } else { None });
149 document["message"] = json!("Error: at least one worker required.");
150 document["termination"] = json!("parameter-validation");
151 document["options"]["execution_stage"] = json!("parameter-validation");
152 document["exit_code"] = json!(exit);
153 return Ok(DfidReport { document, exit });
154 }
155 let model = match SpecModel::load(
156 &req.file,
157 &config,
158 &TraceOptions {
159 inputs: None,
160 compat_tlc: req.compat_tlc,
161 symmetry_liveness: None,
162 no_deadlock: req.no_deadlock,
163 run: Some((seed, req.fp)),
164 library_paths: req.library_paths.clone(),
165 module_paths: req.module_paths.clone(),
166 },
167 ) {
168 Ok(model) => model,
169 Err(e) => {
170 let (kind, exit) = match e {
171 crate::ApiError::Unsupported { .. } => ("unsupported", 3),
172 crate::ApiError::Rejected { .. } => ("rejected", 1),
173 crate::ApiError::Io { .. } => ("input-error", 2),
174 crate::ApiError::BudgetStartup(_) | crate::ApiError::BudgetMeasurement(_) => {
175 ("internal-error", 4)
176 }
177 };
178 document["result"] = json!(kind);
179 document["message"] = json!(e.to_string());
180 document["exit_code"] = json!(exit);
181 return Ok(DfidReport { document, exit });
182 }
183 };
184 document["startup_output"] = json!(
185 model
186 .model()
187 .output
188 .iter()
189 .map(|m| match m {
190 dive_model::Message::Print(text) => json!({"kind": "print", "text": text}),
191 dive_model::Message::Warning { code, message } =>
192 json!({"kind": "warning", "code": code.code(), "text": message}),
193 })
194 .collect::<Vec<_>>()
195 );
196 let mut run_budget = crate::mode_budget::ModeBudget::start(
197 dive_runtime::budget::Phase::Dfid,
198 req.time_limit,
199 req.max_memory,
200 )?;
201 let control = run_budget.control()?;
202 let control_scope =
203 control
204 .enter(&model.model().evaluator)
205 .map_err(|error| crate::ApiError::Rejected {
206 message: error.to_string(),
207 })?;
208 let mut check = if req.compat_tlc {
209 dive_runtime::CheckOptions::tlc(req.fp, seed)
210 } else {
211 dive_runtime::CheckOptions::dive(seed)
212 };
213 check.budget = run_budget.budget.clone();
214 check.fp_index = req.fp;
215 check.workers = req.workers.unwrap_or(1);
216 check.no_deadlock = req.no_deadlock;
217 if req.exact {
218 check.store = dive_store::StoreMode::Exact;
219 }
220 let mut options = Options::new(check, req.max_level);
221 options.worker_seeds.clone_from(&req.worker_seeds);
222 let mut native = None;
223 let mut setup_failure = None;
224 {
225 if let Some(outcome) = crate::dfid_admission::preflight(model.model(), &options) {
226 setup_failure = Some(outcome);
227 } else {
228 match crate::core_modes::Native::probe(
229 &model,
230 seed,
231 if req.compat_tlc {
232 dive_stdlib::random::RandomMode::Tlc
233 } else {
234 dive_stdlib::random::RandomMode::Dive
235 },
236 &run_budget.budget,
237 control.clone(),
238 ) {
239 Ok(prepared) => native = Some(prepared),
240 Err(error) => setup_failure = Some(error.dfid()),
241 }
242 }
243 }
244 document["engine"] = json!("core");
245 document["engine_fallback"] = Value::Null;
247 document["options"]["execution_scope"] = json!("compiled-plan-dfid");
248 let executed = std::thread::scope(|scope| {
249 std::thread::Builder::new()
250 .stack_size(dive_eval::RECOMMENDED_STACK)
251 .spawn_scoped(scope, || {
252 if let Some(failure) = setup_failure {
253 crate::core_modes::dfid::empty(failure)
254 } else if let Some(native) = &mut native {
255 native.dfid(model.model(), &options)
256 } else {
257 crate::core_modes::dfid::empty(Outcome::Internal(
258 "Core DFID was neither prepared nor refused".to_owned(),
259 ))
260 }
261 })
262 .map_err(|e| (0u8, format!("cannot start DFID worker: {e}")))?
263 .join()
264 .map_err(|_| {
265 (
266 1u8,
267 "DFID worker failed internally; statistics unavailable".to_owned(),
268 )
269 })
270 });
271 let report = match executed {
272 Ok(report) => report,
273 Err((workers, message)) => {
274 document["options"]["workers_used"] = json!(workers);
275 document["options"]["execution_stage"] = json!(if workers == 0 {
276 "worker-start"
277 } else {
278 "worker-failure"
279 });
280 document["message"] = json!(message);
281 document["exit_code"] = json!(4);
282 return Ok(DfidReport { document, exit: 4 });
283 }
284 };
285 let (mut kind, code, mut message, mut exit) = match &report.outcome {
286 Outcome::Complete => ("complete", None, None, 0),
287 Outcome::Incomplete => (
288 "incomplete",
289 None,
290 Some("DFID iterative depth bound reached without completion".to_owned()),
291 if req.compat_tlc {
292 if req.max_level < 2 { 255 } else { 0 }
293 } else {
294 3
295 },
296 ),
297 Outcome::Violation { code, .. } => (
298 "violation",
299 Some(*code),
300 None,
301 if req.compat_tlc {
302 tlc_exit(*code)
303 } else if *code == 2114 {
304 11
305 } else {
306 10
307 },
308 ),
309 Outcome::Error { code, message } => (
310 "evaluation-error",
311 Some(*code),
312 Some(message.clone()),
313 if req.compat_tlc { tlc_exit(*code) } else { 13 },
314 ),
315 Outcome::Unsupported(s) => ("unsupported", None, Some(s.clone()), 3),
316 Outcome::Limit(s) => ("resource-limit", None, Some(s.clone()), 3),
317 Outcome::Cancelled => (
318 "resource-limit",
319 None,
320 Some("DFID run budget exhausted".to_owned()),
321 3,
322 ),
323 Outcome::Internal(s) => ("internal-error", None, Some(s.clone()), 4),
324 };
325 let observed_kind = kind;
326 let mut violation_validated = false;
327 if let Outcome::Violation {
328 kind: violation_kind,
329 name,
330 ..
331 } = &report.outcome
332 {
333 match witness(
334 &model,
335 &report.trace,
336 violation_kind,
337 name.as_deref(),
338 &run_budget.budget,
339 control.clone(),
340 ) {
341 Ok((trace, validation)) => {
342 document["counterexample"] = json!({"trace": trace.to_json(), "validation": crate::trace::report_json(&validation)});
343 match validation.validation {
344 Validation::Valid => violation_validated = true,
345 Validation::Unsupported(feature) => {
346 kind = "unsupported";
347 exit = 3;
348 message = Some(format!("independent DFID witness validation: {feature}"));
349 }
350 _ => {
352 kind = "internal-error";
353 exit = 4;
354 message = Some(
355 "independent DFID witness validation rejected the candidate".to_owned(),
356 );
357 }
358 }
359 }
360 Err(feature) => {
361 kind = "unsupported";
362 exit = 3;
363 message = Some(feature);
364 }
365 }
366 }
367 document["result"] = json!(kind);
368 document["observed_result"] = json!(observed_kind);
369 document["observed_deciding"] = json!(report.deciding.as_ref().map(|o| format!("{o:?}")));
370 document["observed_tlc_code"] = json!(code);
371 document["tlc_code"] = json!(if observed_kind == kind { code } else { None });
372 document["message"] = json!(message);
373 document["exit_code"] = json!(exit);
374 document["violation_validated"] = json!(violation_validated);
375 document["exhaustive"] = json!(matches!(report.outcome, Outcome::Complete));
376 document["model_proved"] = json!(matches!(report.outcome, Outcome::Complete));
377 document["termination"] = json!(if matches!(report.outcome, Outcome::Complete) {
378 "visitation-certificate"
379 } else {
380 report.stage
381 });
382 document["tlc_completion_message"] = json!(report.tlc_completion_message);
383 document["options"]["workers_used"] = json!(u8::from(report.stage != "preflight"));
384 document["options"]["execution_stage"] = json!(report.stage);
385 document["options"]["wrapper_threads_used"] = json!(1);
386 document["compatibility_claim"] = json!(
387 "documented pure safety search fields only; raw display and collision probabilities pending"
388 );
389 document["options"]["worker_seeds"] = json!(report.worker_seeds);
390 document["statistics"] = json!({"scope": if matches!(report.outcome, Outcome::Complete) {"complete-model"} else {"completed-prefix"}, "generated": report.generated, "distinct": report.distinct, "initial_candidates": report.initial_candidates, "level": report.level});
391 drop(control_scope);
392 run_budget.finish(
393 &mut document,
394 &mut exit,
395 matches!(report.outcome, Outcome::Cancelled),
396 )?;
397 Ok(DfidReport { document, exit })
398}
399
400fn witness(
401 model: &SpecModel,
402 states: &[dive_eval::next::StateVals],
403 kind: &str,
404 name: Option<&str>,
405 budget: &dive_runtime::budget::Budget,
406 control: std::sync::Arc<dyn dive_eval::HostControl>,
407) -> Result<(TraceDoc, crate::trace::Report), String> {
408 let mut objects = Vec::new();
409 for state in states {
410 if budget.poll() != Ok(None) {
411 return Err("run budget exhausted during DFID witness serialization".to_owned());
412 }
413 let mut object = serde_json::Map::new();
414 for (var, value) in model.model().ir.vars().iter().zip(state.iter()) {
415 let value = value
416 .as_ref()
417 .ok_or_else(|| "incomplete DFID witness state".to_owned())?;
418 object.insert(
419 model.model().ir.decl(*var).name.clone(),
420 dive_trace::value_json::to_json(value, model.model().evaluator.options().ctx)?,
421 );
422 }
423 objects.push(Value::Object(object));
424 }
425 let ending = match kind {
426 "invariant" => Ending::Invariant(name.unwrap_or_default().to_owned()),
427 "property" => Ending::Property(name.unwrap_or_default().to_owned()),
428 _ => Ending::Deadlock,
429 };
430 let document = TraceDoc::behavior(objects)?.with_ending(ending);
431 let validation = model
432 .validate_mode(&document, control)
433 .map_err(|error| error.to_string())?;
434 Ok((document, validation))
435}
436
437fn tlc_exit(code: u32) -> u8 {
438 match code {
439 1102 => 1,
440 2104 => 10,
441 2114 => 11,
442 2107 | 2110 => 12,
443 2108 | 2112 => 13,
444 2103 | 2109 => 75,
445 _ => 255,
446 }
447}