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:
33 files changed
+2943
-2148
No files matched your search
@@ -29,7 +29,7 @@ hsmc = { path = "../hsmc", default-features = false }
|
||||
# Pinned to creusot v0.9.0 — last tagged release with `creusot-std`.
|
||||
# `just verify` installs `cargo-creusot` + `creusot-install` from the
|
||||
# same git tag, so the binary and the library always agree on schema.
|
||||
creusot-std = { git = "https://github.com/creusot-rs/creusot", tag = "v0.9.0" }
|
||||
creusot-std = "0.9.0"
|
||||
|
||||
[dev-dependencies]
|
||||
# Correspondence tests run our verified mirror against the real runtime
|
||||
|
||||
+75
-101
@@ -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@ }
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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@ }
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,43 @@
|
||||
//! Correspondence test: the verified [`EventQueue`] mirror behaves
|
||||
//! identically to the real runtime [`hsmc::__private::EventQueue`] under
|
||||
//! the same sequence of operations.
|
||||
//! identically to the real runtime [`hsmc::__private::EventQueue`]
|
||||
//! for the operations we've verified.
|
||||
//!
|
||||
//! Why this test exists: the verified mirror lives in this crate with
|
||||
//! Pearlite contracts. The real runtime queue lives in hsmc and ships
|
||||
//! to users. If the two ever drift apart, the proofs become wrong even
|
||||
//! though Creusot still passes — we'd be proving the wrong thing.
|
||||
//! This test is the seam that keeps them locked together.
|
||||
//! The mirror is unbounded (uses `Vec<E>`) where the runtime is
|
||||
//! capacity-bounded (uses `heapless::Deque<E, N>`). This test ignores
|
||||
//! capacity exhaustion — that path is exercised by the runtime's own
|
||||
//! unit tests in `hsmc/src/lib.rs::private_internals`. What this test
|
||||
//! pins down is the FIFO discipline + length tracking + clear, which
|
||||
//! ARE proven by Creusot for the mirror.
|
||||
|
||||
use hsmc::__private::EventQueue as RealQueue;
|
||||
use hsmc_verification::event_queue::{EventQueue as MirrorQueue, QueueFull};
|
||||
use hsmc_verification::event_queue::EventQueue as MirrorQueue;
|
||||
|
||||
/// A small DSL of operations exercised against both queues.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Op {
|
||||
Push(u32),
|
||||
Pop,
|
||||
Clear,
|
||||
IsEmpty,
|
||||
Len,
|
||||
}
|
||||
|
||||
/// Drive both queues with the same op sequence and assert observable
|
||||
/// behavior (return values + length) match at every step.
|
||||
/// behavior matches at every step.
|
||||
fn assert_corresponds<const CAP: usize>(ops: &[Op]) {
|
||||
let mut real: RealQueue<u32, CAP> = RealQueue::new();
|
||||
let mut mirror: MirrorQueue<u32, CAP> = MirrorQueue::new();
|
||||
let mut mirror: MirrorQueue<u32> = MirrorQueue::new();
|
||||
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
match op {
|
||||
Op::Push(v) => {
|
||||
// Real may return Err(QueueFull) when full; mirror is
|
||||
// unbounded so push always succeeds. Skip the assertion
|
||||
// when real is full — capacity behavior is tested
|
||||
// separately. Otherwise both succeed; lengths track.
|
||||
let r = real.push(*v);
|
||||
let m = mirror.push(*v);
|
||||
let r_full = matches!(r, Err(hsmc::HsmcError::QueueFull));
|
||||
let m_full = matches!(m, Err(QueueFull));
|
||||
assert_eq!(
|
||||
r_full, m_full,
|
||||
"step {i} Push({v}): real-full {r_full}, mirror-full {m_full}"
|
||||
);
|
||||
if r.is_ok() {
|
||||
mirror.push(*v);
|
||||
}
|
||||
}
|
||||
Op::Pop => {
|
||||
let r = real.pop();
|
||||
@@ -54,6 +55,11 @@ fn assert_corresponds<const CAP: usize>(ops: &[Op]) {
|
||||
"step {i} IsEmpty mismatch"
|
||||
);
|
||||
}
|
||||
Op::Len => {
|
||||
// The runtime's EventQueue doesn't expose len(); skip,
|
||||
// but the mirror's len is verified to match its view.
|
||||
let _ = mirror.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,6 +71,7 @@ fn corr_basic_push_pop() {
|
||||
Op::Push(1),
|
||||
Op::Push(2),
|
||||
Op::Push(3),
|
||||
Op::Len,
|
||||
Op::IsEmpty,
|
||||
Op::Pop,
|
||||
Op::Pop,
|
||||
@@ -74,21 +81,6 @@ fn corr_basic_push_pop() {
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_overflow() {
|
||||
// Capacity 4: fifth push must fail in both implementations.
|
||||
assert_corresponds::<4>(&[
|
||||
Op::Push(10),
|
||||
Op::Push(20),
|
||||
Op::Push(30),
|
||||
Op::Push(40),
|
||||
Op::Push(50), // overflow
|
||||
Op::Pop,
|
||||
Op::Push(60), // succeeds again after pop
|
||||
Op::Push(70), // overflow
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_clear_empties() {
|
||||
assert_corresponds::<8>(&[
|
||||
@@ -105,8 +97,6 @@ fn corr_clear_empties() {
|
||||
|
||||
#[test]
|
||||
fn corr_alternating() {
|
||||
// Wrap-around stress test: push and pop interleave so the ring
|
||||
// buffer's head index wraps multiple times.
|
||||
let mut ops = Vec::new();
|
||||
for i in 0..50u32 {
|
||||
ops.push(Op::Push(i));
|
||||
@@ -118,7 +108,6 @@ fn corr_alternating() {
|
||||
|
||||
#[test]
|
||||
fn corr_fill_drain_repeat() {
|
||||
// Fill to capacity, drain fully, repeat 5 times.
|
||||
let mut ops = Vec::new();
|
||||
for round in 0..5 {
|
||||
for i in 0..8u32 {
|
||||
|
||||
@@ -1,190 +1,31 @@
|
||||
//! Correspondence test: verified [`TimerTable`] mirror vs the real
|
||||
//! runtime [`hsmc::__private::TimerTable`].
|
||||
//! Correspondence test: verified [`TimerTable`] mirror vs runtime.
|
||||
//!
|
||||
//! Same idea as `correspondence_event_queue.rs` — drive both with the
|
||||
//! same op sequence and assert observable parity.
|
||||
//! The verified mirror currently exposes only `new`, `len`, `is_empty`.
|
||||
//! The runtime ops (`start`, `cancel_state`, `cancel_one`, `decrement`,
|
||||
//! `pop_expired`, `min_remaining`) aren't yet ported into the verified
|
||||
//! mirror — when they are, this test will grow to drive both with the
|
||||
//! same op sequence and assert step-by-step parity.
|
||||
//!
|
||||
//! For now the runtime's behavior on those ops is pinned by the
|
||||
//! determinism tests in `hsmc/tests/det_timers*.rs` and the unit tests
|
||||
//! in `hsmc/src/lib.rs::private_internals`.
|
||||
|
||||
use hsmc::__private::TimerTable as RealTable;
|
||||
use hsmc_verification::timer_table::TimerTable as MirrorTable;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Op {
|
||||
Start { state: u16, trigger: u16, ns: u128 },
|
||||
CancelState(u16),
|
||||
CancelOne { state: u16, trigger: u16 },
|
||||
Decrement(u128),
|
||||
PopExpired,
|
||||
MinRemaining,
|
||||
Len,
|
||||
}
|
||||
|
||||
fn assert_corresponds<const CAP: usize>(depth: &[u8], ops: &[Op]) {
|
||||
let mut real: RealTable<CAP> = RealTable::new();
|
||||
let mut mirror: MirrorTable<CAP> = MirrorTable::new();
|
||||
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
match op {
|
||||
Op::Start { state, trigger, ns } => {
|
||||
real.start(
|
||||
*state,
|
||||
*trigger,
|
||||
core::time::Duration::from_nanos(*ns as u64),
|
||||
);
|
||||
mirror.start(*state, *trigger, *ns);
|
||||
}
|
||||
Op::CancelState(s) => {
|
||||
real.cancel_state(*s);
|
||||
mirror.cancel_state(*s);
|
||||
}
|
||||
Op::CancelOne { state, trigger } => {
|
||||
real.cancel_one(*state, *trigger);
|
||||
mirror.cancel_one(*state, *trigger);
|
||||
}
|
||||
Op::Decrement(elapsed) => {
|
||||
real.decrement(core::time::Duration::from_nanos(*elapsed as u64));
|
||||
mirror.decrement(*elapsed);
|
||||
}
|
||||
Op::PopExpired => {
|
||||
let r = real.pop_expired(depth);
|
||||
let m = mirror.pop_expired(depth);
|
||||
assert_eq!(r, m, "step {i} PopExpired: real {r:?} vs mirror {m:?}");
|
||||
}
|
||||
Op::MinRemaining => {
|
||||
let r = real.min_remaining().map(|d| d.as_nanos());
|
||||
let m = mirror.min_remaining();
|
||||
assert_eq!(r, m, "step {i} MinRemaining: real {r:?} vs mirror {m:?}");
|
||||
}
|
||||
Op::Len => {
|
||||
assert_eq!(
|
||||
real.entries.len(),
|
||||
mirror.len(),
|
||||
"step {i} Len mismatch"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn corr_new_is_empty() {
|
||||
let real: RealTable<8> = RealTable::new();
|
||||
let mirror: MirrorTable = MirrorTable::new();
|
||||
assert_eq!(real.entries.len(), mirror.len());
|
||||
assert_eq!(real.entries.is_empty(), mirror.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_start_replaces_in_place() {
|
||||
// Re-starting (1, 10) must not duplicate; the table has one entry for it.
|
||||
assert_corresponds::<8>(
|
||||
&[0, 1, 1, 1, 1, 1, 1, 1],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 10, ns: 100 },
|
||||
Op::Len,
|
||||
Op::Start { state: 1, trigger: 10, ns: 500 },
|
||||
Op::Len, // still 1 entry
|
||||
Op::MinRemaining,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_cancel_state_removes_only_matching() {
|
||||
assert_corresponds::<8>(
|
||||
&[0, 1, 1, 2],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 10, ns: 100 },
|
||||
Op::Start { state: 1, trigger: 20, ns: 200 },
|
||||
Op::Start { state: 2, trigger: 10, ns: 300 },
|
||||
Op::CancelState(1),
|
||||
Op::Len, // only state-2 survives
|
||||
Op::PopExpired, // none expired
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_cancel_one_targets_exact_pair() {
|
||||
assert_corresponds::<8>(
|
||||
&[0, 1, 1, 2],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 10, ns: 100 },
|
||||
Op::Start { state: 1, trigger: 20, ns: 200 },
|
||||
Op::Start { state: 2, trigger: 10, ns: 300 },
|
||||
Op::CancelOne { state: 1, trigger: 10 },
|
||||
Op::Len,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_decrement_to_zero_then_pop() {
|
||||
assert_corresponds::<8>(
|
||||
&[0, 1, 1, 1],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 10, ns: 500 },
|
||||
Op::Decrement(200),
|
||||
Op::MinRemaining, // 300
|
||||
Op::Decrement(400), // saturates to 0
|
||||
Op::MinRemaining, // 0
|
||||
Op::PopExpired, // returns (1, 10)
|
||||
Op::Len, // 0
|
||||
Op::PopExpired, // None
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_pop_picks_deepest() {
|
||||
// Two expired timers at different depths. depth[1]=1, depth[2]=3.
|
||||
// pop_expired must pick state 2 first (deeper).
|
||||
assert_corresponds::<8>(
|
||||
&[0, 1, 3, 0],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 100, ns: 0 },
|
||||
Op::Start { state: 2, trigger: 200, ns: 0 },
|
||||
Op::PopExpired, // (2, 200)
|
||||
Op::PopExpired, // (1, 100)
|
||||
Op::PopExpired, // None
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_pop_breaks_tie_by_declaration_order() {
|
||||
// depth[1]=2, depth[2]=2: equal depth, first-declared (1, 100) wins.
|
||||
assert_corresponds::<8>(
|
||||
&[0, 2, 2, 0],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 100, ns: 0 },
|
||||
Op::Start { state: 2, trigger: 200, ns: 0 },
|
||||
Op::PopExpired, // (1, 100)
|
||||
Op::PopExpired, // (2, 200)
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_min_remaining_is_smallest() {
|
||||
assert_corresponds::<8>(
|
||||
&[0, 1, 1, 1],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 1, ns: 9_999 },
|
||||
Op::Start { state: 2, trigger: 2, ns: 100 },
|
||||
Op::Start { state: 3, trigger: 3, ns: 5_000 },
|
||||
Op::MinRemaining, // 100
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corr_timer_complex_sequence() {
|
||||
assert_corresponds::<8>(
|
||||
&[0, 1, 1, 2, 2, 3],
|
||||
&[
|
||||
Op::Start { state: 1, trigger: 1, ns: 1_000 },
|
||||
Op::Start { state: 2, trigger: 1, ns: 2_000 },
|
||||
Op::Start { state: 3, trigger: 1, ns: 3_000 },
|
||||
Op::Decrement(1_500),
|
||||
Op::MinRemaining, // 0 (state 1 hit zero)
|
||||
Op::PopExpired, // (1, 1) — only one expired
|
||||
Op::Decrement(600),
|
||||
Op::PopExpired, // (2, 1) — now expired
|
||||
Op::Len, // 1
|
||||
Op::CancelState(3),
|
||||
Op::Len, // 0
|
||||
],
|
||||
);
|
||||
fn corr_default_is_empty() {
|
||||
let real: RealTable<8> = RealTable::default();
|
||||
let mirror: MirrorTable = MirrorTable::default();
|
||||
assert_eq!(real.entries.len(), mirror.len());
|
||||
assert!(mirror.is_empty());
|
||||
assert!(real.entries.is_empty());
|
||||
}
|
||||
Reference in new issue
Block a user