/
shrinker.py
1584 lines (1319 loc) · 62.6 KB
/
shrinker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
#
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Most of this work is copyright (C) 2013-2019 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold copyright, and
# consult the git log if you need to determine who owns an individual
# contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
#
# END HEADER
from __future__ import absolute_import, division, print_function
from collections import defaultdict
import attr
from hypothesis.internal.compat import hbytes, hrange, int_from_bytes, int_to_bytes
from hypothesis.internal.conjecture.data import ConjectureResult, Overrun, Status
from hypothesis.internal.conjecture.floats import (
DRAW_FLOAT_LABEL,
float_to_lex,
lex_to_float,
)
from hypothesis.internal.conjecture.junkdrawer import (
binary_search,
pop_random,
replace_all,
)
from hypothesis.internal.conjecture.shrinking import Float, Integer, Lexical, Ordering
from hypothesis.internal.conjecture.shrinking.common import find_integer
if False:
from typing import Dict # noqa
def sort_key(buffer):
"""Returns a sort key such that "simpler" buffers are smaller than
"more complicated" ones.
We define sort_key so that x is simpler than y if x is shorter than y or if
they have the same length and x < y lexicographically. This is called the
shortlex order.
The reason for using the shortlex order is:
1. If x is shorter than y then that means we had to make fewer decisions
in constructing the test case when we ran x than we did when we ran y.
2. If x is the same length as y then replacing a byte with a lower byte
corresponds to reducing the value of an integer we drew with draw_bits
towards zero.
3. We want a total order, and given (2) the natural choices for things of
the same size are either the lexicographic or colexicographic orders
(the latter being the lexicographic order of the reverse of the string).
Because values drawn early in generation potentially get used in more
places they potentially have a more significant impact on the final
result, so it makes sense to prioritise reducing earlier values over
later ones. This makes the lexicographic order the more natural choice.
"""
return (len(buffer), buffer)
SHRINK_PASS_DEFINITIONS = {} # type: Dict[str, ShrinkPassDefinition]
@attr.s()
class ShrinkPassDefinition(object):
"""A shrink pass bundles together a large number of local changes to
the current shrink target.
Each shrink pass is defined by some function and some arguments to that
function. The ``generate_arguments`` function returns all arguments that
might be useful to run on the current shrink target.
The guarantee made by methods defined this way is that after they are
called then *either* the shrink target has changed *or* each of
``fn(*args)`` has been called for every ``args`` in ``generate_arguments(self)``.
No guarantee is made that all of these will be called if the shrink target
changes.
"""
run_step = attr.ib()
generate_arguments = attr.ib()
@property
def name(self):
return self.run_step.__name__
def __attrs_post_init__(self):
assert self.name not in SHRINK_PASS_DEFINITIONS, self.name
SHRINK_PASS_DEFINITIONS[self.name] = self
def defines_shrink_pass(generate_arguments):
"""A convenient decorator for defining shrink passes."""
def accept(run_step):
definition = ShrinkPassDefinition(
generate_arguments=generate_arguments, run_step=run_step
)
def run(self):
assert False, "Shrink passes should not be run directly"
run.__name__ = run_step.__name__
run.is_shrink_pass = True
return run
return accept
class Shrinker(object):
"""A shrinker is a child object of a ConjectureRunner which is designed to
manage the associated state of a particular shrink problem. That is, we
have some initial ConjectureData object and some property of interest
that it satisfies, and we want to find a ConjectureData object with a
shortlex (see sort_key above) smaller buffer that exhibits the same
property.
Currently the only property of interest we use is that the status is
INTERESTING and the interesting_origin takes on some fixed value, but we
may potentially be interested in other use cases later.
However we assume that data with a status < VALID never satisfies the predicate.
The shrinker keeps track of a value shrink_target which represents the
current best known ConjectureData object satisfying the predicate.
It refines this value by repeatedly running *shrink passes*, which are
methods that perform a series of transformations to the current shrink_target
and evaluate the underlying test function to find new ConjectureData
objects. If any of these satisfy the predicate, the shrink_target
is updated automatically. Shrinking runs until no shrink pass can
improve the shrink_target, at which point it stops. It may also be
terminated if the underlying engine throws RunIsComplete, but that
is handled by the calling code rather than the Shrinker.
=======================
Designing Shrink Passes
=======================
Generally a shrink pass is just any function that calls
cached_test_function and/or incorporate_new_buffer a number of times,
but there are a couple of useful things to bear in mind.
A shrink pass *makes progress* if running it changes self.shrink_target
(i.e. it tries a shortlex smaller ConjectureData object satisfying
the predicate). The desired end state of shrinking is to find a
value such that no shrink pass can make progress, i.e. that we
are at a local minimum for each shrink pass.
In aid of this goal, the main invariant that a shrink pass much
satisfy is that whether it makes progress must be deterministic.
It is fine (encouraged even) for the specific progress it makes
to be non-deterministic, but if you run a shrink pass, it makes
no progress, and then you immediately run it again, it should
never succeed on the second time. This allows us to stop as soon
as we have run each shrink pass and seen no progress on any of
them.
This means that e.g. it's fine to try each of N deletions
or replacements in a random order, but it's not OK to try N random
deletions (unless you have already shrunk at least once, though we
don't currently take advantage of this loophole).
Shrink passes need to be written so as to be robust against
change in the underlying shrink target. It is generally safe
to assume that the shrink target does not change prior to the
point of first modification - e.g. if you change no bytes at
index ``i``, all examples whose start is ``<= i`` still exist,
as do all blocks, and the data object is still of length
``>= i + 1``. This can only be violated by bad user code which
relies on an external source of non-determinism.
When the underlying shrink_target changes, shrink
passes should not run substantially more test_function calls
on success than they do on failure. Say, no more than a constant
factor more. In particular shrink passes should not iterate to a
fixed point.
This means that shrink passes are often written with loops that
are carefully designed to do the right thing in the case that no
shrinks occurred and try to adapt to any changes to do a reasonable
job. e.g. say we wanted to write a shrink pass that tried deleting
each individual byte (this isn't an especially good choice,
but it leads to a simple illustrative example), we might do it
by iterating over the buffer like so:
.. code-block:: python
i = 0
while i < len(self.shrink_target.buffer):
if not self.incorporate_new_buffer(
self.shrink_target.buffer[: i] +
self.shrink_target.buffer[i + 1 :]
):
i += 1
The reason for writing the loop this way is that i is always a
valid index into the current buffer, even if the current buffer
changes as a result of our actions. When the buffer changes,
we leave the index where it is rather than restarting from the
beginning, and carry on. This means that the number of steps we
run in this case is always bounded above by the number of steps
we would run if nothing works.
Another thing to bear in mind about shrink pass design is that
they should prioritise *progress*. If you have N operations that
you need to run, you should try to order them in such a way as
to avoid stalling, where you have long periods of test function
invocations where no shrinks happen. This is bad because whenever
we shrink we reduce the amount of work the shrinker has to do
in future, and often speed up the test function, so we ideally
wanted those shrinks to happen much earlier in the process.
Sometimes stalls are inevitable of course - e.g. if the pass
makes no progress, then the entire thing is just one long stall,
but it's helpful to design it so that stalls are less likely
in typical behaviour.
The two easiest ways to do this are:
* Just run the N steps in random order. As long as a
reasonably large proportion of the operations suceed, this
guarantees the expected stall length is quite short. The
book keeping for making sure this does the right thing when
it succeeds can be quite annoying.
* When you have any sort of nested loop, loop in such a way
that both loop variables change each time. This prevents
stalls which occur when one particular value for the outer
loop is impossible to make progress on, rendering the entire
inner loop into a stall.
However, although progress is good, too much progress can be
a bad sign! If you're *only* seeing successful reductions,
that's probably a sign that you are making changes that are
too timid. Two useful things to offset this:
* It's worth writing shrink passes which are *adaptive*, in
the sense that when operations seem to be working really
well we try to bundle multiple of them together. This can
often be used to turn what would be O(m) successful calls
into O(log(m)).
* It's often worth trying one or two special minimal values
before trying anything more fine grained (e.g. replacing
the whole thing with zero).
"""
def derived_value(fn):
"""It's useful during shrinking to have access to derived values of
the current shrink target.
This decorator allows you to define these as cached properties. They
are calculated once, then cached until the shrink target changes, then
recalculated the next time they are used."""
def accept(self):
try:
return self.__derived_values[fn.__name__]
except KeyError:
return self.__derived_values.setdefault(fn.__name__, fn(self))
accept.__name__ = fn.__name__
return property(accept)
def __init__(self, engine, initial, predicate):
"""Create a shrinker for a particular engine, with a given starting
point and predicate. When shrink() is called it will attempt to find an
example for which predicate is True and which is strictly smaller than
initial.
Note that initial is a ConjectureData object, and predicate
takes ConjectureData objects.
"""
self.__engine = engine
self.__predicate = predicate
self.__shrinking_prefixes = set()
self.__derived_values = {}
self.__pending_shrink_explanation = None
self.initial_size = len(initial.buffer)
# We keep track of the current best example on the shrink_target
# attribute.
self.shrink_target = None
self.update_shrink_target(initial)
self.shrinks = 0
self.initial_calls = self.__engine.call_count
self.passes_by_name = {}
self.passes = []
def explain_next_call_as(self, explanation):
self.__pending_shrink_explanation = explanation
def clear_call_explanation(self):
self.__pending_shrink_explanation = None
def add_new_pass(self, run):
"""Creates a shrink pass corresponding to calling ``run(self)``"""
definition = SHRINK_PASS_DEFINITIONS[run]
p = ShrinkPass(
run_with_arguments=definition.run_step,
generate_arguments=definition.generate_arguments,
shrinker=self,
index=len(self.passes),
)
self.passes.append(p)
self.passes_by_name[p.name] = p
return p
def shrink_pass(self, name):
"""Return the ShrinkPass object for the pass with the given name."""
if isinstance(name, ShrinkPass):
return name
if name not in self.passes_by_name:
self.add_new_pass(name)
return self.passes_by_name[name]
@property
def calls(self):
"""Return the number of calls that have been made to the underlying
test function."""
return self.__engine.call_count
def consider_new_buffer(self, buffer):
"""Returns True if after running this buffer the result would be
the current shrink_target."""
buffer = hbytes(buffer)
return buffer.startswith(self.buffer) or self.incorporate_new_buffer(buffer)
def incorporate_new_buffer(self, buffer):
"""Either runs the test function on this buffer and returns True if
that changed the shrink_target, or determines that doing so would
be useless and returns False without running it."""
buffer = hbytes(buffer[: self.shrink_target.index])
# Sometimes an attempt at lexicographic minimization will do the wrong
# thing because the buffer has changed under it (e.g. something has
# turned into a write, the bit size has changed). The result would be
# an invalid string, but it's better for us to just ignore it here as
# it turns out to involve quite a lot of tricky book-keeping to get
# this right and it's better to just handle it in one place.
if sort_key(buffer) >= sort_key(self.shrink_target.buffer):
return False
if self.shrink_target.buffer.startswith(buffer):
return False
previous = self.shrink_target
self.cached_test_function(buffer)
return previous is not self.shrink_target
def incorporate_test_data(self, data):
"""Takes a ConjectureData or Overrun object updates the current
shrink_target if this data represents an improvement over it,
returning True if it is."""
if data is Overrun or data is self.shrink_target:
return
if self.__predicate(data) and sort_key(data.buffer) < sort_key(
self.shrink_target.buffer
):
self.update_shrink_target(data)
self.__shrinking_block_cache = {}
return True
return False
def cached_test_function(self, buffer):
"""Returns a cached version of the underlying test function, so
that the result is either an Overrun object (if the buffer is
too short to be a valid test case) or a ConjectureData object
with status >= INVALID that would result from running this buffer."""
if self.__pending_shrink_explanation is not None:
self.debug(self.__pending_shrink_explanation)
self.__pending_shrink_explanation = None
buffer = hbytes(buffer)
result = self.__engine.cached_test_function(buffer)
self.incorporate_test_data(result)
return result
def debug(self, msg):
self.__engine.debug(msg)
@property
def random(self):
return self.__engine.random
def shrink(self):
"""Run the full set of shrinks and update shrink_target.
This method is "mostly idempotent" - calling it twice is unlikely to
have any effect, though it has a non-zero probability of doing so.
"""
# We assume that if an all-zero block of bytes is an interesting
# example then we're not going to do better than that.
# This might not technically be true: e.g. for integers() | booleans()
# the simplest example is actually [1, 0]. Missing this case is fairly
# harmless and this allows us to make various simplifying assumptions
# about the structure of the data (principally that we're never
# operating on a block of all zero bytes so can use non-zeroness as a
# signpost of complexity).
if not any(self.shrink_target.buffer) or self.incorporate_new_buffer(
hbytes(len(self.shrink_target.buffer))
):
return
try:
self.greedy_shrink()
finally:
if self.__engine.report_debug_info:
def s(n):
return "s" if n != 1 else ""
total_deleted = self.initial_size - len(self.shrink_target.buffer)
self.debug("---------------------")
self.debug("Shrink pass profiling")
self.debug("---------------------")
self.debug("")
calls = self.__engine.call_count - self.initial_calls
self.debug(
(
"Shrinking made a total of %d call%s "
"of which %d shrank. This deleted %d byte%s out of %d."
)
% (
calls,
s(calls),
self.shrinks,
total_deleted,
s(total_deleted),
self.initial_size,
)
)
for useful in [True, False]:
self.debug("")
if useful:
self.debug("Useful passes:")
else:
self.debug("Useless passes:")
self.debug("")
for p in sorted(
self.passes,
key=lambda t: (-t.calls, -t.runs, t.deletions, t.shrinks),
):
if p.calls == 0:
continue
if (p.shrinks != 0) != useful:
continue
self.debug(
(
" * %s ran %d time%s, making %d call%s of which "
"%d shrank, deleting %d byte%s."
)
% (
p.name,
p.runs,
s(p.runs),
p.calls,
s(p.calls),
p.shrinks,
p.deletions,
s(p.deletions),
)
)
self.debug("")
def greedy_shrink(self):
"""Run a full set of greedy shrinks (that is, ones that will only ever
move to a better target) and update shrink_target appropriately.
This method iterates to a fixed point and so is idempontent - calling
it twice will have exactly the same effect as calling it once.
"""
self.fixate_shrink_passes(
[
block_program("X" * 5),
block_program("X" * 4),
block_program("X" * 3),
block_program("X" * 2),
block_program("X" * 1),
"pass_to_descendant",
"adaptive_example_deletion",
"alphabet_minimize",
"zero_examples",
"reorder_examples",
"minimize_floats",
"minimize_duplicated_blocks",
"minimize_individual_blocks",
block_program("-XX"),
"example_deletion_with_block_lowering",
]
)
def fixate_shrink_passes(self, passes):
"""Run steps from each pass in ``passes`` until the current shrink target
is a fixed point of all of them."""
passes = list(map(self.shrink_pass, passes))
initial = None
while initial is not self.shrink_target:
initial = self.shrink_target
for sp in passes:
sp.runs += 1
# We run remove_discarded after every step to do cleanup
# keeping track of whether that actually works. Either there is
# no discarded data and it is basically free, or it reliably works
# and deletes data, or it doesn't work. In that latter case we turn
# it off for the rest of this loop through the passes, but will
# try again once all of the passes have been run.
can_discard = self.remove_discarded()
# We want to run all steps from each pass, but the order in which
# we do this makes a fairly significant difference. If a pass has
# a lot of steps but is useless, we'd like to defer running those
# steps (many of which will become faster or irrelevant) until
# after other, better, passes have had a chance to run.
#
# An ideal outcome would be that we take every pass/step pair,
# run every one of these pairs that would produce a successful
# shrink, then run every pair that wouldn't.
#
# Doing this would of course require us to be magically good at
# predicting which pairs would work, and if we could do that then
# we wouldn't bother running the unsuccessful ones at all. Instead
# what we do is we iterate over them in an order that prioritises
# passes that seem to work well and penalises ones that make useless
# test calls.
# The passes we've not run to completion yet, along with the steps
# they've yet to run. The steps start out as None, so that we only
# calculate the list the first time we run the pass. This is because
# if the shrink target changes between calculating steps and running
# them, a lot of the steps become invalid. Particularly when the
# initial shrink target is large and thus there are a lot of steps
# this is potentially fairly wasteful, so we defer calculation to
# point of first usage where they will definitely be valid.
passes_with_steps = [(sp, None) for sp in passes]
# Run passes that are already at a fixed point last, so that we've
# had a chance to unlock them by the time we come to run them.
passes_with_steps.sort(
key=lambda t: t[0].fixed_point_at is self.shrink_target
)
successful_passes = set()
while passes_with_steps:
to_run_next = []
for sp, steps in passes_with_steps:
if steps is None:
steps = sp.generate_steps()
# We run each pass until it has failed a certain number
# of times, where a "failure" is any step where it made
# at least one call and did not result in a shrink.
# This gives passes which work reasonably often more of
# chance to run.
failures = 0
successes = 0
# The choice of 3 is fairly arbitrary and was hand tuned
# to some particular examples. It is very unlikely that
# is the best choice in general, but it's not an
# unreasonable choice: Making it smaller than this would
# give too high a chance of an otherwise very worthwhile
# pass getting screened out too early if it got unlucky,
# and making it much larger than this would result in us
# spending too much time on bad passes.
max_failures = 3
while steps and failures < max_failures:
prev_calls = self.calls
prev = self.shrink_target
sp.run_step(pop_random(self.random, steps))
if prev_calls != self.calls:
if can_discard:
can_discard = self.remove_discarded()
if prev is self.shrink_target:
failures += 1
else:
successes += 1
if steps:
to_run_next.append((sp, steps))
if successes > 0:
successful_passes.add(sp)
passes_with_steps = to_run_next
# If only some of our shrink passes are doing anything useful
# then run all of those to a fixed point before running the
# full set. This is particularly important when an emergency
# shrink pass unlocks some non-emergency ones and it suddenly
# becomes very expensive to find a bunch of small changes.
if 0 < len(successful_passes) < len(passes):
self.fixate_shrink_passes(successful_passes)
for sp in passes:
sp.fixed_point_at = self.shrink_target
@property
def buffer(self):
return self.shrink_target.buffer
@property
def blocks(self):
return self.shrink_target.blocks
@property
def examples(self):
return self.shrink_target.examples
def all_block_bounds(self):
return self.shrink_target.blocks.all_bounds()
@derived_value
def examples_by_label(self):
"""An index of all examples grouped by their label, with
the examples stored in their normal index order."""
examples_by_label = defaultdict(list)
for ex in self.examples:
examples_by_label[ex.label].append(ex)
return dict(examples_by_label)
def calculate_descents(self):
"""Returns a list of all pairs (i, j) such that
self.examples[i] is an ancestor of self.examples[j] and
they have the same label.
"""
result = []
for ls in self.examples_by_label.values():
if len(ls) <= 1:
continue
for i, ex in enumerate(ls[:-1]):
hi = len(ls)
lo = i + 1
if ls[lo].start >= ex.end:
continue
while lo + 1 < hi:
mid = (lo + hi) // 2
if ls[mid].start >= ex.end:
hi = mid
else:
lo = mid
id1 = self.stable_identifier_for_example(ex)
result.extend(
[
(id1, self.stable_identifier_for_example(ls[j]))
for j in hrange(i + 1, hi)
]
)
return result
@defines_shrink_pass(calculate_descents)
def pass_to_descendant(self, ancestor_id, descendant_id):
"""Attempt to replace each example with a descendant example.
This is designed to deal with strategies that call themselves
recursively. For example, suppose we had:
binary_tree = st.deferred(
lambda: st.one_of(
st.integers(), st.tuples(binary_tree, binary_tree)))
This pass guarantees that we can replace any binary tree with one of
its subtrees - each of those will create an interval that the parent
could validly be replaced with, and this pass will try doing that.
This is pretty expensive - it takes O(len(intervals)^2) - so we run it
late in the process when we've got the number of intervals as far down
as possible.
"""
ancestor = self.example_for_stable_identifier(ancestor_id)
descendant = self.example_for_stable_identifier(descendant_id)
if descendant is None:
return
assert ancestor is not None
self.incorporate_new_buffer(
self.buffer[: ancestor.start]
+ self.buffer[descendant.start : descendant.end]
+ self.buffer[ancestor.end :]
)
def is_shrinking_block(self, i):
"""Checks whether block i has been previously marked as a shrinking
block.
If the shrink target has changed since i was last checked, will
attempt to calculate if an equivalent block in a previous shrink
target was marked as shrinking.
"""
if not self.__shrinking_prefixes:
return False
try:
return self.__shrinking_block_cache[i]
except KeyError:
pass
t = self.shrink_target
return self.__shrinking_block_cache.setdefault(
i, t.buffer[: t.blocks[i].start] in self.__shrinking_prefixes
)
def lower_common_block_offset(self):
"""Sometimes we find ourselves in a situation where changes to one part
of the byte stream unlock changes to other parts. Sometimes this is
good, but sometimes this can cause us to exhibit exponential slow
downs!
e.g. suppose we had the following:
m = draw(integers(min_value=0))
n = draw(integers(min_value=0))
assert abs(m - n) > 1
If this fails then we'll end up with a loop where on each iteration we
reduce each of m and n by 2 - m can't go lower because of n, then n
can't go lower because of m.
This will take us O(m) iterations to complete, which is exponential in
the data size, as we gradually zig zag our way towards zero.
This can only happen if we're failing to reduce the size of the byte
stream: The number of iterations that reduce the length of the byte
stream is bounded by that length.
So what we do is this: We keep track of which blocks are changing, and
then if there's some non-zero common offset to them we try and minimize
them all at once by lowering that offset.
This may not work, and it definitely won't get us out of all possible
exponential slow downs (an example of where it doesn't is where the
shape of the blocks changes as a result of this bouncing behaviour),
but it fails fast when it doesn't work and gets us out of a really
nastily slow case when it does.
"""
if len(self.__changed_blocks) <= 1:
return
current = self.shrink_target
blocked = [current.buffer[u:v] for u, v in self.all_block_bounds()]
changed = [
i
for i in sorted(self.__changed_blocks)
if not self.shrink_target.blocks[i].trivial
]
if not changed:
return
ints = [int_from_bytes(blocked[i]) for i in changed]
offset = min(ints)
assert offset > 0
for i in hrange(len(ints)):
ints[i] -= offset
def reoffset(o):
new_blocks = list(blocked)
for i, v in zip(changed, ints):
new_blocks[i] = int_to_bytes(v + o, len(blocked[i]))
return self.incorporate_new_buffer(hbytes().join(new_blocks))
Integer.shrink(offset, reoffset, random=self.random)
self.clear_change_tracking()
def mark_shrinking(self, blocks):
"""Mark each of these blocks as a shrinking block: That is, lowering
its value lexicographically may cause less data to be drawn after."""
t = self.shrink_target
for i in blocks:
if self.__shrinking_block_cache.get(i) is True:
continue
self.__shrinking_block_cache[i] = True
prefix = t.buffer[: t.blocks[i].start]
self.__shrinking_prefixes.add(prefix)
def clear_change_tracking(self):
self.__last_checked_changed_at = self.shrink_target
self.__all_changed_blocks = set()
def mark_changed(self, i):
self.__changed_blocks.add(i)
@property
def __changed_blocks(self):
if self.__last_checked_changed_at is not self.shrink_target:
prev_target = self.__last_checked_changed_at
new_target = self.shrink_target
assert prev_target is not new_target
prev = prev_target.buffer
new = new_target.buffer
assert sort_key(new) < sort_key(prev)
if (
len(new_target.blocks) != len(prev_target.blocks)
or new_target.blocks.endpoints != prev_target.blocks.endpoints
):
self.__all_changed_blocks = set()
else:
blocks = new_target.blocks
# Index of last block whose contents have been modified, found
# by checking if the tail past this point has been modified.
last_changed = binary_search(
0,
len(blocks),
lambda i: prev[blocks.start(i) :] != new[blocks.start(i) :],
)
# Index of the first block whose contents have been changed,
# because we know that this predicate is true for zero (because
# the prefix from the start is empty), so the result must be True
# for the bytes from the start of this block and False for the
# bytes from the end, hence the change is in this block.
first_changed = binary_search(
0,
len(blocks),
lambda i: prev[: blocks.start(i)] == new[: blocks.start(i)],
)
# Between these two changed regions we now do a linear scan to
# check if any specific block values have changed.
for i in hrange(first_changed, last_changed + 1):
u, v = blocks.bounds(i)
if i not in self.__all_changed_blocks and prev[u:v] != new[u:v]:
self.__all_changed_blocks.add(i)
self.__last_checked_changed_at = new_target
assert self.__last_checked_changed_at is self.shrink_target
return self.__all_changed_blocks
def update_shrink_target(self, new_target):
assert isinstance(new_target, ConjectureResult)
if self.shrink_target is not None:
self.shrinks += 1
else:
self.__all_changed_blocks = set()
self.__last_checked_changed_at = new_target
self.shrink_target = new_target
self.__shrinking_block_cache = {}
self.__derived_values = {}
def try_shrinking_blocks(self, blocks, b):
"""Attempts to replace each block in the blocks list with b. Returns
True if it succeeded (which may include some additional modifications
to shrink_target).
May call mark_shrinking with b if this causes a reduction in size.
In current usage it is expected that each of the blocks currently have
the same value, although this is not essential. Note that b must be
< the block at min(blocks) or this is not a valid shrink.
This method will attempt to do some small amount of work to delete data
that occurs after the end of the blocks. This is useful for cases where
there is some size dependency on the value of a block.
"""
initial_attempt = bytearray(self.shrink_target.buffer)
for i, block in enumerate(blocks):
if block >= len(self.blocks):
blocks = blocks[:i]
break
u, v = self.blocks[block].bounds
n = min(self.blocks[block].length, len(b))
initial_attempt[v - n : v] = b[-n:]
if not blocks:
return False
start = self.shrink_target.blocks[blocks[0]].start
end = self.shrink_target.blocks[blocks[-1]].end
initial_data = self.cached_test_function(initial_attempt)
if initial_data.status == Status.INTERESTING:
self.lower_common_block_offset()
return initial_data is self.shrink_target
# If this produced something completely invalid we ditch it
# here rather than trying to persevere.
if initial_data.status < Status.VALID:
return False
# We've shrunk inside our group of blocks, so we have no way to
# continue. (This only happens when shrinking more than one block at
# a time).
if len(initial_data.buffer) < v:
return False
lost_data = len(self.shrink_target.buffer) - len(initial_data.buffer)
# If this did not in fact cause the data size to shrink we
# bail here because it's not worth trying to delete stuff from
# the remainder.
if lost_data <= 0:
return False
self.mark_shrinking(blocks)
# We now look for contiguous regions to delete that might help fix up
# this failed shrink. We only look for contiguous regions of the right
# lengths because doing anything more than that starts to get very
# expensive. See example_deletion_with_block_lowering for where we
# try to be more aggressive.
regions_to_delete = {(end, end + lost_data)}
for j in (blocks[-1] + 1, blocks[-1] + 2):
if j >= min(len(initial_data.blocks), len(self.blocks)):
continue
# We look for a block very shortly after the last one that has
# lost some of its size, and try to delete from the beginning so
# that it retains the same integer value. This is a bit of a hyper
# specific trick designed to make our integers() strategy shrink
# well.
r1, s1 = self.shrink_target.blocks[j].bounds
r2, s2 = initial_data.blocks[j].bounds
lost = (s1 - r1) - (s2 - r2)
# Apparently a coverage bug? An assert False in the body of this
# will reliably fail, but it shows up as uncovered.
if lost <= 0 or r1 != r2: # pragma: no cover
continue
regions_to_delete.add((r1, r1 + lost))
for ex in self.shrink_target.examples:
if ex.start > start:
continue
if ex.end <= end:
continue
replacement = initial_data.examples[ex.index]
in_original = [c for c in ex.children if c.start >= end]
in_replaced = [c for c in replacement.children if c.start >= end]
if len(in_replaced) >= len(in_original) or not in_replaced:
continue
# We've found an example where some of the children went missing
# as a result of this change, and just replacing it with the data
# it would have had and removing the spillover didn't work. This
# means that some of its children towards the right must be
# important, so we try to arrange it so that it retains its
# rightmost children instead of its leftmost.
regions_to_delete.add(
(in_original[0].start, in_original[-len(in_replaced)].start)
)
for u, v in sorted(regions_to_delete, key=lambda x: x[1] - x[0], reverse=True):
try_with_deleted = bytearray(initial_attempt)
del try_with_deleted[u:v]
if self.incorporate_new_buffer(try_with_deleted):
return True
return False
def remove_discarded(self):
"""Try removing all bytes marked as discarded.
This is primarily to deal with data that has been ignored while
doing rejection sampling - e.g. as a result of an integer range, or a
filtered strategy.
Such data will also be handled by the adaptive_example_deletion pass,
but that pass is necessarily more conservative and will try deleting
each interval individually. The common case is that all data drawn and
rejected can just be thrown away immediately in one block, so this pass
will be much faster than trying each one individually when it works.
returns False if there is discarded data and removing it does not work,
otherwise returns True.
"""
while self.shrink_target.has_discards:
discarded = []
for ex in self.shrink_target.examples:
if (
ex.length > 0
and ex.discarded
and (not discarded or ex.start >= discarded[-1][-1])