diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 01dea48..82bef4a 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -8,6 +8,8 @@ workflows: '.github/workflows/codeql.yml': - 'actions/checkout@v7.0.1' - 'github/codeql-action@v4.39.3' + '.github/workflows/creusot.yml': + - 'actions/checkout@v7.0.1' '.github/workflows/dependabot-automerge.yml': - 'dependabot/fetch-metadata@v3.1.0' '.github/workflows/dogfood-gate.yml': diff --git a/.github/workflows/creusot.yml b/.github/workflows/creusot.yml new file mode 100644 index 0000000..dcf95be --- /dev/null +++ b/.github/workflows/creusot.yml @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +# +# Creusot proofs of the Rust fast core (src/rust), with planted controls and +# code mutants that must be refused. See verification/creusot/README.adoc. +# +# Honesty rules for this job: +# - It is never continue-on-error. An install failure is a RED job. +# - run.sh exits 3 if Creusot is missing; that is also RED here. +# - docs/status/PROOF-STATUS.adoc keeps the Rust (Creusot) row OPEN until a +# green run of this job is cited there as the receipt. +# The estate Creusot gate (proven-cicd-and-workflows) is not used yet: it needs +# a detector fix (#143) and does not carry these pins. This job MOVES to the suite +# gate once #143 merges. Toolchain pins live beside it in verification/creusot/PINS. +name: "πŸ”΄ Gate: Creusot (Rust core)" + +on: + # push: main only. A PR branch is covered by the pull_request event; running on + # both would start two identical long jobs per push in separate concurrency groups. + push: + branches: [main] + paths: + - 'src/rust/**' + - 'verification/creusot/**' + - 'build/just/trope.just' + - '.github/workflows/creusot.yml' + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + creusot: + name: "Creusot: prove, refuse controls, refuse mutants" + runs-on: ubuntu-24.04 + timeout-minutes: 150 + steps: + # Pinned like every workflow here: tag + actions.lock entry (the linter's + # coverage and resolution checks). v7.0.1 = 3d3c42e5aac5ba805825da76410c181273ba90b1. + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install opam and libzmq (as creusot's own CI does) + run: sudo apt-get update && sudo apt-get install -y opam libzmq3-dev + - name: Install the pinned Creusot toolchain + run: bash verification/creusot/install.sh + - name: Prove, then require every control and mutant to be refused + env: + CREUSOT_LOG_DIR: ${{ runner.temp }}/creusot-logs + run: | + set -euo pipefail + bash verification/creusot/run.sh diff --git a/build/just/trope.just b/build/just/trope.just index 08f7bb7..4b77418 100644 --- a/build/just/trope.just +++ b/build/just/trope.just @@ -30,3 +30,8 @@ tropecheck ir: trope-rust: cd src/rust && cargo fmt --all --check && cargo clippy --locked --all-targets -- -D warnings -D clippy::pedantic && cargo test --locked && cargo build --locked --release TROPECHECK_BIN=src/rust/target/release/tropecheck-rs bash tests/conformance/run.sh + +# Exit 3 means Creusot is not installed: OPEN, nothing proved. Pins: verification/creusot/PINS. +# Creusot proofs of the Rust fast core, with planted controls and mutants +creusot: + bash verification/creusot/run.sh diff --git a/docs/status/PROOF-STATUS.adoc b/docs/status/PROOF-STATUS.adoc index d2508bc..50efc6a 100644 --- a/docs/status/PROOF-STATUS.adoc +++ b/docs/status/PROOF-STATUS.adoc @@ -132,8 +132,48 @@ toc::[] | Agda `TB.Reduction`, `TB.Substitution.cut-preserves-grade`. |=== -The Rust fast core (`src/rust/`) is not a proof; it agrees with the Idris2 -reference over the whole conformance corpus (`just trope-rust`). +The Rust fast core (`src/rust/`) agrees with the Idris2 reference over the whole +conformance corpus (`just trope-rust`). That agreement is testing, not proof. The +only Rust code with a proof is the Creusot scope in the next paragraph. + +*Rust (Creusot): PROVED on its stated scope, CI receipt run 44525604501 (head +b6a3c3e, 19 Nov 2026).* Creusot v0.15.0 discharged every file named in +`verification/creusot/SCOPE`. Those are the contracts on `dkey`, `dadd`, +`fate_*`, `bond_*`, `merge_*`, `epsilon`, `grade_compose`, `grade_meet`, +`grade_le` and `violations`, and the lemmas in `creusot_spec.rs`: L1, L2, L3, L5, +L6, L4 (with non-negative attenuation), A2, wf preservation, preorder laws, meet +as glb and correspondence with the Agda order (both on the honest fragment). +"Verdict soundness" there is a spec lemma about the order only (floor βŠ‘ g and +g βŠ‘ ρ imply floor βŠ‘ ρ). It is not a proof about the shipped `check` function. In +the same run, all 9 planted false contracts and all 7 code mutants were refused. +Each of the 16 also has an executable witness, which holds on the shipped code, +and each mutant's witness broke on its mutant. Assumptions are rows CR-A1 to +CR-A3 in the README: creusot-std specs and solver soundness. A refusal is "not +proved within budget", which the witnesses back with a concrete counterexample. +OPEN by name, and not translated by Creusot (`#[cfg(not(creusot))]`, not +trusted): `check`, `acc`, `topo_witness_order`, `validate_graph`, the decoder +(`dec_*`, `req`, `str_list`) and the JSON parser (`Json`, `P`, `parse_json`). +Also OPEN: the 13 derived `Clone` and `PartialEq` files, which are translated +but not proved (assumed under CR-A1). One recorded divergence: on deceptive +inputs the Rust order is not the Agda/Idris2 order (next paragraph). See +`verification/creusot/README.adoc`. + +*Rust order on deceptive values (divergence): RECORDED, owner ruling 13a +(19 Nov 2026).* Agda (`TB/Order.agda`) and Idris2 (`Trope/Coords.idr`) put each +deceptive value at the bottom of its order: `fateLte Falsified _`, `bondLte +Misbound _` and `mergeLte Conflated _` are all true. The Rust `fate_le`, +`bond_le` and `merge_le` make a deceptive value comparable only with itself, so +`grade_le` agrees with `gradeLte` on the honest fragment only, and `fate_meet` +is not a lower bound when one side is deceptive (`meet(Falsified, Present) = +Dropped`). The prevent-profile decoder rejects deceptive writes, so the CLI +cannot reach this. Direct library callers can. Options: +(A) keep the Rust order and state the scope in the `grade_le` documentation; +(B) change Rust to the Agda/Idris2 order, a behaviour change for library callers; +(C) change Agda/Idris2 to the Rust order, which reopens proved rows. +Ruling 13a chose (A) for this week; the `grade_le` documentation now states the +scope. Aligning the orders, (B) or (C), is next week's decision. The Creusot +correspondence and glb lemmas are stated on the honest fragment, and controls +`c03`, `c05` and `c07` must be refused, which keeps the divergence measured. == Proof Witness Grades @@ -387,6 +427,9 @@ Each is specified; none is asserted. Status words follow `spec/calculus.adoc Β§1 mechanising O5-1 as a side condition on an `Oracle`-indexed verdict is OPEN. * *O6* β€” the ceiling verdict, stem:[\rho \sqsubseteq g_{\mathrm{ceiling}}], for the privacy direction (`spec/calculus.adoc Β§5` note on T-Sub, `Β§10`). +* *Rust (Creusot) remainder* β€” `check`, `acc`, `topo_witness_order`, + `validate_graph`, the decoder and the JSON parser have no Creusot proof. They + are excluded from translation, not trusted (`verification/creusot/README.adoc`). == Modelling notes diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 1cf5259..49e37b5 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -28,3 +28,8 @@ path = "src/main.rs" [profile.release] opt-level = 3 + +# `cfg(creusot)` is set only by creusot-rustc (verification/creusot). Declaring it +# here keeps plain builds free of the unexpected-cfg warning. +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(creusot)'] } diff --git a/src/rust/src/creusot_spec.rs b/src/rust/src/creusot_spec.rs new file mode 100644 index 0000000..13dd41c --- /dev/null +++ b/src/rust/src/creusot_spec.rs @@ -0,0 +1,800 @@ +// SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +// SPDX-License-Identifier: MPL-2.0 +// +// Creusot logical model and laws for the Rust fast core. +// +// Compiled ONLY under `cfg(creusot)` (see the top of lib.rs). An ordinary build +// never sees this file. +// +// Layout: +// 1. The model types. `Delta` and `Fate` carry an `i64`, so their deep model is a +// mirror type over the unbounded `Int`. `Bond` and `Merge` are their own model. +// 2. Transcriptions of the Rust functions (`*_m`). Each program function in lib.rs +// carries `ensures(result.deep_model() == f_m(..))`, so Creusot proves the Rust +// code equal to the transcription. +// 3. Transcriptions of the Agda reference order (`agda_*`), copied clause by +// clause from verification/proofs/agda/theorem-b/TB/Order.agda. +// 4. The laws, as lemmas over the transcriptions: L1, L2, L3, L4, L5, L6, A2, +// preorder, honest closure, wf preservation, meet as glb on the honest +// fragment, and the honest correspondence with Agda. +// +// Divergence carried here, not fixed (hub ruling, 19 Nov): Agda and Idris2 put each +// deceptive bottom (Falsified, Misbound, Conflated) at the BOTTOM of the order. The +// Rust order makes it comparable only with itself. The correspondence lemmas are +// therefore stated on the honest fragment. The unrestricted correspondence is a +// planted control that Creusot must refuse (verification/creusot/controls). + +use crate::*; +use creusot_std::prelude::*; + +// ───────────────────────────── 1. model types ───────────────────────────── + +/// Deep model of `Delta`: the finite loss is an unbounded integer. +pub enum DeltaM { + Q(Int), + Inf, + Top, +} + +/// Deep model of `Fate`. +pub enum FateM { + Present, + Atten(DeltaM), + Predicated, + Dropped, + Falsified, +} + +/// Deep model of `Grade`. +pub struct GradeM { + pub q: FateM, + pub b: FateM, + pub c: FateM, + pub r: FateM, + pub bond: Bond, + pub merge: Merge, +} + +// ───────────────────────── 2. transcriptions of the Rust code ───────────────────────── + +/// First component of `dkey`. +#[logic(open)] +pub fn dtag(d: DeltaM) -> Int { + match d { + DeltaM::Q(_) => 0, + DeltaM::Inf => 1, + DeltaM::Top => 2, + } +} + +/// Second component of `dkey`. +#[logic(open)] +pub fn dval(d: DeltaM) -> Int { + match d { + DeltaM::Q(n) => n, + DeltaM::Inf => 0, + DeltaM::Top => 0, + } +} + +/// The Rust delta order used inside `fate_le`: `a` retains at most as much as `b` +/// iff `dkey(a) >= dkey(b)` lexicographically. +#[logic(open)] +pub fn dle_m(a: DeltaM, b: DeltaM) -> bool { + dtag(a) > dtag(b) || (dtag(a) == dtag(b) && dval(a) >= dval(b)) +} + +/// `dadd`, over unbounded integers. +#[logic(open)] +pub fn dadd_m(a: DeltaM, b: DeltaM) -> DeltaM { + match a { + DeltaM::Top => DeltaM::Top, + DeltaM::Inf => match b { + DeltaM::Top => DeltaM::Top, + _ => DeltaM::Inf, + }, + DeltaM::Q(x) => match b { + DeltaM::Top => DeltaM::Top, + DeltaM::Inf => DeltaM::Inf, + DeltaM::Q(y) => DeltaM::Q(x + y), + }, + } +} + +/// Owner ruling (1): i64 overflow is a precondition proved at callers, never a +/// wrapping behaviour. This is that precondition for `dadd`. +#[logic(open)] +pub fn d_no_ovf(a: DeltaM, b: DeltaM) -> bool { + match a { + DeltaM::Q(x) => match b { + DeltaM::Q(y) => pearlite! { i64::MIN@ <= x + y && x + y <= i64::MAX@ }, + _ => true, + }, + _ => true, + } +} + +/// The overflow precondition lifted to `fate_compose` (only AttenΒ·Atten adds). +#[logic(open)] +pub fn f_no_ovf(a: FateM, b: FateM) -> bool { + match a { + FateM::Atten(d1) => match b { + FateM::Atten(d2) => d_no_ovf(d1, d2), + _ => true, + }, + _ => true, + } +} + +/// The overflow precondition lifted to `grade_compose`. +#[logic(open)] +pub fn g_no_ovf(a: GradeM, b: GradeM) -> bool { + f_no_ovf(a.q, b.q) && f_no_ovf(a.b, b.b) && f_no_ovf(a.c, b.c) && f_no_ovf(a.r, b.r) +} + +/// `fate_le`, clause by clause. +#[logic(open)] +pub fn fate_le_m(lo: FateM, hi: FateM) -> bool { + if lo == hi { + true + } else if lo == FateM::Falsified || hi == FateM::Falsified { + false + } else if hi == FateM::Present { + true + } else if lo == FateM::Present { + false + } else { + match lo { + FateM::Atten(a) => match hi { + FateM::Atten(b) => dle_m(a, b), + _ => false, + }, + FateM::Predicated => match hi { + FateM::Atten(_) => true, + _ => false, + }, + FateM::Dropped => match hi { + FateM::Atten(_) => true, + FateM::Predicated => true, + _ => false, + }, + _ => false, + } + } +} + +/// `fate_compose`, clause by clause (A1: the lie survives the drop). +#[logic(open)] +pub fn fate_compose_m(a: FateM, b: FateM) -> FateM { + match a { + FateM::Falsified => FateM::Falsified, + FateM::Present => b, + FateM::Dropped => match b { + FateM::Falsified => FateM::Falsified, + _ => FateM::Dropped, + }, + FateM::Predicated => match b { + FateM::Falsified => FateM::Falsified, + FateM::Dropped => FateM::Dropped, + _ => FateM::Predicated, + }, + FateM::Atten(d1) => match b { + FateM::Falsified => FateM::Falsified, + FateM::Dropped => FateM::Dropped, + FateM::Present => FateM::Atten(d1), + FateM::Atten(d2) => FateM::Atten(dadd_m(d1, d2)), + FateM::Predicated => FateM::Predicated, + }, + } +} + +/// `fate_meet`: the smaller of two comparable fates, else `Dropped`. +#[logic(open)] +pub fn fate_meet_m(a: FateM, b: FateM) -> FateM { + if fate_le_m(a, b) { + a + } else if fate_le_m(b, a) { + b + } else { + FateM::Dropped + } +} + +/// `bond_rank`. +#[logic(open)] +pub fn brank(b: Bond) -> Int { + match b { + Bond::Intact => 3, + Bond::Withheld => 2, + Bond::Severed => 1, + Bond::Misbound => 0, + } +} + +/// `bond_le`. +#[logic(open)] +pub fn bond_le_m(lo: Bond, hi: Bond) -> bool { + if lo == Bond::Misbound || hi == Bond::Misbound { + lo == hi + } else { + brank(lo) <= brank(hi) + } +} + +/// `bond_compose` (and `bond_meet`, which is the same function). +#[logic(open)] +pub fn bond_compose_m(a: Bond, b: Bond) -> Bond { + if a == Bond::Misbound || b == Bond::Misbound { + Bond::Misbound + } else if brank(a) <= brank(b) { + a + } else { + b + } +} + +/// `merge_rank`. +#[logic(open)] +pub fn mrank(m: Merge) -> Int { + match m { + Merge::Single => 3, + Merge::Fused => 2, + Merge::Conflated => 1, + } +} + +/// `merge_le`. +#[logic(open)] +pub fn merge_le_m(lo: Merge, hi: Merge) -> bool { + if lo == Merge::Conflated || hi == Merge::Conflated { + lo == hi + } else { + mrank(lo) <= mrank(hi) + } +} + +/// `merge_compose` (and `merge_meet`). +#[logic(open)] +pub fn merge_compose_m(a: Merge, b: Merge) -> Merge { + if a == Merge::Conflated || b == Merge::Conflated { + Merge::Conflated + } else if mrank(a) <= mrank(b) { + a + } else { + b + } +} + +/// `epsilon()`. +#[logic(open)] +pub fn eps_m() -> GradeM { + GradeM { + q: FateM::Present, + b: FateM::Present, + c: FateM::Present, + r: FateM::Present, + bond: Bond::Intact, + merge: Merge::Single, + } +} + +/// `grade_compose`. +#[logic(open)] +pub fn grade_compose_m(a: GradeM, b: GradeM) -> GradeM { + GradeM { + q: fate_compose_m(a.q, b.q), + b: fate_compose_m(a.b, b.b), + c: fate_compose_m(a.c, b.c), + r: fate_compose_m(a.r, b.r), + bond: bond_compose_m(a.bond, b.bond), + merge: merge_compose_m(a.merge, b.merge), + } +} + +/// `grade_meet`. +#[logic(open)] +pub fn grade_meet_m(a: GradeM, b: GradeM) -> GradeM { + GradeM { + q: fate_meet_m(a.q, b.q), + b: fate_meet_m(a.b, b.b), + c: fate_meet_m(a.c, b.c), + r: fate_meet_m(a.r, b.r), + bond: bond_compose_m(a.bond, b.bond), + merge: merge_compose_m(a.merge, b.merge), + } +} + +/// `grade_le`: the componentwise product order. +#[logic(open)] +pub fn grade_le_m(lo: GradeM, hi: GradeM) -> bool { + fate_le_m(lo.q, hi.q) + && fate_le_m(lo.b, hi.b) + && fate_le_m(lo.c, hi.c) + && fate_le_m(lo.r, hi.r) + && bond_le_m(lo.bond, hi.bond) + && merge_le_m(lo.merge, hi.merge) +} + +/// One optional floor coordinate: absent imposes nothing. +#[logic(open)] +pub fn opt_fate_le(fl: Option, g: FateM) -> bool { + match fl { + None => true, + Some(d) => fate_le_m(d.deep_model(), g), + } +} + +/// The floor order checked by `violations`: every coordinate the floor sets is met. +#[logic(open)] +pub fn floor_le_m(fl: Floor, g: GradeM) -> bool { + opt_fate_le(fl.q, g.q) + && opt_fate_le(fl.b, g.b) + && opt_fate_le(fl.c, g.c) + && opt_fate_le(fl.r, g.r) + && match fl.bond { + None => true, + Some(d) => bond_le_m(d, g.bond), + } + && match fl.merge { + None => true, + Some(d) => merge_le_m(d, g.merge), + } +} + +// ───────────────────────── honesty and well-formedness ───────────────────────── + +#[logic(open)] +pub fn honest_f(f: FateM) -> bool { + f != FateM::Falsified +} + +#[logic(open)] +pub fn honest_g(g: GradeM) -> bool { + honest_f(g.q) + && honest_f(g.b) + && honest_f(g.c) + && honest_f(g.r) + && g.bond != Bond::Misbound + && g.merge != Merge::Conflated +} + +/// Finite losses are non-negative (the decoder admits only `n >= 0`). +#[logic(open)] +pub fn nonneg_f(f: FateM) -> bool { + match f { + FateM::Atten(DeltaM::Q(n)) => n >= 0, + _ => true, + } +} + +/// A3 normal form: `Atten(Q 0)` never occurs (the decoder rewrites it to `Present`). +#[logic(open)] +pub fn normal_f(f: FateM) -> bool { + match f { + FateM::Atten(DeltaM::Q(n)) => n != 0, + _ => true, + } +} + +#[logic(open)] +pub fn wf_f(f: FateM) -> bool { + nonneg_f(f) && normal_f(f) +} + +#[logic(open)] +pub fn wf_g(g: GradeM) -> bool { + wf_f(g.q) && wf_f(g.b) && wf_f(g.c) && wf_f(g.r) +} + +// ───────────────────────── 3. the Agda reference order ───────────────────────── +// Copied from TB/Order.agda (dLte, fateLte, bondLte, mergeLte). +// Agda's Ξ” is `Q β„• | total | unknown`; Rust's Inf is `total`, Top is `unknown`. + +#[logic(open)] +pub fn agda_dlte(a: DeltaM, b: DeltaM) -> bool { + match a { + DeltaM::Top => true, + DeltaM::Q(x) => match b { + DeltaM::Q(y) => y <= x, + _ => false, + }, + DeltaM::Inf => match b { + DeltaM::Top => false, + _ => true, + }, + } +} + +#[logic(open)] +pub fn agda_fate_le(a: FateM, b: FateM) -> bool { + match a { + FateM::Falsified => true, + FateM::Present => b == FateM::Present, + FateM::Atten(x) => match b { + FateM::Present => true, + FateM::Atten(y) => agda_dlte(x, y), + _ => false, + }, + FateM::Predicated => match b { + FateM::Present => true, + FateM::Atten(_) => true, + FateM::Predicated => true, + _ => false, + }, + FateM::Dropped => b != FateM::Falsified, + } +} + +#[logic(open)] +pub fn agda_bond_le(a: Bond, b: Bond) -> bool { + match a { + Bond::Misbound => true, + _ => b != Bond::Misbound && brank(a) <= brank(b), + } +} + +#[logic(open)] +pub fn agda_merge_le(a: Merge, b: Merge) -> bool { + match a { + Merge::Conflated => true, + _ => b != Merge::Conflated && mrank(a) <= mrank(b), + } +} + +// ───────────────────────────────── 4. laws ───────────────────────────────── +// Each lemma is a logic function whose contract is the law. Bodies are empty +// unless a case split is needed to guide the solvers. + +// L1 associativity. +#[logic(open)] +#[ensures(dadd_m(dadd_m(a, b), c) == dadd_m(a, dadd_m(b, c)))] +pub fn l1_dadd_assoc(a: DeltaM, b: DeltaM, c: DeltaM) {} + +#[logic(open)] +#[ensures(fate_compose_m(fate_compose_m(a, b), c) == fate_compose_m(a, fate_compose_m(b, c)))] +pub fn l1_fate_assoc(a: FateM, b: FateM, c: FateM) { + match a { + FateM::Atten(x) => match b { + FateM::Atten(y) => match c { + FateM::Atten(z) => l1_dadd_assoc(x, y, z), + _ => (), + }, + _ => (), + }, + _ => (), + } +} + +#[logic(open)] +#[ensures(bond_compose_m(bond_compose_m(a, b), c) == bond_compose_m(a, bond_compose_m(b, c)))] +pub fn l1_bond_assoc(a: Bond, b: Bond, c: Bond) {} + +#[logic(open)] +#[ensures(merge_compose_m(merge_compose_m(a, b), c) == merge_compose_m(a, merge_compose_m(b, c)))] +pub fn l1_merge_assoc(a: Merge, b: Merge, c: Merge) {} + +#[logic(open)] +#[ensures(grade_compose_m(grade_compose_m(a, b), c) == grade_compose_m(a, grade_compose_m(b, c)))] +pub fn l1_grade_assoc(a: GradeM, b: GradeM, c: GradeM) { + l1_fate_assoc(a.q, b.q, c.q); + l1_fate_assoc(a.b, b.b, c.b); + l1_fate_assoc(a.c, b.c, c.c); + l1_fate_assoc(a.r, b.r, c.r); + l1_bond_assoc(a.bond, b.bond, c.bond); + l1_merge_assoc(a.merge, b.merge, c.merge); +} + +// L2 unit. +#[logic(open)] +#[ensures(fate_compose_m(FateM::Present, a) == a && fate_compose_m(a, FateM::Present) == a)] +pub fn l2_fate_unit(a: FateM) {} + +#[logic(open)] +#[ensures(bond_compose_m(Bond::Intact, a) == a && bond_compose_m(a, Bond::Intact) == a)] +pub fn l2_bond_unit(a: Bond) {} + +#[logic(open)] +#[ensures(merge_compose_m(Merge::Single, a) == a && merge_compose_m(a, Merge::Single) == a)] +pub fn l2_merge_unit(a: Merge) {} + +#[logic(open)] +#[ensures(grade_compose_m(eps_m(), a) == a && grade_compose_m(a, eps_m()) == a)] +pub fn l2_grade_unit(a: GradeM) { + l2_fate_unit(a.q); + l2_fate_unit(a.b); + l2_fate_unit(a.c); + l2_fate_unit(a.r); + l2_bond_unit(a.bond); + l2_merge_unit(a.merge); +} + +// L6 commutativity. +#[logic(open)] +#[ensures(dadd_m(a, b) == dadd_m(b, a))] +pub fn l6_dadd_comm(a: DeltaM, b: DeltaM) {} + +#[logic(open)] +#[ensures(fate_compose_m(a, b) == fate_compose_m(b, a))] +pub fn l6_fate_comm(a: FateM, b: FateM) { + match a { + FateM::Atten(x) => match b { + FateM::Atten(y) => l6_dadd_comm(x, y), + _ => (), + }, + _ => (), + } +} + +#[logic(open)] +#[ensures(bond_compose_m(a, b) == bond_compose_m(b, a))] +pub fn l6_bond_comm(a: Bond, b: Bond) {} + +#[logic(open)] +#[ensures(merge_compose_m(a, b) == merge_compose_m(b, a))] +pub fn l6_merge_comm(a: Merge, b: Merge) {} + +#[logic(open)] +#[ensures(grade_compose_m(a, b) == grade_compose_m(b, a))] +pub fn l6_grade_comm(a: GradeM, b: GradeM) { + l6_fate_comm(a.q, b.q); + l6_fate_comm(a.b, b.b); + l6_fate_comm(a.c, b.c); + l6_fate_comm(a.r, b.r); + l6_bond_comm(a.bond, b.bond); + l6_merge_comm(a.merge, b.merge); +} + +// L3 bottom absorption, two-sided, for every deceptive bottom. +#[logic(open)] +#[ensures(fate_compose_m(FateM::Falsified, a) == FateM::Falsified)] +#[ensures(fate_compose_m(a, FateM::Falsified) == FateM::Falsified)] +pub fn l3_falsified_absorbs(a: FateM) {} + +#[logic(open)] +#[ensures(bond_compose_m(Bond::Misbound, a) == Bond::Misbound)] +#[ensures(bond_compose_m(a, Bond::Misbound) == Bond::Misbound)] +pub fn l3_misbound_absorbs(a: Bond) {} + +#[logic(open)] +#[ensures(merge_compose_m(Merge::Conflated, a) == Merge::Conflated)] +#[ensures(merge_compose_m(a, Merge::Conflated) == Merge::Conflated)] +pub fn l3_conflated_absorbs(a: Merge) {} + +/// Fidelity: `Unknown` (Rust `Top`) is a two-sided zero; `Total` (Rust `Inf`) +/// absorbs every finite loss. +#[logic(open)] +#[ensures(dadd_m(DeltaM::Top, a) == DeltaM::Top && dadd_m(a, DeltaM::Top) == DeltaM::Top)] +#[ensures(a != DeltaM::Top ==> dadd_m(DeltaM::Inf, a) == DeltaM::Inf && dadd_m(a, DeltaM::Inf) == DeltaM::Inf)] +pub fn l3_fidelity_absorbs(a: DeltaM) {} + +// L5 deception infectiousness: a deceptive operand makes the result deceptive. +#[logic(open)] +#[ensures(!honest_f(a) ==> !honest_f(fate_compose_m(a, b)) && !honest_f(fate_compose_m(b, a)))] +pub fn l5_fate(a: FateM, b: FateM) {} + +#[logic(open)] +#[ensures(!honest_g(a) ==> !honest_g(grade_compose_m(a, b)) && !honest_g(grade_compose_m(b, a)))] +pub fn l5_grade(a: GradeM, b: GradeM) {} + +// Honest closure (the closure half of Honest Generation). +#[logic(open)] +#[requires(honest_g(a) && honest_g(b))] +#[ensures(honest_g(grade_compose_m(a, b)))] +#[ensures(honest_g(grade_meet_m(a, b)))] +pub fn honest_closed(a: GradeM, b: GradeM) {} + +// wf (non-negative, A3-normal) is preserved by composition and meet. +#[logic(open)] +#[requires(wf_f(a) && wf_f(b))] +#[ensures(wf_f(fate_compose_m(a, b)))] +#[ensures(wf_f(fate_meet_m(a, b)))] +pub fn wf_fate_closed(a: FateM, b: FateM) {} + +#[logic(open)] +#[requires(wf_g(a) && wf_g(b))] +#[ensures(wf_g(grade_compose_m(a, b)))] +#[ensures(wf_g(grade_meet_m(a, b)))] +pub fn wf_grade_closed(a: GradeM, b: GradeM) { + wf_fate_closed(a.q, b.q); + wf_fate_closed(a.b, b.b); + wf_fate_closed(a.c, b.c); + wf_fate_closed(a.r, b.r); +} + +#[logic(open)] +#[ensures(wf_g(eps_m()) && honest_g(eps_m()))] +pub fn eps_honest_wf() {} + +// The order: reflexive, transitive, antisymmetric. +#[logic(open)] +#[ensures(fate_le_m(a, a) && bond_le_m(b, b) && merge_le_m(m, m))] +pub fn order_refl(a: FateM, b: Bond, m: Merge) {} + +#[logic(open)] +#[requires(fate_le_m(a, b) && fate_le_m(b, c))] +#[ensures(fate_le_m(a, c))] +pub fn fate_trans(a: FateM, b: FateM, c: FateM) {} + +#[logic(open)] +#[requires(fate_le_m(a, b) && fate_le_m(b, a))] +#[ensures(a == b)] +pub fn fate_antisym(a: FateM, b: FateM) {} + +#[logic(open)] +#[requires(bond_le_m(a, b) && bond_le_m(b, c))] +#[ensures(bond_le_m(a, c))] +pub fn bond_trans(a: Bond, b: Bond, c: Bond) {} + +#[logic(open)] +#[requires(merge_le_m(a, b) && merge_le_m(b, c))] +#[ensures(merge_le_m(a, c))] +pub fn merge_trans(a: Merge, b: Merge, c: Merge) {} + +#[logic(open)] +#[ensures(grade_le_m(a, a))] +pub fn grade_refl(a: GradeM) { + order_refl(a.q, a.bond, a.merge); + order_refl(a.b, a.bond, a.merge); + order_refl(a.c, a.bond, a.merge); + order_refl(a.r, a.bond, a.merge); +} + +#[logic(open)] +#[requires(grade_le_m(a, b) && grade_le_m(b, c))] +#[ensures(grade_le_m(a, c))] +pub fn grade_trans(a: GradeM, b: GradeM, c: GradeM) { + fate_trans(a.q, b.q, c.q); + fate_trans(a.b, b.b, c.b); + fate_trans(a.c, b.c, c.c); + fate_trans(a.r, b.r, c.r); + bond_trans(a.bond, b.bond, c.bond); + merge_trans(a.merge, b.merge, c.merge); +} + +// A2: fate is a chain on the honest fragment, and Dropped βŠ‘ Predicated, not back. +#[logic(open)] +#[ensures(fate_le_m(FateM::Dropped, FateM::Predicated))] +#[ensures(!fate_le_m(FateM::Predicated, FateM::Dropped))] +pub fn a2_dropped_le_predicated() {} + +#[logic(open)] +#[requires(honest_f(a) && honest_f(b))] +#[ensures(fate_le_m(a, b) || fate_le_m(b, a))] +pub fn a2_fate_total_on_honest(a: FateM, b: FateM) {} + +// L4 monotonicity of composition in both arguments, under non-negative losses. +// (Non-negativity is needed: with Atten(Q -1) βŠ‘ Present, composing both with +// Atten(Q 1) gives Atten(Q 0) β‹’ Atten(Q 1).) +#[logic(open)] +#[requires(nonneg_f(a) && nonneg_f(b) && nonneg_f(c))] +#[requires(fate_le_m(a, b))] +#[ensures(fate_le_m(fate_compose_m(a, c), fate_compose_m(b, c)))] +#[ensures(fate_le_m(fate_compose_m(c, a), fate_compose_m(c, b)))] +pub fn l4_fate_mono(a: FateM, b: FateM, c: FateM) { + l6_fate_comm(a, c); + l6_fate_comm(b, c); +} + +#[logic(open)] +#[requires(bond_le_m(a, b))] +#[ensures(bond_le_m(bond_compose_m(a, c), bond_compose_m(b, c)))] +#[ensures(bond_le_m(bond_compose_m(c, a), bond_compose_m(c, b)))] +pub fn l4_bond_mono(a: Bond, b: Bond, c: Bond) {} + +#[logic(open)] +#[requires(merge_le_m(a, b))] +#[ensures(merge_le_m(merge_compose_m(a, c), merge_compose_m(b, c)))] +#[ensures(merge_le_m(merge_compose_m(c, a), merge_compose_m(c, b)))] +pub fn l4_merge_mono(a: Merge, b: Merge, c: Merge) {} + +/// L4 at grade level: the lifting spec Β§7's Knaster–Tarski argument uses, which +/// PROOF-STATUS records as not mechanised in Idris2. +#[logic(open)] +#[requires(wf_g(a) && wf_g(b) && wf_g(c))] +#[requires(grade_le_m(a, b))] +#[ensures(grade_le_m(grade_compose_m(a, c), grade_compose_m(b, c)))] +#[ensures(grade_le_m(grade_compose_m(c, a), grade_compose_m(c, b)))] +pub fn l4_grade_mono(a: GradeM, b: GradeM, c: GradeM) { + l4_fate_mono(a.q, b.q, c.q); + l4_fate_mono(a.b, b.b, c.b); + l4_fate_mono(a.c, b.c, c.c); + l4_fate_mono(a.r, b.r, c.r); + l4_bond_mono(a.bond, b.bond, c.bond); + l4_merge_mono(a.merge, b.merge, c.merge); +} + +// Meet is the greatest lower bound on the honest fragment. +#[logic(open)] +#[requires(honest_f(a) && honest_f(b))] +#[ensures(fate_le_m(fate_meet_m(a, b), a) && fate_le_m(fate_meet_m(a, b), b))] +#[ensures(fate_le_m(c, a) && fate_le_m(c, b) ==> fate_le_m(c, fate_meet_m(a, b)))] +pub fn fate_meet_glb(a: FateM, b: FateM, c: FateM) { + a2_fate_total_on_honest(a, b); +} + +#[logic(open)] +#[requires(a != Bond::Misbound && b != Bond::Misbound)] +#[ensures(bond_le_m(bond_compose_m(a, b), a) && bond_le_m(bond_compose_m(a, b), b))] +#[ensures(bond_le_m(c, a) && bond_le_m(c, b) ==> bond_le_m(c, bond_compose_m(a, b)))] +pub fn bond_meet_glb(a: Bond, b: Bond, c: Bond) {} + +#[logic(open)] +#[requires(a != Merge::Conflated && b != Merge::Conflated)] +#[ensures(merge_le_m(merge_compose_m(a, b), a) && merge_le_m(merge_compose_m(a, b), b))] +#[ensures(merge_le_m(c, a) && merge_le_m(c, b) ==> merge_le_m(c, merge_compose_m(a, b)))] +pub fn merge_meet_glb(a: Merge, b: Merge, c: Merge) {} + +#[logic(open)] +#[requires(honest_g(a) && honest_g(b))] +#[ensures(grade_le_m(grade_meet_m(a, b), a) && grade_le_m(grade_meet_m(a, b), b))] +#[ensures(grade_le_m(c, a) && grade_le_m(c, b) ==> grade_le_m(c, grade_meet_m(a, b)))] +pub fn grade_meet_glb(a: GradeM, b: GradeM, c: GradeM) { + fate_meet_glb(a.q, b.q, c.q); + fate_meet_glb(a.b, b.b, c.b); + fate_meet_glb(a.c, b.c, c.c); + fate_meet_glb(a.r, b.r, c.r); + bond_meet_glb(a.bond, b.bond, c.bond); + merge_meet_glb(a.merge, b.merge, c.merge); +} + +// Correspondence with the Agda reference order. +// The delta order agrees everywhere; fate, bond and merge agree on the honest +// fragment. Off it they disagree (see the header): that is a planted control. +#[logic(open)] +#[ensures(dle_m(a, b) == agda_dlte(a, b))] +pub fn corr_delta(a: DeltaM, b: DeltaM) {} + +#[logic(open)] +#[requires(honest_f(a) && honest_f(b))] +#[ensures(fate_le_m(a, b) == agda_fate_le(a, b))] +pub fn corr_fate_honest(a: FateM, b: FateM) { + match a { + FateM::Atten(x) => match b { + FateM::Atten(y) => corr_delta(x, y), + _ => (), + }, + _ => (), + } +} + +#[logic(open)] +#[requires(a != Bond::Misbound && b != Bond::Misbound)] +#[ensures(bond_le_m(a, b) == agda_bond_le(a, b))] +pub fn corr_bond_honest(a: Bond, b: Bond) {} + +#[logic(open)] +#[requires(a != Merge::Conflated && b != Merge::Conflated)] +#[ensures(merge_le_m(a, b) == agda_merge_le(a, b))] +pub fn corr_merge_honest(a: Merge, b: Merge) {} + +// Verdict soundness (Idris2 Trope.Soundness.verdictSound and subSound): a floor +// met by g, with g βŠ‘ ρ, is met by ρ. +#[logic(open)] +#[requires(floor_le_m(fl, g) && grade_le_m(g, rho))] +#[ensures(floor_le_m(fl, rho))] +pub fn verdict_sound(fl: Floor, g: GradeM, rho: GradeM) { + match fl.q { + Some(d) => fate_trans(d.deep_model(), g.q, rho.q), + None => (), + } + match fl.b { + Some(d) => fate_trans(d.deep_model(), g.b, rho.b), + None => (), + } + match fl.c { + Some(d) => fate_trans(d.deep_model(), g.c, rho.c), + None => (), + } + match fl.r { + Some(d) => fate_trans(d.deep_model(), g.r, rho.r), + None => (), + } + match fl.bond { + Some(d) => bond_trans(d, g.bond, rho.bond), + None => (), + } + match fl.merge { + Some(d) => merge_trans(d, g.merge, rho.merge), + None => (), + } +} diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index 698ad09..9c8a700 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -12,8 +12,32 @@ use std::collections::{BTreeMap, BTreeSet}; +// ──────────────────────────── Creusot (verification only) ──────────────────────────── +// Everything Creusot needs is behind `cfg(creusot)`. That cfg is set only by +// creusot-rustc (via the verification crate `verification/creusot`, which uses this +// file as its library root and adds the `creusot-std` dependency). An ordinary +// `cargo build` of tropecheck-rs sees none of it: the crate stays std-only and +// offline, and every attribute below expands to nothing. No runtime behaviour +// changes. The logical model and the laws live in `creusot_spec.rs`. +#[cfg(creusot)] +use creusot_std::prelude::*; +// creusot-std's prelude shadows four std-prelude names (Clone, PartialEq, Default, +// vec!). A glob import cannot disambiguate them, so the ones this file uses are +// imported explicitly (creusot-std prelude docs; first CI run, E0659 on `vec`). +#[cfg(creusot)] +use creusot_std::std::clone::Clone; +#[cfg(creusot)] +use creusot_std::std::cmp::PartialEq; +#[cfg(creusot)] +use creusot_std::std::vec::vec; +#[cfg(creusot)] +pub mod creusot_spec; +#[cfg(creusot)] +use creusot_spec::*; + // ──────────────────────────── JSON (minimal, std-only) ──────────────────────────── #[derive(Clone, Debug)] +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub enum Json { Null, Bool(bool), @@ -23,10 +47,12 @@ pub enum Json { Obj(Vec<(String, Json)>), } +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub struct P<'a> { s: &'a [u8], i: usize, } +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) impl<'a> P<'a> { #[must_use] pub fn new(s: &'a str) -> Self { @@ -216,6 +242,7 @@ impl<'a> P<'a> { /// /// # Errors /// Returns an error for malformed input or trailing content. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn parse_json(s: &str) -> Result { let mut p = P::new(s); let v = p.value()?; @@ -225,6 +252,7 @@ pub fn parse_json(s: &str) -> Result { } Ok(v) } +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) impl Json { #[must_use] pub fn field(&self, k: &str) -> Option<&Json> { @@ -254,12 +282,14 @@ impl Json { // ──────────────────────────── grade algebra (mirror) ──────────────────────────── #[derive(Clone, PartialEq)] +#[cfg_attr(creusot, derive(DeepModel), DeepModelTy = "DeltaM")] pub enum Delta { Q(i64), Inf, Top, } #[derive(Clone, PartialEq)] +#[cfg_attr(creusot, derive(DeepModel), DeepModelTy = "FateM")] pub enum Fate { Present, Atten(Delta), @@ -268,6 +298,7 @@ pub enum Fate { Falsified, } #[derive(Clone, PartialEq)] +#[cfg_attr(creusot, derive(DeepModel), DeepModelTy = "Bond")] pub enum Bond { Intact, Withheld, @@ -275,6 +306,7 @@ pub enum Bond { Misbound, } #[derive(Clone, PartialEq)] +#[cfg_attr(creusot, derive(DeepModel), DeepModelTy = "Merge")] pub enum Merge { Single, Fused, @@ -282,6 +314,7 @@ pub enum Merge { } // loss magnitude key: bigger = more loss = less retention +#[cfg_attr(creusot, ensures(result.0@ == dtag(d.deep_model()) && result.1@ == dval(d.deep_model())))] #[must_use] pub fn dkey(d: &Delta) -> (u8, i64) { match d { @@ -290,6 +323,8 @@ pub fn dkey(d: &Delta) -> (u8, i64) { Delta::Top => (2, 0), } } +#[cfg_attr(creusot, requires(d_no_ovf(a.deep_model(), b.deep_model())))] +#[cfg_attr(creusot, ensures(result.deep_model() == dadd_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn dadd(a: &Delta, b: &Delta) -> Delta { match (a, b) { @@ -305,6 +340,7 @@ pub fn dadd(a: &Delta, b: &Delta) -> Delta { /// /// Honest fates ascend from `Dropped` through `Predicated` and attenuation to /// `Present`; smaller attenuation retains more. `Falsified` compares only with itself. +#[cfg_attr(creusot, ensures(result == fate_le_m(lo.deep_model(), hi.deep_model())))] #[must_use] pub fn fate_le(lo: &Fate, hi: &Fate) -> bool { use Fate::{Atten, Dropped, Falsified, Predicated, Present}; @@ -335,6 +371,8 @@ pub fn fate_le(lo: &Fate, hi: &Fate) -> bool { /// /// # Panics /// Panics if finite loss addition overflows with overflow checks enabled. +#[cfg_attr(creusot, requires(f_no_ovf(a.deep_model(), b.deep_model())))] +#[cfg_attr(creusot, ensures(result.deep_model() == fate_compose_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn fate_compose(a: &Fate, b: &Fate) -> Fate { use Fate::{Atten, Dropped, Falsified, Predicated, Present}; @@ -348,6 +386,7 @@ pub fn fate_compose(a: &Fate, b: &Fate) -> Fate { (Atten(_), Predicated) | (Predicated, _) => Predicated, } } +#[cfg_attr(creusot, ensures(result.deep_model() == fate_meet_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn fate_meet(a: &Fate, b: &Fate) -> Fate { if fate_le(a, b) { @@ -358,6 +397,7 @@ pub fn fate_meet(a: &Fate, b: &Fate) -> Fate { Fate::Dropped } } +#[cfg_attr(creusot, ensures(result@ == brank(b.deep_model())))] #[must_use] pub fn bond_rank(b: &Bond) -> i8 { match b { @@ -367,6 +407,7 @@ pub fn bond_rank(b: &Bond) -> i8 { Bond::Misbound => 0, } } +#[cfg_attr(creusot, ensures(result == bond_le_m(lo.deep_model(), hi.deep_model())))] #[must_use] pub fn bond_le(lo: &Bond, hi: &Bond) -> bool { if matches!(lo, Bond::Misbound) || matches!(hi, Bond::Misbound) { @@ -374,6 +415,7 @@ pub fn bond_le(lo: &Bond, hi: &Bond) -> bool { } bond_rank(lo) <= bond_rank(hi) } +#[cfg_attr(creusot, ensures(result.deep_model() == bond_compose_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn bond_compose(a: &Bond, b: &Bond) -> Bond { if matches!(a, Bond::Misbound) || matches!(b, Bond::Misbound) { @@ -385,10 +427,12 @@ pub fn bond_compose(a: &Bond, b: &Bond) -> Bond { b.clone() } } +#[cfg_attr(creusot, ensures(result.deep_model() == bond_compose_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn bond_meet(a: &Bond, b: &Bond) -> Bond { bond_compose(a, b) } +#[cfg_attr(creusot, ensures(result@ == mrank(m.deep_model())))] #[must_use] pub fn merge_rank(m: &Merge) -> i8 { match m { @@ -397,6 +441,7 @@ pub fn merge_rank(m: &Merge) -> i8 { Merge::Conflated => 1, } } +#[cfg_attr(creusot, ensures(result == merge_le_m(lo.deep_model(), hi.deep_model())))] #[must_use] pub fn merge_le(lo: &Merge, hi: &Merge) -> bool { if matches!(lo, Merge::Conflated) || matches!(hi, Merge::Conflated) { @@ -404,6 +449,7 @@ pub fn merge_le(lo: &Merge, hi: &Merge) -> bool { } merge_rank(lo) <= merge_rank(hi) } +#[cfg_attr(creusot, ensures(result.deep_model() == merge_compose_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn merge_compose(a: &Merge, b: &Merge) -> Merge { if matches!(a, Merge::Conflated) || matches!(b, Merge::Conflated) { @@ -415,12 +461,14 @@ pub fn merge_compose(a: &Merge, b: &Merge) -> Merge { b.clone() } } +#[cfg_attr(creusot, ensures(result.deep_model() == merge_compose_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn merge_meet(a: &Merge, b: &Merge) -> Merge { merge_compose(a, b) } #[derive(Clone)] +#[cfg_attr(creusot, derive(DeepModel), DeepModelTy = "GradeM")] pub struct Grade { pub q: Fate, pub b: Fate, @@ -429,6 +477,7 @@ pub struct Grade { pub bond: Bond, pub merge: Merge, } +#[cfg_attr(creusot, ensures(result.deep_model() == eps_m()))] #[must_use] pub fn epsilon() -> Grade { Grade { @@ -440,6 +489,8 @@ pub fn epsilon() -> Grade { merge: Merge::Single, } } +#[cfg_attr(creusot, requires(g_no_ovf(a.deep_model(), b.deep_model())))] +#[cfg_attr(creusot, ensures(result.deep_model() == grade_compose_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn grade_compose(a: &Grade, b: &Grade) -> Grade { Grade { @@ -451,6 +502,7 @@ pub fn grade_compose(a: &Grade, b: &Grade) -> Grade { merge: merge_compose(&a.merge, &b.merge), } } +#[cfg_attr(creusot, ensures(result.deep_model() == grade_meet_m(a.deep_model(), b.deep_model())))] #[must_use] pub fn grade_meet(a: &Grade, b: &Grade) -> Grade { Grade { @@ -494,6 +546,7 @@ pub struct Doc { /// /// # Errors /// Returns an error unless the value is a non-negative integer, `"inf"`, or `"top"`. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_delta(path: &str, v: &Json) -> Result { match v { Json::Num(n) if *n >= 0 => Ok(Delta::Q(*n)), @@ -511,6 +564,7 @@ pub fn dec_delta(path: &str, v: &Json) -> Result { /// /// # Errors /// Returns an error for malformed or deceptive fates, or predicates outside quality. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_fate(path: &str, is_q: bool, v: &Json) -> Result { match v.field("k").and_then(|k| k.as_str()) { Some("Present") => Ok(Fate::Present), @@ -546,6 +600,7 @@ pub fn dec_fate(path: &str, is_q: bool, v: &Json) -> Result { /// /// # Errors /// Returns an error for a missing, unknown, or deceptive bond. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_bond(path: &str, v: &Json) -> Result { match v.field("k").and_then(|k| k.as_str()) { Some("Intact") => Ok(Bond::Intact), @@ -564,6 +619,7 @@ pub fn dec_bond(path: &str, v: &Json) -> Result { /// /// # Errors /// Returns an error for a missing, unknown, or deceptive merge, or a missing or empty fusion tag. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_merge(path: &str, v: &Json) -> Result { match v.field("k").and_then(|k| k.as_str()) { Some("Single") => Ok(Merge::Single), @@ -585,6 +641,7 @@ pub fn dec_merge(path: &str, v: &Json) -> Result { /// /// # Errors /// Returns an error naming the path and key when the field is absent. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn req<'a>(path: &str, k: &str, v: &'a Json) -> Result<&'a Json, String> { v.field(k).ok_or_else(|| format!("{path}: missing \"{k}\"")) } @@ -596,6 +653,7 @@ pub fn req<'a>(path: &str, k: &str, v: &'a Json) -> Result<&'a Json, String> { /// /// # Errors /// Returns an error for missing or invalid coordinates or an incoherent bond. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_grade(epath: &str, value: &Json) -> Result { let fate = req(&format!("{epath}/grade"), "fate", value)?; let quality = dec_fate( @@ -650,6 +708,7 @@ pub fn dec_grade(epath: &str, value: &Json) -> Result { /// /// Return an empty list if `v` is not an array. #[must_use] +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn str_list(v: &Json) -> Vec { // Deliberately not Option::map_or_default (unstable on some stable // toolchains) nor map().unwrap_or_default() (clippy::map_unwrap_or @@ -671,6 +730,7 @@ pub fn str_list(v: &Json) -> Vec { /// # Errors /// Returns an error for a missing or non-string ID or type, an unknown type, /// or a `FloatingQuality` node listing `bearer` in `present`. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_node(v: &Json) -> Result { let id = v .field("id") @@ -703,6 +763,7 @@ pub fn dec_node(v: &Json) -> Result { /// /// # Errors /// Returns an error for a missing ID or output, or a missing or invalid grade. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_edge(v: &Json) -> Result { let id = v .field("id") @@ -741,6 +802,7 @@ pub fn dec_edge(v: &Json) -> Result { /// /// # Errors /// Returns an error if a supplied coordinate is invalid in the prevent profile. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_floor(v: &Json) -> Result { let ff = |k: &str, is_q: bool| -> Result, String> { match v.field("fate").and_then(|fa| fa.field(k)) { @@ -777,6 +839,7 @@ pub fn dec_floor(v: &Json) -> Result { /// Structural faults are validation faults and MUST NOT produce a verdict: /// accumulation treats a missing producer as grade Ξ΅, so without this check /// an undeclared `use_model.output` silently returned `p-sufficient`. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) fn validate_graph(nodes: &[Node], edges: &[Edge], out: &str) -> Result<(), String> { let mut declared: BTreeSet<&str> = BTreeSet::new(); for n in nodes { @@ -842,6 +905,7 @@ fn validate_graph(nodes: &[Node], edges: &[Edge], out: &str) -> Result<(), Strin /// invalid nodes, edges, or floors, or a structurally invalid graph /// (duplicate node or edge IDs, undeclared node references, duplicate /// producers, or cycles) β€” see `validate_graph`. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn dec_doc(v: &Json) -> Result { // Accepted document versions (IR 0.2, R-2026-07-07). "0.1" stays accepted: // the wire format is identical, and 0.1 documents are normalized and graded @@ -891,6 +955,7 @@ pub fn dec_doc(v: &Json) -> Result { } // ──────────────────────────── checker (DAG accumulate + verdict + witness) ──────── +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn acc(edges: &[Edge], node: &str, fuel: usize, memo: &mut BTreeMap) -> Grade { if fuel == 0 { return epsilon(); @@ -923,6 +988,7 @@ pub fn acc(edges: &[Edge], node: &str, fuel: usize, memo: &mut BTreeMap Vec { let mut v = Vec::new(); @@ -967,6 +1033,7 @@ pub fn violations(fl: &Floor, g: &Grade) -> Vec { /// Documents reaching here are schema-valid DAGs. On a malformed cyclic /// graph the unemittable remainder is simply skipped (accumulation stays /// fuel-bounded in `acc`), never an infinite loop. +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) fn topo_witness_order(doc: &Doc) -> Vec<&Edge> { let producer: BTreeMap<&str, &Edge> = doc.edges.iter().map(|e| (e.output.as_str(), e)).collect(); @@ -1013,6 +1080,7 @@ fn topo_witness_order(doc: &Doc) -> Vec<&Edge> { } #[must_use] +#[cfg(not(creusot))] // OPEN, outside the Creusot proof scope (verification/creusot/SCOPE) pub fn check(doc: &Doc) -> (String, Option<(String, String)>) { let fuel = doc.edges.len() + 1; let mut memo = BTreeMap::new(); @@ -1040,15 +1108,24 @@ pub fn check(doc: &Doc) -> (String, Option<(String, String)>) { /// The retention order βŠ‘ on grades: the componentwise product order. /// -/// True iff `hi` retains at least as much as `lo` in EVERY coordinate. This -/// mirrors `gradeLte` in `verification/proofs/idris2/Trope/Grade.idr` exactly β€” -/// the conjunction of the four field-fates with bond and merge β€” and adds no -/// new semantics: it is built only from the per-coordinate orders already used -/// by `violations`. The algebra is PROVED in Idris2, not here. +/// True iff `hi` retains at least as much as `lo` in EVERY coordinate: the +/// conjunction of the four field-fates with bond and merge, built only from the +/// per-coordinate orders already used by `violations`. +/// +/// On the honest fragment (no `Falsified`, `Misbound` or `Conflated`) this +/// agrees with `gradeLte` in Agda (`TB/Order.agda`) and Idris2 +/// (`verification/proofs/idris2/Trope/Grade.idr`). On deceptive values it does +/// NOT: in Rust a deceptive value is comparable only with itself, while the +/// Agda/Idris2 order puts each deceptive value at the bottom. Owner ruling 13a +/// (19 Nov 2026) keeps the Rust order as it is; see the "Rust order on +/// deceptive values" row in `docs/status/PROOF-STATUS.adoc`. The prevent-profile +/// decoder never produces deceptive values, so the CLI cannot reach the +/// difference; direct library callers can. /// /// Exposed so downstream consumers (e.g. a query engine doing loss-bounded /// traversal) can compare grades in-process instead of reimplementing the /// order and forking the semantics. +#[cfg_attr(creusot, ensures(result == grade_le_m(lo.deep_model(), hi.deep_model())))] #[must_use] pub fn grade_le(lo: &Grade, hi: &Grade) -> bool { fate_le(&lo.q, &hi.q) diff --git a/verification/creusot/.gitignore b/verification/creusot/.gitignore new file mode 100644 index 0000000..58692b7 --- /dev/null +++ b/verification/creusot/.gitignore @@ -0,0 +1,5 @@ +target/ +verif/ +controls/target/ +controls/verif/ +witness/target/ diff --git a/verification/creusot/Cargo.lock b/verification/creusot/Cargo.lock new file mode 100644 index 0000000..6613bfa --- /dev/null +++ b/verification/creusot/Cargo.lock @@ -0,0 +1,232 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "creusot-std" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c258fc3bed45edeb0509fce569f66565cae19b583d24a827faaa4e1abe51d2b" +dependencies = [ + "creusot-std-proc", +] + +[[package]] +name = "creusot-std-proc" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "848b1d0c5b674f9eb80e144602ab64d8ddcef5033d60a07a5be112b1c931d029" +dependencies = [ + "pearlite-syn", + "proc-macro2", + "quote", + "syn 2.0.119", + "uuid", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "pearlite-syn" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7afb8267bb550980a04ce048a1f1592af3741fab76d1b364678696efbe2570" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tropecheck-creusot" +version = "0.1.0" +dependencies = [ + "creusot-std", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] diff --git a/verification/creusot/Cargo.toml b/verification/creusot/Cargo.toml new file mode 100644 index 0000000..3f5fae5 --- /dev/null +++ b/verification/creusot/Cargo.toml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +# SPDX-License-Identifier: MPL-2.0 +# +# Creusot verification crate for the Rust fast core. +# +# Its library root IS src/rust/src/lib.rs: the same source file, not a copy, so +# what Creusot proves is the code that ships. This crate only adds the +# creusot-std dependency. Under creusot-rustc the `cfg(creusot)` attributes in +# lib.rs switch on; under plain rustc they are inert. tropecheck-rs itself keeps +# no dependency and still builds offline. +# +# Run with `just creusot` (verification/creusot/run.sh). Toolchain pins are in +# verification/creusot/PINS. +[package] +name = "tropecheck-creusot" +version = "0.1.0" +edition = "2021" +license = "MPL-2.0" +publish = false + +[lib] +name = "tropecheck_rs" +path = "../../src/rust/src/lib.rs" + +[dependencies] +creusot-std = "=0.15.0" + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(creusot)'] } + +[workspace] diff --git a/verification/creusot/PINS b/verification/creusot/PINS new file mode 100644 index 0000000..f911f15 --- /dev/null +++ b/verification/creusot/PINS @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: MPL-2.0 +# Creusot toolchain pins. run.sh and .github/workflows/creusot.yml read this file. +# The solver versions are the ones creusot v0.15.0's installer fetches and +# sha256-checks (creusot-setup/src/tools_versions_urls.rs at the tag). +CREUSOT_REPO=https://github.com/creusot-rs/creusot +CREUSOT_TAG=v0.15.0 +CREUSOT_SHA=fd4d85b2c237ef93147e99f6a0c04acfc89a6a17 +RUST_NIGHTLY=nightly-2026-08-03 +WHY3_GIT=05bf4ddf55cb3042f34c3bc0ed3aff56a226978a +WHY3FIND_GIT=89dd8721fb9de7fea5d00e58ebdabdc75a8235b8 +ALTERGO=2.6.4 +Z3=5.3.2 +CVC5=1.4.1 +OCAML=5.3.0 diff --git a/verification/creusot/README.adoc b/verification/creusot/README.adoc new file mode 100644 index 0000000..12ebda5 --- /dev/null +++ b/verification/creusot/README.adoc @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +// SPDX-License-Identifier: CC-BY-SA-4.0 += Creusot proofs of the Rust fast core + +Status: *PROVED on the stated scope*. The receipt is CI run 44525604501 of +`.github/workflows/creusot.yml` (head b6a3c3e, 19 Nov 2026). Every file named in +`SCOPE` proved. All 9 controls and all 7 mutants were refused, and every +executable witness behaved as required. The claim covers `SCOPE` only. Every item +marked OPEN below stays OPEN, and the derived `Clone` and `PartialEq` files are +assumed (CR-A1), not proved. `docs/status/PROOF-STATUS.adoc` cites the same run. + +== What is checked, and where + +The contracts are attributes on the shipping code in `src/rust/src/lib.rs`, +written as `#[cfg_attr(creusot, ...)]`. The logical model and the laws are in +`src/rust/src/creusot_spec.rs`, compiled only under `cfg(creusot)`. + +This directory is a second Cargo package whose library root *is* +`src/rust/src/lib.rs`. It is the same file, not a copy. The package only adds +`creusot-std`. `tropecheck-rs` keeps no dependencies and still builds offline. +Under plain rustc every attribute expands to nothing, so runtime behaviour does not change. + +[cols="2,3,1",options="header"] +|=== +| Code | Contract | State + +| `dkey`, `dadd`, `fate_le`, `fate_compose`, `fate_meet`, `bond_*`, `merge_*`, `epsilon`, `grade_compose`, `grade_meet`, `grade_le` +| The result equals a clause-by-clause transcription (`*_m` in `creusot_spec.rs`). `dadd`, `fate_compose` and `grade_compose` require no i64 overflow (owner ruling 1). +| PROVED (run 44525604501) + +| `violations` +| The result is empty iff the floor is met on every coordinate it sets (`floor_le_m`). +| PROVED (run 44525604501) + +| L1, L2, L6, L3 (`Falsified`, `Misbound`, `Conflated`, fidelity `Top`/`Inf`), L5, honest closure, wf preservation, preorder and antisymmetry, A2 and chain on the honest fragment, L4 per coordinate and at grade level, meet as glb on the honest fragment, honest correspondence with Agda `fateLte`/`bondLte`/`mergeLte`/`dLte`, and verdict soundness as a lemma about the order only (floor βŠ‘ g and g βŠ‘ ρ imply floor βŠ‘ ρ). That is not a proof about the shipped `check`, which is OPEN +| Lemmas in `creusot_spec.rs` +| PROVED (run 44525604501) + +| `acc`, `check`, `topo_witness_order`, `validate_graph` +| No contract, and excluded from the Creusot build with `#[cfg(not(creusot))]`. Each uses `BTreeMap`/`BTreeSet`, for which creusot-std v0.15.0 has no specs, and `acc` recurses without a variant. +| OPEN + +| JSON parser (`Json`, `P`, `parse_json`), `dec_*` decoder +| No contract yet, and excluded from the Creusot build with `#[cfg(not(creusot))]`: Creusot rejects the recursive `Json` type (nested under `Vec`) and the mutually recursive `value`/`array`/`object` without termination arguments. The intended contract is that `Ok` implies honest, non-negative and A3-normal, and that `Predicated` occurs only when `is_q`. +| OPEN +|=== + +== The divergence this proof carries (not fixed) + +Agda (`TB/Order.agda`) and Idris2 (`Trope/Coords.idr`) put each deceptive +bottom at the bottom of the order: `fateLte Falsified _ = true`, and likewise +for `Misbound` and `Conflated`. The Rust order makes each deceptive value +comparable only with itself. So the claim in `grade_le`'s doc comment that it +"mirrors gradeLte exactly" is false on deceptive inputs. Also, `fate_meet` is not a +lower bound when one side is deceptive: `meet(Falsified, Present) = Dropped`. + +The CLI cannot reach this. The prevent-profile decoder rejects deceptive +writes, and honesty is closed under compose and meet. The public library API +can reach it. The correspondence and glb lemmas are therefore stated on the +honest fragment. Controls `c03`, `c05` and `c07` keep the divergence live: +they must be refused. Owner ruling 13a (19 Nov 2026) keeps the Rust order for +now and corrects only the `grade_le` documentation. Aligning the orders is next +week's decision. See the named row in `docs/status/PROOF-STATUS.adoc`. + +== Controls and mutants + +`run.sh` fails loudly: + +* Proofs: every Coma file named in `SCOPE` must prove. Each `SCOPE` pattern must + match at least one file. Any other translated file is printed as OPEN. The + parser, the decoder, `acc`, `check` and the witness order are not translated + at all (`#[cfg(not(creusot))]`). None of them is proved or claimed. +* Controls (`controls/`, one Cargo feature each): every false contract must + translate to Coma, produce its own Coma file, and then be refused by the + provers. `c00` is `ensures(false)`. +* Mutants (`mutants/MUTANTS`): each one-line code change must still compile + with plain rustc, translate to Coma, and be refused on the `SCOPE` files. +* A refusal counts only if why3find ran and its output names the intended + control or mutated function. A setup error never counts as a refusal. +* Regeneration is forced on every run. Sources are touched so Creusot's Cargo + cache (`target/creusot`) cannot skip translation, and `verif/` is wiped. +* `why3find.json` in this directory and in `controls/` is a copy of the file at + the pinned Creusot tag. It is what `cargo creusot init` would write. + +Exit 0 means all good, 1 means red, 3 means Creusot is not installed. Exit 3 is +OPEN and never counts as green. + +== What a refusal means + +A control or mutant counts as refused only on why3find's own verdict for the +intended function. The log must contain all of these, matching the format seen in +CI run 44507269211: + +* `... : proof failed` +* `Goal Coma.vc_: ✘` +* `Error: unproved file` + +It must also contain no failing goal for any other function. + +Limit, stated plainly: why3find's `✘` means "not proved within the prover budget". +It does not separate a refutation from a timeout. A prover verdict alone would +therefore show only that the provers could not establish the false claim. + +So each refusal also has an executable falsity witness, in `witness/` (plain +`cargo test`, no Creusot): + +* `witness/tests/controls.rs`: one test per control, named after it. It runs a + concrete counterexample on the shipped code and passes exactly when that + control's claim is false. Examples: `fate_compose(Dropped, Falsified)` is + `Falsified` (c01), `dadd(Q(i64::MAX), Q(1))` overflows (c02), and + `meet(Falsified, Present) = Dropped` is not below `Falsified` (c03). +* `witness/tests/mutants.rs`: one test per mutant, named by its id. It states the + function's contract on one concrete input. It must pass on the shipped code and + fail on the mutated code. + +`run.sh` makes the gate red if any witness is missing, if a control witness or a +mutant witness fails on the shipped code, or if a mutant witness still passes on +its mutant. A timeout therefore can never pass as a refusal on its own: the +falsity is checked independently of the provers. + +== ASSUMED boundaries + +These are third-party specifications that the proofs rely on and do not re-prove (PROOF-POLICY): + +[cols="1,3",options="header"] +|=== +| ID | Assumption + +| CR-A1 +| creusot-std v0.15.0's derive specs: `#[derive(DeepModel)]`, Creusot's `PartialEq` derive (`eq` returns deep-model equality), and rustc's builtin `Clone` derive with Creusot's structural postcondition. + +| CR-A2 +| creusot-std v0.15.0's specs for `Vec::new`, `Vec::push` and `Vec::len` (used by `violations`), and for `i64`/`i8`/`u8` arithmetic and views. + +| CR-A3 +| The pinned Why3, Why3find, Alt-Ergo, Z3 and cvc5 (`PINS`) are sound. +|=== + +The proofs add no `#[trusted]` item and no admitted lemma. If one is ever +needed, it must get a row here first. + +== Running + +---- +bash verification/creusot/install.sh # pinned toolchain (PINS); needs opam +just creusot # = bash verification/creusot/run.sh +---- diff --git a/verification/creusot/SCOPE b/verification/creusot/SCOPE new file mode 100644 index 0000000..7ed79a5 --- /dev/null +++ b/verification/creusot/SCOPE @@ -0,0 +1,29 @@ +# SPDX-License-Identifier: MPL-2.0 +# Proof scope: the Coma files the positive proof must discharge. One cargo-creusot +# segment pattern per line (see `cargo creusot --help`, ). run.sh fails if +# a pattern matches no file, so a renamed function cannot silently drop out. +# Every Coma file NOT matched here is out of scope and listed as OPEN in the log. +# The JSON parser (Json, P, parse_json), the decoder (dec_*, req, str_list, +# validate_graph) and acc/check/topo_witness_order are not translated at all: +# lib.rs marks them #[cfg(not(creusot))] because Creusot rejects their recursion +# (a recursive Json type under Vec, mutually recursive parser functions) without +# termination arguments. They stay OPEN; nothing in SCOPE calls them. +tropecheck_rs_rlib::creusot_spec::* +tropecheck_rs_rlib::dkey +tropecheck_rs_rlib::dadd +tropecheck_rs_rlib::fate_le +tropecheck_rs_rlib::fate_compose +tropecheck_rs_rlib::fate_meet +tropecheck_rs_rlib::bond_rank +tropecheck_rs_rlib::bond_le +tropecheck_rs_rlib::bond_compose +tropecheck_rs_rlib::bond_meet +tropecheck_rs_rlib::merge_rank +tropecheck_rs_rlib::merge_le +tropecheck_rs_rlib::merge_compose +tropecheck_rs_rlib::merge_meet +tropecheck_rs_rlib::epsilon +tropecheck_rs_rlib::grade_compose +tropecheck_rs_rlib::grade_meet +tropecheck_rs_rlib::grade_le +tropecheck_rs_rlib::violations diff --git a/verification/creusot/controls/Cargo.lock b/verification/creusot/controls/Cargo.lock new file mode 100644 index 0000000..f8b2fc9 --- /dev/null +++ b/verification/creusot/controls/Cargo.lock @@ -0,0 +1,240 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "creusot-std" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c258fc3bed45edeb0509fce569f66565cae19b583d24a827faaa4e1abe51d2b" +dependencies = [ + "creusot-std-proc", +] + +[[package]] +name = "creusot-std-proc" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "848b1d0c5b674f9eb80e144602ab64d8ddcef5033d60a07a5be112b1c931d029" +dependencies = [ + "pearlite-syn", + "proc-macro2", + "quote", + "syn 2.0.119", + "uuid", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "pearlite-syn" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7afb8267bb550980a04ce048a1f1592af3741fab76d1b364678696efbe2570" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tropecheck-creusot" +version = "0.1.0" +dependencies = [ + "creusot-std", +] + +[[package]] +name = "tropecheck-creusot-controls" +version = "0.1.0" +dependencies = [ + "creusot-std", + "tropecheck-creusot", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] diff --git a/verification/creusot/controls/Cargo.toml b/verification/creusot/controls/Cargo.toml new file mode 100644 index 0000000..c505367 --- /dev/null +++ b/verification/creusot/controls/Cargo.toml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +# SPDX-License-Identifier: MPL-2.0 +# +# Planted controls. Each feature switches on ONE false contract about the +# verified crate. run.sh proves each feature on its own and requires Creusot to +# REFUSE it. A control that proves is a gate failure: it means the contracts or +# the solvers are not discriminating. +[package] +name = "tropecheck-creusot-controls" +version = "0.1.0" +edition = "2021" +license = "MPL-2.0" +publish = false + +[dependencies] +creusot-std = "=0.15.0" +tropecheck-creusot = { path = ".." } + +[features] +c00_false = [] +c01_pre_a1_drop_absorbs_lie = [] +c02_dadd_without_overflow_precondition = [] +c03_meet_lower_bound_off_honest = [] +c04_predicated_le_dropped = [] +c05_agda_correspondence_everywhere = [] +c06_l4_without_nonneg = [] +c07_meet_lower_bound_grade_off_honest = [] +c08_violations_empty_always = [] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(creusot)'] } + +[workspace] diff --git a/verification/creusot/controls/src/lib.rs b/verification/creusot/controls/src/lib.rs new file mode 100644 index 0000000..b402408 --- /dev/null +++ b/verification/creusot/controls/src/lib.rs @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +// SPDX-License-Identifier: MPL-2.0 +// +// Planted false contracts. Every item here is FALSE. run.sh enables one feature +// at a time and requires Creusot to fail on it. See ../README.adoc. +#![allow(dead_code, unused_imports)] +#![cfg(creusot)] + +use creusot_std::prelude::*; +use tropecheck_rs::creusot_spec::*; +use tropecheck_rs::*; + +/// c00: the solver sanity control. `false` must never be provable. +#[cfg(feature = "c00_false")] +#[ensures(false)] +pub fn c00() {} + +/// c01: the pre-A1 law "the drop swallows the lie". Ratified A1 says the lie +/// survives: compose(Dropped, Falsified) = Falsified. +#[cfg(feature = "c01_pre_a1_drop_absorbs_lie")] +#[ensures(result.deep_model() == FateM::Dropped)] +pub fn c01() -> Fate { + fate_compose(&Fate::Dropped, &Fate::Falsified) +} + +/// c02: calling dadd with no overflow precondition (owner ruling 1: overflow is +/// a precondition proved at callers). Creusot must fail dadd's precondition. +#[cfg(feature = "c02_dadd_without_overflow_precondition")] +pub fn c02(a: &Delta, b: &Delta) -> Delta { + dadd(a, b) +} + +/// c03: meet is a lower bound with no honesty precondition. False in Rust: +/// meet(Falsified, Present) = Dropped, and Dropped is not below Falsified. This +/// is the live control for the deceptive-order divergence. +#[cfg(feature = "c03_meet_lower_bound_off_honest")] +#[ensures(fate_le_m(result.deep_model(), a.deep_model()))] +pub fn c03(a: &Fate, b: &Fate) -> Fate { + fate_meet(a, b) +} + +/// c04: the converse of A2. A checkbox is not retained by nothing. +#[cfg(feature = "c04_predicated_le_dropped")] +#[ensures(result)] +pub fn c04() -> bool { + fate_le(&Fate::Predicated, &Fate::Dropped) +} + +/// c05: the Rust fate order equals the Agda fateLte on ALL inputs. False on +/// deceptive inputs (Agda: Falsified βŠ‘ everything; Rust: only itself). +#[cfg(feature = "c05_agda_correspondence_everywhere")] +#[logic] +#[ensures(fate_le_m(a, b) == agda_fate_le(a, b))] +pub fn c05(a: FateM, b: FateM) {} + +/// c06: L4 without non-negative losses. Atten(Q -1) βŠ‘ Present, but composing +/// both with Atten(Q 1) gives Atten(Q 0) β‹’ Atten(Q 1). +#[cfg(feature = "c06_l4_without_nonneg")] +#[logic] +#[requires(fate_le_m(a, b))] +#[ensures(fate_le_m(fate_compose_m(a, c), fate_compose_m(b, c)))] +pub fn c06(a: FateM, b: FateM, c: FateM) {} + +/// c07: grade meet is a lower bound with no honesty precondition. +#[cfg(feature = "c07_meet_lower_bound_grade_off_honest")] +#[logic] +#[ensures(grade_le_m(grade_meet_m(a, b), a))] +pub fn c07(a: GradeM, b: GradeM) {} + +/// c08: violations never reports anything, whatever the floor. +#[cfg(feature = "c08_violations_empty_always")] +#[ensures(result@.len() == 0)] +pub fn c08(fl: &Floor, g: &Grade) -> Vec { + violations(fl, g) +} diff --git a/verification/creusot/controls/why3find.json b/verification/creusot/controls/why3find.json new file mode 100644 index 0000000..87e98a4 --- /dev/null +++ b/verification/creusot/controls/why3find.json @@ -0,0 +1,16 @@ +{ + "fast": 0.2, + "time": 1.0, + "depth": 6, + "packages": [ "creusot" ], + "provers": [ "alt-ergo", "z3", "cvc5", "cvc4" ], + "tactics": [ "compute_specified", "split_vc" ], + "drivers": [], + "warnoff": [ "unused_variable", "axiom_abstract" ], + "profile": [ + { "prover": "cvc5@", "size": 47, "time": 0.541 }, + { "prover": "z3@", "size": 33, "time": 0.793 }, + { "prover": "alt-ergo@", "size": 17, "time": 0.58 }, + { "prover": "cvc4@", "size": 45, "time": 0.432 } + ] +} diff --git a/verification/creusot/install.sh b/verification/creusot/install.sh new file mode 100755 index 0000000..50dcece --- /dev/null +++ b/verification/creusot/install.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +# SPDX-License-Identifier: MPL-2.0 +# +# Install the pinned Creusot toolchain (verification/creusot/PINS). Used by +# .github/workflows/creusot.yml and by hand. Any failure exits non-zero: the +# gate is then RED, never silently green. +# +# Needs: git, rustup, opam and libzmq3-dev (apt), a C toolchain. Downloads: the creusot +# repo at the pinned SHA, the pinned nightly, why3/why3find from their pinned +# git commits (via opam), and alt-ergo/z3/cvc5 release binaries, which +# creusot's own installer checks against sha256 sums fixed in its source. +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=/dev/null +source "$here/PINS" +dest="${CREUSOT_SRC:-$HOME/.cache/creusot-src}" + +if [[ ! -d "$dest/.git" ]]; then + git clone --quiet --depth 1 --branch "$CREUSOT_TAG" "$CREUSOT_REPO" "$dest" +fi +got="$(git -C "$dest" rev-parse HEAD)" +if [[ "$got" != "$CREUSOT_SHA" ]]; then + echo "FAIL: $CREUSOT_TAG resolved to $got, pinned $CREUSOT_SHA" >&2 + exit 1 +fi +want_nightly="$(sed -n 's/^channel = "\(.*\)"$/\1/p' "$dest/rust-toolchain")" +if [[ "$want_nightly" != "$RUST_NIGHTLY" ]]; then + echo "FAIL: creusot wants $want_nightly, PINS says $RUST_NIGHTLY" >&2 + exit 1 +fi +rustup toolchain install "$RUST_NIGHTLY" --profile minimal -c rustfmt,rustc-dev,llvm-tools + +# The pins the installer will use must still be the ones PINS records. +grep -q "\"ocaml\" {= \"$OCAML\"}" "$dest/creusot-deps.opam" \ + || { echo "FAIL: creusot-deps.opam no longer pins ocaml $OCAML" >&2; exit 1; } +grep -q "$WHY3_GIT" "$dest/creusot-deps.opam" || { echo "FAIL: why3 pin drifted" >&2; exit 1; } +grep -q "$WHY3FIND_GIT" "$dest/creusot-deps.opam" || { echo "FAIL: why3find pin drifted" >&2; exit 1; } + +# Follow creusot's own CI (.github/workflows/rust.yml at the tag): an opam root, +# then `in-creusot-ci=true`, which drops the GTK-based why3-ide from +# creusot-deps.opam (`!?in-creusot-ci`). The gate never opens the IDE. +# ./INSTALL then creates and owns its own opam switch (creusot-install, +# opam_switch) from creusot-deps.opam, compiler included. No separate switch, +# no `opam install --deps-only`, no eval. +export OPAMYES=1 +[[ -d "${OPAMROOT:-$HOME/.opam}" ]] || opam init --bare --disable-sandboxing -n +opam --cli=2.1 var --global in-creusot-ci=true +(cd "$dest" && ./INSTALL) +cargo creusot --help >/dev/null +echo "creusot $CREUSOT_TAG installed" diff --git a/verification/creusot/mutants/MUTANTS b/verification/creusot/mutants/MUTANTS new file mode 100644 index 0000000..f415027 --- /dev/null +++ b/verification/creusot/mutants/MUTANTS @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: MPL-2.0 +# Code mutants. Format: id function exact original text replacement. +# run.sh copies src/rust/src to a scratch tree, applies ONE mutant (it fails if the +# original text is not found exactly once), and requires Creusot to refuse the crate. +m01_drop_swallows_lie fate_compose (Falsified, _) | (Dropped | Atten(_) | Predicated, Falsified) => Falsified, (Falsified, _) | (Atten(_) | Predicated, Falsified) => Falsified, +m02_delta_order_flipped fate_le (Atten(a), Atten(b)) => dkey(a) >= dkey(b), (Atten(a), Atten(b)) => dkey(a) <= dkey(b), +m03_misbound_not_absorbing bond_compose return Bond::Misbound; return Bond::Intact; +m04_quality_floor_inverted violations if !fate_le(d, &g.q) { if fate_le(d, &g.q) { +m05_dadd_drops_rhs dadd (Delta::Q(x), Delta::Q(y)) => Delta::Q(x + y), (Delta::Q(x), Delta::Q(_)) => Delta::Q(*x), +m06_merge_compose_max merge_compose if merge_rank(a) <= merge_rank(b) { if merge_rank(a) >= merge_rank(b) { +m07_a2_reverted fate_le (Predicated | Dropped, Atten(_)) | (Dropped, Predicated) => true, (Predicated | Dropped, Atten(_)) => true, diff --git a/verification/creusot/run.sh b/verification/creusot/run.sh new file mode 100755 index 0000000..415503d --- /dev/null +++ b/verification/creusot/run.sh @@ -0,0 +1,258 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +# SPDX-License-Identifier: MPL-2.0 +# +# Creusot gate for the Rust fast core. Fails loudly: +# 1. `cargo creusot` must be installed. A missing tool is exit 3 (OPEN), never 0. +# 2. The positive proof covers exactly the Coma files named in SCOPE. Every SCOPE +# pattern must match at least one file. Files outside SCOPE are listed as OPEN. +# 3. Every planted control (controls/, one Cargo feature each) must translate to +# Coma, produce its own Coma file, and then be REFUSED by the provers. +# 4. Every mutant (mutants/MUTANTS) must compile with plain rustc, translate to +# Coma, and then be REFUSED by the provers on the SCOPE files. +# A refusal counts only on a positive why3find verdict on the intended function: +# "proof failed", "Goal Coma.vc_: ✘", "Error: unproved file", and no +# other failing goal (see prover_refused). Any other failure fails the gate. A setup error (missing why3find.json, no files, +# launch failure) is a gate failure, never a refusal. +# Regeneration is forced every time: sources are touched so Creusot's Cargo cache +# (target/creusot) cannot skip creusot-rustc, and verif/ is wiped. A self-check +# reruns the crate and one control with identical inputs and a warm cache and +# requires every Coma file to be rewritten. +# Exit codes: 0 all good; 1 red; 3 Creusot not installed (OPEN). +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +root="$(cd "$here/../.." && pwd)" +# shellcheck source=/dev/null +source "$here/PINS" + +if ! command -v cargo-creusot >/dev/null 2>&1; then + echo "OPEN: cargo-creusot is not installed (pinned $CREUSOT_TAG @ $CREUSOT_SHA)." >&2 + echo "OPEN: nothing about the Rust core is proved by this run." >&2 + exit 3 +fi +for ws in "$here" "$here/controls"; do + [[ -f "$ws/why3find.json" ]] || { echo "FAIL: $ws/why3find.json missing"; exit 1; } +done + +fail=0 +COMA_GLOB="*.coma" +log="${CREUSOT_LOG_DIR:-$(mktemp -d)}" +mkdir -p "$log" +echo "logs: $log" +mapfile -t scope < <(grep -v '^#' "$here/SCOPE" | sed '/^[[:space:]]*$/d') +[[ "${#scope[@]}" -gt 0 ]] || { echo "FAIL: SCOPE is empty"; exit 1; } + +# setup_error LOGFILE: true if the prove step failed before or outside the provers. +setup_error() { + local logfile="$1" + grep -qE "No files to prove|failed to launch|not found\. Perhaps|Pattern must be non-empty|could not compile" "$logfile" +} + +# prover_refused LOGFILE FN: true only for a positive why3find verdict on FN. +# Format taken from real CI logs (run 44507269211, why3find 89dd8721): for each +# goal it cannot prove, why3find prints ": proof failed" (the position +# is the Rust source span, or the .coma file for a logic lemma), then +# "Goal Coma.vc_: ✘ ...", and finally "Error: unproved file". A refusal +# needs all three, a failing Goal line naming exactly vc_, and no failing +# Goal line for any other function. Anything else is an unrecognised failure. +# Note: why3find's ✘ means "not proved within the prover budget"; it does not +# distinguish a refutation from a timeout. See README "What a refusal means". +prover_refused() { + local logfile="$1" fn="$2" plain others + plain="$(sed 's/\x1b\[[0-9;]*m//g' "$logfile")" + grep -q ': proof failed$' <<<"$plain" || return 1 + grep -qE '^Error: [0-9]+ unproved file' <<<"$plain" || return 1 + grep -qE "^ *Goal Coma\.vc_${fn}: ✘" <<<"$plain" || return 1 + others="$(grep -E '^ *Goal [^ ]+: ✘' <<<"$plain" | grep -vE "^ *Goal Coma\.vc_${fn}: ✘" || true)" + [[ -z "$others" ]] +} + +# show_log LOGFILE: print the prover output of an unrecognised failure into the CI +# log (colour codes stripped, build noise dropped), so the verdict can be read. +show_log() { + local logfile="$1" + sed 's/\x1b\[[0-9;]*m//g' "$logfile" \ + | grep -v -E '^ *(Compiling|Checking|Downloaded|Downloading|Updating|Locking|Finished) ' \ + | tail -60 | sed 's/^/ | /' +} + +# coma_newer_than WS MARKER: Coma output exists, and every file is newer than MARKER. +coma_newer_than() { + local ws="$1" marker="$2" + [[ -n "$(find "$ws/verif" -name "$COMA_GLOB" -print -quit 2>/dev/null)" ]] \ + && [[ -z "$(find "$ws/verif" -name "$COMA_GLOB" ! -newer "$marker" -print -quit)" ]] +} + +# fresh_coma WS LOGFILE [CARGO ARGS...]: force regeneration, translate, require output. +fresh_coma() { + local ws="$1" out="$2"; shift 2 + rm -rf "$ws/verif" + find "$ws" "$root/src/rust/src" -name '*.rs' -not -path '*/target/*' -exec touch {} + + if ! (cd "$ws" && cargo creusot --only=coma "$@") >"$out" 2>&1; then + return 1 + fi + [[ -n "$(find "$ws/verif" -name "$COMA_GLOB" -print -quit 2>/dev/null)" ]] +} + +# ── 1. the positive proof, on SCOPE only ── +echo "== prove: SCOPE of the verification crate (src/rust/src/lib.rs + creusot_spec.rs)" +if ! fresh_coma "$here" "$log/coma.log"; then + echo "FAIL: translation to Coma failed or wrote no Coma file (see $log/coma.log)" + # Every error with its context, not just the tail: a truncated log hid the + # first error of an earlier run. + grep -v -E '^ *(Compiling|Checking|Downloaded|Downloading|Updating|Locking) ' "$log/coma.log" | head -400 + exit 1 +fi +# Regeneration self-check: translate again with the same inputs and a warm +# target/creusot. Every Coma file must be rewritten (newer than the marker), and +# the output must not be empty. A cache that skips creusot-rustc fails here. +marker="$(mktemp)"; sleep 1 +if ! fresh_coma "$here" "$log/coma-rerun.log" || ! coma_newer_than "$here" "$marker"; then + echo "FAIL: warm-cache rerun did not regenerate every Coma file (see $log/coma-rerun.log)" + fail=1 +else + echo "regenerated (good): verification crate, warm cache, same inputs" +fi +for p in "${scope[@]}"; do + if ! (cd "$here" && cargo creusot --only=prove --dry-run-why3find "$p") >"$log/scope-check.log" 2>&1; then + echo "FAIL: SCOPE pattern '$p' matches no Coma file" + fail=1 + fi +done +(cd "$here" && find verif -name "$COMA_GLOB" | sort) >"$log/all-coma.txt" +(cd "$here" && cargo creusot --only=prove --dry-run-why3find "${scope[@]}") 2>&1 \ + | tr -s ' "' '\n' | grep '\.coma$' | sort -u >"$log/in-scope.txt" || true +echo "Coma files: $(wc -l <"$log/all-coma.txt") total, $(wc -l <"$log/in-scope.txt") in SCOPE." +echo "OPEN (translated, not in SCOPE, not proved):" +comm -23 "$log/all-coma.txt" "$log/in-scope.txt" | sed 's/^/ /' +if (cd "$here" && cargo creusot --only=prove "${scope[@]}") >"$log/prove.log" 2>&1; then + echo "PROVED: every SCOPE file" +else + echo "FAIL: proofs did not go through (see $log/prove.log)" + tail -60 "$log/prove.log" + fail=1 +fi + +# ── 1b. executable falsity witnesses on the shipped code (hub decision (b)) ── +# verification/creusot/witness: plain cargo test, no Creusot. Every control and +# every mutant must have a witness test of the same name, and all of them must +# pass on the shipped code. A missing or failing witness makes the gate red. This +# makes each refusal stand on a checked counterexample, not on a prover verdict +# alone (why3find's ✘ does not separate refutation from timeout). +wit="$here/witness" +if (cd "$wit" && cargo test --offline --locked -q) >"$log/witness.log" 2>&1; then + echo "witnesses (good): every control and mutant witness holds on the shipped code" +else + echo "FAIL: a witness does not hold on the shipped code (see $log/witness.log)" + show_log "$log/witness.log" + fail=1 +fi +while IFS= read -r name; do + grep -q "^fn ${name}()" "$wit/tests/controls.rs" \ + || { echo "FAIL: control $name has no witness in witness/tests/controls.rs"; fail=1; } +done < <(sed -n 's/^\(c[0-9][0-9]_[a-z0-9_]*\) = \[\]$/\1/p' "$here/controls/Cargo.toml") +while IFS=$'\t' read -r id _rest; do + [[ -z "${id}" || "${id}" == \#* ]] && continue + grep -q "^fn ${id}()" "$wit/tests/mutants.rs" \ + || { echo "FAIL: mutant $id has no witness in witness/tests/mutants.rs"; fail=1; } +done < "$here/mutants/MUTANTS" + +# ── 2. the planted controls ── +mapfile -t controls < <(sed -n 's/^\(c[0-9][0-9]_[a-z0-9_]*\) = \[\]$/\1/p' "$here/controls/Cargo.toml") +[[ "${#controls[@]}" -gt 0 ]] || { echo "FAIL: no controls found"; exit 1; } +for c in "${controls[@]}"; do + fn="${c%%_*}" # c03_meet_... -> c03, the control's function name + if ! fresh_coma "$here/controls" "$log/control-$c-coma.log" -- --features "$c"; then + echo "FAIL: control $c did not translate to Coma; a refusal would prove nothing" + fail=1; continue + fi + if [[ -z "$(find "$here/controls/verif" -name "$fn*.coma" -print -quit)" ]]; then + echo "FAIL: control $c produced no Coma file for $fn" + fail=1; continue + fi + if (cd "$here/controls" && cargo creusot --only=prove "tropecheck_creusot_controls_rlib::$fn") >"$log/control-$c.log" 2>&1; then + echo "FAIL: control $c was PROVED. A false contract went through." + fail=1 + elif setup_error "$log/control-$c.log" || ! prover_refused "$log/control-$c.log" "$fn"; then + echo "FAIL: control $c: unrecognised failure, no why3find 'proof failed' verdict on $fn (see $log/control-$c.log)" + show_log "$log/control-$c.log" + fail=1 + else + echo "refused (good): control $c" + sed 's/\x1b\[[0-9;]*m//g' "$log/control-$c.log" | grep -E ': proof failed|^ *Goal ' | head -6 | sed 's/^/ | /' + fi +done + +# Same self-check for a control: rerun the last control with the same feature. +c="${controls[-1]}"; fn="${c%%_*}" +marker="$(mktemp)"; sleep 1 +if fresh_coma "$here/controls" "$log/control-$c-rerun.log" -- --features "$c" \ + && coma_newer_than "$here/controls" "$marker" \ + && [[ -n "$(find "$here/controls/verif" -name "$fn.coma" -newer "$marker" -print -quit)" ]]; then + echo "regenerated (good): control $c, warm cache, same feature" +else + echo "FAIL: control $c rerun did not regenerate its Coma (see $log/control-$c-rerun.log)" + fail=1 +fi + +# ── 3. the mutants ── +while IFS=$'\t' read -r id fn old new; do + [[ -z "${id}" || "${id}" == \#* ]] && continue + work="$(mktemp -d)" + mkdir -p "$work/src/rust" "$work/verification" + cp -r "$root/src/rust/src" "$work/src/rust/src" + cp "$root/src/rust/Cargo.toml" "$work/src/rust/" + # Copy the verification tree without build output, so each mutant starts with + # a fresh target/ and verif/ (both trees). + (cd "$here" && find . \( -path ./target -o -path ./verif -o -path ./controls/target -o -path ./controls/verif -o -path ./witness/target \) -prune -o -type f -print0 \ + | while IFS= read -r -d '' f; do mkdir -p "$work/verification/creusot/$(dirname "$f")"; cp "$f" "$work/verification/creusot/$f"; done) + n="$(grep -cF -- "$old" "$work/src/rust/src/lib.rs" || true)" + if [[ "$n" != "1" ]]; then + echo "FAIL: mutant $id ($fn): original text found $n times, expected 1" + fail=1; rm -rf "$work"; continue + fi + # Literal (not glob) single replacement in pure bash. + src="$(<"$work/src/rust/src/lib.rs")" + printf '%s\n' "${src/"$old"/"$new"}" >"$work/src/rust/src/lib.rs" + if ! (cd "$work/src/rust" && cargo check --offline -q) >"$log/mutant-$id-rustc.log" 2>&1; then + echo "FAIL: mutant $id does not compile with plain rustc; it would be refused for the wrong reason" + fail=1; rm -rf "$work"; continue + fi + if ! (cd "$work/verification/creusot" && cargo creusot --only=coma) >"$log/mutant-$id-coma.log" 2>&1 \ + || [[ -z "$(find "$work/verification/creusot/verif" -name "$COMA_GLOB" -print -quit 2>/dev/null)" ]]; then + echo "FAIL: mutant $id did not translate to Coma; a refusal would prove nothing" + fail=1; rm -rf "$work"; continue + fi + # The witness for this mutant must FAIL on the mutated source: a concrete input + # on which the mutant breaks its contract, independent of the provers. + if (cd "$work/verification/creusot/witness" && cargo test --offline --locked -q --test mutants -- --exact "$id") \ + >"$log/mutant-$id-witness.log" 2>&1; then + echo "FAIL: mutant $id: its witness still passes on the mutated code; no concrete contract break" + fail=1 + elif ! grep -q 'test result: FAILED. 0 passed; 1 failed' "$log/mutant-$id-witness.log"; then + echo "FAIL: mutant $id: the witness did not run exactly one failing test (see $log/mutant-$id-witness.log)" + show_log "$log/mutant-$id-witness.log" + fail=1 + else + echo "witness breaks (good): mutant $id" + fi + if (cd "$work/verification/creusot" && cargo creusot --only=prove "${scope[@]}") >"$log/mutant-$id.log" 2>&1; then + echo "FAIL: mutant $id ($fn) was PROVED. The contracts do not pin the code." + fail=1 + elif setup_error "$log/mutant-$id.log" || ! prover_refused "$log/mutant-$id.log" "$fn"; then + echo "FAIL: mutant $id: unrecognised failure, no why3find 'proof failed' verdict on $fn (see $log/mutant-$id.log)" + show_log "$log/mutant-$id.log" + fail=1 + else + echo "refused (good): mutant $id ($fn)" + sed 's/\x1b\[[0-9;]*m//g' "$log/mutant-$id.log" | grep -E ': proof failed|^ *Goal ' | head -6 | sed 's/^/ | /' + fi + rm -rf "$work" +done < "$here/mutants/MUTANTS" + +if [[ "$fail" -ne 0 ]]; then + echo "CREUSOT GATE: RED" + exit 1 +fi +echo "CREUSOT GATE: GREEN (SCOPE proved; ${#controls[@]} controls and every mutant refused)" diff --git a/verification/creusot/why3find.json b/verification/creusot/why3find.json new file mode 100644 index 0000000..87e98a4 --- /dev/null +++ b/verification/creusot/why3find.json @@ -0,0 +1,16 @@ +{ + "fast": 0.2, + "time": 1.0, + "depth": 6, + "packages": [ "creusot" ], + "provers": [ "alt-ergo", "z3", "cvc5", "cvc4" ], + "tactics": [ "compute_specified", "split_vc" ], + "drivers": [], + "warnoff": [ "unused_variable", "axiom_abstract" ], + "profile": [ + { "prover": "cvc5@", "size": 47, "time": 0.541 }, + { "prover": "z3@", "size": 33, "time": 0.793 }, + { "prover": "alt-ergo@", "size": 17, "time": 0.58 }, + { "prover": "cvc4@", "size": 45, "time": 0.432 } + ] +} diff --git a/verification/creusot/witness/Cargo.lock b/verification/creusot/witness/Cargo.lock new file mode 100644 index 0000000..f3f39d8 --- /dev/null +++ b/verification/creusot/witness/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "tropecheck-rs" +version = "0.1.0" + +[[package]] +name = "tropecheck-witness" +version = "0.1.0" +dependencies = [ + "tropecheck-rs", +] diff --git a/verification/creusot/witness/Cargo.toml b/verification/creusot/witness/Cargo.toml new file mode 100644 index 0000000..03d850c --- /dev/null +++ b/verification/creusot/witness/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +# SPDX-License-Identifier: MPL-2.0 +# +# Executable falsity witnesses (hub decision (b), 19 Nov). Plain Rust, plain +# cargo test, no Creusot. They make each control's falsity and each mutant's +# contract break a checked fact, independent of the provers, so a prover +# timeout can never pass as a refusal. See ../README.adoc, "What a refusal means". +[package] +name = "tropecheck-witness" +version = "0.1.0" +edition = "2021" +license = "MPL-2.0" +publish = false + +[dependencies] +tropecheck-rs = { path = "../../../src/rust" } + +[workspace] diff --git a/verification/creusot/witness/tests/controls.rs b/verification/creusot/witness/tests/controls.rs new file mode 100644 index 0000000..fd548f8 --- /dev/null +++ b/verification/creusot/witness/tests/controls.rs @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +// SPDX-License-Identifier: MPL-2.0 +// +// One test per planted control in ../controls. Each test PASSES on the shipped +// code exactly when that control's claim is FALSE, by running a concrete +// counterexample. run.sh requires every test here to pass; a witness that does +// not hold makes the Creusot gate red. +use tropecheck_rs::{ + dadd, epsilon, fate_compose, fate_le, fate_meet, grade_le, grade_meet, violations, Delta, Fate, + Floor, +}; + +fn floor_q(q: Fate) -> Floor { + Floor { + q: Some(q), + b: None, + c: None, + r: None, + bond: None, + merge: None, + } +} + +/// c00 claims `ensures(false)`: false for every input, nothing to run. +#[test] +fn c00_false() { + let claim = false; + assert!(!claim); +} + +/// c01 claims compose(Dropped, Falsified) = Dropped. A1: it is Falsified. +#[test] +fn c01_pre_a1_drop_absorbs_lie() { + let r = fate_compose(&Fate::Dropped, &Fate::Falsified); + assert!(r == Fate::Falsified); + assert!(r != Fate::Dropped); +} + +/// c02 calls dadd with no overflow precondition. Q(i64::MAX) + Q(1) overflows. +#[test] +#[should_panic(expected = "overflow")] +fn c02_dadd_without_overflow_precondition() { + let _ = dadd(&Delta::Q(i64::MAX), &Delta::Q(1)); +} + +/// c03 claims meet(a, b) βŠ‘ a for all fates. a = Falsified, b = Present: +/// meet = Dropped, and Dropped β‹’ Falsified in the Rust order. +#[test] +fn c03_meet_lower_bound_off_honest() { + let m = fate_meet(&Fate::Falsified, &Fate::Present); + assert!(m == Fate::Dropped); + assert!(!fate_le(&m, &Fate::Falsified)); +} + +/// c04 claims Predicated βŠ‘ Dropped. A2 says the converse only. +#[test] +fn c04_predicated_le_dropped() { + assert!(!fate_le(&Fate::Predicated, &Fate::Dropped)); +} + +/// c05 claims the Rust fate order equals Agda's fateLte everywhere. Agda has +/// `fateLte falsified _ = true` (TB/Order.agda, checked below); Rust says +/// Falsified β‹’ Present. +#[test] +fn c05_agda_correspondence_everywhere() { + let agda = include_str!("../../../proofs/agda/theorem-b/TB/Order.agda"); + assert!(agda.contains("fateLte falsified _ = true")); + assert!(!fate_le(&Fate::Falsified, &Fate::Present)); +} + +/// c06 claims L4 without non-negative losses. a = Atten(-1) βŠ‘ b = Present, but +/// composing both with c = Atten(1) gives Atten(0) β‹’ Atten(1). +#[test] +fn c06_l4_without_nonneg() { + let (a, b, c) = ( + Fate::Atten(Delta::Q(-1)), + Fate::Present, + Fate::Atten(Delta::Q(1)), + ); + assert!(fate_le(&a, &b)); + assert!(!fate_le(&fate_compose(&a, &c), &fate_compose(&b, &c))); +} + +/// c07 claims grade_meet(a, b) βŠ‘ a for all grades. a.q = Falsified, b = Ξ΅. +#[test] +fn c07_meet_lower_bound_grade_off_honest() { + let mut a = epsilon(); + a.q = Fate::Falsified; + let m = grade_meet(&a, &epsilon()); + assert!(!grade_le(&m, &a)); +} + +/// c08 claims violations is always empty. Floor q = Present against q = Dropped. +#[test] +fn c08_violations_empty_always() { + let mut g = epsilon(); + g.q = Fate::Dropped; + assert!(!violations(&floor_q(Fate::Present), &g).is_empty()); +} diff --git a/verification/creusot/witness/tests/mutants.rs b/verification/creusot/witness/tests/mutants.rs new file mode 100644 index 0000000..54f67a8 --- /dev/null +++ b/verification/creusot/witness/tests/mutants.rs @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: Β© 2026 Jonathan D.A. Jewell (hyperpolymath) +// SPDX-License-Identifier: MPL-2.0 +// +// One test per mutant in ../mutants/MUTANTS, named by its id. Each test states +// the function's contract on one concrete input. run.sh requires every test to +// PASS on the shipped code, and the mutant's own test to FAIL on the mutated +// code: a concrete input on which the mutant breaks its contract. +use tropecheck_rs::{ + bond_compose, dadd, epsilon, fate_compose, fate_le, merge_compose, violations, Bond, Delta, + Fate, Floor, Merge, +}; + +fn floor_q(q: Fate) -> Floor { + Floor { + q: Some(q), + b: None, + c: None, + r: None, + bond: None, + merge: None, + } +} + +#[test] +fn m01_drop_swallows_lie() { + assert!(fate_compose(&Fate::Dropped, &Fate::Falsified) == Fate::Falsified); +} + +#[test] +fn m02_delta_order_flipped() { + // Loss 10 retains less than loss 3. + assert!(fate_le( + &Fate::Atten(Delta::Q(10)), + &Fate::Atten(Delta::Q(3)) + )); +} + +#[test] +fn m03_misbound_not_absorbing() { + assert!(bond_compose(&Bond::Misbound, &Bond::Intact) == Bond::Misbound); +} + +#[test] +fn m04_quality_floor_inverted() { + let mut dropped = epsilon(); + dropped.q = Fate::Dropped; + assert!(violations(&floor_q(Fate::Present), &epsilon()).is_empty()); + assert!(violations(&floor_q(Fate::Present), &dropped) == vec!["fate.quality".to_string()]); +} + +#[test] +fn m05_dadd_drops_rhs() { + assert!(dadd(&Delta::Q(2), &Delta::Q(3)) == Delta::Q(5)); +} + +#[test] +fn m06_merge_compose_max() { + assert!(merge_compose(&Merge::Single, &Merge::Fused) == Merge::Fused); +} + +#[test] +fn m07_a2_reverted() { + assert!(fate_le(&Fate::Dropped, &Fate::Predicated)); +}