Every developer knows this failure mode. Your test suite is green, coverage looks healthy, and then production falls over on an input nobody imagined: an empty string, a four-byte unicode sequence, a leap-year boundary, a list containing exactly two elements. Example-based tests can only enumerate the cases you thought to write down, and the gap between “what I thought of” and “what reality sends” is where bugs live. That gap is precisely what property-based testing attacks: instead of writing concrete input-output pairs, you state a property that must hold for all inputs, and a tool generates the inputs for you.

Hypothesis is the Python implementation of that idea, descended from the QuickCheck lineage but engineered far past it. The interesting part is not the generation — random inputs are easy. The interesting part is what happens after a failure: the engine does not hand you the random 300-character string that crashed your parser. It hands you something close to the minimal string that crashes it, usually within seconds, because every failing input is passed through a dedicated reduction machine before it reaches your terminal. That pair of behaviors — generate broadly, then shrink aggressively — is a genuinely hard systems problem, and Hypothesis has spent years refining the machinery behind it.

This post is a source tour of that machinery at the current master commit (b71cb96a4006). The package lives under hypothesis/src/hypothesis/: core.py (2,211 lines) holds the @given decorator and the test runner, strategies/ describes what data to build, and internal/conjecture/ is the engine that decides which data to try and how to reduce failures. Every path and line number below was verified against the real tree before being cited.

Overview architecture of the Hypothesis property-based testing engine, from @given down to the Conjecture engine, shrinking, and providers

From left to right: the public API layer wraps your test, the strategy layer describes data, the Conjecture engine generates and shrinks test cases, and the learned-state and provider modules supply memory and primitive draws.

Reading the overview from left to right, the load-bearing symbols are:

Detailed architecture of Hypothesis: strategy combinators, ConjectureRunner phases, ConjectureData draws, shrinker passes, DataTree memory, providers, and stateful testing

The detail view adds the engine internals: phase gating, mutation passes, the DataTree prefix memory, shrinker passes built on choice trees, and the stateful testing layer.

The Strategy Layer: SearchStrategy and Its Combinators

Everything a test can consume is a SearchStrategy, declared generic over its value type (SearchStrategy(Generic[Ex]) at strategies.py:260). The contract is deliberately tiny: a subclass implements do_draw(data) at line 597, receiving the ConjectureData object and returning a value. That is the entire generation interface. Strategies never generate randomness themselves; they describe structure, and the engine decides which path through that structure to take.

On top of that contract sit three combinators that make strategies composable: map (line 420), flatmap (line 429), and filter (line 460). They return lazy wrapper strategies, so nothing executes until the engine drives do_draw — which is what allows recursive and mutually referential definitions to exist at all. The user-facing builders live in strategies/_internal/core.py, the largest file in the package at 2,512 lines: lists() at line 303, text() at line 849, sampled_from() at line 196, and recursive() at line 1958, which stacks a “extend children into containers” strategy to build arbitrarily deep JSON-like structures. Numeric types get their own module: numbers.py defines IntegersStrategy at line 53 and the public integers() factory at line 123, encoding bounds and shrinking preferences that the engine later exploits.

The Conjecture Engine: Phases, Budgets and Mutations

ConjectureRunner (engine.py:291) is the state machine that owns the whole run. Its run() at line 1023 executes until RunIsComplete is raised, and its final debug line is a nice summary of what it tracks: “Run complete after N test cases (M valid) and S shrinks.” Each candidate test case flows through test_function (line 558), which runs the user’s function against a fresh ConjectureData and records the outcome as valid, invalid, or interesting.

Generation has three distinct moves. generate_novel_prefix (line 819) extends a prefix the engine has already explored into unseen territory, using the DataTree described below. generate_mutations_from (line 1391) takes an interesting case and perturbs it, probing the neighborhood of a known failure. And the whole loop is gated by should_generate_more (line 1156), which checks the active phases — the Phase enum at _settings.py:144 — against the remaining budget. The default profile at _settings.py:1209 is refreshingly modest: max_examples=100 with stateful_step_count=50. On the entry side, run_engine (core.py:1443) hands the runner a closure, and _execute_once_for_engine (core.py:1245) plus execute_once (core.py:1053) handle the per-case mechanics: reporting, timing, and flakiness detection. When something fails, shrink_interesting_test_cases (engine.py:1694) takes over.

Choice Sequences and the Provider Layer

A running test case is a ConjectureData (data.py:678). Its draw() method (line 1292) is where user-visible strategies bottom out into primitives: draw_integer (line 967), draw_float (line 1008), draw_string (line 1052), draw_bytes (line 1076), and draw_boolean (line 1092). Every primitive call appends to the choice sequence and records a span — the Spans structure at data.py:506 tracks the structural coverage of the test, which feeds the mutation heuristics.

