Skip to main content

sail_api/
proof.rs

1//! Version-one proof observations, separate from legacy job lifecycle events.
2//!
3//! Observations never establish a complete target proof. Only a terminal project
4//! report can establish current verification after compiler and input finalization.
5
6use serde::{Deserialize, Serialize};
7
8use crate::output::{Diagnostic, FunctionReport, ObligationReport};
9
10/// Independent proof-stream version.
11pub const VERSION: u32 = 1;
12
13/// A Cargo target's complete identity, including same-name library/binary targets.
14#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
15pub struct Target {
16    /// Cargo package identifier including version/source.
17    pub package_id: String,
18    /// Cargo target name.
19    pub name: String,
20    /// Cargo target kinds.
21    pub kind: Vec<String>,
22}
23
24/// Verification scope of this observation.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "snake_case")]
27pub enum Phase {
28    /// Explicit selected-function verification.
29    Focus,
30    /// Independent complete requested-target verification.
31    Full,
32}
33
34/// Producer-side observation identity. Sequence numbers belong to the journal.
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct InputEvent {
38    /// Always [`VERSION`].
39    pub version: u32,
40    /// Stable unique producer id, for idempotent append/reconnect.
41    pub event_id: String,
42    /// Establishing invocation.
43    pub run_id: String,
44    /// Verification context digest.
45    pub context_sha256: String,
46    /// Input revision associated with the observation.
47    pub input_revision: String,
48    /// Complete Cargo target identity.
49    pub target: Target,
50    /// Focused or full scope.
51    pub phase: Phase,
52    /// Crate-qualified function, when known authoritatively.
53    pub function: Option<String>,
54    /// Obligation identity, when known authoritatively.
55    pub obligation: Option<String>,
56    /// Observed payload; not a current complete verification claim.
57    pub observation: Observation,
58}
59
60/// Bounded query progress; not a complete solver answer or proof verdict.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct ObligationProgress {
64    /// Producer description, limited to 4,096 UTF-8 bytes.
65    pub description: String,
66    /// The source engine finished this query; completion does not imply validity.
67    pub completed: bool,
68}
69
70/// Authoritative producer facts with explicitly preliminary proof interpretation.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
73pub enum Observation {
74    /// A phase began inside its compiler invocation.
75    PhaseStarted,
76    /// A function's checks started.
77    FunctionStarted,
78    /// Progress for one exactly identified query, without solver evidence claims.
79    ObligationProgress(ObligationProgress),
80    /// An obligation's complete solver evidence, including raw model if any.
81    ObligationObserved(ObligationReport),
82    /// A function report, still preliminary before independent finalization.
83    FunctionObserved(FunctionReport),
84    /// A diagnostic emitted by the verifier with exact producer attribution.
85    Diagnostic(Diagnostic),
86    /// The source engine completed this phase's checks.
87    PhaseFinished,
88    /// Compiler checks and target output completed. Currentness remains separate.
89    CompilerSealed,
90    /// Coverage or stream failure: incomplete observations cannot confirm proofs.
91    Unavailable(String),
92}
93
94impl InputEvent {
95    /// Checks the stream contract without inferring missing identities.
96    ///
97    /// # Errors
98    /// Returns a stable explanation when required scope/identity is absent.
99    pub fn validate(&self) -> Result<(), String> {
100        if self.version != VERSION
101            || self.event_id.is_empty()
102            || self.run_id.is_empty()
103            || self.context_sha256.is_empty()
104            || self.input_revision.is_empty()
105            || self.target.package_id.is_empty()
106            || self.target.name.is_empty()
107            || self.target.kind.is_empty()
108        {
109            return Err("SAIL0902: incomplete proof event identity".into());
110        }
111        if self.obligation.is_some() && self.function.is_none() {
112            return Err("SAIL0902: obligation event has no function identity".into());
113        }
114        if matches!(self.observation, Observation::CompilerSealed) && self.phase != Phase::Full {
115            return Err("SAIL0902: compiler seal cannot finalize a focused phase".into());
116        }
117        match &self.observation {
118            Observation::FunctionStarted | Observation::FunctionObserved(_) => {
119                if self.function.is_none() {
120                    return Err("SAIL0902: function event has no function identity".into());
121                }
122            }
123            Observation::ObligationProgress(progress) => {
124                if progress.description.is_empty() || progress.description.len() > 4096 {
125                    return Err("SAIL0902: invalid bounded obligation progress description".into());
126                }
127                let id = self
128                    .obligation
129                    .as_deref()
130                    .and_then(|id| id.parse::<sail_ledger::ObligationId>().ok());
131                if !id.as_ref().is_some_and(|id| {
132                    Some(id.function.as_str()) == self.function.as_deref()
133                        && sail_ledger::ObligationKind::is_query_kind(&id.kind.0)
134                }) {
135                    return Err(
136                        "SAIL0902: query progress requires an exact obligation identity".into(),
137                    );
138                }
139            }
140            Observation::ObligationObserved(report)
141                if self.obligation.as_deref() != Some(&report.id) =>
142            {
143                return Err("SAIL0902: obligation identity disagrees with evidence".into());
144            }
145            _ => {}
146        }
147        if let Observation::FunctionObserved(report) = &self.observation {
148            if self.function.as_deref() != Some(&report.function) {
149                return Err("SAIL0902: function identity disagrees with evidence".into());
150            }
151            if report.establishment != crate::output::EstablishmentName::Provisional
152                || report.verdict != crate::output::VerdictName::Provisional
153                || report.evidence_tier.is_some()
154            {
155                return Err("SAIL0902: live function evidence must remain provisional".into());
156            }
157        }
158        Ok(())
159    }
160}
161
162/// One durable event. The journal alone assigns monotone sequence numbers.
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
164pub struct Event {
165    /// Proof-stream version.
166    pub version: u32,
167    /// Job id; stream identity changes when the retained job is replaced.
168    pub stream_id: String,
169    /// Strictly increasing journal sequence, starting at one.
170    pub sequence: u64,
171    /// Immutable source-engine observation.
172    pub input: InputEvent,
173}
174
175/// A resumable cursor. It is meaningful only within its named stream.
176#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
177pub struct Cursor {
178    /// Named durable stream; empty on the first request.
179    pub stream_id: String,
180    /// Last sequence consumed; zero before the first event.
181    pub after: u64,
182}
183
184/// Bounded proof event page, independent from whole-result RPC payload size.
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186pub struct Page {
187    /// Independent stream version.
188    pub version: u32,
189    /// Cursor to pass to the next request, including empty pages.
190    pub next: Cursor,
191    /// Ordered durable observations.
192    pub events: Vec<Event>,
193    /// True only when no further worker observations can arrive.
194    pub terminal: bool,
195    /// Missing or rejected events make the stream incomplete; never hide a gap.
196    pub gap: Option<String>,
197}