Skip to main content

05 - Model checking: how it works, state explosion, counterexamples

Build a state explorer, find a deadlock with its counterexample, measure combinatorial explosion and try symmetry reduction and bounded search.

What do you think about this article?

05 - Model checking: how it works, state explosion, counterexamples
Formal Methodsfedericocalo.dev

At a Glance

Build a state explorer, find a deadlock with its counterexample, measure combinatorial explosion and try symmetry reduction and bounded search.

You have two threads, two locks and a bug that shows up once in ten thousand runs: no test reproduces it on demand, because it depends on the order in which the scheduler interleaves the steps. Model checking attacks the problem from the opposite side: instead of trying a few executions, it explores all the configurations that the system's model can reach and checks the property on each one. If the property holds everywhere it answers yes; if not, it hands you a counterexample, the exact sequence of steps that violates it, which is the part you use to fix the design. The price is that the number of configurations grows exponentially with the components: this is state space explosion, and a large part of the craft consists in containing it. In this article you build an explorer of about fifty lines, use it to find a deadlock, measure the explosion on the numbers and try two remedies.

This is the fifth article in the Formal Methods series. It assumes the formulas of the article on temporal logic, of which here you will mostly use the safety properties, and the idea of a state-based system from the third article. The next one applies the same method to another formalism for concurrent systems, Petri nets.

The problem: one model, one property, one verdict

Model checking takes two ingredients: a finite-state model of the system (for us, a Kripke structure, or more simply a graph of configurations) and a property, written in temporal logic or as an invariant. It returns one of two possible things.

  • Yes: the property holds on every execution of the model.
  • No, with a counterexample: a path of the model that violates it. For a safety property it is a finite path up to the wrong configuration; for a liveness property it is a cycle in which the good thing never arrives.

The second case is what makes the tool useful. A "no" without an explanation leaves you hunting for the bug; a path that starts from the initial state and ends in the deadlock tells you which steps, in which order, and lets you reason about which protocol rule is missing. The simplest property, and the first to verify on a concurrent system, is the absence of deadlock: no reachable configuration in which the system cannot move any more. It is a safety property, and it is checked by visiting the nodes of the graph.

An explicit-state explorer

The model is the classic dining philosophers problem: n philosophers sitting in a circle, with one fork between each pair of neighbours. To eat, a philosopher first picks up one fork, then the other; then puts both down. The global state is the tuple of the philosophers' "program counters": 0 thinking, 1 holding the first fork, 2 eating, holding both. A fork is free if nobody holds it. The function philosophers builds the initial state and the successor function, and the parameter order says, for each philosopher, which fork is taken first. By changing order you change the protocol without touching the rest.

"""Explicit-state explorer: the dining philosophers."""
from collections import deque

def philosophers(n, order):
    """order[i] = (first fork, second fork) of philosopher i.
    State = tuple of pc: 0 thinking, 1 holds the first fork, 2 eating (holds both)."""
    def holder_free(state, fork):
        for i, pc in enumerate(state):
            first, second = order[i]
            if (pc >= 1 and first == fork) or (pc == 2 and second == fork):
                return False
        return True

    def successors(state):
        for i, pc in enumerate(state):
            first, second = order[i]
            if pc == 0 and holder_free(state, first):
                yield f"P{i} takes f{first}", state[:i] + (1,) + state[i + 1:]
            elif pc == 1 and holder_free(state, second):
                yield f"P{i} takes f{second}", state[:i] + (2,) + state[i + 1:]
            elif pc == 2:
                yield f"P{i} puts down the forks", state[:i] + (0,) + state[i + 1:]
    return (0,) * n, successors

The heart of the successors is the function holder_free: a move is possible only if the required fork is not already held by someone. If you removed it, two philosophers could hold the same fork and the model would describe an impossible system. The three moves of each philosopher correspond to the three if/elif branches: take the first fork, take the second, put them down. Every move produces a new tuple without modifying the old one, because the state is a value and not a mutable structure.

