25 April 2017

What's your proof?

Programmers check their code at a handful of points; mathematicians reason about whole domains. Property-based testing, specs that double as generators, and where static types fit in.

Translated from Russian · originalslidestalk video ↗

Hi. I’m Andrii, and today I’d like to talk about evaluating and proving properties of software. What is a programmer’s job? One of the most popular answers is: to provide a solution to an existing problem. An integral part of that process is analysing the solution we’ve built — trying to understand what we actually got, what its limitations and scope are, and which trade-offs it makes. In other words, how well it solves the original problem and how many new problems it adds.

Today most of that analysis happens in informal terms: “this solution is unreliable”, “this code is hard to read”, “it’s hard to test”, and so on. For formal analysis we mostly use various kinds of tests based on test cases. Informal analysis doesn’t interest us right now — it is closer to philosophy and sophistry than to the exact sciences. So let’s focus on testing, and look at it from the point of view of an exact science — mathematics.

Mathematicians, like programmers, create solutions and analyse them. Take the analysis of functions as an example (functions are the closest thing to programs). What is a test case from the point of view of function analysis? It’s a point — an input value — of the function. A test, accordingly, is an analysis of the function’s behaviour at that point. (The points are usually not chosen at random, but in regions where the function behaves differently; that’s what code-coverage information is typically used for.)

Studying a function’s behaviour at certain important points is an integral part of mathematical analysis. But mathematicians also spend a lot of time analysing properties that hold over the entire domain — for example, that addition is associative, commutative, and so on.

Analysing a function: points vs. properties

Programs, like mathematical functions, are usually defined on a huge number of values (close to infinite). Yet for some reason programmers aren’t interested in the properties of their programs beyond specific points — test cases. As a result, we can’t say anything definite about how the program behaves at all the other points. How do we fix that?

A simple example

Let’s start with an example from basic arithmetic, and then move on to something more practical. Take ordinary addition. As I mentioned, addition has many properties. For instance, the sum of two non-negative numbers is always greater than or equal to each of the summands.

That is, for any a and b greater than or equal to zero, a + b >= a && a + b >= b holds. In JavaScript the property can be written as a function:

function (a, b) {
  return a + b >= a && a + b >= b
}

All that’s left is to prove it. What are our options?

  • Go the mathematician’s way: surround ourselves with Coq, Agda, TLA+, Lean and other theorem-proving tools, and in a couple of years we might be able to verify this property.
  • As usual in programming, unlike mathematicians, we can cut a few corners and simply check the property very many times on different values.

That’s pretty easy to do. First, let’s write a generator of the values we need:

function genPosNumber() {
  return Math.random() * 10000000000
}

Then a function that takes generators and a property and builds a property check:

function property(argGenerators, propertyFn) {
  return function () {
    var generatedArgs = argGenerators.map((gen) => gen())

    return {
      success: propertyFn(...generatedArgs),
      args: generatedArgs,
    }
  }
}

And finally, a function that checks the property a given number of times (100 by default):

function check(property, tries = 100) {
  for (var i = 0; i < tries; i++) {
    var res = property()
    if (!res.success) {
      throw new Error('Property hasnt held on arguments: ' + JSON.stringify(res.args, null, 2))
    }
  }
}

Now we can write a test for our property:

it('forall a, b - a + b >= a && a + b >= b', () => {
  check(
    property([genPosNumber, genPosNumber], function (a, b) {
      return a + b >= a && a + b >= b
    }),
  )
})

The obvious question: did we need to write any of this, or has it all been written before us? Yes — it all exists already.

This approach is called property-based testing (a.k.a. QuickCheck tests, property tests, generative testing). It originated in the Haskell community. Today there are implementations for practically every language, JavaScript included. In the examples I’ll use testcheck-js, which integrates with Jest and is actually a binding to test.check, written in ClojureScript. With it, our example looks like this:

var testcheck = require('testcheck')
var gen = testcheck.gen

it('forall a, b - a + b >= a && a + b >= b', () => {
  testcheck.check(
    testcheck.property([gen.posInt, gen.posInt], function (a, b) {
      return a + b >= a && a + b >= b
    }),
  )
})

Overall almost nothing changed, except that we now use ready-made functions and generators instead of hand-written ones. Let’s move on to a harder example.

A harder example

The frontend almost always operates on entities that came from the backend, and often, to make them more convenient to use, we have to change their structure. That’s simple enough: we get a function convertFrom that converts a structure (say, data about a family) into a shape convenient for display.

function convertFrom(structFromBackend) {
  ...
  return structForFrontend;
}

