Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2. Loop invariants, state machines and conservation laws as code contracts

School of Engineering, Nazarbayev University

Off-by-one bugs (< against <=, hi against hi - 1) are common even in short while loops. Edsger W. Dijkstra’s remedy was to treat a loop the way a physicist treats a control volume: write the conserved quantity (the loop invariant) and a decreasing quantity (the termination variant) before writing the loop body. This lecture applies Mental Move #6, Write the Loop Invariant Before the Loop, to Russian-peasant binary exponentiation, Dijkstra’s 3-way Dutch National Flag partition (representation_scaling.dutch_national_flag_partition), safety-interlocked Finite-State Machines (FSMs), and mass-conserving flux networks.

Learning objectives

  1. Prove loop correctness and termination simultaneously using a Loop Invariant I(s)I(s) (inductive conservation predicate) and an integer Lyapunov Variant V(s)∈NV(s) \in \mathbb{N} that strictly decreases each iteration.

  2. Partition noisy sensor arrays into 3 ordered quality bands in a single O(N)\mathcal{O}(N) pass with O(1)\mathcal{O}(1) extra memory via representation_scaling.dutch_national_flag_partition.

  3. Design deterministic Finite-State Machine (FSM) valve/protocol controllers and verify unreachable hazard states via exhaustive state-space breadth-first reachability.

  4. Enforce discrete physical conservation laws (mass, charge, probability) as runtime assert code contracts using antisymmetric pairwise fluxes Jij=−JjiJ_{ij} = -J_{ji}.

Time: about 60 min

1. The Anatomy of a Loop Contract: Invariant I(s)I(s) + Lyapunov Variant V(s)V(s)

Every deterministic loop updates a state tuple sk→sk+1s_k \to s_{k+1} while guard G(sk)G(s_k) holds. A loop is provably total-correct when four obligations hold:

  1. Initialization: Invariant I(s0)I(s_0) holds before the first iteration.

  2. Maintenance (Conservation): If I(sk)∧G(sk)I(s_k) \land G(s_k) holds at the top of the body, then I(sk+1)I(s_{k+1}) holds at the bottom.

  3. Termination (Lyapunov Variant): An integer function V(sk)≥0V(s_k) \ge 0 satisfies V(sk+1)<V(sk)V(s_{k+1}) < V(s_k) every step, forbidding infinite loops.

  4. Postcondition: When the loop exits (I(sf)∧¬G(sf)I(s_f) \land \neg G(s_f)), the desired mathematical answer follows immediately.

Consider computing x0y0 mod mx_0^{y_0} \bmod m for y0=1018y_0 = 10^{18}. Multiplying by x0x_0 1018 times is out of reach; instead, initialize (a,b,p)=(x0 mod m, y0, 1)(a, b, p) = (x_0 \bmod m,\, y_0,\, 1) and maintain the exact product-power invariant:

I(a,b,p):(p⋅ab) mod m=x0y0 mod m,V(b)=b(1.1)I(a, b, p): \quad (p \cdot a^b) \bmod m = x_0^{y_0} \bmod m, \qquad V(b) = b \tag{1.1}

Whenever bb is odd, peel one factor of aa into pp; then square a←a2 mod ma \leftarrow a^2 \bmod m and halve b←⌊b/2⌋b \leftarrow \lfloor b / 2 \rfloor. At termination b=0b = 0, a0=1a^0 = 1, so I(a,0,p)I(a, 0, p) forces p=x0y0 mod mp = x_0^{y_0} \bmod m in at most ⌊log⁡2y0⌋+1=60\lfloor \log_2 y_0 \rfloor + 1 = 60 steps.


Demonstration 1: Binary modular exponentiation via invariant (p * a^b) mod m == x0^y0 mod m
===========================================================================================
Step-by-step trace for 7^13 mod 1000 (exact = 407):
Step |   Base a |    Exp b |  Accum p |   Invariant (p * a^b) mod 1000
----------------------------------------------------------------------
   0 |        7 |       13 |        1 |                            407
   1 |       49 |        6 |        7 |                            407
   2 |      401 |        3 |        7 |                            407
   3 |      801 |        1 |      807 |                            407
   4 |      601 |        0 |      407 |                            407