The sequence itself is typed. choice.py defines ChoiceTemplate (line 75) and ChoiceNode (line 103), pairing each value with its constraints. The module is full of bijective index encodings: zigzag_index/zigzag_value (lines 308 and 317) map signed integers to naturals so “smaller” is well-defined, and choice_to_index/choice_from_index (lines 327 and 445) let the engine address any choice by number — exactly the kind of careful, reversible encoding you find in interpreter internals like /cpython/. Beneath the primitives sits the provider layer: an AVAILABLE_PROVIDERS registry (providers.py:130), the PrimitiveProvider abstract class (line 405) with draw methods mirroring the data layer, and HypothesisProvider (line 765) as the default backend tuned for bug finding. Third-party backends register through with_register_backend (line 388), and a byte-string adapter survives as BytestringProvider (line 1118) for the conformance suite in provider_conformance.py.

Shrinking and Stateful Testing

The Shrinker (shrinker.py:164) is where Hypothesis earns its reputation. Entry is shrink() (line 457): a greedy_shrink pass (line 726) first, backed by initial_coarse_reduction (line 735) and reduce_each_alternative (line 757), followed by finer refinement. Passes are driven by ChoiceTree objects (shrinking/choicetree.py:116) — trees of candidate moves enumerated without repeats by a Chooser (line 50) — so the shrinker never re-tries a move that already failed. If the reduced case still looks mysterious, explain() (line 513) reports the minimal prefix that must exist for the failure to trigger. Two hard caps keep shrinking from running forever: MAX_SHRINKS = 500 (engine.py:86) and MAX_SHRINKING_SECONDS = 300 (engine.py:98).

Stateful testing reuses this entire stack. RuleBasedStateMachine (stateful.py:338) lets you declare Rule (line 569) methods that draw from Bundle (line 663) — pools of previously produced values — and Invariant (line 1189) checks that run between steps. run_state_machine_as_test (line 287) compiles the machine into a single property-based test driven by RuleStrategy (line 1253), so a shrunken stateful failure arrives as a minimal rule sequence, reduced by exactly the machinery above.

From Byte Buffers to Choice Sequences: Build Facts in the Code

The clearest way to see the architecture’s age is in its data model. Earlier generations of this engine treated a test case as an opaque byte buffer and reconstructed values from it; today the sequence of typed ChoiceNode objects is the test case, and the byte-string view exists only as the BytestringProvider adapter. The DataTree (datatree.py:546) is the memory that makes the new model pay off: a prefix tree of every explored test, fed by a TreeRecordingObserver (line 986) attached to each ConjectureData, with Branch records (line 85) marking which prefixes lead anywhere. That tree is what lets generate_novel_prefix aim at genuinely unexplored inputs instead of re-rolling dice.

The numbers tell their own story. The four heaviest modules — strategies/_internal/core.py at 2,512 lines, core.py at 2,211, shrinker.py at 1,700, and engine.py at 1,625 — are all load-bearing in the paths above; data.py (1,338 lines), stateful.py (1,160), providers.py (1,141), datatree.py (1,047), and choice.py (593) fill out the engine. Even find() (core.py:2477), the little “give me the minimal value satisfying this predicate” helper, is built on @given with Settings(max_examples=2000) (line 2488) — there is no second engine. Integrations reuse the same primitives too: extra/django/_fields.py maps Django form and model fields onto strategies through a plain lookup table (the same philosophy as /django/ model layers), and when you need a shared failure database across machines, RedisExampleDatabase (extra/redis.py:24) plugs the example database into /redis/ rather than inventing a storage format.

Honest Limits

This tour tracks one commit (b71cb96a4006) of a fast-moving codebase; line numbers drift with every refactor, so treat the GitHub links as coordinates, not permalinks to logic. We read the strategies/ and internal/ subtrees plus a few single files — the engine has more rooms we did not open: the optimiser and Pareto-front modules in internal/conjecture/, float-specific encoding tricks, the observability and escalations layers, and the health-check machinery in internal/healthcheck.py. Behavior settings like max_examples bound wall-clock exploration rather than guaranteeing exhaustive coverage; 100 examples is a smoke test of a property, not a proof, and the shrinking caps mean pathological inputs can arrive only nearly minimal. Finally, a source tour is not a usage guide: if you want to write property-based tests, start with the official documentation, then come back and read engine.py — it rewards the second visit.

Watch PyShine on YouTube

Contents