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