Skip to main content

dive_trace/
endpoint.rs

1//! Untrusted source context for independently replayed temporal row errors.
2
3use dive_eval::{Ec, ErrorClass, EvalError};
4use dive_model::Model;
5use serde_json::{Value, json};
6
7/// A request to validate the first source-state temporal demand error.
8///
9/// This contains no scope, predicate selector, execution proof or cached truth.
10/// Only fresh source-bound validation may establish its claim. An older trace
11/// reader retains the ordinary unsupported error ending.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct TemporalStateEndpoint {
14    module: String,
15    start: u32,
16    end: u32,
17    instance: Option<String>,
18}
19
20impl TemporalStateEndpoint {
21    /// Records an original inner error's source context, without certifying it.
22    ///
23    /// ```no_run
24    /// # fn context(model: &dive_model::Model, error: &dive_eval::EvalError) {
25    /// let request = dive_trace::TemporalStateEndpoint::from_error(model, error);
26    /// // The independent validator must reconstruct and replay the demand.
27    /// # let _ = request;
28    /// # }
29    /// ```
30    #[must_use]
31    pub fn from_error(model: &Model, error: &EvalError) -> Option<Self> {
32        if error.class() != ErrorClass::Eval
33            || !error.is_eval_exception()
34            || !matches!(error.ec(), Ec::DivisionByZero | Ec::ModuleEvaluating)
35        {
36            return None;
37        }
38        Self::from_origin(&model.ir, error)
39    }
40
41    fn from_origin(ir: &dive_ir::Ir, error: &EvalError) -> Option<Self> {
42        Self::from_expression(ir, error.origin()?)
43    }
44
45    fn from_expression(ir: &dive_ir::Ir, expression: dive_ir::ExprId) -> Option<Self> {
46        let origin = ir.nodes().get(expression.index())?.origin;
47        let file = ir.files().get(origin.file?.index())?;
48        let instance = if let Some(definition) = origin.instance {
49            let definition = ir.defs().get(definition.index())?;
50            Some(format!(
51                "{}: {}",
52                definition.name,
53                ir.location(&definition.origin)
54            ))
55        } else {
56            None
57        };
58        Some(Self {
59            module: file.module.clone(),
60            start: origin.range.0,
61            end: origin.range.1,
62            instance,
63        })
64    }
65
66    pub(crate) fn to_json(&self) -> Value {
67        self.to_stage("temporal-state-row")
68    }
69
70    fn to_stage(&self, stage: &str) -> Value {
71        json!({"stage":stage, "source":{
72            "module":self.module,"start":self.start,"end":self.end,"instance":self.instance
73        }})
74    }
75
76    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
77        Self::from_stage(value, "temporal-state-row")
78    }
79
80    fn from_stage(value: &Value, stage: &str) -> Result<Self, String> {
81        let object = value.as_object().ok_or("endpoint must be an object")?;
82        if object.len() != 2 || value["stage"] != stage {
83            return Err("unknown temporal error endpoint stage or fields".into());
84        }
85        let source = value["source"]
86            .as_object()
87            .ok_or("missing endpoint source")?;
88        if source.len() != 4
89            || !["module", "start", "end", "instance"]
90                .iter()
91                .all(|key| source.contains_key(*key))
92        {
93            return Err("unknown temporal error source fields".into());
94        }
95        let number = |key: &str| {
96            value["source"][key]
97                .as_u64()
98                .and_then(|n| u32::try_from(n).ok())
99                .ok_or_else(|| format!("invalid endpoint source {key}"))
100        };
101        let module = value["source"]["module"]
102            .as_str()
103            .filter(|s| !s.is_empty())
104            .ok_or("invalid endpoint module")?
105            .to_owned();
106        let instance = if value["source"]["instance"].is_null() {
107            None
108        } else {
109            Some(
110                value["source"]["instance"]
111                    .as_str()
112                    .filter(|s| !s.is_empty())
113                    .ok_or("invalid endpoint instance")?
114                    .to_owned(),
115            )
116        };
117        let start = number("start")?;
118        let end = number("end")?;
119        if start > end {
120            return Err("reversed endpoint source range".into());
121        }
122        Ok(Self {
123            module,
124            start,
125            end,
126            instance,
127        })
128    }
129}
130
131/// Untrusted source of the first post-Next temporal-row error (native version 5).
132/// Fresh replay reconstructs Next and the complete ordered demand lifecycle;
133/// this descriptor contains no predicate selector or diagnostic-suppression flag.
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub struct TemporalSourceEndpoint {
136    source: TemporalStateEndpoint,
137}
138
139impl TemporalSourceEndpoint {
140    /// Records an observed row error's source without establishing its class.
141    ///
142    /// ```no_run
143    /// # fn request(model: &dive_model::Model, error: &dive_eval::EvalError) {
144    /// let request = dive_trace::TemporalSourceEndpoint::from_error(model, error);
145    /// # let _ = request;
146    /// # }
147    /// ```
148    #[must_use]
149    pub fn from_error(model: &Model, error: &EvalError) -> Option<Self> {
150        (error.class() == ErrorClass::Eval)
151            .then(|| TemporalStateEndpoint::from_origin(&model.ir, error))
152            .flatten()
153            .map(|source| Self { source })
154    }
155
156    pub(crate) fn matches_error(&self, model: &Model, error: &EvalError) -> bool {
157        Self::from_error(model, error).as_ref() == Some(self)
158    }
159
160    pub(crate) fn to_json(&self) -> Value {
161        self.source.to_stage("temporal-source-row")
162    }
163
164    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
165        TemporalStateEndpoint::from_stage(value, "temporal-source-row")
166            .map(|source| Self { source })
167    }
168}
169
170/// Untrusted original source context for a Next error before any successor.
171/// The fresh validator enumerates the real configured actions independently;
172/// this descriptor selects no expression, action, scope or cached value.
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct NextStateEndpoint {
175    source: TemporalStateEndpoint,
176    ordered: Option<(u32, u32)>,
177}
178
179impl NextStateEndpoint {
180    pub(crate) fn instantiated(&self) -> bool {
181        self.source.instance.is_some()
182    }
183
184    /// Records an observed evaluation error's original source, without proof.
185    /// The producer separately requires the typed Next error site.
186    ///
187    /// ```no_run
188    /// # fn request(ir: &dive_ir::Ir, error: &dive_eval::EvalError) {
189    /// let origin = dive_trace::NextStateEndpoint::from_error(ir, error);
190    /// // The descriptor must still be checked by fresh independent replay.
191    /// # let _ = origin;
192    /// # }
193    /// ```
194    #[must_use]
195    pub fn from_error(ir: &dive_ir::Ir, error: &EvalError) -> Option<Self> {
196        (error.class() == ErrorClass::Eval)
197            .then(|| TemporalStateEndpoint::from_origin(ir, error))
198            .flatten()
199            .map(|source| Self {
200                source,
201                ordered: None,
202            })
203    }
204
205    /// Requests actual ordered primary and diagnostic Next replay. Reported
206    /// and deciding codes are untrusted claims, not classifier overrides.
207    #[must_use]
208    pub fn from_ordered_error(
209        ir: &dive_ir::Ir,
210        error: &EvalError,
211        reported: u32,
212        deciding: u32,
213    ) -> Option<Self> {
214        let mut request = Self::from_error(ir, error)?;
215        request.ordered = Some((reported, deciding));
216        Some(request)
217    }
218
219    /// Claimed deciding code, requiring independent diagnostic replay.
220    #[must_use]
221    pub fn deciding_code(&self) -> Option<u32> {
222        self.ordered.map(|(_, deciding)| deciding)
223    }
224
225    pub(crate) fn ordered_codes(&self) -> Option<(u32, u32)> {
226        self.ordered
227    }
228
229    pub(crate) fn matches_error_source(&self, ir: &dive_ir::Ir, error: &EvalError) -> bool {
230        TemporalStateEndpoint::from_origin(ir, error).as_ref() == Some(&self.source)
231    }
232
233    pub(crate) fn to_json(&self) -> Value {
234        if let Some((reported, deciding)) = self.ordered {
235            let mut value = self.source.to_stage("next-ordered-terminal");
236            value["reported"] = Value::from(reported);
237            value["deciding"] = Value::from(deciding);
238            value
239        } else {
240            self.source.to_stage("next-before-successor")
241        }
242    }
243
244    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
245        if value["stage"] == "next-ordered-terminal" {
246            let object = value.as_object().ok_or("Next endpoint must be an object")?;
247            if object.len() != 4 {
248                return Err("unknown ordered Next endpoint fields".into());
249            }
250            let code = |name: &str| {
251                value[name]
252                    .as_u64()
253                    .and_then(|code| u32::try_from(code).ok())
254                    .filter(|code| *code != 0)
255                    .ok_or("invalid ordered Next error code")
256            };
257            let ordered = Some((code("reported")?, code("deciding")?));
258            let mut source = value.clone();
259            let context = source
260                .as_object_mut()
261                .ok_or("Next endpoint must be an object")?;
262            context.remove("reported");
263            context.remove("deciding");
264            Ok(Self {
265                source: TemporalStateEndpoint::from_stage(&source, "next-ordered-terminal")?,
266                ordered,
267            })
268        } else {
269            TemporalStateEndpoint::from_stage(value, "next-before-successor").map(|source| Self {
270                source,
271                ordered: None,
272            })
273        }
274    }
275}
276
277/// Untrusted terminal partial bindings, distinct from every complete prefix row.
278/// The source names the actual generating action; it selects no replay action.
279#[derive(Clone, Debug, PartialEq, Eq)]
280pub struct PartialStateEndpoint {
281    initial: bool,
282    source: TemporalStateEndpoint,
283    assignments: serde_json::Map<String, Value>,
284    unassigned: Vec<String>,
285}
286
287/// Compatibility name for the original Next partial request.
288pub type PartialNextEndpoint = PartialStateEndpoint;
289
290impl PartialStateEndpoint {
291    /// Records an actual incomplete candidate without certifying it.
292    #[must_use]
293    pub fn from_candidate(
294        ir: &dive_ir::Ir,
295        expression: dive_ir::ExprId,
296        assignments: serde_json::Map<String, Value>,
297        unassigned: Vec<String>,
298    ) -> Option<Self> {
299        (!unassigned.is_empty()).then_some(Self {
300            initial: false,
301            source: TemporalStateEndpoint::from_expression(ir, expression)?,
302            assignments,
303            unassigned,
304        })
305    }
306
307    /// Records actual partial Init bindings and the observed generating source.
308    #[must_use]
309    pub fn from_initial_candidate(
310        ir: &dive_ir::Ir,
311        expression: dive_ir::ExprId,
312        assignments: serde_json::Map<String, Value>,
313        unassigned: Vec<String>,
314    ) -> Option<Self> {
315        let mut endpoint = Self::from_candidate(ir, expression, assignments, unassigned)?;
316        endpoint.initial = true;
317        Some(endpoint)
318    }
319
320    pub(crate) fn initial(&self) -> bool {
321        self.initial
322    }
323
324    pub(crate) fn assignments(&self) -> &serde_json::Map<String, Value> {
325        &self.assignments
326    }
327
328    pub(crate) fn unassigned(&self) -> &[String] {
329        &self.unassigned
330    }
331
332    pub(crate) fn matches_source(&self, ir: &dive_ir::Ir, expression: dive_ir::ExprId) -> bool {
333        TemporalStateEndpoint::from_expression(ir, expression).as_ref() == Some(&self.source)
334    }
335
336    pub(crate) fn to_json(&self) -> Value {
337        let mut value = self.source.to_stage(if self.initial {
338            "init-partial-state"
339        } else {
340            "next-partial-state"
341        });
342        value["assignments"] = Value::Object(self.assignments.clone());
343        value["unassigned"] = serde_json::json!(self.unassigned);
344        value
345    }
346
347    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
348        let object = value
349            .as_object()
350            .ok_or("partial endpoint must be an object")?;
351        if object.len() != 4
352            || !object.contains_key("assignments")
353            || !object.contains_key("unassigned")
354        {
355            return Err("unknown partial endpoint fields".into());
356        }
357        let mut context = value.clone();
358        let object = context
359            .as_object_mut()
360            .ok_or("partial endpoint must be an object")?;
361        object.remove("assignments");
362        object.remove("unassigned");
363        let stage = match value["stage"].as_str() {
364            Some("next-partial-state") => "next-partial-state",
365            Some("init-partial-state") => "init-partial-state",
366            _ => return Err("unknown partial terminal stage".into()),
367        };
368        let source = TemporalStateEndpoint::from_stage(&context, stage)?;
369        let assignments = value["assignments"]
370            .as_object()
371            .ok_or("partial assignments must be an object")?
372            .clone();
373        let unassigned: Vec<String> = value["unassigned"]
374            .as_array()
375            .ok_or("partial unassigned must be a list")?
376            .iter()
377            .map(|v| {
378                v.as_str()
379                    .filter(|s| !s.is_empty())
380                    .map(str::to_owned)
381                    .ok_or("partial unassigned needs variable names")
382            })
383            .collect::<Result<_, _>>()?;
384        let names: std::collections::BTreeSet<_> = unassigned.iter().collect();
385        if unassigned.is_empty()
386            || names.len() != unassigned.len()
387            || unassigned.iter().any(|name| assignments.contains_key(name))
388        {
389            return Err("partial assigned and unassigned variables must be disjoint, with at least one unassigned".into());
390        }
391        Ok(Self {
392            initial: stage == "init-partial-state",
393            source,
394            assignments,
395            unassigned,
396        })
397    }
398}
399
400/// The independently discovered candidate-side error site.
401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402pub enum CandidateErrorSite {
403    /// An ordered state constraint.
404    Constraint,
405    /// An ordered action constraint.
406    ActionConstraint,
407    /// An ordered implied action property.
408    ImpliedAction,
409}
410impl CandidateErrorSite {
411    pub(crate) fn name(self) -> &'static str {
412        match self {
413            Self::Constraint => "constraint",
414            Self::ActionConstraint => "action-constraint",
415            Self::ImpliedAction => "implied-action",
416        }
417    }
418}
419
420/// Untrusted candidate-side primary and diagnostic identities. This never
421/// selects an expression, action or candidate during independent execution.
422#[derive(Clone, Debug, PartialEq, Eq)]
423pub struct CandidateStateEndpoint {
424    pub(crate) next: NextStateEndpoint,
425    pub(crate) site: CandidateErrorSite,
426}
427impl CandidateStateEndpoint {
428    /// Records a typed producer observation; only fresh replay can prove it.
429    #[must_use]
430    pub fn from_error(
431        ir: &dive_ir::Ir,
432        error: &EvalError,
433        site: CandidateErrorSite,
434        reported: u32,
435        deciding: u32,
436    ) -> Option<Self> {
437        Some(Self {
438            next: NextStateEndpoint::from_ordered_error(ir, error, reported, deciding)?,
439            site,
440        })
441    }
442
443    /// The untrusted deciding identity, checked against the report and replay.
444    #[must_use]
445    pub fn deciding_code(&self) -> Option<u32> {
446        self.next.deciding_code()
447    }
448
449    pub(crate) fn to_json(&self) -> Value {
450        let mut value = self.next.to_json();
451        value["stage"] = Value::from("candidate-ordered-terminal");
452        value["site"] = Value::from(self.site.name());
453        value
454    }
455
456    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
457        let mut value = value.clone();
458        let object = value
459            .as_object_mut()
460            .ok_or("candidate endpoint must be an object")?;
461        if object.len() != 5
462            || object.get("stage").and_then(Value::as_str) != Some("candidate-ordered-terminal")
463        {
464            return Err("unknown candidate endpoint fields or stage".into());
465        }
466        let site = match object
467            .remove("site")
468            .and_then(|v| v.as_str().map(str::to_owned))
469            .as_deref()
470        {
471            Some("constraint") => CandidateErrorSite::Constraint,
472            Some("action-constraint") => CandidateErrorSite::ActionConstraint,
473            Some("implied-action") => CandidateErrorSite::ImpliedAction,
474            _ => return Err("unknown candidate error site".into()),
475        };
476        object.insert("stage".into(), Value::from("next-ordered-terminal"));
477        Ok(Self {
478            next: NextStateEndpoint::from_json(&value)?,
479            site,
480        })
481    }
482}
483
484/// Untrusted source of a VIEW failure while expanding the last complete row.
485/// Native version 6 preserves that source-final word; actual fresh prefix and
486/// diagnostic execution supply the candidate, admission history and identities.
487#[derive(Clone, Debug, PartialEq, Eq)]
488pub struct ViewSourceEndpoint {
489    next: NextStateEndpoint,
490}
491impl ViewSourceEndpoint {
492    /// Records typed source and identity observations without certifying them.
493    #[must_use]
494    pub fn from_error(
495        ir: &dive_ir::Ir,
496        error: &EvalError,
497        reported: u32,
498        deciding: u32,
499    ) -> Option<Self> {
500        Some(Self {
501            next: NextStateEndpoint::from_ordered_error(ir, error, reported, deciding)?,
502        })
503    }
504    /// Claimed primary wrapper, independently checked during execution.
505    #[must_use]
506    pub fn reported_code(&self) -> u32 {
507        self.next.ordered.map_or(0, |pair| pair.0)
508    }
509    /// Claimed diagnostic identity, independently checked during execution.
510    #[must_use]
511    pub fn deciding_code(&self) -> u32 {
512        self.next.ordered.map_or(0, |pair| pair.1)
513    }
514    pub(crate) fn matches_error(&self, ir: &dive_ir::Ir, error: &EvalError) -> bool {
515        self.next.matches_error_source(ir, error)
516    }
517    pub(crate) fn to_json(&self) -> Value {
518        let mut value = self.next.to_json();
519        value["stage"] = Value::from("view-source-terminal");
520        value
521    }
522    pub(crate) fn from_json(value: &Value) -> Result<Self, String> {
523        if value["stage"] != "view-source-terminal" {
524            return Err("unknown VIEW endpoint stage".into());
525        }
526        let mut value = value.clone();
527        value["stage"] = Value::from("next-ordered-terminal");
528        Ok(Self {
529            next: NextStateEndpoint::from_json(&value)?,
530        })
531    }
532}