Vaughan Reid's blog

Formal methods: Can a mathematical model of the design reveal invalid state transitions?

In the intro post I spoke about my experiments with checks we can give AI to get better validation of our changes.

A common scenario:

  1. Your tests pass and the pilot looks good.
  2. But then you deploy to production and something breaks.
  3. You dig deep into your data to find the issue and eventually you find the edge case. A sequence of unlikely events that broke a promise of your system.

As systems get more complex, it’s really difficult to find all the edge cases in testing. To get everything can be very slow and expensive!

A year ago a valuable way to get comfortable in complex systems was to have some bake time. Let it sit in the test environment for a couple of sessions and see if something bad pops up.

These days it’s often not just one change. With everyone using AI, teams are shipping so much faster. There is much more churn of changes we need to test at any point.

Formal methods

For some classes of issues there is a way to surface your edge cases at build time. It’s called formal methods. It’s been around for a long time but a little obscure. AWS was a major player that invested in it because across billions of transactions edge cases really matter. They had specialised teams who were more academic and would model their systems with a different paradigm. It was an expensive exercise but was worth their effort.

For the rest of us, bake time was good enough. It just wasn’t worth the time and effort to have this parallel effort to find obscure bugs.

What is it?

The idea is a little abstract. Mathematically model your module in terms of states and allowed transitions. Then check for properties that have to be true. This is now your module represented as a model. With this mathematical model you can use a model checker to brute force scenarios where an order of events breaks.

Before AI, you needed someone as fluent in writing your code as they are in writing the mathematical model of it. Not impossible but even in that case it was slow. Even in those cases, it was a one-off thing. Each time you update your code, you might need to update the model again!

An example

Let’s try an example to make this a little more concrete. We have a Python module that publishes internal updates to a multicast feed. Each message gets a sequence number. The client needs the transport to send those numbers in increasing order.

Here is the publishing method. sequence starts at zero, and encode is an asynchronous packet-building step. The complete module includes the surrounding types and setup.

async def publish(self, payload: str) -> None:
    self.sequence += 1
    message = Message(self.sequence, payload)
    packet = await self.encode(message)
    self.transport.sendto(packet, self.target)

Test this one call at a time and it works. All good?

But two callers can overlap! The first reserves sequence 1 and waits while building its packet. The second reserves sequence 2, finishes first, and sends it. Classic race condition.

What the model looks like

We are going to use TLA+ to model this. To be honest, it’s quite hard to read. I’m not putting the whole model here because that isn’t really the point. The agent can help write it, but we still need to check that it describes our code.

In the complete model, Allocate reserves a sequence number. Send represents packet construction finishing and the immediate call to the transport. Another caller can run while the first awaits packet construction.

The property we want to check is short:

InOrder == \A i \in 2..Len(sent) : sent[i - 1] < sent[i]

Every number in that history must be greater than the previous one. The model explores the allowed orderings of two calls, rather than relying on a test run to happen upon the bad one.

The configuration selects the unprotected implementation and enables the property:

CONSTANT Serialized = FALSE
INIT Init
NEXT Next
INVARIANT InOrder

TLA+ describes the model. TLC is the Java program that checks it. From the directory containing the model, configuration, and tla2tools.jar, run:

java -jar tla2tools.jar -config Publisher.cfg Publisher.tla

What TLC found

TLC reports Invariant InOrder is violated. Its trace starts at the initial state and takes four transitions. In the Python module’s terms:

  1. Caller A reserves sequence 1.
  2. Caller B reserves sequence 2.
  3. B finishes building its packet and sends sequence 2.
  4. A finishes building its packet and sends sequence 1.

We sent [2, 1]. Not what we wanted.

We’re not done yet!

The checker is exploring a model, not executing our Python. That is important to understand. These are separate things. We need to confirm that this ordering is possible in the implementation too.

The regression tests hold A inside the encoder, let B finish, then release A. They reproduce that same [2, 1] interleaving without sleeps.

Keep allocation and sending together

One fix for this single-process example is to initialize an asyncio.Lock and hold it across the whole publishing operation:

async def publish_serialized(self, payload: str) -> None:
    async with self.lock:
        await self.publish(payload)

Locking just the counter would not fix the bug. No second caller may allocate and send while the first is building its packet.

With Serialized = TRUE, the model represents that lock. TLC finds no invariant violation in the bounded model. The same Python regression scenario now produces [1, 2].

Now we’re done!

Keep the model connected to the code

Changing the Python does not automatically update the model, which is definitely a gotcha if you rely on remembering to update it.

The way I get a reminder to update the model is that I keep model-derived scenarios as regression tests. A test failure is a reason to investigate the code and model, not to automatically regenerate the model until it agrees with a bug.