Exponents y0 : [10, 10000, 10000000, 10000000000, 10000000000000, 10000000000000000]
Loop steps   : [4, 14, 24, 34, 44, 54] (54 steps for y0 = 10^16, against 10^16 - 1 multiplications by repeated multiplication)
  • In the table, (p * a^b) mod 1000 equals 407 on every row, from Step 0 (1 * 7^13) to Step 4 (407 * 601^0): each step moves value from the unsettled term aba^b into the settled accumulator pp while bb decreases to 0. For y0=1016y_0 = 10^{16} the loop takes 54 steps.


2. Dijkstra’s 3-Way Partition Invariant (dutch_national_flag_partition)

Suppose an inline optical wafer scanner streams NN thickness readings that must be partitioned in-place into Under-Etched (< lo_p), In-Spec ([lo_p, hi_p]), and Over-Deposited (> hi_p) in one pass. Mental Move #6, Write the Loop Invariant Before the Loop divides the array using three pointers 0 <= lo <= mid <= hi + 1 <= N:

A[0:lo]⏟<plo  ∣  A[lo:mid]⏟[plo, phi]  ∣  A[mid:hi+1]⏟Unclassified (V=hi−mid+1)  ∣  A[hi+1:N]⏟>phi(2.1)\underbrace{A[0 : \mathrm{lo}]}_{< p_{\mathrm{lo}}} \;\Big|\; \underbrace{A[\mathrm{lo} : \mathrm{mid}]}_{[p_{\mathrm{lo}},\, p_{\mathrm{hi}}]} \;\Big|\; \underbrace{A[\mathrm{mid} : \mathrm{hi}+1]}_{\text{Unclassified }(V = \mathrm{hi} - \mathrm{mid} + 1)} \;\Big|\; \underbrace{A[\mathrm{hi}+1 : N]}_{> p_{\mathrm{hi}}} \tag{2.1}

Every iteration inspects A[mid] and shrinks the unclassified middle gap V=hi−mid+1V = \mathrm{hi} - \mathrm{mid} + 1 by exactly 1 until mid>hi\mathrm{mid} > \mathrm{hi} (V=0V = 0).


Demonstration 2: Dutch national flag 3-zone sensor partition and live zone-evolution carpet
===========================================================================================
Partitioned N = 36 wafer readings around [95.0, 105.0] nm:
  Zone counts -> Under (<95): 10 | In-Spec ([95,105]): 14 | Over (>105): 12
  Swaps = 22 (<= N) | Comparisons = 62 (<= 2N)
<Figure size 1265x451 with 2 Axes>

Figure 2.1. Dutch national flag partition of 36 wafer readings. (a) State of the array at every iteration: the unclassified zone (grey) shrinks by exactly one cell per step while the low zone (blue) grows from the left, the high zone (red) from the right and the in-spec zone (green) between them. (b) The partitioned output, with the two thresholds at 95 and 105 nm.

What Demonstration 2 shows.

  • Look at the left heatmap: the pale orange unclassified wedge (mid .. hi) narrows by strictly one column per row, so the loop ends after exactly N=36N = 36 steps, while blue (< 95) grows from the left and red (> 105) grows from the right.


3. Finite-State Machines (FSMs) & Safety-Interlock Reachability

Industrial autoclaves, radiation therapy beams, and TCP network sockets are safer when they are not written with scattered boolean flags (if is_hot and not is_venting and is_purged: ...), whose 2k2^k combinations are hard to test. Modeling the controller as an explicit Deterministic Finite-State Machine M=(Q,Σ,δ,q0)\mathcal{M} = (Q, \Sigma, \delta, q_0) restricts execution to well-defined states q∈Qq \in Q and lets us prove via exhaustive Breadth-First Search (BFS) over all transition edges that hazardous combinations (such as opening an atmospheric vent while pressurized with toxic H2S\mathrm{H_2S}/syngas) are unreachable from q0q_0 under every possible input sequence Σ∗\Sigma^*.


Demonstration 3: High-pressure autoclave interlock FSM and exhaustive reachability proof
========================================================================================
Reachable states from IDLE_OPEN (7/7): ['COOL_DEPRESS', 'ESTOP_LOCK', 'IDLE_OPEN', 'PRESSURIZED', 'PURGED_READY', 'REACTING_HOT', 'SEALED_PURGING']
Adversarial trace rejected illegal commands: ['IGNITE_HEATER', 'FEED_GAS', 'OPEN_VENT', 'OPEN_VENT'] | Final safe state: ESTOP_LOCK

What Demonstration 3 shows.

  • Finite verification of infinite traces: Even though an operator can press buttons infinitely many times (∣Σ∗∣=∞|\Sigma^*| = \infty), BFS visits all ∣Q∣=7|Q| = 7 states and 7×8=567 \times 8 = 56 transitions and so proves that neither vent and press nor unpurged pressurization can ever occur.


