Property Based Thinking
This blog post explores different ways of modeling a problem in terms of properties, either formal or functional as we will see later. My goal for this entry is to share my journey of property-based testing, formal methodology and deterministic simulation in hopes of sharing insights that may help you on your own journey.
By the end of this blog, I hope you will gain some insight on what properties can be, how they can be defined and how you can verify them.
What is a property in software testing?
We understand a property to be a statement about a system or procedure that can be true or false for a given run.
For the purposes of this blog, we will consider two schools of properties that being Formal Methods Properties and Property-Based Testing. In my opinion the major dividing line is you can think about formal properties describing the behaviour of the whole system over time, whereas PBT properties focus on relationships between method input and output. The general definition holds for both but each considers a single to run to be at a different scope.
Formal properties
Formal methods require us to define what "correct" means for our system in a way that is verifiable by tooling. There are two main categories of properties in most formal methods: safety and liveness.
The classic definition of a safety property is "something bad never happens".
It is an invariant that must hold at every point in time, in every possible
execution of the system. Imagine you are writing your own implementation of
Go's sync.Mutex. A safety property would be that two goroutines can never
hold the lock at the same time. If any execution ever ends up with two holders,
you know your mutex has a bug.
The classic definition of a liveness property is "something good eventually happens". It must hold for every possible execution: no matter what sequence of events occurs, the good thing must happen at some point. Imagine you are writing an eventually consistent datastore. A liveness property would be that once writes stop, every replica eventually converges on the same value. Unlike a safety property, no single moment can violate it: replicas are allowed to disagree for a while. The property is only violated if there is some execution in which they disagree forever and never reconcile.
These terms were first introduced by L. Lamport in his original paper from 1977:
A safety property is one which states that something will not happen. For example, the partial correctness of a single process program is a safety property. It states that if the program is started with the correct input, then it cannot stop if it does not produce the correct output. A liveness property is one which states that something must happen. An example of a liveness property is the statement that a program will terminate if its input is correct. [1]
These terms were later formally defined by B. Alpern and F. B. Schneider [2]. We will leave reading the mathematical definitions as an exercise for the reader, but one idea from the paper is worth calling out. A property is a liveness property if no partial execution is irremediable: whatever has happened so far, it is always still possible for the good thing to happen. A system satisfies it only if the good thing actually does happen in every one of its executions.
What is property-based testing?
Where formal properties describe how a whole system behaves over time, property-based testing (PBT) usually works at a scope of a single function or data structure.
A property is a statement about the relationship between a function's input and its output that should hold for any data. Generally tests make use of a fuzzer to randomize the inputs to a function, and the test asserts that the relationship between input and output holds regardless of what the fuzzer can generate. Writing fuzzers for this purpose is an entire research field in itself, so we will leave that out of this post for brevity.
For a wonderful introduction, I highly recommend "How to Specify It!" by John Hughes [3]. Rather than reinventing it, I'll borrow its opening example, which captures the most important mindset change.
Hughes opens the paper with reverse. An example-based test is trivial to
write: reversing [1, 2, 3] gives [3, 2, 1]. But as soon as the input is
random, there is no expected value to compare against, and it's tempting to
re-implement reverse in the test. That's a trap: the test becomes as complex
as the code, and shares its bugs. Instead, think about what must be true of the
output in relation to the input.
The snippets below use rapid [4], a
property-based testing library for Go, along with testify's require package
[5] for assertions.
// Example: checks the one case we thought of.
require.Equal(t, []int{3, 2, 1}, Reverse([]int{1, 2, 3}))
// Property: holds for any list, without knowing the expected output.
rapid.Check(t, func(t *rapid.T) {
x := rapid.SliceOf(rapid.Int()).Draw(t, "x")
require.Equal(t, x, Reverse(Reverse(x)))
})
"Think in properties, not data".
You don't need to know the right answer to recognise a wrong one.
The keen-eyed reader may point out that this property isn't sufficient on its
own: a Reverse that simply returns its input passes it too. This is why a
function is usually tested with several properties, each ruling out a different
class of bug. Hughes groups them into five categories:
- Invariants (Hughes calls this validity testing): every operation leaves the data in a valid state. For example, a binary search tree is still ordered after an insert.
- Postconditions: the result of a call satisfies something we can check
directly. For example,
len(Reverse(x)) == len(x). - Metamorphic: The relationship of two separate results holds a certain property. For example, reversing two lists joined together is the same as joining their reverses in the opposite order.
- Inductive: Inductive properties relate a call of the function to calls with smaller arguments, building up a proof that holds for all inputs.
- Model-based (or Oracle): compare against a simpler implementation of the same function. For example, check a binary search tree against a sorted slice holding the same keys.
In my opinion, these properties are most useful for localized code such as functions and data structures, rather than for whole systems. We will call back to several of these categories in the pagination example.
A worked example: pagination
Now that we have some awareness of what properties can be, I think it's
important to consider how we can define them. My personal belief is that the
quality of the properties you can define will dictate how useful the methods
discussed in this blog and the wider series will be. To keep things simple we
will use a relatively simple concept within the Teleport codebase, that is the
List* family of RPCs. I would expect that all engineers at Teleport have had
the pleasure of interacting with this API but for readers external to Teleport
I will lay out the basic idea here.
Following Teleport's internal resource API guidelines, a List call takes a
page size and a page token, and returns a page of items
along with the token for the next page. A client calls it repeatedly, passing
the token back each time, until it receives an empty token or an error.
Most resource types in Teleport don't implement this logic themselves. List
calls are usually served from the cache, and rather than each resource
hand-rolling pagination, they share a single generic implementation:
genericLister.
Pagination is easy to get subtly wrong: an off-by-one at a page boundary, a
token pointing at the wrong item, an invalid page size. Getting it right once,
in one place, means a fix or a bug affects every resource at the same time.
That makes genericLister a good candidate for properties.
An example-based test for it may look like this:
matching := newApp("app-a")
filtered := newApp("app-b")
require.NoError(t, collection.store.put(matching))
require.NoError(t, collection.store.put(filtered))
lister := genericLister[types.Application, appIndex]{
// ...
nextToken: types.Application.GetName,
filter: func(app types.Application) bool {
return app.GetName() == matching.GetName()
},
}
page, next, err := lister.list(t.Context(), 1, "")
require.NoError(t, err)
require.Len(t, page, 1)
require.Equal(t, matching.GetName(), page[0].GetName())
require.Empty(t, next)
Note that every assertion made in this test is completely dependent on the data that the author chooses. And of course normally a test like this would also be accompanied by edge case tests, which depend on the internal implementation of the method. While this may verify that our chosen properties hold for this particular set of inputs, it gives us little confidence that the properties will hold for any input.
How to define properties at design time
So we know what different properties may be, and we know why we may wish to find them. How does one go about determining their properties?
My advice is that these should be determined at design. In fact for both formal and most PBTs properties, I would argue that you don't need to write a single line of code to come up with a set of properties you would like to hold. It is also far more challenging to 'retrofit' properties to an existing system, as you may discover properties that were not intended or desirable to begin with. In my opinion, incorporating property-based thinking into your design process will increase chances of success.
Fortunately, here at Teleport we have a robust design methodology, so by the time we have started exploring these methods I was able to lean heavily on our design documents (called RFDs) to determine properties for pagination.
Note for the purpose of this blog I have categorised each property here into
both PBT and Formal to illustrate the differences between the two. For Formal
properties we may be interested in the property holding over the entire system
runtime when List APIs are made from the client. For PBT properties we would
like to ensure they are upheld by the backing implementation where possible.
| Property | Statement | PBT | Formal |
|---|---|---|---|
| Page size bound | For every call, len(page) <= pageSize. | postcondition | safety |
| Default page size | For any pageSize <= 0, the result equals the result for the default page size. | metamorphic | N/A |
| Uniqueness | Across a full iteration, no item is returned more than once. | postcondition | safety |
| Termination | Following tokens eventually reach "", for any page size. | postcondition (bounded) | liveness |
| End of list | Once every item has been returned, the next token is "". | postcondition | safety |
| Completeness | Every item in the collection is eventually returned. | model-based | liveness |
| Page size independence | Any two page sizes return the same set of items. | metamorphic | N/A |
As you may have noticed some PBT properties are not suitable for Formal Methods, they may rely on internal implementation details (default page size) and metamorphic properties rely on tying together multiple run results. Depending on the design and what you are building, you may choose either of these approaches or both.
You may also discover limitations in your system. For example, our design guidelines note that the Teleport backend does not support snapshotting. This means that the completeness property of a collection only holds for collections not altered mid-iteration.
By this point, you should hopefully have a handful of properties to begin testing and modeling.
Property-based testing in Go with rapid
Here at Teleport we have chosen rapid
[4] as our PBT framework for Go. rapid
provides a range of default generators and a top level function called
rapid.Check which verifies the inner method has not falsified the property by
calling standard Go testing failure methods such as T.Fatalf, *T.Errorf,
etc. This is very handy as it allows you to wrap your normal tests and convert
them to PBTs with ease. Using our example above, let's see what a test for
unique items may look like:
rapid.Check(t, func(t *rapid.T) {
n := rapid.IntRange(0, 300).Draw(t, "n")
isDesc := rapid.Bool().Draw(t, "isDesc")
// Small page sizes stress the pagination boundary logic
defaultPageSize := rapid.IntRange(1, 5).Draw(t, "defaultPageSize")
fixture := newTestListerFixture(n, isDesc, defaultPageSize)
seen := make(map[int]int, n)
for item, err := range fixture.lister.Range(t.Context(), "", "") {
require.NoError(t, err)
seen[item]++
require.Equal(t, 1, seen[item], "item %d was returned more than once", item)
}
require.Len(t, seen, n)
})
Note in the example above we specifically use IntRange to guide the fuzzer
towards values we suspect may be more problematic. In general, PBT fuzzers
already are biased towards well known edge case values, for integers it may be
0, -1, or MaxInt as a simple example. That said if you know a certain
input may cause issues you may wish to explicitly guide the fuzzer towards it.
"Guide the fuzzer".
As mentioned before, fuzzers are an incredibly deep topic, different
implementations provide different functionality for guidance and coverage.
rapid's own documentation
[4] calls this out:
rapid shines in generating complex structured data, including state machine tests, but lacks coverage-guided feedback and mutations
It is good to be aware of the trade off you are making when selecting a fuzzer and what purpose it is trying to fulfil.
Most notably, these tests are a single, in memory instance with a static collection. Teleport of course has to cope with concurrent writes, network calls and a real backend. So how can we test these properties under more lifelike scenarios? The modern answer to this is deterministic simulation testing which we will cover next.
Deterministic simulation testing with Antithesis
The safety and liveness properties in the Formal column above describe the
system as a whole, and the natural way to verify them would be to write a
formal model. We don't have a formal model of Teleport's List APIs, and building
one that is faithful to the cache, the backend and replication between auth
servers would be a significant project of its own. Other entries in this series
focus on the formal modeling side. This is where Antithesis is an interesting
alternative: rather than modeling the system, it runs a full Teleport
deployment and checks safety and liveness assertions against the real thing,
while the fuzzer explores interleavings and injects faults.
So, what even is Antithesis? Antithesis is a deterministic simulation testing platform. It runs your entire system, in our case a full Teleport cluster deployed as a set of containers, inside a deterministic hypervisor, so that every run can be replayed exactly. Because runs are reproducible, Antithesis can stop at an interesting moment, branch, and try something different from there: a different ordering of requests, a network partition, a process restart. Coverage feedback and the assertions in your code guide which branches are worth exploring. For those interested, Alex Pshenichkin's 'So you think you want to write a deterministic hypervisor?' [6] is an incredible write-up of what it takes to build such a platform. The idea with this approach is to verify whether your properties hold under many different conditions of the system, rather than many different inputs. So where local PBT fuzzes the inputs, Antithesis fuzzes workload schedules and faults.
If a property holds across all of these timelines, that is much stronger evidence than a handful of hand-written integration tests can give. It is of course, not a formal proof, but it is strong evidence nonetheless.
In order to do this, the SDK provides assertions [7] which can be mapped to properties we have discussed above:
| Assertion | Meaning | Property | Example from our workloads |
|---|---|---|---|
assert.Always | The condition is true every time it is evaluated, and it is evaluated at least once. | safety | "goroutine leak profile is empty" |
assert.AlwaysOrUnreachable | The condition is true every time it is evaluated but does not have to be reachable. | safety | "List observes at most one copy of a resource" (uniqueness) |
assert.Unreachable | This line of code is never executed. | safety | "Updating resource with a stale revision should never succeed" |
assert.Sometimes | The condition is true in at least one evaluation across all runs. | coverage | "sometimes running property succeeds" |
So using the uniqueness check from before, let's see how this may look in Antithesis. First let's make sure the backend has some items for us to work with:
// adminOps and ops are thin wrappers in our workload around the Teleport
// client for a single resource kind: NewResource builds a resource with
// the given name, Create writes it to the cluster.
rng := rand.New(random.Source().(rand.Source))
for range rng.Int32N(64) {
resource, err := adminOps.NewResource(fuzzerPrefix + "-" + uuid.New().String())
if err != nil {
return trace.Wrap(err, "creating resource")
}
if _, err = ops.Create(ctx, resource); err != nil {
return trace.Wrap(err, "creating fixture")
}
}
An important note here is that when writing Antithesis tests, we must be
careful when choosing the source of randomness. Because the whole system runs
in a deterministic simulation, any random number generator we seed ourselves
gives the same sequence in every run. Instead, whenever the test makes a random
decision (such as the number of items to create), we ask the SDK for the value
via random.Source(). This hands the decision to Antithesis, which can then
vary it between runs and, over time, learn which choices lead to more
interesting behaviour and provide them more often
[8].
Finally we may list all resources and check for uniqueness:
// ResourcesWithPageSize iterates through every page of a List RPC,
// passing the next-page token back until it's empty.
pageSize := int(rng.Int32N(64))
for r, err := range clientutils.ResourcesWithPageSize(ctx, ops.List153, pageSize) {
if err != nil {
return trace.Wrap(err, "listing resources for duplicate check")
}
name := r.GetMetadata().GetName()
namemap[name]++
if namemap[name] > 1 {
details["duplicate"] = name
assert.AlwaysOrUnreachable(false, "List observes at most one copy of a resource", details)
return trace.Errorf("list returned duplicate resource %q", name)
}
}
Because this is a real system under faults, there will be multiple timelines where the propagation of the write is slower due to network faults. There may also be timelines where the cache is unhealthy and the reads fall back to the backend. We are interested in all of those scenarios. However we must also ensure that we are hitting our safety check at least some of the time.
"Pair safety properties with reachability"
Under heavy fault injection every call to List could fail due to network
partitioning, timeouts due to jammed interfaces, etc. For this reason we
recommend pairing safety with reachability to ensure the codepath is successful
at least in some timelines, and when they are, the properties hold.
Testing liveness properties in Antithesis
Note that none of the above are considered liveness properties. Sometimes
says that a good thing can happen in at least one timeline, not that it
eventually happens in every timeline. These provide guidance but also
confidence for the user that the codepath has been tested at least once in the
full simulation set.
As with rapid, there is no eventually assertion in the Antithesis SDK.
Liveness requires bounds and using a timeout for this is not a good idea within
Antithesis as the fuzzer will simply learn to fault inject for a longer period
of time to violate the assertion. Instead, the eventually_ test commands
[9]
can be used. This command is only invoked once fault injection is stopped and
can be used to verify the system reaches a desired state after no faults are
present. Most liveness properties will only hold when no faults are being
injected.
Our completeness property is a good example. Under faults, a List served by
Auth may legitimately be missing items the backend already has: the cache may
still be catching up, or be unhealthy altogether. Once faults stop, Auth must
eventually serve exactly what is in the backend. The
eventually_auth_consistent command checks this for every resource kind by
listing all items through Auth and directly from the backend, and comparing the
two:
// authOps lists through the Auth service (served from the cache).
// backendOps reads the backend directly. ListAll pages through every item.
eventually.Assert(ctx, eventually.AssertParams{
Message: "auth resources are eventually consistent with the backend",
Timeout: cacheConsistencyTimeout,
Details: map[string]any{"kind": kind},
Condition: func(ctx context.Context, _ eventually.AddDetailFunc) (bool, error) {
authItems, err := crud.ListAll(ctx, authOps, 0)
if err != nil {
return false, trace.Wrap(err, "listing auth resources")
}
backendItems, err := crud.ListAll(ctx, backendOps, 0)
if err != nil {
return false, trace.Wrap(err, "listing backend resources")
}
return crud.EqualResourceSlices(backendItems, authItems, backendOps.Equal), nil
},
})
This check, together with a reachability assertion to ensure it runs in our tests, gives us the confidence that the cache is eventually consistent regardless of what faults and workloads ran against the cluster.
Key takeaways
In this post we have explored two different approaches to properties. Formal
properties, safety and liveness, describe how a whole system behaves over time.
PBT properties describe the relationship between a function's input and its
output. Using Teleport's List RPCs as an example, we derived a set of
properties from our design documents without writing a line of code, then checked them in
two very different ways: rapid fuzzed the inputs to genericLister, and
Antithesis fuzzed a full Teleport cluster.
My biggest takeaway from this exercise is that tooling is not the challenging part of thinking in properties. Once you can successfully determine a set of properties for your problem, the methodology follows from the scope of the problem being solved. Regardless of which tools you choose to adopt in your workflow, the properties of the system being tested will remain useful.
You may have noticed that this post skipped the most formal option: we never wrote a model of pagination. We'll follow up next week with a post covering how we've been using formal methods to fix bugs.
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.
References
- L. Lamport, Proving the Correctness of Multiprocess Programs, 1977.
- B. Alpern and F. B. Schneider, Defining Liveness, 1985.
- J. Hughes, How to Specify It!
- rapid
- testify
- A. Pshenichkin, So you think you want to write a deterministic hypervisor?
- Antithesis: Assertions
- Antithesis: Generating randomness
- Antithesis: Test Composer reference