dive-trace 0.1.0

TLA+ counterexample trace format and independent trace validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Untrusted source context for independently replayed temporal row errors.

use dive_eval::{Ec, ErrorClass, EvalError};
use dive_model::Model;
use serde_json::{Value, json};

/// A request to validate the first source-state temporal demand error.
///
/// This contains no scope, predicate selector, execution proof or cached truth.
/// Only fresh source-bound validation may establish its claim. An older trace
/// reader retains the ordinary unsupported error ending.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TemporalStateEndpoint {
    module: String,
    start: u32,
    end: u32,
    instance: Option<String>,
}

impl TemporalStateEndpoint {
    /// Records an original inner error's source context, without certifying it.
    ///
    /// ```no_run
    /// # fn context(model: &dive_model::Model, error: &dive_eval::EvalError) {
    /// let request = dive_trace::TemporalStateEndpoint::from_error(model, error);
    /// // The independent validator must reconstruct and replay the demand.
    /// # let _ = request;
    /// # }
    /// ```
    #[must_use]
    pub fn from_error(model: &Model, error: &EvalError) -> Option<Self> {
        if error.class() != ErrorClass::Eval
            || !error.is_eval_exception()
            || !matches!(error.ec(), Ec::DivisionByZero | Ec::ModuleEvaluating)
        {
            return None;
        }
        Self::from_origin(&model.ir, error)
    }

    fn from_origin(ir: &dive_ir::Ir, error: &EvalError) -> Option<Self> {
        Self::from_expression(ir, error.origin()?)
    }

    fn from_expression(ir: &dive_ir::Ir, expression: dive_ir::ExprId) -> Option<Self> {
        let origin = ir.nodes().get(expression.index())?.origin;
        let file = ir.files().get(origin.file?.index())?;
        let instance = if let Some(definition) = origin.instance {
            let definition = ir.defs().get(definition.index())?;
            Some(format!(
                "{}: {}",
                definition.name,
                ir.location(&definition.origin)
            ))
        } else {
            None
        };
        Some(Self {
            module: file.module.clone(),
            start: origin.range.0,
            end: origin.range.1,
            instance,
        })
    }

    pub(crate) fn to_json(&self) -> Value {
        self.to_stage("temporal-state-row")
    }

    fn to_stage(&self, stage: &str) -> Value {
        json!({"stage":stage, "source":{
            "module":self.module,"start":self.start,"end":self.end,"instance":self.instance
        }})
    }

    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
        Self::from_stage(value, "temporal-state-row")
    }

    fn from_stage(value: &Value, stage: &str) -> Result<Self, String> {
        let object = value.as_object().ok_or("endpoint must be an object")?;
        if object.len() != 2 || value["stage"] != stage {
            return Err("unknown temporal error endpoint stage or fields".into());
        }
        let source = value["source"]
            .as_object()
            .ok_or("missing endpoint source")?;
        if source.len() != 4
            || !["module", "start", "end", "instance"]
                .iter()
                .all(|key| source.contains_key(*key))
        {
            return Err("unknown temporal error source fields".into());
        }
        let number = |key: &str| {
            value["source"][key]
                .as_u64()
                .and_then(|n| u32::try_from(n).ok())
                .ok_or_else(|| format!("invalid endpoint source {key}"))
        };
        let module = value["source"]["module"]
            .as_str()
            .filter(|s| !s.is_empty())
            .ok_or("invalid endpoint module")?
            .to_owned();
        let instance = if value["source"]["instance"].is_null() {
            None
        } else {
            Some(
                value["source"]["instance"]
                    .as_str()
                    .filter(|s| !s.is_empty())
                    .ok_or("invalid endpoint instance")?
                    .to_owned(),
            )
        };
        let start = number("start")?;
        let end = number("end")?;
        if start > end {
            return Err("reversed endpoint source range".into());
        }
        Ok(Self {
            module,
            start,
            end,
            instance,
        })
    }
}

/// Untrusted source of the first post-Next temporal-row error (native version 5).
/// Fresh replay reconstructs Next and the complete ordered demand lifecycle;
/// this descriptor contains no predicate selector or diagnostic-suppression flag.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TemporalSourceEndpoint {
    source: TemporalStateEndpoint,
}

