feat(verify): discharge Creusot VCs end-to-end

Make `just verify` actually invoke Why3 + alt-ergo + z3 against every
Pearlite VC, and fix the mutant + miri pipelines along the way.

Verification crate
  - Drop the const-generic CAP types for EventQueue / TimerTable.
    Mirror with std::vec::Vec, whose creusot-std specs carry the
    proof burden. Capacity behavior is exercised by the runtime's
    own unit tests + correspondence tests.
  - View impls are #[logic(open)] over a pub field so contracts on
    push/pop/etc. can see the link to the inner Vec's @ view.
  - 14/14 VCs discharge: EventQueue {new, push, pop, is_empty, len,
    clear, Default}; TimerTable {new, len, is_empty, Default};
    Entry derives.
  - `cargo creusot prove --no-cache` always runs the SMT solvers;
    `time` shows ~7s CPU on ~1.2s wall-clock = real parallel work.

Tooling
  - verification/mise.toml pins nightly-2025-11-13 + rust-src,
    rustc-dev, llvm-tools-preview, rustfmt; declares opam, python,
    uv, and the project-local .venv. Inherits root mise.toml's just
    + cargo-* tools.
  - just verify clones creusot v0.9.0 to ~/.local/share/hsmc-verify/
    and runs the canonical ./INSTALL — that's the only way the
    bundled prelude-generator + creusot-rustc actually build.
  - just verify --no-cache forces SMT re-runs every time.
  - Drop bespoke pin/install of cargo-creusot from mise.toml; the
    cargo backend goes through cargo-binstall which can't pin a
    multi-bin git workspace at a tag.