But some entities aren’t only displayed — they’re also edited. Then we also need a convertTo function that converts the structure from the frontend representation back to the original one, which we can save on the backend.

function convertTo(structForFrontend) {
  ...
  return structFromBackend;
}

You’ve probably already noticed a property of these two functions: convertTo is the inverse of convertFrom. That is, for any a, convertTo(convertFrom(a)) is equivalent to a.

Let’s write this property in JavaScript:

function isRevertable(structFromBackend) {
  var structForFrontend = convertFrom(structFromBackend)
  var structForBackend = convertTo(structForFrontend)

  expect(structFromBackend).toEqual(structForBackend)
}

Now we need a generator for structFromBackend. Testcheck already has a large set of built-in generators, and by combining them we can build new ones. For example:

gen.int // generates integers
gen.array // generates arrays
gen.array(gen.int) // generates arrays of integers

What does our structure (family data) consist of?

  • type — one of espoused, single, common_law_marriage, undefined;
  • members — an array of objects shaped like this:
    • role — one of sibling, child, parent, spouse;
    • fio — an object with the keys firstname, lastname, middlename;
    • dependant — boolean or undefined.

Let’s start with type, using the generator docs. For enumerations there is the returnOneOf generator:

gen.returnOneOf(['espoused', 'single', 'common_law_marriage', undefined])

Now the hardest part — the generator for a member object. We’ll build the generator for role with the returnOneOf we’ve already used:

gen.returnOneOf(['sibling', 'child', 'parent', 'spouse'])

For dependant we take the gen.boolean and gen.undefined generators and combine them with gen.oneOf:

// oneOf takes several generators and returns a generator
// that randomly uses one or the other
gen.oneOf([gen.boolean, gen.undefined])

For fio we use gen.object combined with gen.string and gen.undefined:

gen.object({
  firstname: gen.oneOf([gen.string, gen.undefined]),
  lastname: gen.oneOf([gen.string, gen.undefined]),
  middlename: gen.oneOf([gen.string, gen.undefined]),
})

Putting it all together:

var familyInfoGen = gen.object({
  type: gen.returnOneOf(['espoused', 'single', 'common_law_marriage', undefined]),
  members: gen.array(
    gen.object({
      role: gen.returnOneOf(['sibling', 'child', 'parent', 'spouse']),
      fio: gen.object({
        firstname: gen.oneOf([gen.string, gen.undefined]),
        lastname: gen.oneOf([gen.string, gen.undefined]),
        middlename: gen.oneOf([gen.string, gen.undefined]),
      }),
      dependant: gen.oneOf([gen.boolean, gen.undefined]),
    }),
  ),
})

Let’s check it:

var sample = require('testcheck').sample

console.log(JSON.stringify(sample(familyInfoGen, { times: 2 }), null, 2))
/*
[
  {
    "type": "espoused",
    "members": []
  },
  {
    "members": []
  }
]
*/

And here’s the first problem. Sometimes we generate structures without a spouse but with type === 'espoused'. That’s impossible — the backend can’t send us data like that. How can we constrain or transform the generated sequence according to some rule? There are two options:

  • suchThat — filters the generated sequence by a predicate. Not a great fit: it increases the number of generation attempts, which slows the tests down;
  • map — maps the elements of the generated sequence through some function.

Let’s see how we can use map for our purposes. First, the rules:

  • There can be only one spouse;
  • If there is one, then type === 'espoused';
  • If type !== 'espoused', there must be no spouse.

And so we write:

function mapFamily(familyObject) {
  // find all spouses
  var spouse = familyObject.members.filter((member) => member.role === 'spouse')
  // married, but no spouse
  if (familyObject.type === 'espoused' && spouse.length === 0) {
    return {
      type: familyObject.type,
      members: [
        // so add one
        { role: 'spouse', fio: {} },
        ...familyObject.members,
      ],
    }
    // not married, but there is a spouse
  } else if (familyObject.type !== 'espoused' && spouse.length !== 0) {
    return {
      type: familyObject.type,
      // remove them
      members: familyObject.members.filter((member) => member.role !== 'spouse'),
    }
    // more than one spouse: keep only the first
  } else if (spouse.length > 1) {
    return {
      type: familyObject.type,
      members: familyObject.members.reduce(
        (acc, member) => {
          if (member.role !== 'spouse') {
            acc.members.push(member)
          } else if (!acc.hasSpouse) {
            acc.members.push(member)
            acc.hasSpouse = true
          }
          return acc
        },
        { members: [], hasSpouse: false },
      ).members,
    }
  }
  // the structure is valid: return it unchanged
  return familyObject
}

Apply it to our generator:

var familyInfoGenFixed = gen.map(mapFamily, familyInfoGen)

Check:

console.log(JSON.stringify(sample(familyInfoGenFixed, { times: 2 }), null, 2))
/*
[
  {
    "type": "espoused",
    "members": [
      {
        "role": "spouse",
        "fio": {}
      }
    ]
  },
  {
    "type": "common_law_marriage",
    "members": [
      {
        "role": "child",
        "fio": {
          "firstname": "&",
          "lastname": "",
        }
      }
    ]
  }
]
*/

Now the generated objects definitely meet our requirements, and we can move on to checking the property itself. We’ll use the check.it helper from the jasmine-check package: it takes a description of the property, an array of generators, and the property as a function.

require('jasmine-check').install()

check.it('convertTo is revert function for convertFrom', [familyInfoGenFixed], isRevertable)

But the property check fails:

● convertFrom and convertTo properties
  › convertFrom -> convertTo save original shape (
    {"type":"single","members":[{"role": "sibling", "fio": {}}]}
  )

expect(received).toEqual(expected)

Expected value to equal:
  {"type":"single","members": Array [
    {"role": "sibling", "fio": Object {}}
  ]}
Received:
  {"type":"single","members": Array [
    {"role": "sibling", "fio": Object {}, "dependant": false}
  ]}

Difference:

- Expected
+ Received

  Object {
    "type":"single"
    "members": Array [
      Object {
        "role": "sibling",
        "fio": Object {},
+       "dependant": false
      }
    ]
  }

The thing is, besides converting one structure into another, convertFrom also fills in some default values (false for dependant) — it doesn’t preserve the original values. What do we do?

Solution #1 — the complicated one

What follows is a lot of code hacked together in a short time as a proof of concept. It’s here only to illustrate an idea, not to be used as is.

The first thing that comes to mind: yes, the values change, but the structure stays the same. So we can weaken the property and check not for exact equality but for the structure being preserved:

function isSameShape(structFromBackend) {
  var structForFrontend = convertFrom(structFromBackend)
  var structForBackend = convertTo(structForFrontend)

  expect(checkFamilyStruct(structForBackend)).toBe(true)
}

All that’s left is to write checkFamilyStruct.

Hmm, but wait. We’ve already described the structure of our data! In the generator we described both the types and the various constraints (in mapFamily). Can we somehow reuse the generator to validate the shape of the result? Probably not. We’d have to analyse the generator’s internal structure, and it’s rather intricate (it’s written in ClojureScript, after all).

What we can do is what programmers love doing most — invent a new API for describing data structures, one that gives us both a generator and a validator. And let’s make it look like React.PropTypes, because we all love React so much.

The only new method will be .invariant, responsible for transforming the generated sequence (remember .map).

Using our API should look like this:

const makeFamilySpec = (spec) =>
  spec
    .shape({
      type: spec.oneOf(['espoused', 'single', 'common_law_marriage']),
      members: spec.arrayOf(
        spec.shape({
          role: spec.oneOf(['sibling', 'child', 'parent', 'spouse']).isRequired,
          fio: spec.shape({
            firstname: spec.string,
            lastname: spec.string,
            middlename: spec.string,
          }),
          dependant: spec.bool,
        }).isRequired,
      ),
    })
    .invariant(mapFamily)

Now we need to define the spec object — once for the validator and once for the generator. For validation I’ll use Jest’s expect, simply because it was at hand. Obviously any data-validation library would do, and the format of the description could be anything.

First, the overall shape of the validator API:

const jestSpec = {
  // specJest is just a wrapper that adds all the necessary methods
  string: specJest((actual) => expect(isString(actual)).toBe(true)), // for primitives we just check the type
  bool: specJest((actual) => expect(isBoolean(actual)).toBe(true)),
  oneOf: (list) => specJest((actual) => expect(list).toContainEqual(actual)),
  shape: (shape) =>
    specJest((actual) => {
      expect(isPlainObject(actual)).toBe(true)
      keys(shape).forEach((key) => {
        // for an object we check that every key matches its description
        shape[key](actual[key])
      })
    }),
  arrayOf: (itemSpec) =>
    specJest((actual) => {
      expect(isArray(actual)).toBe(true)
      // for an array we check the elements it contains
      actual.forEach((item) => itemSpec(item))
    }),
}

Now the same for the generator:

export const genSpec = {
  // specGen is just a wrapper that adds all the necessary methods
  string: specGen(gen.asciiString),
  bool: specGen(gen.boolean),
  oneOf: (list) => specGen(gen.returnOneOf(list)),
  shape: (shape) => specGen(gen.object(shape)),
  arrayOf: (itemSpec) => specGen(gen.array(itemSpec)),
}

