1use std::sync::Arc;
4
5use dive_eval::{Ec, ErrorClass, EvalError, HostControl, St, ValueMethod};
6use dive_model::Model;
7
8use crate::ordered::{Driver, Event, Site};
9use crate::{Check, Failure, State, Validation};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct InitialInvariantClass {
18 reported: u32,
19 deciding: u32,
20}
21
22impl InitialInvariantClass {
23 #[must_use]
25 pub const fn reported_code(self) -> u32 {
26 self.reported
27 }
28
29 #[must_use]
31 pub const fn deciding_code(self) -> u32 {
32 self.deciding
33 }
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum InitialErrorStage {
41 Generation,
43 InvariantReceiver,
45 LegacyInvariant,
47}
48
49#[allow(
50 clippy::too_many_lines,
51 reason = "first-event routing retains both actual no-word diagnostic lifecycles"
52)]
53pub(crate) fn stage(
54 model: &Model,
55 host: &crate::validate::TraceHost,
56 control: Option<&dyn HostControl>,
57) -> Result<(Validation, Option<InitialErrorStage>), EvalError> {
58 let empty = Arc::from(vec![None; model.ir.vars().len()]);
59 let driver = Driver {
60 initial: true,
61 model,
62 source: &empty,
63 level: 0,
64 host,
65 control,
66 };
67 if let Some(refusal) = crate::next_error::preflight(model, true, control)? {
68 return Ok((refusal, None));
69 }
70 let (event, emitted) = driver.primary_with_count(false)?;
71 driver.poll()?;
72 let reached = match event {
73 Event::Error {
74 site: Site::Init,
75 error,
76 ..
77 } if emitted == 0 && error.value_method().is_some() => {
78 let mut yielded = false;
79 let diagnostic =
80 model
81 .evaluator
82 .init_states_diagnostic(&model.init_actions, &mut |_| {
83 yielded = true;
84 dive_eval::next::Flow::Stop
85 });
86 driver.poll()?;
87 let secondary = match diagnostic {
88 Err(failure)
89 if matches!(
90 failure.error.class(),
91 ErrorClass::Interrupted | ErrorClass::ResourceLimit | ErrorClass::Bug
92 ) =>
93 {
94 return Err(failure.error);
95 }
96 Err(failure) if !yielded && failure.emitted == 0 => failure.error,
97 _ => {
98 return Ok((
99 Validation::Unsupported(
100 "diagnostic Init does not reproduce its pre-emission error".into(),
101 ),
102 None,
103 ));
104 }
105 };
106 if !same_receiver(&error, &secondary) {
107 if matches!(
108 secondary.class(),
109 ErrorClass::Interrupted | ErrorClass::ResourceLimit | ErrorClass::Bug
110 ) {
111 return Err(secondary);
112 }
113 return Ok((
114 Validation::Unsupported("diagnostic Init receiver class is unproved".into()),
115 None,
116 ));
117 }
118 InitialErrorStage::Generation
119 }
120 Event::Error {
121 site: Site::Invariant,
122 error,
123 candidate: Some(candidate),
124 ..
125 } if emitted == 1 => match error
126 .value_method()
127 .map(dive_eval::ValueMethodFailure::method)
128 {
129 Some(ValueMethod::TupleEquals | ValueMethod::RecordEquals)
130 if error.ec() == Ec::General && !error.is_eval_exception() =>
131 {
132 InitialErrorStage::InvariantReceiver
133 }
134 Some(ValueMethod::FunctionMaterialize) if error.is_eval_exception() => {
135 let Some(first) = model.invariants.first() else {
136 return Ok((
137 Validation::Unsupported("legacy initial invariant is missing".into()),
138 None,
139 ));
140 };
141 if !model.constraints.is_empty()
142 || model
143 .ir
144 .node(first.pred.expr)
145 .effects
146 .intersects(dive_ir::Effects::IMPURE)
147 || model.evaluator.scope_has_effects(&first.pred.scope)
148 || !closed_state(model, &candidate, &driver)?
149 {
150 return Ok((
151 Validation::Unsupported(
152 "legacy initial invariant history is unproved".into(),
153 ),
154 None,
155 ));
156 }
157 host.set_replay_level(1);
158 let Err(secondary) = model.eval(&first.pred, &St::state(candidate).diagnostic())
159 else {
160 return Ok((
161 Validation::Unsupported("legacy diagnostic invariant completes".into()),
162 None,
163 ));
164 };
165 if !same_receiver(&error, &secondary) {
166 if matches!(
167 secondary.class(),
168 ErrorClass::Interrupted | ErrorClass::ResourceLimit | ErrorClass::Bug
169 ) {
170 return Err(secondary);
171 }
172 return Ok((
173 Validation::Unsupported(
174 "legacy initial invariant diagnostic class is unproved".into(),
175 ),
176 None,
177 ));
178 }
179 InitialErrorStage::LegacyInvariant
180 }
181 _ => {
182 return Ok((
183 Validation::Unsupported("unproved initial receiver lifecycle".into()),
184 None,
185 ));
186 }
187 },
188 Event::Refused(reason) => return Ok((Validation::Unsupported(reason), None)),
189 _ => {
190 return Ok((
191 Validation::Unsupported(
192 "source does not establish a bounded first initial error".into(),
193 ),
194 None,
195 ));
196 }
197 };
198 Ok((Validation::Valid, Some(reached)))
199}
200
201#[allow(
202 clippy::too_many_lines,
203 reason = "one actual primary/diagnostic receiver lifecycle retains private history"
204)]
205pub(crate) fn replay(
206 model: &Model,
207 state: &State,
208 name: &str,
209 ec: &str,
210 host: &crate::validate::TraceHost,
211 control: Option<&dyn HostControl>,
212) -> Result<(Validation, Option<InitialInvariantClass>), EvalError> {
213 let driver = Driver {
214 initial: true,
215 model,
216 source: state,
217 level: 0,
218 host,
219 control,
220 };
221 driver.poll()?;
222 if let Some(refusal) = crate::next_error::preflight(model, true, control)? {
223 return Ok((refusal, None));
224 }
225 let Some(first) = model.invariants.first().filter(|first| first.name == name) else {
226 return Ok(refused(
227 "initial receiver replay requires the first configured invariant",
228 ));
229 };
230 if !model.constraints.is_empty()
231 || model
232 .ir
233 .node(first.pred.expr)
234 .effects
235 .intersects(dive_ir::Effects::IMPURE)
236 || model.evaluator.scope_has_effects(&first.pred.scope)
237 {
238 return Ok(refused(
239 "initial receiver replay with constraints or invariant effects",
240 ));
241 }
242 let (primary, original) = match driver.primary(false)? {
243 Event::Error {
244 site: Site::Invariant,
245 error,
246 candidate: Some(candidate),
247 ..
248 } => (error, candidate),
249 Event::Refused(reason) => return Ok((Validation::Unsupported(reason), None)),
250 Event::Failed { check, detail } => {
251 return Ok((
252 Validation::Invalid(Failure {
253 state: 0,
254 check,
255 detail,
256 }),
257 None,
258 ));
259 }
260 _ => {
261 return Ok(refused(
262 "the first Init operation does not fail at the claimed invariant",
263 ));
264 }
265 };
266 if !closed_state(model, &original, &driver)? || original != *state {
267 return Ok(refused(
268 "the first actual Init emission differs or retains unproved value history",
269 ));
270 }
271 if primary.class() != ErrorClass::Eval || primary.ec().name() != ec {
272 return Ok((
273 invalid("the actual first invariant has a different underlying cause"),
274 None,
275 ));
276 }
277 let Some(_receiver) = primary.value_method().filter(|receiver| {
278 matches!(
279 receiver.method(),
280 ValueMethod::TupleEquals | ValueMethod::RecordEquals
281 )
282 }) else {
283 return Ok(refused(
284 "the initial invariant has no certified tuple/record receiver catch",
285 ));
286 };
287 if primary.ec() != Ec::General || primary.is_eval_exception() {
291 return Ok(refused(
292 "the original initial receiver exception constructor is unproved",
293 ));
294 }
295 host.set_replay_level(0);
299 let mut diagnostic = None;
300 let mut stopped = None;
301 let generated = model
302 .evaluator
303 .init_states_diagnostic(&model.init_actions, &mut |candidate| {
304 let attempt = (|| {
305 driver.poll()?;
306 if candidate.ordinal != 0
307 || !candidate.complete()
308 || !closed_state(model, candidate.state, &driver)?
309 || candidate.state != original.as_ref()
310 {
311 return Ok(None);
312 }
313 host.set_replay_level(1);
314 let context = St::state(Arc::from(candidate.state)).diagnostic();
315 match model.eval(&first.pred, &context) {
316 Err(error)
317 if matches!(
318 error.class(),
319 ErrorClass::Interrupted | ErrorClass::ResourceLimit | ErrorClass::Bug
320 ) =>
321 {
322 Err(error)
323 }
324 Err(error) => Ok(Some(error)),
325 Ok(_) => Ok(None),
326 }
327 })();
328 match attempt {
329 Ok(error) => diagnostic = error,
330 Err(error) => stopped = Some(error),
331 }
332 dive_eval::next::Flow::Stop
333 });
334 driver.poll()?;
335 if let Some(error) = stopped {
336 return Err(error);
337 }
338 if let Err(failure) = generated {
339 return if matches!(
340 failure.error.class(),
341 ErrorClass::Interrupted | ErrorClass::ResourceLimit | ErrorClass::Bug
342 ) {
343 Err(failure.error)
344 } else {
345 Ok(refused(
346 "diagnostic Init fails before the original invariant receiver",
347 ))
348 };
349 }
350 let Some(diagnostic) = diagnostic else {
351 return Ok(refused(
352 "diagnostic Init cannot reconstruct the first invariant failure",
353 ));
354 };
355 if !same_receiver(&primary, &diagnostic) {
356 return Ok(refused(
357 "diagnostic receiver construction/source lifetime is not certified",
358 ));
359 }
360 driver.poll()?;
361 Ok((
362 Validation::Valid,
363 Some(InitialInvariantClass {
364 reported: 2102,
365 deciding: 2147,
366 }),
367 ))
368}
369
370fn same_receiver(primary: &EvalError, diagnostic: &EvalError) -> bool {
371 primary.class() == ErrorClass::Eval
372 && diagnostic.class() == ErrorClass::Eval
373 && primary.ec() == diagnostic.ec()
374 && primary.is_eval_exception() == diagnostic.is_eval_exception()
375 && primary.exception_kind() == diagnostic.exception_kind()
376 && primary.origin().is_some()
377 && primary.origin() == diagnostic.origin()
378 && primary.value_method().is_some_and(|receiver| {
379 diagnostic.value_method().is_some_and(|actual| {
380 actual.method() == receiver.method()
381 && actual.constructor() == receiver.constructor()
382 && actual.source().is_some()
383 })
384 })
385}
386
387fn closed_state(
388 model: &Model,
389 state: &[Option<dive_value::Value>],
390 driver: &Driver<'_>,
391) -> Result<bool, EvalError> {
392 let mut stopped = None;
393 let mut proceed = || match driver.poll() {
394 Ok(()) => true,
395 Err(error) => {
396 stopped = Some(error);
397 false
398 }
399 };
400 let closed = state.iter().all(|value| {
401 value.as_ref().is_some_and(|value| {
402 value
403 .closed_function_cache_heap_bytes(&model.names, &mut proceed)
404 .is_some()
405 })
406 });
407 if let Some(error) = stopped {
408 Err(error)
409 } else {
410 Ok(closed)
411 }
412}
413
414fn refused(reason: &str) -> (Validation, Option<InitialInvariantClass>) {
415 (Validation::Unsupported(reason.into()), None)
416}
417
418fn invalid(detail: &str) -> Validation {
419 Validation::Invalid(Failure {
420 state: 0,
421 check: Check::Ending,
422 detail: detail.into(),
423 })
424}