impl TemporalSourceEndpoint {
    /// Records an observed row error's source without establishing its class.
    ///
    /// ```no_run
    /// # fn request(model: &dive_model::Model, error: &dive_eval::EvalError) {
    /// let request = dive_trace::TemporalSourceEndpoint::from_error(model, error);
    /// # let _ = request;
    /// # }
    /// ```
    #[must_use]
    pub fn from_error(model: &Model, error: &EvalError) -> Option<Self> {
        (error.class() == ErrorClass::Eval)
            .then(|| TemporalStateEndpoint::from_origin(&model.ir, error))
            .flatten()
            .map(|source| Self { source })
    }

    pub(crate) fn matches_error(&self, model: &Model, error: &EvalError) -> bool {
        Self::from_error(model, error).as_ref() == Some(self)
    }

    pub(crate) fn to_json(&self) -> Value {
        self.source.to_stage("temporal-source-row")
    }

    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
        TemporalStateEndpoint::from_stage(value, "temporal-source-row")
            .map(|source| Self { source })
    }
}

/// Untrusted original source context for a Next error before any successor.
/// The fresh validator enumerates the real configured actions independently;
/// this descriptor selects no expression, action, scope or cached value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NextStateEndpoint {
    source: TemporalStateEndpoint,
    ordered: Option<(u32, u32)>,
}

impl NextStateEndpoint {
    pub(crate) fn instantiated(&self) -> bool {
        self.source.instance.is_some()
    }

    /// Records an observed evaluation error's original source, without proof.
    /// The producer separately requires the typed Next error site.
    ///
    /// ```no_run
    /// # fn request(ir: &dive_ir::Ir, error: &dive_eval::EvalError) {
    /// let origin = dive_trace::NextStateEndpoint::from_error(ir, error);
    /// // The descriptor must still be checked by fresh independent replay.
    /// # let _ = origin;
    /// # }
    /// ```
    #[must_use]
    pub fn from_error(ir: &dive_ir::Ir, error: &EvalError) -> Option<Self> {
        (error.class() == ErrorClass::Eval)
            .then(|| TemporalStateEndpoint::from_origin(ir, error))
            .flatten()
            .map(|source| Self {
                source,
                ordered: None,
            })
    }

    /// Requests actual ordered primary and diagnostic Next replay. Reported
    /// and deciding codes are untrusted claims, not classifier overrides.
    #[must_use]
    pub fn from_ordered_error(
        ir: &dive_ir::Ir,
        error: &EvalError,
        reported: u32,
        deciding: u32,
    ) -> Option<Self> {
        let mut request = Self::from_error(ir, error)?;
        request.ordered = Some((reported, deciding));
        Some(request)
    }

    /// Claimed deciding code, requiring independent diagnostic replay.
    #[must_use]
    pub fn deciding_code(&self) -> Option<u32> {
        self.ordered.map(|(_, deciding)| deciding)
    }

    pub(crate) fn ordered_codes(&self) -> Option<(u32, u32)> {
        self.ordered
    }

    pub(crate) fn matches_error_source(&self, ir: &dive_ir::Ir, error: &EvalError) -> bool {
        TemporalStateEndpoint::from_origin(ir, error).as_ref() == Some(&self.source)
    }

    pub(crate) fn to_json(&self) -> Value {
        if let Some((reported, deciding)) = self.ordered {
            let mut value = self.source.to_stage("next-ordered-terminal");
            value["reported"] = Value::from(reported);
            value["deciding"] = Value::from(deciding);
            value
        } else {
            self.source.to_stage("next-before-successor")
        }
    }

    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
        if value["stage"] == "next-ordered-terminal" {
            let object = value.as_object().ok_or("Next endpoint must be an object")?;
            if object.len() != 4 {
                return Err("unknown ordered Next endpoint fields".into());
            }
            let code = |name: &str| {
                value[name]
                    .as_u64()
                    .and_then(|code| u32::try_from(code).ok())
                    .filter(|code| *code != 0)
                    .ok_or("invalid ordered Next error code")
            };
            let ordered = Some((code("reported")?, code("deciding")?));
            let mut source = value.clone();
            let context = source
                .as_object_mut()
                .ok_or("Next endpoint must be an object")?;
            context.remove("reported");
            context.remove("deciding");
            Ok(Self {
                source: TemporalStateEndpoint::from_stage(&source, "next-ordered-terminal")?,
                ordered,
            })
        } else {
            TemporalStateEndpoint::from_stage(value, "next-before-successor").map(|source| Self {
                source,
                ordered: None,
            })
        }
    }
}

