Visitar URL original
Merge pull request #31857 from charris/backport-31775 · numpy/numpy@4dee265 · GitHub
Skip to content

Commit 4dee265

Browse files
authored
Merge pull request #31857 from charris/backport-31775
BUG: Fix segfault in MT19937 by preventing recursive seed lists (#31775)
2 parents dc8d553 + baa2589 commit 4dee265

2 files changed

Lines changed: 33 additions & 2 deletions

File tree

‎numpy/random/bit_generator.pyx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,16 @@ def _coerce_to_uint32_array(x):
142142
else:
143143
if len(x) == 0:
144144
return np.array([], dtype=np.uint32)
145+
145146
# Should be a sequence of interpretable-as-ints. Convert each one to
146147
# a uint32 array and concatenate.
147-
subseqs = [_coerce_to_uint32_array(v) for v in x]
148+
subseqs = []
149+
for v in x:
150+
if hasattr(v, '__len__') and not isinstance(v, str):
151+
raise TypeError("SeedSequence does not accept nested sequences.")
152+
153+
subseqs.append(_coerce_to_uint32_array(v))
154+
148155
return np.concatenate(subseqs)
149156

150157

‎numpy/random/tests/test_seed_sequence.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import numpy as np
22
from numpy.random import SeedSequence
3-
from numpy.testing import assert_array_compare, assert_array_equal
3+
from numpy.testing import (
4+
assert_array_compare,
5+
assert_array_equal,
6+
assert_raises,
7+
assert_raises_regex,
8+
)
49

510

611
def test_reference_data():
@@ -77,3 +82,22 @@ def test_zero_padding():
7782
np.not_equal,
7883
SeedSequence(42, spawn_key=(0,)).generate_state(4),
7984
expected42)
85+
86+
87+
def test_seedsequence_rejects_nested_sequence():
88+
with assert_raises(TypeError):
89+
SeedSequence(SeedSequence(42))
90+
91+
# Prevents infinite recursion (Issue #28822) and rejects
92+
# invalid types (Issue #27380)
93+
match_str = "SeedSequence does not accept nested sequences."
94+
95+
# Test standard nested lists
96+
with assert_raises_regex(TypeError, match_str):
97+
SeedSequence([[1, 2], [3, 4]])
98+
99+
# Test self-referencing/cyclic lists
100+
with assert_raises_regex(TypeError, match_str):
101+
cyclic_seed = []
102+
cyclic_seed.append(cyclic_seed)
103+
SeedSequence(cyclic_seed)

0 commit comments

Comments
 (0)