Property Testing (Two Cameras, One Juggler)
Two Cameras
PyCPU is a computer built from NAND gates, and it has two ways of running it. The gate engine is the real thing: every wire and every gate, one tiny step at a time. It is slow, like a slow-motion camera. The fast engine does the same job with plain Python numbers. It is quick, like a flip-book. (You can read about them in Two Engines.)
Now imagine a juggler filmed by both cameras at once. How would you check that neither camera is lying?
The usual way: ask the juggler to throw three balls, film it, and compare the two films. That is an example test. It is useful, but it only tells you about the one trick you thought of.
Now imagine a judge. They ask for thousands of different tricks: one ball, nine balls, a juggler who starts with a ball already in the air, one who drops everything on the first throw. After every single throw they hold the two films side by side and check one rule:
The two cameras show exactly the same picture.
That rule is a property. It doesn't say what any one trick looks like. It says something that must be true for every trick.
When the judge finds a trick where the pictures differ, they don't just report "something odd happened at the circus". They try again with less and less -- fewer balls, shorter tricks, simpler starts -- checking the cameras still disagree each time, until the trick is as small as it can be. That boiling-down is called shrinking, and it is the best part: the smallest failing input usually points straight at the bug.
In Python, the judge is a library called
Hypothesis. Most of the series keeps
its property tests in one file called tests/test_properties.py. PyCPU names
its tests by subject instead, so the property tests sit in the same file as
the example tests for the same part: tests/test_lockstep.py for the two
engines, tests/test_isa.py for instruction words, tests/test_assembler.py
for the assembler, and so on. Fifteen of the test files use Hypothesis. The
shared settings live in conftest.py at the top of the project.
A Property from PyCPU
The main property of the whole project is the two-cameras rule: the gate engine and the fast engine agree on the whole machine state after every step, whatever state you start from.
"The whole machine state" means everything: the program counter, the stack pointer, all the registers, the four flags, every word of memory, whether it has halted and why, and what it has printed. Here is the property:
states = st.builds(
MachineState,
pc=_word_near(EDGES),
sp=_word_near(EDGES),
registers=st.tuples(*[_word_near(EDGES)] * REGISTER_COUNT),
flags=st.builds(Flags, *[st.integers(0, 1)] * len(Flags._fields)),
memory=st.tuples(*[st.integers(0, WORD_MASK)] * WORDS),
halted=st.booleans(),
halt_code=st.integers(0, HALT_CODE_MAX),
output=st.lists(st.integers(0, WORD_MASK), max_size=MAX_OUTPUT).map(tuple),
)
def _run_side_by_side(gate: GateMachine, start: MachineState) -> MachineState:
"""Load `start` into both engines, step both, and fail at the first step they differ.
Return the final state, so a caller can check where the run ended.
"""
fast = FastMachine(WORDS)
fast.load_state(start)
gate.load_state(start)
assert gate.state() == fast.state()
for step in range(MAX_STEPS):
fast_moved = fast.step()
gate_moved = gate.step()
assert gate_moved == fast_moved, f"step {step}: one engine had already halted"
assert gate.state() == fast.state(), f"the engines differ after step {step + 1}"
if not fast_moved:
break
return fast.state()
@settings(max_examples=200, deadline=None)
@given(start=states)
def test_both_engines_agree_from_any_state(gate: GateMachine, start: MachineState) -> None:
"""From any loadable state, halted or not, both engines stay equal; a halted one stays put."""
_run_side_by_side(gate, start)
Line by line:
statesis a strategy: a recipe for making random inputs. This one makes a wholeMachineState, field by field. The flags are each 0 or 1. The memory is 64 random words. A state can even start already halted, with a made-up halt code._word_near(EDGES)is a strategy too, and it is there for a reason. The test computer has only 64 words of memory, and a completely random 16-bit word is nearly always a bad address, so every run would fault on its first step and nothing interesting would happen. So this strategy leans towards real addresses and the edges (0, 1, 63, 64, 65 and the output port) while any 16-bit value can still turn up.@given(start=states)tells Hypothesis to run the test many times, each time with a freshstart.@settings(max_examples=200, deadline=None)asks for 200 here, because each example runs the slow gate engine. (deadline=Nonemeans "don't complain that a gate-level step takes a while".)_run_side_by_sideis the judge holding the two films together. It loads the same state into both engines, checks they match before anything runs, then steps both and compares the whole state after every single step. If they differ, the message says on which step.gateis a fixture: one small gate computer (64 words of memory), built once for the whole file, because building gates takes a moment.load_stateresets it every time.- The docstring says the rule in plain English. If you can't say the rule in one sentence, it probably isn't a good property yet.
Notice what the test doesn't say. It never says what the machine should do.
It never says "add r1, r2, r3 makes 7". It doesn't need to know any
answers, because the other camera is the answer. It only needs a rule that
is always true.
That makes the test strong but also easy to cheat: a state where both
engines are wrong in the same way would pass. That is why the series also
checks the gate engine against plain Python arithmetic, and the Pebble
translator against the Pebble VM (tests/test_conformance.py). Two cameras
catch a lying camera. They can't catch both cameras being fooled by the same
mistake.
Random programs
A random state is mostly random memory. Real programs are more tidy, so there is a second property that writes programs, in assembly, from real instructions:
TEMPLATES = (
"<alu> <r>, <r>, <r>",
"<shift> <r>, <r>",
"mov <r>, <r>",
"li <r>, <byte>",
"load <r>, [<r>+<offset>]",
"store <r>, [<r>+<offset>]",
"call <address>",
"br <cond>, <address>",
"push <r>",
"halt <code>",
# ... and the rest, one for every kind of instruction
)
@st.composite
def programs(draw: st.DrawFn) -> str:
"""Build a short program from random real instructions, as assembly text."""
chosen = draw(st.lists(st.sampled_from(TEMPLATES), min_size=PROGRAM_MIN, max_size=PROGRAM_MAX))
return "\n".join(
re.sub(r"<(\w+)>", lambda piece: draw(PIECES[piece[1]]), template) for template in chosen
)
@settings(max_examples=200, deadline=None)
@given(source=programs())
def test_both_engines_agree_on_assembled_programs(gate: GateMachine, source: str) -> None:
"""A random program written in assembly runs the same, step for step, on both engines."""
fast = FastMachine(WORDS)
fast.load_program(assemble(source, words=WORDS).words)
_run_side_by_side(gate, fast.state())
Each template has holes like <r> (a register) and <byte> (a number), and
every hole is filled with a fresh random choice. The program is assembled by
PyCPU's own assembler, loaded, and run side by side with the same
_run_side_by_side check. Shrinking works here too: a failing program
shrinks to fewer lines and simpler registers, which is exactly how a person
would like to read a bug report.
The other properties check different corners of PyCPU:
| Rule | Test |
|---|---|
| The gate ripple adder adds any two words, with any carry in | test_ripple_adder_adds_any_two_words |
| The gate ALU matches a plain Python model for every operation | test_alu_matches_the_plain_python_model |
| Every 16-bit word is an instruction, and re-encoding it reads back the same | test_decode_accepts_every_word_and_encode_reads_it_back |
| After a subtraction, each branch condition matches a plain comparison | test_conditions_agree_with_python_comparisons_after_a_subtraction |
Whatever text you give the assembler, it makes a program or raises AssemblyError, never anything else |
test_random_text_gives_a_program_or_an_assembly_error_and_nothing_else |
| Multiplying and dividing in assembly routines match Python | test_multiply_matches_python_for_any_two_words, test_divmod_matches_python_floor_division |
| Rewinding after any number of gate steps returns to the start of the instruction | test_rewind_after_gate_steps_restores_the_instruction_start |
| Pausing, wandering through the gates, rewinding and resuming never drifts | test_resume_mid_instruction_matches_a_straight_run |
Try It Yourself
Let's break the fast engine on purpose and watch the judge find it.
Open src/pycpu/fast.py and find alu_model. The SHR line shifts a word
right by one and keeps the bit that fell off the end as the carry flag:
Change it to forget the carry:
Now the fast engine's shr gets the number right but never sets the carry
flag. Run the lockstep tests (the gate engine is slow, so give it room by
switching off the 60 second limit):
Hypothesis reports something like this (trimmed to the interesting part):
AssertionError: the engines differ after step 27
assert MachineState(...=0, output=()) == MachineState(...=0, output=())
Differing attributes:
['flags']
Drill down into differing attribute flags:
flags: Flags(zero=0, negative=0, carry=1, overflow=0) != Flags(zero=0, negative=0, carry=0, overflow=0)
The result and every register agree. Only the flags differ, and only the
carry. The gate engine, built from real gates, says carry=1; the fast
engine says carry=0. The gate camera is right, so the bug is in the fast
engine's SHR line.
When this was tried, the program-writing property did not notice the bug in its run: a random program only sees it if it shifts a word that has a 1 in its lowest bit. The property that starts from any state, with registers full of random words, did find it, but it took about three minutes, because every example (and every shrinking attempt) runs the slow gate engine. That is the point of having more than one kind of strategy.
Put the line back to a >> 1, a & 1 (git checkout src/pycpu/fast.py does it)
and run the tests again. They pass.
Slow shrinking
Every example runs the gate engine, so shrinking a failure takes a while,
and PyCPU's normal 60 second limit per test can cut it short. Hypothesis
then complains the failure is "flaky" and shows several half-shrunk
attempts. The --timeout=0 above lets it finish.
Run It Yourself
Run just the lockstep tests, which took about 20 seconds on the laptop this was written on (200 examples each, the same every time):
To run the whole suite, Hypothesis tests and all (the --no-cov in the command
above turns off the coverage check, which expects the whole suite to run and
would fail on one file):
Run them the long way (2,000 random examples each, different every run) to hunt for rarer bugs before a release:
The normal run uses a fixed seed, so it tries the same inputs every time and
a passing build means the same thing on every computer. The thorough run is
random, so each time you run it the judge asks for a brand-new set of tricks.
(The lockstep tests set their own count of 200, which takes priority.)
Both profiles live in conftest.py.
Your Turn
Write one new property for PyCPU: a halted machine never changes. Start
a state with halted=True, step both engines a few times, and check the state
is exactly what you started with. What's the strategy? (Hint: states already
makes halted states; you can make it always halted with .map(...) or
st.builds.) Run it and watch it pass. Then break it on purpose -- make the
fast engine's step carry on and run one more instruction after a halt -- and
watch the judge find it.
Back to the home page.