Skip to content

Commit 552a461

Browse files
Zac-HDclaude
andcommitted
Make date/time drawing symbolic-execution friendly
Rewrite draw_capped_multipart to use branchless arithmetic instead of branching on drawn values, and add a branchless _num_days_in_month helper in place of calendar.monthrange. The generated distribution is unchanged, but symbolic-execution backends such as crosshair can now solve for a specific date directly instead of concretely enumerating candidates. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 2c6dfdb commit 552a461

4 files changed

Lines changed: 69 additions & 8 deletions

File tree

‎hypothesis/RELEASE.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
RELEASE_TYPE: patch
2+
3+
This patch rewrites the internal date- and time-drawing helper to use plain
4+
arithmetic instead of branching on the values it draws. The generated
5+
distribution is unchanged, but :func:`~hypothesis.strategies.dates`,
6+
:func:`~hypothesis.strategies.datetimes`, and
7+
:func:`~hypothesis.strategies.times` are now much more efficient under
8+
symbolic-execution backends such as :pypi:`crosshair-tool`, which can now
9+
solve for a specific date directly rather than enumerating candidates
10+
(:issue:`4759`).

‎hypothesis/src/hypothesis/strategies/_internal/datetime.py‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import operator as op
1313
import warnings
1414
import zoneinfo
15-
from calendar import monthrange
1615
from functools import cache, partial
1716
from importlib import resources
1817
from pathlib import Path
@@ -88,26 +87,55 @@ def datetime_does_not_exist(value):
8887
return value != roundtrip
8988

9089

90+
def _num_days_in_month(year, month):
91+
"""Equivalent to ``monthrange(year, month)[1]`` for valid inputs.
92+
93+
Written using only arithmetic and (in)equality, with no branching, ``and``,
94+
``or``, or indexing on ``month``/``year``. This keeps the result symbolic
95+
under symbolic-execution backends (which would otherwise concretize the year
96+
and month the moment they hit a branch or a list lookup), while remaining a
97+
handful of cheap integer ops for the blackbox engine.
98+
"""
99+
leap = (year % 4 == 0) * (1 - (year % 100 == 0) * (year % 400 != 0))
100+
is_feb = month == 2
101+
is_30_day = 1 - (month != 4) * (month != 6) * (month != 9) * (month != 11)
102+
return 31 - is_30_day - is_feb * (3 - leap)
103+
104+
91105
def draw_capped_multipart(
92106
data, min_value, max_value, duration_names=DATENAMES + TIMENAMES
93107
):
94108
assert isinstance(min_value, (dt.date, dt.time, dt.datetime))
95109
assert type(min_value) == type(max_value)
96110
assert min_value <= max_value
97111
result = {}
98-
cap_low, cap_high = True, True
112+
# ``cap_low``/``cap_high`` are 0/1 integers (not booleans) recording whether
113+
# every field drawn so far has equalled ``min_value``'s / ``max_value``'s,
114+
# i.e. whether that bound is still "active" and constrains the next field.
115+
# We combine them into the bounds with arithmetic rather than branching, so
116+
# that the *same* code stays fully symbolic under symbolic-execution
117+
# backends (important for cross-backend database replay) yet compiles down
118+
# to a few integer ops for the blackbox engine. The draws themselves --
119+
# their count, order, bounds, and ``shrink_towards`` -- are byte-for-byte
120+
# identical to the previous branchy implementation.
121+
cap_low = cap_high = 1
99122
for name in duration_names:
100-
low = getattr(min_value if cap_low else dt.datetime.min, name)
101-
high = getattr(max_value if cap_high else dt.datetime.max, name)
102-
if name == "day" and not cap_high:
103-
_, high = monthrange(**result)
123+
natural_low = getattr(dt.datetime.min, name)
124+
if name == "day":
125+
natural_high = _num_days_in_month(result["year"], result["month"])
126+
else:
127+
natural_high = getattr(dt.datetime.max, name)
128+
# low = min_value.<name> if cap_low else natural_low
129+
# high = max_value.<name> if cap_high else natural_high
130+
low = natural_low + cap_low * (getattr(min_value, name) - natural_low)
131+
high = natural_high + cap_high * (getattr(max_value, name) - natural_high)
104132
if name == "year":
105133
val = data.draw_integer(low, high, shrink_towards=2000)
106134
else:
107135
val = data.draw_integer(low, high)
108136
result[name] = val
109-
cap_low = cap_low and val == low
110-
cap_high = cap_high and val == high
137+
cap_low = cap_low * (val == low)
138+
cap_high = cap_high * (val == high)
111139
if hasattr(min_value, "fold"):
112140
# The `fold` attribute is ignored in comparison of naive datetimes.
113141
# In tz-aware datetimes it would require *very* invasive changes to

‎hypothesis/tests/cover/test_datetimes.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,25 @@
99
# obtain one at https://mozilla.org/MPL/2.0/.
1010

1111
import datetime as dt
12+
from calendar import monthrange
1213

1314
import pytest
1415

1516
from hypothesis import HealthCheck, given, settings
1617
from hypothesis.strategies import dates, datetimes, timedeltas, times
18+
from hypothesis.strategies._internal.datetime import _num_days_in_month
1719

1820
from tests.common.debug import assert_simple_property, find_any, minimal
1921

2022

23+
@pytest.mark.parametrize("year", [1, 1900, 2000, 2004, 2023, 2024, 2100, 9999])
24+
def test_num_days_in_month_matches_monthrange(year):
25+
# The branchless _num_days_in_month must agree with the stdlib for every
26+
# month, including the century/400-year leap rules around February.
27+
for month in range(1, 13):
28+
assert _num_days_in_month(year, month) == monthrange(year, month)[1]
29+
30+
2131
def test_can_find_positive_delta():
2232
assert minimal(timedeltas(), lambda x: x.days > 0) == dt.timedelta(1)
2333

‎hypothesis/tests/crosshair/test_crosshair.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
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 as dt
12+
1113
import crosshair
1214
import pytest
1315
from hypothesis_crosshair_provider.crosshair_provider import CrossHairPrimitiveProvider
@@ -224,3 +226,14 @@ def test(n):
224226
def test_event_with_realization(value):
225227
event(value)
226228
float(value)
229+
230+
231+
def test_crosshair_can_hit_a_specific_date():
232+
# See https://github.com/HypothesisWorks/hypothesis/issues/4759.
233+
@given(st.dates())
234+
@settings(backend="crosshair", database=None)
235+
def f(d):
236+
assert d != dt.date(2030, 2, 14)
237+
238+
with pytest.raises(AssertionError):
239+
f()

0 commit comments

Comments
 (0)