/// Untrusted terminal partial bindings, distinct from every complete prefix row.
/// The source names the actual generating action; it selects no replay action.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PartialStateEndpoint {
    initial: bool,
    source: TemporalStateEndpoint,
    assignments: serde_json::Map<String, Value>,
    unassigned: Vec<String>,
}

/// Compatibility name for the original Next partial request.
pub type PartialNextEndpoint = PartialStateEndpoint;

impl PartialStateEndpoint {
    /// Records an actual incomplete candidate without certifying it.
    #[must_use]
    pub fn from_candidate(
        ir: &dive_ir::Ir,
        expression: dive_ir::ExprId,
        assignments: serde_json::Map<String, Value>,
        unassigned: Vec<String>,
    ) -> Option<Self> {
        (!unassigned.is_empty()).then_some(Self {
            initial: false,
            source: TemporalStateEndpoint::from_expression(ir, expression)?,
            assignments,
            unassigned,
        })
    }

    /// Records actual partial Init bindings and the observed generating source.
    #[must_use]
    pub fn from_initial_candidate(
        ir: &dive_ir::Ir,
        expression: dive_ir::ExprId,
        assignments: serde_json::Map<String, Value>,
        unassigned: Vec<String>,
    ) -> Option<Self> {
        let mut endpoint = Self::from_candidate(ir, expression, assignments, unassigned)?;
        endpoint.initial = true;
        Some(endpoint)
    }

    pub(crate) fn initial(&self) -> bool {
        self.initial
    }

    pub(crate) fn assignments(&self) -> &serde_json::Map<String, Value> {
        &self.assignments
    }

    pub(crate) fn unassigned(&self) -> &[String] {
        &self.unassigned
    }

    pub(crate) fn matches_source(&self, ir: &dive_ir::Ir, expression: dive_ir::ExprId) -> bool {
        TemporalStateEndpoint::from_expression(ir, expression).as_ref() == Some(&self.source)
    }

    pub(crate) fn to_json(&self) -> Value {
        let mut value = self.source.to_stage(if self.initial {
            "init-partial-state"
        } else {
            "next-partial-state"
        });
        value["assignments"] = Value::Object(self.assignments.clone());
        value["unassigned"] = serde_json::json!(self.unassigned);
        value
    }

    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
        let object = value
            .as_object()
            .ok_or("partial endpoint must be an object")?;
        if object.len() != 4
            || !object.contains_key("assignments")
            || !object.contains_key("unassigned")
        {
            return Err("unknown partial endpoint fields".into());
        }
        let mut context = value.clone();
        let object = context
            .as_object_mut()
            .ok_or("partial endpoint must be an object")?;
        object.remove("assignments");
        object.remove("unassigned");
        let stage = match value["stage"].as_str() {
            Some("next-partial-state") => "next-partial-state",
            Some("init-partial-state") => "init-partial-state",
            _ => return Err("unknown partial terminal stage".into()),
        };
        let source = TemporalStateEndpoint::from_stage(&context, stage)?;
        let assignments = value["assignments"]
            .as_object()
            .ok_or("partial assignments must be an object")?
            .clone();
        let unassigned: Vec<String> = value["unassigned"]
            .as_array()
            .ok_or("partial unassigned must be a list")?
            .iter()
            .map(|v| {
                v.as_str()
                    .filter(|s| !s.is_empty())
                    .map(str::to_owned)
                    .ok_or("partial unassigned needs variable names")
            })
            .collect::<Result<_, _>>()?;
        let names: std::collections::BTreeSet<_> = unassigned.iter().collect();
        if unassigned.is_empty()
            || names.len() != unassigned.len()
            || unassigned.iter().any(|name| assignments.contains_key(name))
        {
            return Err("partial assigned and unassigned variables must be disjoint, with at least one unassigned".into());
        }
        Ok(Self {
            initial: stage == "init-partial-state",
            source,
            assignments,
            unassigned,
        })
    }
}