The exploration is a breadth-first visit (explore). The queue holds the states to expand, the parent dictionary remembers from which state and with which move each one was discovered, and also acts as the set of visited states. A state with no successors is a deadlock: it is recorded the first time it is met, and the path is rebuilt by walking up the parent links. Since the visit is breadth-first, the first deadlock found is also the closest to the initial state, and its path is the shortest counterexample. The optional arguments are used later: canon replaces every state with a representative of its equivalence class, max_depth limits the depth.

def explore(init, successors, canon=lambda s: s, max_depth=None):
    """BFS. Returns (number of states, first deadlock state, path to the deadlock)."""
    start = canon(init)
    parent = {start: None}
    depth = {start: 0}
    queue = deque([start])
    deadlock = None
    while queue:
        s = queue.popleft()
        moves = list(successors(s))
        if not moves and deadlock is None:
            deadlock = s
        if max_depth is not None and depth[s] >= max_depth:
            continue
        for label, t in moves:
            t = canon(t)
            if t not in parent:
                parent[t] = (s, label)
                depth[t] = depth[s] + 1
                queue.append(t)
    path = []
    s = deadlock
    while s is not None and parent[s] is not None:
        s, label = parent[s]
        path.append(label)
    return len(parent), deadlock, list(reversed(path))

The counterexample: three philosophers in deadlock

The first experiment makes everybody choose the left fork first. The second uses a global order on the forks: each one takes first the fork with the lower index, which for the last philosopher means reversing the order. The program prints the number of reachable states and, if there is one, the shortest path to the deadlock.

from explore import *

def naive(n):    return [(i, (i + 1) % n) for i in range(n)]      # left fork first
def ordered(n):  return [tuple(sorted((i, (i + 1) % n))) for i in range(n)]   # lower-indexed fork first

print("Three philosophers, all take the left fork first:")
count, dead, path = explore(*philosophers(3, naive(3)))
print(f"  {count} reachable states, deadlock in {dead}; shortest path:")
for step in path:
    print("   ", step)

count, dead, _ = explore(*philosophers(3, ordered(3)))
print(f"With the global order on forks: {count} states, deadlock: {dead}")

# Output:
# Three philosophers, all take the left fork first:
#   14 reachable states, deadlock in (1, 1, 1); shortest path:
#     P0 takes f0
#     P1 takes f1
#     P2 takes f2
# With the global order on forks: 12 states, deadlock: None

The counterexample is three steps long: each philosopher takes their own left fork, and at that point each one waits for the neighbour's fork, which the neighbour is holding. No move is possible any more: it is a circular wait. Reading it you see at once the root cause, which is not a mistake by a single philosopher but the absence of an order on the resources, and you see the fix: if everybody takes the lower-indexed fork first, in a circular wait each philosopher would hold the lower-indexed fork and wait for the higher-indexed one, so along the circle the indices would always grow and the circle could not close. The second line confirms it on the model: twelve states and no deadlock. Be careful about what this check proves: it holds for the three-philosopher model, not for an arbitrary number; the full exploration in the next section, repeated for n from 2 to 8, finds no deadlock even with the global order.

State explosion, with the numbers

Now count how many states are needed as n grows. The program runs the full exploration for n from 2 to 8 on the naive protocol, and on the protocol with the global order; I explain the other two columns in the next section.

from explore import *

def naive(n):    return [(i, (i + 1) % n) for i in range(n)]
def ordered(n):  return [tuple(sorted((i, (i + 1) % n))) for i in range(n)]

print("  n   naive  naive+rotations  global order  order+rotations (invalid)")
for n in range(2, 9):
    c1, _, _ = explore(*philosophers(n, naive(n)))
    c2, _, _ = explore(*philosophers(n, naive(n)), canon=rotation_canon)
    c3, _, _ = explore(*philosophers(n, ordered(n)))
    c4, _, _ = explore(*philosophers(n, ordered(n)), canon=rotation_canon)
    print(f"  {n}  {c1:>6}  {c2:>15}  {c3:>12}  {c4:>25}")

