clock_dbm/ops/relations.rs
1//! Comparing zones and querying clock constraints.
2//!
3//! [`Dbm::entails`](crate::Dbm::entails) checks whether **every** valuation
4//! satisfies a constraint, whereas
5//! [`Dbm::intersects_constraint`](crate::Dbm::intersects_constraint) asks
6//! whether **some** valuation satisfies it. The former is true on an empty
7//! zone (vacuously), and the latter is false.
8//!
9//! [`Dbm::is_subset_of`](crate::Dbm::is_subset_of) tests inclusion of zones;
10//! [`Dbm::try_intersect`](crate::Dbm::try_intersect) constructs their
11//! intersection; and [`Dbm::difference_bound`](crate::Dbm::difference_bound)
12//! returns a tight bound on a clock difference.
13
14// Source-level implementation and proof notes (not part of public API Rustdoc).
15// Relations and queries: intersection, inclusion and constraint queries.
16//
17// Notation: `d` is the matrix dimension including reference clock zero;
18// `γ(D)` is the set of nonnegative-real valuations represented by `D`,
19// `⟦g⟧` is the set satisfying guard `g`, and `∅_d` is the empty
20// zone of dimension `d`. `Le c` means `<= c`, `Lt c` means `< c`;
21// `a ≼ b` means `a` is at least as tight as `b`, and `a ≺ b` means
22// strictly tighter.
23//
24// Throughout, `D` and `E` are public DBMs, so each is `∅_d` or canonical
25// and nonempty (the public invariant), and `g = (i, j, b)` is the
26// constraint `xᵢ − xⱼ ⋈ b`. Every method validates its arguments first
27// (dimension, then clock indices), also on empty zones, and only then looks
28// at emptiness. An argument error is never reported as `false`, and no query
29// returns `Err(Range)`.
30//
31// # Queries: closed forms on canonical matrices
32//
33// | Method | `∅_d` | Canonical nonempty `D` | Cost |
34// |---|---|---|---|
35// | `is_subset_of(D, E)` | `true` | `E = ∅_d`: `false`; else `∀ i,j. D[i][j] ≼ E[i][j]` | `O(d²)` |
36// | `entails(D, g)` | `true` | `D[i][j] ≼ b` | `O(1)` |
37// | `intersects_constraint(D, g)` | `false` | `¬(b + D[j][i] ≺ Le 0)` | `O(1)` |
38// | `difference_bound(D, i, j)` | `None` | `Some(D[i][j])` (`∞` if unbounded) | `O(1)` |
39//
40// None of them closes, copies or allocates.
41//
42// - **Inclusion**: for a canonical, nonempty `D`, `γ(D) ⊆ γ(E)`
43// iff `D ≤ E` entrywise. Only `D` needs to be
44// canonical; `E` is canonical anyway. The scan is `Dbm::entries_le`.
45// - **Entailment and `difference_bound`**: each entry of a canonical,
46// nonempty DBM is the tightest bound of its difference over the zone
47// (by tightness of canonical entries). So `γ(D) ⊆ ⟦g⟧` iff `D[i][j] ≼ b`.
48// - **Constraint intersection**: `D ∧ g` is empty iff its closure finds a
49// negative cycle. In a canonical `D`, the only new cycle is `i → j → i`
50// through the new edge, so the test is the
51// contradiction test of constraint insertion, `ops::constraints::
52// below_le_zero`. The sum is compared exactly and never
53// stored, so an unrepresentable sum is not an error.
54//
55// # Intersection: pointwise minimum, then closure over the touched clocks
56//
57// `try_intersect` moves `self`'s storage into a working matrix `W` and
58// takes the entrywise minimum with `other`:
59//
60// 1. **Minimum** (`Matrix::meet`): every entry that `E` strictly tightens
61// marks both of its clocks as touched. If a tightened entry contradicts
62// the current opposite entry (`W[i][j] + W[j][i] ≺ Le 0`, the exact test
63// `below_le_zero`), the result is `∅_d` at once: a negative 2-cycle.
64// 2. **Closure over the touched clocks** (`Matrix::close_pivots`):
65// Floyd–Warshall with only the touched clocks as pivots, each row relaxed
66// by the proved, vectorized `Matrix::relax_row`. A negative diagonal
67// gives `∅_d`.
68//
69// *Why the restricted closure is the closure.* Call an entry of `W`
70// *changed* if `E` tightened it; its endpoints are touched. Take any walk
71// in `W`. A run of consecutive unchanged edges has weight at least the
72// entry of the canonical `D` between its ends, which is at least `W`'s
73// entry there; so it can be replaced by that single edge without
74// increasing the weight. After this, no two consecutive edges are
75// unchanged, so every intermediate vertex is an endpoint of a changed edge,
76// i.e. touched. Floyd–Warshall over any pivot set computes the shortest
77// walks whose intermediate vertices are pivots, so it yields the closure.
78// A negative cycle of `W` contains a changed edge (cycles of `D` are
79// nonnegative), so it reduces the same way to a negative cycle through
80// touched pivots, and a diagonal entry becomes negative. The minimum of two
81// canonical matrices is **not** canonical in general, so some closure is
82// required; with nothing touched, `W = D` already is canonical.
83//
84// *As proved, without walks:*
85// - `proof::min_closed`: `W` already satisfies the triangle inequality
86// through every untouched clock;
87// - `proof::pivot_keep`: a full pivot step keeps every triangle that
88// holds and adds its own.
89//
90// So `Matrix::close_pivots` ends with the triangle inequality through every
91// clock, i.e. canonical. Each relaxation preserves the zone, so a negative
92// diagonal means emptiness. By `canonical_unique`, the result equals the
93// full closure.
94//
95// Cost: `O(d²)` for the minimum plus `O(p·d²)` for `p` touched clocks (a
96// guard-like `E` touches few clocks). The storage is reused, and the
97// touched flags live in the `Workspace`: no allocation once the workspace
98// has grown. An empty operand short-circuits after the dimension check.
99//
100// # Equality and hashing
101//
102// `PartialEq`/`Eq`/`Hash` on `Dbm` are those of `dbm.rs`: structural on
103// the canonical storage, which is semantic equality.
104//
105// - **Machine-checked:** `Dbm::eq_semantic` proves that `==` holds
106// iff the two DBMs have the same number of variables and denote the same
107// zone. Different dimensions are unequal, also for empty zones.
108// - **By construction, not machine-checked:** `Hash` is derived over the
109// same fields that `==` compares, so equal DBMs hash alike.
110// - **Outside the verified subset:** `std::hash::Hasher` has no Creusot
111// specification. No hashing abstraction or trusted specification is
112// added for it.
113//
114// # Verification status
115//
116// Every method of this module is machine-checked with Creusot v0.14.0 on
117// the shipped code, with termination. The same holds for the kernels
118// `Dbm::entries_le`, `Matrix::meet` and `Matrix::close_pivots`, and for
119// `Workspace::reset_touched`. The contracts are stated over nonnegative real
120// valuations (`Dbm::zone`):
121//
122// - `is_subset_of`: `γ(self) ⊆ γ(other)`;
123// - `entails` / `intersects_constraint`: universal and existential
124// satisfaction of the constraint;
125// - `difference_bound`: the canonical entry, the tightest bound (`∞`
126// included), and `None` exactly on `∅_d`;
127// - `try_intersect`: `γ(self) ∩ γ(other)`, with `∅_d` exactly when it is
128// empty, through negative cycles of any length;
129// - errors: the exact argument errors (checked before emptiness), and
130// `Range` only with its provenance (`proof::mrange_failure`).
131//
132// The lemmas are in `relations/proof.rs` (`entry_tight`,
133// `subset_pointwise`, `meets`) and `dbm/proof.rs` (`min_closed`,
134// `pivot_keep`, `relax_row_full`). They rest on `tight`, the `edge` lemmas
135// and `canonical_unique`. See `verification/PROOF_STATUS.md`. The
136// exact-oracle tests in `relations/tests.rs` remain as regression tests.
137
138// `?` is not a terminating call for Creusot; keep the style of `dbm.rs`.
139#![allow(clippy::question_mark)]
140
141use crate::bounds::{Bound, Clock, Constraint};
142#[cfg(creusot)]
143use crate::bounds::{order_refines, sat};
144#[cfg(creusot)]
145use crate::dbm::Matrix;
146use crate::dbm::{Dbm, Workspace, tighter};
147use crate::error::Error;
148use crate::ops::constraints::below_le_zero;
149#[cfg(creusot)]
150use crate::ops::constraints::clock_error;
151#[cfg(creusot)]
152use crate::ops::constraints::proof::{csat, valid};
153use creusot_std::prelude::*;
154
155impl Dbm {
156 /// Returns the zone of valuations that belong to **both** input zones.
157 ///
158 /// The inputs must have the same number of actual clocks. An empty
159 /// intersection is a successful **empty zone**, not an error.
160 /// On success the result is canonical or empty, and no partial update
161 /// becomes visible.
162 ///
163 /// When either input is empty, the result is empty. The `ws`
164 /// parameter does not affect the result.
165 ///
166 /// # Errors
167 ///
168 /// - [`Error::DimensionMismatch`] if `other` has a different clock
169 /// count, even if either zone is empty;
170 /// - [`Error::Range`] if closure needs a finite bound beyond the
171 /// supported integer range. This is not an empty-zone result.
172 ///
173 /// # Complexity
174 ///
175 /// `O(d³)` time in the worst case for matrix dimension
176 /// `d = self.dimension()`. An empty operand returns immediately.
177 /// The workspace reuses scratch storage across calls.
178 #[check(terminates)]
179 #[ensures(match result {
180 Ok(r) => other.variables_logic() == self.variables_logic()
181 && r.variables_logic() == self.variables_logic()
182 && forall<u: crate::dbm::proof::Val> r.zone(u) == (self.zone(u) && other.zone(u)),
183 Err(e) => if other.variables_logic() != self.variables_logic() {
184 match e {
185 Error::DimensionMismatch { expected, found } =>
186 expected@ == self.variables_logic() && found@ == other.variables_logic(),
187 _ => false,
188 }
189 } else {
190 e == Error::Range && !self.is_empty_logic() && !other.is_empty_logic()
191 && crate::dbm::proof::mrange_failure(
192 crate::dbm::proof::bmin_mat(self.mmat(), other.mmat()),
193 self.variables_logic() + 1)
194 },
195 })]
196 // Exactness: when `self` is entrywise at most `other`, the meet
197 // tightens nothing, no pivot is closed and the result is not `Err`.
198 #[ensures(other.variables_logic() == self.variables_logic()
199 && !self.is_empty_logic() && !other.is_empty_logic()
200 && (forall<i: Int, j: Int>
201 0 <= i && i <= self.variables_logic() && 0 <= j && j <= self.variables_logic() ==>
202 self.at(i, j).deep_model() <= other.at(i, j).deep_model())
203 ==> match result { Ok(_) => true, Err(_) => false })]
204 pub fn try_intersect(self, other: &Dbm, ws: &mut Workspace) -> Result<Dbm, Error> {
205 match self.check_variables(other.variables()) {
206 Ok(()) => {}
207 Err(e) => return Err(e),
208 }
209 snapshot!(self.model());
210 snapshot!(other.model());
211 let min = snapshot!(crate::dbm::proof::bmin_mat(self.mmat(), other.mmat()));
212 let empty = self.empty_like();
213 if other.is_empty() {
214 return Ok(empty);
215 }
216 let mut m = match self.into_matrix() {
217 Some(m) => m,
218 None => return Ok(empty),
219 };
220 let w0 = snapshot!(m);
221 snapshot!(w0.model());
222 ws.reset_touched(m.dimension());
223 if !m.meet(other, &mut ws.touched) {
224 return Ok(empty);
225 }
226 snapshot!(Matrix::meet_ready(*w0, *other, m, ws.touched@));
227 let w1 = snapshot!(m);
228 let r = m.close_pivots(&ws.touched);
229 proof_assert!(match r {
230 Err(_) => {
231 w1.range_failure_model();
232 crate::dbm::proof::mrange_failure_meq(w1.mmat(), *min, w1.dim_logic());
233 true
234 }
235 Ok(_) => true,
236 });
237 r
238 }
239}
240
241impl Dbm {
242 /// Tests whether **every valuation of this zone** also belongs to
243 /// `other`.
244 ///
245 /// An empty zone is a subset of every zone of the same clock count;
246 /// a nonempty zone is not a subset of an empty zone.
247 ///
248 /// # Errors
249 ///
250 /// [`Error::DimensionMismatch`] if the two zones have different
251 /// numbers of actual clocks, even when either zone is empty.
252 ///
253 /// # Complexity
254 ///
255 /// `O(d²)` time in the worst case for matrix dimension
256 /// `d = self.dimension()`; empty-zone cases take `O(1)`.
257 #[check(terminates)]
258 #[ensures(match result {
259 Ok(b) => other.variables_logic() == self.variables_logic()
260 && b == forall<u: crate::dbm::proof::Val> self.zone(u) ==> other.zone(u),
261 Err(e) => other.variables_logic() != self.variables_logic() && match e {
262 Error::DimensionMismatch { expected, found } =>
263 expected@ == self.variables_logic() && found@ == other.variables_logic(),
264 _ => false,
265 },
266 })]
267 pub fn is_subset_of(&self, other: &Dbm) -> Result<bool, Error> {
268 match self.check_variables(other.variables()) {
269 Ok(()) => {}
270 Err(e) => return Err(e),
271 }
272 snapshot!(self.model());
273 snapshot!(other.model());
274 if self.is_empty() {
275 Ok(true)
276 } else if other.is_empty() {
277 Ok(false)
278 } else {
279 let d = snapshot!(self.variables_logic() + 1);
280 proof_assert!(forall<i: Int, j: Int> 0 <= i && i < *d && 0 <= j && j < *d ==> {
281 order_refines(self.at(i, j), other.at(i, j));
282 (self.at(i, j).deep_model() <= other.at(i, j).deep_model())
283 == self.mmat()[i][j].le(other.mmat()[i][j])
284 });
285 snapshot!(proof::subset_pointwise(self.mmat(), other.mmat(), *d));
286 Ok(self.entries_le(other))
287 }
288 }
289
290 /// Returns whether **every** valuation in this zone satisfies `c`.
291 ///
292 /// The result is `true` precisely when all nonnegative-real clock
293 /// valuations allowed by this zone satisfy `c`. This is different
294 /// from asking whether **some** valuation satisfies it; for that,
295 /// use [`Dbm::intersects_constraint`]. An empty zone entails every
296 /// well-formed constraint (vacuously).
297 ///
298 /// # Example
299 ///
300 /// ```
301 /// use clock_dbm::{Clock, Constraint, Dbm};
302 /// # fn main() -> Result<(), clock_dbm::Error> {
303 /// let x = Clock::new(1).unwrap();
304 /// let z = Dbm::universe(1)?
305 /// .try_constrain(Constraint::le(x, Clock::ZERO, 10)?)?;
306 /// let x_below_five = Constraint::lt(x, Clock::ZERO, 5)?;
307 /// assert!(!z.entails(&x_below_five)?);
308 /// assert!(z.intersects_constraint(&x_below_five)?);
309 /// assert!(z.entails(&Constraint::le(x, Clock::ZERO, 10)?)?);
310 /// # Ok(())
311 /// # }
312 /// ```
313 ///
314 /// # Errors
315 ///
316 /// [`Error::ClockOutOfRange`] if a clock of `c` is not a clock of this
317 /// DBM, also when the DBM is empty.
318 ///
319 /// # Complexity
320 ///
321 /// `O(1)` time; the query does not build a new zone.
322
323 #[check(terminates)]
324 #[ensures(match result {
325 Ok(b) => valid(*c, self.variables_logic())
326 && b == forall<u: crate::dbm::proof::Val> self.zone(u) ==> csat(*c, u),
327 Err(e) => !valid(*c, self.variables_logic()) && clock_error(*c, self.variables_logic(), e),
328 })]
329 pub fn entails(&self, c: &Constraint) -> Result<bool, Error> {
330 let (i, j) = match self.check_constraint(*c) {
331 Ok(ij) => ij,
332 Err(e) => return Err(e),
333 };
334 snapshot!(self.model());
335 if self.is_empty() {
336 return Ok(true);
337 }
338 let e = self.entry(i, j);
339 let b = c.bound();
340 snapshot!(order_refines(e, b));
341 snapshot!(proof::entry_tight(self.mmat(), self.variables_logic() + 1, i@, j@, b@));
342 Ok(!tighter(b, e))
343 }
344
345 /// Tests whether **at least one valuation** in this zone satisfies
346 /// the difference constraint `c`.
347 ///
348 /// Equivalently, this asks whether restricting the zone by `c` would
349 /// produce a nonempty result. Unlike [`Dbm::entails`], which checks
350 /// **every** valuation, this returns `false` on an empty zone.
351 ///
352 /// # Errors
353 ///
354 /// [`Error::ClockOutOfRange`] if a clock in `c` is not among this
355 /// zone's clocks, even when the zone is empty.
356 ///
357 /// # Complexity
358 ///
359 /// `O(1)` time; the query does not build a new zone.
360 #[check(terminates)]
361 #[ensures(match result {
362 Ok(b) => valid(*c, self.variables_logic())
363 && b == exists<u: crate::dbm::proof::Val> self.zone(u) && csat(*c, u),
364 Err(e) => !valid(*c, self.variables_logic()) && clock_error(*c, self.variables_logic(), e),
365 })]
366 pub fn intersects_constraint(&self, c: &Constraint) -> Result<bool, Error> {
367 let (i, j) = match self.check_constraint(*c) {
368 Ok(ij) => ij,
369 Err(e) => return Err(e),
370 };
371 snapshot!(self.model());
372 if self.is_empty() {
373 return Ok(false);
374 }
375 snapshot!(proof::meets(self.mmat(), self.variables_logic() + 1, i@, j@, c@.2));
376 Ok(!below_le_zero(c.bound(), self.entry(j, i)))
377 }
378
379 /// Returns the tightest bound on `clock i - clock j` that holds for
380 /// **every valuation** of this zone.
381 ///
382 /// On a nonempty canonical zone this returns the corresponding
383 /// stored difference bound. [`Bound::INFINITY`] means that the
384 /// difference has no finite upper bound. For an empty zone, this
385 /// returns `None`, since every bound is vacuously satisfied.
386 ///
387 /// # Errors
388 ///
389 /// [`Error::ClockOutOfRange`] if `i` or `j` is outside this
390 /// zone's clock range (checking `i` first), even for an empty zone.
391 ///
392 /// # Complexity
393 ///
394 /// `O(1)` time.
395 #[check(terminates)]
396 #[ensures(match result {
397 Ok(None) => i@ <= self.variables_logic() && j@ <= self.variables_logic()
398 && self.is_empty_logic(),
399 Ok(Some(b)) => i@ <= self.variables_logic() && j@ <= self.variables_logic()
400 && !self.is_empty_logic() && b == self.at(i@, j@)
401 && forall<c: crate::bounds::BoundModel> b@.le(c) ==
402 forall<u: crate::dbm::proof::Val> self.zone(u) ==> sat(c, u[i@] - u[j@]),
403 Err(e) => match e {
404 Error::ClockOutOfRange { clock, variables } =>
405 variables@ == self.variables_logic()
406 && if i@ > self.variables_logic() { clock@ == i@ }
407 else { j@ > self.variables_logic() && clock@ == j@ },
408 _ => false,
409 },
410 })]
411 pub fn difference_bound(&self, i: Clock, j: Clock) -> Result<Option<Bound>, Error> {
412 let i = match self.check_clock(i) {
413 Ok(i) => i,
414 Err(e) => return Err(e),
415 };
416 let j = match self.check_clock(j) {
417 Ok(j) => j,
418 Err(e) => return Err(e),
419 };
420 snapshot!(self.model());
421 if self.is_empty() {
422 return Ok(None);
423 }
424 let b = self.entry(i, j);
425 proof_assert!(forall<c: crate::bounds::BoundModel> {
426 proof::entry_tight(self.mmat(), self.variables_logic() + 1, i@, j@, c);
427 true
428 });
429 Ok(Some(b))
430 }
431}
432
433#[cfg(creusot)]
434pub(crate) mod proof;
435
436#[cfg(test)]
437mod tests;