/// The independently discovered candidate-side error site.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CandidateErrorSite {
    /// An ordered state constraint.
    Constraint,
    /// An ordered action constraint.
    ActionConstraint,
    /// An ordered implied action property.
    ImpliedAction,
}
impl CandidateErrorSite {
    pub(crate) fn name(self) -> &'static str {
        match self {
            Self::Constraint => "constraint",
            Self::ActionConstraint => "action-constraint",
            Self::ImpliedAction => "implied-action",
        }
    }
}

/// Untrusted candidate-side primary and diagnostic identities. This never
/// selects an expression, action or candidate during independent execution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CandidateStateEndpoint {
    pub(crate) next: NextStateEndpoint,
    pub(crate) site: CandidateErrorSite,
}
impl CandidateStateEndpoint {
    /// Records a typed producer observation; only fresh replay can prove it.
    #[must_use]
    pub fn from_error(
        ir: &dive_ir::Ir,
        error: &EvalError,
        site: CandidateErrorSite,
        reported: u32,
        deciding: u32,
    ) -> Option<Self> {
        Some(Self {
            next: NextStateEndpoint::from_ordered_error(ir, error, reported, deciding)?,
            site,
        })
    }

    /// The untrusted deciding identity, checked against the report and replay.
    #[must_use]
    pub fn deciding_code(&self) -> Option<u32> {
        self.next.deciding_code()
    }

    pub(crate) fn to_json(&self) -> Value {
        let mut value = self.next.to_json();
        value["stage"] = Value::from("candidate-ordered-terminal");
        value["site"] = Value::from(self.site.name());
        value
    }

    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
        let mut value = value.clone();
        let object = value
            .as_object_mut()
            .ok_or("candidate endpoint must be an object")?;
        if object.len() != 5
            || object.get("stage").and_then(Value::as_str) != Some("candidate-ordered-terminal")
        {
            return Err("unknown candidate endpoint fields or stage".into());
        }
        let site = match object
            .remove("site")
            .and_then(|v| v.as_str().map(str::to_owned))
            .as_deref()
        {
            Some("constraint") => CandidateErrorSite::Constraint,
            Some("action-constraint") => CandidateErrorSite::ActionConstraint,
            Some("implied-action") => CandidateErrorSite::ImpliedAction,
            _ => return Err("unknown candidate error site".into()),
        };
        object.insert("stage".into(), Value::from("next-ordered-terminal"));
        Ok(Self {
            next: NextStateEndpoint::from_json(&value)?,
            site,
        })
    }
}

/// Untrusted source of a VIEW failure while expanding the last complete row.
/// Native version 6 preserves that source-final word; actual fresh prefix and
/// diagnostic execution supply the candidate, admission history and identities.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViewSourceEndpoint {
    next: NextStateEndpoint,
}
impl ViewSourceEndpoint {
    /// Records typed source and identity observations without certifying them.
    #[must_use]
    pub fn from_error(
        ir: &dive_ir::Ir,
        error: &EvalError,
        reported: u32,
        deciding: u32,
    ) -> Option<Self> {
        Some(Self {
            next: NextStateEndpoint::from_ordered_error(ir, error, reported, deciding)?,
        })
    }
    /// Claimed primary wrapper, independently checked during execution.
    #[must_use]
    pub fn reported_code(&self) -> u32 {
        self.next.ordered.map_or(0, |pair| pair.0)
    }
    /// Claimed diagnostic identity, independently checked during execution.
    #[must_use]
    pub fn deciding_code(&self) -> u32 {
        self.next.ordered.map_or(0, |pair| pair.1)
    }
    pub(crate) fn matches_error(&self, ir: &dive_ir::Ir, error: &EvalError) -> bool {
        self.next.matches_error_source(ir, error)
    }
    pub(crate) fn to_json(&self) -> Value {
        let mut value = self.next.to_json();
        value["stage"] = Value::from("view-source-terminal");
        value
    }
    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
        if value["stage"] != "view-source-terminal" {
            return Err("unknown VIEW endpoint stage".into());
        }
        let mut value = value.clone();
        value["stage"] = Value::from("next-ordered-terminal");
        Ok(Self {
            next: NextStateEndpoint::from_json(&value)?,
        })
    }
}