88# v. 2.0. If a copy of the MPL was not distributed with this file, You can
99# obtain one at https://mozilla.org/MPL/2.0/.
1010
11+ import datetime
1112import math
1213import time
14+ import types
15+ import weakref
1316from collections import defaultdict
1417from collections .abc import Hashable , Iterable , Iterator , Sequence
1518from dataclasses import dataclass , field
7275from hypothesis .internal .intervalsets import IntervalSet
7376from hypothesis .internal .observability import PredicateCounts
7477from hypothesis .reporting import debug_report
75- from hypothesis .utils .conventions import not_set
78+ from hypothesis .utils .conventions import UniqueIdentifier , not_set
7679from hypothesis .utils .deprecation import note_deprecation
7780from hypothesis .utils .threading import ThreadLocal
7881
@@ -141,9 +144,26 @@ def structural_coverage(label: int) -> StructuralCoverageTag:
141144# performance. We lose scan resistance, but that's probably fine here.
142145POOLED_CONSTRAINTS_CACHE : LRUCache [tuple [Any , ...], ChoiceConstraintsT ] = LRUCache (4096 )
143146
144- # A tuple rather than a set so that ``in`` works even if a value's class has
145- # an unhashable metaclass. Exact type checks also exclude symbolic backends.
146- _PRIMITIVE_CHOICE_TYPES : tuple [type , ...] = (int , bool , str , bytes , float )
147+ # The exact types whose values record_value_for_span holds directly: small
148+ # immutable stdlib types, none of which support weak references. Values of
149+ # any other type are held via weakref where possible, so that recording never
150+ # extends an object's lifetime. A tuple rather than a set so that ``in``
151+ # works even if a value's class has an unhashable metaclass. Exact type
152+ # checks also exclude symbolic backends.
153+ _RECORDABLE_VALUE_TYPES : tuple [type , ...] = (
154+ int ,
155+ bool ,
156+ str ,
157+ bytes ,
158+ float ,
159+ types .NoneType ,
160+ datetime .date ,
161+ datetime .time ,
162+ datetime .datetime ,
163+ datetime .timedelta ,
164+ )
165+
166+ no_recorded_value = UniqueIdentifier ("no_recorded_value" )
147167
148168
149169class Span :
@@ -249,9 +269,13 @@ def children(self) -> "list[Span]":
249269 @property
250270 def recorded_value (self ) -> Any :
251271 """The value produced by the strategy draw corresponding to this span,
252- or ``None`` if no value was recorded. Only values of the primitive
253- choice types (int, bool, float, str, bytes) are recorded."""
254- return self .owner .span_values .get (self .index )
272+ or the ``no_recorded_value`` sentinel if no value was recorded, or if
273+ a weakly-referenced value has since been collected."""
274+ value = self .owner .span_values .get (self .index , no_recorded_value )
275+ if isinstance (value , weakref .ReferenceType ):
276+ referent = value ()
277+ return no_recorded_value if referent is None else referent
278+ return value
255279
256280
257281class SpanProperty :
@@ -363,12 +387,17 @@ def stop_span(self, *, discard: bool) -> None:
363387 self .trail .append (TrailType .STOP_SPAN_NO_DISCARD )
364388
365389 def record_value_for_span (self , span_index : int , value : Any ) -> None :
366- # Record ``value`` against the span at ``span_index``, if it is one of
367- # the primitive choice types. Called by ConjectureData.draw with the
368- # value each strategy's do_draw returned.
369- if type (value ) not in _PRIMITIVE_CHOICE_TYPES :
370- return
371- self .span_values [span_index ] = value
390+ # Record ``value`` against the span at ``span_index``. Called by
391+ # ConjectureData.draw with the value each strategy's do_draw returned.
392+ # Values which can be neither held directly nor weakly referenced
393+ # (e.g. stdlib containers) are not recorded, and so cannot widen.
394+ if type (value ) in _RECORDABLE_VALUE_TYPES :
395+ self .span_values [span_index ] = value
396+ else :
397+ try :
398+ self .span_values [span_index ] = weakref .ref (value )
399+ except TypeError :
400+ pass
372401
373402
374403class _starts_and_ends (SpanProperty ):
@@ -740,6 +769,7 @@ def __init__(
740769 self .expected_traceback : str | None = None
741770
742771 self .prefix = prefix
772+ self ._inverting = False
743773 self .nodes : tuple [ChoiceNode , ...] = ()
744774 self .misaligned_at : MisalignedAt | None = None
745775 self .cannot_proceed_scope : CannotProceedScopeT | None = None
@@ -822,6 +852,11 @@ def _draw(
822852 observe : bool ,
823853 forced : ChoiceT | None ,
824854 ) -> ChoiceT :
855+ if self ._inverting :
856+ # A strategy tried to draw while re-encoding a ValueHole - e.g. a
857+ # filter predicate which draws, like stateful's rule filters.
858+ # Inversions must be pure, so treat this as unencodable.
859+ raise CannotInvert ("cannot draw during _invert" )
825860 # this is somewhat redundant with the length > max_length check at the
826861 # end of the function, but avoids trying to use a null self.random when
827862 # drawing past the node of a ConjectureData.for_choices data.
@@ -1249,6 +1284,7 @@ def draw(
12491284 and self .index < len (self .prefix )
12501285 and isinstance (hole := self .prefix [self .index ], ValueHole )
12511286 ):
1287+ self ._inverting = True
12521288 try :
12531289 inverted = unwrapped ._invert (hole .value )
12541290 except CannotInvert :
@@ -1259,6 +1295,8 @@ def draw(
12591295 + inverted
12601296 + tuple (self .prefix [self .index + 1 :])
12611297 )
1298+ finally :
1299+ self ._inverting = False
12621300
12631301 span_index = self .__span_record .span_count
12641302 self .start_span (label = label )
0 commit comments