Mutants — was missing every JournalSink mutant
  - Recipe runs with --features tokio,journal so journal_* and det_*
    tests (gated on both) actually execute.
  - Add clear_journal_empties_the_journal test in journal_smoke.rs
    to kill the JournalSink::clear with-() mutant.
  - Remove dead JournalSink::len + is_empty (called nowhere; only
    existed as mutation-bait).
  Result: 0 missed, 42 caught, 211 unviable (proc-macro emitted
  code that mutants can't standalone-compile).

Miri — was hitting the trybuild glob isolation issue
  - --exclude hsmc-macros (trybuild ui test isn't UB-relevant)
  - --exclude hsmc-verification (different pinned toolchain)
  - 66 tests pass under Miri, 0 UB.

Gitignore
  - /verif/, /why3find.json, /.why3find/, **/.venv/ — all
    regenerated by `just verify`. Repo stays clean of per-machine
    prover timings + venv artifacts.

Misc
  - Fix root-state targetability: `on(Trig) => <ChartName>;` resolves
    to root id 0 in both ir.rs::resolve_transitions and
    validate.rs's separate name_map.
  - `set shell` and `set script-interpreter` route every justfile
    recipe through `mise exec`, so all subshells see the right
    Rust + opam + cargo-* tools regardless of how `just` was
    invoked. No shebangs anywhere.
This commit is contained in:
swaits committed 2026-04-27 21:22:44 -06:00
1 parent 081bd28cca
commit e183cdd95e
33 files changed
+2943 -2148

No files matched your search

+75 -101
View File
@@ -1,138 +1,112 @@
//! Verified mirror of `hsmc::__private::EventQueue`.
//!
//! Bounded FIFO queue. The runtime uses `heapless::Deque<E, N>` under the
//! hood (a fixed-capacity ring buffer); this mirror uses an array with
//! head index + length, which Creusot can reason about directly via the
//! `Seq<E>` view returned by [`View::view`].
//! FIFO queue. The runtime uses a fixed-capacity ring buffer
//! (`heapless::Deque<E, N>`); this mirror uses a `Vec<E>` for which
//! creusot-std already ships full specs — push/pop/remove/clear all
//! have proven contracts upstream. Our wrapper just exposes the FIFO
//! discipline on top.
//!
//! Spec rules pinned (see `docs/002. hsmc-semantics-formal.md`):
//! Spec rules pinned (see `docs/002. hsmc-semantics-formal.md`,
//! section "emit() — sending events from inside an action"):
//!
//! - `push()` returns `Err(QueueFull)` exactly when at capacity.
//! - `push()` on a non-full queue grows the view by appending at the back.
//! - `pop()` returns `None` exactly when empty; otherwise returns the
//! front element and truncates the view from the front.
//! - `is_empty()` ⇔ `view().len() == 0`.
//! - `clear()` makes the view empty.
//! - **S6.FIFO**: push appends to the back; pop returns view[0].
//! - **S6.EMPTY**: pop returns `None` iff empty.
//! - **S6.CLEAR**: clear empties the view.
//! - **S6.LEN**: len matches view length.
//!
//! Correspondence with the real runtime type is enforced by
//! `tests/correspondence.rs`.
//! Boundedness (the runtime's `Err(QueueFull)` path) is intentionally
//! NOT modeled here — it's a property of the ring buffer at the
//! runtime level and is verified by the unit tests in
//! `hsmc/src/lib.rs::private_internals` and the correspondence tests
//! in `tests/correspondence_event_queue.rs`. Creusot proves the FIFO
//! discipline; the unit tests pin the cap behavior.
// Specific imports — avoid `creusot_std::prelude::*` because its
// `Clone` / `PartialEq` derive macros conflict with core's preludes.
//
// `invariant` looks unused to plain `cargo check` because it resolves
// at the inline-attribute level inside loop bodies, but Creusot's
// preprocessing needs the import. Allow the false warning.
#[allow(unused_imports)]
use creusot_std::macros::invariant;
use creusot_std::logic::Seq;
use creusot_std::model::{DeepModel, View};
use creusot_std::macros::{ensures, logic, requires, trusted};
use creusot_std::macros::ensures;
// `pearlite!` looks unused to plain rustc but Creusot's preprocessing
// needs it for the View impl body.
#[allow(unused_imports)]
use creusot_std::macros::pearlite;
/// Error returned by `push()` when the queue is full.
#[derive(Debug, Clone, Copy, PartialEq, Eq, DeepModel)]
pub struct QueueFull;
/// Bounded FIFO event queue.
///
/// Logical view is a `Seq<E>` of length `0..=CAP`, with `view()[0]` the
/// next element to be popped.
pub struct EventQueue<E, const CAP: usize> {
items: [Option<E>; CAP],
head: usize,
len: usize,
/// FIFO event queue. Logical view is a `Seq<E>` in arrival order;
/// `view()[0]` is the next item to be popped.
pub struct EventQueue<E> {
// `pub` because the View impl is `#[logic(open)]` (publicly
// transparent) and references this field — Creusot requires the
// referenced items to have visibility ≥ the view's openness.
pub items: ::std::vec::Vec<E>,
}
impl<E, const CAP: usize> View for EventQueue<E, CAP> {
type ViewTy = Seq<E>;
// Logical model treated as opaque — defined extensionally by the
// contracts on push/pop. `#[logic(opaque)]` says "no body, given
// by axiom"; `dead` is the pearlite placeholder for an unreachable
// body.
#[trusted]
#[logic(opaque)]
fn view(self) -> Seq<E> {
dead
}
}
impl<E: Copy, const CAP: usize> Default for EventQueue<E, CAP> {
fn default() -> Self {
Self::new()
}
}
impl<E: Copy, const CAP: usize> EventQueue<E, CAP> {
impl<E> EventQueue<E> {
/// Construct an empty queue.
#[ensures(result@.len() == 0)]
pub const fn new() -> Self {
#[ensures(result@ == Seq::empty())]
pub fn new() -> Self {
Self {
items: [None; CAP],
head: 0,
len: 0,
items: ::std::vec::Vec::new(),
}
}
/// Push to the back. Fails iff the queue is full.
/// Push to the back.
///
/// - **S6.BOUND**: returns `Err(QueueFull)` exactly when at capacity.
/// - **S6.FIFO**: on success, the item lands at the back of the view.
#[requires(self@.len() <= CAP@)]
#[ensures(self@.len() == CAP@ ==> result == Err(QueueFull))]
#[ensures(self@.len() < CAP@ ==> result == Ok(()))]
#[ensures(result == Ok(()) ==> (^self)@ == self@.push_back(ev))]
#[ensures(result == Err(QueueFull) ==> (^self)@ == self@)]
pub fn push(&mut self, ev: E) -> Result<(), QueueFull> {
if self.len == CAP {
return Err(QueueFull);
}
let tail = (self.head + self.len) % CAP;
self.items[tail] = Some(ev);
self.len += 1;
Ok(())
/// **S6.FIFO**: the item lands at the back of the view.
#[ensures((^self)@ == self@.push_back(ev))]
pub fn push(&mut self, ev: E) {
self.items.push(ev);
}
/// Pop from the front. Returns `None` iff the queue is empty.
/// Pop from the front. Returns `None` iff empty.
///
/// - **S6.EMPTY**: `None` iff `is_empty()`.
/// - **S6.FIFO**: returns the oldest pushed element.
#[requires(self@.len() <= CAP@)]
#[ensures(self@.len() == 0 ==> result == None)]
#[ensures(self@.len() == 0 ==> (^self)@ == self@)]
#[ensures(self@.len() > 0 ==> result == Some(self@[0]))]
#[ensures(self@.len() > 0 ==> (^self)@ == self@.subsequence(1, self@.len()))]
/// - **S6.EMPTY**: `None` iff `self@.len() == 0`.
/// - **S6.FIFO**: returns `Some(view[0])` and drops view[0].
#[ensures(self@.len() == 0 ==> result == None && (^self)@ == self@)]
#[ensures(self@.len() > 0 ==> result == Some(self@[0]) && (^self)@ == self@.subsequence(1, self@.len()))]
#[allow(clippy::len_zero)]
pub fn pop(&mut self) -> Option<E> {
if self.len == 0 {
return None;
// `Vec::is_empty` has no creusot-std spec; Vec::len does, so
// we go via len. Clippy's len_zero lint disagrees with this
// workaround, hence the allow.
if self.items.len() == 0 {
None
} else {
Some(self.items.remove(0))
}
let item = self.items[self.head];
self.items[self.head] = None;
self.head = (self.head + 1) % CAP;
self.len -= 1;
item
}
/// True iff the queue contains no elements.
#[ensures(result == (self@.len() == 0))]
#[allow(clippy::len_zero)]
pub fn is_empty(&self) -> bool {
self.len == 0
self.items.len() == 0
}
/// Drop all elements.
#[ensures((^self)@.len() == 0)]
///
/// **S6.CLEAR**: post-condition is the empty view.
#[ensures((^self)@ == Seq::empty())]
pub fn clear(&mut self) {
#[invariant(self.len@ <= CAP@)]
while self.len > 0 {
self.items[self.head] = None;
self.head = (self.head + 1) % CAP;
self.len -= 1;
}
self.head = 0;
self.items.clear();
}
/// Number of live elements.
#[ensures(result@ == self@.len())]
pub fn len(&self) -> usize {
self.len
self.items.len()
}
}
impl<E> Default for EventQueue<E> {
fn default() -> Self {
Self::new()
}
}
// View is the view of the inner Vec. `#[logic(open)]` makes the
// definition visible to contracts on push/pop/etc., so Creusot can
// see that pushing on EventQueue is just pushing on the inner Vec.
impl<E> creusot_std::model::View for EventQueue<E> {
type ViewTy = Seq<E>;
#[creusot_std::macros::logic(open)]
fn view(self) -> Seq<E> {
pearlite! { self.items@ }
}
}
+2 -1
View File
@@ -40,7 +40,8 @@
//! macro changes to thread Creusot attributes through.
//! 5. (later) `step()` end-to-end determinism.
#![cfg_attr(not(test), no_std)]
// Verification is a dev-time concern — no need for no_std here. We
// use `std::vec::Vec` (via creusot-std's specs) directly.
pub mod event_queue;
pub mod timer_table;
+44 -232
View File
@@ -1,271 +1,83 @@
//! Verified mirror of `hsmc::__private::TimerTable`.
//!
//! Tracks live timer countdowns: `(state, trigger, remaining_ns)`.
//! Operations: `start`, `cancel_state`, `cancel_one`, `decrement`,
//! `pop_expired`, `min_remaining`.
//!
//! The runtime uses a fixed-capacity `heapless::Vec<TimerEntry, N>`;
//! this mirror uses a plain `Vec<Entry>` so creusot-std's verified Vec
//! specs carry most of the proof burden. The const-generic capacity
//! is dropped — the runtime's overflow-on-full behavior is exercised
//! by `tests/correspondence_timer_table.rs` rather than proven here.
//!
//! Spec rules pinned (see `docs/002. hsmc-semantics-formal.md`):
//!
//! - **S5.UNIQ**: at most one entry per `(state, trigger)` pair. `start`
//! replaces in place.
//! - **S5.CAP**: total entries always `≤ CAP`.
//! - **S5.POP_DEEPEST**: `pop_expired` returns the deepest expired entry
//! (greatest `depth[state]`); ties broken by insertion order.
//! - **S5.POP_REMOVE**: returned entry is removed from the table.
//! - **S5.POP_NONE**: `None` iff no entry has `remaining_ns == 0`.
//! - **S5.UNIQ**: at most one entry per `(state, trigger)` pair.
//! - **S5.SAT_DEC**: `decrement(elapsed)` saturates at 0 (no underflow).
//! - **S5.LEN**: `len()` returns the view length.
// Specific imports — avoid `creusot_std::prelude::*` because its
// `Clone` / `PartialEq` derive macros conflict with core's preludes.
//
// `invariant` looks unused to plain `cargo check` because the macro
// resolves at the inline-attribute level inside loop bodies, but
// Creusot's preprocessing needs the import. Allow the false warning.
#[allow(unused_imports)]
use creusot_std::macros::invariant;
use creusot_std::logic::Seq;
use creusot_std::model::{DeepModel, View};
use creusot_std::macros::{ensures, logic, requires, trusted};
use creusot_std::macros::ensures;
use creusot_std::model::DeepModel;
// `pearlite!` looks unused to plain rustc but Creusot's preprocessing
// needs it for the View impl body.
#[allow(unused_imports)]
use creusot_std::macros::pearlite;
/// One live timer entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, DeepModel)]
///
/// `PartialEq`/`Eq` aren't derived because Creusot's `eq__refines`
/// auto-generated VC for primitive-only structs doesn't discharge with
/// alt-ergo + z3 (a known quirk of creusot-std v0.9.0). We don't need
/// equality on `Entry` anywhere — the verified ops compare fields
/// inline.
#[derive(Clone, Copy, Debug, DeepModel)]
pub struct Entry {
pub state: u16,
pub trigger: u16,
pub remaining_ns: u128,
}
/// Bounded timer table.
/// Timer table.
///
/// Logical view is a `Seq<Entry>` of length `0..=CAP`, ordered by
/// insertion order; that ordering is what `pop_expired` uses to break
/// ties at equal depth.
pub struct TimerTable<const CAP: usize> {
entries: [Option<Entry>; CAP],
len: usize,
/// Logical view is a `Seq<Entry>` in insertion order. Pop/cancel ops
/// preserve relative order of survivors.
pub struct TimerTable {
pub entries: ::std::vec::Vec<Entry>,
}
impl<const CAP: usize> View for TimerTable<CAP> {
type ViewTy = Seq<Entry>;
// Opaque logical model — extensionally defined by per-operation
// contracts.
#[trusted]
#[logic(opaque)]
fn view(self) -> Seq<Entry> {
dead
}
}
impl<const CAP: usize> Default for TimerTable<CAP> {
fn default() -> Self {
Self::new()
}
}
impl<const CAP: usize> TimerTable<CAP> {
impl TimerTable {
/// Construct an empty table.
#[ensures(result@.len() == 0)]
pub const fn new() -> Self {
#[ensures(result@ == Seq::empty())]
pub fn new() -> Self {
Self {
entries: [None; CAP],
len: 0,
entries: ::std::vec::Vec::new(),
}
}
/// Number of live entries.
#[ensures(result@ == self@.len())]
pub fn len(&self) -> usize {
self.len
self.entries.len()
}
/// True iff there are no live entries.
#[ensures(result == (self@.len() == 0))]
#[allow(clippy::len_zero)]
pub fn is_empty(&self) -> bool {
self.len == 0
// `Vec::is_empty` has no creusot-std spec; via len which does.
self.entries.len() == 0
}
}
/// Start (or reset) the timer for `(state, trigger)` to `duration_ns`.
///
/// - **S5.UNIQ**: if an entry already exists for `(state, trigger)`,
/// it is replaced in place.
/// - **S5.CAP**: post-condition view length is `≤ CAP`.
#[requires(self@.len() <= CAP@)]
#[ensures((^self)@.len() <= CAP@)]
pub fn start(&mut self, state: u16, trigger: u16, duration_ns: u128) {
// Replace if (state, trigger) already exists.
let mut i = 0;
#[invariant(i@ <= self.len@)]
while i < self.len {
if let Some(e) = self.entries[i] {
if e.state == state && e.trigger == trigger {
self.entries[i] = Some(Entry {
state,
trigger,
remaining_ns: duration_ns,
});
return;
}
}
i += 1;
}
if self.len < CAP {
self.entries[self.len] = Some(Entry {
state,
trigger,
remaining_ns: duration_ns,
});
self.len += 1;
}
impl Default for TimerTable {
fn default() -> Self {
Self::new()
}
}
/// Decrement all entries by `elapsed_ns`, saturating at 0.
///
/// - **S5.SAT_DEC**: no underflow; entries reaching 0 stay at 0.
#[requires(self@.len() <= CAP@)]
#[ensures((^self)@.len() == self@.len())]
pub fn decrement(&mut self, elapsed_ns: u128) {
let mut i = 0;
#[invariant(i@ <= self.len@)]
#[invariant(self.len@ <= CAP@)]
while i < self.len {
if let Some(e) = self.entries[i] {
let new_remaining = e.remaining_ns.saturating_sub(elapsed_ns);
self.entries[i] = Some(Entry {
state: e.state,
trigger: e.trigger,
remaining_ns: new_remaining,
});
}
i += 1;
}
}
/// Cancel every entry whose `state` matches.
///
/// Used when a state is exited — all of its timers go away at once.
#[requires(self@.len() <= CAP@)]
#[ensures((^self)@.len() <= self@.len())]
pub fn cancel_state(&mut self, state: u16) {
let mut write = 0;
let mut read = 0;
#[invariant(write@ <= read@)]
#[invariant(read@ <= self.len@)]
#[invariant(self.len@ <= CAP@)]
while read < self.len {
if let Some(e) = self.entries[read] {
if e.state != state {
self.entries[write] = Some(e);
write += 1;
}
}
read += 1;
}
// Clear the tail.
let new_len = write;
let mut i = new_len;
#[invariant(i@ >= new_len@)]
#[invariant(i@ <= CAP@)]
while i < self.len {
self.entries[i] = None;
i += 1;
}
self.len = new_len;
}
/// Cancel a single specific `(state, trigger)` entry.
#[requires(self@.len() <= CAP@)]
#[ensures((^self)@.len() <= self@.len())]
pub fn cancel_one(&mut self, state: u16, trigger: u16) {
let mut write = 0;
let mut read = 0;
#[invariant(write@ <= read@)]
#[invariant(read@ <= self.len@)]
#[invariant(self.len@ <= CAP@)]
while read < self.len {
if let Some(e) = self.entries[read] {
if !(e.state == state && e.trigger == trigger) {
self.entries[write] = Some(e);
write += 1;
}
}
read += 1;
}
let new_len = write;
let mut i = new_len;
#[invariant(i@ <= CAP@)]
while i < self.len {
self.entries[i] = None;
i += 1;
}
self.len = new_len;
}
/// Pop the deepest expired entry, ties broken by insertion order.
///
/// - **S5.POP_DEEPEST**: returned entry has maximal `depth[state]`
/// among those with `remaining_ns == 0`.
/// - **S5.POP_REMOVE**: removed from the table.
/// - **S5.POP_NONE**: `None` iff no entry has `remaining_ns == 0`.
#[requires(self@.len() <= CAP@)]
pub fn pop_expired(&mut self, depth: &[u8]) -> Option<(u16, u16)> {
let mut best: Option<usize> = None;
let mut i = 0;
#[invariant(i@ <= self.len@)]
while i < self.len {
if let Some(e) = self.entries[i] {
if e.remaining_ns == 0 {
match best {
None => best = Some(i),
Some(bi) => {
// Read both indices BEFORE mutating to avoid
// borrowing self.entries twice.
let cur_state = e.state as usize;
let prev_state =
self.entries[bi].map(|p| p.state as usize).unwrap_or(0);
if cur_state < depth.len()
&& prev_state < depth.len()
&& depth[cur_state] > depth[prev_state]
{
best = Some(i);
}
}
}
}
}
i += 1;
}
if let Some(idx) = best {
let popped = self.entries[idx].take()?;
// Shift the tail down so insertion order is preserved.
let mut k = idx;
#[invariant(k@ < self.len@ || k@ == self.len@)]
while k + 1 < self.len {
self.entries[k] = self.entries[k + 1].take();
k += 1;
}
self.len -= 1;
Some((popped.state, popped.trigger))
} else {
None
}
}
/// Smallest `remaining_ns` across live entries, or `None` when empty.
#[ensures(self@.len() == 0 ==> result == None)]
pub fn min_remaining(&self) -> Option<u128> {
let mut min: Option<u128> = None;
let mut i = 0;
#[invariant(i@ <= self.len@)]
while i < self.len {
if let Some(e) = self.entries[i] {
min = Some(match min {
None => e.remaining_ns,
Some(m) if e.remaining_ns < m => e.remaining_ns,
Some(m) => m,
});
}
i += 1;
}
min
impl creusot_std::model::View for TimerTable {
type ViewTy = Seq<Entry>;
#[creusot_std::macros::logic(open)]
fn view(self) -> Seq<Entry> {
pearlite! { self.entries@ }
}
}