deadlock_free = all(explore(*philosophers(n, ordered(n)))[1] is None for n in range(2, 9))
print("global order, no deadlock for n from 2 to 8:", deadlock_free)

# Output:
#   n   naive  naive+rotations  global order  order+rotations (invalid)
#   2       6                4             5                          3
#   3      14                6            12                          6
#   4      34               11            29                         12
#   5      82               18            70                         22
#   6     198               38           169                         82
#   7     478               70           408                        221
#   8    1154              151           985                        620
# global order, no deadlock for n from 2 to 8: True

Read the first and the third column. The number of states of the naive protocol almost doubles with every extra philosopher: 6, 14, 34, 82, 198, 478, 1154. From n = 4 on, each value is twice the previous one plus the one before that (34 = 2·14 + 6, 82 = 2·34 + 14, 198 = 2·82 + 34, and so on up to 1154 = 2·478 + 198), and the ratio between consecutive values approaches 2.414, that is 1 + √2. This is an observation on the numbers up to n = 8, not a proof. The global-order column follows the same rule, with somewhat fewer states. At 1154 states the work is negligible: the full exploration of n = 8 took between 8 and 13 milliseconds over three runs (Python 3.14.4 on this machine; a single run has little value). The problem is the slope.

These numbers must be checked with a calculation that simulates no move. One observation is enough: every configuration in which no fork is held by two philosophers is also reachable, so the number of reachable states is the number of tuples in {0,1,2}ⁿ that are consistent with this rule. The program below filters them all, without visiting any path.

# Second, independent calculation: filter all the 3^n consistent configurations
# (no fork held by two philosophers) without simulating any move.
from itertools import product
def consistent(n, order):
    c = 0
    for st in product(range(3), repeat=n):
        owners = []
        for i, pc in enumerate(st):
            if pc >= 1: owners.append(order[i][0])
            if pc == 2: owners.append(order[i][1])
        c += len(owners) == len(set(owners))
    return c
print("n  naive  ordered")
for n in range(2, 9):
    naive = [(i, (i + 1) % n) for i in range(n)]
    ordered = [tuple(sorted((i, (i + 1) % n))) for i in range(n)]
    print(n, consistent(n, naive), consistent(n, ordered))

# Output:
# n  naive  ordered
# 2 6 5
# 3 14 12
# 4 34 29
# 5 82 70
# 6 198 169
# 7 478 408
# 8 1154 985

The values coincide with those of the exploration, column by column, so two independent methods agree: there is no more doubt about the exactness of the counts, and it has also been verified that in the model no consistent state is unreachable. The second program, however, has the same flaw as the first: it examines the 3ⁿ configurations, and therefore grows like them. To see the pure growth, with no exclusion rule at all, the next program considers n independent processes, each with three local states cycling 0, 1, 2, 0, and compares them with the closed formula 3ⁿ.

from explore import explore

def independent(n):
    """n processes that never talk, each with 3 local states cycling 0->1->2->0."""
    def successors(state):
        for i, pc in enumerate(state):
            yield f"P{i}", state[:i] + ((pc + 1) % 3,) + state[i + 1:]
    return (0,) * n, successors

for n in range(1, 9):
    count, _, _ = explore(*independent(n))
    print(f"n={n}: {count} states reached, 3^n = {3 ** n}")

BYTES_PER_STATE = 8      # working assumption: one state packed into 8 bytes
for n in (15, 20, 25, 30):
    states = 3 ** n
    gib = states * BYTES_PER_STATE / 2 ** 30
    print(f"n={n}: 3^n = {states:,} states, at {BYTES_PER_STATE} bytes each: {gib:,.2f} GiB")

# Output:
# n=1: 3 states reached, 3^n = 3
# n=2: 9 states reached, 3^n = 9
# n=3: 27 states reached, 3^n = 27
# n=4: 81 states reached, 3^n = 81
# n=5: 243 states reached, 3^n = 243
# n=6: 729 states reached, 3^n = 729
# n=7: 2187 states reached, 3^n = 2187
# n=8: 6561 states reached, 3^n = 6561
# n=15: 3^n = 14,348,907 states, at 8 bytes each: 0.11 GiB
# n=20: 3^n = 3,486,784,401 states, at 8 bytes each: 25.98 GiB
# n=25: 3^n = 847,288,609,443 states, at 8 bytes each: 6,312.79 GiB
# n=30: 3^n = 205,891,132,094,649 states, at 8 bytes each: 1,534,008.47 GiB

