Beams, the trusted runtime for AI agents, is now GA
Read now
Home
Blog
Fixing a Bug with Formal Methods and Property-Based Testing

Fixing a Bug with Formal Methods and Property-Based Testing

Russell Jones

15 min read
Published December 6, 2026

Branching tree of execution paths with one highlighted path ending in a liveness lasso loop.

This post shows how we used formal methods, with the P language, to find and fix a concurrency bug in Teleport, then used property-based testing, with Rapid in Go, to prevent regressions.

If you are not familiar with formal methods or property-based testing (PBT), this post is a gentle introduction to both. The issue is simple enough that most programmers can reason about it, and I'll walk you through modeling and fixing it step by step. You don't need experience with the P programming language or Rapid to follow along.

Illuminating our Thinking

This post is part of a series of blog posts from the Teleport Engineering team called "Illuminating our Thinking" where a pilot group used formal and semi-formal methods and frontier AI models to find and fix issues in Teleport.

Each post shares the author's perspective and takeaways as we adopt formal methods at Teleport.

  1. Property Based Thinking
  2. Fixing a Bug with Formal Methods and Property-Based Testing

What is the P language?

P is a programming language for modeling and checking distributed systems as state machines that communicate by passing messages. Each machine starts out in a state, waits for a message, reacts to it, and maybe moves to a new state or sends messages to other machines. P runs your program many times, each time picking a different order in which the machines take turns handling their events, so it can catch bugs that only appear under an unlucky interleaving. This is the power of P and formal methods: it helps you find those difficult to reason about bugs.

