Debian Codegraph @

website/content/2017-09-14-multi-bug-discovery.md

raw symbols SCIP
1 ---
2 tags: technical, details, python
3 date: 2017-09-26 12:00
4 title: When multiple bugs attack
5 author: drmaciver
6 ---
7
8 When Hypothesis finds an example triggering a bug, it tries to shrink the example
9 down to something simpler that triggers it. This is a pretty common feature, and
10 most property-based testing libraries implement something similar (though there
11 are a number of differences between them). Stand-alone test case reducers are
12 also fairly common, as it's a useful thing to be able to do when reporting bugs
13 in external projects - rather than submitting a giant file triggering the bug,
14 a good test case reducer can often shrink it down to a couple of lines.
15
16 But there's a problem with doing this: How do you know that the bug you started
17 with is the same as the bug you ended up with?
18
19 This isn't just an academic question. [It's very common for the bug you started
20 with to slip to another one](https://blog.regehr.org/archives/1284).
21
22 Consider for example, the following test:
23
24 ```python
25 from hypothesis import given, strategies as st
26
27
28 def mean(ls):
29 return sum(ls) / len(ls)
30
31
32 @given(st.lists(st.floats()))
33 def test(ls):
34 assert min(ls) <= mean(ls) <= max(ls)
35 ```
36
37 This has a number of interesting ways to fail: We could pass `NaN`, we could
38 pass `[-float('inf'), +float('inf')]`, we could pass numbers which trigger a
39 precision error, etc.
40
41 But after test case reduction, we'll pass the empty list and it will fail
42 because we tried to take the min of an empty sequence.
43
44 This isn't necessarily a huge problem - we're still finding a bug after all
45 (though in this case as much in the test as in the code under test) -
46 and sometimes it's even desirable - you find more bugs this way, and sometimes
47 they're ones that Hypothesis would have missed - but often it's not, and an
48 interesting and rare bug slips to a boring and common one.
49
50 Historically Hypothesis has had a better answer to this than most - because
51 of the Hypothesis example database, all intermediate bugs are saved and a
52 selection of them will be replayed when you rerun the test. So if you fix
53 one bug then rerun the test, you'll find the other bugs that were previously
54 being hidden from you by that simpler bug.
55
56 But that's still not a great user experience - it means that you're not getting
57 nearly as much information as you could be, and you're fixing bugs in
58 Hypothesis's priority order rather than yours. Wouldn't it be better if Hypothesis
59 just told you about all of the bugs it found and you could prioritise them yourself?
60
61 Well, as of Hypothesis 3.29.0, released a few weeks ago, now it does!
62
63 If you run the above test now, you'll get the following:
64
65 ```
66 Falsifying example: test(ls=[nan])
67 Traceback (most recent call last):
68 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 671, in run
69 print_example=True, is_final=True
70 File "/home/david/hypothesis-python/src/hypothesis/executors.py", line 58, in default_new_style_executor
71 return function(data)
72 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 120, in run
73 return test(*args, **kwargs)
74 File "broken.py", line 8, in test
75 def test(ls):
76 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 531, in timed_test
77 result = test(*args, **kwargs)
78 File "broken.py", line 9, in test
79 assert min(ls) <= mean(ls) <= max(ls)
80 AssertionError
81
82 Falsifying example: test(ls=[])
83 Traceback (most recent call last):
84 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 671, in run
85 print_example=True, is_final=True
86 File "/home/david/hypothesis-python/src/hypothesis/executors.py", line 58, in default_new_style_executor
87 return function(data)
88 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 120, in run
89 return test(*args, **kwargs)
90 File "broken.py", line 8, in test
91 def test(ls):
92 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 531, in timed_test
93 result = test(*args, **kwargs)
94 File "broken.py", line 9, in test
95 assert min(ls) <= mean(ls) <= max(ls)
96 ValueError: min() arg is an empty sequence
97
98 You can add @seed(67388524433957857561882369659879357765) to this test to reproduce this failure.
99 Traceback (most recent call last):
100 File "broken.py", line 12, in <module>
101 test()
102 File "broken.py", line 8, in test
103 def test(ls):
104 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 815, in wrapped_test
105 state.run()
106 File "/home/david/hypothesis-python/src/hypothesis/core.py", line 732, in run
107 len(self.falsifying_examples,)))
108 hypothesis.errors.MultipleFailures: Hypothesis found 2 distinct failures.
109 ```
110
111 (The stack traces are a bit noisy, I know.
112 [We have an issue open about cleaning them up](https://github.com/HypothesisWorks/hypothesis-python/issues/848)).
113
114 All of the different bugs are minimized simultaneously and take full advantage of Hypothesis's
115 example shrinking, so each bug is as easy (or hard) to read as if it were the only bug we'd found.
116
117 This isn't perfect: The heuristic we use for determining if two bugs are the same is whether they
118 have the same exception type and the exception is thrown from the same line. This will necessarily
119 conflate some bugs that are actually different - for example, `[float('nan')]`,
120 `[-float('inf'), float('inf')]` and `[3002399751580415.0, 3002399751580415.0, 3002399751580415.0]`
121 each trigger the assertion in the test, but they are arguably "different" bugs.
122
123 But that's OK. The heuristic is deliberately conservative - the point is not that it can
124 distinguish whether any two examples are the same bug, just that any two examples it distinguishes
125 are different enough that it's interesting to show both, and this heuristic definitely manages that.
126
127 As far as I know this is a first in property-based testing libraries (though something like it is
128 common in fuzzing tools, and [theft is hot on our tail with something similar](
129 https://github.com/silentbicycle/theft/compare/develop-failure_tagging)) and there's been
130 [some interesting related but mostly orthogonal research](
131 http://www.cse.chalmers.se/~nicsma/papers/more-bugs.pdf) in Erlang QuickCheck.
132
133 It was also surprisingly easy.
134
135 A lot of things went right in writing this feature, some of them technical, some of them social,
136 somewhere in between.
137
138 The technical ones are fairly straightforward: Hypothesis's core model turned out to be very
139 well suited to this feature. Because Hypothesis has a single unified intermediate representation
140 which defines a total ordering for simplicity, adapting Hypothesis to shrink multiple things at
141 once was quite easy - whenever we attempt a shrink and it produces a different bug than the one
142 we were looking for, we compare it to our existing best example for that bug and replace it if
143 the current one is better (or we've discovered a new bug). We then just repeatedly run the shrinking
144 process for each bug we know about until they've all been fully shrunk.
145
146 This is in a sense not surprising - I've been thinking about the problem of multiple-shrinking for
147 a long time and, while this is the first time it's actually appeared in Hypothesis, the current
148 choice of model was very much informed by it.
149
150 The social ones are perhaps more interesting. Certainly I'm very pleased with how they turned
151 out here.
152
153 The first is that this work emerged tangentially from
154 [the recent Stripe funded work](https://stripe.com/blog/hypothesis) - Stripe paid me
155 to develop some initial support for testing Pandas code with Hypothesis, and I observed
156 a bunch of bug slippage happening in the wild while I was testing that (it turns out there
157 are quite a lot of ways to trigger exceptions from Pandas - they weren't really Pandas
158 bugs so much as bugs in the Pandas integration, but they still slipped between several
159 different exception types), so that was what got me thinking about this problem again.
160
161 Not by accident, this feature also greatly simplified the implementation
162 of [the new deadline feature](https://hypothesis.readthedocs.io/en/latest/settings.html#hypothesis.settings.deadline)
163 that [Smarkets](https://smarkets.com/) funded, which was going to have to have a lot of
164 logic about how deadlines and bugs interacted, but all that went away as soon as we were
165 able to handle multiple bugs sensibly.
166
167 This has been a relatively consistent theme in Hypothesis development - practical problems
168 tend to spark related interesting theoretical developments. It's not a huge exaggeration
169 to say that the fundamental Hypothesis model exists because I wanted to support testing
170 Django nicely. So the recent funded development from Stripe and Smarkets has been a
171 great way to spark a lot of seemingly unrelated development and improve Hypothesis
172 for everyone, even outside the scope of the funded work.
173
174 Another thing that really helped here is our review process, and [the review from Zac
175 in particular](https://github.com/HypothesisWorks/hypothesis-python/pull/836).
176
177 This wasn't the feature I originally set out to develop. It started out life as a
178 much simpler feature that used much of the same machinery, and just had a goal of
179 avoiding slipping to new errors all together. Zac pushed back with some good questions
180 around whether this was really the correct thing to do, and after some experimentation
181 and feedback I eventually hit on the design that lead to displaying all of the errors.
182
183 Our [review handbook](https://github.com/HypothesisWorks/hypothesis-python/blob/master/guides/review.rst)
184 emphasises that code review is a collaborative design process, and I feel this was
185 a particularly good example of that. We've created a great culture of code review,
186 and we're reaping the benefits (and if you want to get in on it, we could always
187 use more people able and willing to do review...).
188
189 All told, I'm really pleased with how this turned out. I think it's a nice example
190 of getting a lot of things right up front and this resulting in a really cool new
191 feature.
192
193 I'm looking forward to seeing how it behaves in the wild. If you notice any
194 particularly fun examples, do [let me know](mailto:[email protected]), or write
195 up a post about them yourself!