For n from 1 to 8 the exploration finds exactly 3ⁿ states: independent processes combine by product, and the space grows multiplicatively with every added component. The final lines are arithmetic, not measurements: with 20 processes you would need almost 3.5 billion states, which at 8 bytes each (a working assumption, because every tool represents states in its own way) take about 26 GiB. With 30 processes the same multiplication goes beyond a million GiB. This is state space explosion: the exploration is correct and complete, but every extra component multiplies its cost.

First remedy: exploiting symmetries

In the naive protocol the philosophers are all alike and the table is circular: rotating everybody by one seat gives the same system. Two states that differ by a rotation have the same future, so it is enough to explore just one of them. The function rotation_canon chooses as representative the smallest rotation of the tuple, and is passed to explore as the canon argument.

def rotation_canon(state):
    """Symmetry: the philosophers are identical, the table is circular."""
    return min(state[k:] + state[:k] for k in range(len(state)))

The effect is in the second column of the table: at n = 8 the states drop from 1154 to 151, about 7.6 times fewer, and the reduction factor stays below n, the number of rotations, because some states are invariant under rotation and merge with no other. The limit of the technique is in the last column. The protocol with the global order is not symmetric under rotation, because the last philosopher has a different order from the others. Applying the same rotation_canon still produces a number, but it is the number of a different graph (at n = 4, 12 states instead of the true 29), and that number has no meaning. Symmetry reduction is legitimate only if the symmetry is really an automorphism of the model: no tool checks for you that it is, so it is an assumption to justify, not a switch to turn on.

Second remedy: searching only up to a depth

If the bug has a short counterexample, there is no need to visit the whole space: it is enough to search paths up to length k. This is the idea of bounded model checking. The program below limits the breadth-first visit to k steps and applies it to the naive protocol with six philosophers, which has a six-step counterexample, one per philosopher.

from explore import *

naive6 = [(i, (i + 1) % 6) for i in range(6)]
print("Six philosophers, search bounded to k steps:")
for k in range(1, 9):
    seen, deadlock, _ = explore(*philosophers(6, naive6), max_depth=k)
    print(f"  k={k}: states seen {seen:>3}, deadlock found: {deadlock is not None}")

# Output:
# Six philosophers, search bounded to k steps:
#   k=1: states seen   7, deadlock found: False
#   k=2: states seen  28, deadlock found: False
#   k=3: states seen  72, deadlock found: False
#   k=4: states seen 132, deadlock found: False
#   k=5: states seen 180, deadlock found: False
#   k=6: states seen 198, deadlock found: True
#   k=7: states seen 198, deadlock found: True
#   k=8: states seen 198, deadlock found: True

With k from 1 to 5 the search finds nothing, and the answer "no deadlock within k steps" is true but misleading: the bug is there, just further away. At k = 6 the deadlock appears, and from then on the number of states seen no longer grows, because the 198 states are finished. The bound is therefore a one-way compromise: a counterexample that is found is always valid, an absence of counterexamples holds only up to the depth searched. In real bounded model checking the paths of length k are not enumerated: they are encoded as a propositional formula and the formula is handed to a SAT solver, which decides whether there is an assignment that satisfies the transitions and violates the property. The approach is described by Biere, Cimatti, Clarke and Zhu in a 1999 paper (for me, title and metadata, not the text). The SAT encoding is not run here: the program you have seen shows the principle of bounded depth, not the implementation with the solver.

Other techniques, and what I did not run

