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