journal + determinism tests + Creusot verification scaffolding
Phase 1 — semantics doc
docs/002. hsmc-semantics-formal.md
Phase 2 — deterministic execution journal
hsmc/src/journal.rs (TraceEvent, JournalSink, ActionKind)
hsmc-macros: __chart_journal! emission at every observable site
(entry/exit/action/transition/timer arm-cancel-fire/during/emit/
event delivery/terminate). Per-state during count helpers, stable
chart-hash via FNV-1a. Action observation moved out of run_action
and into call sites so ActionKind is accurate.
Public API on the generated machine: journal(), take_journal(),
clear_journal(), CHART_HASH.
Phase 3 — verification crate (Creusot scaffolding)
verification/{Cargo.toml,mise.toml,requirements.txt,INVARIANTS.md}
verification/src/{event_queue.rs,timer_table.rs} — Pearlite
contracts on simplified mirrors of the runtime types. cargo
creusot generates Coma IR cleanly; VCs not yet discharged.
Correspondence tests drive the verified mirror and the runtime
type with the same op sequences and assert observable parity.
Tests — 113 deterministic-flow tests across 22 files. Each compares a
hand-built expected journal byte-for-byte against actual, anchored
to a spec section: initial entry, lateral/self/up transitions,
bubbling, timers, emit, ordering, durings, step/dispatch
equivalence, root-targeting, current_state, termination.
Tooling — mise.toml (root): stable Rust + cargo subcommands.
verification/mise.toml: pinned nightly-2025-11-13 + opam + python
venv + uv. just verify is fully self-installing.
Bug fix — root state targetable by the chart's own name (e.g.
`on(Trig) => ChartName;`) per spec §"How transitions work".
CHART_HASH — stable FNV-1a fingerprint over the chart's structural
definition; mismatch on replay = different chart.
This commit is contained in:
55 files changed
+6476
-151
No files matched your search
@@ -0,0 +1,138 @@
|
||||
//! 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`].
|
||||
//!
|
||||
//! Spec rules pinned (see `docs/002. hsmc-semantics-formal.md`):
|
||||
//!
|
||||
//! - `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.
|
||||
//!
|
||||
//! Correspondence with the real runtime type is enforced by
|
||||
//! `tests/correspondence.rs`.
|
||||
|
||||
// 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};
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
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> {
|
||||
/// Construct an empty queue.
|
||||
#[ensures(result@.len() == 0)]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
items: [None; CAP],
|
||||
head: 0,
|
||||
len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Push to the back. Fails iff the queue is full.
|
||||
///
|
||||
/// - **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(())
|
||||
}
|
||||
|
||||
/// Pop from the front. Returns `None` iff the queue is 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()))]
|
||||
pub fn pop(&mut self) -> Option<E> {
|
||||
if self.len == 0 {
|
||||
return None;
|
||||
}
|
||||
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))]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
/// Drop all elements.
|
||||
#[ensures((^self)@.len() == 0)]
|
||||
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;
|
||||
}
|
||||
|
||||
/// Number of live elements.
|
||||
#[ensures(result@ == self@.len())]
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Deductive proofs for the `hsmc` runtime data structures.
|
||||
//!
|
||||
//! This crate hosts Creusot/Pearlite contracts on simplified mirrors of
|
||||
//! `hsmc::__private::EventQueue` and `hsmc::__private::TimerTable`. The
|
||||
//! mirrors are byte-for-byte equivalent to the runtime types' observable
|
||||
//! behavior; the difference is that the mirrors carry full
|
||||
//! `#[requires] / #[ensures]` annotations, so a Creusot run discharges
|
||||
//! VCs (verification conditions) for them.
|
||||
//!
|
||||
//! ## Why mirror, not annotate hsmc directly?
|
||||
//!
|
||||
//! Two reasons:
|
||||
//!
|
||||
//! 1. **Cleanliness.** `hsmc` itself stays free of `creusot-contracts`
|
||||
//! — production users don't have to think about a verifier dep.
|
||||
//! 2. **Tractability.** The runtime types are layered on `heapless`
|
||||
//! types whose Pearlite models would have to be written first.
|
||||
//! A simplified mirror with `&mut [_; CAP]` storage avoids the
|
||||
//! indirection and makes the proofs readable.
|
||||
//!
|
||||
//! The correspondence is enforced by `tests/correspondence.rs`, which
|
||||
//! drives both the mirror AND the real `hsmc` runtime type with the same
|
||||
//! operation sequences and asserts equal observable results. If the
|
||||
//! mirror drifts away from the runtime, the correspondence test fails
|
||||
//! before the proofs become wrong.
|
||||
//!
|
||||
//! ## Status
|
||||
//!
|
||||
//! See `INVARIANTS.md` for the spec-rule → proof mapping. Initial focus
|
||||
//! (in priority order):
|
||||
//!
|
||||
//! 1. `EventQueue` — FIFO; bounded; pop-after-push returns the pushed
|
||||
//! value. (S6 in the semantics doc.)
|
||||
//! 2. `TimerTable::start` — at most one entry per `(state, trigger)`
|
||||
//! pair; capacity respected. (S5.1)
|
||||
//! 3. `TimerTable::pop_expired` — deepest expired entry first; ties
|
||||
//! broken by insertion index; entry removed; `None` iff none expired.
|
||||
//! (S5.2)
|
||||
//! 4. (later) `transition()` path validity — codegen-emitted; needs
|
||||
//! macro changes to thread Creusot attributes through.
|
||||
//! 5. (later) `step()` end-to-end determinism.
|
||||
|
||||
#![cfg_attr(not(test), no_std)]
|
||||
|
||||
pub mod event_queue;
|
||||
pub mod timer_table;
|
||||
@@ -0,0 +1,271 @@
|
||||
//! 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`.
|
||||
//!
|
||||
//! 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.SAT_DEC**: `decrement(elapsed)` saturates at 0 (no underflow).
|
||||
|
||||
// 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};
|
||||
|
||||
/// One live timer entry.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, DeepModel)]
|
||||
pub struct Entry {
|
||||
pub state: u16,
|
||||
pub trigger: u16,
|
||||
pub remaining_ns: u128,
|
||||
}
|
||||
|
||||
/// Bounded 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,
|
||||
}
|
||||
|
||||
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> {
|
||||
/// Construct an empty table.
|
||||
#[ensures(result@.len() == 0)]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
entries: [None; CAP],
|
||||
len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of live entries.
|
||||
#[ensures(result@ == self@.len())]
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
/// True iff there are no live entries.
|
||||
#[ensures(result == (self@.len() == 0))]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.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;
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user