| 1 | --- |
| 2 | tags: python, technical, intro |
| 3 | date: 2017-04-05 10:00 |
| 4 | title: Solving the Water Jug Problem from Die Hard 3 with TLA+ and Hypothesis |
| 5 | author: nchammas |
| 6 | --- |
| 7 | |
| 8 | _This post was originally published on [the author's personal site](http://nchammas.com/writing/how-not-to-die-hard-with-hypothesis). |
| 9 | It is reproduced here with his permission._ |
| 10 | |
| 11 | In the movie [Die Hard with a Vengeance](https://en.wikipedia.org/wiki/Die_Hard_with_a_Vengeance) |
| 12 | (aka Die Hard 3), there is |
| 13 | [this famous scene](https://www.youtube.com/watch?v=6cAbgAaEOVE) where |
| 14 | John McClane (Bruce Willis) and Zeus Carver (Samuel L. Jackson) |
| 15 | are forced to solve a problem or be blown up: Given a 3 gallon jug and |
| 16 | 5 gallon jug, how do you measure out exactly 4 gallons of water? |
| 17 | |
| 18 | <div style="text-align: center;"> |
| 19 | <iframe |
| 20 | width="560" |
| 21 | height="315" |
| 22 | src="https://www.youtube.com/embed/6cAbgAaEOVE?rel=0" |
| 23 | frameborder="0" |
| 24 | allowfullscreen> |
| 25 | </iframe> |
| 26 | <p> |
| 27 | (The video title is wrong. It's Die Hard 3.) |
| 28 | </p> |
| 29 | </div> |
| 30 | |
| 31 | <!--more--> |
| 32 | |
| 33 | Apparently, you can solve this problem using a formal specification |
| 34 | language like [TLA+](https://en.wikipedia.org/wiki/TLA%2B). I don't know |
| 35 | much about this topic, but it appears that a [formal specification language](https://en.wikipedia.org/wiki/Formal_specification) |
| 36 | is much like a programming language in that it lets you describe the |
| 37 | behavior of a system. However, it's much more rigorous and builds |
| 38 | on mathematical techniques that enable you to reason more effectively |
| 39 | about the behavior of the system you're describing than you can with |
| 40 | a typical programming language. |
| 41 | |
| 42 | In a recent discussion on Hacker News about TLA+, |
| 43 | I came across [this comment](https://news.ycombinator.com/item?id=13919251) |
| 44 | which linked to a fun and simple example |
| 45 | showing [how to solve the Die Hard 3 problem with TLA+](https://github.com/tlaplus/Examples/blob/master/specifications/DieHard/DieHard.tla). |
| 46 | I had to watch the first two lectures from [Leslie Lamport's video course on TLA+](http://lamport.azurewebsites.net/video/videos.html) |
| 47 | to understand the example well, but once I did I was reminded of the |
| 48 | idea of property-based testing and, specifically, [Hypothesis](http://hypothesis.works/). |
| 49 | |
| 50 | So what's property-based testing? It's a powerful way of testing your |
| 51 | logic by giving your machine a high-level description of how your code |
| 52 | should behave and letting it generate test cases automatically to see |
| 53 | if that description holds. Compare that to traditional unit testing, |
| 54 | for example, where you manually code up specific inputs and outputs |
| 55 | and make sure they match. |
| 56 | |
| 57 | ## How not to Die Hard with Hypothesis |
| 58 | |
| 59 | Hypothesis has an excellent implementation of property-based testing |
| 60 | [for Python](https://github.com/HypothesisWorks/hypothesis-python). |
| 61 | I thought to myself: I wonder if you can write that |
| 62 | Die Hard specification using Hypothesis? As it turns out, Hypothesis |
| 63 | supports [stateful testing](https://hypothesis.readthedocs.io/en/latest/stateful.html), |
| 64 | and I was able to port the [TLA+ example](https://github.com/tlaplus/Examples/blob/master/specifications/DieHard/DieHard.tla) |
| 65 | to Python pretty easily: |
| 66 | |
| 67 | ```python |
| 68 | from hypothesis import note, settings |
| 69 | from hypothesis.stateful import RuleBasedStateMachine, invariant, rule |
| 70 | |
| 71 | |
| 72 | # The default is not always enough for Hypothesis to find a failing example. |
| 73 | @settings(max_examples=2000) |
| 74 | class DieHardProblem(RuleBasedStateMachine): |
| 75 | small = 0 |
| 76 | big = 0 |
| 77 | |
| 78 | @rule() |
| 79 | def fill_small(self): |
| 80 | self.small = 3 |
| 81 | |
| 82 | @rule() |
| 83 | def fill_big(self): |
| 84 | self.big = 5 |
| 85 | |
| 86 | @rule() |
| 87 | def empty_small(self): |
| 88 | self.small = 0 |
| 89 | |
| 90 | @rule() |
| 91 | def empty_big(self): |
| 92 | self.big = 0 |
| 93 | |
| 94 | @rule() |
| 95 | def pour_small_into_big(self): |
| 96 | old_big = self.big |
| 97 | self.big = min(5, self.big + self.small) |
| 98 | self.small = self.small - (self.big - old_big) |
| 99 | |
| 100 | @rule() |
| 101 | def pour_big_into_small(self): |
| 102 | old_small = self.small |
| 103 | self.small = min(3, self.small + self.big) |
| 104 | self.big = self.big - (self.small - old_small) |
| 105 | |
| 106 | @invariant() |
| 107 | def physics_of_jugs(self): |
| 108 | assert 0 <= self.small <= 3 |
| 109 | assert 0 <= self.big <= 5 |
| 110 | |
| 111 | @invariant() |
| 112 | def die_hard_problem_not_solved(self): |
| 113 | note(f"> small: {self.small} big: {self.big}") |
| 114 | assert self.big != 4 |
| 115 | |
| 116 | |
| 117 | DieHardTest = DieHardProblem.TestCase |
| 118 | ``` |
| 119 | |
| 120 | Calling `pytest` on this file quickly digs up a solution: |
| 121 | |
| 122 | ``` |
| 123 | self = DieHardProblem({}) |
| 124 | |
| 125 | @invariant() |
| 126 | def die_hard_problem_not_solved(self): |
| 127 | note("> small: {s} big: {b}".format(s=self.small, b=self.big)) |
| 128 | > assert self.big != 4 |
| 129 | E AssertionError: assert 4 != 4 |
| 130 | E + where 4 = DieHardProblem({}).big |
| 131 | |
| 132 | how-not-to-die-hard-with-hypothesis.py:17: AssertionError |
| 133 | ----------------------------- Hypothesis ----------------------------- |
| 134 | > small: 0 big: 0 |
| 135 | Step #1: fill_big() |
| 136 | > small: 0 big: 5 |
| 137 | Step #2: pour_big_into_small() |
| 138 | > small: 3 big: 2 |
| 139 | Step #3: empty_small() |
| 140 | > small: 0 big: 2 |
| 141 | Step #4: pour_big_into_small() |
| 142 | > small: 2 big: 0 |
| 143 | Step #5: fill_big() |
| 144 | > small: 2 big: 5 |
| 145 | Step #6: pour_big_into_small() |
| 146 | > small: 3 big: 4 |
| 147 | ====================== 1 failed in 0.22 seconds ====================== |
| 148 | ``` |
| 149 | |
| 150 | ## What's Going on Here |
| 151 | |
| 152 | The code and test output are pretty self-explanatory, but here's a |
| 153 | recap of what's going on: |
| 154 | |
| 155 | We're defining a state machine. That state machine has an initial |
| 156 | state (two empty jugs) along with some possible transitions. Those |
| 157 | transitions are captured with the `rule()` decorator. The initial |
| 158 | state and possible transitions together define how our system works. |
| 159 | |
| 160 | Next we define invariants, which are properties that must always hold |
| 161 | true in our system. Our first invariant, `physics_of_jugs`, says that |
| 162 | the jugs must hold an amount of water that makes sense. For example, |
| 163 | the big jug can never hold more than 5 gallons of water. |
| 164 | |
| 165 | Our next invariant, `die_hard_problem_not_solved`, is where it gets |
| 166 | interesting. Here we're declaring that the problem of getting exactly |
| 167 | 4 gallons in the big jug _cannot_ be solved. Since Hypothesis's job |
| 168 | is to test our logic for bugs, it will give our state machine a |
| 169 | thorough shake down and see if we ever violate our invariants. |
| 170 | In other words, we're basically goading Hypothesis into solving the |
| 171 | Die Hard problem for us. |
| 172 | |
| 173 | I'm not entirely clear on how Hypothesis does its work, but I know |
| 174 | the basic summary is this: It takes the program properties we've |
| 175 | specified -- including things like rules, invariants, data types, and |
| 176 | function signatures -- and generates data or actions to probe the |
| 177 | behavior of our program. If Hypothesis finds a piece of data or |
| 178 | sequence of actions that get our program to violate its stated properties, it |
| 179 | tries to whittle that down to a _minimum falsifying example_---i.e. |
| 180 | something that exposes the same problem but with a minimum number of |
| 181 | steps. This makes it much easier for you to understand how Hypothesis |
| 182 | broke your code. |
| 183 | |
| 184 | Hypothesis's output above tells us that it was able to violate the |
| 185 | `die_hard_problem_not_solved` invariant and provides us with a |
| 186 | minimal reproduction showing exactly how it did so. That reproduction |
| 187 | is our solution to the problem. It's also how McClane and Carver did |
| 188 | it in the movie! |
| 189 | |
| 190 | ## Final Thoughts |
| 191 | |
| 192 | All in all, I was pretty impressed with how straightforward it was to |
| 193 | translate the TLA+ example into Python using Hypothesis. And when |
| 194 | Hypothesis spit out the solution, I couldn't help but smile. It's |
| 195 | pretty cool to see your computer essentially generate a program that |
| 196 | solves a problem for you. And the Python version of the Die Hard |
| 197 | "spec" is not much more verbose than the |
| 198 | original in TLA+, though TLA+'s notation for current vs. next value |
| 199 | (e.g. `small` vs. `small'`) is elegant and cuts out the need to have |
| 200 | variables like `old_small` and `old_big`. |
| 201 | |
| 202 | I don't know how Hypothesis compares to TLA+ in a general sense. I've |
| 203 | only just started to learn about property-based testing and TLA+, and |
| 204 | I wonder if they have a place in the work that I do these days, which |
| 205 | is mostly Data Engineering-type stuff. Still, I found this little |
| 206 | exercise fun, and I hope you learned something interesting from it. |
| 207 | |
| 208 | _Thanks to [Julia], [Dan], Laura, Anjana, and Cip for reading drafts |
| 209 | of this post._ |
| 210 | |
| 211 | [Julia]: http://jvns.ca/ |
| 212 | [Dan]: https://danluu.com/ |