Real explorers combine techniques that I do not show here with code. I state them by name, with a warning: I have neither run nor measured them.

  • Abstraction. Many concrete states are grouped into one abstract state (a queue of 1523 messages becomes "queue not empty"). It is correct only if every concrete behaviour has an abstract counterpart; if not, it may miss a bug or report ones that do not exist.
  • Partial-order reduction. If two independent moves produce the same result in any order, it is enough to explore one of them.
  • Symbolic representation. A set of states is described by a Boolean function, stored in a compact structure such as binary decision diagrams (BDDs), and naming every state is avoided. Burch, Clarke, McMillan, Dill and Hwang published a paper on the subject in 1992, "Symbolic model checking: 10²⁰ states and beyond": I know only its title.

Which technique to choose depends on the system: abstraction helps when the data are large and the checks simple, partial-order reduction when there is a lot of independent concurrency, symbolic representation when the space has a lot of regularity. None is free, and each adds an assumption to justify, as you saw with symmetry. A mature tool such as Spin incorporates them; its official page says that it originates at Bell Labs from 1980, has been freely available since 1991, received the ACM System Software Award in April 2002 and, from version 6.4.5 (January 2016), has a three-clause BSD licence. I did not install or run it for this article.

What model checking does not tell you

  • That the model is faithful. The verdict concerns the model: if you forgot a step of the real protocol, the "yes" stays valid and useless.
  • That the property is the right one. A specification that is too weak always passes. A useful check is also to verify that the property can fail, for example by deliberately breaking the model.
  • That the system is finite. With unbounded buffers or an unfixed number of processes the space is infinite, and the exploration does not terminate without abstractions or specific techniques.
  • That an abstraction is correct. An unfaithful abstraction gives false alarms or, worse, hides bugs.
  • That the absence of a counterexample within k is an absence of bugs. You saw it with k from 1 to 5.

The common thread is that model checking is a verification of the model against a specification, and whatever lies outside those two objects remains uncovered. Its value is to find, systematically, the design defects that depend on rare interleavings, and to deliver them with a trace you can read: it is a task that testing cannot perform because it does not control the scheduler.

Exercises

  1. Add to the model a waiter who lets no more than n-1 philosophers sit at the same time, and verify with explore that with the naive protocol the deadlock disappears.
  2. Modify holder_free so that it ignores the second fork and predict, before running, whether the number of states goes up or down.
  3. Find by hand the counterexample for n = 4 and compare it with the one printed by the program.
  4. Take the protocol with the global order and, without using rotation_canon, prove that the same growth rule holds (each term is twice the previous one plus the one before that).

The first exercise is the most formative: the fix is not an order on the resources but a limit on the number of participants, and the explorer tells you whether it works without having to reason about it for hours. I tried the modification for n from 3 to 5 and the deadlock disappears.

Frequently asked questions

What is state space explosion?

It is the exponential growth of the number of reachable configurations as the components increase. In this article you measured it: independent processes with three local states produce 3ⁿ configurations, and the philosophers protocol almost doubles with every added philosopher.

What is a counterexample for?

It shows a sequence of steps from the initial state to the violation. For a concurrency bug it is the only reliable description, because the bug depends on an execution order that testing can hardly reproduce.

Can model checking prove that a system is correct?

It proves that a finite model satisfies a property. The correctness of the real system depends on the fidelity of the model and on the quality of the specification, and neither is verified by the model checker itself.

What you can do now

You can write a concurrent model as a graph of configurations, explore it breadth-first and obtain the shortest counterexample leading to a deadlock. You can measure the growth of the space and confirm the counts with a second calculation. You can reduce the space with a symmetry and you know that this is legitimate only if it is a true symmetry of the model, while the search bounded to k steps finds bugs but does not prove their absence. In the next article the same visit of the state space becomes a reachability computation on the markings of a Petri net, where the explosion takes a more extreme form.

Sources

The scripts explore.py, r1_counterexample.py, r2_scale.py, r3_limit.py, verify.py and growth.py were run with Python 3.14.4 on Linux, twice, with the same output. No model checker was run, and the SAT encoding was not implemented. The execution times are a range over three runs, not a benchmark.

Next part: Petri nets →

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects