Skip to main content

logicaffeine_tv/
lib.rs

1#![doc = include_str!("../README.md")]
2
3pub mod equiv;
4pub mod parse;
5pub mod symexec;
6pub mod tensor;
7pub mod verdict;
8
9use logicaffeine_compile::compile::interpret_program;
10use logicaffeine_verify::{BitVecOp, VerifyExpr};
11
12pub use symexec::{SymSummary, SymValue};
13pub use verdict::{SoundnessReport, TvError};
14
15/// Parse `source` and symbolically execute it into a [`SymSummary`] over the LOGOS
16/// semantics. Does not run the optimizer (the source-of-truth side).
17pub fn summarize_logos(source: &str) -> Result<SymSummary, TvError> {
18    match parse::with_program(source, false, symexec::execute) {
19        Ok(Ok(summary)) => Ok(summary),
20        Ok(Err(symexec::Unsupported(reason))) => Err(TvError::Unsupported(reason)),
21        Err(e) => Err(TvError::Parse(e)),
22    }
23}
24
25/// Cross-validate the LOGOS encoder against the tree-walking interpreter on one program.
26///
27/// Runs the program through `interpret_program` (the independent ground truth) and the
28/// symbolic encoder, then proves with Z3 that they agree on the full observable behavior
29/// — the ordered `Show` outputs and whether an error was raised. This is the meta-oracle
30/// that makes the encoder trustworthy: a buggy encoder is caught here, not masked by a
31/// downstream equivalence that "proves" two wrong things equal.
32pub fn check_encoder_sound(source: &str) -> SoundnessReport {
33    // Gate on the determinacy classifier (FINISH_INTERPRETER invariant I4). A *Determinate*
34    // program's output is schedule-independent (Kahn), so a single encoded schedule is
35    // canonical and reuses the existing equivalence with zero new obligations. A
36    // *Nondeterminate* program is validated by seeded replay — encoder(seed) vs
37    // interpreter(seed) over a seed sweep, the `Select` winner drawn from the same SplitMix64.
38    match logicaffeine_compile::classify_source(source) {
39        Err(e) => {
40            return SoundnessReport::ParseFailed {
41                detail: format!("{e:?}"),
42            }
43        }
44        Ok(logicaffeine_compile::concurrency::Determinacy::Nondeterminate { .. }) => {
45            return check_seeded_sweep(source);
46        }
47        Ok(logicaffeine_compile::concurrency::Determinacy::Determinate) => {}
48    }
49
50    let summary = match summarize_logos(source) {
51        Ok(s) => s,
52        Err(TvError::Unsupported(reason)) => return SoundnessReport::Unsupported { reason },
53        Err(TvError::Parse(e)) => {
54            return SoundnessReport::ParseFailed {
55                detail: format!("{e:?}"),
56            }
57        }
58    };
59    check_against_interp(
60        &summary,
61        interpret_program(source).map_err(|e| format!("{e:?}")),
62    )
63}
64
65/// Prove the encoder's `summary` matches a single interpreter run (`Ok(output)`, or
66/// `Err(msg)` if the interpreter raised). The shared core of the determinate and
67/// seeded-replay checks. Returns [`SoundnessReport::Agrees`]/[`SoundnessReport::Disagrees`].
68fn check_against_interp(summary: &SymSummary, interp: Result<String, String>) -> SoundnessReport {
69    match interp {
70        Err(e) => {
71            // Interpreter raised → the encoder must prove the error condition holds.
72            if equiv::is_valid(&summary.errored) {
73                SoundnessReport::Agrees
74            } else {
75                SoundnessReport::Disagrees {
76                    detail: format!(
77                        "interpreter errored ({e}) but encoder did not prove `errored`"
78                    ),
79                }
80            }
81        }
82        Ok(out) => {
83            // Interpreter succeeded → the encoder must prove it does *not* error, and the
84            // outputs must match position-for-position.
85            if !equiv::is_valid(&VerifyExpr::not(summary.errored.clone())) {
86                return SoundnessReport::Disagrees {
87                    detail: "encoder admits an error on an input where the interpreter succeeded"
88                        .to_string(),
89                };
90            }
91            compare_outputs(&summary.outputs, &out)
92        }
93    }
94}
95
96/// Validate a nondeterministic program by seeded replay over a fixed seed sweep. The encoder
97/// and interpreter are both pinned to each seed; if they provably agree at every seed ⇒
98/// [`SoundnessReport::SeedReplayAgrees`]; any divergence ⇒ [`SoundnessReport::SeedReplayDisagrees`]
99/// (the per-seed cross-check makes a false agreement impossible); a construct outside the
100/// seeded fragment ⇒ [`SoundnessReport::Unsupported`].
101fn check_seeded_sweep(source: &str) -> SoundnessReport {
102    const SEEDS: [u64; 5] = [0, 1, 2, 7, 42];
103    for seed in SEEDS {
104        let summary = match parse::with_program(source, false, |stmts, interner| {
105            symexec::execute_seeded(stmts, interner, seed)
106        }) {
107            Ok(Ok(s)) => s,
108            Ok(Err(symexec::Unsupported(reason))) => {
109                return SoundnessReport::Unsupported { reason }
110            }
111            Err(e) => {
112                return SoundnessReport::ParseFailed {
113                    detail: format!("{e:?}"),
114                }
115            }
116        };
117        let run = logicaffeine_compile::run_treewalker_concurrent_seeded(source, seed);
118        let interp = match run.error {
119            Some(e) => Err(e),
120            None => Ok(run.lines.join("\n")),
121        };
122        match check_against_interp(&summary, interp) {
123            SoundnessReport::Agrees => continue,
124            SoundnessReport::Disagrees { detail } => {
125                return SoundnessReport::SeedReplayDisagrees {
126                    detail: format!("seed {seed}: {detail}"),
127                }
128            }
129            other => return other, // Unsupported / ParseFailed propagate as-is
130        }
131    }
132    SoundnessReport::SeedReplayAgrees
133}
134
135/// What the interpreter's textual output line is expected to be.
136enum Expected {
137    Int(i64),
138    Bool(bool),
139}
140
141fn parse_expected(line: &str) -> Option<Expected> {
142    match line {
143        "true" => Some(Expected::Bool(true)),
144        "false" => Some(Expected::Bool(false)),
145        _ => line.parse::<i64>().ok().map(Expected::Int),
146    }
147}
148
149fn compare_outputs(outputs: &[SymValue], interp_out: &str) -> SoundnessReport {
150    let lines: Vec<&str> = if interp_out.is_empty() {
151        Vec::new()
152    } else {
153        interp_out.split('\n').collect()
154    };
155
156    if outputs.len() != lines.len() {
157        return SoundnessReport::Disagrees {
158            detail: format!(
159                "output count: encoder produced {} line(s), interpreter produced {} ({:?})",
160                outputs.len(),
161                lines.len(),
162                lines
163            ),
164        };
165    }
166
167    for (i, (slot, line)) in outputs.iter().zip(lines.iter()).enumerate() {
168        let expected = match parse_expected(line) {
169            Some(e) => e,
170            None => {
171                return SoundnessReport::Unsupported {
172                    reason: format!("non-Int/Bool output line {i}: {line:?}"),
173                }
174            }
175        };
176        let pred = match (slot, expected) {
177            (SymValue::Int(e), Expected::Int(n)) => {
178                VerifyExpr::bv_binary(BitVecOp::Eq, e.clone(), VerifyExpr::bv_const(64, n as u64))
179            }
180            (SymValue::Bool(e), Expected::Bool(b)) => {
181                VerifyExpr::iff(e.clone(), VerifyExpr::bool(b))
182            }
183            (slot, _) => {
184                return SoundnessReport::Disagrees {
185                    detail: format!(
186                        "output {i}: kind mismatch (encoder {} vs interpreter {line:?})",
187                        kind_of(slot)
188                    ),
189                }
190            }
191        };
192        if !equiv::is_valid(&pred) {
193            return SoundnessReport::Disagrees {
194                detail: format!("output {i}: encoder value disagrees with interpreter {line:?}"),
195            };
196        }
197    }
198
199    SoundnessReport::Agrees
200}
201
202fn kind_of(v: &SymValue) -> &'static str {
203    match v {
204        SymValue::Int(_) => "Int",
205        SymValue::Bool(_) => "Bool",
206        SymValue::Chan(_) => "Chan",
207    }
208}