Debian Codegraph @

website/content/2017-03-09-hypothesis-for-researchers.md

raw symbols SCIP
1 ---
2 tags: python, details, technical
3 date: 2017-03-09 11:00
4 title: Hypothesis for Computer Science Researchers
5 author: drmaciver
6 ---
7
8 I'm in the process of [trying to turn my work on Hypothesis into a PhD](http://www.drmaciver.com/2017/03/looking-into-starting-a-phd/)
9 and I realised that I don't have a good self-contained summary as to why researchers should care about it.
10
11 So this is that piece. I'll try to give a from scratch introduction to the why and what of Hypothesis. It's primarily
12 intended for potential PhD supervisors, but should be of general interest as well (especially if you
13 work in this field).
14
15 ### Why should I care about Hypothesis from a research point of view?
16
17 The short version:
18
19 Hypothesis takes an existing effective style of testing (property-based testing) which has proven highly effective in practice
20 and makes it accessible to a much larger audience. It does so by taking several previously unconnected ideas from the existing
21 research literature on testing and verification, and combining them to produce a novel implementation that has proven very effective
22 in practice.
23
24 The long version is the rest of this article.
25
26 <!--more-->
27
28 The remainder is divided into several sections:
29
30 * [What is Hypothesis?](#what-is-hypothesis) is a from-scratch introduction to Hypothesis. If you are already familiar with
31 property-based testing (e.g. from QuickCheck) you can probably skip this.
32 * [How is Hypothesis innovative?](#how-is-hypothesis-innovative) is about the current state of the art of Hypothesis and why
33 it's interesting. If you've already read [How Hypothesis Works](http://hypothesis.works/articles/how-hypothesis-works/) this
34 is unlikely to teach you anything new and you can skip it.
35 * [What prior art is it based on?](#what-prior-art-is-it-based-on) is a short set of references for some of the inspirations
36 for Hypothesis. You probably shouldn't skip this, because it's short and the linked material is all interesting.
37 * [What are some interesting research directions?](#what-are-some-interesting-research-directions) explores possible directions
38 I'm looking into for the future of Hypothesis, some of which I would hope to include in any PhD related to it that I worked
39 on. You probably shouldn't skip this if you care about this document at all.
40 * [What should you do with this information?](#what-should-you-do-with-this-information) simply closes off the article and
41 winds things down.
42
43 So, without further ado, the actual content.
44
45 ### What is Hypothesis?
46
47 Hypothesis is an implementation of *property-based testing*, an idea that originated with a Haskell library called QuickCheck.
48
49 Property-based testing is a way to augment your unit tests with a source of structured random data that allows a tool to explore
50 the edge cases of your tests and attempt to find errors automatically. I've made a [longer and more formal discussion](http://hypothesis.works/articles/what-is-property-based-testing/)
51 of this definition in the past.
52
53 An example of a property-based test using Hypothesis:
54
55 ```python
56 from hypothesis import given, strategies as st
57
58
59 @given(st.lists(st.integers()))
60 def test_sort_is_idempotent(ls):
61 sort1 = sorted(ls)
62 assert sorted(sort1) == sort1
63 ```
64
65 This exposes a normal function which can be picked up by a standard runner such as py.test. You can also just call it
66 directly:
67
68 ```python
69 if __name__ == "__main__":
70 test_sort_is_idempotent()
71 ```
72
73 When the test is run, Hypothesis will generate random lists of integers
74 and pass them to the test. The test sorts the integers, then sorts them again, and asserts that the two results are the same.
75
76 As long as the test passes for every input Hypothesis feeds it this will appear to be a normal test. If it fails however,
77 Hypothesis will then repeatedly rerun it with progressively simpler examples to try and find a minimal input that causes
78 the failure.
79
80 To see this, suppose we implemented the following rather broken implementation of sorted:
81
82 ```python
83 def sorted(ls):
84 return list(reversed(ls))
85 ```
86
87 Then on running we would see the following output:
88
89 ```
90 @given(st.lists(st.integers()))
91 def test_sort_is_idempotent(ls):
92 sort1 = sorted(ls)
93 > assert sorted(sort1) == sort1
94 E assert [0, 1] == [1, 0]
95 E At index 0 diff: 0 != 1
96 E Use -v to get the full diff
97
98 sorting.py:12: AssertionError
99
100 ---- Hypothesis ----
101
102 Falsifying example: test_sort_is_idempotent(ls=[0, 1])
103 ```
104
105 Hypothesis probably started with a much more complicated example (the test fails for essentially any list with more
106 than one element) and then successfully reduced it to the simplest possible example: A list with two distinct elements.
107
108 Importantly, when the test is rerun, Hypothesis will start from the falsifying example it found last time rather than
109 trying to generate and shrink a new one from scratch. In this particular case that doesn't matter very much - the
110 example is found very quickly and it always finds the same one - but for more complex and slower tests this is an
111 vital part of the development workflow: It means that tests run much faster and don't stop failing until
112 the bug is actually fixed.
113
114 Tests can also draw more data as they execute:
115
116 ```python
117 @given(st.lists(st.integers(), min_size=1), st.data())
118 def test_sort_is_idempotent(ls, data):
119 ls.sort()
120 i = data.draw(st.integers(0, len(ls) - 1))
121 assert ls[i - 1] <= ls[i]
122 ```
123
124 This fails because we've forgotten than `i` may be zero, and also about Python's negative indexing of lists:
125
126 ```
127 @given(st.lists(st.integers(), min_size=1), st.data())
128 def test_sort_is_idempotent(ls, data):
129 ls.sort()
130 i = data.draw(st.integers(0, len(ls) - 1))
131 > assert ls[i - 1] <= ls[i]
132 E assert 1 <= 0
133
134 sorting.py:15: AssertionError
135
136 ---- Hypothesis ----
137
138 Falsifying example: test_sort_is_idempotent(ls=[0, 1], data=data(...))
139 Draw 1: 0
140 ```
141
142 Simplification and example saving work as normal for data drawn in this way.
143
144 Hypothesis also has a form of [model based testing](http://hypothesis.works/articles/rule-based-stateful-testing/),
145 in which you specify a set of valid operations on your API and it attempts to generate whole programs using those
146 operations and find a simple one that breaks.
147
148 ### How is Hypothesis innovative?
149
150 From an end user point of view, Hypothesis adds several important things:
151
152 * It exists at all and people use it. Historically this sort of testing has been found mostly within the functional
153 programming community, and attempts to make it work in other languages have not seen much success or widespread
154 adoption. Some of this is due to novel implementation details in Hypothesis, and some is due to design decisions
155 making it "feel" like normal testing instead of formal methods.
156 * Specifying data generators is much easier than in traditional QuickCheck methods, and you get a great deal more
157 functionality "for free" when you do. This is similar to [test.check](https://github.com/clojure/test.check) for
158 Clojure, or indeed to the [Erlang version of QuickCheck](http://www.quviq.com/products/erlang-quickcheck/), but
159 some of the design decisions of Hypothesis make it significantly more flexible here.
160 * The fact that arbitrary examples can be saved and replayed significantly improves the development work-flow. Other
161 implementations of property-based testing either don't do this at all, only save the seed, or rely on being able to
162 serialize the generated objects (which can break invariants when reading them back in).
163 * The fact that you can generate additional data within the test is often extremely useful, and seems to be unique
164 to Hypothesis in this category of testing tool.
165
166 These have worked together well to fairly effectively bring property based testing "to the masses", and Hypothesis
167 has started to see increasingly widespread use within the Python community, and is being actively used in the
168 development of tools and libraries, as well as in the development of both CPython and pypy, the two major implementations
169 of Python.
170
171 Much of this was made possible by Hypothesis's novel implementation.
172
173 From an implementation point of view, the novel feature of Hypothesis is this: Unlike other implementations of
174 property-based testing, it does not need to understand the structure of the data it is generating at all (it sometimes
175 has to make guesses about it, but its correctness is not dependent on the accuracy of those guesses).
176
177 Hypothesis is divided into three logically distinct parts:
178
179 1. A core engine called *Conjecture*, which can be thought of as an interactive fuzzer for lightly structured byte streams.
180 2. A strategy library, which is designed to take Conjecture's output and turn it into arbitrary values representable
181 in the programming language.
182 3. An interface to external test runners that takes tests built on top of the strategy library and runs them using Conjecture
183 (in Python this mostly just consists of exposing a function that the test runners can pick up, but in the
184 [Java Prototype](http://github.com/HypothesisWorks/hypothesis-java) this is more involved and ends up having
185 to interact with some interesting JUnit specific features.
186
187 Conjecture is essentially the interesting part of Hypothesis's implementation and is what supports most of its functionality:
188 Generation, shrinking, and serialization are all built into the core engine, so implementations of strategies do not require
189 any awareness of these features to be correct. They simply repeatedly ask the Conjecture engine for blocks of bytes, which
190 it duly provides, and they return the desired result.
191
192 If you want to know more about this, I have previously written
193 [How Hypothesis Works](http://hypothesis.works/articles/how-hypothesis-works/), which provides a bit more detail
194 about Conjecture and how Hypothesis is built on top of it.
195
196 ### What prior art is it based on?
197
198 I've done a fair bit of general reading of the literature in the course of working on Hypothesis.
199
200 The two main papers on which Hypothesis is based are:
201
202 * [QuickCheck: a lightweight tool for random testing of Haskell programs](https://dl.acm.org/citation.cfm?id=351266) essentially
203 started the entire field of property-based testing. Hypothesis began life as a QuickCheck implementation, and its user facing
204 API continues to be heavily based on QuickCheck, even though the implementation has diverged very heavily from it.
205 * [EXPLODE: a lightweight, general system for finding serious storage system errors](https://dl.acm.org/citation.cfm?id=1298469)
206 provided the key idea on which the Conjecture engine is based - instead of doing static data generation separate from the tests,
207 provide tests with an interactive primitive from which they can draw data.
208
209 Additionally, the following are major design inspirations in the Conjecture engine, although their designs are not currently
210 used directly:
211
212 * [American Fuzzy Lop](http://lcamtuf.coredump.cx/afl/) is an excellent security-oriented fuzzer, although one without much
213 academic connections. I've learned a fair bit about the design of fuzzers from it. For a variety of pragmatic reasons I don't
214 currently use its most important innovation (branch coverage metrics as a tool for corpus discovery), but I've successfully
215 prototyped implementations of that on top of Hypothesis which work pretty well.
216 * [Swarm Testing](https://dl.acm.org/citation.cfm?id=2336763) drove a lot of the early designs of Hypothesis's data generation.
217 It is currently not explicitly present in the Conjecture implementation, but some of what Conjecture does to induce deliberate
218 correlations in data is inspired by it.
219
220 ### What are some interesting research directions?
221
222 I have a large number of possible directions that my work on Hypothesis could be taken.
223
224 None of these are *necessarily* a thing that would be the focus of a PhD - in doing a PhD I would almost certainly
225 focus on a more specific research question that might include some or all of them. These are just areas that I am interested
226 in exploring which I think might form an interesting starting point, and whatever focus I actually end up with will likely
227 be more carefully tailored in discussion with my potential supervisors.
228
229 One thing that's also worth considering: Most of these research directions are ones that would result in improvements
230 to Hypothesis without changing its public interface. This results in a great practical advantage to performing the
231 research because of the relatively large (and ever-growing) corpus of open source projects which are already using
232 Hypothesis - many of these changes could at least partly be validated by just running peoples' existing tests and seeing
233 if any new and interesting bugs are found!
234
235 Without further ado, here are some of what I think are the most interesting directions to go next.
236
237 #### More structured byte streams
238
239 My current immediate research focus on Hypothesis is to replace the core Conjecture primitive with a more structured one
240 that bears a stronger resemblance to its origins in EXPLODE. This is designed to address a number of practical problems
241 that Hypothesis users currently experience (mostly performance related), but it also opens up a number of other novel
242 abstractions that can be built on top of the core engine.
243
244 The idea is to pare down the interface so that when calling in to Conjecture you simply draw a single byte, specifying
245 a range of possible valid bytes. This gives Conjecture much more fine-grained information to work with, which opens up
246 a number of additional features and abstractions that can be built on top of it.
247
248 From this primitive you can then rebuild arbitrary weighted samplers that shrink correctly (using a variation of the
249 Alias Method), and arbitrary grammars (probably using [Boltzmann Samplers](https://dl.acm.org/citation.cfm?id=1024669)
250 or similar).
251
252 This will provide a much more thorough basis for high quality data generation than the current rather ad hoc method
253 of specifying byte streams.
254
255 This is perhaps more engineering than research, but I think it would at the bare minimum make any paper I wrote about
256 the core approach of Hypothesis significantly more compelling, and it contains a number of interesting applications of
257 the theory.
258
259 #### Glass box testing
260
261 Currently Conjecture treats the tests it calls as a black box and does not get much information about what the tests
262 it executes are actually doing.
263
264 One obvious thing to do which brings in some more ideas from e.g. American Fuzzy Lop is to use more coverage information,
265 but so far I haven't had much success with making my prototypes of this idea suitable for real world use. The primary
266 reason for this so far has been that all of the techniques I've found have worked well when tests are allowed
267 to run for minutes or hours, but the current design focus of Hypothesis assumes tests have seconds to run at most,
268 which limits the utility of these methods and means they haven't been a priority so far.
269
270 But in principle this should be an extremely profitable line of attack, even with that limitation, and I would like
271 to explore it further.
272
273 The main idea would be to add a notion of "tags" to the core Conjecture engine which could be used to guide the
274 search. Coverage would be one source of tags, but others are possible. For example, my previous work on
275 [Schroedinteger](https://github.com/DRMacIver/schroedinteger) implements what is essentially a form of lightweight
276 [Concolic testing](https://en.wikipedia.org/wiki/Concolic_testing) that would be another possibly interesting source
277 of information to use.
278
279 Exactly how much of this is original research and how much is just applications of existing research is yet to be
280 determined, but I think it very likely that at the very least figuring out how to make use of this sort of information
281 in sharply bounded time is likely to bear interesting fruit. The opportunity to see how Concolic testing behaves in the
282 wild is also likely to result in a number of additional questions.
283
284 #### Making the Conjecture engine smarter
285
286 A thing I've looked into in the past is the possible use of grammar inference to improve shrinking and data generation.
287
288 At the time the obstacle I ran into was that the algorithm I was using -
289 [an optimized variation of L\* search](https://dl.acm.org/citation.cfm?id=73047) - did not get good performance in
290 practice on the problems I tried it on.
291
292 [Synthesizing Program Input Grammars](https://arxiv.org/abs/1608.01723) promises to lift this restriction by providing
293 much better grammar inference in practical scenarios that are quite closely related to this problem domain, so I would
294 like to revisit this and see if it can prove useful.
295
296 There are likely a number of other ways that the Conjecture engine can probe the state of the system under test
297 to determine interesting potential behaviours, especially in combination with glass box testing features.
298
299 I think there are a lot of potentially interesting research directions in here - especially if this is combined with
300 the glass box testing. Given that I haven't even been able to make this perform acceptably in the past, the first
301 one would be to see if I can!
302
303 This will also require a fair bit of practical experimentation to see what works well at actually finding bugs and what
304 doesn't. This is one area in particular where a corpus of open source projects tested with Hypothesis will be extremely
305 helpful.
306
307 #### Other testing abstractions
308
309 Despite Hypothesis primarily being a library for property based testing, the core Conjecture engine actually has
310 very little to do with property-based testing and is a more powerful low-level testing abstraction. It would be interesting
311 to see how far that could be taken - the existing stateful/model-based testing is one partial step in that direction,
312 but it could also potentially be used more directly for other things. e.g. in tandem with some of the above features
313 it could be used for low-level fuzzing of binaries, or using it to drive thread scheduling.
314
315 The nice thing about the Conjecture separation is that because it is so self-contained, it can be used as the core
316 building block on which other tools can be rebuilt and gain a lot of its major features for free.
317
318 I don't currently have any concrete plans in this direction, but it seems likely there are some interesting possibilities
319 here that will emerge after more review of the testing literature.
320
321 This is probably just engineering unless some particularly interesting application emerges, but I think the basic
322 potential of the technology would probably give pretty good odds of such an application.
323
324 ### What should you do with this information?
325
326 It depends who you are.
327
328 * If I'm already talking to you because you're a potential PhD supervisor, tell me what about this interests you and
329 ask me lots of questions.
330 * If you're a potential PhD supervisor who I'm *not* already talking to but you'd like me to, please let me know!
331 * If you're somebody else, it's rather up to you. Feel free to send me papers, questions, etc.
332
333 Whoever you are, if you found this document interesting I'd love to hear from you. Drop me an email at
334 [[email protected]](mailto:[email protected]).