| 1 | --- |
| 2 | tags: python, details, technical |
| 3 | date: 2016-12-10 11:00 |
| 4 | title: How Hypothesis Works |
| 5 | author: drmaciver |
| 6 | --- |
| 7 | |
| 8 | Hypothesis has a very different underlying implementation to any other |
| 9 | property-based testing system. As far as I know, it's an entirely novel |
| 10 | design that I invented. |
| 11 | |
| 12 | Central to this design is the following feature set which *every* |
| 13 | Hypothesis strategy supports automatically (the only way to break |
| 14 | this is by having the data generated depend somehow on external |
| 15 | global state): |
| 16 | |
| 17 | 1. All generated examples can be safely mutated |
| 18 | 2. All generated examples can be saved to disk (this is important because |
| 19 | Hypothesis remembers and replays previous failures). |
| 20 | 3. All generated examples can be shrunk |
| 21 | 4. All invariants that hold in generation must hold during shrinking ( |
| 22 | though the probability distribution can of course change, so things |
| 23 | which are only supported with high probability may not be). |
| 24 | |
| 25 | (Essentially no other property based systems manage one of these claims, |
| 26 | let alone all) |
| 27 | |
| 28 | The initial mechanisms for supporting this were fairly complicated, but |
| 29 | after passing through a number of iterations I hit on a very powerful |
| 30 | underlying design that unifies all of these features. |
| 31 | |
| 32 | It's still fairly complicated in implementation, but most of that is |
| 33 | optimisations and things needed to make the core idea work. More |
| 34 | importantly, the complexity is quite contained: A fairly small kernel |
| 35 | handles all of the complexity, and there is little to no additional |
| 36 | complexity (at least, compared to how it normally looks) in defining |
| 37 | new strategies, etc. |
| 38 | |
| 39 | This article will give a high level overview of that model and how |
| 40 | it works. |
| 41 | |
| 42 | <!--more--> |
| 43 | |
| 44 | Hypothesis consists of essentially three parts, each built on top |
| 45 | of the previous: |
| 46 | |
| 47 | 1. A low level interactive byte stream fuzzer called *Conjecture* |
| 48 | 2. A strategy library for turning Conjecture's byte streams into |
| 49 | high level structured data. |
| 50 | 3. A testing interface for driving test with data from Hypothesis's |
| 51 | strategy library. |
| 52 | |
| 53 | I'll focus purely on the first two here, as the latter is complex |
| 54 | but mostly a matter of plumbing. |
| 55 | |
| 56 | The basic object exposed by Conjecture is a class called TestData, |
| 57 | which essentially looks like an open file handle you can read |
| 58 | bytes from: |
| 59 | |
| 60 | ```python |
| 61 | class TestData: |
| 62 | def draw_bytes(self, n): ... |
| 63 | ``` |
| 64 | |
| 65 | (note: The Python code in this article isn't an exact copy of what's |
| 66 | found in Hypothesis, but has been simplified for pedagogical reasons). |
| 67 | |
| 68 | A strategy is then just an object which implements a single abstract |
| 69 | method from the strategy class: |
| 70 | |
| 71 | ```python |
| 72 | class SearchStrategy: |
| 73 | def do_draw(self, data): |
| 74 | raise NotImplementedError() |
| 75 | ``` |
| 76 | |
| 77 | The testing interface then turns test functions plus the strategies |
| 78 | they need into something that takes a TestData object and returns |
| 79 | True if the test fails and False if it passes. |
| 80 | |
| 81 | For a simple example, we can implement a strategy for unsigned |
| 82 | 64-bit integers as follows: |
| 83 | |
| 84 | |
| 85 | ```python |
| 86 | class Int64Strategy: |
| 87 | def do_draw(self, data): |
| 88 | return int.from_bytes(data.draw_bytes(8), byteorder="big", signed=False) |
| 89 | ``` |
| 90 | |
| 91 | As well as returning bytes, draw_bytes can raise an exception |
| 92 | that stops the test. This is useful as a way to stop examples |
| 93 | from getting too big (and will also be necessary for shrinking, |
| 94 | as we'll see in a moment). |
| 95 | |
| 96 | From this it should be fairly clear how we support saving and |
| 97 | mutation: Saving every example is possible because we can just |
| 98 | write the bytes that produced it to disk, and mutation is possible |
| 99 | because strategies are just returning values that we don't |
| 100 | in any way hang on to. |
| 101 | |
| 102 | But how does shrinking work? |
| 103 | |
| 104 | Well the key idea is the one I mentioned in |
| 105 | [my last article about shrinking |
| 106 | ](../compositional-shrinking/) - |
| 107 | shrinking inputs suffices to shrink outputs. In this case the |
| 108 | input is the byte stream. |
| 109 | |
| 110 | Once Hypothesis has found a failure it begins shrinking the |
| 111 | byte stream using a TestData object that looks like the following: |
| 112 | |
| 113 | ```python |
| 114 | class ShrinkingTestData: |
| 115 | def __init__(self, data): |
| 116 | self.data = data |
| 117 | self.index = 0 |
| 118 | |
| 119 | def draw_bytes(self, n): |
| 120 | if self.index + n > len(self.data): |
| 121 | raise StopTest() |
| 122 | result = self.data[self.index : self.index + n] |
| 123 | self.index += n |
| 124 | return result |
| 125 | ``` |
| 126 | |
| 127 | Shrinking now reduces to shrinking the byte array that gets |
| 128 | passed in as data, subject to the condition that our transformed |
| 129 | test function still returns True. |
| 130 | |
| 131 | Shrinking of the byte array is designed to try to minimize it |
| 132 | according to the following rules: |
| 133 | |
| 134 | 1. Shorter is always simpler. |
| 135 | 2. Given two byte arrays of the same length, the one which is |
| 136 | lexicographically earlier (considering bytes as unsigned 8 |
| 137 | bit integers) is simpler. |
| 138 | |
| 139 | You can imagine that some variant of [Delta Debugging](https://en.wikipedia.org/wiki/Delta_Debugging) |
| 140 | is used for the purpose of shrinking the byte array, |
| 141 | repeatedly deleting data and lowering bytes until no |
| 142 | byte may be deleted or lowered. It's a lot more complicated |
| 143 | than that, but I'm mostly going to gloss over that part |
| 144 | for now. |
| 145 | |
| 146 | As long as the strategy is well written (and to some extent |
| 147 | even when it's not - it requires a certain amount of active |
| 148 | sabotage to create strategies that produce more complex data |
| 149 | given fewer bytes) this results in shrinks to the byte array |
| 150 | giving good shrinks to the generated data. e.g. our 64-bit |
| 151 | unsigned integers are chosen to be big endian so that |
| 152 | shrinking the byte data lexicographically shrinks the integer |
| 153 | towards zero. |
| 154 | |
| 155 | In order to get really good deleting behaviour in our strategies |
| 156 | we need to be a little careful about how we arrange things, so |
| 157 | that deleting in the underlying bytestream corresponds to |
| 158 | deleting in generated data. |
| 159 | |
| 160 | For example, suppose we tried to implement lists as follows: |
| 161 | |
| 162 | |
| 163 | ```python |
| 164 | class ListStrategy(SearchStrategy): |
| 165 | def __init__(self, elements): |
| 166 | super().__init__() |
| 167 | self.elements = elements |
| 168 | |
| 169 | def do_draw(self, data): |
| 170 | n_elements = integers(0, 10).do_draw(self.elements) |
| 171 | return [self.elements.do_draw(data) for _ in range(n_elements)] |
| 172 | ``` |
| 173 | |
| 174 | The problem with this is that deleting data doesn't actually |
| 175 | result in deleting elements - all that will happen is that |
| 176 | drawing will run off the end of the buffer. You can |
| 177 | potentially shrink n_elmements, but that only lets you |
| 178 | delete things from the end of the list and will leave a |
| 179 | bunch of left over data at the end if you do - if this is |
| 180 | the last data drawn that's not a problem, and it might be |
| 181 | OK anyway if the data usefully runs into the next strategy, |
| 182 | but it works fairly unreliably. |
| 183 | |
| 184 | I am in fact working on an improvement to how shrinking works |
| 185 | for strategies that are defined like this - they're quite |
| 186 | common in user code, so they're worth supporting - but it's |
| 187 | better to just have deletion of elements correspond to |
| 188 | deletion of data in the underlying bytestream. We can do |
| 189 | this as follows: |
| 190 | |
| 191 | |
| 192 | ```python |
| 193 | class ListStrategy(SearchStrategy): |
| 194 | def __init__(self, elements): |
| 195 | super().__init__() |
| 196 | self.elements = elements |
| 197 | |
| 198 | def do_draw(self, data): |
| 199 | result = [] |
| 200 | while booleans().do_draw(data): |
| 201 | result.append(self.elements.do_draw(data)) |
| 202 | return result |
| 203 | ``` |
| 204 | |
| 205 | We now draw lists as a series True, element, |
| 206 | True, element, ..., False, etc. So if you delete the |
| 207 | interval in the byte stream that starts with a True |
| 208 | and finishes at the end of an element, that just deletes |
| 209 | that element from the list and shifts everything afterwards |
| 210 | left one space. |
| 211 | |
| 212 | Given some careful strategy design this ends up working |
| 213 | pretty well. It does however run into problems in two |
| 214 | minor cases: |
| 215 | |
| 216 | 1. It doesn't generate very good data |
| 217 | 2. It doesn't shrink very well |
| 218 | |
| 219 | Fortunately both of these are fixable. |
| 220 | |
| 221 | The reason for the lack of good data is that Conjecture |
| 222 | doesn't know enough to produce a good distribution of bytes |
| 223 | for the specific special values for your strategy. e.g. in |
| 224 | our unsigned 64 bit integer examples above it can probably |
| 225 | guess that 0 is a special value, but it's not necessarily |
| 226 | obvious that e.g. focusing on small values is quite useful. |
| 227 | |
| 228 | This gets worse as you move further away from things that |
| 229 | look like unsigned integers. e.g. if you're turning bytes |
| 230 | into floats, how is Conjecture supposed to know that |
| 231 | Infinity is an interesting value? |
| 232 | |
| 233 | The simple solution is to allow the user to provide a |
| 234 | distribution hint: |
| 235 | |
| 236 | |
| 237 | ```python |
| 238 | class TestData: |
| 239 | def draw_bytes(self, n, distribution=None): ... |
| 240 | ``` |
| 241 | |
| 242 | Where a distribution function takes a Random object |
| 243 | and a number of bytes. |
| 244 | |
| 245 | This lets users specify the distribution of bytes. It |
| 246 | won't necessarily be respected - e.g. it certainly isn't |
| 247 | in shrinking, but the fuzzer can and does mutate the |
| 248 | values during generation too - but it provides a good |
| 249 | starting point which allows you to highlight special |
| 250 | values, etc. |
| 251 | |
| 252 | So for example we could redefine our integer strategy |
| 253 | as: |
| 254 | |
| 255 | |
| 256 | ```python |
| 257 | class Int64Strategy: |
| 258 | def do_draw(self, data): |
| 259 | def biased_distribution(random, n): |
| 260 | if random.randint(0, 1): |
| 261 | return random.randint(0, 100).to_bytes(n, byteorder="big", signed=False) |
| 262 | else: |
| 263 | return uniform(random, n) |
| 264 | |
| 265 | return int.from_bytes( |
| 266 | data.draw_bytes(8, biased_distribution), byteorder="big", signed=False |
| 267 | ) |
| 268 | ``` |
| 269 | |
| 270 | Now we have a biased integer distribution which will |
| 271 | produce integers between 0 and 100 half the time. |
| 272 | |
| 273 | We then use the strategies to generate our initial |
| 274 | buffers. For example we could pass in a TestData |
| 275 | implementation that looked like this: |
| 276 | |
| 277 | ```python |
| 278 | class GeneratingTestData(TestData): |
| 279 | def __init__(self, random, max_bytes): |
| 280 | self.max_bytes = max_bytes |
| 281 | self.random = random |
| 282 | self.record = bytearray() |
| 283 | |
| 284 | def draw_bytes(self, n, distribution): |
| 285 | if n + len(self.record) > self.max_bytes: |
| 286 | raise StopTest() |
| 287 | result = distribution(self.random, n) |
| 288 | self.record.extend(result) |
| 289 | return result |
| 290 | ``` |
| 291 | |
| 292 | This draws data from the provided distribution |
| 293 | and records it, so at the end we have a record of |
| 294 | all the bytes we've drawn so that we can replay |
| 295 | the test afterwards. |
| 296 | |
| 297 | This turns out to be mostly enough. I've got some |
| 298 | pending research to replace this API with something |
| 299 | a bit more structured (the ideal would be that instead |
| 300 | of opaque distribution objects you draw from an explicit |
| 301 | mixture of grammars), but for the moment research on |
| 302 | big changes like that is side lined because nobody is |
| 303 | funding Hypothesis development, so I've not got very far |
| 304 | with it. |
| 305 | |
| 306 | Initial designs tried to avoid this approach by using |
| 307 | data from the byte stream to define the distribution, |
| 308 | but this ended up producing quite opaque structures in |
| 309 | the byte stream that didn't shrink very well, and this |
| 310 | turned out to be simpler. |
| 311 | |
| 312 | The second problem of it not shrinking well is also |
| 313 | fairly easily resolved: The problem is not that we |
| 314 | *can't* shrink it well, but that shrinking ends up |
| 315 | being slow because we can't tell what we need to |
| 316 | do: In our lists example above, the only way we |
| 317 | currently have to delete elements is to delete the |
| 318 | corresponding intervals, and the only way we have |
| 319 | to find the right intervals is to try *all* of them. |
| 320 | This potentially requires O(n^2) deletions to get the |
| 321 | right one. |
| 322 | |
| 323 | The solution is just to do a bit more book keeping as we |
| 324 | generate data to mark useful intervals. TestData now |
| 325 | looks like this: |
| 326 | |
| 327 | ```python |
| 328 | class TestData: |
| 329 | def start_interval(self): ... |
| 330 | |
| 331 | def stop_interval(self): ... |
| 332 | |
| 333 | def draw_bytes(self, n): ... |
| 334 | |
| 335 | def draw(self, strategy): |
| 336 | self.start_interval() |
| 337 | result = strategy.do_draw(self) |
| 338 | self.stop_interval() |
| 339 | return result |
| 340 | ``` |
| 341 | |
| 342 | |
| 343 | We then pass everything through data.draw instead |
| 344 | of strategy.do_draw to maintain this bookkeeping. |
| 345 | |
| 346 | These mark useful boundaries in the bytestram that |
| 347 | we can try deleting: Intervals which don't cross a |
| 348 | value boundary are much more likely to be useful to |
| 349 | delete. |
| 350 | |
| 351 | There are a large number of other details that are |
| 352 | required to make Hypothesis work: The shrinker and |
| 353 | the strategy library are both carefully developed |
| 354 | to work together, and this requires a fairly large |
| 355 | number of heuristics and special cases to make things |
| 356 | work, as well as a bunch of book keeping beyond the |
| 357 | intervals that I've glossed over. |
| 358 | |
| 359 | It's not a perfect system, but it works and works well: |
| 360 | This has been the underlying implementation of Hypothesis |
| 361 | since the 3.0 release in early 2016, and the switch over |
| 362 | was nearly transparent to end users: the previous |
| 363 | implementation was much closer to a classic QuickCheck |
| 364 | model (with a great deal of extra complexity to support |
| 365 | the full Hypothesis feature set). |
| 366 | |
| 367 | In a lot of cases it even works better than heavily |
| 368 | customized solutions: For example, a benefit of the byte |
| 369 | based approach is that all parts of the data are |
| 370 | fully comprehensible to it. Often more structured |
| 371 | shrinkers get stuck in local minima because shrinking |
| 372 | one part of the data requires simultaneously shrinking |
| 373 | another part of the data, whileas Hypothesis can just |
| 374 | spot patterns in the data and speculatively shrink |
| 375 | them together to see if it works. |
| 376 | |
| 377 | The support for chaining data generation together |
| 378 | is another thing that benefits here. In Hypothesis |
| 379 | you can chain strategies together like this: |
| 380 | |
| 381 | |
| 382 | ```python |
| 383 | class SearchStrategy: |
| 384 | def do_draw(self, data): |
| 385 | raise NotImplementedError() |
| 386 | |
| 387 | def flatmap(self, bind): |
| 388 | return FlatmappedStrategy(self, bind) |
| 389 | |
| 390 | |
| 391 | class FlatmappedStrategy(SearchStrategy): |
| 392 | def __init__(self, base, bind): |
| 393 | super().__init__() |
| 394 | self.base = base |
| 395 | self.bind = bind |
| 396 | |
| 397 | def do_draw(self, data): |
| 398 | value = data.draw(self.base) |
| 399 | return data.draw(self.bind(value)) |
| 400 | ``` |
| 401 | |
| 402 | The idea is that flatmap lets you chain strategy definitions together by |
| 403 | drawing data that is dependent on a value from other strategies. |
| 404 | |
| 405 | This works fairly well in modern Hypothesis, but has historically (e.g. in |
| 406 | test.check or pre 3.0 Hypothesis) been a problem for integrated testing and |
| 407 | generation. |
| 408 | |
| 409 | The reason this is normally a problem is that if you shrink the first value |
| 410 | you've drawn then you essentially *have* to invalidate the value drawn from |
| 411 | bind(value): There's no real way to retain it because it came from a completely |
| 412 | different generator. This potentially results in throwing away a lot of |
| 413 | previous work if a shrink elsewhere suddenly makes it to shrink the |
| 414 | initial value. |
| 415 | |
| 416 | With the Hypothesis byte stream approach this is mostly a non-issue: As long as |
| 417 | the new strategy has roughly the same shape as the old strategy it will just |
| 418 | pick up where the old shrinks left off because they operate on the same |
| 419 | underlying byte stream. |
| 420 | |
| 421 | This sort of structure *does* cause problems for Hypothesis if shrinking the |
| 422 | first value would change the structure of the bound strategy too much, but |
| 423 | in practice it usually seems to work out pretty well because there's enough |
| 424 | flexibility in how the shrinks happen that the shrinker can usually work past |
| 425 | it. |
| 426 | |
| 427 | This model has proven pretty powerful even in its current form, but there's |
| 428 | also a lot of scope to expand it. |
| 429 | |
| 430 | But hopefully not by too much. One of the advantages of the model in its |
| 431 | current form though is its simplicity. The [Hypothesis for Java |
| 432 | prototype](https://github.com/HypothesisWorks/hypothesis-java) was written in |
| 433 | an afternoon and is pretty powerful. The whole of the Conjecture implementation |
| 434 | in Python is a bit under a thousand significant lines of fairly portable code. |
| 435 | Although the strategy library and testing interface are still a fair bit of |
| 436 | work, I'm still hopeful that the Hypothesis/Conjecture approach is the tool |
| 437 | needed to bring an end to the dark era of property based testing libraries |
| 438 | that don't implement shrinking at all. |