Skip to main content

sail_api/
temporal.rs

1//! Public native temporal payloads and attributed runtime jobs.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use std::collections::BTreeMap;
6
7/// Complete ITF states with explicit native claim metadata, never lossy values.
8#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(deny_unknown_fields)]
10pub struct ItfTrace {
11    /// Complete ordered variable list.
12    pub vars: Vec<String>,
13    /// ITF value objects, one complete variable assignment per state.
14    pub states: Vec<serde_json::Map<String, Value>>,
15    /// Explicit native ending claim, including zero-based loop index.
16    pub ending: Value,
17    /// All properties claimed false by a periodic word.
18    pub properties: Vec<String>,
19    /// Native action labels retained separately from ITF values.
20    pub actions: Vec<Value>,
21    /// Original optional claimed length.
22    pub length: Option<usize>,
23}
24
25/// The exact D.I.V.E. release (`dive-api` and `dive-ir` from crates.io, ADR
26/// 0172) that the native backend links, reported as `backend_revision`.
27/// Moving it requires native conformance.
28pub const DIVE_VERSION: &str = "0.1.0";
29/// Worker payload protocol version.
30pub const VERSION: u32 = 1;
31/// Maximum encoded request or response, before JSON decoding.
32pub const MAX_DOCUMENT_BYTES: usize = 16 * 1024 * 1024;
33
34/// Immutable closed model inputs. Paths are portable relative file names.
35#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct Model {
38    /// Every supplied source and configuration byte, as strict UTF-8.
39    pub files: BTreeMap<String, String>,
40    /// Root TLA+ module path.
41    pub root: String,
42    /// Configuration path.
43    pub config: String,
44}
45
46/// Native operation payload, without caller IDs or ledger metadata.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
49pub enum Operation {
50    /// Exhaustive safety or final/short temporal checking, within limits.
51    Check {
52        /// Maximum admitted states; stopping is not a holding verdict.
53        max_states: u64,
54        /// Maximum BFS depth; stopping is not a holding verdict.
55        max_depth: u64,
56    },
57    /// Finite seeded simulation, never an exhaustive proof.
58    Simulate {
59        /// Positive finite number of traces.
60        traces: u64,
61        /// Maximum transitions per trace.
62        depth: usize,
63    },
64    /// Independent validation of complete states and an explicit ending.
65    Validate {
66        /// ITF values with a separate semantic ending claim.
67        trace: ItfTrace,
68    },
69}
70
71/// One worker request. The parent owns deadline and cancellation.
72#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct Request {
75    /// Exactly [`VERSION`].
76    pub version: u32,
77    /// Frozen model closure.
78    pub model: Model,
79    /// Requested native work.
80    pub operation: Operation,
81}
82
83/// Deciding backend result. Execution failures are never logical success.
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(rename_all = "kebab-case")]
86pub enum Outcome {
87    /// Complete finite graph establishes the requested checks.
88    Holds,
89    /// Concrete counterexample independently passes semantic validation.
90    Refuted,
91    /// Finite sampled traces, with no exhaustive proof.
92    Sampled,
93    /// The supplied trace satisfies its explicit semantic claim.
94    Valid,
95    /// The supplied trace fails its explicit semantic claim.
96    Invalid,
97    /// A named feature cannot be evaluated faithfully.
98    Unsupported,
99    /// A deterministic exploration/resource limit stopped the work.
100    Stopped,
101    /// Input is malformed or semantically rejected.
102    Rejected,
103    /// Internal or infrastructure failure, never a model verdict.
104    Error,
105}
106
107/// Actual typed completion, independent of JSON discriminators.
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "kebab-case")]
110pub enum Completion {
111    /// No complete exploration is established.
112    None,
113    /// Typed safety success with an empty remaining queue.
114    Safety,
115    /// Typed temporal Holds with a complete captured graph.
116    Temporal,
117}
118
119/// Configured checks, retained separately from the actual completion route.
120#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(deny_unknown_fields)]
122pub struct RequestedChecks {
123    /// Configured invariant names, in source order.
124    pub invariants: Vec<String>,
125    /// Configured PROPERTY names, whose actual roles the backend binds.
126    pub properties: Vec<String>,
127    /// Configured postconditions.
128    pub postconditions: Vec<String>,
129    /// Configured reachability assertions.
130    pub possible: Vec<String>,
131    /// Whether deadlock checking is enabled by the configuration.
132    pub deadlock: bool,
133}
134
135/// Original native evidence plus a separate admitted ITF rendering.
136#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(deny_unknown_fields)]
138pub struct Response {
139    /// Exactly [`VERSION`].
140    pub version: u32,
141    /// Exact backend revision.
142    pub backend_revision: String,
143    /// SHA-256 of the exact canonically serialized worker request.
144    pub request_sha256: String,
145    /// Deciding outcome.
146    pub outcome: Outcome,
147    /// Actual typed complete-exploration evidence.
148    pub completion: Completion,
149    /// Exact configured property names, independent of JSON route labels.
150    pub requested_checks: Option<RequestedChecks>,
151    /// Native original report, unmodified.
152    pub native_report: Value,
153    /// Original native trace documents, unmodified.
154    pub native_traces: Vec<Value>,
155    /// Strict, round-tripped ITF renderings.
156    pub itf_traces: Vec<ItfTrace>,
157    /// Original independent trace validation reports.
158    pub validations: Vec<Value>,
159    /// Named refusal/error details, when applicable.
160    pub message: Option<String>,
161}
162
163impl Response {
164    /// Constructs an unevaluated native evidence record.
165    #[must_use]
166    pub fn new(outcome: Outcome, native_report: Value) -> Self {
167        Self {
168            version: VERSION,
169            backend_revision: DIVE_VERSION.into(),
170            request_sha256: String::new(),
171            outcome,
172            completion: Completion::None,
173            requested_checks: None,
174            native_report,
175            native_traces: Vec::new(),
176            itf_traces: Vec::new(),
177            validations: Vec::new(),
178            message: None,
179        }
180    }
181
182    /// A named failure with no model evidence.
183    #[must_use]
184    pub fn failure(outcome: Outcome, message: impl Into<String>) -> Self {
185        let mut result = Self::new(outcome, Value::Null);
186        result.message = Some(message.into());
187        result
188    }
189}
190
191/// Exact byte SHA-256, used for worker and payload content identities.
192#[must_use]
193pub fn sha256(bytes: &[u8]) -> String {
194    use std::fmt::Write as _;
195    sail_key::sha256(bytes)
196        .iter()
197        .fold(String::new(), |mut value, byte| {
198            let _ = write!(value, "{byte:02x}");
199            value
200        })
201}
202
203/// Canonical payload identity. Model maps are ordered and trace values use
204/// serde's sorted object representation; no timestamps enter this identity.
205///
206/// # Errors
207/// A payload value cannot be serialized.
208pub fn request_sha256(request: &Request) -> std::result::Result<String, serde_json::Error> {
209    let mut value = serde_json::to_value(request)?;
210    value.sort_all_objects();
211    serde_json::to_vec(&value).map(|bytes| sha256(&bytes))
212}
213
214/// One attributed temporal invocation through the shared runtime.
215#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
216#[serde(deny_unknown_fields)]
217pub struct Job {
218    /// Stable caller obligation identity.
219    pub obligation_id: String,
220    /// Strictly sorted unique caller requirement identities.
221    pub requirement_ids: Vec<String>,
222    /// Exact native payload, without executable choices.
223    pub request: Request,
224    /// Whole-worker deadline, positive and at most five minutes.
225    pub wall_time_ms: u64,
226}
227
228/// Attributed worker result; execution and native outcomes remain separate.
229#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
230pub struct Result {
231    /// Caller obligation identity, unchanged.
232    pub obligation_id: String,
233    /// Caller requirement identities, unchanged.
234    pub requirement_ids: Vec<String>,
235    /// Canonical identity of the exact worker request.
236    pub request_sha256: String,
237    /// Exact backend source revision.
238    pub backend_revision: String,
239    /// Authenticated worker bytes, absent when unavailable.
240    pub worker_sha256: Option<String>,
241    /// Effective whole-worker deadline.
242    pub wall_time_ms: u64,
243    /// Process outcome, independent of native logical evidence.
244    pub outcome: crate::runtime::Outcome,
245    /// Original complete worker evidence, absent on execution failure.
246    pub response: Option<Response>,
247    /// Explicit execution diagnostic.
248    pub error: Option<crate::runtime::Error>,
249    /// This slice never caches temporal evidence.
250    pub cache_hit: bool,
251}
252
253/// Implemented temporal operations and authenticated installation readiness.
254#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
255pub struct Capability {
256    /// Native check, finite simulation and trace validation are implemented.
257    pub implemented: bool,
258    /// Trusted worker bytes were authenticated for this installation.
259    pub installed: bool,
260    /// Exact linked backend release ([`DIVE_VERSION`]).
261    pub backend_revision: String,
262    /// Actual authenticated worker identity, when installed.
263    pub worker_sha256: Option<String>,
264    /// Actionable unavailable diagnostic.
265    pub error: Option<crate::runtime::Error>,
266}
267
268/// Checks a returned worker's request identity and conclusive evidence shape.
269/// This supplements the parent's pinned worker-byte admission; it does not
270/// authenticate an arbitrary caller-supplied verdict as a native result.
271///
272/// # Errors
273/// Mismatched protocol/input or absent/incompatible conclusive evidence.
274pub fn validate_response(
275    request: &Request,
276    response: &Response,
277) -> std::result::Result<(), String> {
278    if response.version != VERSION
279        || response.backend_revision != DIVE_VERSION
280        || response.request_sha256 != request_sha256(request).map_err(|e| e.to_string())?
281    {
282        return Err("SAIL4213: worker protocol, backend or request identity differs".into());
283    }
284    let report = &response.native_report;
285    let conclusive = matches!(
286        response.outcome,
287        Outcome::Holds | Outcome::Refuted | Outcome::Sampled | Outcome::Valid | Outcome::Invalid
288    );
289    if conclusive && report["schema_version"] != 3 {
290        return Err("SAIL4213: conclusive outcome lacks native schema-3 evidence".into());
291    }
292    let compatible = match response.outcome {
293        Outcome::Holds => {
294            matches!(request.operation, Operation::Check { .. })
295                && report["command"] == "check"
296                && report["verdict"] == "success"
297                && report["options"]["profile"] == "dive"
298                && report["options"]["store"] == "exact"
299                && report["statistics"]["left_on_queue"] == 0
300                && (response.completion == Completion::Safety
301                    || (response.completion == Completion::Temporal
302                        && report["execution"]["capture_completed"] == true))
303        }
304        Outcome::Refuted => {
305            matches!(
306                request.operation,
307                Operation::Check { .. } | Operation::Simulate { .. }
308            ) && !response.native_traces.is_empty()
309                && response.native_traces.len() == response.itf_traces.len()
310                && response.validations.len() == response.native_traces.len()
311                && response.validations.iter().all(|v| v["result"] == "valid")
312        }
313        Outcome::Sampled => {
314            matches!(request.operation, Operation::Simulate { .. })
315                && report["result"] == "sampled"
316                && report["model_proved"] == false
317                && report["exhaustive"] == false
318                && !response.native_traces.is_empty()
319                && response.native_traces.len() == response.itf_traces.len()
320                && response.validations.len() == response.native_traces.len()
321                && response.validations.iter().all(|v| v["result"] == "valid")
322        }
323        Outcome::Valid => {
324            matches!(request.operation, Operation::Validate { .. }) && report["result"] == "valid"
325        }
326        Outcome::Invalid => {
327            matches!(request.operation, Operation::Validate { .. }) && report["result"] == "invalid"
328        }
329        _ => true,
330    };
331    if !compatible {
332        return Err("SAIL4213: outcome lacks matching native operation evidence".into());
333    }
334    Ok(())
335}
336
337use serde::Deserializer;
338use serde::de::{self, MapAccess, SeqAccess, Visitor};
339use serde_json::Map;
340use std::fmt;
341
342struct Unique(Value);
343impl<'de> Deserialize<'de> for Unique {
344    fn deserialize<D: Deserializer<'de>>(decoder: D) -> std::result::Result<Self, D::Error> {
345        struct Any;
346        impl<'de> Visitor<'de> for Any {
347            type Value = Unique;
348            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349                f.write_str("JSON with unique object fields")
350            }
351            fn visit_bool<E: de::Error>(self, v: bool) -> std::result::Result<Unique, E> {
352                Ok(Unique(Value::Bool(v)))
353            }
354            fn visit_i64<E: de::Error>(self, v: i64) -> std::result::Result<Unique, E> {
355                Ok(Unique(Value::from(v)))
356            }
357            fn visit_u64<E: de::Error>(self, v: u64) -> std::result::Result<Unique, E> {
358                Ok(Unique(Value::from(v)))
359            }
360            fn visit_f64<E: de::Error>(self, v: f64) -> std::result::Result<Unique, E> {
361                serde_json::Number::from_f64(v)
362                    .map(Value::Number)
363                    .map(Unique)
364                    .ok_or_else(|| E::custom("non-finite JSON number"))
365            }
366            fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<Unique, E> {
367                Ok(Unique(Value::from(v)))
368            }
369            fn visit_string<E: de::Error>(self, v: String) -> std::result::Result<Unique, E> {
370                Ok(Unique(Value::String(v)))
371            }
372            fn visit_unit<E: de::Error>(self) -> std::result::Result<Unique, E> {
373                Ok(Unique(Value::Null))
374            }
375            fn visit_none<E: de::Error>(self) -> std::result::Result<Unique, E> {
376                Ok(Unique(Value::Null))
377            }
378            fn visit_seq<A: SeqAccess<'de>>(
379                self,
380                mut a: A,
381            ) -> std::result::Result<Unique, A::Error> {
382                let mut values = Vec::new();
383                while let Some(Unique(value)) = a.next_element()? {
384                    values.push(value);
385                }
386                Ok(Unique(Value::Array(values)))
387            }
388            fn visit_map<A: MapAccess<'de>>(
389                self,
390                mut a: A,
391            ) -> std::result::Result<Unique, A::Error> {
392                let mut fields = Map::new();
393                while let Some((key, Unique(value))) = a.next_entry::<String, Unique>()? {
394                    if fields.insert(key, value).is_some() {
395                        return Err(de::Error::custom("SAIL4214: duplicate JSON object field"));
396                    }
397                }
398                Ok(Unique(Value::Object(fields)))
399            }
400        }
401        decoder.deserialize_any(Any)
402    }
403}
404
405/// Strict whole-document JSON decode, including unique nested object fields.
406///
407/// # Errors
408/// Rejects duplicates, trailing input or an incompatible typed payload.
409pub fn decode<T: serde::de::DeserializeOwned>(
410    bytes: &[u8],
411) -> std::result::Result<T, serde_json::Error> {
412    let Unique(value) = serde_json::from_slice(bytes)?;
413    serde_json::from_value(value)
414}