How type and spec systems will take your job

Andrii Melnikov

What are our goals?

Whoever thinks that the products of programmers are the programs they write is deeply mistaken. A programmer must produce trustworthy solutions and present them in the form of convincing arguments; the text of the program is merely accompanying material to which those arguments apply.

— Edsger W. Dijkstra (paraphrased)

An argument is a proof

The single source of truth

function sum(a, b) {
  return parseInt(a, 10) + parseInt(b, 10)
}

But truth is fleeting

Everything flows, everything changes

— Heraclitus

The whole is greater than the sum of its parts

— Aristotle

 function sum(a, b) {
-  return parseInt(a, 10) + parseInt(b, 10)
+  return summator(prepareArgs(a, b))
 }

Change and impermanence are built into the very reason code exists.

Observe, don't fight

A flower needs time to grow. So there's no need to strain — better to observe.

— Yongey Mingyur Rinpoche

VCS?

 function sum(a, b) {
-  return parseInt(a, 10) + parseInt(b, 10)
+  return summator(prepareArgs(a, b))
 }

A bit of fun linguistics: change comes from the same root as exchange.

Exchange

What is good and what is bad?

Behaviour:

  • desired (sum(2, 2) returns 4)
  • undesired (sum(2, 2) returns something that isn't a number)

Its proofs:

  • proof of the absence of some undesired behaviour — a safety property
  • proof of the presence of some desired behaviour — a liveness property

Behaviour

!exists(!safe) ≡ all(liveness) ⇒ all(safe) ≡ all(liveness)

The program works correctly

describe('sum', () => {
  it('2 + 2 = 4', () => expect(sum(2, 2)).toBe(4))
})

How many tests are enough?

…or does it?

Program testing can be used to show the presence of bugs, but never to show their absence!

— Edsger W. Dijkstra

A program is a function

f(x) = y

A test checks the function at one point

f(2) = 1

The set of points a program is defined on is usually close to infinite.

Mathematicians vs programmers

Mathematicians

  • domain and codomain
  • properties (parity, monotonicity, etc.)
  • values at specific points (inflection points, extrema, and just some random points)

Programmers

  • values at specific points

Analysing a function

At least don't break anything

  • the sum of non-negative numbers is at least each summand: a + b >= a && a + b >= b
  • sorting is idempotent: sort(sort(x)) ≡ sort(x)
  • reverse is its own inverse: reverse(reverse(str)) ≡ str
  • sorting doesn't change a list's length: length(sort(x)) ≡ length(x)
  • the sum of two numbers is a number: typeof sum(a, b) ≡ 'number'

There are two ways…

Prove the property statically with Coq / Agda / TLA+ / Lean

Mathematician

Just check the property on very many random points

∀ x ∈ random() × 1000

Property-based testing

Steps:

  • describe the property as a check, a.k.a. invariant, a.k.a. contract
  • generate lots of different arguments for a function (or a set of functions)
  • check that the property holds for all of them

Libraries:

  • testcheck.js (a port of Clojure's test.check)
  • jsverify

Back to real life

function convertFrom(structFromBackend) {
  ...
  return structForFrontend;
}
function convertTo(structForFrontend) {
  ...
  return structFromBackend;
}
function isRevertable(structFromBackend) {
  var structForFrontend = convertFrom(structFromBackend);
  var structForBackend = convertTo(structForFrontend);

  expect(structFromBackend).toEqual(structForBackend);
}

How do you make a family?

jsc.string // generates strings
jsc.record({ ... }) // generates records
jsc.elements([ ... ]) // picks one of the elements
jsc.oneof([ ... ]) // uses one of the generators
import * as jsc from 'jsverify'

var familyInfoGen = jsc.record({
  type: jsc.elements(['espoused', 'single', 'common_law_marriage', undefined]),
  members: jsc.array(
    jsc.record({
      role: jsc.elements(['sibling', 'child', 'parent', 'spouse']),
      fio: jsc.record({
        firstname: jsc.oneof([jsc.string, jsc.undefined]),
        lastname: jsc.oneof([jsc.string, jsc.undefined]),
        middlename: jsc.oneof([jsc.string, jsc.undefined])
      }),
      dependant: jsc.oneof([jsc.boolean, jsc.undefined])
    })
  )
});

No polygamy — dynamic constraints

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

smap maps the elements of the generated sequence through a function:

var familyInfoGenFixed = familyInfoGen
  .smap(dropManySpouseOrFixMaritalStatus, identity);

Defaults

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

Difference:

- Expected
+ Received

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

Let's change the check

import { Record, Literal as L, Union, Array, Boolean, String, Void } from 'runtypes'

const FamilyStruct = Record({
  type: Union(L('espoused'), L('single'), L('common_law_marriage'), Void),
  members: Array(
    Record({
      role: Union(L('sibling'), L('child'), L('parent'), L('spouse')),
      fio: Record({
        firstname: String.Or(Void),
        lastname: String.Or(Void),
        middlename: String.Or(Void)
      }),
      dependant: Boolean.Or(Void)
    })
  )
})
const FamilyWithSingleSpouse = FamilyStruct.withConstraint(
  isSingleSpouse,
  { tag: 'FamilyStructWithSingleSpouse' }
)

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

  expect(FamilyWithSingleSpouse.guard(structForBackend)).toBe(true);
}

With one flick of the wrist, the validator turns into… a generator!

import { addTypeToRegistry, makeJsverifyArbitrary } from 'runtypes-generate';

addTypeToRegistry(
  'FamilyStructWithSingleSpouse',
  () => makeJsverifyArbitrary(FamilyWithSingleSpouse)
    .smap(dropManySpouseOrFixMaritalStatus, x => x)
);
jsc.assert(
  jsc.forall(makeJsverifyArbitrary(FamilyWithSingleSpouse), isSameShape)
)

This reminds me of something…

type Family = {
  type: 'espoused' | 'single' | 'common_law_marriage' | undefined | null,
  members: Array<{
    role: 'sibling' | 'child' | 'parent' | 'spouse',
    fio: {
      firstname: string | undefined | null,
      lastname: string | undefined | null,
      middlename: string | undefined | null
    },
    dependant: boolean | undefined | null
  }>
}
function convertFrom(structFromBackend: Family): ConvertedFamily {}
function convertTo(structForFrontend: ConvertedFamily): Family {}

A digression: what are static types?

Type annotations aren't just part of a language — they're a separate language.

It can be Turing-complete:

With static typing we write code in two languages: one does something, and the other makes sure the first doesn't do anything extra.

Programming with computations at the level of the type system is called type-level programming.

Example: natural numbers

interface Nat {
  prev?: any
  isZero: 'true' | 'false'
}

interface Positive {
  prev: Positive | _0
  isZero: 'false'
}

type Succ<N extends Positive | _0> = { prev: N; isZero: 'false' }

type _0 = { isZero: 'true' }
type _1 = Succ<_0>
type _2 = Succ<_1>

This trick is known as Church numerals (strictly speaking, Peano-style numbers).

But there's a small problem…

// v1 :: Vector<_1, number>
const v1 = Vector.create([1])
// v2 :: Vector<_2, number>
const v2 = Vector.create([2, 3])
console.log(v2.zip(v1.append(v1))) // Vector([[2,1],[3,1]])

v2.zip(v1) // error

[ts]
Argument of type 'Vector<Succ<Succ<_0>>, number>' is not assignable to parameter of type 'Vector<Succ<Succ<Succ<_0>>>, number>'.
  Type 'Succ<Succ<_0>>' is not assignable to type 'Succ<Succ<Succ<_0>>>'.
    Types of property 'prev' are incompatible.
      Type 'Succ<_0>' is not assignable to type 'Succ<Succ<_0>>'.
        Types of property 'prev' are incompatible.
          Type '_0' is not assignable to type 'Succ<_0>'.
            Property 'prev' is missing in type '_0'.

gcanti/typelevel-ts

An alternative?

Dependent types built into the compiler: Coq, Agda, Idris — types restricted down to values

function add<A extends Nat, B extends Nat>(
  a: A, b: B
): Add<A, B>

THEOREM PROVING IN DA HOUSE!

Refinement (liquid) types built into the compiler:

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

Outside research projects they don't really exist yet:

Static vs dynamic

mean(list) = divide(sum(list), length(list)) — prove that it returns a number for any list of numbers.

Statically:

sum(list: number[]): number
length(list: number[]): number
div(a: number, b: number): number
mean(list: number[]): number

Proof by construction, a.k.a. verification (from verus — true).

The way the program is built guarantees a property.

Dynamically:

jsc.forall(
  [jsc.array(jsc.number)],
  list => isNumber(mean(list))
)

Proof by results, a.k.a. validation (from valere — to be worth).

The result of running the program has a property.

The proof cube

Proof cube

Example

Proof cube example

A glass wall between worlds

Static (by construction):

  • rely on the program's structure and source code
  • give a 100% guarantee
  • don't require running the program
  • require every intermediate part to be built fully correctly and consistently

Dynamic (by results):

  • rely only on the program's output
  • give only probabilistic guarantees
  • don't need access to the source code
  • it doesn't matter how the program is built — only input and output matter

Exchange with proofs

Remember the example

const FamilyStruct = Record({
  type: Union(L('espoused'), L('single'),
    L('common_law_marriage'), Void),
  members: Array(
    Record({
      role: Union(L('sibling'), L('child'),
        L('parent'), L('spouse')),
      fio: Record({
        firstname: String.Or(Void),
        lastname: String.Or(Void),
        middlename: String.Or(Void)
      }),
      dependant: Boolean.Or(Void)
    })
  )
})
type Family = {
  type: 'espoused' | 'single'
    | 'common_law_marriage' | undefined | null,
  members: Array<{
    role: 'sibling' | 'child'
      | 'parent' | 'spouse',
    fio: {
      firstname: string | undefined | null,
      lastname: string | undefined | null,
      middlename: string | undefined | null
    },
    dependant: boolean | undefined | null
  }>
}

Breaking the wall

import { Static } from 'runtypes'

type Family = Static<typeof FamilyStruct>

From a single description of the data (a spec) we get:

  • a dynamic validator for data from the outside (untyped) world and for complex checks that can't be expressed statically
  • a data generator for property tests
  • a static type for the type checker at compile time

Dynamic vs static proof is now just a matter of tactics:

Static proof — is the code's internal structure stable and won't be rewritten soon?

Dynamic proof — will the code most likely be rewritten many times soon (prototype stage)?

Example (any resemblance is purely coincidental!)

Task: a new module that computes the mean of a list of numbers.

TypeScript, --allowJs

function meanFn(list) {
  return divide(sum(list), length(list))
}

Step 1. Prototype

The module is experimental; business changes and refactorings are likely. Stage: active development.

mean.js

import { Contract, Array, Number } from 'runtypes';

const meanConstraint = ([list], result) =>
  result >= min(list) && result <= max(list)
export const MeanSpec = Contract(Array(Number), Number)
  .withConstraint(meanConstraint);
export const mean = MeanSpec.enforce(meanFn)

mean.test.js

import { makeJsverifyArbitrary } from 'runtypes-generate';
import { MeanSpec, mean } from './mean';

jsc.assert(jsc.forall(
  [makeJsverifyArbitrary(MeanSpec.reflect.argsTypes)],
  list => mean(list)
))

Step 2. Stable structure

The module's internal structure has stabilised. Stage: maintenance.

mean.js → mean.ts

function sum(list: number[]): number
function length(list: number[]): number
function div(a: number, b: number): number

If requirements change drastically — say, we need the median instead of the mean: mean.ts → mean.js and back to step 1, practically without losses.

What else useful can we come up with?

Generating tests from run time

mean.js

export const mean = trace('module/mean', meanFn)

When the application exits, or on a special signal:

import { mean } from './mean.js'
import convert from 'call-to-jasmine-test'

mean.calls // array of calls made while the app was running
convert(mean.calls) // code of jasmine test cases
/*
  it(1, () => expect(mean([1, 2, 3])).toEqual(2))
  ...
*/

Generating types from run time

import { mean } from './mean.js';
import infer from 'runtypes-infer'

mean.calls // array of calls made while the app was running
infer(mean.calls) // type description for runtypes
/*
  Contract(Array(Number), Number)
*/

Automatic annotations — only for Clojure :(

Auto pipeline

The ideal bottom-up pipeline

  1. Write the code (a prototype)
function mean(list) {
  return divide(sum(list), length(list))
}
  1. Test it a bit by hand — collect a list of calls
[[1, 2, 3], 2], ...
  1. Get tests from the run-time calls — extend or fix them if needed
describe(() => it(() => expect(mean([1, 2, 3])).toEqual(2)))

The ideal bottom-up pipeline

  1. Generate type specs from them
const MeanSpec = Contract(Array(Number), Number)
  1. Run generated tests against them — discover edge cases
jsc.assert(jsc.forall(
  [makeJsverifyArbitrary(MeanSpec.reflect.argsTypes)],
  list => mean(list)
))
  1. Once the code is stable — switch to static mode and add the missing static types: mean.js → mean.ts

Automatically proving versioning is correct

Semantic Versioning — also see ComVer

SemVer

Automatically proving versioning is correct

How do you prove a change is backwards compatible?

Dynamically: Cracks

Run the previous version's tests against the new one

semantic-release

Statically: elm-package

Compare the function signatures of the previous and new versions

Elm semver

Problems?

mean.ts

We had tests:

it(() => expect(mean([1, 2, 3])).toBe(2))
it(() => expect(mean([])).toBe(0))

And types:

function mean(list: number[]): number

But this change goes unnoticed:

 function mean(list) {
-  return meanFn(list)
+  return medianFn(list)
 }

Solution — combine the approaches

  1. We have a type description: const MeanSpec = Contract(Array(Number), Number)
  2. Check that the result hasn't changed for any input
import { mean as prevMean, MeanSpec as prevSpec } from 'project-prev/mean';
import { mean as currMean, MeanSpec as currSpec } from 'project-curr/mean';

// the specs themselves haven't changed (the "static" approach)
assert(isEqualSpec(prevSpec, currSpec))

jsc.assert(
  jsc.forall(
    [makeJsverifyArbitrary(prevSpec.reflect.argsTypes)],
    // and neither have the results (the "dynamic" approach)
    list => prevMean(list) === currMean(list)
  )
)
  1. PROFIT!

Refinement types

Dynamic:

Number.withConstraint(v => v >= 0)

How do you generate data of such a type?

An interesting paper with a possible solution

Static:

{ v: number | 0 ≤ v }

How do you check it statically?

Refinement Types for TypeScript

Type Spec-driven development

User page · in list To Do: Frontend

Build the user page. API request GET /userInfo:

{ fio: { lastname: 'Ivanov', firstname: 'Ivan' }, balance: 1000000 }

Displayed result: Name: Ivan Ivanov · Balance: 1 000 000 ₽

If the API returns invalid data, show a placeholder: An unexpected error occurred

Now let's try the top-down approach.

What do we want to get?

The overall spec:

type App = {
  {
    fio: {
      firstname?: string,
      lastname?: string
    } | !isEmpty v.lastname || !isEmpty v.firstname,
    balance: PositiveNumber
  }: {
    fio: FioString,
    amount: AmountString
  };
  any: HtmlError
}

Cases:

expect(app({
  fio: { lastname: 'Ivanov', firstname: 'Ivan' },
  balance: 1000000
})).toEqual({
  fio: 'Ivan Ivanov',
  amount: '1000000 ₽'
})
...

Find what you can't name

Rambo for Ramda

const solve = require('rambo').solve
const solution = solve([1, 2, 3, 4], [5, 6, 7, 8])
console.log(solution.name) // "R.map(R.add(4))"

Combining the approaches

  1. Somehow break the type mappings into the smallest pieces
{ firstname?: string, lastname?: string }
  | !isEmpty v.lastname || !isEmpty v.firstname
  -> FioString
PositiveNumber -> AmountString
...
  1. Search the project and its libraries for matching specs
formatFio(
  { firstname?: string, lastname?: string }
): FioString
formatAmountRub(x: number): AmountString
  1. Assemble a possible implementation
  2. Check it against the cases — if not OK, back to step 1
  3. Bolt on machine learning
  4. ???
  5. PROFIT

See also: Exference, Djinn

A plan for laying off most programmers

A well-posed question is half the answer

  1. Dynamic proofs
    • improve runtypes-generate, io-ts-generate
    • generate data from predicates (refinement types)
  2. Static proofs

A plan for laying off most programmers

  1. Finish breaking the wall between dynamic and static properties
  2. Bottom-up
    • tracing calls of entities (e.g. React components)
    • generating tests from traces
    • inferring types from traces
  3. Top-down
    • searching specs across the project (a DB) or npm, validated by tests — a Hoogle for TypeScript
    • AI

Appendix

Generator

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

Property

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

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

Checker

function assert(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)
      );
    }
  }
}

Into the test!

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

Hidden vs observable change

var a = { a: 1 };
changeObj(a) // hidden change

var a = { a: 1 };
var changedA = changeObj(a) // observable change

FRP:

var getCurrentUnixTimeWithDelay = () => Time.now() + 5
getCurrentUnixTimeWithDelay()
...
// hidden change
getCurrentUnixTimeWithDelay()

var time = Time.toBehavior()
var withDelay = time.map(now => now + 5)
// observable change
withDelay.sample(Time.interval(1)).subscribe(x => console.log(x))

Solutions?

I don't know

  1. SMT (satisfiability modulo theories) solving
  2. Moving to dependent types — more general, but less convenient for programmers

Dynamic: Min(Number, 0)

Static: Min<Number, _0>

Managers' secret dreams xD

Pinky and the Brain

← Andrii MelnikovHow type and spec systems will take your jobarticlevideo ↗1 / 55