4. Physical Conservation Laws as Runtime Code Contracts

In finite-volume fluid dynamics, chemical kinetics, and Markov chains, total mass/probability ∑i=1Nmi(t)=M0\sum_{i=1}^N m_i^{(t)} = M_0 is a loop invariant. Why do buggy diffusive codes slowly gain or lose mass over thousands of steps? Because computing flux Ji→jJ_{i \to j} and Jj→iJ_{j \to i} separately (or clipping negative concentrations locally after updating) breaks exact antisymmetry Jij=−JjiJ_{ij} = -J_{ji}. We contrast an antisymmetric face-flux update (with CFL positivity bound Δt≤12dmax⁡D\Delta t \le \frac{1}{2 d_{\max} D}) against a naive node-clipped update.


Demonstration 4: Antisymmetric conservative fluxes against mass-leaking clipped updates
=======================================================================================
<Figure size 1265x451 with 2 Axes>
Final Conservative Mass = 100.000000000000 kg | Buggy Clipped Mass = 4754.87 kg (+4654.9% fake mass)

Figure 2.2. Conservation as a code contract on a diffusion network. (a) Total mass against time step: the antisymmetric face-flux update keeps 100 kg exactly, while clipping negative values after an over-large step creates mass. (b) The mixing entropy of the conservative update rises monotonically towards its equilibrium value ln⁡N\ln N.

Inside the algorithm

We inspect representation_scaling.dutch_national_flag_partition and construct instrumented_dnf_with_invariant_assertions, which checks the loop contract (the zone bounds, conservation of the multiset of values and the strict decrease of V=hi−mid+1V = \mathrm{hi} - \mathrm{mid} + 1) before and after every iteration.

Check against the library


Inside the algorithm: Dutch national flag instrumented with full per-step contract assertions
=============================================================================================
def dutch_national_flag_partition(arr: np.ndarray, low_pivot: float, high_pivot: float) -> dict:
    """Dijkstra 3-way loop-invariant partition (< low_pivot | [low_pivot, high_pivot] | > high_pivot) in O(N)."""
    if low_pivot > high_pivot:
        raise ValueError("Require low_pivot <= high_pivot.")
    out = np.asarray(arr, dtype=float).ravel().copy()
    lo = 0
    mid = 0
    hi = out.size - 1
    comparisons = 0
    swaps = 0
    # Loop invariant: out[:lo] < low_pivot <= out[lo:mid] <= high_pivot < out[hi+1:]
    while mid <= hi:
        comparisons += 1
        if out[mid] < low_pivot:
            out[lo], out[mid] = out[mid], out[lo]
            swaps += 1
            lo += 1
            mid += 1
        else:
            comparisons += 1
            if out[mid] > high_pivot:
                out[mid], out[hi] = out[hi], out[mid]
                swaps += 1
                hi -= 1
            else:
                mid += 1
    return {"partitioned": out, "boundaries": (lo, mid), "comparisons": comparisons, "swaps": swaps}

Verified all 5 contract assertions across 64 iterations (including boundary ties)

Exercises

Worked solutions are in 02_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Implement Boyer–Moore’s O(N)\mathcal{O}(N) time, O(1)\mathcal{O}(1) space majority-vote algorithm with an explicit constructive pair-cancellation witness verifying at every prefix ii that (i−count)(i - \mathrm{count}) elements form disjoint heterogeneous pairs (u≠v)(u \neq v), and test across 40 randomized and adversarial sensor streams.

  2. Find how it fails. Demonstrate and quantify two classic loop-invariant bugs: (a) advancing mid += 1 inside the out[mid] > high_pivot swap of Dutch National Flag on [1.0, 9.0, 3.0, 8.0] ([lo_p, hi_p] = [2.0, 5.0]), and (b) pairing mid = (lo + hi) // 2 with lo = mid in binary search on [10, 20].

  3. Implement it yourself. Implement verify_chemical_valve_fsm(events, omit_low_level_trip=False) controlling batch reactor states (EMPTY, FILLING, FULL_READY, HEATING, DRAINING, LOCKOUT) with actuator tuple (level_low, inlet_open, drain_open, heater_on), plus bfs_find_hazard_trace(omit_low_level_trip) that proves zero reachable hazards for the safe FSM and finds the shortest dry-boil trace when the low-level trip is omitted.


Self-check for the exercises
============================
All checks passed.