Next we implement the wrappers that add the extra methods. Since most of the code is shared between the validator and the generator, we’ll move it into a makeSpecable function. It takes two functions that contain the generator- or validator-specific logic:

  • makeNotRequired — defines how to make an optional generator/validator out of the one we were given.

That one’s simple. For the validator:

;(check) => (actual) => isUndefined(actual) || check(actual)

For the generator:

;(generator) => gen.oneOf([gen.undefined, generator])
  • makeInvariant — defines how to add a constraint, expressed as a custom function, to a generator/validator.

We’ve already done this for the generator — it’s our familiar .map:

;(generator, func) => gen.map(func, generator)

The validator is trickier. What does mapFamily actually do? It brings a structure into a valid shape. And what does it do to a structure that has no violations? Right — nothing, it leaves it unchanged. So we can check: if mapFamily didn’t change anything, the structure was valid:

expect(mapFamily(familyStruct)).toEqual(familyStruct)

Armed with this idea, let’s write makeInvariant for the validator:

;(check, func) => (actual) => {
  expect(func(actual)).toEqual(actual)
  check(actual)
}

And finally makeSpecable, which adds the methods:

const makeSpecable = (makeNotRequired, makeInvariant) => (specable) => {
  const notRequired = makeNotRequired(specable)
  notRequired.isRequired = specable
  notRequired.invariant = (func) => makeInvariant(specable, func)
  return notRequired
}

Let’s check:

const checkFamilyStruct = makeFamilySpec(jestSpec)
const generatorFamilyStruct = makeFamilySpec(genSpec)

describe('convertFrom and convertTo properties', () => {
  check.it(
    'convertFrom -> convertTo save original shape',
    [generatorFamilyStruct],
    (structFromBackend) => {
      const structForFrontend = convertFrom(structFromBackend)
      const structForBackend = convertTo(structForFrontend)
      checkFamilyStruct(structForBackend)
    },
  )
})

Hooray, it works! Gist with the full code.

Of course, the idea of having a single description of the data and deriving both validators and generators from it isn’t mine. It’s exactly what a fairly new technology — clojure.spec — is built on, which in turn drew inspiration from Racket’s contract system.

The Automatic annotations project for Clojure goes even further. Its authors propose analysing unit tests dynamically, inferring possible constraints on the data from them, and then using those constraints both for compile-time checks with core.typed (an optional type system for Clojure) and for run-time checks with clojure.spec.

On the other hand, the Haskell community has approaches where property tests are generated from the types in the program. Here’s an interesting talk on the subject.

Just as types can help write tests, tests can help write types — there is clearly some connection between them.

Solutions like these let us check simple constraints (for instance, that we don’t pass strings to a function that adds numbers) statically — with instant feedback — and check complex properties (say, that a user’s balance never goes negative whatever operations are applied, or that serialising and deserialising any value returns the original) dynamically, with generative tests. That’s slower, of course, but doesn’t require complex type systems with dependent and refinement types.

Types, you say?

Readers familiar with statically typed languages may already have noticed how similar the specs we used to describe a user’s family are to type declarations in static languages.

Compare:

const makeFamilySpec = (spec) =>
  spec
    .shape({
      type: spec.oneOf(['espoused', 'single', 'common_law_marriage']),
      members: spec.arrayOf(
        spec.shape({
          role: spec.oneOf(['sibling', 'child', 'parent', 'spouse']).isRequired,
          fio: spec.shape({
            firstname: spec.string,
            lastname: spec.string,
            middlename: spec.string,
          }),
          dependant: spec.bool,
        }).isRequired,
      ),
    })
    .invariant(mapFamily)

with this TypeScript:

interface FamilySpec {
  type?: 'espoused' | 'single' | 'common_law_marriage'
  members: Array<{
    role: 'sibling' | 'child' | 'parent' | 'spouse'
    fio?: {
      firstname?: string
      lastname?: string
      middlename?: string
    }
    dependant?: boolean
  }>
}

You’ll agree the two declarations mean very nearly the same thing, even though the syntax differs. And our property is easy to write in TypeScript too:

function convertFrom(family: FamilySpec): FamilyConverted
function convertTo(familyConverted: FamilyConverted): FamilySpec

However, TypeScript’s type system gives us no way to express the mapFamily invariant that checks the structure, which greatly reduces the usefulness of our spec. But that’s a limitation of TypeScript and similar type systems specifically. There are refinement and dependent types that let you statically prove that a value satisfies some predicate. A simple example is the type of natural numbers:

type nat = { v: number | 0 ≤ v }

The check of a user’s family structure could be expressed in a similar way. It would be an entirely static check, guaranteed to hold at every point of the program. But we’d have to prove to the compiler that the property holds everywhere. For complex properties that can take more code than describing the application logic itself.

In the end, the whole difference between static and dynamic specifications comes down to this:

  • Static: checked with static verification tools and give a 100% guarantee that the code conforms to the spec. But by default they assume your code does not conform, and make you write a lot of extra code to prove that it does.
  • Dynamic: checked with generative testing (and other kinds of testing) and give only a probabilistic guarantee. By default the code is assumed to work according to the spec, and the spec is considered violated only if testing shows otherwise. No special code is needed to prove the code correct.

There is no fundamental contradiction between dynamic and static languages and type systems.

Perhaps the languages of the future won’t be divided into static and dynamic at all, but will simply let us control how strict our checks are, and how many of them there are, as a program evolves.

At stages where correctness isn’t critical (say, the prototype stage), we’ll make do with a small set of properties — partly inferred at run time from tests, partly written by us — and check them with property tests at run time. As we move to stages where correctness comes first (many users, lots of code, many developers), we’ll add more properties and start checking them with static verification tools (refinement and dependent types).

In the end, we’ll be able to check the same properties both statically and dynamically, depending on what matters more at a given stage of development — correctness, or speed and convenience.

Solution #2 — the simple one

But we’ve drifted off topic a little. Our goal was to prove that convertTo is the inverse of convertFrom, and the default values got in the way. Could we have solved this without weakening the property and without inventing a new API?

Yes, of course: we can simply move the filling-in of default values out of convertFrom into a separate setDefault function (run before or after convertFrom), and then convertFrom will satisfy the original property.

Sometimes beginner developers (like me, for example) rush to write code that solves a problem the moment it appears. It’s often worth stopping first to ask: “maybe this problem can be solved at a completely different level?” For example, by splitting a module’s API according to the guarantees each call provides — as in our case.

As is tradition, for those not yet tired of reading, a little homework: what property might setDefault satisfy? As a reminder, it fills in default values in a data structure where values are missing.

What makes it hard?

The hard part

Despite the obvious benefits, property-based tests aren’t very popular among developers, even though there are implementations for almost every programming language.

The reason is that properties suitable for this kind of checking are very hard to identify in typical production code. Why?

First, developers aren’t used to thinking about the properties their solution provides — so we design and build systems without relying on any properties at all. TDD and BDD have largely taught us to think and to develop in terms of individual scenarios: “if you input A, you get B” — in essence, individual “points”. It’s very hard to move from that discrete way of thinking to a more continuous one: “the property holds for any A from some set”. Only practice helps here, your own and other people’s: look for properties in your code and see how others do it (I’ve left links to great articles with examples below).

Second, you may have noticed that the functions we examined were pure (no side effects). Unfortunately, most frontend code consists of functions with side effects (from network calls to working with global state). It’s well known that functions with side effects are harder to test than pure ones, and identifying their properties is practically impossible. A side effect deals with something outside the boundaries of the entity under test, something whose properties are undefined by definition — its behaviour is unpredictable. There are approaches that separate side effects from the core code (the business logic) and keep it pure, but that’s a topic for a separate, long article.

  • Choosing properties for property-based testing — walks through many practical cases for property-based testing, with examples and even pictures. A must-read if you want to use the approach in practice.
  • JSVerify — another implementation of the approach, in plain JavaScript. I recommend it where possible: it’s much easier to debug than testcheck-js (stack traces don’t lead you off into the infinity of the ClojureScript runtime). It has a large set of built-in generators and supports asynchronous properties.
  • js.spec — a port of clojure.spec to JS. Still very raw and, out of the box, supports only validation, not generation from specs.
  • Applying Property Based Testing to User Interfaces — a good article on real-world use of property-based tests for UI testing (on the example of user state). It’s written for Om, but the same practices work for testing Redux applications.
  • Refinement Types for TypeScript — an interesting paper, as part of which a verifier for TypeScript programs based on refinement types was built.
  • LiquidHaskell — refinement types for Haskell, explained simply.

Finally, I’d like to say that property-based testing, like any other method of controlling program behaviour (static types, any other kind of testing, verification), pays off from the very moment you start applying it — because the developer starts thinking about how their code works and which properties and guarantees it provides. That alone reveals many problems, or simply leads to a better solution in terms of architecture and API. Don’t be afraid to try new practices for analysing your programs: even if you can’t adopt them for some reason, you may come to understand your code better.

Thanks for reading!