We chose P because it works at scale (it's used at AWS) and is easy to onboard onto. This is not a minor concern for us as a team, onboarding a triple-digit number of engineers with little exposure to formal methods is not an easy task.

Modeling a concurrency bug in P

The issue we'll fix is #61383: The teleport_cache_health metric can get stuck with the wrong value after shutdowns or restarts. This bug is a classic concurrency issue. We have a single metric but multiple caches write to it, which can lead to the metric being clobbered.

When working with formal methods, the first step is to model the current behavior.

If we think about a Cache as a Finite State Machine (FSM). What states can it be in?

A simplified state machine diagram of a cache with four states: Init, Healthy, Unhealthy, and Stopped
  • Init: Set up the cache
  • Healthy: The cache is running, connected to the backend, and healthy
  • Unhealthy: The cache is running but isn't connected to the backend, making it unhealthy
  • Stopped: The cache is closed and shut down, for example, during a reload

What about the transitions? It can bounce between Healthy and Unhealthy and transition from either of those states to a Stopped state.

Let's write a P model for this.

Don't worry about the implementation details too much at this point, try and understand the broad strokes in the code below and make sure you understand how it matches what is described above.

event eReport: (who: machine, healthy: bool);
event eStop;
event eDeregister: machine;
event eSetHealth: bool;

machine Cache {
    var metric: machine;

    start state Init {
        entry (m: machine) {
            metric = m;
            goto Healthy;
        }
    }

    state Healthy {
        entry {
            send metric, eReport, (who = this, healthy = true);
            announce eCacheHealth, (who = this, healthy = true);
        }

        on eSetHealth do (healthy: bool) {
            if (!healthy) {
                goto Unhealthy;
            }
        }

        on eStop do {
            goto Stopped;
        }
    }

    state Unhealthy {
        entry {
            send metric, eReport, (who = this, healthy = false);
            announce eCacheHealth, (who = this, healthy = false);
        }

        on eSetHealth do (healthy: bool) {
            if (healthy) {
                goto Healthy;
            }
        }

        on eStop do {
            goto Stopped;
        }
    }

    state Stopped {
        entry {
            send metric, eDeregister, this;
            announce eCacheDown, this;
        }

        ignore eStop;
        ignore eSetHealth;
    }
}

Going back to the state machine diagram, let's update it to be a little more rigorous and include P syntax.

A P state machine diagram of a cache with four states: Init, Healthy, Unhealthy, and Stopped

Before going further, let's dig into the Healthy state to understand what is happening a bit more. Once we enter the Healthy state we send and announce (to someone, more on this later) that the Cache is healthy. Then we sit around and wait for either the eSetHealth or eStop events. Once either arrives we execute their handlers to either transition to a Unhealthy state or Stopped state.

The next FSM is the Metric. First let's start with the buggy one.

machine MetricBug {
    var healthy: bool;

    start state Reporting {
        entry {
            healthy = false;
        }

        on eReport do (r: (who: machine, healthy: bool)) {
            healthy = r.healthy;
            announce eMetricChanged, healthy;
        }

        ignore eDeregister;
    }
}
State machine diagram of the buggy metric modeled in P, with a single Reporting state

The FSM only has a single state Reporting and has a single handler that waits for the eReport event, updates if it's healthy or not, and announces (to someone, more on this later) that the value of the cache has changed.

We can now reveal the first mystery.

Remember the send metric, eReport, (who = this, healthy = false); line? That was the Cache communicating with the Metric. The Cache sent a message eReport and the only FSM listening for that event is MetricBug. It receives the message and updates its state.

At this point before continuing, it's worthwhile sitting with the diagrams and code of the two machines to see if you can work out in your head how two instances of a Cache would clobber the healthy value being tracked in MetricBug.

Specifying correctness with safety and liveness properties

Great, we've modeled the bug but have not said anything about what correct behavior is, which means we have not reproduced it yet. That's where the specification comes in.

We write specifications (or a monitor) for how the system should work. In the formal verification world we do this through the specification of safety and liveness properties.

What are safety and liveness properties?

The classic definition of a safety property is "something bad never happens." Think about it as a claim you are going to make about the system that must always be true. If the checker ever finds a trace where this property is not true, that trace violates the safety property. Imagine you are writing your own implementation of sync.Mutex. A safety property would be that two goroutines can never hold the lock at the same time. If anything ever violates that property you know you have a bug in your implementation of sync.Mutex.

The classic definition of liveness is "something good eventually happens." Imagine you are writing an eventually consistent datastore. A liveness property would be that after writes stop, eventually every replica converges on the same value. Liveness properties are violated when two replicas hold different values forever and never reconcile. Forever is a long time right? P handles liveness through cold and hot states for your specification. A cold state is when the system has converged, and a hot state is when the system is still diverged. A liveness violation would be the checker finding a loop where the system stays in a hot state forever (a lasso).

One last thing, there is a property of P I have been glossing over until now, but we need to cover it to understand the specification. At its core, with P you are defining state machines. Each state machine has a strict FIFO inbox and the state machines can send messages to each other. P will cause different interleavings and delays between the messages hitting the inboxes. As you can imagine, this is a highly asynchronous system, so you can't rely on ordering between messages from different machines. This is the magic that finds concurrent bugs.

So what does a specification look like? It's another FSM that monitors events being sent to it by the model and asserts either safety or liveness properties.

Now we'll reveal the second mystery.

Remember those strange "announce" messages before? The specification is the one listening to those events and asserting correctness through safety and liveness properties.

MetricEventuallyConverges monitors three events eCacheDown, eCacheHealth, and eMetricChanged. Two of those come from the Cache and one from MetricBug. That will be important later. The monitor starts in the cold state. It will shadow the state of the model in up and healthyUp which will update whenever the Cache updates. When the Cache or Metric announces a change, the monitor checks if the state matches the expected state. If the state matches, the monitor stays in the cold state, if not it diverges into the hot state. The checker will run the model against this monitor and verify that we don't enter a loop and remain in a hot state forever (forever diverged from the real state).

spec MetricEventuallyConverges
    observes eCacheDown, eCacheHealth, eMetricChanged {
    // up is every running cache.
    var up: set[machine];
    // healthyUp is every running and healthy cache.
    var healthyUp: set[machine];
    var metric: bool;

    start cold state Init {
        entry {
            goto Converged;
        }
    }

    cold state Converged {
        on eCacheHealth do (r: (who: machine, healthy: bool)) {
            up += (r.who);
            if (r.healthy) {
                healthyUp += (r.who);
            } else {
                healthyUp -= (r.who);
            }
            check();
        }

        on eCacheDown do (who: machine) {
            up -= (who);
            healthyUp -= (who);
            check();
        }

        on eMetricChanged do (h: bool) {
            metric = h;
            check();
        }
    }

    hot state Diverged {
        on eCacheHealth do (r: (who: machine, healthy: bool)) {
            up += (r.who);
            if (r.healthy) {
                healthyUp += (r.who);
            } else {
                healthyUp -= (r.who);
            }
            check();
        }

        on eCacheDown do (who: machine) {
            up -= (who);
            healthyUp -= (who);
            check();
        }

        on eMetricChanged do (h: bool) {
            metric = h;
            check();
        }
    }

    fun check() {
        if (metric == expected()) {
            goto Converged;
        } else {
            goto Diverged;
        }
    }

    fun expected(): bool {
        return sizeof(up) == 0 || sizeof(healthyUp) > 0;
    }
}

Ideally I'd pair this liveness property with a safety property to really lock down correctness. While I could think up several safety properties, none of them were really meaningful.

Fault injection with non-determinism

Great, we have a model and a specification. However if you have been reading closely you might wonder, how do we now trigger a fault? Remember the eSetHealth event that would cause the Cache to flap? Someone has to send that event. Who was sending it?

If you look at the Driver below, I've wrapped each Cache with a FaultInjector. This fault injector will non-deterministically emit eSetHealth events to each Cache, allowing the checker to simulate network issues which will explore more schedules. It's the following line.

send cache, eSetHealth, $;

That $ is the non-deterministic part: sometimes it sends true and sometimes it sends false causing the cache to flap. $ is P's syntactic sugar for choose(), different modelling languages have similar ways to inject non-determinism into the model.

This is quite useful for systems modeling. Usually to simulate these non-deterministic behavior you have to run your tests under stress hoping to reproduce a flake or debug some weird behavior in the middle of the night over a Zoom call. Formal methods allow us to inject faults (and fix them) during the design phase.

machine Driver {
    var m: machine;

    var a: machine;
    var b: machine;

    start state Init {
        entry {
            m = new Metric();
            a = new Cache(m);
            b = new Cache(m);

            new FaultInjector(a);
            new FaultInjector(b);

            send a, eStop;
            send b, eStop;
        }
    }
}

machine FaultInjector {
    var cache: machine;
    var failures: int;

    start state Init {
        entry (c: machine) {
            cache = c;
            failures = 4;
            goto InjectFailure;
        }
    }

    state InjectFailure {
        entry {
            if (failures == 0) {
                goto Done;
            }

            send cache, eSetHealth, $;

            failures = failures - 1;
            goto InjectFailure;
        }
    }

    state Done {}
}

That's it. We've now modeled the bug, written a specification for correctness, and have a driver that can inject faults to trigger incorrect behavior.

When we run the model checker, we'll see that in 0.08s the model checker found a trace where the value was clobbered!

$ p compile && p check -tc tcOverlap -i 1000
[...]
... Checking statistics:
..... Found 1 bug.
..... Found 100.00% buggy schedules.
[...]
... Elapsed 0.0878672 sec.

The fact that a bug was uncovered is nice, but what's even better is that a worked-out trace is also emitted. This trace tells you the exact transitions that lead to the bug.

Let's walk through a simplified trace.

Sequence diagram of a P model checker trace showing two caches clobbering a shared health metric

Cache 3 starts and is healthy, so the metric is true and the monitor is happy. Cache 4 starts before Cache 3 is stopped, and the metric is still true. The Driver flaps Cache 3 and then shuts it down. Cache 4 is up and healthy, but the metric stays stuck as unhealthy forever.

This may feel trivial for this particular bug (and it is), but having a trace for more complex issues dramatically speeds up debugging.

Modeling the fix

We have one last thing to model now: the fixed metric.

machine Metric {
    var health: map[machine, bool];

    start state Init {
        entry {
            goto Reporting;
        }
    }

    state Reporting {
        on eReport do (r: (who: machine, healthy: bool)) {
            health[r.who] = r.healthy;
            announce eMetricChanged, anyHealthy();
        }

        on eDeregister do (who: machine) {
            health -= who;
            announce eMetricChanged, anyHealthy();
        }
    }

    fun anyHealthy(): bool {
        var k: machine;

        // If no cache is up, report healthy. This is a valid state
        // and alternative to deleting this metric.
        if (sizeof(health) == 0) {
            return true;
        }

        // If any cache is healthy, report healthy status.
        foreach (k in keys(health)) {
            if (health[k]) {
                return true;
            }
        }

        // If nothing is healthy, then report unhealthy.
        return false;
    }
}

Notice the difference? We now track the health of each cache independently and aggregate health across all caches and announce the aggregated value. This prevents any one cache from clobbering the value of the metric.

Aside: I did have another specification I built where I could independently verify anyHealthy() as well, but it got really long and brittle. I ditched it when I realized the value in formal methods was more from preventing the metric from getting stuck, not from the accuracy of the short anyHealthy() function.

If we re-run the model checker, it no longer finds any buggy schedules.

Preventing regressions with property-based testing in Go

At this point we've modeled and reproduced the bug, written a fix, and even have a spec that verifies correct behavior. However all of this sits outside our implementation.

To fix this in our implementation, let's start by writing a test that reproduces the bug. We could write a few unit tests that cover the specific scenarios outlined in #61383 but that would just cover those particular scenarios and would still leave us open to regressions.

However, we can write a property-based test that uses StateMachineActions which is almost a 1-to-1 port of the P specification I wrote previously. It's not a lot of work and it's the link that locks down our implementation directly to what we specified in our formal model.

package cache

import (
	"context"
	"errors"
	"testing"

	"github.com/gravitational/teleport/lib/services"
	"github.com/gravitational/teleport/lib/utils"
	"github.com/prometheus/client_golang/prometheus/testutil"
	"pgregory.net/rapid"
)

type machine struct {
	up        map[*Cache]bool
	healthyUp map[*Cache]bool

	all []*Cache
}

func (m *machine) init(t *rapid.T) {
	cacheHealth.Reset()

	m.up = map[*Cache]bool{}
	m.healthyUp = map[*Cache]bool{}

	// Create 2, 3, or 4 caches.
	for range rapid.IntRange(2, 4).Draw(t, "n") {
		// Create a Cache directly instead of using newPackForAuth because
		// starting a Cache launches goroutines that call setInitError. To make
		// this test deterministic, only this test should call setInitError.
		ctx, cancel := context.WithCancel(context.Background())
		c := &Cache{
			Config:         Config{target: "auth"},
			ctx:            ctx,
			cancel:         cancel,
			initC:          make(chan struct{}),
			firstTimeInitC: make(chan struct{}),
			eventsFanout:   services.NewFanoutV2(services.FanoutV2Config{}),
			lowVolumeEventsFanout: utils.NewRoundRobin([]*services.FanoutV2{
				services.NewFanoutV2(services.FanoutV2Config{})}),
		}
		c.setInitError(nil)
		m.up[c] = true
		m.healthyUp[c] = true

		m.all = append(m.all, c)
	}
}

// SetCacheHealthy will pick a random cache from the slice of caches
// and set its state to healthy.
func (m *machine) SetCacheHealthy(t *rapid.T) {
	c := m.all[rapid.IntRange(0, len(m.all)-1).Draw(t, "i")]

	c.setInitError(nil)

	m.up[c] = true
	m.healthyUp[c] = true
}

// SetCacheUnhealthy will pick a random cache from the slice of caches
// and set its state to unhealthy.
func (m *machine) SetCacheUnhealthy(t *rapid.T) {
	c := m.all[rapid.IntRange(0, len(m.all)-1).Draw(t, "i")]

	c.setInitError(errors.New("unhealthy"))

	m.up[c] = true
	delete(m.healthyUp, c)
}

// SetCacheDown will pick a random cache from the slice of caches and close it
// to shut it down.
func (m *machine) SetCacheDown(t *rapid.T) {
	c := m.all[rapid.IntRange(0, len(m.all)-1).Draw(t, "i")]

	c.Close()

	delete(m.up, c)
	delete(m.healthyUp, c)
}

// expected is the health property that enforces correctness. The metric is
// healthy if any cache is up or no cache is up. Otherwise it's unhealthy.
func (m *machine) expected() float64 {
	if len(m.up) == 0 || len(m.healthyUp) > 0 {
		return 1.0
	}
	return 0
}

// Check enforces the state machine invariant. It's run after every action
// (SetCacheHealthy, SetCacheUnhealthy, SetCacheDown) and asserts the expected
// value matches the received value of the gauge.
func (m *machine) Check(t *rapid.T) {
	got := testutil.ToFloat64(cacheHealth.WithLabelValues("auth"))
	want := m.expected()

	if got != want {
		t.Fatalf("got gauge %v, want: %v", got, want)
	}
}

// TestMetricConverges ensures that caches correctly report their health to the
// prometheus metric.
func TestMetricConverges(tt *testing.T) {
	rapid.Check(tt, func(rt *rapid.T) {
		m := &machine{}
		m.init(rt)
		rt.Repeat(rapid.StateMachineActions(m))
	})
}

To understand what's happening Rapid will create a machine which will then randomly call SetCacheHealthy, SetCacheUnhealthy, and SetCacheDown for 100 iterations. After each iteration it will call Check. If you recall, this is very close to what we did in P. This will cover strange orderings that we may not think happen in production, but actually will occur in production.

Running this test consistently reproduces the issue in the implementation as well.

The almost one-to-one mapping is really powerful and lets us take the most important parts of correctness and lock them in as PBT tests preventing future drift.

I'll leave the implementation as an exercise for the reader as it's not that interesting, the interesting parts are the model and PBT.

Are formal methods worth the cost?

Yes they are!

We've now formally modeled and fixed a real bug! Yes it was a simple bug, but it does illustrate how powerful formal and semi-formal methods are for systems engineers.

If you have ever spent time hunting down flaky tests, this will feel like cheating. You can catch bugs at design time instead of runtime!

To front run the usual complaints about formal methods, the natural question will come up: won't this take a lot of time and cost a lot? Maybe. However, consider the cost of incorrectness:

  • The cost of incident response
  • The cost of paying down technical debt because we implemented an incorrect design
  • The time our teammates spend waiting on CI due to a flaky test
  • The cost to roll back a release
  • The cost in the loss of confidence in your product

That's pretty expensive.

In addition, over the past 12 months frontier models have gotten really good. You can now use Claude and Codex to teach you formal methods, help write formal models, and write property-based tests.

This is why I am not sure the objections still hold true. However, all the benefits do continue to hold true.

At Teleport, we tackle problems like this to make distributed systems more reliable and secure. If you enjoy digging into subtle bugs, challenging assumptions, and turning better designs into working code, we'd love to work with you. Explore our open roles.


Related Articles