Debian Codegraph @

hypothesis-python/src/hypothesis/internal/conjecture/optimiser.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 from hypothesis.internal.compat import int_from_bytes, int_to_bytes
12 from hypothesis.internal.conjecture.choice import ChoiceT, choice_permitted
13 from hypothesis.internal.conjecture.data import ConjectureResult, Status, _Overrun
14 from hypothesis.internal.conjecture.engine import ConjectureRunner
15 from hypothesis.internal.conjecture.junkdrawer import bits_to_bytes, find_integer
16 from hypothesis.internal.conjecture.pareto import NO_SCORE
17
18
19 class Optimiser:
20 """A fairly basic optimiser designed to increase the value of scores for
21 targeted property-based testing.
22
23 This implements a fairly naive hill climbing algorithm based on randomly
24 regenerating parts of the test case to attempt to improve the result. It is
25 not expected to produce amazing results, because it is designed to be run
26 in a fairly small testing budget, so it prioritises finding easy wins and
27 bailing out quickly if that doesn't work.
28
29 For more information about targeted property-based testing, see
30 Löscher, Andreas, and Konstantinos Sagonas. "Targeted property-based
31 testing." Proceedings of the 26th ACM SIGSOFT International Symposium on
32 Software Testing and Analysis. ACM, 2017.
33 """
34
35 def __init__(
36 self,
37 engine: ConjectureRunner,
38 data: ConjectureResult,
39 target: str,
40 max_improvements: int = 100,
41 ) -> None:
42 """Optimise ``target`` starting from ``data``. Will stop either when
43 we seem to have found a local maximum or when the target score has
44 been improved ``max_improvements`` times. This limit is in place to
45 deal with the fact that the target score may not be bounded above."""
46 self.engine = engine
47 self.current_data = data
48 self.target = target
49 self.max_improvements = max_improvements
50 self.improvements = 0
51
52 def run(self) -> None:
53 self.hill_climb()
54
55 def score_function(self, data: ConjectureResult) -> float:
56 return data.target_observations.get(self.target, NO_SCORE)
57
58 @property
59 def current_score(self) -> float:
60 return self.score_function(self.current_data)
61
62 def consider_new_data(self, data: ConjectureResult | _Overrun) -> bool:
63 """Consider a new data object as a candidate target. If it is better
64 than the current one, return True."""
65 if data.status < Status.VALID:
66 return False
67 assert isinstance(data, ConjectureResult)
68 score = self.score_function(data)
69 if score < self.current_score:
70 return False
71 if score > self.current_score:
72 self.improvements += 1
73 self.current_data = data
74 return True
75 assert score == self.current_score
76 # We allow transitions that leave the score unchanged as long as they
77 # don't increase the number of nodes. This gives us a certain amount of
78 # freedom for lateral moves that will take us out of local maxima.
79 if len(data.nodes) <= len(self.current_data.nodes):
80 self.current_data = data
81 return True
82 return False
83
84 def hill_climb(self) -> None:
85 """The main hill climbing loop where we actually do the work: Take
86 data, and attempt to improve its score for target. select_example takes
87 a data object and returns an index to an example where we should focus
88 our efforts."""
89
90 nodes_examined = set()
91
92 prev: ConjectureResult | None = None
93 i = len(self.current_data.nodes) - 1
94 while i >= 0 and self.improvements <= self.max_improvements:
95 if prev is not self.current_data:
96 i = len(self.current_data.nodes) - 1
97 prev = self.current_data
98
99 if i in nodes_examined:
100 i -= 1
101 continue
102
103 nodes_examined.add(i)
104 node = self.current_data.nodes[i]
105 assert node.index is not None
106 # we can only (sensibly & easily) define hill climbing for
107 # numeric-style nodes. It's not clear hill-climbing a string is
108 # useful, for instance.
109 if node.type not in {"integer", "float", "bytes", "boolean"}:
110 continue
111
112 def attempt_replace(k: int) -> bool:
113 """
114 Try replacing the current node in the current best test case
115 with a value which is "k times larger", where the exact notion
116 of "larger" depends on the choice_type.
117
118 Note that we use the *current* best and not the one we started with.
119 This helps ensure that if we luck into a good draw when making
120 random choices we get to keep the good bits.
121 """
122 # we don't want to infinitely drive up an unbounded score.
123 if abs(k) > 2**20:
124 return False
125
126 node = self.current_data.nodes[i]
127 assert node.index is not None
128 if node.was_forced:
129 return False # pragma: no cover
130
131 new_choice: ChoiceT
132 if node.type in {"integer", "float"}:
133 assert isinstance(node.value, (int, float))
134 new_choice = node.value + k
135 elif node.type == "boolean":
136 assert isinstance(node.value, bool)
137 if abs(k) > 1:
138 return False
139 if k == -1:
140 new_choice = False
141 if k == 1:
142 new_choice = True
143 if k == 0: # pragma: no cover
144 new_choice = node.value
145 else:
146 assert node.type == "bytes"
147 assert isinstance(node.value, bytes)
148 v = int_from_bytes(node.value)
149 # can't go below zero for bytes
150 if v + k < 0:
151 return False
152 v += k
153 # allow adding k to increase the number of bytes. we don't want
154 # to decrease so that b"01" doesn't turn into b"1".
155 size = max(len(node.value), bits_to_bytes(v.bit_length()))
156 new_choice = int_to_bytes(v, size)
157
158 if not choice_permitted(new_choice, node.constraints):
159 return False
160
161 for _ in range(3):
162 choices = self.current_data.choices
163 attempt_choices = (
164 choices[: node.index]
165 + (new_choice,)
166 + choices[node.index + 1 :]
167 )
168 attempt = self.engine.cached_test_function(
169 attempt_choices, extend="full"
170 )
171
172 if self.consider_new_data(attempt):
173 return True
174
175 if attempt.status is Status.OVERRUN:
176 return False
177
178 assert isinstance(attempt, ConjectureResult)
179 if len(attempt.nodes) == len(self.current_data.nodes):
180 return False
181
182 for j, ex in enumerate(self.current_data.spans):
183 if ex.start >= node.index + 1:
184 break # pragma: no cover
185 if ex.end <= node.index:
186 continue
187 ex_attempt = attempt.spans[j]
188 if ex.choice_count == ex_attempt.choice_count:
189 continue # pragma: no cover
190 replacement = attempt.choices[ex_attempt.start : ex_attempt.end]
191 if self.consider_new_data(
192 self.engine.cached_test_function(
193 choices[: node.index]
194 + replacement
195 + self.current_data.choices[ex.end :]
196 )
197 ):
198 return True
199 return False
200
201 # we don't know whether a target score increases or decreases with
202 # respect to the value of some node, so try both directions.
203 find_integer(lambda k: attempt_replace(k))
204 find_integer(lambda k: attempt_replace(-k))